PageRenderTime 133ms CodeModel.GetById 34ms RepoModel.GetById 1ms app.codeStats 1ms

/ext-4.1.0_b3/builds/ext-core-debug-w-comments.js

https://bitbucket.org/srogerf/javascript
JavaScript | 14240 lines | 6492 code | 1590 blank | 6158 comment | 1480 complexity | 52b43a9b21ab8a7a7a4aca5537b04488 MD5 | raw file
  1. /*
  2. This file is part of Ext JS 4.1
  3. Copyright (c) 2011-2012 Sencha Inc
  4. Contact: http://www.sencha.com/contact
  5. Pre-release code in the Ext repository is intended for development purposes only and will
  6. not always be stable.
  7. Use of pre-release code is permitted with your application at your own risk under standard
  8. Ext license terms. Public redistribution is prohibited.
  9. For early licensing, please contact us at licensing@sencha.com
  10. Build date: 2012-02-21 23:18:31 (3a639ae9dd5443bffbde7bec9922e6fb07a923a8)
  11. */
  12. /**
  13. * @class Ext
  14. * @singleton
  15. */
  16. var Ext = Ext || {};
  17. Ext._startTime = new Date().getTime();
  18. (function() {
  19. var global = this,
  20. objectPrototype = Object.prototype,
  21. toString = objectPrototype.toString,
  22. enumerables = true,
  23. enumerablesTest = { toString: 1 },
  24. emptyFn = function(){},
  25. i;
  26. Ext.global = global;
  27. for (i in enumerablesTest) {
  28. enumerables = null;
  29. }
  30. if (enumerables) {
  31. enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable',
  32. 'toLocaleString', 'toString', 'constructor'];
  33. }
  34. /**
  35. * An array containing extra enumerables for old browsers
  36. * @property {String[]}
  37. */
  38. Ext.enumerables = enumerables;
  39. /**
  40. * Copies all the properties of config to the specified object.
  41. * Note that if recursive merging and cloning without referencing the original objects / arrays is needed, use
  42. * {@link Ext.Object#merge} instead.
  43. * @param {Object} object The receiver of the properties
  44. * @param {Object} config The source of the properties
  45. * @param {Object} defaults A different object that will also be applied for default values
  46. * @return {Object} returns obj
  47. */
  48. Ext.apply = function(object, config, defaults) {
  49. if (defaults) {
  50. Ext.apply(object, defaults);
  51. }
  52. if (object && config && typeof config === 'object') {
  53. var i, j, k;
  54. for (i in config) {
  55. object[i] = config[i];
  56. }
  57. if (enumerables) {
  58. for (j = enumerables.length; j--;) {
  59. k = enumerables[j];
  60. if (config.hasOwnProperty(k)) {
  61. object[k] = config[k];
  62. }
  63. }
  64. }
  65. }
  66. return object;
  67. };
  68. Ext.buildSettings = Ext.apply({
  69. baseCSSPrefix: 'x-',
  70. scopeResetCSS: false
  71. }, Ext.buildSettings || {});
  72. Ext.apply(Ext, {
  73. /**
  74. * @property {String} [name='Ext']
  75. * <p>The name of the property in the global namespace (The <code>window</code> in browser environments) which refers to the current instance of Ext.</p>
  76. * <p>This is usually <code>"Ext"</code>, but if a sandboxed build of ExtJS is being used, this will be an alternative name.</p>
  77. * <p>If code is being generated for use by <code>eval</code> or to create a <code>new Function</code>, and the global instance
  78. * of Ext must be referenced, this is the name that should be built into the code.</p>
  79. */
  80. name: Ext.sandboxName || 'Ext',
  81. /**
  82. * A reusable empty function
  83. */
  84. emptyFn: emptyFn,
  85. /**
  86. * A zero length string which will pass a truth test. Useful for passing to methods
  87. * which use a truth test to reject <i>falsy</i> values where a string value must be cleared.
  88. */
  89. emptyString: new String(),
  90. baseCSSPrefix: Ext.buildSettings.baseCSSPrefix,
  91. /**
  92. * Copies all the properties of config to object if they don't already exist.
  93. * @param {Object} object The receiver of the properties
  94. * @param {Object} config The source of the properties
  95. * @return {Object} returns obj
  96. */
  97. applyIf: function(object, config) {
  98. var property;
  99. if (object) {
  100. for (property in config) {
  101. if (object[property] === undefined) {
  102. object[property] = config[property];
  103. }
  104. }
  105. }
  106. return object;
  107. },
  108. /**
  109. * Iterates either an array or an object. This method delegates to
  110. * {@link Ext.Array#each Ext.Array.each} if the given value is iterable, and {@link Ext.Object#each Ext.Object.each} otherwise.
  111. *
  112. * @param {Object/Array} object The object or array to be iterated.
  113. * @param {Function} fn The function to be called for each iteration. See and {@link Ext.Array#each Ext.Array.each} and
  114. * {@link Ext.Object#each Ext.Object.each} for detailed lists of arguments passed to this function depending on the given object
  115. * type that is being iterated.
  116. * @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed.
  117. * Defaults to the object being iterated itself.
  118. * @markdown
  119. */
  120. iterate: function(object, fn, scope) {
  121. if (Ext.isEmpty(object)) {
  122. return;
  123. }
  124. if (scope === undefined) {
  125. scope = object;
  126. }
  127. if (Ext.isIterable(object)) {
  128. Ext.Array.each.call(Ext.Array, object, fn, scope);
  129. }
  130. else {
  131. Ext.Object.each.call(Ext.Object, object, fn, scope);
  132. }
  133. }
  134. });
  135. Ext.apply(Ext, {
  136. /**
  137. * This method deprecated. Use {@link Ext#define Ext.define} instead.
  138. * @method
  139. * @param {Function} superclass
  140. * @param {Object} overrides
  141. * @return {Function} The subclass constructor from the <tt>overrides</tt> parameter, or a generated one if not provided.
  142. * @deprecated 4.0.0 Use {@link Ext#define Ext.define} instead
  143. */
  144. extend: function() {
  145. // inline overrides
  146. var objectConstructor = objectPrototype.constructor,
  147. inlineOverrides = function(o) {
  148. for (var m in o) {
  149. if (!o.hasOwnProperty(m)) {
  150. continue;
  151. }
  152. this[m] = o[m];
  153. }
  154. };
  155. return function(subclass, superclass, overrides) {
  156. // First we check if the user passed in just the superClass with overrides
  157. if (Ext.isObject(superclass)) {
  158. overrides = superclass;
  159. superclass = subclass;
  160. subclass = overrides.constructor !== objectConstructor ? overrides.constructor : function() {
  161. superclass.apply(this, arguments);
  162. };
  163. }
  164. // We create a new temporary class
  165. var F = function() {},
  166. subclassProto, superclassProto = superclass.prototype;
  167. F.prototype = superclassProto;
  168. subclassProto = subclass.prototype = new F();
  169. subclassProto.constructor = subclass;
  170. subclass.superclass = superclassProto;
  171. if (superclassProto.constructor === objectConstructor) {
  172. superclassProto.constructor = superclass;
  173. }
  174. subclass.override = function(overrides) {
  175. Ext.override(subclass, overrides);
  176. };
  177. subclassProto.override = inlineOverrides;
  178. subclassProto.proto = subclassProto;
  179. subclass.override(overrides);
  180. subclass.extend = function(o) {
  181. return Ext.extend(subclass, o);
  182. };
  183. return subclass;
  184. };
  185. }(),
  186. /**
  187. * Proxy to {@link Ext.Base#override}. Please refer {@link Ext.Base#override} for further details.
  188. *
  189. * @param {Object} cls The class to override
  190. * @param {Object} overrides The properties to add to origClass. This should be specified as an object literal
  191. * containing one or more properties.
  192. * @method override
  193. * @markdown
  194. * @deprecated 4.1.0 Use {@link Ext#define Ext.define} instead
  195. */
  196. override: function(cls, overrides) {
  197. if (cls.$isClass) {
  198. return cls.override(overrides);
  199. }
  200. else {
  201. Ext.apply(cls.prototype, overrides);
  202. }
  203. }
  204. });
  205. // A full set of static methods to do type checking
  206. Ext.apply(Ext, {
  207. /**
  208. * Returns the given value itself if it's not empty, as described in {@link Ext#isEmpty}; returns the default
  209. * value (second argument) otherwise.
  210. *
  211. * @param {Object} value The value to test
  212. * @param {Object} defaultValue The value to return if the original value is empty
  213. * @param {Boolean} allowBlank (optional) true to allow zero length strings to qualify as non-empty (defaults to false)
  214. * @return {Object} value, if non-empty, else defaultValue
  215. */
  216. valueFrom: function(value, defaultValue, allowBlank){
  217. return Ext.isEmpty(value, allowBlank) ? defaultValue : value;
  218. },
  219. /**
  220. * Returns the type of the given variable in string format. List of possible values are:
  221. *
  222. * - `undefined`: If the given value is `undefined`
  223. * - `null`: If the given value is `null`
  224. * - `string`: If the given value is a string
  225. * - `number`: If the given value is a number
  226. * - `boolean`: If the given value is a boolean value
  227. * - `date`: If the given value is a `Date` object
  228. * - `function`: If the given value is a function reference
  229. * - `object`: If the given value is an object
  230. * - `array`: If the given value is an array
  231. * - `regexp`: If the given value is a regular expression
  232. * - `element`: If the given value is a DOM Element
  233. * - `textnode`: If the given value is a DOM text node and contains something other than whitespace
  234. * - `whitespace`: If the given value is a DOM text node and contains only whitespace
  235. *
  236. * @param {Object} value
  237. * @return {String}
  238. * @markdown
  239. */
  240. typeOf: function(value) {
  241. if (value === null) {
  242. return 'null';
  243. }
  244. var type = typeof value;
  245. if (type === 'undefined' || type === 'string' || type === 'number' || type === 'boolean') {
  246. return type;
  247. }
  248. var typeToString = toString.call(value);
  249. switch(typeToString) {
  250. case '[object Array]':
  251. return 'array';
  252. case '[object Date]':
  253. return 'date';
  254. case '[object Boolean]':
  255. return 'boolean';
  256. case '[object Number]':
  257. return 'number';
  258. case '[object RegExp]':
  259. return 'regexp';
  260. }
  261. if (type === 'function') {
  262. return 'function';
  263. }
  264. if (type === 'object') {
  265. if (value.nodeType !== undefined) {
  266. if (value.nodeType === 3) {
  267. return (/\S/).test(value.nodeValue) ? 'textnode' : 'whitespace';
  268. }
  269. else {
  270. return 'element';
  271. }
  272. }
  273. return 'object';
  274. }
  275. },
  276. /**
  277. * Returns true if the passed value is empty, false otherwise. The value is deemed to be empty if it is either:
  278. *
  279. * - `null`
  280. * - `undefined`
  281. * - a zero-length array
  282. * - a zero-length string (Unless the `allowEmptyString` parameter is set to `true`)
  283. *
  284. * @param {Object} value The value to test
  285. * @param {Boolean} allowEmptyString (optional) true to allow empty strings (defaults to false)
  286. * @return {Boolean}
  287. * @markdown
  288. */
  289. isEmpty: function(value, allowEmptyString) {
  290. return (value === null) || (value === undefined) || (!allowEmptyString ? value === '' : false) || (Ext.isArray(value) && value.length === 0);
  291. },
  292. /**
  293. * Returns true if the passed value is a JavaScript Array, false otherwise.
  294. *
  295. * @param {Object} target The target to test
  296. * @return {Boolean}
  297. * @method
  298. */
  299. isArray: ('isArray' in Array) ? Array.isArray : function(value) {
  300. return toString.call(value) === '[object Array]';
  301. },
  302. /**
  303. * Returns true if the passed value is a JavaScript Date object, false otherwise.
  304. * @param {Object} object The object to test
  305. * @return {Boolean}
  306. */
  307. isDate: function(value) {
  308. return toString.call(value) === '[object Date]';
  309. },
  310. /**
  311. * Returns true if the passed value is a JavaScript Object, false otherwise.
  312. * @param {Object} value The value to test
  313. * @return {Boolean}
  314. * @method
  315. */
  316. isObject: (toString.call(null) === '[object Object]') ?
  317. function(value) {
  318. // check ownerDocument here as well to exclude DOM nodes
  319. return value !== null && value !== undefined && toString.call(value) === '[object Object]' && value.ownerDocument === undefined;
  320. } :
  321. function(value) {
  322. return toString.call(value) === '[object Object]';
  323. },
  324. /**
  325. * @private
  326. */
  327. isSimpleObject: function(value) {
  328. return value instanceof Object && value.constructor === Object;
  329. },
  330. /**
  331. * Returns true if the passed value is a JavaScript 'primitive', a string, number or boolean.
  332. * @param {Object} value The value to test
  333. * @return {Boolean}
  334. */
  335. isPrimitive: function(value) {
  336. var type = typeof value;
  337. return type === 'string' || type === 'number' || type === 'boolean';
  338. },
  339. /**
  340. * Returns true if the passed value is a JavaScript Function, false otherwise.
  341. * @param {Object} value The value to test
  342. * @return {Boolean}
  343. * @method
  344. */
  345. isFunction:
  346. // Safari 3.x and 4.x returns 'function' for typeof <NodeList>, hence we need to fall back to using
  347. // Object.prototype.toString (slower)
  348. (typeof document !== 'undefined' && typeof document.getElementsByTagName('body') === 'function') ? function(value) {
  349. return toString.call(value) === '[object Function]';
  350. } : function(value) {
  351. return typeof value === 'function';
  352. },
  353. /**
  354. * Returns true if the passed value is a number. Returns false for non-finite numbers.
  355. * @param {Object} value The value to test
  356. * @return {Boolean}
  357. */
  358. isNumber: function(value) {
  359. return typeof value === 'number' && isFinite(value);
  360. },
  361. /**
  362. * Validates that a value is numeric.
  363. * @param {Object} value Examples: 1, '1', '2.34'
  364. * @return {Boolean} True if numeric, false otherwise
  365. */
  366. isNumeric: function(value) {
  367. return !isNaN(parseFloat(value)) && isFinite(value);
  368. },
  369. /**
  370. * Returns true if the passed value is a string.
  371. * @param {Object} value The value to test
  372. * @return {Boolean}
  373. */
  374. isString: function(value) {
  375. return typeof value === 'string';
  376. },
  377. /**
  378. * Returns true if the passed value is a boolean.
  379. *
  380. * @param {Object} value The value to test
  381. * @return {Boolean}
  382. */
  383. isBoolean: function(value) {
  384. return typeof value === 'boolean';
  385. },
  386. /**
  387. * Returns true if the passed value is an HTMLElement
  388. * @param {Object} value The value to test
  389. * @return {Boolean}
  390. */
  391. isElement: function(value) {
  392. return value ? value.nodeType === 1 : false;
  393. },
  394. /**
  395. * Returns true if the passed value is a TextNode
  396. * @param {Object} value The value to test
  397. * @return {Boolean}
  398. */
  399. isTextNode: function(value) {
  400. return value ? value.nodeName === "#text" : false;
  401. },
  402. /**
  403. * Returns true if the passed value is defined.
  404. * @param {Object} value The value to test
  405. * @return {Boolean}
  406. */
  407. isDefined: function(value) {
  408. return typeof value !== 'undefined';
  409. },
  410. /**
  411. * Returns true if the passed value is iterable, false otherwise
  412. * @param {Object} value The value to test
  413. * @return {Boolean}
  414. */
  415. isIterable: function(value) {
  416. var type = typeof value,
  417. checkLength = false;
  418. if (value && type != 'string') {
  419. // Functions have a length property, so we need to filter them out
  420. if (type == 'function') {
  421. // In Safari, NodeList/HTMLCollection both return "function" when using typeof, so we need
  422. // to explicitly check them here.
  423. if (Ext.isSafari) {
  424. checkLength = value instanceof NodeList || value instanceof HTMLCollection;
  425. }
  426. } else {
  427. checkLength = true;
  428. }
  429. }
  430. return checkLength ? value.length !== undefined : false;
  431. }
  432. });
  433. Ext.apply(Ext, {
  434. /**
  435. * Clone almost any type of variable including array, object, DOM nodes and Date without keeping the old reference
  436. * @param {Object} item The variable to clone
  437. * @return {Object} clone
  438. */
  439. clone: function(item) {
  440. if (item === null || item === undefined) {
  441. return item;
  442. }
  443. // DOM nodes
  444. // TODO proxy this to Ext.Element.clone to handle automatic id attribute changing
  445. // recursively
  446. if (item.nodeType && item.cloneNode) {
  447. return item.cloneNode(true);
  448. }
  449. var type = toString.call(item);
  450. // Date
  451. if (type === '[object Date]') {
  452. return new Date(item.getTime());
  453. }
  454. var i, j, k, clone, key;
  455. // Array
  456. if (type === '[object Array]') {
  457. i = item.length;
  458. clone = [];
  459. while (i--) {
  460. clone[i] = Ext.clone(item[i]);
  461. }
  462. }
  463. // Object
  464. else if (type === '[object Object]' && item.constructor === Object) {
  465. clone = {};
  466. for (key in item) {
  467. clone[key] = Ext.clone(item[key]);
  468. }
  469. if (enumerables) {
  470. for (j = enumerables.length; j--;) {
  471. k = enumerables[j];
  472. clone[k] = item[k];
  473. }
  474. }
  475. }
  476. return clone || item;
  477. },
  478. /**
  479. * @private
  480. * Generate a unique reference of Ext in the global scope, useful for sandboxing
  481. */
  482. getUniqueGlobalNamespace: function() {
  483. var uniqueGlobalNamespace = this.uniqueGlobalNamespace;
  484. if (uniqueGlobalNamespace === undefined) {
  485. var i = 0;
  486. do {
  487. uniqueGlobalNamespace = 'ExtBox' + (++i);
  488. } while (Ext.global[uniqueGlobalNamespace] !== undefined);
  489. Ext.global[uniqueGlobalNamespace] = Ext;
  490. this.uniqueGlobalNamespace = uniqueGlobalNamespace;
  491. }
  492. return uniqueGlobalNamespace;
  493. },
  494. /**
  495. * @private
  496. */
  497. functionFactoryCache: {},
  498. cacheableFunctionFactory: function() {
  499. var me = this,
  500. args = Array.prototype.slice.call(arguments),
  501. cache = me.functionFactoryCache,
  502. idx, fn, ln;
  503. if (Ext.isSandboxed) {
  504. ln = args.length;
  505. if (ln > 0) {
  506. ln--;
  507. args[ln] = 'var Ext=window.' + Ext.name + ';' + args[ln];
  508. }
  509. }
  510. idx = args.join('');
  511. fn = cache[idx];
  512. if (!fn) {
  513. fn = Function.prototype.constructor.apply(Function.prototype, args);
  514. cache[idx] = fn;
  515. }
  516. return fn;
  517. },
  518. functionFactory: function() {
  519. var me = this,
  520. args = Array.prototype.slice.call(arguments),
  521. ln;
  522. if (Ext.isSandboxed) {
  523. ln = args.length;
  524. if (ln > 0) {
  525. ln--;
  526. args[ln] = 'var Ext=window.' + Ext.name + ';' + args[ln];
  527. }
  528. }
  529. return Function.prototype.constructor.apply(Function.prototype, args);
  530. },
  531. /**
  532. * @property
  533. * @private
  534. */
  535. globalEval: ('execScript' in global) ? function(code) {
  536. global.execScript(code)
  537. } : function(code) {
  538. (function(){
  539. eval(code);
  540. })();
  541. },
  542. /**
  543. * @private
  544. * @property
  545. */
  546. Logger: {
  547. verbose: emptyFn,
  548. log: emptyFn,
  549. info: emptyFn,
  550. warn: emptyFn,
  551. error: function(message) {
  552. throw new Error(message);
  553. },
  554. deprecate: emptyFn
  555. }
  556. });
  557. /**
  558. * Old alias to {@link Ext#typeOf}
  559. * @deprecated 4.0.0 Use {@link Ext#typeOf} instead
  560. * @method
  561. * @inheritdoc Ext#typeOf
  562. */
  563. Ext.type = Ext.typeOf;
  564. })();
  565. /**
  566. * @author Jacky Nguyen <jacky@sencha.com>
  567. * @docauthor Jacky Nguyen <jacky@sencha.com>
  568. * @class Ext.Version
  569. *
  570. * A utility class that wrap around a string version number and provide convenient
  571. * method to perform comparison. See also: {@link Ext.Version#compare compare}. Example:
  572. var version = new Ext.Version('1.0.2beta');
  573. console.log("Version is " + version); // Version is 1.0.2beta
  574. console.log(version.getMajor()); // 1
  575. console.log(version.getMinor()); // 0
  576. console.log(version.getPatch()); // 2
  577. console.log(version.getBuild()); // 0
  578. console.log(version.getRelease()); // beta
  579. console.log(version.isGreaterThan('1.0.1')); // True
  580. console.log(version.isGreaterThan('1.0.2alpha')); // True
  581. console.log(version.isGreaterThan('1.0.2RC')); // False
  582. console.log(version.isGreaterThan('1.0.2')); // False
  583. console.log(version.isLessThan('1.0.2')); // True
  584. console.log(version.match(1.0)); // True
  585. console.log(version.match('1.0.2')); // True
  586. * @markdown
  587. */
  588. (function() {
  589. // Current core version
  590. var version = '4.1.0beta', Version;
  591. Ext.Version = Version = Ext.extend(Object, {
  592. /**
  593. * @param {String/Number} version The version number in the follow standard format: major[.minor[.patch[.build[release]]]]
  594. * Examples: 1.0 or 1.2.3beta or 1.2.3.4RC
  595. * @return {Ext.Version} this
  596. */
  597. constructor: function(version) {
  598. var parts, releaseStartIndex;
  599. if (version instanceof Version) {
  600. return version;
  601. }
  602. this.version = this.shortVersion = String(version).toLowerCase().replace(/_/g, '.').replace(/[\-+]/g, '');
  603. releaseStartIndex = this.version.search(/([^\d\.])/);
  604. if (releaseStartIndex !== -1) {
  605. this.release = this.version.substr(releaseStartIndex, version.length);
  606. this.shortVersion = this.version.substr(0, releaseStartIndex);
  607. }
  608. this.shortVersion = this.shortVersion.replace(/[^\d]/g, '');
  609. parts = this.version.split('.');
  610. this.major = parseInt(parts.shift() || 0, 10);
  611. this.minor = parseInt(parts.shift() || 0, 10);
  612. this.patch = parseInt(parts.shift() || 0, 10);
  613. this.build = parseInt(parts.shift() || 0, 10);
  614. return this;
  615. },
  616. /**
  617. * Override the native toString method
  618. * @private
  619. * @return {String} version
  620. */
  621. toString: function() {
  622. return this.version;
  623. },
  624. /**
  625. * Override the native valueOf method
  626. * @private
  627. * @return {String} version
  628. */
  629. valueOf: function() {
  630. return this.version;
  631. },
  632. /**
  633. * Returns the major component value
  634. * @return {Number} major
  635. */
  636. getMajor: function() {
  637. return this.major || 0;
  638. },
  639. /**
  640. * Returns the minor component value
  641. * @return {Number} minor
  642. */
  643. getMinor: function() {
  644. return this.minor || 0;
  645. },
  646. /**
  647. * Returns the patch component value
  648. * @return {Number} patch
  649. */
  650. getPatch: function() {
  651. return this.patch || 0;
  652. },
  653. /**
  654. * Returns the build component value
  655. * @return {Number} build
  656. */
  657. getBuild: function() {
  658. return this.build || 0;
  659. },
  660. /**
  661. * Returns the release component value
  662. * @return {Number} release
  663. */
  664. getRelease: function() {
  665. return this.release || '';
  666. },
  667. /**
  668. * Returns whether this version if greater than the supplied argument
  669. * @param {String/Number} target The version to compare with
  670. * @return {Boolean} True if this version if greater than the target, false otherwise
  671. */
  672. isGreaterThan: function(target) {
  673. return Version.compare(this.version, target) === 1;
  674. },
  675. /**
  676. * Returns whether this version if greater than or equal to the supplied argument
  677. * @param {String/Number} target The version to compare with
  678. * @return {Boolean} True if this version if greater than or equal to the target, false otherwise
  679. */
  680. isGreaterThanOrEqual: function(target) {
  681. return Version.compare(this.version, target) >= 0;
  682. },
  683. /**
  684. * Returns whether this version if smaller than the supplied argument
  685. * @param {String/Number} target The version to compare with
  686. * @return {Boolean} True if this version if smaller than the target, false otherwise
  687. */
  688. isLessThan: function(target) {
  689. return Version.compare(this.version, target) === -1;
  690. },
  691. /**
  692. * Returns whether this version if less than or equal to the supplied argument
  693. * @param {String/Number} target The version to compare with
  694. * @return {Boolean} True if this version if less than or equal to the target, false otherwise
  695. */
  696. isLessThanOrEqual: function(target) {
  697. return Version.compare(this.version, target) <= 0;
  698. },
  699. /**
  700. * Returns whether this version equals to the supplied argument
  701. * @param {String/Number} target The version to compare with
  702. * @return {Boolean} True if this version equals to the target, false otherwise
  703. */
  704. equals: function(target) {
  705. return Version.compare(this.version, target) === 0;
  706. },
  707. /**
  708. * Returns whether this version matches the supplied argument. Example:
  709. * <pre><code>
  710. * var version = new Ext.Version('1.0.2beta');
  711. * console.log(version.match(1)); // True
  712. * console.log(version.match(1.0)); // True
  713. * console.log(version.match('1.0.2')); // True
  714. * console.log(version.match('1.0.2RC')); // False
  715. * </code></pre>
  716. * @param {String/Number} target The version to compare with
  717. * @return {Boolean} True if this version matches the target, false otherwise
  718. */
  719. match: function(target) {
  720. target = String(target);
  721. return this.version.substr(0, target.length) === target;
  722. },
  723. /**
  724. * Returns this format: [major, minor, patch, build, release]. Useful for comparison
  725. * @return {Number[]}
  726. */
  727. toArray: function() {
  728. return [this.getMajor(), this.getMinor(), this.getPatch(), this.getBuild(), this.getRelease()];
  729. },
  730. /**
  731. * Returns shortVersion version without dots and release
  732. * @return {String}
  733. */
  734. getShortVersion: function() {
  735. return this.shortVersion;
  736. },
  737. /**
  738. * Convenient alias to {@link Ext.Version#isGreaterThan isGreaterThan}
  739. * @param {String/Number} target
  740. * @return {Boolean}
  741. */
  742. gt: function() {
  743. return this.isGreaterThan.apply(this, arguments);
  744. },
  745. /**
  746. * Convenient alias to {@link Ext.Version#isLessThan isLessThan}
  747. * @param {String/Number} target
  748. * @return {Boolean}
  749. */
  750. lt: function() {
  751. return this.isLessThan.apply(this, arguments);
  752. },
  753. /**
  754. * Convenient alias to {@link Ext.Version#isGreaterThanOrEqual isGreaterThanOrEqual}
  755. * @param {String/Number} target
  756. * @return {Boolean}
  757. */
  758. gtEq: function() {
  759. return this.isGreaterThanOrEqual.apply(this, arguments);
  760. },
  761. /**
  762. * Convenient alias to {@link Ext.Version#isLessThanOrEqual isLessThanOrEqual}
  763. * @param {String/Number} target
  764. * @return {Boolean}
  765. */
  766. ltEq: function() {
  767. return this.isLessThanOrEqual.apply(this, arguments);
  768. }
  769. });
  770. Ext.apply(Version, {
  771. // @private
  772. releaseValueMap: {
  773. 'dev': -6,
  774. 'alpha': -5,
  775. 'a': -5,
  776. 'beta': -4,
  777. 'b': -4,
  778. 'rc': -3,
  779. '#': -2,
  780. 'p': -1,
  781. 'pl': -1
  782. },
  783. /**
  784. * Converts a version component to a comparable value
  785. *
  786. * @static
  787. * @param {Object} value The value to convert
  788. * @return {Object}
  789. */
  790. getComponentValue: function(value) {
  791. return !value ? 0 : (isNaN(value) ? this.releaseValueMap[value] || value : parseInt(value, 10));
  792. },
  793. /**
  794. * Compare 2 specified versions, starting from left to right. If a part contains special version strings,
  795. * they are handled in the following order:
  796. * 'dev' < 'alpha' = 'a' < 'beta' = 'b' < 'RC' = 'rc' < '#' < 'pl' = 'p' < 'anything else'
  797. *
  798. * @static
  799. * @param {String} current The current version to compare to
  800. * @param {String} target The target version to compare to
  801. * @return {Number} Returns -1 if the current version is smaller than the target version, 1 if greater, and 0 if they're equivalent
  802. */
  803. compare: function(current, target) {
  804. var currentValue, targetValue, i;
  805. current = new Version(current).toArray();
  806. target = new Version(target).toArray();
  807. for (i = 0; i < Math.max(current.length, target.length); i++) {
  808. currentValue = this.getComponentValue(current[i]);
  809. targetValue = this.getComponentValue(target[i]);
  810. if (currentValue < targetValue) {
  811. return -1;
  812. } else if (currentValue > targetValue) {
  813. return 1;
  814. }
  815. }
  816. return 0;
  817. }
  818. });
  819. Ext.apply(Ext, {
  820. /**
  821. * @private
  822. */
  823. versions: {},
  824. /**
  825. * @private
  826. */
  827. lastRegisteredVersion: null,
  828. /**
  829. * Set version number for the given package name.
  830. *
  831. * @param {String} packageName The package name, for example: 'core', 'touch', 'extjs'
  832. * @param {String/Ext.Version} version The version, for example: '1.2.3alpha', '2.4.0-dev'
  833. * @return {Ext}
  834. */
  835. setVersion: function(packageName, version) {
  836. Ext.versions[packageName] = new Version(version);
  837. Ext.lastRegisteredVersion = Ext.versions[packageName];
  838. return this;
  839. },
  840. /**
  841. * Get the version number of the supplied package name; will return the last registered version
  842. * (last Ext.setVersion call) if there's no package name given.
  843. *
  844. * @param {String} packageName (Optional) The package name, for example: 'core', 'touch', 'extjs'
  845. * @return {Ext.Version} The version
  846. */
  847. getVersion: function(packageName) {
  848. if (packageName === undefined) {
  849. return Ext.lastRegisteredVersion;
  850. }
  851. return Ext.versions[packageName];
  852. },
  853. /**
  854. * Create a closure for deprecated code.
  855. *
  856. // This means Ext.oldMethod is only supported in 4.0.0beta and older.
  857. // If Ext.getVersion('extjs') returns a version that is later than '4.0.0beta', for example '4.0.0RC',
  858. // the closure will not be invoked
  859. Ext.deprecate('extjs', '4.0.0beta', function() {
  860. Ext.oldMethod = Ext.newMethod;
  861. ...
  862. });
  863. * @param {String} packageName The package name
  864. * @param {String} since The last version before it's deprecated
  865. * @param {Function} closure The callback function to be executed with the specified version is less than the current version
  866. * @param {Object} scope The execution scope (<tt>this</tt>) if the closure
  867. * @markdown
  868. */
  869. deprecate: function(packageName, since, closure, scope) {
  870. if (Version.compare(Ext.getVersion(packageName), since) < 1) {
  871. closure.call(scope);
  872. }
  873. }
  874. }); // End Versioning
  875. Ext.setVersion('core', version);
  876. })();
  877. /**
  878. * @class Ext.String
  879. *
  880. * A collection of useful static methods to deal with strings
  881. * @singleton
  882. */
  883. Ext.String = (function() {
  884. var 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,
  885. escapeRe = /('|\\)/g,
  886. formatRe = /\{(\d+)\}/g,
  887. escapeRegexRe = /([-.*+?^${}()|[\]\/\\])/g,
  888. basicTrimRe = /^\s+|\s+$/g,
  889. whitespaceRe = /\s+/,
  890. varReplace = /(^[^a-z]*|[^\w])/gi,
  891. charToEntity = {
  892. '&': '&amp;',
  893. '>': '&gt;',
  894. '<': '&lt;',
  895. '"': '&quot;'
  896. },
  897. entityToChar = {
  898. '&amp;': '&',
  899. '&gt;': '>',
  900. '&lt;': '<',
  901. '&quot;': '"'
  902. },
  903. keys = [],
  904. key,
  905. charToEntityRegex,
  906. entityToCharRegex,
  907. htmlEncodeReplaceFn = function(match, capture) {
  908. return charToEntity[capture];
  909. },
  910. htmlEncode = function(value) {
  911. return (!value) ? value : String(value).replace(charToEntityRegex, htmlEncodeReplaceFn);
  912. },
  913. htmlDecodeReplaceFn = function(match, capture) {
  914. return (capture in entityToChar) ? entityToChar[capture] : String.fromCharCode(parseInt(capture.substr(2), 10));
  915. },
  916. htmlDecode = function(value) {
  917. return (!value) ? value : String(value).replace(entityToCharRegex, htmlDecodeReplaceFn);
  918. };
  919. // Compile RexExps for HTML encode and decode functions
  920. for (key in charToEntity) {
  921. keys.push(key);
  922. }
  923. charToEntityRegex = new RegExp('(' + keys.join('|') + ')', 'g');
  924. keys = [];
  925. for (key in entityToChar) {
  926. keys.push(key);
  927. }
  928. entityToCharRegex = new RegExp('(' + keys.join('|') + '|&#[0-9]{1,5};' + ')', 'g');
  929. return {
  930. /**
  931. * Converts a string of characters into a legal, parseable Javascript `var` name as long as the passed
  932. * string contains at least one alphabetic character. Non alphanumeric characters, and *leading* non alphabetic
  933. * characters will be removed.
  934. * @param {String} s A string to be converted into a `var` name.
  935. * @return {String} A legal Javascript `var` name.
  936. */
  937. createVarName: function(s) {
  938. return s.replace(varReplace, '');
  939. },
  940. /**
  941. * Convert certain characters (&, <, >, and ") to their HTML character equivalents for literal display in web pages.
  942. * @param {String} value The string to encode
  943. * @return {String} The encoded text
  944. * @method
  945. */
  946. htmlEncode: htmlEncode,
  947. /**
  948. * Convert certain characters (&, <, >, and ") from their HTML character equivalents.
  949. * @param {String} value The string to decode
  950. * @return {String} The decoded text
  951. * @method
  952. */
  953. htmlDecode: htmlDecode,
  954. /**
  955. * Appends content to the query string of a URL, handling logic for whether to place
  956. * a question mark or ampersand.
  957. * @param {String} url The URL to append to.
  958. * @param {String} string The content to append to the URL.
  959. * @return {String} The resulting URL
  960. */
  961. urlAppend : function(url, string) {
  962. if (!Ext.isEmpty(string)) {
  963. return url + (url.indexOf('?') === -1 ? '?' : '&') + string;
  964. }
  965. return url;
  966. },
  967. /**
  968. * Trims whitespace from either end of a string, leaving spaces within the string intact. Example:
  969. * @example
  970. var s = ' foo bar ';
  971. alert('-' + s + '-'); //alerts "- foo bar -"
  972. alert('-' + Ext.String.trim(s) + '-'); //alerts "-foo bar-"
  973. * @param {String} string The string to escape
  974. * @return {String} The trimmed string
  975. */
  976. trim: function(string) {
  977. return string.replace(trimRegex, "");
  978. },
  979. /**
  980. * Capitalize the given string
  981. * @param {String} string
  982. * @return {String}
  983. */
  984. capitalize: function(string) {
  985. return string.charAt(0).toUpperCase() + string.substr(1);
  986. },
  987. /**
  988. * Uncapitalize the given string
  989. * @param {String} string
  990. * @return {String}
  991. */
  992. uncapitalize: function(string) {
  993. return string.charAt(0).toLowerCase() + string.substr(1);
  994. },
  995. /**
  996. * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
  997. * @param {String} value The string to truncate
  998. * @param {Number} length The maximum length to allow before truncating
  999. * @param {Boolean} word True to try to find a common word break
  1000. * @return {String} The converted text
  1001. */
  1002. ellipsis: function(value, len, word) {
  1003. if (value && value.length > len) {
  1004. if (word) {
  1005. var vs = value.substr(0, len - 2),
  1006. index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?'));
  1007. if (index !== -1 && index >= (len - 15)) {
  1008. return vs.substr(0, index) + "...";
  1009. }
  1010. }
  1011. return value.substr(0, len - 3) + "...";
  1012. }
  1013. return value;
  1014. },
  1015. /**
  1016. * Escapes the passed string for use in a regular expression
  1017. * @param {String} string
  1018. * @return {String}
  1019. */
  1020. escapeRegex: function(string) {
  1021. return string.replace(escapeRegexRe, "\\$1");
  1022. },
  1023. /**
  1024. * Escapes the passed string for ' and \
  1025. * @param {String} string The string to escape
  1026. * @return {String} The escaped string
  1027. */
  1028. escape: function(string) {
  1029. return string.replace(escapeRe, "\\$1");
  1030. },
  1031. /**
  1032. * Utility function that allows you to easily switch a string between two alternating values. The passed value
  1033. * is compared to the current string, and if they are equal, the other value that was passed in is returned. If
  1034. * they are already different, the first value passed in is returned. Note that this method returns the new value
  1035. * but does not change the current string.
  1036. * <pre><code>
  1037. // alternate sort directions
  1038. sort = Ext.String.toggle(sort, 'ASC', 'DESC');
  1039. // instead of conditional logic:
  1040. sort = (sort == 'ASC' ? 'DESC' : 'ASC');
  1041. </code></pre>
  1042. * @param {String} string The current string
  1043. * @param {String} value The value to compare to the current string
  1044. * @param {String} other The new value to use if the string already equals the first value passed in
  1045. * @return {String} The new value
  1046. */
  1047. toggle: function(string, value, other) {
  1048. return string === value ? other : value;
  1049. },
  1050. /**
  1051. * Pads the left side of a string with a specified character. This is especially useful
  1052. * for normalizing number and date strings. Example usage:
  1053. *
  1054. * <pre><code>
  1055. var s = Ext.String.leftPad('123', 5, '0');
  1056. // s now contains the string: '00123'
  1057. </code></pre>
  1058. * @param {String} string The original string
  1059. * @param {Number} size The total length of the output string
  1060. * @param {String} character (optional) The character with which to pad the original string (defaults to empty string " ")
  1061. * @return {String} The padded string
  1062. */
  1063. leftPad: function(string, size, character) {
  1064. var result = String(string);
  1065. character = character || " ";
  1066. while (result.length < size) {
  1067. result = character + result;
  1068. }
  1069. return result;
  1070. },
  1071. /**
  1072. * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
  1073. * token must be unique, and must increment in the format {0}, {1}, etc. Example usage:
  1074. * <pre><code>
  1075. var cls = 'my-class', text = 'Some text';
  1076. var s = Ext.String.format('&lt;div class="{0}">{1}&lt;/div>', cls, text);
  1077. // s now contains the string: '&lt;div class="my-class">Some text&lt;/div>'
  1078. </code></pre>
  1079. * @param {String} string The tokenized string to be formatted
  1080. * @param {String} value1 The value to replace token {0}
  1081. * @param {String} value2 Etc...
  1082. * @return {String} The formatted string
  1083. */
  1084. format: function(format) {
  1085. var args = Ext.Array.toArray(arguments, 1);
  1086. return format.replace(formatRe, function(m, i) {
  1087. return args[i];
  1088. });
  1089. },
  1090. /**
  1091. * Returns a string with a specified number of repititions a given string pattern.
  1092. * The pattern be separated by a different string.
  1093. *
  1094. * var s = Ext.String.repeat('---', 4); // = '------------'
  1095. * var t = Ext.String.repeat('--', 3, '/'); // = '--/--/--'
  1096. *
  1097. * @param {String} pattern The pattern to repeat.
  1098. * @param {Number} count The number of times to repeat the pattern (may be 0).
  1099. * @param {String} sep An option string to separate each pattern.
  1100. */
  1101. repeat: function(pattern, count, sep) {
  1102. for (var buf = [], i = count; i--; ) {
  1103. buf.push(pattern);
  1104. }
  1105. return buf.join(sep || '');
  1106. },
  1107. /**
  1108. * Splits a string of space separated words into an array, trimming as needed. If the
  1109. * words are already an array, it is returned.
  1110. *
  1111. * @param {String/Array} words
  1112. */
  1113. splitWords: function (words) {
  1114. if (words && typeof words == 'string') {
  1115. return words.replace(basicTrimRe, '').split(whitespaceRe);
  1116. }
  1117. return words || [];
  1118. }
  1119. };
  1120. })();
  1121. /**
  1122. * Old alias to {@link Ext.String#htmlEncode}
  1123. * @deprecated Use {@link Ext.String#htmlEncode} instead
  1124. * @method
  1125. * @member Ext
  1126. * @inheritdoc Ext.String#htmlEncode
  1127. */
  1128. Ext.htmlEncode = Ext.String.htmlEncode;
  1129. /**
  1130. * Old alias to {@link Ext.String#htmlDecode}
  1131. * @deprecated Use {@link Ext.String#htmlDecode} instead
  1132. * @method
  1133. * @member Ext
  1134. * @inheritdoc Ext.String#htmlDecode
  1135. */
  1136. Ext.htmlDecode = Ext.String.htmlDecode;
  1137. /**
  1138. * Old alias to {@link Ext.String#urlAppend}
  1139. * @deprecated Use {@link Ext.String#urlAppend} instead
  1140. * @method
  1141. * @member Ext
  1142. * @inheritdoc Ext.String#urlAppend
  1143. */
  1144. Ext.urlAppend = Ext.String.urlAppend;
  1145. /**
  1146. * @class Ext.Number
  1147. *
  1148. * A collection of useful static methods to deal with numbers
  1149. * @singleton
  1150. */
  1151. Ext.Number = new function() {
  1152. var me = this,
  1153. isToFixedBroken = (0.9).toFixed() !== '1',
  1154. math = Math;
  1155. Ext.apply(this, {
  1156. /**
  1157. * Checks whether or not the passed number is within a desired range. If the number is already within the
  1158. * range it is returned, otherwise the min or max value is returned depending on which side of the range is
  1159. * exceeded. Note that this method returns the constrained value but does not change the current number.
  1160. * @param {Number} number The number to check
  1161. * @param {Number} min The minimum number in the range
  1162. * @param {Number} max The maximum number in the range
  1163. * @return {Number} The constrained value if outside the range, otherwise the current value
  1164. */
  1165. constrain: function(number, min, max) {
  1166. number = parseFloat(number);
  1167. if (!isNaN(min)) {
  1168. number = math.max(number, min);
  1169. }
  1170. if (!isNaN(max)) {
  1171. number = math.min(number, max);
  1172. }
  1173. return number;
  1174. },
  1175. /**
  1176. * Snaps the passed number between stopping points based upon a passed increment value.
  1177. *
  1178. * The difference between this and {@link #snapInRange} is that {@link #snapInRange} uses the minValue
  1179. * when calculating snap points:
  1180. *
  1181. * r = Ext.Number.snap(56, 2, 55, 65); // Returns 56 - snap points are zero based
  1182. *
  1183. * r = Ext.Number.snapInRange(56, 2, 55, 65); // Returns 57 - snap points are based from minValue
  1184. *
  1185. * @param {Number} value The unsnapped value.
  1186. * @param {Number} increment The increment by which the value must move.
  1187. * @param {Number} minValue The minimum value to which the returned value must be constrained. Overrides the increment.
  1188. * @param {Number} maxValue The maximum value to which the returned value must be constrained. Overrides the increment.
  1189. * @return {Number} The value of the nearest snap target.
  1190. */
  1191. snap : function(value, increment, minValue, maxValue) {
  1192. var m;
  1193. // If no value passed, or minValue was passed and value is less than minValue (anything < undefined is false)
  1194. // Then use the minValue (or zero if the value was undefined)
  1195. if (value === undefined || value < minValue) {
  1196. return minValue || 0;
  1197. }
  1198. if (increment) {
  1199. m = value % increment;
  1200. if (m !== 0) {
  1201. value -= m;
  1202. if (m * 2 >= increment) {
  1203. value += increment;
  1204. } else if (m * 2 < -increment) {
  1205. value -= increment;
  1206. }
  1207. }
  1208. }
  1209. return me.constrain(value, minValue, maxValue);
  1210. },
  1211. /**
  1212. * Snaps the passed number between stopping points based upon a passed increment value.
  1213. *
  1214. * The difference between this and {@link #snap} is that {@link #snap} does not use the minValue
  1215. * when calculating snap points:
  1216. *
  1217. * r = Ext.Number.snap(56, 2, 55, 65); // Returns 56 - snap points are zero based
  1218. *
  1219. * r = Ext.Number.snapInRange(56, 2, 55, 65); // Returns 57 - snap points are based from minValue
  1220. *
  1221. * @param {Number} value The unsnapped value.
  1222. * @param {Number} increment The increment by which the value must move.
  1223. * @param {Number} [minValue=0] The minimum value to which the returned value must be constrained.
  1224. * @param {Number} [maxValue=Infinity] The maximum value to which the returned value must be constrained.
  1225. * @return {Number} The value of the nearest snap target.
  1226. */
  1227. snapInRange : function(value, increment, minValue, maxValue) {
  1228. var tween;
  1229. // default minValue to zero
  1230. minValue = (minValue || 0);
  1231. // If value is undefined, or less than minValue, use minValue
  1232. if (value === undefined || value < minValue) {
  1233. return minValue;
  1234. }
  1235. // Calculate how many snap points from the minValue the passed value is.
  1236. if (increment && (tween = ((value - minValue) % increment))) {
  1237. value -= tween;
  1238. tween *= 2;
  1239. if (tween >= increment) {
  1240. value += increment;
  1241. }
  1242. }
  1243. // If constraining within a maximum, ensure the maximum is on a snap point
  1244. if (maxValue !== undefined) {
  1245. if (value > (maxValue = me.snapInRange(maxValue, increment, minValue))) {
  1246. value = maxValue;
  1247. }
  1248. }
  1249. return value;
  1250. },
  1251. /**
  1252. * Formats a number using fixed-point notation
  1253. * @param {Number} value The number to format
  1254. * @param {Number} precision The number of digits to show after the decimal point
  1255. */
  1256. toFixed: isToFixedBroken ? function(value, precision) {
  1257. precision = precision || 0;
  1258. var pow = math.pow(10, precision);
  1259. return (math.round(value * pow) / pow).toFixed(precision);
  1260. } : function(value, precision) {
  1261. return value.toFixed(precision);
  1262. },
  1263. /**
  1264. * Validate that a value is numeric and convert it to a number if necessary. Returns the specified default value if
  1265. * it is not.
  1266. Ext.Number.from('1.23', 1); // returns 1.23
  1267. Ext.Number.from('abc', 1); // returns 1
  1268. * @param {Object} value
  1269. * @param {Number} defaultValue The value to return if the original value is non-numeric
  1270. * @return {Number} value, if numeric, defaultValue otherwise
  1271. */
  1272. from: function(value, defaultValue) {
  1273. if (isFinite(value)) {
  1274. value = parseFloat(value);
  1275. }
  1276. return !isNaN(value) ? value : defaultValue;
  1277. },
  1278. /**
  1279. * Returns a random integer between the specified range (inclusive)
  1280. * @param {Number} from Lowest value to return.
  1281. * @param {Number} to Highst value to return.
  1282. * @return {Number} A random integer within the specified range.
  1283. */
  1284. randomInt: function (from, to) {
  1285. return math.floor(math.random() * (to - from + 1) + from);
  1286. }
  1287. });
  1288. /**
  1289. * @deprecated 4.0.0 Please use {@link Ext.Number#from} instead.
  1290. * @member Ext
  1291. * @method num
  1292. * @inheritdoc Ext.Number#from
  1293. */
  1294. Ext.num = function() {
  1295. return me.from.apply(this, arguments);
  1296. };
  1297. };
  1298. /**
  1299. * @class Ext.Array
  1300. * @singleton
  1301. * @author Jacky Nguyen <jacky@sencha.com>
  1302. * @docauthor Jacky Nguyen <jacky@sencha.com>
  1303. *
  1304. * A set of useful static methods to deal with arrays; provide missing methods for older browsers.
  1305. */
  1306. (function() {
  1307. var arrayPrototype = Array.prototype,
  1308. slice = arrayPrototype.slice,
  1309. supportsSplice = function () {
  1310. var array = [],
  1311. lengthBefore,
  1312. j = 20;
  1313. if (!array.splice) {
  1314. return false;
  1315. }
  1316. // This detects a bug in IE8 splice method:
  1317. // see http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/6e946d03-e09f-4b22-a4dd-cd5e276bf05a/
  1318. while (j--) {
  1319. array.push("A");
  1320. }
  1321. 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");
  1322. lengthBefore = array.length; //41
  1323. array.splice(13, 0, "XXX"); // add one element
  1324. if (lengthBefore+1 != array.length) {
  1325. return false;
  1326. }
  1327. // end IE8 bug
  1328. return true;
  1329. }(),
  1330. supportsForEach = 'forEach' in arrayPrototype,
  1331. supportsMap = 'map' in arrayPrototype,
  1332. supportsIndexOf = 'indexOf' in arrayPrototype,
  1333. supportsEvery = 'every' in arrayPrototype,
  1334. supportsSome = 'some' in arrayPrototype,
  1335. supportsFilter = 'filter' in arrayPrototype,
  1336. supportsSort = function() {
  1337. var a = [1,2,3,4,5].sort(function(){ return 0; });
  1338. return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5;
  1339. }(),
  1340. supportsSliceOnNodeList = true,
  1341. ExtArray;
  1342. try {
  1343. // IE 6 - 8 will throw an error when using Array.prototype.slice on NodeList
  1344. if (typeof document !== 'undefined') {
  1345. slice.call(document.getElementsByTagName('body'));
  1346. }
  1347. } catch (e) {
  1348. supportsSliceOnNodeList = false;
  1349. }
  1350. function fixArrayIndex (array, index) {
  1351. return (index < 0) ? Math.max(0, array.length + index)
  1352. : Math.min(array.length, index);
  1353. }
  1354. /*
  1355. Does the same work as splice, but with a slightly more convenient signature. The splice
  1356. method has bugs in IE8, so this is the implementation we use on that platform.
  1357. The rippling of items in the array can be tricky. Consider two use cases:
  1358. index=2
  1359. removeCount=2
  1360. /=====\
  1361. +---+---+---+---+---+---+---+---+
  1362. | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
  1363. +---+---+---+---+---+---+---+---+
  1364. / \/ \/ \/ \
  1365. / /\ /\ /\ \
  1366. / / \/ \/ \ +--------------------------+
  1367. / / /\ /\ +--------------------------+ \
  1368. / / / \/ +--------------------------+ \ \
  1369. / / / /+--------------------------+ \ \ \
  1370. / / / / \ \ \ \
  1371. v v v v v v v v
  1372. +---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+---+
  1373. | 0 | 1 | 4 | 5 | 6 | 7 | | 0 | 1 | a | b | c | 4 | 5 | 6 | 7 |
  1374. +---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+---+
  1375. A B \=========/
  1376. insert=[a,b,c]
  1377. In case A, it is obvious that copying of [4,5,6,7] must be left-to-right so
  1378. that we don't end up with [0,1,6,7,6,7]. In case B, we have the opposite; we
  1379. must go right-to-left or else we would end up with [0,1,a,b,c,4,4,4,4].
  1380. */
  1381. function replaceSim (array, index, removeCount, insert) {
  1382. var add = insert ? insert.length : 0,
  1383. length = array.length,
  1384. pos = fixArrayIndex(array, index);
  1385. // we try to use Array.push when we can for efficiency...
  1386. if (pos === length) {
  1387. if (add) {
  1388. array.push.apply(array, insert);
  1389. }
  1390. } else {
  1391. var remove = Math.min(removeCount, length - pos),
  1392. tailOldPos = pos + remove,
  1393. tailNewPos = tailOldPos + add - remove,
  1394. tailCount = length - tailOldPos,
  1395. lengthAfterRemove = length - remove,
  1396. i;
  1397. if (tailNewPos < tailOldPos) { // case A
  1398. for (i = 0; i < tailCount; ++i) {
  1399. array[tailNewPos+i] = array[tailOldPos+i];
  1400. }
  1401. } else if (tailNewPos > tailOldPos) { // case B
  1402. for (i = tailCount; i--; ) {
  1403. array[tailNewPos+i] = array[tailOldPos+i];
  1404. }
  1405. } // else, add == remove (nothing to do)
  1406. if (add && pos === lengthAfterRemove) {
  1407. array.length = lengthAfterRemove; // truncate array
  1408. array.push.apply(array, insert);
  1409. } else {
  1410. array.length = lengthAfterRemove + add; // reserves space
  1411. for (i = 0; i < add; ++i) {
  1412. array[pos+i] = insert[i];
  1413. }
  1414. }
  1415. }
  1416. return array;
  1417. }
  1418. function replaceNative (array, index, removeCount, insert) {
  1419. if (insert && insert.length) {
  1420. if (index < array.length) {
  1421. array.splice.apply(array, [index, removeCount].concat(insert));
  1422. } else {
  1423. array.push.apply(array, insert);
  1424. }
  1425. } else {
  1426. array.splice(index, removeCount);
  1427. }
  1428. return array;
  1429. }
  1430. function eraseSim (array, index, removeCount) {
  1431. return replaceSim(array, index, removeCount);
  1432. }
  1433. function eraseNative (array, index, removeCount) {
  1434. array.splice(index, removeCount);
  1435. return array;
  1436. }
  1437. function spliceSim (array, index, removeCount) {
  1438. var pos = fixArrayIndex(array, index),
  1439. removed = array.slice(index, fixArrayIndex(array, pos+removeCount));
  1440. if (arguments.length < 4) {
  1441. replaceSim(array, pos, removeCount);
  1442. } else {
  1443. replaceSim(array, pos, removeCount, slice.call(arguments, 3));
  1444. }
  1445. return removed;
  1446. }
  1447. function spliceNative (array) {
  1448. return array.splice.apply(array, slice.call(arguments, 1));
  1449. }
  1450. var erase = supportsSplice ? eraseNative : eraseSim,
  1451. replace = supportsSplice ? replaceNative : replaceSim,
  1452. splice = supportsSplice ? spliceNative : spliceSim;
  1453. // NOTE: from here on, use erase, replace or splice (not native methods)...
  1454. ExtArray = Ext.Array = {
  1455. /**
  1456. * Iterates an array or an iterable value and invoke the given callback function for each item.
  1457. *
  1458. * var countries = ['Vietnam', 'Singapore', 'United States', 'Russia'];
  1459. *
  1460. * Ext.Array.each(countries, function(name, index, countriesItSelf) {
  1461. * console.log(name);
  1462. * });
  1463. *
  1464. * var sum = function() {
  1465. * var sum = 0;
  1466. *
  1467. * Ext.Array.each(arguments, function(value) {
  1468. * sum += value;
  1469. * });
  1470. *
  1471. * return sum;
  1472. * };
  1473. *
  1474. * sum(1, 2, 3); // returns 6
  1475. *
  1476. * The iteration can be stopped by returning false in the function callback.
  1477. *
  1478. * Ext.Array.each(countries, function(name, index, countriesItSelf) {
  1479. * if (name === 'Singapore') {
  1480. * return false; // break here
  1481. * }
  1482. * });
  1483. *
  1484. * {@link Ext#each Ext.each} is alias for {@link Ext.Array#each Ext.Array.each}
  1485. *
  1486. * @param {Array/NodeList/Object} iterable The value to be iterated. If this
  1487. * argument is not iterable, the callback function is called once.
  1488. * @param {Function} fn The callback function. If it returns false, the iteration stops and this method returns
  1489. * the current `index`.
  1490. * @param {Object} fn.item The item at the current `index` in the passed `array`
  1491. * @param {Number} fn.index The current `index` within the `array`
  1492. * @param {Array} fn.allItems The `array` itself which was passed as the first argument
  1493. * @param {Boolean} fn.return Return false to stop iteration.
  1494. * @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed.
  1495. * @param {Boolean} reverse (Optional) Reverse the iteration order (loop from the end to the beginning)
  1496. * Defaults false
  1497. * @return {Boolean} See description for the `fn` parameter.
  1498. */
  1499. each: function(array, fn, scope, reverse) {
  1500. array = ExtArray.from(array);
  1501. var i,
  1502. ln = array.length;
  1503. if (reverse !== true) {
  1504. for (i = 0; i < ln; i++) {
  1505. if (fn.call(scope || array[i], array[i], i, array) === false) {
  1506. return i;
  1507. }
  1508. }
  1509. }
  1510. else {
  1511. for (i = ln - 1; i > -1; i--) {
  1512. if (fn.call(scope || array[i], array[i], i, array) === false) {
  1513. return i;
  1514. }
  1515. }
  1516. }
  1517. return true;
  1518. },
  1519. /**
  1520. * Iterates an array and invoke the given callback function for each item. Note that this will simply
  1521. * delegate to the native Array.prototype.forEach method if supported. It doesn't support stopping the
  1522. * iteration by returning false in the callback function like {@link Ext.Array#each}. However, performance
  1523. * could be much better in modern browsers comparing with {@link Ext.Array#each}
  1524. *
  1525. * @param {Array} array The array to iterate
  1526. * @param {Function} fn The callback function.
  1527. * @param {Object} fn.item The item at the current `index` in the passed `array`
  1528. * @param {Number} fn.index The current `index` within the `array`
  1529. * @param {Array} fn.allItems The `array` itself which was passed as the first argument
  1530. * @param {Object} scope (Optional) The execution scope (`this`) in which the specified function is executed.
  1531. */
  1532. forEach: supportsForEach ? function(array, fn, scope) {
  1533. return array.forEach(fn, scope);
  1534. } : function(array, fn, scope) {
  1535. var i = 0,
  1536. ln = array.length;
  1537. for (; i < ln; i++) {
  1538. fn.call(scope, array[i], i, array);
  1539. }
  1540. },
  1541. /**
  1542. * Get the index of the provided `item` in the given `array`, a supplement for the
  1543. * missing arrayPrototype.indexOf in Internet Explorer.
  1544. *
  1545. * @param {Array} array The array to check
  1546. * @param {Object} item The item to look for
  1547. * @param {Number} from (Optional) The index at which to begin the search
  1548. * @return {Number} The index of item in the array (or -1 if it is not found)
  1549. */
  1550. indexOf: supportsIndexOf ? function(array, item, from) {
  1551. return array.indexOf(item, from);
  1552. } : function(array, item, from) {
  1553. var i, length = array.length;
  1554. for (i = (from < 0) ? Math.max(0, length + from) : from || 0; i < length; i++) {
  1555. if (array[i] === item) {
  1556. return i;
  1557. }
  1558. }
  1559. return -1;
  1560. },
  1561. /**
  1562. * Checks whether or not the given `array` contains the specified `item`
  1563. *
  1564. * @param {Array} array The array to check
  1565. * @param {Object} item The item to look for
  1566. * @return {Boolean} True if the array contains the item, false otherwise
  1567. */
  1568. contains: supportsIndexOf ? function(array, item) {
  1569. return array.indexOf(item) !== -1;
  1570. } : function(array, item) {
  1571. var i, ln;
  1572. for (i = 0, ln = array.length; i < ln; i++) {
  1573. if (array[i] === item) {
  1574. return true;
  1575. }
  1576. }
  1577. return false;
  1578. },
  1579. /**
  1580. * Converts any iterable (numeric indices and a length property) into a true array.
  1581. *
  1582. * function test() {
  1583. * var args = Ext.Array.toArray(arguments),
  1584. * fromSecondToLastArgs = Ext.Array.toArray(arguments, 1);
  1585. *
  1586. * alert(args.join(' '));
  1587. * alert(fromSecondToLastArgs.join(' '));
  1588. * }
  1589. *
  1590. * test('just', 'testing', 'here'); // alerts 'just testing here';
  1591. * // alerts 'testing here';
  1592. *
  1593. * Ext.Array.toArray(document.getElementsByTagName('div')); // will convert the NodeList into an array
  1594. * Ext.Array.toArray('splitted'); // returns ['s', 'p', 'l', 'i', 't', 't', 'e', 'd']
  1595. * Ext.Array.toArray('splitted', 0, 3); // returns ['s', 'p', 'l', 'i']
  1596. *
  1597. * {@link Ext#toArray Ext.toArray} is alias for {@link Ext.Array#toArray Ext.Array.toArray}
  1598. *
  1599. * @param {Object} iterable the iterable object to be turned into a true Array.
  1600. * @param {Number} start (Optional) a zero-based index that specifies the start of extraction. Defaults to 0
  1601. * @param {Number} end (Optional) a zero-based index that specifies the end of extraction. Defaults to the last
  1602. * index of the iterable value
  1603. * @return {Array} array
  1604. */
  1605. toArray: function(iterable, start, end){
  1606. if (!iterable || !iterable.length) {
  1607. return [];
  1608. }
  1609. if (typeof iterable === 'string') {
  1610. iterable = iterable.split('');
  1611. }
  1612. if (supportsSliceOnNodeList) {
  1613. return slice.call(iterable, start || 0, end || iterable.length);
  1614. }
  1615. var array = [],
  1616. i;
  1617. start = start || 0;
  1618. end = end ? ((end < 0) ? iterable.length + end : end) : iterable.length;
  1619. for (i = start; i < end; i++) {
  1620. array.push(iterable[i]);
  1621. }
  1622. return array;
  1623. },
  1624. /**
  1625. * Plucks the value of a property from each item in the Array. Example:
  1626. *
  1627. * Ext.Array.pluck(Ext.query("p"), "className"); // [el1.className, el2.className, ..., elN.className]
  1628. *
  1629. * @param {Array/NodeList} array The Array of items to pluck the value from.
  1630. * @param {String} propertyName The property name to pluck from each element.
  1631. * @return {Array} The value from each item in the Array.
  1632. */
  1633. pluck: function(array, propertyName) {
  1634. var ret = [],
  1635. i, ln, item;
  1636. for (i = 0, ln = array.length; i < ln; i++) {
  1637. item = array[i];
  1638. ret.push(item[propertyName]);
  1639. }
  1640. return ret;
  1641. },
  1642. /**
  1643. * Creates a new array with the results of calling a provided function on every element in this array.
  1644. *
  1645. * @param {Array} array
  1646. * @param {Function} fn Callback function for each item
  1647. * @param {Object} scope Callback function scope
  1648. * @return {Array} results
  1649. */
  1650. map: supportsMap ? function(array, fn, scope) {
  1651. return array.map(fn, scope);
  1652. } : function(array, fn, scope) {
  1653. var results = [],
  1654. i = 0,
  1655. len = array.length;
  1656. for (; i < len; i++) {
  1657. results[i] = fn.call(scope, array[i], i, array);
  1658. }
  1659. return results;
  1660. },
  1661. /**
  1662. * Executes the specified function for each array element until the function returns a falsy value.
  1663. * If such an item is found, the function will return false immediately.
  1664. * Otherwise, it will return true.
  1665. *
  1666. * @param {Array} array
  1667. * @param {Function} fn Callback function for each item
  1668. * @param {Object} scope Callback function scope
  1669. * @return {Boolean} True if no false value is returned by the callback function.
  1670. */
  1671. every: supportsEvery ? function(array, fn, scope) {
  1672. return array.every(fn, scope);
  1673. } : function(array, fn, scope) {
  1674. var i = 0,
  1675. ln = array.length;
  1676. for (; i < ln; ++i) {
  1677. if (!fn.call(scope, array[i], i, array)) {
  1678. return false;
  1679. }
  1680. }
  1681. return true;
  1682. },
  1683. /**
  1684. * Executes the specified function for each array element until the function returns a truthy value.
  1685. * If such an item is found, the function will return true immediately. Otherwise, it will return false.
  1686. *
  1687. * @param {Array} array
  1688. * @param {Function} fn Callback function for each item
  1689. * @param {Object} scope Callback function scope
  1690. * @return {Boolean} True if the callback function returns a truthy value.
  1691. */
  1692. some: supportsSome ? function(array, fn, scope) {
  1693. return array.some(fn, scope);
  1694. } : function(array, fn, scope) {
  1695. var i = 0,
  1696. ln = array.length;
  1697. for (; i < ln; ++i) {
  1698. if (fn.call(scope, array[i], i, array)) {
  1699. return true;
  1700. }
  1701. }
  1702. return false;
  1703. },
  1704. /**
  1705. * Filter through an array and remove empty item as defined in {@link Ext#isEmpty Ext.isEmpty}
  1706. *
  1707. * See {@link Ext.Array#filter}
  1708. *
  1709. * @param {Array} array
  1710. * @return {Array} results
  1711. */
  1712. clean: function(array) {
  1713. var results = [],
  1714. i = 0,
  1715. ln = array.length,
  1716. item;
  1717. for (; i < ln; i++) {
  1718. item = array[i];
  1719. if (!Ext.isEmpty(item)) {
  1720. results.push(item);
  1721. }
  1722. }
  1723. return results;
  1724. },
  1725. /**
  1726. * Returns a new array with unique items
  1727. *
  1728. * @param {Array} array
  1729. * @return {Array} results
  1730. */
  1731. unique: function(array) {
  1732. var clone = [],
  1733. i = 0,
  1734. ln = array.length,
  1735. item;
  1736. for (; i < ln; i++) {
  1737. item = array[i];
  1738. if (ExtArray.indexOf(clone, item) === -1) {
  1739. clone.push(item);
  1740. }
  1741. }
  1742. return clone;
  1743. },
  1744. /**
  1745. * Creates a new array with all of the elements of this array for which
  1746. * the provided filtering function returns true.
  1747. *
  1748. * @param {Array} array
  1749. * @param {Function} fn Callback function for each item
  1750. * @param {Object} scope Callback function scope
  1751. * @return {Array} results
  1752. */
  1753. filter: supportsFilter ? function(array, fn, scope) {
  1754. return array.filter(fn, scope);
  1755. } : function(array, fn, scope) {
  1756. var results = [],
  1757. i = 0,
  1758. ln = array.length;
  1759. for (; i < ln; i++) {
  1760. if (fn.call(scope, array[i], i, array)) {
  1761. results.push(array[i]);
  1762. }
  1763. }
  1764. return results;
  1765. },
  1766. /**
  1767. * Converts a value to an array if it's not already an array; returns:
  1768. *
  1769. * - An empty array if given value is `undefined` or `null`
  1770. * - Itself if given value is already an array
  1771. * - An array copy if given value is {@link Ext#isIterable iterable} (arguments, NodeList and alike)
  1772. * - An array with one item which is the given value, otherwise
  1773. *
  1774. * @param {Object} value The value to convert to an array if it's not already is an array
  1775. * @param {Boolean} newReference (Optional) True to clone the given array and return a new reference if necessary,
  1776. * defaults to false
  1777. * @return {Array} array
  1778. */
  1779. from: function(value, newReference) {
  1780. if (value === undefined || value === null) {
  1781. return [];
  1782. }
  1783. if (Ext.isArray(value)) {
  1784. return (newReference) ? slice.call(value) : value;
  1785. }
  1786. if (value && value.length !== undefined && typeof value !== 'string') {
  1787. return ExtArray.toArray(value);
  1788. }
  1789. return [value];
  1790. },
  1791. /**
  1792. * Removes the specified item from the array if it exists
  1793. *
  1794. * @param {Array} array The array
  1795. * @param {Object} item The item to remove
  1796. * @return {Array} The passed array itself
  1797. */
  1798. remove: function(array, item) {
  1799. var index = ExtArray.indexOf(array, item);
  1800. if (index !== -1) {
  1801. erase(array, index, 1);
  1802. }
  1803. return array;
  1804. },
  1805. /**
  1806. * Push an item into the array only if the array doesn't contain it yet
  1807. *
  1808. * @param {Array} array The array
  1809. * @param {Object} item The item to include
  1810. */
  1811. include: function(array, item) {
  1812. if (!ExtArray.contains(array, item)) {
  1813. array.push(item);
  1814. }
  1815. },
  1816. /**
  1817. * Clone a flat array without referencing the previous one. Note that this is different
  1818. * from Ext.clone since it doesn't handle recursive cloning. It's simply a convenient, easy-to-remember method
  1819. * for Array.prototype.slice.call(array)
  1820. *
  1821. * @param {Array} array The array
  1822. * @return {Array} The clone array
  1823. */
  1824. clone: function(array) {
  1825. return slice.call(array);
  1826. },
  1827. /**
  1828. * Merge multiple arrays into one with unique items.
  1829. *
  1830. * {@link Ext.Array#union} is alias for {@link Ext.Array#merge}
  1831. *
  1832. * @param {Array} array1
  1833. * @param {Array} array2
  1834. * @param {Array} etc
  1835. * @return {Array} merged
  1836. */
  1837. merge: function() {
  1838. var args = slice.call(arguments),
  1839. array = [],
  1840. i, ln;
  1841. for (i = 0, ln = args.length; i < ln; i++) {
  1842. array = array.concat(args[i]);
  1843. }
  1844. return ExtArray.unique(array);
  1845. },
  1846. /**
  1847. * Merge multiple arrays into one with unique items that exist in all of the arrays.
  1848. *
  1849. * @param {Array} array1
  1850. * @param {Array} array2
  1851. * @param {Array} etc
  1852. * @return {Array} intersect
  1853. */
  1854. intersect: function() {
  1855. var intersect = [],
  1856. arrays = slice.call(arguments),
  1857. i, j, k, minArray, array, x, y, ln, arraysLn, arrayLn;
  1858. if (!arrays.length) {
  1859. return intersect;
  1860. }
  1861. // Find the smallest array
  1862. for (i = x = 0,ln = arrays.length; i < ln,array = arrays[i]; i++) {
  1863. if (!minArray || array.length < minArray.length) {
  1864. minArray = array;
  1865. x = i;
  1866. }
  1867. }
  1868. minArray = ExtArray.unique(minArray);
  1869. erase(arrays, x, 1);
  1870. // Use the smallest unique'd array as the anchor loop. If the other array(s) do contain
  1871. // an item in the small array, we're likely to find it before reaching the end
  1872. // of the inner loop and can terminate the search early.
  1873. for (i = 0,ln = minArray.length; i < ln,x = minArray[i]; i++) {
  1874. var count = 0;
  1875. for (j = 0,arraysLn = arrays.length; j < arraysLn,array = arrays[j]; j++) {
  1876. for (k = 0,arrayLn = array.length; k < arrayLn,y = array[k]; k++) {
  1877. if (x === y) {
  1878. count++;
  1879. break;
  1880. }
  1881. }
  1882. }
  1883. if (count === arraysLn) {
  1884. intersect.push(x);
  1885. }
  1886. }
  1887. return intersect;
  1888. },
  1889. /**
  1890. * Perform a set difference A-B by subtracting all items in array B from array A.
  1891. *
  1892. * @param {Array} arrayA
  1893. * @param {Array} arrayB
  1894. * @return {Array} difference
  1895. */
  1896. difference: function(arrayA, arrayB) {
  1897. var clone = slice.call(arrayA),
  1898. ln = clone.length,
  1899. i, j, lnB;
  1900. for (i = 0,lnB = arrayB.length; i < lnB; i++) {
  1901. for (j = 0; j < ln; j++) {
  1902. if (clone[j] === arrayB[i]) {
  1903. erase(clone, j, 1);
  1904. j--;
  1905. ln--;
  1906. }
  1907. }
  1908. }
  1909. return clone;
  1910. },
  1911. /**
  1912. * Returns a shallow copy of a part of an array. This is equivalent to the native
  1913. * call "Array.prototype.slice.call(array, begin, end)". This is often used when "array"
  1914. * is "arguments" since the arguments object does not supply a slice method but can
  1915. * be the context object to Array.prototype.slice.
  1916. *
  1917. * @param {Array} array The array (or arguments object).
  1918. * @param {Number} begin The index at which to begin. Negative values are offsets from
  1919. * the end of the array.
  1920. * @param {Number} end The index at which to end. The copied items do not include
  1921. * end. Negative values are offsets from the end of the array. If end is omitted,
  1922. * all items up to the end of the array are copied.
  1923. * @return {Array} The copied piece of the array.
  1924. * @method
  1925. */
  1926. // Note: IE6 will return [] on slice.call(x, undefined).
  1927. slice: ([1,2].slice(1, undefined).length ?
  1928. function (array, begin, end) {
  1929. return slice.call(array, begin, end);
  1930. } :
  1931. // at least IE6 uses arguments.length for variadic signature
  1932. function (array, begin, end) {
  1933. // After tested for IE 6, the one below is of the best performance
  1934. // see http://jsperf.com/slice-fix
  1935. if (typeof begin === 'undefined') {
  1936. return slice.call(array);
  1937. }
  1938. if (typeof end === 'undefined') {
  1939. return slice.call(array, begin);
  1940. }
  1941. return slice.call(array, begin, end);
  1942. }
  1943. ),
  1944. /**
  1945. * Sorts the elements of an Array.
  1946. * By default, this method sorts the elements alphabetically and ascending.
  1947. *
  1948. * @param {Array} array The array to sort.
  1949. * @param {Function} sortFn (optional) The comparison function.
  1950. * @return {Array} The sorted array.
  1951. */
  1952. sort: supportsSort ? function(array, sortFn) {
  1953. if (sortFn) {
  1954. return array.sort(sortFn);
  1955. } else {
  1956. return array.sort();
  1957. }
  1958. } : function(array, sortFn) {
  1959. var length = array.length,
  1960. i = 0,
  1961. comparison,
  1962. j, min, tmp;
  1963. for (; i < length; i++) {
  1964. min = i;
  1965. for (j = i + 1; j < length; j++) {
  1966. if (sortFn) {
  1967. comparison = sortFn(array[j], array[min]);
  1968. if (comparison < 0) {
  1969. min = j;
  1970. }
  1971. } else if (array[j] < array[min]) {
  1972. min = j;
  1973. }
  1974. }
  1975. if (min !== i) {
  1976. tmp = array[i];
  1977. array[i] = array[min];
  1978. array[min] = tmp;
  1979. }
  1980. }
  1981. return array;
  1982. },
  1983. /**
  1984. * Recursively flattens into 1-d Array. Injects Arrays inline.
  1985. *
  1986. * @param {Array} array The array to flatten
  1987. * @return {Array} The 1-d array.
  1988. */
  1989. flatten: function(array) {
  1990. var worker = [];
  1991. function rFlatten(a) {
  1992. var i, ln, v;
  1993. for (i = 0, ln = a.length; i < ln; i++) {
  1994. v = a[i];
  1995. if (Ext.isArray(v)) {
  1996. rFlatten(v);
  1997. } else {
  1998. worker.push(v);
  1999. }
  2000. }
  2001. return worker;
  2002. }
  2003. return rFlatten(array);
  2004. },
  2005. /**
  2006. * Returns the minimum value in the Array.
  2007. *
  2008. * @param {Array/NodeList} array The Array from which to select the minimum value.
  2009. * @param {Function} comparisonFn (optional) a function to perform the comparision which determines minimization.
  2010. * If omitted the "<" operator will be used. Note: gt = 1; eq = 0; lt = -1
  2011. * @return {Object} minValue The minimum value
  2012. */
  2013. min: function(array, comparisonFn) {
  2014. var min = array[0],
  2015. i, ln, item;
  2016. for (i = 0, ln = array.length; i < ln; i++) {
  2017. item = array[i];
  2018. if (comparisonFn) {
  2019. if (comparisonFn(min, item) === 1) {
  2020. min = item;
  2021. }
  2022. }
  2023. else {
  2024. if (item < min) {
  2025. min = item;
  2026. }
  2027. }
  2028. }
  2029. return min;
  2030. },
  2031. /**
  2032. * Returns the maximum value in the Array.
  2033. *
  2034. * @param {Array/NodeList} array The Array from which to select the maximum value.
  2035. * @param {Function} comparisonFn (optional) a function to perform the comparision which determines maximization.
  2036. * If omitted the ">" operator will be used. Note: gt = 1; eq = 0; lt = -1
  2037. * @return {Object} maxValue The maximum value
  2038. */
  2039. max: function(array, comparisonFn) {
  2040. var max = array[0],
  2041. i, ln, item;
  2042. for (i = 0, ln = array.length; i < ln; i++) {
  2043. item = array[i];
  2044. if (comparisonFn) {
  2045. if (comparisonFn(max, item) === -1) {
  2046. max = item;
  2047. }
  2048. }
  2049. else {
  2050. if (item > max) {
  2051. max = item;
  2052. }
  2053. }
  2054. }
  2055. return max;
  2056. },
  2057. /**
  2058. * Calculates the mean of all items in the array.
  2059. *
  2060. * @param {Array} array The Array to calculate the mean value of.
  2061. * @return {Number} The mean.
  2062. */
  2063. mean: function(array) {
  2064. return array.length > 0 ? ExtArray.sum(array) / array.length : undefined;
  2065. },
  2066. /**
  2067. * Calculates the sum of all items in the given array.
  2068. *
  2069. * @param {Array} array The Array to calculate the sum value of.
  2070. * @return {Number} The sum.
  2071. */
  2072. sum: function(array) {
  2073. var sum = 0,
  2074. i, ln, item;
  2075. for (i = 0,ln = array.length; i < ln; i++) {
  2076. item = array[i];
  2077. sum += item;
  2078. }
  2079. return sum;
  2080. },
  2081. /**
  2082. * Creates a map (object) keyed by the elements of the given array. The values in
  2083. * the map are the index+1 of the array element. For example:
  2084. *
  2085. * var map = Ext.Array.toMap(['a','b','c']);
  2086. *
  2087. * // map = { a: 1, b: 2, c: 3 };
  2088. *
  2089. * Or a key property can be specified:
  2090. *
  2091. * var map = Ext.Array.toMap([
  2092. * { name: 'a' },
  2093. * { name: 'b' },
  2094. * { name: 'c' }
  2095. * ], 'name');
  2096. *
  2097. * // map = { a: 1, b: 2, c: 3 };
  2098. *
  2099. * Lastly, a key extractor can be provided:
  2100. *
  2101. * var map = Ext.Array.toMap([
  2102. * { name: 'a' },
  2103. * { name: 'b' },
  2104. * { name: 'c' }
  2105. * ], function (obj) { return obj.name.toUpperCase(); });
  2106. *
  2107. * // map = { A: 1, B: 2, C: 3 };
  2108. */
  2109. toMap: function(array, getKey, scope) {
  2110. var map = {},
  2111. i = array.length;
  2112. if (!getKey) {
  2113. while (i--) {
  2114. map[array[i]] = i+1;
  2115. }
  2116. } else if (typeof getKey == 'string') {
  2117. while (i--) {
  2118. map[array[i][getKey]] = i+1;
  2119. }
  2120. } else {
  2121. while (i--) {
  2122. map[getKey.call(scope, array[i])] = i+1;
  2123. }
  2124. }
  2125. return map;
  2126. },
  2127. /**
  2128. * Removes items from an array. This is functionally equivalent to the splice method
  2129. * of Array, but works around bugs in IE8's splice method and does not copy the
  2130. * removed elements in order to return them (because very often they are ignored).
  2131. *
  2132. * @param {Array} array The Array on which to replace.
  2133. * @param {Number} index The index in the array at which to operate.
  2134. * @param {Number} removeCount The number of items to remove at index.
  2135. * @return {Array} The array passed.
  2136. * @method
  2137. */
  2138. erase: erase,
  2139. /**
  2140. * Inserts items in to an array.
  2141. *
  2142. * @param {Array} array The Array in which to insert.
  2143. * @param {Number} index The index in the array at which to operate.
  2144. * @param {Array} items The array of items to insert at index.
  2145. * @return {Array} The array passed.
  2146. */
  2147. insert: function (array, index, items) {
  2148. return replace(array, index, 0, items);
  2149. },
  2150. /**
  2151. * Replaces items in an array. This is functionally equivalent to the splice method
  2152. * of Array, but works around bugs in IE8's splice method and is often more convenient
  2153. * to call because it accepts an array of items to insert rather than use a variadic
  2154. * argument list.
  2155. *
  2156. * @param {Array} array The Array on which to replace.
  2157. * @param {Number} index The index in the array at which to operate.
  2158. * @param {Number} removeCount The number of items to remove at index (can be 0).
  2159. * @param {Array} insert (optional) An array of items to insert at index.
  2160. * @return {Array} The array passed.
  2161. * @method
  2162. */
  2163. replace: replace,
  2164. /**
  2165. * Replaces items in an array. This is equivalent to the splice method of Array, but
  2166. * works around bugs in IE8's splice method. The signature is exactly the same as the
  2167. * splice method except that the array is the first argument. All arguments following
  2168. * removeCount are inserted in the array at index.
  2169. *
  2170. * @param {Array} array The Array on which to replace.
  2171. * @param {Number} index The index in the array at which to operate.
  2172. * @param {Number} removeCount The number of items to remove at index (can be 0).
  2173. * @param {Object...} elements The elements to add to the array. If you don't specify
  2174. * any elements, splice simply removes elements from the array.
  2175. * @return {Array} An array containing the removed items.
  2176. * @method
  2177. */
  2178. splice: splice,
  2179. /**
  2180. * Pushes new items onto the end of an Array.
  2181. *
  2182. * Passed parameters may be single items, or arrays of items. If an Array is found in the argument list, all its
  2183. * elements are pushed into the end of the target Array.
  2184. *
  2185. * @param {Array} target The Array onto which to push new items
  2186. * @param {Object...} elements The elements to add to the array. Each parameter may
  2187. * be an Array, in which case all the elements of that Array will be pushed into the end of the
  2188. * destination Array.
  2189. * @return {Array} An array containing all the new items push onto the end.
  2190. *
  2191. */
  2192. push: function(array) {
  2193. var len = arguments.length,
  2194. i = 1,
  2195. newItem;
  2196. if (array === undefined) {
  2197. array = [];
  2198. } else if (!Ext.isArray(array)) {
  2199. array = [array];
  2200. }
  2201. for (; i < len; i++) {
  2202. newItem = arguments[i];
  2203. Array.prototype.push[Ext.isArray(newItem) ? 'apply' : 'call'](array, newItem);
  2204. }
  2205. return array;
  2206. }
  2207. };
  2208. /**
  2209. * @method
  2210. * @member Ext
  2211. * @inheritdoc Ext.Array#each
  2212. */
  2213. Ext.each = ExtArray.each;
  2214. /**
  2215. * @method
  2216. * @member Ext.Array
  2217. * @inheritdoc Ext.Array#merge
  2218. */
  2219. ExtArray.union = ExtArray.merge;
  2220. /**
  2221. * Old alias to {@link Ext.Array#min}
  2222. * @deprecated 4.0.0 Use {@link Ext.Array#min} instead
  2223. * @method
  2224. * @member Ext
  2225. * @inheritdoc Ext.Array#min
  2226. */
  2227. Ext.min = ExtArray.min;
  2228. /**
  2229. * Old alias to {@link Ext.Array#max}
  2230. * @deprecated 4.0.0 Use {@link Ext.Array#max} instead
  2231. * @method
  2232. * @member Ext
  2233. * @inheritdoc Ext.Array#max
  2234. */
  2235. Ext.max = ExtArray.max;
  2236. /**
  2237. * Old alias to {@link Ext.Array#sum}
  2238. * @deprecated 4.0.0 Use {@link Ext.Array#sum} instead
  2239. * @method
  2240. * @member Ext
  2241. * @inheritdoc Ext.Array#sum
  2242. */
  2243. Ext.sum = ExtArray.sum;
  2244. /**
  2245. * Old alias to {@link Ext.Array#mean}
  2246. * @deprecated 4.0.0 Use {@link Ext.Array#mean} instead
  2247. * @method
  2248. * @member Ext
  2249. * @inheritdoc Ext.Array#mean
  2250. */
  2251. Ext.mean = ExtArray.mean;
  2252. /**
  2253. * Old alias to {@link Ext.Array#flatten}
  2254. * @deprecated 4.0.0 Use {@link Ext.Array#flatten} instead
  2255. * @method
  2256. * @member Ext
  2257. * @inheritdoc Ext.Array#flatten
  2258. */
  2259. Ext.flatten = ExtArray.flatten;
  2260. /**
  2261. * Old alias to {@link Ext.Array#clean}
  2262. * @deprecated 4.0.0 Use {@link Ext.Array#clean} instead
  2263. * @method
  2264. * @member Ext
  2265. * @inheritdoc Ext.Array#clean
  2266. */
  2267. Ext.clean = ExtArray.clean;
  2268. /**
  2269. * Old alias to {@link Ext.Array#unique}
  2270. * @deprecated 4.0.0 Use {@link Ext.Array#unique} instead
  2271. * @method
  2272. * @member Ext
  2273. * @inheritdoc Ext.Array#unique
  2274. */
  2275. Ext.unique = ExtArray.unique;
  2276. /**
  2277. * Old alias to {@link Ext.Array#pluck Ext.Array.pluck}
  2278. * @deprecated 4.0.0 Use {@link Ext.Array#pluck Ext.Array.pluck} instead
  2279. * @method
  2280. * @member Ext
  2281. * @inheritdoc Ext.Array#pluck
  2282. */
  2283. Ext.pluck = ExtArray.pluck;
  2284. /**
  2285. * @method
  2286. * @member Ext
  2287. * @inheritdoc Ext.Array#toArray
  2288. */
  2289. Ext.toArray = function() {
  2290. return ExtArray.toArray.apply(ExtArray, arguments);
  2291. };
  2292. })();
  2293. /**
  2294. * @class Ext.Function
  2295. *
  2296. * A collection of useful static methods to deal with function callbacks
  2297. * @singleton
  2298. * @alternateClassName Ext.util.Functions
  2299. */
  2300. Ext.Function = {
  2301. /**
  2302. * A very commonly used method throughout the framework. It acts as a wrapper around another method
  2303. * which originally accepts 2 arguments for `name` and `value`.
  2304. * The wrapped function then allows "flexible" value setting of either:
  2305. *
  2306. * - `name` and `value` as 2 arguments
  2307. * - one single object argument with multiple key - value pairs
  2308. *
  2309. * For example:
  2310. *
  2311. * var setValue = Ext.Function.flexSetter(function(name, value) {
  2312. * this[name] = value;
  2313. * });
  2314. *
  2315. * // Afterwards
  2316. * // Setting a single name - value
  2317. * setValue('name1', 'value1');
  2318. *
  2319. * // Settings multiple name - value pairs
  2320. * setValue({
  2321. * name1: 'value1',
  2322. * name2: 'value2',
  2323. * name3: 'value3'
  2324. * });
  2325. *
  2326. * @param {Function} setter
  2327. * @returns {Function} flexSetter
  2328. */
  2329. flexSetter: function(fn) {
  2330. return function(a, b) {
  2331. var k, i;
  2332. if (a === null) {
  2333. return this;
  2334. }
  2335. if (typeof a !== 'string') {
  2336. for (k in a) {
  2337. if (a.hasOwnProperty(k)) {
  2338. fn.call(this, k, a[k]);
  2339. }
  2340. }
  2341. if (Ext.enumerables) {
  2342. for (i = Ext.enumerables.length; i--;) {
  2343. k = Ext.enumerables[i];
  2344. if (a.hasOwnProperty(k)) {
  2345. fn.call(this, k, a[k]);
  2346. }
  2347. }
  2348. }
  2349. } else {
  2350. fn.call(this, a, b);
  2351. }
  2352. return this;
  2353. };
  2354. },
  2355. /**
  2356. * Create a new function from the provided `fn`, change `this` to the provided scope, optionally
  2357. * overrides arguments for the call. (Defaults to the arguments passed by the caller)
  2358. *
  2359. * {@link Ext#bind Ext.bind} is alias for {@link Ext.Function#bind Ext.Function.bind}
  2360. *
  2361. * @param {Function} fn The function to delegate.
  2362. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
  2363. * **If omitted, defaults to the default global environment object (usually the browser window).**
  2364. * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
  2365. * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
  2366. * if a number the args are inserted at the specified position
  2367. * @return {Function} The new function
  2368. */
  2369. bind: function(fn, scope, args, appendArgs) {
  2370. if (arguments.length === 2) {
  2371. return function() {
  2372. return fn.apply(scope, arguments);
  2373. };
  2374. }
  2375. var method = fn,
  2376. slice = Array.prototype.slice;
  2377. return function() {
  2378. var callArgs = args || arguments;
  2379. if (appendArgs === true) {
  2380. callArgs = slice.call(arguments, 0);
  2381. callArgs = callArgs.concat(args);
  2382. }
  2383. else if (typeof appendArgs == 'number') {
  2384. callArgs = slice.call(arguments, 0); // copy arguments first
  2385. Ext.Array.insert(callArgs, appendArgs, args);
  2386. }
  2387. return method.apply(scope || Ext.global, callArgs);
  2388. };
  2389. },
  2390. /**
  2391. * Create a new function from the provided `fn`, the arguments of which are pre-set to `args`.
  2392. * New arguments passed to the newly created callback when it's invoked are appended after the pre-set ones.
  2393. * This is especially useful when creating callbacks.
  2394. *
  2395. * For example:
  2396. *
  2397. * var originalFunction = function(){
  2398. * alert(Ext.Array.from(arguments).join(' '));
  2399. * };
  2400. *
  2401. * var callback = Ext.Function.pass(originalFunction, ['Hello', 'World']);
  2402. *
  2403. * callback(); // alerts 'Hello World'
  2404. * callback('by Me'); // alerts 'Hello World by Me'
  2405. *
  2406. * {@link Ext#pass Ext.pass} is alias for {@link Ext.Function#pass Ext.Function.pass}
  2407. *
  2408. * @param {Function} fn The original function
  2409. * @param {Array} args The arguments to pass to new callback
  2410. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
  2411. * @return {Function} The new callback function
  2412. */
  2413. pass: function(fn, args, scope) {
  2414. if (!Ext.isArray(args)) {
  2415. if (Ext.isIterable(args)) {
  2416. args = Ext.Array.clone(args);
  2417. } else {
  2418. args = args !== undefined ? [args] : [];
  2419. }
  2420. };
  2421. return function() {
  2422. var fnArgs = [].concat(args);
  2423. fnArgs.push.apply(fnArgs, arguments);
  2424. return fn.apply(scope || this, fnArgs);
  2425. };
  2426. },
  2427. /**
  2428. * Create an alias to the provided method property with name `methodName` of `object`.
  2429. * Note that the execution scope will still be bound to the provided `object` itself.
  2430. *
  2431. * @param {Object/Function} object
  2432. * @param {String} methodName
  2433. * @return {Function} aliasFn
  2434. */
  2435. alias: function(object, methodName) {
  2436. return function() {
  2437. return object[methodName].apply(object, arguments);
  2438. };
  2439. },
  2440. /**
  2441. * Create a "clone" of the provided method. The returned method will call the given
  2442. * method passing along all arguments and the "this" pointer and return its result.
  2443. *
  2444. * @param {Function} method
  2445. * @return {Function} cloneFn
  2446. */
  2447. clone: function(method) {
  2448. return function() {
  2449. return method.apply(this, arguments);
  2450. };
  2451. },
  2452. /**
  2453. * Creates an interceptor function. The passed function is called before the original one. If it returns false,
  2454. * the original one is not called. The resulting function returns the results of the original function.
  2455. * The passed function is called with the parameters of the original function. Example usage:
  2456. *
  2457. * var sayHi = function(name){
  2458. * alert('Hi, ' + name);
  2459. * }
  2460. *
  2461. * sayHi('Fred'); // alerts "Hi, Fred"
  2462. *
  2463. * // create a new function that validates input without
  2464. * // directly modifying the original function:
  2465. * var sayHiToFriend = Ext.Function.createInterceptor(sayHi, function(name){
  2466. * return name == 'Brian';
  2467. * });
  2468. *
  2469. * sayHiToFriend('Fred'); // no alert
  2470. * sayHiToFriend('Brian'); // alerts "Hi, Brian"
  2471. *
  2472. * @param {Function} origFn The original function.
  2473. * @param {Function} newFn The function to call before the original
  2474. * @param {Object} scope (optional) The scope (`this` reference) in which the passed function is executed.
  2475. * **If omitted, defaults to the scope in which the original function is called or the browser window.**
  2476. * @param {Object} returnValue (optional) The value to return if the passed function return false (defaults to null).
  2477. * @return {Function} The new function
  2478. */
  2479. createInterceptor: function(origFn, newFn, scope, returnValue) {
  2480. var method = origFn;
  2481. if (!Ext.isFunction(newFn)) {
  2482. return origFn;
  2483. }
  2484. else {
  2485. return function() {
  2486. var me = this,
  2487. args = arguments;
  2488. newFn.target = me;
  2489. newFn.method = origFn;
  2490. return (newFn.apply(scope || me || Ext.global, args) !== false) ? origFn.apply(me || Ext.global, args) : returnValue || null;
  2491. };
  2492. }
  2493. },
  2494. /**
  2495. * Creates a delegate (callback) which, when called, executes after a specific delay.
  2496. *
  2497. * @param {Function} fn The function which will be called on a delay when the returned function is called.
  2498. * Optionally, a replacement (or additional) argument list may be specified.
  2499. * @param {Number} delay The number of milliseconds to defer execution by whenever called.
  2500. * @param {Object} scope (optional) The scope (`this` reference) used by the function at execution time.
  2501. * @param {Array} args (optional) Override arguments for the call. (Defaults to the arguments passed by the caller)
  2502. * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
  2503. * if a number the args are inserted at the specified position.
  2504. * @return {Function} A function which, when called, executes the original function after the specified delay.
  2505. */
  2506. createDelayed: function(fn, delay, scope, args, appendArgs) {
  2507. if (scope || args) {
  2508. fn = Ext.Function.bind(fn, scope, args, appendArgs);
  2509. }
  2510. return function() {
  2511. var me = this,
  2512. args = Array.prototype.slice.call(arguments);
  2513. setTimeout(function() {
  2514. fn.apply(me, args);
  2515. }, delay);
  2516. };
  2517. },
  2518. /**
  2519. * Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage:
  2520. *
  2521. * var sayHi = function(name){
  2522. * alert('Hi, ' + name);
  2523. * }
  2524. *
  2525. * // executes immediately:
  2526. * sayHi('Fred');
  2527. *
  2528. * // executes after 2 seconds:
  2529. * Ext.Function.defer(sayHi, 2000, this, ['Fred']);
  2530. *
  2531. * // this syntax is sometimes useful for deferring
  2532. * // execution of an anonymous function:
  2533. * Ext.Function.defer(function(){
  2534. * alert('Anonymous');
  2535. * }, 100);
  2536. *
  2537. * {@link Ext#defer Ext.defer} is alias for {@link Ext.Function#defer Ext.Function.defer}
  2538. *
  2539. * @param {Function} fn The function to defer.
  2540. * @param {Number} millis The number of milliseconds for the setTimeout call
  2541. * (if less than or equal to 0 the function is executed immediately)
  2542. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
  2543. * **If omitted, defaults to the browser window.**
  2544. * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
  2545. * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
  2546. * if a number the args are inserted at the specified position
  2547. * @return {Number} The timeout id that can be used with clearTimeout
  2548. */
  2549. defer: function(fn, millis, scope, args, appendArgs) {
  2550. fn = Ext.Function.bind(fn, scope, args, appendArgs);
  2551. if (millis > 0) {
  2552. return setTimeout(fn, millis);
  2553. }
  2554. fn();
  2555. return 0;
  2556. },
  2557. /**
  2558. * Create a combined function call sequence of the original function + the passed function.
  2559. * The resulting function returns the results of the original function.
  2560. * The passed function is called with the parameters of the original function. Example usage:
  2561. *
  2562. * var sayHi = function(name){
  2563. * alert('Hi, ' + name);
  2564. * }
  2565. *
  2566. * sayHi('Fred'); // alerts "Hi, Fred"
  2567. *
  2568. * var sayGoodbye = Ext.Function.createSequence(sayHi, function(name){
  2569. * alert('Bye, ' + name);
  2570. * });
  2571. *
  2572. * sayGoodbye('Fred'); // both alerts show
  2573. *
  2574. * @param {Function} originalFn The original function.
  2575. * @param {Function} newFn The function to sequence
  2576. * @param {Object} scope (optional) The scope (`this` reference) in which the passed function is executed.
  2577. * If omitted, defaults to the scope in which the original function is called or the default global environment object (usually the browser window).
  2578. * @return {Function} The new function
  2579. */
  2580. createSequence: function(originalFn, newFn, scope) {
  2581. if (!newFn) {
  2582. return originalFn;
  2583. }
  2584. else {
  2585. return function() {
  2586. var result = originalFn.apply(this, arguments);
  2587. newFn.apply(scope || this, arguments);
  2588. return result;
  2589. };
  2590. }
  2591. },
  2592. /**
  2593. * Creates a delegate function, optionally with a bound scope which, when called, buffers
  2594. * the execution of the passed function for the configured number of milliseconds.
  2595. * If called again within that period, the impending invocation will be canceled, and the
  2596. * timeout period will begin again.
  2597. *
  2598. * @param {Function} fn The function to invoke on a buffered timer.
  2599. * @param {Number} buffer The number of milliseconds by which to buffer the invocation of the
  2600. * function.
  2601. * @param {Object} scope (optional) The scope (`this` reference) in which
  2602. * the passed function is executed. If omitted, defaults to the scope specified by the caller.
  2603. * @param {Array} args (optional) Override arguments for the call. Defaults to the arguments
  2604. * passed by the caller.
  2605. * @return {Function} A function which invokes the passed function after buffering for the specified time.
  2606. */
  2607. createBuffered: function(fn, buffer, scope, args) {
  2608. var timerId;
  2609. return function() {
  2610. var callArgs = args || Array.prototype.slice.call(arguments, 0),
  2611. me = scope || this;
  2612. if (timerId) {
  2613. clearTimeout(timerId);
  2614. }
  2615. timerId = setTimeout(function(){
  2616. fn.apply(me, callArgs);
  2617. }, buffer);
  2618. };
  2619. },
  2620. /**
  2621. * Creates a throttled version of the passed function which, when called repeatedly and
  2622. * rapidly, invokes the passed function only after a certain interval has elapsed since the
  2623. * previous invocation.
  2624. *
  2625. * This is useful for wrapping functions which may be called repeatedly, such as
  2626. * a handler of a mouse move event when the processing is expensive.
  2627. *
  2628. * @param {Function} fn The function to execute at a regular time interval.
  2629. * @param {Number} interval The interval **in milliseconds** on which the passed function is executed.
  2630. * @param {Object} scope (optional) The scope (`this` reference) in which
  2631. * the passed function is executed. If omitted, defaults to the scope specified by the caller.
  2632. * @returns {Function} A function which invokes the passed function at the specified interval.
  2633. */
  2634. createThrottled: function(fn, interval, scope) {
  2635. var lastCallTime, elapsed, lastArgs, timer, execute = function() {
  2636. fn.apply(scope || this, lastArgs);
  2637. lastCallTime = new Date().getTime();
  2638. };
  2639. return function() {
  2640. elapsed = new Date().getTime() - lastCallTime;
  2641. lastArgs = arguments;
  2642. clearTimeout(timer);
  2643. if (!lastCallTime || (elapsed >= interval)) {
  2644. execute();
  2645. } else {
  2646. timer = setTimeout(execute, interval - elapsed);
  2647. }
  2648. };
  2649. },
  2650. /**
  2651. * Adds behavior to an existing method that is executed before the
  2652. * original behavior of the function. For example:
  2653. *
  2654. * var soup = {
  2655. * contents: [],
  2656. * add: function(ingredient) {
  2657. * this.contents.push(ingredient);
  2658. * }
  2659. * };
  2660. * Ext.Function.interceptBefore(soup, "add", function(ingredient){
  2661. * if (!this.contents.length && ingredient !== "water") {
  2662. * // Always add water to start with
  2663. * this.contents.push("water");
  2664. * }
  2665. * });
  2666. * soup.add("onions");
  2667. * soup.add("salt");
  2668. * soup.contents; // will contain: water, onions, salt
  2669. *
  2670. * @param {Object} object The target object
  2671. * @param {String} methodName Name of the method to override
  2672. * @param {Function} fn Function with the new behavior. It will
  2673. * be called with the same arguments as the original method. The
  2674. * return value of this function will be the return value of the
  2675. * new method.
  2676. * @param {Object} [scope] The scope to execute the interceptor function. Defaults to the object.
  2677. * @return {Function} The new function just created.
  2678. */
  2679. interceptBefore: function(object, methodName, fn, scope) {
  2680. var method = object[methodName] || Ext.emptyFn;
  2681. return (object[methodName] = function() {
  2682. var ret = fn.apply(scope || this, arguments);
  2683. method.apply(this, arguments);
  2684. return ret;
  2685. });
  2686. },
  2687. /**
  2688. * Adds behavior to an existing method that is executed after the
  2689. * original behavior of the function. For example:
  2690. *
  2691. * var soup = {
  2692. * contents: [],
  2693. * add: function(ingredient) {
  2694. * this.contents.push(ingredient);
  2695. * }
  2696. * };
  2697. * Ext.Function.interceptAfter(soup, "add", function(ingredient){
  2698. * // Always add a bit of extra salt
  2699. * this.contents.push("salt");
  2700. * });
  2701. * soup.add("water");
  2702. * soup.add("onions");
  2703. * soup.contents; // will contain: water, salt, onions, salt
  2704. *
  2705. * @param {Object} object The target object
  2706. * @param {String} methodName Name of the method to override
  2707. * @param {Function} fn Function with the new behavior. It will
  2708. * be called with the same arguments as the original method. The
  2709. * return value of this function will be the return value of the
  2710. * new method.
  2711. * @param {Object} [scope] The scope to execute the interceptor function. Defaults to the object.
  2712. * @return {Function} The new function just created.
  2713. */
  2714. interceptAfter: function(object, methodName, fn, scope) {
  2715. var method = object[methodName] || Ext.emptyFn;
  2716. return (object[methodName] = function() {
  2717. method.apply(this, arguments);
  2718. return fn.apply(scope || this, arguments);
  2719. });
  2720. }
  2721. };
  2722. /**
  2723. * @method
  2724. * @member Ext
  2725. * @inheritdoc Ext.Function#defer
  2726. */
  2727. Ext.defer = Ext.Function.alias(Ext.Function, 'defer');
  2728. /**
  2729. * @method
  2730. * @member Ext
  2731. * @inheritdoc Ext.Function#pass
  2732. */
  2733. Ext.pass = Ext.Function.alias(Ext.Function, 'pass');
  2734. /**
  2735. * @method
  2736. * @member Ext
  2737. * @inheritdoc Ext.Function#bind
  2738. */
  2739. Ext.bind = Ext.Function.alias(Ext.Function, 'bind');
  2740. /**
  2741. * @author Jacky Nguyen <jacky@sencha.com>
  2742. * @docauthor Jacky Nguyen <jacky@sencha.com>
  2743. * @class Ext.Object
  2744. *
  2745. * A collection of useful static methods to deal with objects.
  2746. *
  2747. * @singleton
  2748. */
  2749. (function() {
  2750. // The "constructor" for chain:
  2751. var TemplateClass = function(){};
  2752. var ExtObject = Ext.Object = {
  2753. /**
  2754. * Returns a new object with the given object as the prototype chain.
  2755. * @param {Object} object The prototype chain for the new object.
  2756. */
  2757. chain: function (object) {
  2758. TemplateClass.prototype = object;
  2759. var result = new TemplateClass();
  2760. TemplateClass.prototype = null;
  2761. return result;
  2762. },
  2763. /**
  2764. * Converts a `name` - `value` pair to an array of objects with support for nested structures. Useful to construct
  2765. * query strings. For example:
  2766. *
  2767. * var objects = Ext.Object.toQueryObjects('hobbies', ['reading', 'cooking', 'swimming']);
  2768. *
  2769. * // objects then equals:
  2770. * [
  2771. * { name: 'hobbies', value: 'reading' },
  2772. * { name: 'hobbies', value: 'cooking' },
  2773. * { name: 'hobbies', value: 'swimming' },
  2774. * ];
  2775. *
  2776. * var objects = Ext.Object.toQueryObjects('dateOfBirth', {
  2777. * day: 3,
  2778. * month: 8,
  2779. * year: 1987,
  2780. * extra: {
  2781. * hour: 4
  2782. * minute: 30
  2783. * }
  2784. * }, true); // Recursive
  2785. *
  2786. * // objects then equals:
  2787. * [
  2788. * { name: 'dateOfBirth[day]', value: 3 },
  2789. * { name: 'dateOfBirth[month]', value: 8 },
  2790. * { name: 'dateOfBirth[year]', value: 1987 },
  2791. * { name: 'dateOfBirth[extra][hour]', value: 4 },
  2792. * { name: 'dateOfBirth[extra][minute]', value: 30 },
  2793. * ];
  2794. *
  2795. * @param {String} name
  2796. * @param {Object/Array} value
  2797. * @param {Boolean} [recursive=false] True to traverse object recursively
  2798. * @return {Array}
  2799. */
  2800. toQueryObjects: function(name, value, recursive) {
  2801. var self = ExtObject.toQueryObjects,
  2802. objects = [],
  2803. i, ln;
  2804. if (Ext.isArray(value)) {
  2805. for (i = 0, ln = value.length; i < ln; i++) {
  2806. if (recursive) {
  2807. objects = objects.concat(self(name + '[' + i + ']', value[i], true));
  2808. }
  2809. else {
  2810. objects.push({
  2811. name: name,
  2812. value: value[i]
  2813. });
  2814. }
  2815. }
  2816. }
  2817. else if (Ext.isObject(value)) {
  2818. for (i in value) {
  2819. if (value.hasOwnProperty(i)) {
  2820. if (recursive) {
  2821. objects = objects.concat(self(name + '[' + i + ']', value[i], true));
  2822. }
  2823. else {
  2824. objects.push({
  2825. name: name,
  2826. value: value[i]
  2827. });
  2828. }
  2829. }
  2830. }
  2831. }
  2832. else {
  2833. objects.push({
  2834. name: name,
  2835. value: value
  2836. });
  2837. }
  2838. return objects;
  2839. },
  2840. /**
  2841. * Takes an object and converts it to an encoded query string.
  2842. *
  2843. * Non-recursive:
  2844. *
  2845. * Ext.Object.toQueryString({foo: 1, bar: 2}); // returns "foo=1&bar=2"
  2846. * Ext.Object.toQueryString({foo: null, bar: 2}); // returns "foo=&bar=2"
  2847. * Ext.Object.toQueryString({'some price': '$300'}); // returns "some%20price=%24300"
  2848. * Ext.Object.toQueryString({date: new Date(2011, 0, 1)}); // returns "date=%222011-01-01T00%3A00%3A00%22"
  2849. * Ext.Object.toQueryString({colors: ['red', 'green', 'blue']}); // returns "colors=red&colors=green&colors=blue"
  2850. *
  2851. * Recursive:
  2852. *
  2853. * Ext.Object.toQueryString({
  2854. * username: 'Jacky',
  2855. * dateOfBirth: {
  2856. * day: 1,
  2857. * month: 2,
  2858. * year: 1911
  2859. * },
  2860. * hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']]
  2861. * }, true); // returns the following string (broken down and url-decoded for ease of reading purpose):
  2862. * // username=Jacky
  2863. * // &dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911
  2864. * // &hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&hobbies[3][0]=nested&hobbies[3][1]=stuff
  2865. *
  2866. * @param {Object} object The object to encode
  2867. * @param {Boolean} [recursive=false] Whether or not to interpret the object in recursive format.
  2868. * (PHP / Ruby on Rails servers and similar).
  2869. * @return {String} queryString
  2870. */
  2871. toQueryString: function(object, recursive) {
  2872. var paramObjects = [],
  2873. params = [],
  2874. i, j, ln, paramObject, value;
  2875. for (i in object) {
  2876. if (object.hasOwnProperty(i)) {
  2877. paramObjects = paramObjects.concat(ExtObject.toQueryObjects(i, object[i], recursive));
  2878. }
  2879. }
  2880. for (j = 0, ln = paramObjects.length; j < ln; j++) {
  2881. paramObject = paramObjects[j];
  2882. value = paramObject.value;
  2883. if (Ext.isEmpty(value)) {
  2884. value = '';
  2885. }
  2886. else if (Ext.isDate(value)) {
  2887. value = Ext.Date.toString(value);
  2888. }
  2889. params.push(encodeURIComponent(paramObject.name) + '=' + encodeURIComponent(String(value)));
  2890. }
  2891. return params.join('&');
  2892. },
  2893. /**
  2894. * Converts a query string back into an object.
  2895. *
  2896. * Non-recursive:
  2897. *
  2898. * Ext.Object.fromQueryString("foo=1&bar=2"); // returns {foo: 1, bar: 2}
  2899. * Ext.Object.fromQueryString("foo=&bar=2"); // returns {foo: null, bar: 2}
  2900. * Ext.Object.fromQueryString("some%20price=%24300"); // returns {'some price': '$300'}
  2901. * Ext.Object.fromQueryString("colors=red&colors=green&colors=blue"); // returns {colors: ['red', 'green', 'blue']}
  2902. *
  2903. * Recursive:
  2904. *
  2905. * Ext.Object.fromQueryString(
  2906. * "username=Jacky&"+
  2907. * "dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911&"+
  2908. * "hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&"+
  2909. * "hobbies[3][0]=nested&hobbies[3][1]=stuff", true);
  2910. *
  2911. * // returns
  2912. * {
  2913. * username: 'Jacky',
  2914. * dateOfBirth: {
  2915. * day: '1',
  2916. * month: '2',
  2917. * year: '1911'
  2918. * },
  2919. * hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']]
  2920. * }
  2921. *
  2922. * @param {String} queryString The query string to decode
  2923. * @param {Boolean} [recursive=false] Whether or not to recursively decode the string. This format is supported by
  2924. * PHP / Ruby on Rails servers and similar.
  2925. * @return {Object}
  2926. */
  2927. fromQueryString: function(queryString, recursive) {
  2928. var parts = queryString.replace(/^\?/, '').split('&'),
  2929. object = {},
  2930. temp, components, name, value, i, ln,
  2931. part, j, subLn, matchedKeys, matchedName,
  2932. keys, key, nextKey;
  2933. for (i = 0, ln = parts.length; i < ln; i++) {
  2934. part = parts[i];
  2935. if (part.length > 0) {
  2936. components = part.split('=');
  2937. name = decodeURIComponent(components[0]);
  2938. value = (components[1] !== undefined) ? decodeURIComponent(components[1]) : '';
  2939. if (!recursive) {
  2940. if (object.hasOwnProperty(name)) {
  2941. if (!Ext.isArray(object[name])) {
  2942. object[name] = [object[name]];
  2943. }
  2944. object[name].push(value);
  2945. }
  2946. else {
  2947. object[name] = value;
  2948. }
  2949. }
  2950. else {
  2951. matchedKeys = name.match(/(\[):?([^\]]*)\]/g);
  2952. matchedName = name.match(/^([^\[]+)/);
  2953. name = matchedName[0];
  2954. keys = [];
  2955. if (matchedKeys === null) {
  2956. object[name] = value;
  2957. continue;
  2958. }
  2959. for (j = 0, subLn = matchedKeys.length; j < subLn; j++) {
  2960. key = matchedKeys[j];
  2961. key = (key.length === 2) ? '' : key.substring(1, key.length - 1);
  2962. keys.push(key);
  2963. }
  2964. keys.unshift(name);
  2965. temp = object;
  2966. for (j = 0, subLn = keys.length; j < subLn; j++) {
  2967. key = keys[j];
  2968. if (j === subLn - 1) {
  2969. if (Ext.isArray(temp) && key === '') {
  2970. temp.push(value);
  2971. }
  2972. else {
  2973. temp[key] = value;
  2974. }
  2975. }
  2976. else {
  2977. if (temp[key] === undefined || typeof temp[key] === 'string') {
  2978. nextKey = keys[j+1];
  2979. temp[key] = (Ext.isNumeric(nextKey) || nextKey === '') ? [] : {};
  2980. }
  2981. temp = temp[key];
  2982. }
  2983. }
  2984. }
  2985. }
  2986. }
  2987. return object;
  2988. },
  2989. /**
  2990. * Iterates through an object and invokes the given callback function for each iteration.
  2991. * The iteration can be stopped by returning `false` in the callback function. For example:
  2992. *
  2993. * var person = {
  2994. * name: 'Jacky'
  2995. * hairColor: 'black'
  2996. * loves: ['food', 'sleeping', 'wife']
  2997. * };
  2998. *
  2999. * Ext.Object.each(person, function(key, value, myself) {
  3000. * console.log(key + ":" + value);
  3001. *
  3002. * if (key === 'hairColor') {
  3003. * return false; // stop the iteration
  3004. * }
  3005. * });
  3006. *
  3007. * @param {Object} object The object to iterate
  3008. * @param {Function} fn The callback function.
  3009. * @param {String} fn.key
  3010. * @param {Object} fn.value
  3011. * @param {Object} fn.object The object itself
  3012. * @param {Object} [scope] The execution scope (`this`) of the callback function
  3013. */
  3014. each: function(object, fn, scope) {
  3015. for (var property in object) {
  3016. if (object.hasOwnProperty(property)) {
  3017. if (fn.call(scope || object, property, object[property], object) === false) {
  3018. return;
  3019. }
  3020. }
  3021. }
  3022. },
  3023. /**
  3024. * Merges any number of objects recursively without referencing them or their children.
  3025. *
  3026. * var extjs = {
  3027. * companyName: 'Ext JS',
  3028. * products: ['Ext JS', 'Ext GWT', 'Ext Designer'],
  3029. * isSuperCool: true,
  3030. * office: {
  3031. * size: 2000,
  3032. * location: 'Palo Alto',
  3033. * isFun: true
  3034. * }
  3035. * };
  3036. *
  3037. * var newStuff = {
  3038. * companyName: 'Sencha Inc.',
  3039. * products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'],
  3040. * office: {
  3041. * size: 40000,
  3042. * location: 'Redwood City'
  3043. * }
  3044. * };
  3045. *
  3046. * var sencha = Ext.Object.merge(extjs, newStuff);
  3047. *
  3048. * // extjs and sencha then equals to
  3049. * {
  3050. * companyName: 'Sencha Inc.',
  3051. * products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'],
  3052. * isSuperCool: true,
  3053. * office: {
  3054. * size: 40000,
  3055. * location: 'Redwood City'
  3056. * isFun: true
  3057. * }
  3058. * }
  3059. *
  3060. * @param {Object...} object Any number of objects to merge.
  3061. * @return {Object} merged The object that is created as a result of merging all the objects passed in.
  3062. */
  3063. merge: function(source) {
  3064. var i = 1,
  3065. ln = arguments.length,
  3066. mergeFn = ExtObject.merge,
  3067. cloneFn = Ext.clone,
  3068. object, key, value, sourceKey;
  3069. for (; i < ln; i++) {
  3070. object = arguments[i];
  3071. for (key in object) {
  3072. value = object[key];
  3073. if (value && value.constructor === Object) {
  3074. sourceKey = source[key];
  3075. if (sourceKey && sourceKey.constructor === Object) {
  3076. mergeFn(sourceKey, value);
  3077. }
  3078. else {
  3079. source[key] = cloneFn(value);
  3080. }
  3081. }
  3082. else {
  3083. source[key] = value;
  3084. }
  3085. }
  3086. }
  3087. return source;
  3088. },
  3089. /**
  3090. * @private
  3091. * @param source
  3092. */
  3093. mergeIf: function(source) {
  3094. var i = 1,
  3095. ln = arguments.length,
  3096. cloneFn = Ext.clone,
  3097. object, key, value;
  3098. for (; i < ln; i++) {
  3099. object = arguments[i];
  3100. for (key in object) {
  3101. if (!(key in source)) {
  3102. value = object[key];
  3103. if (value && value.constructor === Object) {
  3104. source[key] = cloneFn(value);
  3105. }
  3106. else {
  3107. source[key] = value;
  3108. }
  3109. }
  3110. }
  3111. }
  3112. return source;
  3113. },
  3114. /**
  3115. * Returns the first matching key corresponding to the given value.
  3116. * If no matching value is found, null is returned.
  3117. *
  3118. * var person = {
  3119. * name: 'Jacky',
  3120. * loves: 'food'
  3121. * };
  3122. *
  3123. * alert(Ext.Object.getKey(person, 'food')); // alerts 'loves'
  3124. *
  3125. * @param {Object} object
  3126. * @param {Object} value The value to find
  3127. */
  3128. getKey: function(object, value) {
  3129. for (var property in object) {
  3130. if (object.hasOwnProperty(property) && object[property] === value) {
  3131. return property;
  3132. }
  3133. }
  3134. return null;
  3135. },
  3136. /**
  3137. * Gets all values of the given object as an array.
  3138. *
  3139. * var values = Ext.Object.getValues({
  3140. * name: 'Jacky',
  3141. * loves: 'food'
  3142. * }); // ['Jacky', 'food']
  3143. *
  3144. * @param {Object} object
  3145. * @return {Array} An array of values from the object
  3146. */
  3147. getValues: function(object) {
  3148. var values = [],
  3149. property;
  3150. for (property in object) {
  3151. if (object.hasOwnProperty(property)) {
  3152. values.push(object[property]);
  3153. }
  3154. }
  3155. return values;
  3156. },
  3157. /**
  3158. * Gets all keys of the given object as an array.
  3159. *
  3160. * var values = Ext.Object.getKeys({
  3161. * name: 'Jacky',
  3162. * loves: 'food'
  3163. * }); // ['name', 'loves']
  3164. *
  3165. * @param {Object} object
  3166. * @return {String[]} An array of keys from the object
  3167. * @method
  3168. */
  3169. getKeys: (typeof Object.keys == 'function')
  3170. ? function(object){
  3171. if (!object) {
  3172. return [];
  3173. }
  3174. return Object.keys(object);
  3175. }
  3176. : function(object) {
  3177. var keys = [],
  3178. property;
  3179. for (property in object) {
  3180. if (object.hasOwnProperty(property)) {
  3181. keys.push(property);
  3182. }
  3183. }
  3184. return keys;
  3185. },
  3186. /**
  3187. * Gets the total number of this object's own properties
  3188. *
  3189. * var size = Ext.Object.getSize({
  3190. * name: 'Jacky',
  3191. * loves: 'food'
  3192. * }); // size equals 2
  3193. *
  3194. * @param {Object} object
  3195. * @return {Number} size
  3196. */
  3197. getSize: function(object) {
  3198. var size = 0,
  3199. property;
  3200. for (property in object) {
  3201. if (object.hasOwnProperty(property)) {
  3202. size++;
  3203. }
  3204. }
  3205. return size;
  3206. },
  3207. /**
  3208. * @private
  3209. */
  3210. classify: function(object) {
  3211. var prototype = object,
  3212. objectProperties = [],
  3213. propertyClassesMap = {},
  3214. objectClass = function() {
  3215. var i = 0,
  3216. ln = objectProperties.length,
  3217. property;
  3218. for (; i < ln; i++) {
  3219. property = objectProperties[i];
  3220. this[property] = new propertyClassesMap[property];
  3221. }
  3222. },
  3223. key, value;
  3224. for (key in object) {
  3225. if (object.hasOwnProperty(key)) {
  3226. value = object[key];
  3227. if (value && value.constructor === Object) {
  3228. objectProperties.push(key);
  3229. propertyClassesMap[key] = ExtObject.classify(value);
  3230. }
  3231. }
  3232. }
  3233. objectClass.prototype = prototype;
  3234. return objectClass;
  3235. }
  3236. };
  3237. /**
  3238. * A convenient alias method for {@link Ext.Object#merge}.
  3239. *
  3240. * @member Ext
  3241. * @method merge
  3242. * @inheritdoc Ext.Object#merge
  3243. */
  3244. Ext.merge = Ext.Object.merge;
  3245. /**
  3246. * @private
  3247. */
  3248. Ext.mergeIf = Ext.Object.mergeIf;
  3249. /**
  3250. *
  3251. * @member Ext
  3252. * @method urlEncode
  3253. * @inheritdoc Ext.Object#toQueryString
  3254. * @deprecated 4.0.0 Use {@link Ext.Object#toQueryString} instead
  3255. */
  3256. Ext.urlEncode = function() {
  3257. var args = Ext.Array.from(arguments),
  3258. prefix = '';
  3259. // Support for the old `pre` argument
  3260. if ((typeof args[1] === 'string')) {
  3261. prefix = args[1] + '&';
  3262. args[1] = false;
  3263. }
  3264. return prefix + ExtObject.toQueryString.apply(ExtObject, args);
  3265. };
  3266. /**
  3267. * Alias for {@link Ext.Object#fromQueryString}.
  3268. *
  3269. * @member Ext
  3270. * @method urlDecode
  3271. * @inheritdoc Ext.Object#fromQueryString
  3272. * @deprecated 4.0.0 Use {@link Ext.Object#fromQueryString} instead
  3273. */
  3274. Ext.urlDecode = function() {
  3275. return ExtObject.fromQueryString.apply(ExtObject, arguments);
  3276. };
  3277. })();
  3278. //<localeInfo useApply="true" />
  3279. /**
  3280. * @class Ext.Date
  3281. * A set of useful static methods to deal with date
  3282. * Note that if Ext.Date is required and loaded, it will copy all methods / properties to
  3283. * this object for convenience
  3284. *
  3285. * The date parsing and formatting syntax contains a subset of
  3286. * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
  3287. * supported will provide results equivalent to their PHP versions.
  3288. *
  3289. * The following is a list of all currently supported formats:
  3290. * <pre class="">
  3291. Format Description Example returned values
  3292. ------ ----------------------------------------------------------------------- -----------------------
  3293. d Day of the month, 2 digits with leading zeros 01 to 31
  3294. D A short textual representation of the day of the week Mon to Sun
  3295. j Day of the month without leading zeros 1 to 31
  3296. l A full textual representation of the day of the week Sunday to Saturday
  3297. N ISO-8601 numeric representation of the day of the week 1 (for Monday) through 7 (for Sunday)
  3298. S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
  3299. w Numeric representation of the day of the week 0 (for Sunday) to 6 (for Saturday)
  3300. z The day of the year (starting from 0) 0 to 364 (365 in leap years)
  3301. W ISO-8601 week number of year, weeks starting on Monday 01 to 53
  3302. F A full textual representation of a month, such as January or March January to December
  3303. m Numeric representation of a month, with leading zeros 01 to 12
  3304. M A short textual representation of a month Jan to Dec
  3305. n Numeric representation of a month, without leading zeros 1 to 12
  3306. t Number of days in the given month 28 to 31
  3307. L Whether it&#39;s a leap year 1 if it is a leap year, 0 otherwise.
  3308. o ISO-8601 year number (identical to (Y), but if the ISO week number (W) Examples: 1998 or 2004
  3309. belongs to the previous or next year, that year is used instead)
  3310. Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
  3311. y A two digit representation of a year Examples: 99 or 03
  3312. a Lowercase Ante meridiem and Post meridiem am or pm
  3313. A Uppercase Ante meridiem and Post meridiem AM or PM
  3314. g 12-hour format of an hour without leading zeros 1 to 12
  3315. G 24-hour format of an hour without leading zeros 0 to 23
  3316. h 12-hour format of an hour with leading zeros 01 to 12
  3317. H 24-hour format of an hour with leading zeros 00 to 23
  3318. i Minutes, with leading zeros 00 to 59
  3319. s Seconds, with leading zeros 00 to 59
  3320. u Decimal fraction of a second Examples:
  3321. (minimum 1 digit, arbitrary number of digits allowed) 001 (i.e. 0.001s) or
  3322. 100 (i.e. 0.100s) or
  3323. 999 (i.e. 0.999s) or
  3324. 999876543210 (i.e. 0.999876543210s)
  3325. O Difference to Greenwich time (GMT) in hours and minutes Example: +1030
  3326. P Difference to Greenwich time (GMT) with colon between hours and minutes Example: -08:00
  3327. T Timezone abbreviation of the machine running the code Examples: EST, MDT, PDT ...
  3328. Z Timezone offset in seconds (negative if west of UTC, positive if east) -43200 to 50400
  3329. c ISO 8601 date
  3330. Notes: Examples:
  3331. 1) If unspecified, the month / day defaults to the current month / day, 1991 or
  3332. the time defaults to midnight, while the timezone defaults to the 1992-10 or
  3333. browser's timezone. If a time is specified, it must include both hours 1993-09-20 or
  3334. and minutes. The "T" delimiter, seconds, milliseconds and timezone 1994-08-19T16:20+01:00 or
  3335. are optional. 1995-07-18T17:21:28-02:00 or
  3336. 2) The decimal fraction of a second, if specified, must contain at 1996-06-17T18:22:29.98765+03:00 or
  3337. least 1 digit (there is no limit to the maximum number 1997-05-16T19:23:30,12345-0400 or
  3338. of digits allowed), and may be delimited by either a '.' or a ',' 1998-04-15T20:24:31.2468Z or
  3339. Refer to the examples on the right for the various levels of 1999-03-14T20:24:32Z or
  3340. date-time granularity which are supported, or see 2000-02-13T21:25:33
  3341. http://www.w3.org/TR/NOTE-datetime for more info. 2001-01-12 22:26:34
  3342. U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) 1193432466 or -2138434463
  3343. MS Microsoft AJAX serialized dates \/Date(1238606590509)\/ (i.e. UTC milliseconds since epoch) or
  3344. \/Date(1238606590509+0800)\/
  3345. </pre>
  3346. *
  3347. * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
  3348. * <pre><code>
  3349. // Sample date:
  3350. // 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
  3351. var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
  3352. console.log(Ext.Date.format(dt, 'Y-m-d')); // 2007-01-10
  3353. console.log(Ext.Date.format(dt, 'F j, Y, g:i a')); // January 10, 2007, 3:05 pm
  3354. 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
  3355. </code></pre>
  3356. *
  3357. * Here are some standard date/time patterns that you might find helpful. They
  3358. * are not part of the source of Ext.Date, but to use them you can simply copy this
  3359. * block of code into any script that is included after Ext.Date and they will also become
  3360. * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
  3361. * <pre><code>
  3362. Ext.Date.patterns = {
  3363. ISO8601Long:"Y-m-d H:i:s",
  3364. ISO8601Short:"Y-m-d",
  3365. ShortDate: "n/j/Y",
  3366. LongDate: "l, F d, Y",
  3367. FullDateTime: "l, F d, Y g:i:s A",
  3368. MonthDay: "F d",
  3369. ShortTime: "g:i A",
  3370. LongTime: "g:i:s A",
  3371. SortableDateTime: "Y-m-d\\TH:i:s",
  3372. UniversalSortableDateTime: "Y-m-d H:i:sO",
  3373. YearMonth: "F, Y"
  3374. };
  3375. </code></pre>
  3376. *
  3377. * Example usage:
  3378. * <pre><code>
  3379. var dt = new Date();
  3380. console.log(Ext.Date.format(dt, Ext.Date.patterns.ShortDate));
  3381. </code></pre>
  3382. * <p>Developer-written, custom formats may be used by supplying both a formatting and a parsing function
  3383. * which perform to specialized requirements. The functions are stored in {@link #parseFunctions} and {@link #formatFunctions}.</p>
  3384. * @singleton
  3385. */
  3386. /*
  3387. * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
  3388. * (see http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/)
  3389. * They generate precompiled functions from format patterns instead of parsing and
  3390. * processing each pattern every time a date is formatted. These functions are available
  3391. * on every Date object.
  3392. */
  3393. (function() {
  3394. // create private copy of Ext's Ext.util.Format.format() method
  3395. // - to remove unnecessary dependency
  3396. // - to resolve namespace conflict with MS-Ajax's implementation
  3397. function xf(format) {
  3398. var args = Array.prototype.slice.call(arguments, 1);
  3399. return format.replace(/\{(\d+)\}/g, function(m, i) {
  3400. return args[i];
  3401. });
  3402. }
  3403. Ext.Date = {
  3404. /**
  3405. * Returns the current timestamp
  3406. * @return {Number} The current timestamp
  3407. * @method
  3408. */
  3409. now: Date.now || function() {
  3410. return +new Date();
  3411. },
  3412. /**
  3413. * @private
  3414. * Private for now
  3415. */
  3416. toString: function(date) {
  3417. var pad = Ext.String.leftPad;
  3418. return date.getFullYear() + "-"
  3419. + pad(date.getMonth() + 1, 2, '0') + "-"
  3420. + pad(date.getDate(), 2, '0') + "T"
  3421. + pad(date.getHours(), 2, '0') + ":"
  3422. + pad(date.getMinutes(), 2, '0') + ":"
  3423. + pad(date.getSeconds(), 2, '0');
  3424. },
  3425. /**
  3426. * Returns the number of milliseconds between two dates
  3427. * @param {Date} dateA The first date
  3428. * @param {Date} dateB (optional) The second date, defaults to now
  3429. * @return {Number} The difference in milliseconds
  3430. */
  3431. getElapsed: function(dateA, dateB) {
  3432. return Math.abs(dateA - (dateB || new Date()));
  3433. },
  3434. /**
  3435. * Global flag which determines if strict date parsing should be used.
  3436. * Strict date parsing will not roll-over invalid dates, which is the
  3437. * default behaviour of javascript Date objects.
  3438. * (see {@link #parse} for more information)
  3439. * Defaults to <tt>false</tt>.
  3440. * @type Boolean
  3441. */
  3442. useStrict: false,
  3443. // private
  3444. formatCodeToRegex: function(character, currentGroup) {
  3445. // Note: currentGroup - position in regex result array (see notes for Ext.Date.parseCodes below)
  3446. var p = utilDate.parseCodes[character];
  3447. if (p) {
  3448. p = typeof p == 'function'? p() : p;
  3449. utilDate.parseCodes[character] = p; // reassign function result to prevent repeated execution
  3450. }
  3451. return p ? Ext.applyIf({
  3452. c: p.c ? xf(p.c, currentGroup || "{0}") : p.c
  3453. }, p) : {
  3454. g: 0,
  3455. c: null,
  3456. s: Ext.String.escapeRegex(character) // treat unrecognised characters as literals
  3457. };
  3458. },
  3459. /**
  3460. * <p>An object hash in which each property is a date parsing function. The property name is the
  3461. * format string which that function parses.</p>
  3462. * <p>This object is automatically populated with date parsing functions as
  3463. * date formats are requested for Ext standard formatting strings.</p>
  3464. * <p>Custom parsing functions may be inserted into this object, keyed by a name which from then on
  3465. * may be used as a format string to {@link #parse}.<p>
  3466. * <p>Example:</p><pre><code>
  3467. Ext.Date.parseFunctions['x-date-format'] = myDateParser;
  3468. </code></pre>
  3469. * <p>A parsing function should return a Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
  3470. * <li><code>date</code> : String<div class="sub-desc">The date string to parse.</div></li>
  3471. * <li><code>strict</code> : Boolean<div class="sub-desc">True to validate date strings while parsing
  3472. * (i.e. prevent javascript Date "rollover") (The default must be false).
  3473. * Invalid date strings should return null when parsed.</div></li>
  3474. * </ul></div></p>
  3475. * <p>To enable Dates to also be <i>formatted</i> according to that format, a corresponding
  3476. * formatting function must be placed into the {@link #formatFunctions} property.
  3477. * @property parseFunctions
  3478. * @type Object
  3479. */
  3480. parseFunctions: {
  3481. "MS": function(input, strict) {
  3482. // note: the timezone offset is ignored since the MS Ajax server sends
  3483. // a UTC milliseconds-since-Unix-epoch value (negative values are allowed)
  3484. var re = new RegExp('\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/');
  3485. var r = (input || '').match(re);
  3486. return r? new Date(((r[1] || '') + r[2]) * 1) : null;
  3487. }
  3488. },
  3489. parseRegexes: [],
  3490. /**
  3491. * <p>An object hash in which each property is a date formatting function. The property name is the
  3492. * format string which corresponds to the produced formatted date string.</p>
  3493. * <p>This object is automatically populated with date formatting functions as
  3494. * date formats are requested for Ext standard formatting strings.</p>
  3495. * <p>Custom formatting functions may be inserted into this object, keyed by a name which from then on
  3496. * may be used as a format string to {@link #format}. Example:</p><pre><code>
  3497. Ext.Date.formatFunctions['x-date-format'] = myDateFormatter;
  3498. </code></pre>
  3499. * <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>
  3500. * <li><code>date</code> : Date<div class="sub-desc">The Date to format.</div></li>
  3501. * </ul></div></p>
  3502. * <p>To enable date strings to also be <i>parsed</i> according to that format, a corresponding
  3503. * parsing function must be placed into the {@link #parseFunctions} property.
  3504. * @property formatFunctions
  3505. * @type Object
  3506. */
  3507. formatFunctions: {
  3508. "MS": function() {
  3509. // UTC milliseconds since Unix epoch (MS-AJAX serialized date format (MRSF))
  3510. return '\\/Date(' + this.getTime() + ')\\/';
  3511. }
  3512. },
  3513. y2kYear : 50,
  3514. /**
  3515. * Date interval constant
  3516. * @type String
  3517. */
  3518. MILLI : "ms",
  3519. /**
  3520. * Date interval constant
  3521. * @type String
  3522. */
  3523. SECOND : "s",
  3524. /**
  3525. * Date interval constant
  3526. * @type String
  3527. */
  3528. MINUTE : "mi",
  3529. /** Date interval constant
  3530. * @type String
  3531. */
  3532. HOUR : "h",
  3533. /**
  3534. * Date interval constant
  3535. * @type String
  3536. */
  3537. DAY : "d",
  3538. /**
  3539. * Date interval constant
  3540. * @type String
  3541. */
  3542. MONTH : "mo",
  3543. /**
  3544. * Date interval constant
  3545. * @type String
  3546. */
  3547. YEAR : "y",
  3548. /**
  3549. * <p>An object hash containing default date values used during date parsing.</p>
  3550. * <p>The following properties are available:<div class="mdetail-params"><ul>
  3551. * <li><code>y</code> : Number<div class="sub-desc">The default year value. (defaults to undefined)</div></li>
  3552. * <li><code>m</code> : Number<div class="sub-desc">The default 1-based month value. (defaults to undefined)</div></li>
  3553. * <li><code>d</code> : Number<div class="sub-desc">The default day value. (defaults to undefined)</div></li>
  3554. * <li><code>h</code> : Number<div class="sub-desc">The default hour value. (defaults to undefined)</div></li>
  3555. * <li><code>i</code> : Number<div class="sub-desc">The default minute value. (defaults to undefined)</div></li>
  3556. * <li><code>s</code> : Number<div class="sub-desc">The default second value. (defaults to undefined)</div></li>
  3557. * <li><code>ms</code> : Number<div class="sub-desc">The default millisecond value. (defaults to undefined)</div></li>
  3558. * </ul></div></p>
  3559. * <p>Override these properties to customize the default date values used by the {@link #parse} method.</p>
  3560. * <p><b>Note: In countries which experience Daylight Saving Time (i.e. DST), the <tt>h</tt>, <tt>i</tt>, <tt>s</tt>
  3561. * and <tt>ms</tt> properties may coincide with the exact time in which DST takes effect.
  3562. * It is the responsiblity of the developer to account for this.</b></p>
  3563. * Example Usage:
  3564. * <pre><code>
  3565. // set default day value to the first day of the month
  3566. Ext.Date.defaults.d = 1;
  3567. // parse a February date string containing only year and month values.
  3568. // setting the default day value to 1 prevents weird date rollover issues
  3569. // when attempting to parse the following date string on, for example, March 31st 2009.
  3570. Ext.Date.parse('2009-02', 'Y-m'); // returns a Date object representing February 1st 2009
  3571. </code></pre>
  3572. * @property defaults
  3573. * @type Object
  3574. */
  3575. defaults: {},
  3576. /**
  3577. * @property {String[]} dayNames
  3578. * An array of textual day names.
  3579. * Override these values for international dates.
  3580. * Example:
  3581. * <pre><code>
  3582. Ext.Date.dayNames = [
  3583. 'SundayInYourLang',
  3584. 'MondayInYourLang',
  3585. ...
  3586. ];
  3587. </code></pre>
  3588. */
  3589. //<locale type="array">
  3590. dayNames : [
  3591. "Sunday",
  3592. "Monday",
  3593. "Tuesday",
  3594. "Wednesday",
  3595. "Thursday",
  3596. "Friday",
  3597. "Saturday"
  3598. ],
  3599. //</locale>
  3600. /**
  3601. * @property {String[]} monthNames
  3602. * An array of textual month names.
  3603. * Override these values for international dates.
  3604. * Example:
  3605. * <pre><code>
  3606. Ext.Date.monthNames = [
  3607. 'JanInYourLang',
  3608. 'FebInYourLang',
  3609. ...
  3610. ];
  3611. </code></pre>
  3612. */
  3613. //<locale type="array">
  3614. monthNames : [
  3615. "January",
  3616. "February",
  3617. "March",
  3618. "April",
  3619. "May",
  3620. "June",
  3621. "July",
  3622. "August",
  3623. "September",
  3624. "October",
  3625. "November",
  3626. "December"
  3627. ],
  3628. //</locale>
  3629. /**
  3630. * @property {Object} monthNumbers
  3631. * An object hash of zero-based javascript month numbers (with short month names as keys. note: keys are case-sensitive).
  3632. * Override these values for international dates.
  3633. * Example:
  3634. * <pre><code>
  3635. Ext.Date.monthNumbers = {
  3636. 'ShortJanNameInYourLang':0,
  3637. 'ShortFebNameInYourLang':1,
  3638. ...
  3639. };
  3640. </code></pre>
  3641. */
  3642. //<locale type="object">
  3643. monthNumbers : {
  3644. Jan:0,
  3645. Feb:1,
  3646. Mar:2,
  3647. Apr:3,
  3648. May:4,
  3649. Jun:5,
  3650. Jul:6,
  3651. Aug:7,
  3652. Sep:8,
  3653. Oct:9,
  3654. Nov:10,
  3655. Dec:11
  3656. },
  3657. //</locale>
  3658. /**
  3659. * @property {String} defaultFormat
  3660. * <p>The date format string that the {@link Ext.util.Format#dateRenderer}
  3661. * and {@link Ext.util.Format#date} functions use. See {@link Ext.Date} for details.</p>
  3662. * <p>This may be overridden in a locale file.</p>
  3663. */
  3664. //<locale>
  3665. defaultFormat : "m/d/Y",
  3666. //</locale>
  3667. /**
  3668. * Get the short month name for the given month number.
  3669. * Override this function for international dates.
  3670. * @param {Number} month A zero-based javascript month number.
  3671. * @return {String} The short month name.
  3672. */
  3673. //<locale type="function">
  3674. getShortMonthName : function(month) {
  3675. return Ext.Date.monthNames[month].substring(0, 3);
  3676. },
  3677. //</locale>
  3678. /**
  3679. * Get the short day name for the given day number.
  3680. * Override this function for international dates.
  3681. * @param {Number} day A zero-based javascript day number.
  3682. * @return {String} The short day name.
  3683. */
  3684. //<locale type="function">
  3685. getShortDayName : function(day) {
  3686. return Ext.Date.dayNames[day].substring(0, 3);
  3687. },
  3688. //</locale>
  3689. /**
  3690. * Get the zero-based javascript month number for the given short/full month name.
  3691. * Override this function for international dates.
  3692. * @param {String} name The short/full month name.
  3693. * @return {Number} The zero-based javascript month number.
  3694. */
  3695. //<locale type="function">
  3696. getMonthNumber : function(name) {
  3697. // handle camel casing for english month names (since the keys for the Ext.Date.monthNumbers hash are case sensitive)
  3698. return Ext.Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()];
  3699. },
  3700. //</locale>
  3701. /**
  3702. * Checks if the specified format contains hour information
  3703. * @param {String} format The format to check
  3704. * @return {Boolean} True if the format contains hour information
  3705. * @method
  3706. */
  3707. formatContainsHourInfo : (function(){
  3708. var stripEscapeRe = /(\\.)/g,
  3709. hourInfoRe = /([gGhHisucUOPZ]|MS)/;
  3710. return function(format){
  3711. return hourInfoRe.test(format.replace(stripEscapeRe, ''));
  3712. };
  3713. })(),
  3714. /**
  3715. * Checks if the specified format contains information about
  3716. * anything other than the time.
  3717. * @param {String} format The format to check
  3718. * @return {Boolean} True if the format contains information about
  3719. * date/day information.
  3720. * @method
  3721. */
  3722. formatContainsDateInfo : (function(){
  3723. var stripEscapeRe = /(\\.)/g,
  3724. dateInfoRe = /([djzmnYycU]|MS)/;
  3725. return function(format){
  3726. return dateInfoRe.test(format.replace(stripEscapeRe, ''));
  3727. };
  3728. })(),
  3729. /**
  3730. * The base format-code to formatting-function hashmap used by the {@link #format} method.
  3731. * Formatting functions are strings (or functions which return strings) which
  3732. * will return the appropriate value when evaluated in the context of the Date object
  3733. * from which the {@link #format} method is called.
  3734. * Add to / override these mappings for custom date formatting.
  3735. * Note: Ext.Date.format() treats characters as literals if an appropriate mapping cannot be found.
  3736. * Example:
  3737. * <pre><code>
  3738. Ext.Date.formatCodes.x = "Ext.util.Format.leftPad(this.getDate(), 2, '0')";
  3739. console.log(Ext.Date.format(new Date(), 'X'); // returns the current day of the month
  3740. </code></pre>
  3741. * @type Object
  3742. */
  3743. formatCodes : {
  3744. d: "Ext.String.leftPad(this.getDate(), 2, '0')",
  3745. D: "Ext.Date.getShortDayName(this.getDay())", // get localised short day name
  3746. j: "this.getDate()",
  3747. l: "Ext.Date.dayNames[this.getDay()]",
  3748. N: "(this.getDay() ? this.getDay() : 7)",
  3749. S: "Ext.Date.getSuffix(this)",
  3750. w: "this.getDay()",
  3751. z: "Ext.Date.getDayOfYear(this)",
  3752. W: "Ext.String.leftPad(Ext.Date.getWeekOfYear(this), 2, '0')",
  3753. F: "Ext.Date.monthNames[this.getMonth()]",
  3754. m: "Ext.String.leftPad(this.getMonth() + 1, 2, '0')",
  3755. M: "Ext.Date.getShortMonthName(this.getMonth())", // get localised short month name
  3756. n: "(this.getMonth() + 1)",
  3757. t: "Ext.Date.getDaysInMonth(this)",
  3758. L: "(Ext.Date.isLeapYear(this) ? 1 : 0)",
  3759. o: "(this.getFullYear() + (Ext.Date.getWeekOfYear(this) == 1 && this.getMonth() > 0 ? +1 : (Ext.Date.getWeekOfYear(this) >= 52 && this.getMonth() < 11 ? -1 : 0)))",
  3760. Y: "Ext.String.leftPad(this.getFullYear(), 4, '0')",
  3761. y: "('' + this.getFullYear()).substring(2, 4)",
  3762. a: "(this.getHours() < 12 ? 'am' : 'pm')",
  3763. A: "(this.getHours() < 12 ? 'AM' : 'PM')",
  3764. g: "((this.getHours() % 12) ? this.getHours() % 12 : 12)",
  3765. G: "this.getHours()",
  3766. h: "Ext.String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')",
  3767. H: "Ext.String.leftPad(this.getHours(), 2, '0')",
  3768. i: "Ext.String.leftPad(this.getMinutes(), 2, '0')",
  3769. s: "Ext.String.leftPad(this.getSeconds(), 2, '0')",
  3770. u: "Ext.String.leftPad(this.getMilliseconds(), 3, '0')",
  3771. O: "Ext.Date.getGMTOffset(this)",
  3772. P: "Ext.Date.getGMTOffset(this, true)",
  3773. T: "Ext.Date.getTimezone(this)",
  3774. Z: "(this.getTimezoneOffset() * -60)",
  3775. c: function() { // ISO-8601 -- GMT format
  3776. for (var c = "Y-m-dTH:i:sP", code = [], i = 0, l = c.length; i < l; ++i) {
  3777. var e = c.charAt(i);
  3778. code.push(e == "T" ? "'T'" : utilDate.getFormatCode(e)); // treat T as a character literal
  3779. }
  3780. return code.join(" + ");
  3781. },
  3782. /*
  3783. c: function() { // ISO-8601 -- UTC format
  3784. return [
  3785. "this.getUTCFullYear()", "'-'",
  3786. "Ext.util.Format.leftPad(this.getUTCMonth() + 1, 2, '0')", "'-'",
  3787. "Ext.util.Format.leftPad(this.getUTCDate(), 2, '0')",
  3788. "'T'",
  3789. "Ext.util.Format.leftPad(this.getUTCHours(), 2, '0')", "':'",
  3790. "Ext.util.Format.leftPad(this.getUTCMinutes(), 2, '0')", "':'",
  3791. "Ext.util.Format.leftPad(this.getUTCSeconds(), 2, '0')",
  3792. "'Z'"
  3793. ].join(" + ");
  3794. },
  3795. */
  3796. U: "Math.round(this.getTime() / 1000)"
  3797. },
  3798. /**
  3799. * Checks if the passed Date parameters will cause a javascript Date "rollover".
  3800. * @param {Number} year 4-digit year
  3801. * @param {Number} month 1-based month-of-year
  3802. * @param {Number} day Day of month
  3803. * @param {Number} hour (optional) Hour
  3804. * @param {Number} minute (optional) Minute
  3805. * @param {Number} second (optional) Second
  3806. * @param {Number} millisecond (optional) Millisecond
  3807. * @return {Boolean} true if the passed parameters do not cause a Date "rollover", false otherwise.
  3808. */
  3809. isValid : function(y, m, d, h, i, s, ms) {
  3810. // setup defaults
  3811. h = h || 0;
  3812. i = i || 0;
  3813. s = s || 0;
  3814. ms = ms || 0;
  3815. // Special handling for year < 100
  3816. var dt = utilDate.add(new Date(y < 100 ? 100 : y, m - 1, d, h, i, s, ms), utilDate.YEAR, y < 100 ? y - 100 : 0);
  3817. return y == dt.getFullYear() &&
  3818. m == dt.getMonth() + 1 &&
  3819. d == dt.getDate() &&
  3820. h == dt.getHours() &&
  3821. i == dt.getMinutes() &&
  3822. s == dt.getSeconds() &&
  3823. ms == dt.getMilliseconds();
  3824. },
  3825. /**
  3826. * Parses the passed string using the specified date format.
  3827. * Note that this function expects normal calendar dates, meaning that months are 1-based (i.e. 1 = January).
  3828. * The {@link #defaults} hash will be used for any date value (i.e. year, month, day, hour, minute, second or millisecond)
  3829. * which cannot be found in the passed string. If a corresponding default date value has not been specified in the {@link #defaults} hash,
  3830. * the current date's year, month, day or DST-adjusted zero-hour time value will be used instead.
  3831. * Keep in mind that the input date string must precisely match the specified format string
  3832. * in order for the parse operation to be successful (failed parse operations return a null value).
  3833. * <p>Example:</p><pre><code>
  3834. //dt = Fri May 25 2007 (current date)
  3835. var dt = new Date();
  3836. //dt = Thu May 25 2006 (today&#39;s month/day in 2006)
  3837. dt = Ext.Date.parse("2006", "Y");
  3838. //dt = Sun Jan 15 2006 (all date parts specified)
  3839. dt = Ext.Date.parse("2006-01-15", "Y-m-d");
  3840. //dt = Sun Jan 15 2006 15:20:01
  3841. dt = Ext.Date.parse("2006-01-15 3:20:01 PM", "Y-m-d g:i:s A");
  3842. // attempt to parse Sun Feb 29 2006 03:20:01 in strict mode
  3843. dt = Ext.Date.parse("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
  3844. </code></pre>
  3845. * @param {String} input The raw date string.
  3846. * @param {String} format The expected date string format.
  3847. * @param {Boolean} strict (optional) True to validate date strings while parsing (i.e. prevents javascript Date "rollover")
  3848. (defaults to false). Invalid date strings will return null when parsed.
  3849. * @return {Date} The parsed Date.
  3850. */
  3851. parse : function(input, format, strict) {
  3852. var p = utilDate.parseFunctions;
  3853. if (p[format] == null) {
  3854. utilDate.createParser(format);
  3855. }
  3856. return p[format](input, Ext.isDefined(strict) ? strict : utilDate.useStrict);
  3857. },
  3858. // Backwards compat
  3859. parseDate: function(input, format, strict){
  3860. return utilDate.parse(input, format, strict);
  3861. },
  3862. // private
  3863. getFormatCode : function(character) {
  3864. var f = utilDate.formatCodes[character];
  3865. if (f) {
  3866. f = typeof f == 'function'? f() : f;
  3867. utilDate.formatCodes[character] = f; // reassign function result to prevent repeated execution
  3868. }
  3869. // note: unknown characters are treated as literals
  3870. return f || ("'" + Ext.String.escape(character) + "'");
  3871. },
  3872. // private
  3873. createFormat : function(format) {
  3874. var code = [],
  3875. special = false,
  3876. ch = '';
  3877. for (var i = 0; i < format.length; ++i) {
  3878. ch = format.charAt(i);
  3879. if (!special && ch == "\\") {
  3880. special = true;
  3881. } else if (special) {
  3882. special = false;
  3883. code.push("'" + Ext.String.escape(ch) + "'");
  3884. } else {
  3885. code.push(utilDate.getFormatCode(ch));
  3886. }
  3887. }
  3888. utilDate.formatFunctions[format] = Ext.functionFactory("return " + code.join('+'));
  3889. },
  3890. // private
  3891. createParser : (function() {
  3892. var code = [
  3893. "var dt, y, m, d, h, i, s, ms, o, z, zz, u, v,",
  3894. "def = Ext.Date.defaults,",
  3895. "results = String(input).match(Ext.Date.parseRegexes[{0}]);", // either null, or an array of matched strings
  3896. "if(results){",
  3897. "{1}",
  3898. "if(u != null){", // i.e. unix time is defined
  3899. "v = new Date(u * 1000);", // give top priority to UNIX time
  3900. "}else{",
  3901. // create Date object representing midnight of the current day;
  3902. // this will provide us with our date defaults
  3903. // (note: clearTime() handles Daylight Saving Time automatically)
  3904. "dt = Ext.Date.clearTime(new Date);",
  3905. // date calculations (note: these calculations create a dependency on Ext.Number.from())
  3906. "y = Ext.Number.from(y, Ext.Number.from(def.y, dt.getFullYear()));",
  3907. "m = Ext.Number.from(m, Ext.Number.from(def.m - 1, dt.getMonth()));",
  3908. "d = Ext.Number.from(d, Ext.Number.from(def.d, dt.getDate()));",
  3909. // time calculations (note: these calculations create a dependency on Ext.Number.from())
  3910. "h = Ext.Number.from(h, Ext.Number.from(def.h, dt.getHours()));",
  3911. "i = Ext.Number.from(i, Ext.Number.from(def.i, dt.getMinutes()));",
  3912. "s = Ext.Number.from(s, Ext.Number.from(def.s, dt.getSeconds()));",
  3913. "ms = Ext.Number.from(ms, Ext.Number.from(def.ms, dt.getMilliseconds()));",
  3914. "if(z >= 0 && y >= 0){",
  3915. // both the year and zero-based day of year are defined and >= 0.
  3916. // these 2 values alone provide sufficient info to create a full date object
  3917. // create Date object representing January 1st for the given year
  3918. // handle years < 100 appropriately
  3919. "v = Ext.Date.add(new Date(y < 100 ? 100 : y, 0, 1, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
  3920. // then add day of year, checking for Date "rollover" if necessary
  3921. "v = !strict? v : (strict === true && (z <= 364 || (Ext.Date.isLeapYear(v) && z <= 365))? Ext.Date.add(v, Ext.Date.DAY, z) : null);",
  3922. "}else if(strict === true && !Ext.Date.isValid(y, m + 1, d, h, i, s, ms)){", // check for Date "rollover"
  3923. "v = null;", // invalid date, so return null
  3924. "}else{",
  3925. // plain old Date object
  3926. // handle years < 100 properly
  3927. "v = Ext.Date.add(new Date(y < 100 ? 100 : y, m, d, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
  3928. "}",
  3929. "}",
  3930. "}",
  3931. "if(v){",
  3932. // favour UTC offset over GMT offset
  3933. "if(zz != null){",
  3934. // reset to UTC, then add offset
  3935. "v = Ext.Date.add(v, Ext.Date.SECOND, -v.getTimezoneOffset() * 60 - zz);",
  3936. "}else if(o){",
  3937. // reset to GMT, then add offset
  3938. "v = Ext.Date.add(v, Ext.Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));",
  3939. "}",
  3940. "}",
  3941. "return v;"
  3942. ].join('\n');
  3943. return function(format) {
  3944. var regexNum = utilDate.parseRegexes.length,
  3945. currentGroup = 1,
  3946. calc = [],
  3947. regex = [],
  3948. special = false,
  3949. ch = "",
  3950. i = 0,
  3951. len = format.length,
  3952. atEnd = [],
  3953. obj;
  3954. for (; i < len; ++i) {
  3955. ch = format.charAt(i);
  3956. if (!special && ch == "\\") {
  3957. special = true;
  3958. } else if (special) {
  3959. special = false;
  3960. regex.push(Ext.String.escape(ch));
  3961. } else {
  3962. obj = utilDate.formatCodeToRegex(ch, currentGroup);
  3963. currentGroup += obj.g;
  3964. regex.push(obj.s);
  3965. if (obj.g && obj.c) {
  3966. if (obj.calcAtEnd) {
  3967. atEnd.push(obj.c);
  3968. } else {
  3969. calc.push(obj.c);
  3970. }
  3971. }
  3972. }
  3973. }
  3974. calc = calc.concat(atEnd);
  3975. utilDate.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$", 'i');
  3976. utilDate.parseFunctions[format] = Ext.functionFactory("input", "strict", xf(code, regexNum, calc.join('')));
  3977. };
  3978. })(),
  3979. // private
  3980. parseCodes : {
  3981. /*
  3982. * Notes:
  3983. * g = {Number} calculation group (0 or 1. only group 1 contributes to date calculations.)
  3984. * c = {String} calculation method (required for group 1. null for group 0. {0} = currentGroup - position in regex result array)
  3985. * s = {String} regex pattern. all matches are stored in results[], and are accessible by the calculation mapped to 'c'
  3986. */
  3987. d: {
  3988. g:1,
  3989. c:"d = parseInt(results[{0}], 10);\n",
  3990. s:"(3[0-1]|[1-2][0-9]|0[1-9])" // day of month with leading zeroes (01 - 31)
  3991. },
  3992. j: {
  3993. g:1,
  3994. c:"d = parseInt(results[{0}], 10);\n",
  3995. s:"(3[0-1]|[1-2][0-9]|[1-9])" // day of month without leading zeroes (1 - 31)
  3996. },
  3997. D: function() {
  3998. for (var a = [], i = 0; i < 7; a.push(utilDate.getShortDayName(i)), ++i); // get localised short day names
  3999. return {
  4000. g:0,
  4001. c:null,
  4002. s:"(?:" + a.join("|") +")"
  4003. };
  4004. },
  4005. l: function() {
  4006. return {
  4007. g:0,
  4008. c:null,
  4009. s:"(?:" + utilDate.dayNames.join("|") + ")"
  4010. };
  4011. },
  4012. N: {
  4013. g:0,
  4014. c:null,
  4015. s:"[1-7]" // ISO-8601 day number (1 (monday) - 7 (sunday))
  4016. },
  4017. //<locale type="object" property="parseCodes">
  4018. S: {
  4019. g:0,
  4020. c:null,
  4021. s:"(?:st|nd|rd|th)"
  4022. },
  4023. //</locale>
  4024. w: {
  4025. g:0,
  4026. c:null,
  4027. s:"[0-6]" // javascript day number (0 (sunday) - 6 (saturday))
  4028. },
  4029. z: {
  4030. g:1,
  4031. c:"z = parseInt(results[{0}], 10);\n",
  4032. s:"(\\d{1,3})" // day of the year (0 - 364 (365 in leap years))
  4033. },
  4034. W: {
  4035. g:0,
  4036. c:null,
  4037. s:"(?:\\d{2})" // ISO-8601 week number (with leading zero)
  4038. },
  4039. F: function() {
  4040. return {
  4041. g:1,
  4042. c:"m = parseInt(Ext.Date.getMonthNumber(results[{0}]), 10);\n", // get localised month number
  4043. s:"(" + utilDate.monthNames.join("|") + ")"
  4044. };
  4045. },
  4046. M: function() {
  4047. for (var a = [], i = 0; i < 12; a.push(utilDate.getShortMonthName(i)), ++i); // get localised short month names
  4048. return Ext.applyIf({
  4049. s:"(" + a.join("|") + ")"
  4050. }, utilDate.formatCodeToRegex("F"));
  4051. },
  4052. m: {
  4053. g:1,
  4054. c:"m = parseInt(results[{0}], 10) - 1;\n",
  4055. s:"(1[0-2]|0[1-9])" // month number with leading zeros (01 - 12)
  4056. },
  4057. n: {
  4058. g:1,
  4059. c:"m = parseInt(results[{0}], 10) - 1;\n",
  4060. s:"(1[0-2]|[1-9])" // month number without leading zeros (1 - 12)
  4061. },
  4062. t: {
  4063. g:0,
  4064. c:null,
  4065. s:"(?:\\d{2})" // no. of days in the month (28 - 31)
  4066. },
  4067. L: {
  4068. g:0,
  4069. c:null,
  4070. s:"(?:1|0)"
  4071. },
  4072. o: function() {
  4073. return utilDate.formatCodeToRegex("Y");
  4074. },
  4075. Y: {
  4076. g:1,
  4077. c:"y = parseInt(results[{0}], 10);\n",
  4078. s:"(\\d{4})" // 4-digit year
  4079. },
  4080. y: {
  4081. g:1,
  4082. c:"var ty = parseInt(results[{0}], 10);\n"
  4083. + "y = ty > Ext.Date.y2kYear ? 1900 + ty : 2000 + ty;\n", // 2-digit year
  4084. s:"(\\d{1,2})"
  4085. },
  4086. /*
  4087. * In the am/pm parsing routines, we allow both upper and lower case
  4088. * even though it doesn't exactly match the spec. It gives much more flexibility
  4089. * in being able to specify case insensitive regexes.
  4090. */
  4091. a: {
  4092. g:1,
  4093. c:"if (/(am)/i.test(results[{0}])) {\n"
  4094. + "if (!h || h == 12) { h = 0; }\n"
  4095. + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
  4096. s:"(am|pm|AM|PM)",
  4097. calcAtEnd: true
  4098. },
  4099. A: {
  4100. g:1,
  4101. c:"if (/(am)/i.test(results[{0}])) {\n"
  4102. + "if (!h || h == 12) { h = 0; }\n"
  4103. + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
  4104. s:"(AM|PM|am|pm)",
  4105. calcAtEnd: true
  4106. },
  4107. g: {
  4108. g:1,
  4109. c:"h = parseInt(results[{0}], 10);\n",
  4110. s:"(1[0-2]|[0-9])" // 12-hr format of an hour without leading zeroes (1 - 12)
  4111. },
  4112. G: {
  4113. g:1,
  4114. c:"h = parseInt(results[{0}], 10);\n",
  4115. s:"(2[0-3]|1[0-9]|[0-9])" // 24-hr format of an hour without leading zeroes (0 - 23)
  4116. },
  4117. h: {
  4118. g:1,
  4119. c:"h = parseInt(results[{0}], 10);\n",
  4120. s:"(1[0-2]|0[1-9])" // 12-hr format of an hour with leading zeroes (01 - 12)
  4121. },
  4122. H: {
  4123. g:1,
  4124. c:"h = parseInt(results[{0}], 10);\n",
  4125. s:"(2[0-3]|[0-1][0-9])" // 24-hr format of an hour with leading zeroes (00 - 23)
  4126. },
  4127. i: {
  4128. g:1,
  4129. c:"i = parseInt(results[{0}], 10);\n",
  4130. s:"([0-5][0-9])" // minutes with leading zeros (00 - 59)
  4131. },
  4132. s: {
  4133. g:1,
  4134. c:"s = parseInt(results[{0}], 10);\n",
  4135. s:"([0-5][0-9])" // seconds with leading zeros (00 - 59)
  4136. },
  4137. u: {
  4138. g:1,
  4139. c:"ms = results[{0}]; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n",
  4140. s:"(\\d+)" // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
  4141. },
  4142. O: {
  4143. g:1,
  4144. c:[
  4145. "o = results[{0}];",
  4146. "var sn = o.substring(0,1),", // get + / - sign
  4147. "hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
  4148. "mn = o.substring(3,5) % 60;", // get minutes
  4149. "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
  4150. ].join("\n"),
  4151. s: "([+\-]\\d{4})" // GMT offset in hrs and mins
  4152. },
  4153. P: {
  4154. g:1,
  4155. c:[
  4156. "o = results[{0}];",
  4157. "var sn = o.substring(0,1),", // get + / - sign
  4158. "hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
  4159. "mn = o.substring(4,6) % 60;", // get minutes
  4160. "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
  4161. ].join("\n"),
  4162. s: "([+\-]\\d{2}:\\d{2})" // GMT offset in hrs and mins (with colon separator)
  4163. },
  4164. T: {
  4165. g:0,
  4166. c:null,
  4167. s:"[A-Z]{1,4}" // timezone abbrev. may be between 1 - 4 chars
  4168. },
  4169. Z: {
  4170. g:1,
  4171. c:"zz = results[{0}] * 1;\n" // -43200 <= UTC offset <= 50400
  4172. + "zz = (-43200 <= zz && zz <= 50400)? zz : null;\n",
  4173. s:"([+\-]?\\d{1,5})" // leading '+' sign is optional for UTC offset
  4174. },
  4175. c: function() {
  4176. var calc = [],
  4177. arr = [
  4178. utilDate.formatCodeToRegex("Y", 1), // year
  4179. utilDate.formatCodeToRegex("m", 2), // month
  4180. utilDate.formatCodeToRegex("d", 3), // day
  4181. utilDate.formatCodeToRegex("H", 4), // hour
  4182. utilDate.formatCodeToRegex("i", 5), // minute
  4183. utilDate.formatCodeToRegex("s", 6), // second
  4184. {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)
  4185. {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
  4186. "if(results[8]) {", // timezone specified
  4187. "if(results[8] == 'Z'){",
  4188. "zz = 0;", // UTC
  4189. "}else if (results[8].indexOf(':') > -1){",
  4190. utilDate.formatCodeToRegex("P", 8).c, // timezone offset with colon separator
  4191. "}else{",
  4192. utilDate.formatCodeToRegex("O", 8).c, // timezone offset without colon separator
  4193. "}",
  4194. "}"
  4195. ].join('\n')}
  4196. ];
  4197. for (var i = 0, l = arr.length; i < l; ++i) {
  4198. calc.push(arr[i].c);
  4199. }
  4200. return {
  4201. g:1,
  4202. c:calc.join(""),
  4203. s:[
  4204. arr[0].s, // year (required)
  4205. "(?:", "-", arr[1].s, // month (optional)
  4206. "(?:", "-", arr[2].s, // day (optional)
  4207. "(?:",
  4208. "(?:T| )?", // time delimiter -- either a "T" or a single blank space
  4209. 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
  4210. "(?::", arr[5].s, ")?", // seconds (optional)
  4211. "(?:(?:\\.|,)(\\d+))?", // decimal fraction of a second (e.g. ",12345" or ".98765") (optional)
  4212. "(Z|(?:[-+]\\d{2}(?::)?\\d{2}))?", // "Z" (UTC) or "-0530" (UTC offset without colon delimiter) or "+08:00" (UTC offset with colon delimiter) (optional)
  4213. ")?",
  4214. ")?",
  4215. ")?"
  4216. ].join("")
  4217. };
  4218. },
  4219. U: {
  4220. g:1,
  4221. c:"u = parseInt(results[{0}], 10);\n",
  4222. s:"(-?\\d+)" // leading minus sign indicates seconds before UNIX epoch
  4223. }
  4224. },
  4225. //Old Ext.Date prototype methods.
  4226. // private
  4227. dateFormat: function(date, format) {
  4228. return utilDate.format(date, format);
  4229. },
  4230. /**
  4231. * Compares if two dates are equal by comparing their values.
  4232. * @param {Date} date1
  4233. * @param {Date} date2
  4234. * @return {Boolean} True if the date values are equal
  4235. */
  4236. isEqual: function(date1, date2) {
  4237. // check we have 2 date objects
  4238. if (date1 && date2) {
  4239. return (date1.getTime() === date2.getTime());
  4240. }
  4241. // one or both isn't a date, only equal if both are falsey
  4242. return !(date1 || date2);
  4243. },
  4244. /**
  4245. * Formats a date given the supplied format string.
  4246. * @param {Date} date The date to format
  4247. * @param {String} format The format string
  4248. * @return {String} The formatted date
  4249. */
  4250. format: function(date, format) {
  4251. if (utilDate.formatFunctions[format] == null) {
  4252. utilDate.createFormat(format);
  4253. }
  4254. var result = utilDate.formatFunctions[format].call(date);
  4255. return result + '';
  4256. },
  4257. /**
  4258. * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
  4259. *
  4260. * Note: The date string returned by the javascript Date object's toString() method varies
  4261. * between browsers (e.g. FF vs IE) and system region settings (e.g. IE in Asia vs IE in America).
  4262. * For a given date string e.g. "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)",
  4263. * getTimezone() first tries to get the timezone abbreviation from between a pair of parentheses
  4264. * (which may or may not be present), failing which it proceeds to get the timezone abbreviation
  4265. * from the GMT offset portion of the date string.
  4266. * @param {Date} date The date
  4267. * @return {String} The abbreviated timezone name (e.g. 'CST', 'PDT', 'EDT', 'MPST' ...).
  4268. */
  4269. getTimezone : function(date) {
  4270. // the following list shows the differences between date strings from different browsers on a WinXP SP2 machine from an Asian locale:
  4271. //
  4272. // Opera : "Thu, 25 Oct 2007 22:53:45 GMT+0800" -- shortest (weirdest) date string of the lot
  4273. // 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)
  4274. // FF : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone
  4275. // IE : "Thu Oct 25 22:54:35 UTC+0800 2007" -- (Asian system setting) look for 3-4 letter timezone abbrev
  4276. // IE : "Thu Oct 25 17:06:37 PDT 2007" -- (American system setting) look for 3-4 letter timezone abbrev
  4277. //
  4278. // this crazy regex attempts to guess the correct timezone abbreviation despite these differences.
  4279. // step 1: (?:\((.*)\) -- find timezone in parentheses
  4280. // 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
  4281. // step 3: remove all non uppercase characters found in step 1 and 2
  4282. return date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, "");
  4283. },
  4284. /**
  4285. * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
  4286. * @param {Date} date The date
  4287. * @param {Boolean} colon (optional) true to separate the hours and minutes with a colon (defaults to false).
  4288. * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600').
  4289. */
  4290. getGMTOffset : function(date, colon) {
  4291. var offset = date.getTimezoneOffset();
  4292. return (offset > 0 ? "-" : "+")
  4293. + Ext.String.leftPad(Math.floor(Math.abs(offset) / 60), 2, "0")
  4294. + (colon ? ":" : "")
  4295. + Ext.String.leftPad(Math.abs(offset % 60), 2, "0");
  4296. },
  4297. /**
  4298. * Get the numeric day number of the year, adjusted for leap year.
  4299. * @param {Date} date The date
  4300. * @return {Number} 0 to 364 (365 in leap years).
  4301. */
  4302. getDayOfYear: function(date) {
  4303. var num = 0,
  4304. d = Ext.Date.clone(date),
  4305. m = date.getMonth(),
  4306. i;
  4307. for (i = 0, d.setDate(1), d.setMonth(0); i < m; d.setMonth(++i)) {
  4308. num += utilDate.getDaysInMonth(d);
  4309. }
  4310. return num + date.getDate() - 1;
  4311. },
  4312. /**
  4313. * Get the numeric ISO-8601 week number of the year.
  4314. * (equivalent to the format specifier 'W', but without a leading zero).
  4315. * @param {Date} date The date
  4316. * @return {Number} 1 to 53
  4317. * @method
  4318. */
  4319. getWeekOfYear : (function() {
  4320. // adapted from http://www.merlyn.demon.co.uk/weekcalc.htm
  4321. var ms1d = 864e5, // milliseconds in a day
  4322. ms7d = 7 * ms1d; // milliseconds in a week
  4323. return function(date) { // return a closure so constants get calculated only once
  4324. var DC3 = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate() + 3) / ms1d, // an Absolute Day Number
  4325. AWN = Math.floor(DC3 / 7), // an Absolute Week Number
  4326. Wyr = new Date(AWN * ms7d).getUTCFullYear();
  4327. return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1;
  4328. };
  4329. })(),
  4330. /**
  4331. * Checks if the current date falls within a leap year.
  4332. * @param {Date} date The date
  4333. * @return {Boolean} True if the current date falls within a leap year, false otherwise.
  4334. */
  4335. isLeapYear : function(date) {
  4336. var year = date.getFullYear();
  4337. return !!((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
  4338. },
  4339. /**
  4340. * Get the first day of the current month, adjusted for leap year. The returned value
  4341. * is the numeric day index within the week (0-6) which can be used in conjunction with
  4342. * the {@link #monthNames} array to retrieve the textual day name.
  4343. * Example:
  4344. * <pre><code>
  4345. var dt = new Date('1/10/2007'),
  4346. firstDay = Ext.Date.getFirstDayOfMonth(dt);
  4347. console.log(Ext.Date.dayNames[firstDay]); //output: 'Monday'
  4348. * </code></pre>
  4349. * @param {Date} date The date
  4350. * @return {Number} The day number (0-6).
  4351. */
  4352. getFirstDayOfMonth : function(date) {
  4353. var day = (date.getDay() - (date.getDate() - 1)) % 7;
  4354. return (day < 0) ? (day + 7) : day;
  4355. },
  4356. /**
  4357. * Get the last day of the current month, adjusted for leap year. The returned value
  4358. * is the numeric day index within the week (0-6) which can be used in conjunction with
  4359. * the {@link #monthNames} array to retrieve the textual day name.
  4360. * Example:
  4361. * <pre><code>
  4362. var dt = new Date('1/10/2007'),
  4363. lastDay = Ext.Date.getLastDayOfMonth(dt);
  4364. console.log(Ext.Date.dayNames[lastDay]); //output: 'Wednesday'
  4365. * </code></pre>
  4366. * @param {Date} date The date
  4367. * @return {Number} The day number (0-6).
  4368. */
  4369. getLastDayOfMonth : function(date) {
  4370. return utilDate.getLastDateOfMonth(date).getDay();
  4371. },
  4372. /**
  4373. * Get the date of the first day of the month in which this date resides.
  4374. * @param {Date} date The date
  4375. * @return {Date}
  4376. */
  4377. getFirstDateOfMonth : function(date) {
  4378. return new Date(date.getFullYear(), date.getMonth(), 1);
  4379. },
  4380. /**
  4381. * Get the date of the last day of the month in which this date resides.
  4382. * @param {Date} date The date
  4383. * @return {Date}
  4384. */
  4385. getLastDateOfMonth : function(date) {
  4386. return new Date(date.getFullYear(), date.getMonth(), utilDate.getDaysInMonth(date));
  4387. },
  4388. /**
  4389. * Get the number of days in the current month, adjusted for leap year.
  4390. * @param {Date} date The date
  4391. * @return {Number} The number of days in the month.
  4392. * @method
  4393. */
  4394. getDaysInMonth: (function() {
  4395. var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  4396. return function(date) { // return a closure for efficiency
  4397. var m = date.getMonth();
  4398. return m == 1 && utilDate.isLeapYear(date) ? 29 : daysInMonth[m];
  4399. };
  4400. })(),
  4401. /**
  4402. * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
  4403. * @param {Date} date The date
  4404. * @return {String} 'st, 'nd', 'rd' or 'th'.
  4405. */
  4406. //<locale type="function">
  4407. getSuffix : function(date) {
  4408. switch (date.getDate()) {
  4409. case 1:
  4410. case 21:
  4411. case 31:
  4412. return "st";
  4413. case 2:
  4414. case 22:
  4415. return "nd";
  4416. case 3:
  4417. case 23:
  4418. return "rd";
  4419. default:
  4420. return "th";
  4421. }
  4422. },
  4423. //</locale>
  4424. /**
  4425. * Creates and returns a new Date instance with the exact same date value as the called instance.
  4426. * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
  4427. * variable will also be changed. When the intention is to create a new variable that will not
  4428. * modify the original instance, you should create a clone.
  4429. *
  4430. * Example of correctly cloning a date:
  4431. * <pre><code>
  4432. //wrong way:
  4433. var orig = new Date('10/1/2006');
  4434. var copy = orig;
  4435. copy.setDate(5);
  4436. console.log(orig); //returns 'Thu Oct 05 2006'!
  4437. //correct way:
  4438. var orig = new Date('10/1/2006'),
  4439. copy = Ext.Date.clone(orig);
  4440. copy.setDate(5);
  4441. console.log(orig); //returns 'Thu Oct 01 2006'
  4442. * </code></pre>
  4443. * @param {Date} date The date
  4444. * @return {Date} The new Date instance.
  4445. */
  4446. clone : function(date) {
  4447. return new Date(date.getTime());
  4448. },
  4449. /**
  4450. * Checks if the current date is affected by Daylight Saving Time (DST).
  4451. * @param {Date} date The date
  4452. * @return {Boolean} True if the current date is affected by DST.
  4453. */
  4454. isDST : function(date) {
  4455. // adapted from http://sencha.com/forum/showthread.php?p=247172#post247172
  4456. // courtesy of @geoffrey.mcgill
  4457. return new Date(date.getFullYear(), 0, 1).getTimezoneOffset() != date.getTimezoneOffset();
  4458. },
  4459. /**
  4460. * Attempts to clear all time information from this Date by setting the time to midnight of the same day,
  4461. * automatically adjusting for Daylight Saving Time (DST) where applicable.
  4462. * (note: DST timezone information for the browser's host operating system is assumed to be up-to-date)
  4463. * @param {Date} date The date
  4464. * @param {Boolean} clone true to create a clone of this date, clear the time and return it (defaults to false).
  4465. * @return {Date} this or the clone.
  4466. */
  4467. clearTime : function(date, clone) {
  4468. if (clone) {
  4469. return Ext.Date.clearTime(Ext.Date.clone(date));
  4470. }
  4471. // get current date before clearing time
  4472. var d = date.getDate();
  4473. // clear time
  4474. date.setHours(0);
  4475. date.setMinutes(0);
  4476. date.setSeconds(0);
  4477. date.setMilliseconds(0);
  4478. if (date.getDate() != d) { // account for DST (i.e. day of month changed when setting hour = 0)
  4479. // note: DST adjustments are assumed to occur in multiples of 1 hour (this is almost always the case)
  4480. // refer to http://www.timeanddate.com/time/aboutdst.html for the (rare) exceptions to this rule
  4481. // increment hour until cloned date == current date
  4482. for (var hr = 1, c = utilDate.add(date, Ext.Date.HOUR, hr); c.getDate() != d; hr++, c = utilDate.add(date, Ext.Date.HOUR, hr));
  4483. date.setDate(d);
  4484. date.setHours(c.getHours());
  4485. };
  4486. return date;
  4487. },
  4488. /**
  4489. * Provides a convenient method for performing basic date arithmetic. This method
  4490. * does not modify the Date instance being called - it creates and returns
  4491. * a new Date instance containing the resulting date value.
  4492. *
  4493. * Examples:
  4494. * <pre><code>
  4495. // Basic usage:
  4496. var dt = Ext.Date.add(new Date('10/29/2006'), Ext.Date.DAY, 5);
  4497. console.log(dt); //returns 'Fri Nov 03 2006 00:00:00'
  4498. // Negative values will be subtracted:
  4499. var dt2 = Ext.Date.add(new Date('10/1/2006'), Ext.Date.DAY, -5);
  4500. console.log(dt2); //returns 'Tue Sep 26 2006 00:00:00'
  4501. * </code></pre>
  4502. *
  4503. * @param {Date} date The date to modify
  4504. * @param {String} interval A valid date interval enum value.
  4505. * @param {Number} value The amount to add to the current date.
  4506. * @return {Date} The new Date instance.
  4507. */
  4508. add : function(date, interval, value) {
  4509. var d = Ext.Date.clone(date),
  4510. Date = Ext.Date;
  4511. if (!interval || value === 0) return d;
  4512. switch(interval.toLowerCase()) {
  4513. case Ext.Date.MILLI:
  4514. d.setMilliseconds(d.getMilliseconds() + value);
  4515. break;
  4516. case Ext.Date.SECOND:
  4517. d.setSeconds(d.getSeconds() + value);
  4518. break;
  4519. case Ext.Date.MINUTE:
  4520. d.setMinutes(d.getMinutes() + value);
  4521. break;
  4522. case Ext.Date.HOUR:
  4523. d.setHours(d.getHours() + value);
  4524. break;
  4525. case Ext.Date.DAY:
  4526. d.setDate(d.getDate() + value);
  4527. break;
  4528. case Ext.Date.MONTH:
  4529. var day = date.getDate();
  4530. if (day > 28) {
  4531. day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), Ext.Date.MONTH, value)).getDate());
  4532. }
  4533. d.setDate(day);
  4534. d.setMonth(date.getMonth() + value);
  4535. break;
  4536. case Ext.Date.YEAR:
  4537. var day = date.getDate();
  4538. if (day > 28) {
  4539. day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), Ext.Date.YEAR, value)).getDate());
  4540. }
  4541. d.setDate(day);
  4542. d.setFullYear(date.getFullYear() + value);
  4543. break;
  4544. }
  4545. return d;
  4546. },
  4547. /**
  4548. * Checks if a date falls on or between the given start and end dates.
  4549. * @param {Date} date The date to check
  4550. * @param {Date} start Start date
  4551. * @param {Date} end End date
  4552. * @return {Boolean} true if this date falls on or between the given start and end dates.
  4553. */
  4554. between : function(date, start, end) {
  4555. var t = date.getTime();
  4556. return start.getTime() <= t && t <= end.getTime();
  4557. },
  4558. //Maintains compatibility with old static and prototype window.Date methods.
  4559. compat: function() {
  4560. var nativeDate = window.Date,
  4561. p, u,
  4562. 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'],
  4563. proto = ['dateFormat', 'format', 'getTimezone', 'getGMTOffset', 'getDayOfYear', 'getWeekOfYear', 'isLeapYear', 'getFirstDayOfMonth', 'getLastDayOfMonth', 'getDaysInMonth', 'getSuffix', 'clone', 'isDST', 'clearTime', 'add', 'between'];
  4564. sLen = statics.length,
  4565. pLen = proto.length,
  4566. stat, prot, s;
  4567. //Append statics
  4568. for (s = 0; s < sLen; s++) {
  4569. stat = statics[s];
  4570. nativeDate[stat] = utilDate[stat];
  4571. }
  4572. //Append to prototype
  4573. for (p = 0; p < pLen; p++) {
  4574. prot = proto[p];
  4575. nativeDate.prototype[prot] = function() {
  4576. var args = Array.prototype.slice.call(arguments);
  4577. args.unshift(this);
  4578. return utilDate[prot].apply(utilDate, args);
  4579. };
  4580. }
  4581. }
  4582. };
  4583. var utilDate = Ext.Date;
  4584. })();
  4585. /**
  4586. * @author Jacky Nguyen <jacky@sencha.com>
  4587. * @docauthor Jacky Nguyen <jacky@sencha.com>
  4588. * @class Ext.Base
  4589. *
  4590. * The root of all classes created with {@link Ext#define}.
  4591. *
  4592. * Ext.Base is the building block of all Ext classes. All classes in Ext inherit from Ext.Base.
  4593. * All prototype and static members of this class are inherited by all other classes.
  4594. */
  4595. (function(flexSetter) {
  4596. var noArgs = [],
  4597. Base = function(){};
  4598. // This is the "$previous" method of a hook function on an instance. When called, it
  4599. // calls through the class prototype by the name of the called method.
  4600. function callHookParent () {
  4601. var method = callHookParent.caller.caller; // skip callParent (our caller)
  4602. return method.$owner.prototype[method.$name].apply(this, arguments);
  4603. }
  4604. // These static properties will be copied to every newly created class with {@link Ext#define}
  4605. Ext.apply(Base, {
  4606. $className: 'Ext.Base',
  4607. $isClass: true,
  4608. /**
  4609. * Create a new instance of this Class.
  4610. *
  4611. * Ext.define('My.cool.Class', {
  4612. * ...
  4613. * });
  4614. *
  4615. * My.cool.Class.create({
  4616. * someConfig: true
  4617. * });
  4618. *
  4619. * All parameters are passed to the constructor of the class.
  4620. *
  4621. * @return {Object} the created instance.
  4622. * @static
  4623. * @inheritable
  4624. */
  4625. create: function() {
  4626. return Ext.create.apply(Ext, [this].concat(Array.prototype.slice.call(arguments, 0)));
  4627. },
  4628. /**
  4629. * @private
  4630. * @param config
  4631. */
  4632. extend: function(parent) {
  4633. var parentPrototype = parent.prototype,
  4634. basePrototype, prototype, i, ln, name, statics;
  4635. prototype = this.prototype = Ext.Object.chain(parentPrototype);
  4636. prototype.self = this;
  4637. this.superclass = prototype.superclass = parentPrototype;
  4638. if (!parent.$isClass) {
  4639. basePrototype = Ext.Base.prototype;
  4640. for (i in basePrototype) {
  4641. if (i in prototype) {
  4642. prototype[i] = basePrototype[i];
  4643. }
  4644. }
  4645. }
  4646. // Statics inheritance
  4647. statics = parentPrototype.$inheritableStatics;
  4648. if (statics) {
  4649. for (i = 0,ln = statics.length; i < ln; i++) {
  4650. name = statics[i];
  4651. if (!this.hasOwnProperty(name)) {
  4652. this[name] = parent[name];
  4653. }
  4654. }
  4655. }
  4656. if (parent.$onExtended) {
  4657. this.$onExtended = parent.$onExtended.slice();
  4658. }
  4659. prototype.config = new prototype.configClass;
  4660. prototype.initConfigList = prototype.initConfigList.slice();
  4661. prototype.initConfigMap = Ext.clone(prototype.initConfigMap);
  4662. prototype.configMap = Ext.Object.chain(prototype.configMap);
  4663. },
  4664. /**
  4665. * @private
  4666. * @param config
  4667. */
  4668. '$onExtended': [],
  4669. /**
  4670. * @private
  4671. * @param config
  4672. */
  4673. triggerExtended: function() {
  4674. var callbacks = this.$onExtended,
  4675. ln = callbacks.length,
  4676. i, callback;
  4677. if (ln > 0) {
  4678. for (i = 0; i < ln; i++) {
  4679. callback = callbacks[i];
  4680. callback.fn.apply(callback.scope || this, arguments);
  4681. }
  4682. }
  4683. },
  4684. /**
  4685. * @private
  4686. * @param config
  4687. */
  4688. onExtended: function(fn, scope) {
  4689. this.$onExtended.push({
  4690. fn: fn,
  4691. scope: scope
  4692. });
  4693. return this;
  4694. },
  4695. /**
  4696. * @private
  4697. * @param config
  4698. */
  4699. addConfig: function(config, fullMerge) {
  4700. var prototype = this.prototype,
  4701. configNameCache = Ext.Class.configNameCache,
  4702. hasConfig = prototype.configMap,
  4703. initConfigList = prototype.initConfigList,
  4704. initConfigMap = prototype.initConfigMap,
  4705. defaultConfig = prototype.config,
  4706. initializedName, name, value;
  4707. for (name in config) {
  4708. if (config.hasOwnProperty(name)) {
  4709. if (!hasConfig[name]) {
  4710. hasConfig[name] = true;
  4711. }
  4712. value = config[name];
  4713. initializedName = configNameCache[name].initialized;
  4714. if (!initConfigMap[name] && value !== null && !prototype[initializedName]) {
  4715. initConfigMap[name] = true;
  4716. initConfigList.push(name);
  4717. }
  4718. }
  4719. }
  4720. if (fullMerge) {
  4721. Ext.merge(defaultConfig, config);
  4722. }
  4723. else {
  4724. Ext.mergeIf(defaultConfig, config);
  4725. }
  4726. prototype.configClass = Ext.Object.classify(defaultConfig);
  4727. },
  4728. /**
  4729. * Add / override static properties of this class.
  4730. *
  4731. * Ext.define('My.cool.Class', {
  4732. * ...
  4733. * });
  4734. *
  4735. * My.cool.Class.addStatics({
  4736. * someProperty: 'someValue', // My.cool.Class.someProperty = 'someValue'
  4737. * method1: function() { ... }, // My.cool.Class.method1 = function() { ... };
  4738. * method2: function() { ... } // My.cool.Class.method2 = function() { ... };
  4739. * });
  4740. *
  4741. * @param {Object} members
  4742. * @return {Ext.Base} this
  4743. * @static
  4744. * @inheritable
  4745. */
  4746. addStatics: function(members) {
  4747. var member, name;
  4748. for (name in members) {
  4749. if (members.hasOwnProperty(name)) {
  4750. member = members[name];
  4751. this[name] = member;
  4752. }
  4753. }
  4754. return this;
  4755. },
  4756. /**
  4757. * @private
  4758. * @param {Object} members
  4759. */
  4760. addInheritableStatics: function(members) {
  4761. var inheritableStatics,
  4762. hasInheritableStatics,
  4763. prototype = this.prototype,
  4764. name, member;
  4765. inheritableStatics = prototype.$inheritableStatics;
  4766. hasInheritableStatics = prototype.$hasInheritableStatics;
  4767. if (!inheritableStatics) {
  4768. inheritableStatics = prototype.$inheritableStatics = [];
  4769. hasInheritableStatics = prototype.$hasInheritableStatics = {};
  4770. }
  4771. for (name in members) {
  4772. if (members.hasOwnProperty(name)) {
  4773. member = members[name];
  4774. this[name] = member;
  4775. if (!hasInheritableStatics[name]) {
  4776. hasInheritableStatics[name] = true;
  4777. inheritableStatics.push(name);
  4778. }
  4779. }
  4780. }
  4781. return this;
  4782. },
  4783. /**
  4784. * Add methods / properties to the prototype of this class.
  4785. *
  4786. * Ext.define('My.awesome.Cat', {
  4787. * constructor: function() {
  4788. * ...
  4789. * }
  4790. * });
  4791. *
  4792. * My.awesome.Cat.implement({
  4793. * meow: function() {
  4794. * alert('Meowww...');
  4795. * }
  4796. * });
  4797. *
  4798. * var kitty = new My.awesome.Cat;
  4799. * kitty.meow();
  4800. *
  4801. * @param {Object} members
  4802. * @static
  4803. * @inheritable
  4804. */
  4805. addMembers: function(members) {
  4806. var prototype = this.prototype,
  4807. enumerables = Ext.enumerables,
  4808. names = [],
  4809. i, ln, name, member;
  4810. for (name in members) {
  4811. names.push(name);
  4812. }
  4813. if (enumerables) {
  4814. names.push.apply(names, enumerables);
  4815. }
  4816. for (i = 0,ln = names.length; i < ln; i++) {
  4817. name = names[i];
  4818. if (members.hasOwnProperty(name)) {
  4819. member = members[name];
  4820. if (typeof member == 'function' && !member.$isClass && member !== Ext.emptyFn) {
  4821. member.$owner = this;
  4822. member.$name = name;
  4823. }
  4824. prototype[name] = member;
  4825. }
  4826. }
  4827. return this;
  4828. },
  4829. /**
  4830. * @private
  4831. * @param name
  4832. * @param member
  4833. */
  4834. addMember: function(name, member) {
  4835. if (typeof member == 'function' && !member.$isClass && member !== Ext.emptyFn) {
  4836. member.$owner = this;
  4837. member.$name = name;
  4838. }
  4839. this.prototype[name] = member;
  4840. return this;
  4841. },
  4842. /**
  4843. * @private
  4844. */
  4845. implement: function() {
  4846. this.addMembers.apply(this, arguments);
  4847. },
  4848. /**
  4849. * Borrow another class' members to the prototype of this class.
  4850. *
  4851. * Ext.define('Bank', {
  4852. * money: '$$$',
  4853. * printMoney: function() {
  4854. * alert('$$$$$$$');
  4855. * }
  4856. * });
  4857. *
  4858. * Ext.define('Thief', {
  4859. * ...
  4860. * });
  4861. *
  4862. * Thief.borrow(Bank, ['money', 'printMoney']);
  4863. *
  4864. * var steve = new Thief();
  4865. *
  4866. * alert(steve.money); // alerts '$$$'
  4867. * steve.printMoney(); // alerts '$$$$$$$'
  4868. *
  4869. * @param {Ext.Base} fromClass The class to borrow members from
  4870. * @param {Array/String} members The names of the members to borrow
  4871. * @return {Ext.Base} this
  4872. * @static
  4873. * @inheritable
  4874. * @private
  4875. */
  4876. borrow: function(fromClass, members) {
  4877. var prototype = this.prototype,
  4878. fromPrototype = fromClass.prototype,
  4879. i, ln, name, fn, toBorrow;
  4880. members = Ext.Array.from(members);
  4881. for (i = 0,ln = members.length; i < ln; i++) {
  4882. name = members[i];
  4883. toBorrow = fromPrototype[name];
  4884. if (typeof toBorrow == 'function') {
  4885. fn = function() {
  4886. return toBorrow.apply(this, arguments);
  4887. };
  4888. fn.$owner = this;
  4889. fn.$name = name;
  4890. prototype[name] = fn;
  4891. }
  4892. else {
  4893. prototype[name] = toBorrow;
  4894. }
  4895. }
  4896. return this;
  4897. },
  4898. /**
  4899. * Override members of this class. Overridden methods can be invoked via
  4900. * {@link Ext.Base#callParent}.
  4901. *
  4902. * Ext.define('My.Cat', {
  4903. * constructor: function() {
  4904. * alert("I'm a cat!");
  4905. * }
  4906. * });
  4907. *
  4908. * My.Cat.override({
  4909. * constructor: function() {
  4910. * alert("I'm going to be a cat!");
  4911. *
  4912. * var instance = this.callParent(arguments);
  4913. *
  4914. * alert("Meeeeoooowwww");
  4915. *
  4916. * return instance;
  4917. * }
  4918. * });
  4919. *
  4920. * var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
  4921. * // alerts "I'm a cat!"
  4922. * // alerts "Meeeeoooowwww"
  4923. *
  4924. * As of 4.1, direct use of this method is deprecated. Use {@link Ext#define Ext.define}
  4925. * instead:
  4926. *
  4927. * Ext.define('My.CatOverride', {
  4928. * override: 'My.Cat',
  4929. * constructor: function() {
  4930. * alert("I'm going to be a cat!");
  4931. *
  4932. * var instance = this.callParent(arguments);
  4933. *
  4934. * alert("Meeeeoooowwww");
  4935. *
  4936. * return instance;
  4937. * }
  4938. * });
  4939. *
  4940. * The above accomplishes the same result but can be managed by the {@link Ext.Loader}
  4941. * which can properly order the override and its target class and the build process
  4942. * can determine whether the override is needed based on the required state of the
  4943. * target class (My.Cat).
  4944. *
  4945. * @param {Object} members The properties to add to this class. This should be
  4946. * specified as an object literal containing one or more properties.
  4947. * @return {Ext.Base} this class
  4948. * @static
  4949. * @inheritable
  4950. * @markdown
  4951. * @deprecated 4.1.0 Use {@link Ext#define Ext.define} instead
  4952. */
  4953. override: function(members) {
  4954. var me = this,
  4955. enumerables = Ext.enumerables,
  4956. target = me.prototype,
  4957. cloneFunction = Ext.Function.clone,
  4958. name, index, member, statics, names, previous;
  4959. if (arguments.length === 2) {
  4960. name = members;
  4961. members = {};
  4962. members[name] = arguments[1];
  4963. enumerables = null;
  4964. }
  4965. do {
  4966. names = []; // clean slate for prototype (1st pass) and static (2nd pass)
  4967. statics = null; // not needed 1st pass, but needs to be cleared for 2nd pass
  4968. for (name in members) { // hasOwnProperty is checked in the next loop...
  4969. if (name == 'statics') {
  4970. statics = members[name];
  4971. } else {
  4972. names.push(name);
  4973. }
  4974. }
  4975. if (enumerables) {
  4976. names.push.apply(names, enumerables);
  4977. }
  4978. for (index = names.length; index--; ) {
  4979. name = names[index];
  4980. if (members.hasOwnProperty(name)) {
  4981. member = members[name];
  4982. if (typeof member == 'function' && !member.$className && member !== Ext.emptyFn) {
  4983. if (typeof member.$owner != 'undefined') {
  4984. member = cloneFunction(member);
  4985. }
  4986. member.$owner = me;
  4987. member.$name = name;
  4988. previous = target[name];
  4989. if (previous) {
  4990. member.$previous = previous;
  4991. }
  4992. }
  4993. target[name] = member;
  4994. }
  4995. }
  4996. target = me; // 2nd pass is for statics
  4997. members = statics; // statics will be null on 2nd pass
  4998. } while (members);
  4999. return this;
  5000. },
  5001. // Documented downwards
  5002. callParent: function(args) {
  5003. var method;
  5004. // This code is intentionally inlined for the least number of debugger stepping
  5005. return (method = this.callParent.caller) && (method.$previous ||
  5006. ((method = method.$owner ? method : method.caller) &&
  5007. method.$owner.superclass.$class[method.$name])).apply(this, args || noArgs);
  5008. },
  5009. /**
  5010. * Used internally by the mixins pre-processor
  5011. * @private
  5012. * @inheritable
  5013. */
  5014. mixin: function(name, mixinClass) {
  5015. var mixin = mixinClass.prototype,
  5016. prototype = this.prototype,
  5017. key;
  5018. if (typeof mixin.onClassMixedIn != 'undefined') {
  5019. mixin.onClassMixedIn.call(mixinClass, this);
  5020. }
  5021. if (!prototype.hasOwnProperty('mixins')) {
  5022. if ('mixins' in prototype) {
  5023. prototype.mixins = Ext.Object.chain(prototype.mixins);
  5024. }
  5025. else {
  5026. prototype.mixins = {};
  5027. }
  5028. }
  5029. for (key in mixin) {
  5030. if (key === 'mixins') {
  5031. Ext.merge(prototype.mixins, mixin[key]);
  5032. }
  5033. else if (typeof prototype[key] == 'undefined' && key != 'mixinId' && key != 'config') {
  5034. prototype[key] = mixin[key];
  5035. }
  5036. }
  5037. if ('config' in mixin) {
  5038. this.addConfig(mixin.config, false);
  5039. }
  5040. prototype.mixins[name] = mixin;
  5041. },
  5042. /**
  5043. * Get the current class' name in string format.
  5044. *
  5045. * Ext.define('My.cool.Class', {
  5046. * constructor: function() {
  5047. * alert(this.self.getName()); // alerts 'My.cool.Class'
  5048. * }
  5049. * });
  5050. *
  5051. * My.cool.Class.getName(); // 'My.cool.Class'
  5052. *
  5053. * @return {String} className
  5054. * @static
  5055. * @inheritable
  5056. */
  5057. getName: function() {
  5058. return Ext.getClassName(this);
  5059. },
  5060. /**
  5061. * Create aliases for existing prototype methods. Example:
  5062. *
  5063. * Ext.define('My.cool.Class', {
  5064. * method1: function() { ... },
  5065. * method2: function() { ... }
  5066. * });
  5067. *
  5068. * var test = new My.cool.Class();
  5069. *
  5070. * My.cool.Class.createAlias({
  5071. * method3: 'method1',
  5072. * method4: 'method2'
  5073. * });
  5074. *
  5075. * test.method3(); // test.method1()
  5076. *
  5077. * My.cool.Class.createAlias('method5', 'method3');
  5078. *
  5079. * test.method5(); // test.method3() -> test.method1()
  5080. *
  5081. * @param {String/Object} alias The new method name, or an object to set multiple aliases. See
  5082. * {@link Ext.Function#flexSetter flexSetter}
  5083. * @param {String/Object} origin The original method name
  5084. * @static
  5085. * @inheritable
  5086. * @method
  5087. */
  5088. createAlias: flexSetter(function(alias, origin) {
  5089. this.override(alias, function() {
  5090. return this[origin].apply(this, arguments);
  5091. });
  5092. }),
  5093. /**
  5094. * @private
  5095. */
  5096. addXtype: function(xtype) {
  5097. var prototype = this.prototype,
  5098. xtypesMap = prototype.xtypesMap,
  5099. xtypes = prototype.xtypes,
  5100. xtypesChain = prototype.xtypesChain;
  5101. if (!prototype.hasOwnProperty('xtypesMap')) {
  5102. xtypesMap = prototype.xtypesMap = Ext.merge({}, prototype.xtypesMap || {});
  5103. xtypes = prototype.xtypes = prototype.xtypes ? [].concat(prototype.xtypes) : [];
  5104. xtypesChain = prototype.xtypesChain = prototype.xtypesChain ? [].concat(prototype.xtypesChain) : [];
  5105. prototype.xtype = xtype;
  5106. }
  5107. if (!xtypesMap[xtype]) {
  5108. xtypesMap[xtype] = true;
  5109. xtypes.push(xtype);
  5110. xtypesChain.push(xtype);
  5111. Ext.ClassManager.setAlias(this, 'widget.' + xtype);
  5112. }
  5113. return this;
  5114. }
  5115. });
  5116. Base.implement({
  5117. isInstance: true,
  5118. $className: 'Ext.Base',
  5119. configClass: Ext.emptyFn,
  5120. initConfigList: [],
  5121. configMap: {},
  5122. initConfigMap: {},
  5123. /**
  5124. * Get the reference to the class from which this object was instantiated. Note that unlike {@link Ext.Base#self},
  5125. * `this.statics()` is scope-independent and it always returns the class from which it was called, regardless of what
  5126. * `this` points to during run-time
  5127. *
  5128. * Ext.define('My.Cat', {
  5129. * statics: {
  5130. * totalCreated: 0,
  5131. * speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
  5132. * },
  5133. *
  5134. * constructor: function() {
  5135. * var statics = this.statics();
  5136. *
  5137. * alert(statics.speciesName); // always equals to 'Cat' no matter what 'this' refers to
  5138. * // equivalent to: My.Cat.speciesName
  5139. *
  5140. * alert(this.self.speciesName); // dependent on 'this'
  5141. *
  5142. * statics.totalCreated++;
  5143. * },
  5144. *
  5145. * clone: function() {
  5146. * var cloned = new this.self; // dependent on 'this'
  5147. *
  5148. * cloned.groupName = this.statics().speciesName; // equivalent to: My.Cat.speciesName
  5149. *
  5150. * return cloned;
  5151. * }
  5152. * });
  5153. *
  5154. *
  5155. * Ext.define('My.SnowLeopard', {
  5156. * extend: 'My.Cat',
  5157. *
  5158. * statics: {
  5159. * speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
  5160. * },
  5161. *
  5162. * constructor: function() {
  5163. * this.callParent();
  5164. * }
  5165. * });
  5166. *
  5167. * var cat = new My.Cat(); // alerts 'Cat', then alerts 'Cat'
  5168. *
  5169. * var snowLeopard = new My.SnowLeopard(); // alerts 'Cat', then alerts 'Snow Leopard'
  5170. *
  5171. * var clone = snowLeopard.clone();
  5172. * alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard'
  5173. * alert(clone.groupName); // alerts 'Cat'
  5174. *
  5175. * alert(My.Cat.totalCreated); // alerts 3
  5176. *
  5177. * @protected
  5178. * @return {Ext.Class}
  5179. */
  5180. statics: function() {
  5181. var method = this.statics.caller,
  5182. self = this.self;
  5183. if (!method) {
  5184. return self;
  5185. }
  5186. return method.$owner;
  5187. },
  5188. /**
  5189. * Call the "parent" method of the current method. That is the method previously
  5190. * overridden by derivation or by an override (see {@link Ext#define}).
  5191. *
  5192. * Ext.define('My.Base', {
  5193. * constructor: function (x) {
  5194. * this.x = x;
  5195. * },
  5196. *
  5197. * statics: {
  5198. * method: function (x) {
  5199. * return x;
  5200. * }
  5201. * }
  5202. * });
  5203. *
  5204. * Ext.define('My.Derived', {
  5205. * extend: 'My.Base',
  5206. *
  5207. * constructor: function () {
  5208. * this.callParent([21]);
  5209. * }
  5210. * });
  5211. *
  5212. * var obj = new My.Derived();
  5213. *
  5214. * alert(obj.x); // alerts 21
  5215. *
  5216. * This can be used with an override as follows:
  5217. *
  5218. * Ext.define('My.DerivedOverride', {
  5219. * override: 'My.Derived',
  5220. *
  5221. * constructor: function (x) {
  5222. * this.callParent([x*2]); // calls original My.Derived constructor
  5223. * }
  5224. * });
  5225. *
  5226. * var obj = new My.Derived();
  5227. *
  5228. * alert(obj.x); // now alerts 42
  5229. *
  5230. * This also works with static methods.
  5231. *
  5232. * Ext.define('My.Derived2', {
  5233. * extend: 'My.Base',
  5234. *
  5235. * statics: {
  5236. * method: function (x) {
  5237. * return this.callParent([x*2]); // calls My.Base.method
  5238. * }
  5239. * }
  5240. * });
  5241. *
  5242. * alert(My.Base.method(10); // alerts 10
  5243. * alert(My.Derived2.method(10); // alerts 20
  5244. *
  5245. * Lastly, it also works with overridden static methods.
  5246. *
  5247. * Ext.define('My.Derived2Override', {
  5248. * override: 'My.Derived2',
  5249. *
  5250. * statics: {
  5251. * method: function (x) {
  5252. * return this.callParent([x*2]); // calls My.Derived2.method
  5253. * }
  5254. * }
  5255. * });
  5256. *
  5257. * alert(My.Derived2.method(10); // now alerts 40
  5258. *
  5259. * @protected
  5260. * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
  5261. * from the current method, for example: `this.callParent(arguments)`
  5262. * @return {Object} Returns the result of calling the parent method
  5263. */
  5264. callParent: function(args) {
  5265. // NOTE: this code is deliberately as few expressions (and no function calls)
  5266. // as possible so that a debugger can skip over this noise with the minimum number
  5267. // of steps. Basically, just hit Step Into until you are where you really wanted
  5268. // to be.
  5269. var method,
  5270. superMethod = (method = this.callParent.caller) && (method.$previous ||
  5271. ((method = method.$owner ? method : method.caller) &&
  5272. method.$owner.superclass[method.$name]));
  5273. return superMethod.apply(this, args || noArgs);
  5274. },
  5275. /**
  5276. * @property {Ext.Class} self
  5277. *
  5278. * Get the reference to the current class from which this object was instantiated. Unlike {@link Ext.Base#statics},
  5279. * `this.self` is scope-dependent and it's meant to be used for dynamic inheritance. See {@link Ext.Base#statics}
  5280. * for a detailed comparison
  5281. *
  5282. * Ext.define('My.Cat', {
  5283. * statics: {
  5284. * speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
  5285. * },
  5286. *
  5287. * constructor: function() {
  5288. * alert(this.self.speciesName); / dependentOL on 'this'
  5289. * },
  5290. *
  5291. * clone: function() {
  5292. * return new this.self();
  5293. * }
  5294. * });
  5295. *
  5296. *
  5297. * Ext.define('My.SnowLeopard', {
  5298. * extend: 'My.Cat',
  5299. * statics: {
  5300. * speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
  5301. * }
  5302. * });
  5303. *
  5304. * var cat = new My.Cat(); // alerts 'Cat'
  5305. * var snowLeopard = new My.SnowLeopard(); // alerts 'Snow Leopard'
  5306. *
  5307. * var clone = snowLeopard.clone();
  5308. * alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard'
  5309. *
  5310. * @protected
  5311. */
  5312. self: Base,
  5313. // Default constructor, simply returns `this`
  5314. constructor: function() {
  5315. return this;
  5316. },
  5317. hookMethod: function (name, hookFn) {
  5318. var me = this,
  5319. owner = me.self;
  5320. hookFn.$owner = owner;
  5321. hookFn.$name = name;
  5322. if (me.hasOwnProperty(name)) {
  5323. hookFn.$previous = me[name]; // already hooked, so call previous hook
  5324. } else {
  5325. hookFn.$previous = callHookParent; // special "previous" to call on prototype
  5326. }
  5327. me[name] = hookFn;
  5328. },
  5329. hookMethods: function (hooks) {
  5330. Ext.Object.each(hooks, this.hookMethod, this);
  5331. },
  5332. /**
  5333. * Initialize configuration for this class. a typical example:
  5334. *
  5335. * Ext.define('My.awesome.Class', {
  5336. * // The default config
  5337. * config: {
  5338. * name: 'Awesome',
  5339. * isAwesome: true
  5340. * },
  5341. *
  5342. * constructor: function(config) {
  5343. * this.initConfig(config);
  5344. * }
  5345. * });
  5346. *
  5347. * var awesome = new My.awesome.Class({
  5348. * name: 'Super Awesome'
  5349. * });
  5350. *
  5351. * alert(awesome.getName()); // 'Super Awesome'
  5352. *
  5353. * @protected
  5354. * @param {Object} config
  5355. * @return {Object} mixins The mixin prototypes as key - value pairs
  5356. */
  5357. initConfig: function(config) {
  5358. var instanceConfig = config,
  5359. configNameCache = Ext.Class.configNameCache,
  5360. defaultConfig = new this.configClass,
  5361. defaultConfigList = this.initConfigList,
  5362. hasConfig = this.configMap,
  5363. nameMap, i, ln, name, initializedName;
  5364. this.initConfig = Ext.emptyFn;
  5365. this.initialConfig = instanceConfig || {};
  5366. this.config = config = (instanceConfig) ? Ext.merge(defaultConfig, config) : defaultConfig;
  5367. if (instanceConfig) {
  5368. defaultConfigList = defaultConfigList.slice();
  5369. for (name in instanceConfig) {
  5370. if (hasConfig[name]) {
  5371. if (instanceConfig[name] !== null) {
  5372. defaultConfigList.push(name);
  5373. this[configNameCache[name].initialized] = false;
  5374. }
  5375. }
  5376. }
  5377. }
  5378. for (i = 0,ln = defaultConfigList.length; i < ln; i++) {
  5379. name = defaultConfigList[i];
  5380. nameMap = configNameCache[name];
  5381. initializedName = nameMap.initialized;
  5382. if (!this[initializedName]) {
  5383. this[initializedName] = true;
  5384. this[nameMap.set].call(this, config[name]);
  5385. }
  5386. }
  5387. return this;
  5388. },
  5389. /**
  5390. * @private
  5391. * @param config
  5392. */
  5393. hasConfig: function(name) {
  5394. return Boolean(this.configMap[name]);
  5395. },
  5396. /**
  5397. * @private
  5398. */
  5399. setConfig: function(config, applyIfNotSet) {
  5400. if (!config) {
  5401. return this;
  5402. }
  5403. var configNameCache = Ext.Class.configNameCache,
  5404. currentConfig = this.config,
  5405. hasConfig = this.configMap,
  5406. initialConfig = this.initialConfig,
  5407. name, value;
  5408. applyIfNotSet = Boolean(applyIfNotSet);
  5409. for (name in config) {
  5410. if (applyIfNotSet && initialConfig.hasOwnProperty(name)) {
  5411. continue;
  5412. }
  5413. value = config[name];
  5414. currentConfig[name] = value;
  5415. if (hasConfig[name]) {
  5416. this[configNameCache[name].set](value);
  5417. }
  5418. }
  5419. return this;
  5420. },
  5421. /**
  5422. * @private
  5423. * @param name
  5424. */
  5425. getConfig: function(name) {
  5426. var configNameCache = Ext.Class.configNameCache;
  5427. return this[configNameCache[name].get]();
  5428. },
  5429. /**
  5430. *
  5431. * @param name
  5432. */
  5433. getInitialConfig: function(name) {
  5434. var config = this.config;
  5435. if (!name) {
  5436. return config;
  5437. }
  5438. else {
  5439. return config[name];
  5440. }
  5441. },
  5442. /**
  5443. * @private
  5444. * @param names
  5445. * @param callback
  5446. * @param scope
  5447. */
  5448. onConfigUpdate: function(names, callback, scope) {
  5449. var self = this.self,
  5450. i, ln, name,
  5451. updaterName, updater, newUpdater;
  5452. names = Ext.Array.from(names);
  5453. scope = scope || this;
  5454. for (i = 0,ln = names.length; i < ln; i++) {
  5455. name = names[i];
  5456. updaterName = 'update' + Ext.String.capitalize(name);
  5457. updater = this[updaterName] || Ext.emptyFn;
  5458. newUpdater = function() {
  5459. updater.apply(this, arguments);
  5460. scope[callback].apply(scope, arguments);
  5461. };
  5462. newUpdater.$name = updaterName;
  5463. newUpdater.$owner = self;
  5464. this[updaterName] = newUpdater;
  5465. }
  5466. },
  5467. destroy: function() {
  5468. this.destroy = Ext.emptyFn;
  5469. }
  5470. });
  5471. /**
  5472. * Call the original method that was previously overridden with {@link Ext.Base#override}
  5473. *
  5474. * Ext.define('My.Cat', {
  5475. * constructor: function() {
  5476. * alert("I'm a cat!");
  5477. * }
  5478. * });
  5479. *
  5480. * My.Cat.override({
  5481. * constructor: function() {
  5482. * alert("I'm going to be a cat!");
  5483. *
  5484. * var instance = this.callOverridden();
  5485. *
  5486. * alert("Meeeeoooowwww");
  5487. *
  5488. * return instance;
  5489. * }
  5490. * });
  5491. *
  5492. * var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
  5493. * // alerts "I'm a cat!"
  5494. * // alerts "Meeeeoooowwww"
  5495. *
  5496. * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
  5497. * from the current method, for example: `this.callOverridden(arguments)`
  5498. * @return {Object} Returns the result of calling the overridden method
  5499. * @protected
  5500. * @deprecated as of 4.1. Use {@link #callParent} instead.
  5501. */
  5502. Base.prototype.callOverridden = Base.prototype.callParent;
  5503. Ext.Base = Base;
  5504. })(Ext.Function.flexSetter);
  5505. /**
  5506. * @author Jacky Nguyen <jacky@sencha.com>
  5507. * @docauthor Jacky Nguyen <jacky@sencha.com>
  5508. * @class Ext.Class
  5509. *
  5510. * Handles class creation throughout the framework. This is a low level factory that is used by Ext.ClassManager and generally
  5511. * should not be used directly. If you choose to use Ext.Class you will lose out on the namespace, aliasing and depency loading
  5512. * features made available by Ext.ClassManager. The only time you would use Ext.Class directly is to create an anonymous class.
  5513. *
  5514. * If you wish to create a class you should use {@link Ext#define Ext.define} which aliases
  5515. * {@link Ext.ClassManager#create Ext.ClassManager.create} to enable namespacing and dynamic dependency resolution.
  5516. *
  5517. * Ext.Class is the factory and **not** the superclass of everything. For the base class that **all** Ext classes inherit
  5518. * from, see {@link Ext.Base}.
  5519. */
  5520. (function() {
  5521. var ExtClass,
  5522. Base = Ext.Base,
  5523. baseStaticMembers = [],
  5524. baseStaticMember, baseStaticMemberLength;
  5525. for (baseStaticMember in Base) {
  5526. if (Base.hasOwnProperty(baseStaticMember)) {
  5527. baseStaticMembers.push(baseStaticMember);
  5528. }
  5529. }
  5530. baseStaticMemberLength = baseStaticMembers.length;
  5531. // Creates a constructor that has nothing extra in its scope chain.
  5532. function makeCtor (className) {
  5533. function constructor () {
  5534. return this.constructor.apply(this, arguments);
  5535. };
  5536. return constructor;
  5537. }
  5538. /**
  5539. * @method constructor
  5540. * Create a new anonymous class.
  5541. *
  5542. * @param {Object} data An object represent the properties of this class
  5543. * @param {Function} onCreated Optional, the callback function to be executed when this class is fully created.
  5544. * Note that the creation process can be asynchronous depending on the pre-processors used.
  5545. *
  5546. * @return {Ext.Base} The newly created class
  5547. */
  5548. Ext.Class = ExtClass = function(Class, data, onCreated) {
  5549. if (typeof Class != 'function') {
  5550. onCreated = data;
  5551. data = Class;
  5552. Class = null;
  5553. }
  5554. if (!data) {
  5555. data = {};
  5556. }
  5557. Class = ExtClass.create(Class, data);
  5558. ExtClass.process(Class, data, onCreated);
  5559. return Class;
  5560. };
  5561. Ext.apply(ExtClass, {
  5562. /**
  5563. * @private
  5564. * @param Class
  5565. * @param data
  5566. * @param hooks
  5567. */
  5568. onBeforeCreated: function(Class, data, hooks) {
  5569. Class.addMembers(data);
  5570. hooks.onCreated.call(Class, Class);
  5571. },
  5572. /**
  5573. * @private
  5574. * @param Class
  5575. * @param classData
  5576. * @param onClassCreated
  5577. */
  5578. create: function(Class, data) {
  5579. var name, i;
  5580. if (!Class) {
  5581. // This "helped" a bit in IE8 when we create 450k instances (3400ms->2700ms),
  5582. // but removes some flexibility as a result because overrides cannot override
  5583. // the constructor method... kept in case we want to reconsider because it is
  5584. // more involved than just use the pass 'constructor'
  5585. //
  5586. //if (data.hasOwnProperty('constructor')) {
  5587. // Class = data.constructor;
  5588. // delete data.constructor;
  5589. // Class.$owner = Class;
  5590. // Class.$name = 'constructor';
  5591. //} else {
  5592. Class = makeCtor(
  5593. );
  5594. //}
  5595. }
  5596. for (i = 0; i < baseStaticMemberLength; i++) {
  5597. name = baseStaticMembers[i];
  5598. Class[name] = Base[name];
  5599. }
  5600. return Class;
  5601. },
  5602. /**
  5603. * @private
  5604. * @param Class
  5605. * @param data
  5606. * @param onCreated
  5607. */
  5608. process: function(Class, data, onCreated) {
  5609. var preprocessorStack = data.preprocessors || ExtClass.defaultPreprocessors,
  5610. registeredPreprocessors = this.preprocessors,
  5611. hooks = {
  5612. onBeforeCreated: this.onBeforeCreated
  5613. },
  5614. preprocessors = [],
  5615. preprocessor, preprocessorsProperties,
  5616. i, ln, j, subLn, preprocessorProperty, process;
  5617. delete data.preprocessors;
  5618. for (i = 0,ln = preprocessorStack.length; i < ln; i++) {
  5619. preprocessor = preprocessorStack[i];
  5620. if (typeof preprocessor == 'string') {
  5621. preprocessor = registeredPreprocessors[preprocessor];
  5622. preprocessorsProperties = preprocessor.properties;
  5623. if (preprocessorsProperties === true) {
  5624. preprocessors.push(preprocessor.fn);
  5625. }
  5626. else if (preprocessorsProperties) {
  5627. for (j = 0,subLn = preprocessorsProperties.length; j < subLn; j++) {
  5628. preprocessorProperty = preprocessorsProperties[j];
  5629. if (data.hasOwnProperty(preprocessorProperty)) {
  5630. preprocessors.push(preprocessor.fn);
  5631. break;
  5632. }
  5633. }
  5634. }
  5635. }
  5636. else {
  5637. preprocessors.push(preprocessor);
  5638. }
  5639. }
  5640. hooks.onCreated = onCreated ? onCreated : Ext.emptyFn;
  5641. hooks.preprocessors = preprocessors;
  5642. this.doProcess(Class, data, hooks);
  5643. },
  5644. doProcess: function(Class, data, hooks){
  5645. var me = this,
  5646. preprocessor = hooks.preprocessors.shift();
  5647. if (!preprocessor) {
  5648. hooks.onBeforeCreated.apply(me, arguments);
  5649. return;
  5650. }
  5651. if (preprocessor.call(me, Class, data, hooks, me.doProcess) !== false) {
  5652. me.doProcess(Class, data, hooks);
  5653. }
  5654. },
  5655. /** @private */
  5656. preprocessors: {},
  5657. /**
  5658. * Register a new pre-processor to be used during the class creation process
  5659. *
  5660. * @param {String} name The pre-processor's name
  5661. * @param {Function} fn The callback function to be executed. Typical format:
  5662. *
  5663. * function(cls, data, fn) {
  5664. * // Your code here
  5665. *
  5666. * // Execute this when the processing is finished.
  5667. * // Asynchronous processing is perfectly ok
  5668. * if (fn) {
  5669. * fn.call(this, cls, data);
  5670. * }
  5671. * });
  5672. *
  5673. * @param {Function} fn.cls The created class
  5674. * @param {Object} fn.data The set of properties passed in {@link Ext.Class} constructor
  5675. * @param {Function} fn.fn The callback function that **must** to be executed when this
  5676. * pre-processor finishes, regardless of whether the processing is synchronous or aynchronous.
  5677. * @return {Ext.Class} this
  5678. * @private
  5679. * @static
  5680. */
  5681. registerPreprocessor: function(name, fn, properties, position, relativeTo) {
  5682. if (!position) {
  5683. position = 'last';
  5684. }
  5685. if (!properties) {
  5686. properties = [name];
  5687. }
  5688. this.preprocessors[name] = {
  5689. name: name,
  5690. properties: properties || false,
  5691. fn: fn
  5692. };
  5693. this.setDefaultPreprocessorPosition(name, position, relativeTo);
  5694. return this;
  5695. },
  5696. /**
  5697. * Retrieve a pre-processor callback function by its name, which has been registered before
  5698. *
  5699. * @param {String} name
  5700. * @return {Function} preprocessor
  5701. * @private
  5702. * @static
  5703. */
  5704. getPreprocessor: function(name) {
  5705. return this.preprocessors[name];
  5706. },
  5707. /**
  5708. * @private
  5709. */
  5710. getPreprocessors: function() {
  5711. return this.preprocessors;
  5712. },
  5713. /**
  5714. * @private
  5715. */
  5716. defaultPreprocessors: [],
  5717. /**
  5718. * Retrieve the array stack of default pre-processors
  5719. * @return {Function[]} defaultPreprocessors
  5720. * @private
  5721. * @static
  5722. */
  5723. getDefaultPreprocessors: function() {
  5724. return this.defaultPreprocessors;
  5725. },
  5726. /**
  5727. * Set the default array stack of default pre-processors
  5728. *
  5729. * @private
  5730. * @param {Array} preprocessors
  5731. * @return {Ext.Class} this
  5732. * @static
  5733. */
  5734. setDefaultPreprocessors: function(preprocessors) {
  5735. this.defaultPreprocessors = Ext.Array.from(preprocessors);
  5736. return this;
  5737. },
  5738. /**
  5739. * Insert this pre-processor at a specific position in the stack, optionally relative to
  5740. * any existing pre-processor. For example:
  5741. *
  5742. * Ext.Class.registerPreprocessor('debug', function(cls, data, fn) {
  5743. * // Your code here
  5744. *
  5745. * if (fn) {
  5746. * fn.call(this, cls, data);
  5747. * }
  5748. * }).setDefaultPreprocessorPosition('debug', 'last');
  5749. *
  5750. * @private
  5751. * @param {String} name The pre-processor name. Note that it needs to be registered with
  5752. * {@link Ext#registerPreprocessor registerPreprocessor} before this
  5753. * @param {String} offset The insertion position. Four possible values are:
  5754. * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument)
  5755. * @param {String} relativeName
  5756. * @return {Ext.Class} this
  5757. * @static
  5758. */
  5759. setDefaultPreprocessorPosition: function(name, offset, relativeName) {
  5760. var defaultPreprocessors = this.defaultPreprocessors,
  5761. index;
  5762. if (typeof offset == 'string') {
  5763. if (offset === 'first') {
  5764. defaultPreprocessors.unshift(name);
  5765. return this;
  5766. }
  5767. else if (offset === 'last') {
  5768. defaultPreprocessors.push(name);
  5769. return this;
  5770. }
  5771. offset = (offset === 'after') ? 1 : -1;
  5772. }
  5773. index = Ext.Array.indexOf(defaultPreprocessors, relativeName);
  5774. if (index !== -1) {
  5775. Ext.Array.splice(defaultPreprocessors, Math.max(0, index + offset), 0, name);
  5776. }
  5777. return this;
  5778. },
  5779. configNameCache: {},
  5780. getConfigNameMap: function(name) {
  5781. var cache = this.configNameCache,
  5782. map = cache[name],
  5783. capitalizedName;
  5784. if (!map) {
  5785. capitalizedName = name.charAt(0).toUpperCase() + name.substr(1);
  5786. map = cache[name] = {
  5787. internal: name,
  5788. initialized: '_is' + capitalizedName + 'Initialized',
  5789. apply: 'apply' + capitalizedName,
  5790. update: 'update' + capitalizedName,
  5791. 'set': 'set' + capitalizedName,
  5792. 'get': 'get' + capitalizedName,
  5793. doSet : 'doSet' + capitalizedName,
  5794. changeEvent: name.toLowerCase() + 'change'
  5795. }
  5796. }
  5797. return map;
  5798. }
  5799. });
  5800. /**
  5801. * @cfg {String} extend
  5802. * The parent class that this class extends. For example:
  5803. *
  5804. * Ext.define('Person', {
  5805. * say: function(text) { alert(text); }
  5806. * });
  5807. *
  5808. * Ext.define('Developer', {
  5809. * extend: 'Person',
  5810. * say: function(text) { this.callParent(["print "+text]); }
  5811. * });
  5812. */
  5813. ExtClass.registerPreprocessor('extend', function(Class, data) {
  5814. var Base = Ext.Base,
  5815. basePrototype = Base.prototype,
  5816. extend = data.extend,
  5817. Parent, parentPrototype, i;
  5818. delete data.extend;
  5819. if (extend && extend !== Object) {
  5820. Parent = extend;
  5821. }
  5822. else {
  5823. Parent = Base;
  5824. }
  5825. parentPrototype = Parent.prototype;
  5826. if (!Parent.$isClass) {
  5827. for (i in basePrototype) {
  5828. if (!parentPrototype[i]) {
  5829. parentPrototype[i] = basePrototype[i];
  5830. }
  5831. }
  5832. }
  5833. Class.extend(Parent);
  5834. Class.triggerExtended.apply(Class, arguments);
  5835. if (data.onClassExtended) {
  5836. Class.onExtended(data.onClassExtended);
  5837. delete data.onClassExtended;
  5838. }
  5839. }, true);
  5840. /**
  5841. * @cfg {Object} statics
  5842. * List of static methods for this class. For example:
  5843. *
  5844. * Ext.define('Computer', {
  5845. * statics: {
  5846. * factory: function(brand) {
  5847. * // 'this' in static methods refer to the class itself
  5848. * return new this(brand);
  5849. * }
  5850. * },
  5851. *
  5852. * constructor: function() { ... }
  5853. * });
  5854. *
  5855. * var dellComputer = Computer.factory('Dell');
  5856. */
  5857. ExtClass.registerPreprocessor('statics', function(Class, data) {
  5858. Class.addStatics(data.statics);
  5859. delete data.statics;
  5860. });
  5861. /**
  5862. * @cfg {Object} inheritableStatics
  5863. * List of inheritable static methods for this class.
  5864. * Otherwise just like {@link #statics} but subclasses inherit these methods.
  5865. */
  5866. ExtClass.registerPreprocessor('inheritableStatics', function(Class, data) {
  5867. Class.addInheritableStatics(data.inheritableStatics);
  5868. delete data.inheritableStatics;
  5869. });
  5870. /**
  5871. * @cfg {Object} config
  5872. * List of configuration options with their default values, for which automatically
  5873. * accessor methods are generated. For example:
  5874. *
  5875. * Ext.define('SmartPhone', {
  5876. * config: {
  5877. * hasTouchScreen: false,
  5878. * operatingSystem: 'Other',
  5879. * price: 500
  5880. * },
  5881. * constructor: function(cfg) {
  5882. * this.initConfig(cfg);
  5883. * }
  5884. * });
  5885. *
  5886. * var iPhone = new SmartPhone({
  5887. * hasTouchScreen: true,
  5888. * operatingSystem: 'iOS'
  5889. * });
  5890. *
  5891. * iPhone.getPrice(); // 500;
  5892. * iPhone.getOperatingSystem(); // 'iOS'
  5893. * iPhone.getHasTouchScreen(); // true;
  5894. */
  5895. ExtClass.registerPreprocessor('config', function(Class, data) {
  5896. var config = data.config,
  5897. prototype = Class.prototype;
  5898. delete data.config;
  5899. Ext.Object.each(config, function(name, value) {
  5900. var nameMap = ExtClass.getConfigNameMap(name),
  5901. internalName = nameMap.internal,
  5902. initializedName = nameMap.initialized,
  5903. applyName = nameMap.apply,
  5904. updateName = nameMap.update,
  5905. setName = nameMap.set,
  5906. getName = nameMap.get,
  5907. hasOwnSetter = (setName in prototype) || data.hasOwnProperty(setName),
  5908. hasOwnApplier = (applyName in prototype) || data.hasOwnProperty(applyName),
  5909. hasOwnUpdater = (updateName in prototype) || data.hasOwnProperty(updateName),
  5910. optimizedGetter, customGetter;
  5911. if (value === null || (!hasOwnSetter && !hasOwnApplier && !hasOwnUpdater)) {
  5912. prototype[internalName] = value;
  5913. prototype[initializedName] = true;
  5914. }
  5915. else {
  5916. prototype[initializedName] = false;
  5917. }
  5918. if (!hasOwnSetter) {
  5919. data[setName] = function(value) {
  5920. var oldValue = this[internalName],
  5921. applier = this[applyName],
  5922. updater = this[updateName];
  5923. if (!this[initializedName]) {
  5924. this[initializedName] = true;
  5925. }
  5926. if (applier) {
  5927. value = applier.call(this, value, oldValue);
  5928. }
  5929. if (typeof value != 'undefined') {
  5930. this[internalName] = value;
  5931. if (updater && value !== oldValue) {
  5932. updater.call(this, value, oldValue);
  5933. }
  5934. }
  5935. return this;
  5936. }
  5937. }
  5938. if (!(getName in prototype) || data.hasOwnProperty(getName)) {
  5939. customGetter = data[getName] || false;
  5940. if (customGetter) {
  5941. optimizedGetter = function() {
  5942. return customGetter.apply(this, arguments);
  5943. };
  5944. }
  5945. else {
  5946. optimizedGetter = function() {
  5947. return this[internalName];
  5948. };
  5949. }
  5950. data[getName] = function() {
  5951. var currentGetter;
  5952. if (!this[initializedName]) {
  5953. this[initializedName] = true;
  5954. this[setName](this.config[name]);
  5955. }
  5956. currentGetter = this[getName];
  5957. if ('$previous' in currentGetter) {
  5958. currentGetter.$previous = optimizedGetter;
  5959. }
  5960. else {
  5961. this[getName] = optimizedGetter;
  5962. }
  5963. return optimizedGetter.apply(this, arguments);
  5964. };
  5965. }
  5966. });
  5967. Class.addConfig(config, true);
  5968. });
  5969. /**
  5970. * @cfg {String[]/Object} mixins
  5971. * List of classes to mix into this class. For example:
  5972. *
  5973. * Ext.define('CanSing', {
  5974. * sing: function() {
  5975. * alert("I'm on the highway to hell...")
  5976. * }
  5977. * });
  5978. *
  5979. * Ext.define('Musician', {
  5980. * mixins: ['CanSing']
  5981. * })
  5982. *
  5983. * In this case the Musician class will get a `sing` method from CanSing mixin.
  5984. *
  5985. * But what if the Musician already has a `sing` method? Or you want to mix
  5986. * in two classes, both of which define `sing`? In such a cases it's good
  5987. * to define mixins as an object, where you assign a name to each mixin:
  5988. *
  5989. * Ext.define('Musician', {
  5990. * mixins: {
  5991. * canSing: 'CanSing'
  5992. * },
  5993. *
  5994. * sing: function() {
  5995. * // delegate singing operation to mixin
  5996. * this.mixins.canSing.sing.call(this);
  5997. * }
  5998. * })
  5999. *
  6000. * In this case the `sing` method of Musician will overwrite the
  6001. * mixed in `sing` method. But you can access the original mixed in method
  6002. * through special `mixins` property.
  6003. */
  6004. ExtClass.registerPreprocessor('mixins', function(Class, data, hooks) {
  6005. var mixins = data.mixins,
  6006. name, mixin, i, ln;
  6007. delete data.mixins;
  6008. Ext.Function.interceptBefore(hooks, 'onCreated', function() {
  6009. if (mixins instanceof Array) {
  6010. for (i = 0,ln = mixins.length; i < ln; i++) {
  6011. mixin = mixins[i];
  6012. name = mixin.prototype.mixinId || mixin.$className;
  6013. Class.mixin(name, mixin);
  6014. }
  6015. }
  6016. else {
  6017. for (name in mixins) {
  6018. if (mixins.hasOwnProperty(name)) {
  6019. Class.mixin(name, mixins[name]);
  6020. }
  6021. }
  6022. }
  6023. });
  6024. });
  6025. // Backwards compatible
  6026. Ext.extend = function(Class, Parent, members) {
  6027. if (arguments.length === 2 && Ext.isObject(Parent)) {
  6028. members = Parent;
  6029. Parent = Class;
  6030. Class = null;
  6031. }
  6032. var cls;
  6033. if (!Parent) {
  6034. throw new Error("[Ext.extend] Attempting to extend from a class which has not been loaded on the page.");
  6035. }
  6036. members.extend = Parent;
  6037. members.preprocessors = [
  6038. 'extend'
  6039. ,'statics'
  6040. ,'inheritableStatics'
  6041. ,'mixins'
  6042. ,'config'
  6043. ];
  6044. if (Class) {
  6045. cls = new ExtClass(Class, members);
  6046. }
  6047. else {
  6048. cls = new ExtClass(members);
  6049. }
  6050. cls.prototype.override = function(o) {
  6051. for (var m in o) {
  6052. if (o.hasOwnProperty(m)) {
  6053. this[m] = o[m];
  6054. }
  6055. }
  6056. };
  6057. return cls;
  6058. };
  6059. })();
  6060. /**
  6061. * @author Jacky Nguyen <jacky@sencha.com>
  6062. * @docauthor Jacky Nguyen <jacky@sencha.com>
  6063. * @class Ext.ClassManager
  6064. *
  6065. * Ext.ClassManager manages all classes and handles mapping from string class name to
  6066. * actual class objects throughout the whole framework. It is not generally accessed directly, rather through
  6067. * these convenient shorthands:
  6068. *
  6069. * - {@link Ext#define Ext.define}
  6070. * - {@link Ext#create Ext.create}
  6071. * - {@link Ext#widget Ext.widget}
  6072. * - {@link Ext#getClass Ext.getClass}
  6073. * - {@link Ext#getClassName Ext.getClassName}
  6074. *
  6075. * # Basic syntax:
  6076. *
  6077. * Ext.define(className, properties);
  6078. *
  6079. * in which `properties` is an object represent a collection of properties that apply to the class. See
  6080. * {@link Ext.ClassManager#create} for more detailed instructions.
  6081. *
  6082. * Ext.define('Person', {
  6083. * name: 'Unknown',
  6084. *
  6085. * constructor: function(name) {
  6086. * if (name) {
  6087. * this.name = name;
  6088. * }
  6089. *
  6090. * return this;
  6091. * },
  6092. *
  6093. * eat: function(foodType) {
  6094. * alert("I'm eating: " + foodType);
  6095. *
  6096. * return this;
  6097. * }
  6098. * });
  6099. *
  6100. * var aaron = new Person("Aaron");
  6101. * aaron.eat("Sandwich"); // alert("I'm eating: Sandwich");
  6102. *
  6103. * Ext.Class has a powerful set of extensible {@link Ext.Class#registerPreprocessor pre-processors} which takes care of
  6104. * everything related to class creation, including but not limited to inheritance, mixins, configuration, statics, etc.
  6105. *
  6106. * # Inheritance:
  6107. *
  6108. * Ext.define('Developer', {
  6109. * extend: 'Person',
  6110. *
  6111. * constructor: function(name, isGeek) {
  6112. * this.isGeek = isGeek;
  6113. *
  6114. * // Apply a method from the parent class' prototype
  6115. * this.callParent([name]);
  6116. *
  6117. * return this;
  6118. *
  6119. * },
  6120. *
  6121. * code: function(language) {
  6122. * alert("I'm coding in: " + language);
  6123. *
  6124. * this.eat("Bugs");
  6125. *
  6126. * return this;
  6127. * }
  6128. * });
  6129. *
  6130. * var jacky = new Developer("Jacky", true);
  6131. * jacky.code("JavaScript"); // alert("I'm coding in: JavaScript");
  6132. * // alert("I'm eating: Bugs");
  6133. *
  6134. * See {@link Ext.Base#callParent} for more details on calling superclass' methods
  6135. *
  6136. * # Mixins:
  6137. *
  6138. * Ext.define('CanPlayGuitar', {
  6139. * playGuitar: function() {
  6140. * alert("F#...G...D...A");
  6141. * }
  6142. * });
  6143. *
  6144. * Ext.define('CanComposeSongs', {
  6145. * composeSongs: function() { ... }
  6146. * });
  6147. *
  6148. * Ext.define('CanSing', {
  6149. * sing: function() {
  6150. * alert("I'm on the highway to hell...")
  6151. * }
  6152. * });
  6153. *
  6154. * Ext.define('Musician', {
  6155. * extend: 'Person',
  6156. *
  6157. * mixins: {
  6158. * canPlayGuitar: 'CanPlayGuitar',
  6159. * canComposeSongs: 'CanComposeSongs',
  6160. * canSing: 'CanSing'
  6161. * }
  6162. * })
  6163. *
  6164. * Ext.define('CoolPerson', {
  6165. * extend: 'Person',
  6166. *
  6167. * mixins: {
  6168. * canPlayGuitar: 'CanPlayGuitar',
  6169. * canSing: 'CanSing'
  6170. * },
  6171. *
  6172. * sing: function() {
  6173. * alert("Ahem....");
  6174. *
  6175. * this.mixins.canSing.sing.call(this);
  6176. *
  6177. * alert("[Playing guitar at the same time...]");
  6178. *
  6179. * this.playGuitar();
  6180. * }
  6181. * });
  6182. *
  6183. * var me = new CoolPerson("Jacky");
  6184. *
  6185. * me.sing(); // alert("Ahem...");
  6186. * // alert("I'm on the highway to hell...");
  6187. * // alert("[Playing guitar at the same time...]");
  6188. * // alert("F#...G...D...A");
  6189. *
  6190. * # Config:
  6191. *
  6192. * Ext.define('SmartPhone', {
  6193. * config: {
  6194. * hasTouchScreen: false,
  6195. * operatingSystem: 'Other',
  6196. * price: 500
  6197. * },
  6198. *
  6199. * isExpensive: false,
  6200. *
  6201. * constructor: function(config) {
  6202. * this.initConfig(config);
  6203. *
  6204. * return this;
  6205. * },
  6206. *
  6207. * applyPrice: function(price) {
  6208. * this.isExpensive = (price > 500);
  6209. *
  6210. * return price;
  6211. * },
  6212. *
  6213. * applyOperatingSystem: function(operatingSystem) {
  6214. * if (!(/^(iOS|Android|BlackBerry)$/i).test(operatingSystem)) {
  6215. * return 'Other';
  6216. * }
  6217. *
  6218. * return operatingSystem;
  6219. * }
  6220. * });
  6221. *
  6222. * var iPhone = new SmartPhone({
  6223. * hasTouchScreen: true,
  6224. * operatingSystem: 'iOS'
  6225. * });
  6226. *
  6227. * iPhone.getPrice(); // 500;
  6228. * iPhone.getOperatingSystem(); // 'iOS'
  6229. * iPhone.getHasTouchScreen(); // true;
  6230. * iPhone.hasTouchScreen(); // true
  6231. *
  6232. * iPhone.isExpensive; // false;
  6233. * iPhone.setPrice(600);
  6234. * iPhone.getPrice(); // 600
  6235. * iPhone.isExpensive; // true;
  6236. *
  6237. * iPhone.setOperatingSystem('AlienOS');
  6238. * iPhone.getOperatingSystem(); // 'Other'
  6239. *
  6240. * # Statics:
  6241. *
  6242. * Ext.define('Computer', {
  6243. * statics: {
  6244. * factory: function(brand) {
  6245. * // 'this' in static methods refer to the class itself
  6246. * return new this(brand);
  6247. * }
  6248. * },
  6249. *
  6250. * constructor: function() { ... }
  6251. * });
  6252. *
  6253. * var dellComputer = Computer.factory('Dell');
  6254. *
  6255. * Also see {@link Ext.Base#statics} and {@link Ext.Base#self} for more details on accessing
  6256. * static properties within class methods
  6257. *
  6258. * @singleton
  6259. */
  6260. (function(Class, alias, arraySlice, arrayFrom, global) {
  6261. var Manager = Ext.ClassManager = {
  6262. /**
  6263. * @property {Object} classes
  6264. * All classes which were defined through the ClassManager. Keys are the
  6265. * name of the classes and the values are references to the classes.
  6266. * @private
  6267. */
  6268. classes: {},
  6269. /**
  6270. * @private
  6271. */
  6272. existCache: {},
  6273. /**
  6274. * @private
  6275. */
  6276. namespaceRewrites: [{
  6277. from: 'Ext.',
  6278. to: Ext
  6279. }],
  6280. /**
  6281. * @private
  6282. */
  6283. maps: {
  6284. alternateToName: {},
  6285. aliasToName: {},
  6286. nameToAliases: {},
  6287. nameToAlternates: {},
  6288. overridesByName: {}
  6289. },
  6290. /** @private */
  6291. enableNamespaceParseCache: true,
  6292. /** @private */
  6293. namespaceParseCache: {},
  6294. /** @private */
  6295. instantiators: [],
  6296. /**
  6297. * Checks if a class has already been created.
  6298. *
  6299. * @param {String} className
  6300. * @return {Boolean} exist
  6301. */
  6302. isCreated: function(className) {
  6303. var existCache = this.existCache,
  6304. i, ln, part, root, parts;
  6305. if (this.classes[className] || existCache[className]) {
  6306. return true;
  6307. }
  6308. root = global;
  6309. parts = this.parseNamespace(className);
  6310. for (i = 0, ln = parts.length; i < ln; i++) {
  6311. part = parts[i];
  6312. if (typeof part != 'string') {
  6313. root = part;
  6314. } else {
  6315. if (!root || !root[part]) {
  6316. return false;
  6317. }
  6318. root = root[part];
  6319. }
  6320. }
  6321. existCache[className] = true;
  6322. this.triggerCreated(className);
  6323. return true;
  6324. },
  6325. /**
  6326. * @private
  6327. */
  6328. createdListeners: [],
  6329. /**
  6330. * @private
  6331. */
  6332. nameCreatedListeners: {},
  6333. /**
  6334. * @private
  6335. */
  6336. triggerCreated: function(className) {
  6337. var listeners = this.createdListeners,
  6338. nameListeners = this.nameCreatedListeners,
  6339. i, ln, listener;
  6340. for (i = 0,ln = listeners.length; i < ln; i++) {
  6341. listener = listeners[i];
  6342. listener.fn.call(listener.scope, className);
  6343. }
  6344. listeners = nameListeners[className];
  6345. if (listeners) {
  6346. for (i = 0,ln = listeners.length; i < ln; i++) {
  6347. listener = listeners[i];
  6348. listener.fn.call(listener.scope, className);
  6349. }
  6350. delete nameListeners[className];
  6351. }
  6352. },
  6353. /**
  6354. * @private
  6355. */
  6356. onCreated: function(fn, scope, className) {
  6357. var listeners = this.createdListeners,
  6358. nameListeners = this.nameCreatedListeners,
  6359. listener = {
  6360. fn: fn,
  6361. scope: scope
  6362. };
  6363. if (className) {
  6364. if (this.isCreated(className)) {
  6365. fn.call(scope, className);
  6366. return;
  6367. }
  6368. if (!nameListeners[className]) {
  6369. nameListeners[className] = [];
  6370. }
  6371. nameListeners[className].push(listener);
  6372. }
  6373. else {
  6374. listeners.push(listener);
  6375. }
  6376. },
  6377. /**
  6378. * Supports namespace rewriting
  6379. * @private
  6380. */
  6381. parseNamespace: function(namespace) {
  6382. var cache = this.namespaceParseCache;
  6383. if (this.enableNamespaceParseCache) {
  6384. if (cache.hasOwnProperty(namespace)) {
  6385. return cache[namespace];
  6386. }
  6387. }
  6388. var parts = [],
  6389. rewrites = this.namespaceRewrites,
  6390. root = global,
  6391. name = namespace,
  6392. rewrite, from, to, i, ln;
  6393. for (i = 0, ln = rewrites.length; i < ln; i++) {
  6394. rewrite = rewrites[i];
  6395. from = rewrite.from;
  6396. to = rewrite.to;
  6397. if (name === from || name.substring(0, from.length) === from) {
  6398. name = name.substring(from.length);
  6399. if (typeof to != 'string') {
  6400. root = to;
  6401. } else {
  6402. parts = parts.concat(to.split('.'));
  6403. }
  6404. break;
  6405. }
  6406. }
  6407. parts.push(root);
  6408. parts = parts.concat(name.split('.'));
  6409. if (this.enableNamespaceParseCache) {
  6410. cache[namespace] = parts;
  6411. }
  6412. return parts;
  6413. },
  6414. /**
  6415. * Creates a namespace and assign the `value` to the created object
  6416. *
  6417. * Ext.ClassManager.setNamespace('MyCompany.pkg.Example', someObject);
  6418. *
  6419. * alert(MyCompany.pkg.Example === someObject); // alerts true
  6420. *
  6421. * @param {String} name
  6422. * @param {Object} value
  6423. */
  6424. setNamespace: function(name, value) {
  6425. var root = global,
  6426. parts = this.parseNamespace(name),
  6427. ln = parts.length - 1,
  6428. leaf = parts[ln],
  6429. i, part;
  6430. for (i = 0; i < ln; i++) {
  6431. part = parts[i];
  6432. if (typeof part != 'string') {
  6433. root = part;
  6434. } else {
  6435. if (!root[part]) {
  6436. root[part] = {};
  6437. }
  6438. root = root[part];
  6439. }
  6440. }
  6441. root[leaf] = value;
  6442. return root[leaf];
  6443. },
  6444. /**
  6445. * The new Ext.ns, supports namespace rewriting
  6446. * @private
  6447. */
  6448. createNamespaces: function() {
  6449. var root = global,
  6450. parts, part, i, j, ln, subLn;
  6451. for (i = 0, ln = arguments.length; i < ln; i++) {
  6452. parts = this.parseNamespace(arguments[i]);
  6453. for (j = 0, subLn = parts.length; j < subLn; j++) {
  6454. part = parts[j];
  6455. if (typeof part != 'string') {
  6456. root = part;
  6457. } else {
  6458. if (!root[part]) {
  6459. root[part] = {};
  6460. }
  6461. root = root[part];
  6462. }
  6463. }
  6464. }
  6465. return root;
  6466. },
  6467. /**
  6468. * Sets a name reference to a class.
  6469. *
  6470. * @param {String} name
  6471. * @param {Object} value
  6472. * @return {Ext.ClassManager} this
  6473. */
  6474. set: function(name, value) {
  6475. var me = this,
  6476. maps = me.maps,
  6477. nameToAlternates = maps.nameToAlternates,
  6478. targetName = me.getName(value),
  6479. alternates;
  6480. me.classes[name] = me.setNamespace(name, value);
  6481. if (targetName && targetName !== name) {
  6482. maps.alternateToName[name] = targetName;
  6483. alternates = nameToAlternates[targetName] || (nameToAlternates[targetName] = []);
  6484. alternates.push(name);
  6485. }
  6486. return this;
  6487. },
  6488. /**
  6489. * Retrieve a class by its name.
  6490. *
  6491. * @param {String} name
  6492. * @return {Ext.Class} class
  6493. */
  6494. get: function(name) {
  6495. var classes = this.classes;
  6496. if (classes[name]) {
  6497. return classes[name];
  6498. }
  6499. var root = global,
  6500. parts = this.parseNamespace(name),
  6501. part, i, ln;
  6502. for (i = 0, ln = parts.length; i < ln; i++) {
  6503. part = parts[i];
  6504. if (typeof part != 'string') {
  6505. root = part;
  6506. } else {
  6507. if (!root || !root[part]) {
  6508. return null;
  6509. }
  6510. root = root[part];
  6511. }
  6512. }
  6513. return root;
  6514. },
  6515. /**
  6516. * Register the alias for a class.
  6517. *
  6518. * @param {Ext.Class/String} cls a reference to a class or a className
  6519. * @param {String} alias Alias to use when referring to this class
  6520. */
  6521. setAlias: function(cls, alias) {
  6522. var aliasToNameMap = this.maps.aliasToName,
  6523. nameToAliasesMap = this.maps.nameToAliases,
  6524. className;
  6525. if (typeof cls == 'string') {
  6526. className = cls;
  6527. } else {
  6528. className = this.getName(cls);
  6529. }
  6530. if (alias && aliasToNameMap[alias] !== className) {
  6531. aliasToNameMap[alias] = className;
  6532. }
  6533. if (!nameToAliasesMap[className]) {
  6534. nameToAliasesMap[className] = [];
  6535. }
  6536. if (alias) {
  6537. Ext.Array.include(nameToAliasesMap[className], alias);
  6538. }
  6539. return this;
  6540. },
  6541. /**
  6542. * Get a reference to the class by its alias.
  6543. *
  6544. * @param {String} alias
  6545. * @return {Ext.Class} class
  6546. */
  6547. getByAlias: function(alias) {
  6548. return this.get(this.getNameByAlias(alias));
  6549. },
  6550. /**
  6551. * Get the name of a class by its alias.
  6552. *
  6553. * @param {String} alias
  6554. * @return {String} className
  6555. */
  6556. getNameByAlias: function(alias) {
  6557. return this.maps.aliasToName[alias] || '';
  6558. },
  6559. /**
  6560. * Get the name of a class by its alternate name.
  6561. *
  6562. * @param {String} alternate
  6563. * @return {String} className
  6564. */
  6565. getNameByAlternate: function(alternate) {
  6566. return this.maps.alternateToName[alternate] || '';
  6567. },
  6568. /**
  6569. * Get the aliases of a class by the class name
  6570. *
  6571. * @param {String} name
  6572. * @return {Array} aliases
  6573. */
  6574. getAliasesByName: function(name) {
  6575. return this.maps.nameToAliases[name] || [];
  6576. },
  6577. /**
  6578. * Get the name of the class by its reference or its instance;
  6579. * usually invoked by the shorthand {@link Ext#getClassName Ext.getClassName}
  6580. *
  6581. * Ext.ClassManager.getName(Ext.Action); // returns "Ext.Action"
  6582. *
  6583. * @param {Ext.Class/Object} object
  6584. * @return {String} className
  6585. */
  6586. getName: function(object) {
  6587. return object && object.$className || '';
  6588. },
  6589. /**
  6590. * Get the class of the provided object; returns null if it's not an instance
  6591. * of any class created with Ext.define. This is usually invoked by the shorthand {@link Ext#getClass Ext.getClass}
  6592. *
  6593. * var component = new Ext.Component();
  6594. *
  6595. * Ext.ClassManager.getClass(component); // returns Ext.Component
  6596. *
  6597. * @param {Object} object
  6598. * @return {Ext.Class} class
  6599. */
  6600. getClass: function(object) {
  6601. return object && object.self || null;
  6602. },
  6603. /**
  6604. * @private
  6605. */
  6606. applyOverrides: function (name) {
  6607. var me = this,
  6608. overridesByName = me.maps.overridesByName,
  6609. overrides = overridesByName[name],
  6610. length = overrides && overrides.length || 0,
  6611. createOverride = me.createOverride,
  6612. i;
  6613. delete overridesByName[name];
  6614. for (i = 0; i < length; ++i) {
  6615. createOverride.apply(me, overrides[i]);
  6616. }
  6617. },
  6618. /**
  6619. * Defines a class.
  6620. * @deprecated 4.1.0 Use {@link Ext#define} instead, as that also supports creating overrides.
  6621. */
  6622. create: function(className, data, createdFn) {
  6623. data.$className = className;
  6624. return new Class(data, function() {
  6625. var postprocessorStack = data.postprocessors || Manager.defaultPostprocessors,
  6626. registeredPostprocessors = Manager.postprocessors,
  6627. postprocessors = [],
  6628. postprocessor, i, ln, j, subLn, postprocessorProperties, postprocessorProperty,
  6629. alternateNames;
  6630. delete data.postprocessors;
  6631. for (i = 0,ln = postprocessorStack.length; i < ln; i++) {
  6632. postprocessor = postprocessorStack[i];
  6633. if (typeof postprocessor == 'string') {
  6634. postprocessor = registeredPostprocessors[postprocessor];
  6635. postprocessorProperties = postprocessor.properties;
  6636. if (postprocessorProperties === true) {
  6637. postprocessors.push(postprocessor.fn);
  6638. }
  6639. else if (postprocessorProperties) {
  6640. for (j = 0,subLn = postprocessorProperties.length; j < subLn; j++) {
  6641. postprocessorProperty = postprocessorProperties[j];
  6642. if (data.hasOwnProperty(postprocessorProperty)) {
  6643. postprocessors.push(postprocessor.fn);
  6644. break;
  6645. }
  6646. }
  6647. }
  6648. }
  6649. else {
  6650. postprocessors.push(postprocessor);
  6651. }
  6652. }
  6653. data.postprocessors = postprocessors;
  6654. data.createdFn = createdFn;
  6655. Manager.processCreate(className, this, data);
  6656. //TODO: Take this out, hook into classCreated instead
  6657. Manager.applyOverrides(className);
  6658. alternateNames = Manager.maps.nameToAlternates[className];
  6659. for (i = 0, ln = alternateNames && alternateNames.length || 0; i < ln; ++i) {
  6660. Manager.applyOverrides(alternateNames[i]);
  6661. }
  6662. });
  6663. },
  6664. processCreate: function(className, cls, clsData){
  6665. var me = this,
  6666. postprocessor = clsData.postprocessors.shift(),
  6667. createdFn = clsData.createdFn;
  6668. if (!postprocessor) {
  6669. me.set(className, cls);
  6670. if (createdFn) {
  6671. createdFn.call(cls, cls);
  6672. }
  6673. me.triggerCreated(className);
  6674. return;
  6675. }
  6676. if (postprocessor.call(me, className, cls, clsData, me.processCreate) !== false) {
  6677. me.processCreate(className, cls, clsData);
  6678. }
  6679. },
  6680. createOverride: function (overrideName, data, createdFn) {
  6681. var me = this,
  6682. className = data.override,
  6683. cls = me.get(className),
  6684. overrideBody, overridesByName, overrides;
  6685. if (cls) {
  6686. // We use a "faux class" here because it has all the mechanics we need to
  6687. // work with the loader via uses/requires and loader history (for build).
  6688. // This way we don't have to refactor any of the class-loader relationship.
  6689. // hoist any 'requires' or 'uses' from the body onto the faux class:
  6690. overrideBody = Ext.apply({}, data);
  6691. delete overrideBody.requires;
  6692. delete overrideBody.uses;
  6693. delete overrideBody.override;
  6694. me.create(overrideName, {
  6695. requires: data.requires,
  6696. uses: data.uses,
  6697. override: className
  6698. }, function () {
  6699. this.active = true;
  6700. if (cls.override) { // if (normal class)
  6701. cls.override(overrideBody);
  6702. } else { // else (singleton)
  6703. cls.self.override(overrideBody);
  6704. }
  6705. if (createdFn) {
  6706. // called once the override is applied and with the context of the
  6707. // overridden class (the override itself is a meaningless, name-only
  6708. // thing).
  6709. createdFn.call(cls);
  6710. }
  6711. });
  6712. } else {
  6713. // The class is not loaded and may never load, but in case it does we add
  6714. // the override arguments to an internal map keyed by the className. When
  6715. // (or if) the class loads, we will call this method again with those same
  6716. // arguments to complete the override.
  6717. overridesByName = me.maps.overridesByName;
  6718. overrides = overridesByName[className] || (overridesByName[className] = []);
  6719. overrides.push(Array.prototype.slice.call(arguments, 0));
  6720. // place an inactive stub in the namespace (appeases the Loader and could
  6721. // be useful diagnostically)
  6722. me.setNamespace(overrideName, {
  6723. override: className
  6724. });
  6725. }
  6726. },
  6727. /**
  6728. * Instantiate a class by its alias; usually invoked by the convenient shorthand {@link Ext#createByAlias Ext.createByAlias}
  6729. * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has not been defined yet, it will
  6730. * attempt to load the class via synchronous loading.
  6731. *
  6732. * var window = Ext.ClassManager.instantiateByAlias('widget.window', { width: 600, height: 800, ... });
  6733. *
  6734. * @param {String} alias
  6735. * @param {Object...} args Additional arguments after the alias will be passed to the
  6736. * class constructor.
  6737. * @return {Object} instance
  6738. */
  6739. instantiateByAlias: function() {
  6740. var alias = arguments[0],
  6741. args = arraySlice.call(arguments),
  6742. className = this.getNameByAlias(alias);
  6743. if (!className) {
  6744. className = this.maps.aliasToName[alias];
  6745. Ext.syncRequire(className);
  6746. }
  6747. args[0] = className;
  6748. return this.instantiate.apply(this, args);
  6749. },
  6750. /**
  6751. * @private
  6752. */
  6753. instantiate: function() {
  6754. var name = arguments[0],
  6755. nameType = typeof name,
  6756. args = arraySlice.call(arguments, 1),
  6757. alias = name,
  6758. possibleName, cls;
  6759. if (nameType != 'function') {
  6760. if (nameType != 'string' && args.length === 0) {
  6761. args = [name];
  6762. name = name.xclass;
  6763. }
  6764. cls = this.get(name);
  6765. }
  6766. else {
  6767. cls = name;
  6768. }
  6769. // No record of this class name, it's possibly an alias, so look it up
  6770. if (!cls) {
  6771. possibleName = this.getNameByAlias(name);
  6772. if (possibleName) {
  6773. name = possibleName;
  6774. cls = this.get(name);
  6775. }
  6776. }
  6777. // Still no record of this class name, it's possibly an alternate name, so look it up
  6778. if (!cls) {
  6779. possibleName = this.getNameByAlternate(name);
  6780. if (possibleName) {
  6781. name = possibleName;
  6782. cls = this.get(name);
  6783. }
  6784. }
  6785. // Still not existing at this point, try to load it via synchronous mode as the last resort
  6786. if (!cls) {
  6787. Ext.syncRequire(name);
  6788. cls = this.get(name);
  6789. }
  6790. return this.getInstantiator(args.length)(cls, args);
  6791. },
  6792. /**
  6793. * @private
  6794. * @param name
  6795. * @param args
  6796. */
  6797. dynInstantiate: function(name, args) {
  6798. args = arrayFrom(args, true);
  6799. args.unshift(name);
  6800. return this.instantiate.apply(this, args);
  6801. },
  6802. /**
  6803. * @private
  6804. * @param length
  6805. */
  6806. getInstantiator: function(length) {
  6807. var instantiators = this.instantiators,
  6808. instantiator;
  6809. instantiator = instantiators[length];
  6810. if (!instantiator) {
  6811. var i = length,
  6812. args = [];
  6813. for (i = 0; i < length; i++) {
  6814. args.push('a[' + i + ']');
  6815. }
  6816. instantiator = instantiators[length] = new Function('c', 'a', 'return new c(' + args.join(',') + ')');
  6817. }
  6818. return instantiator;
  6819. },
  6820. /**
  6821. * @private
  6822. */
  6823. postprocessors: {},
  6824. /**
  6825. * @private
  6826. */
  6827. defaultPostprocessors: [],
  6828. /**
  6829. * Register a post-processor function.
  6830. *
  6831. * @private
  6832. * @param {String} name
  6833. * @param {Function} postprocessor
  6834. */
  6835. registerPostprocessor: function(name, fn, properties, position, relativeTo) {
  6836. if (!position) {
  6837. position = 'last';
  6838. }
  6839. if (!properties) {
  6840. properties = [name];
  6841. }
  6842. this.postprocessors[name] = {
  6843. name: name,
  6844. properties: properties || false,
  6845. fn: fn
  6846. };
  6847. this.setDefaultPostprocessorPosition(name, position, relativeTo);
  6848. return this;
  6849. },
  6850. /**
  6851. * Set the default post processors array stack which are applied to every class.
  6852. *
  6853. * @private
  6854. * @param {String/Array} The name of a registered post processor or an array of registered names.
  6855. * @return {Ext.ClassManager} this
  6856. */
  6857. setDefaultPostprocessors: function(postprocessors) {
  6858. this.defaultPostprocessors = arrayFrom(postprocessors);
  6859. return this;
  6860. },
  6861. /**
  6862. * Insert this post-processor at a specific position in the stack, optionally relative to
  6863. * any existing post-processor
  6864. *
  6865. * @private
  6866. * @param {String} name The post-processor name. Note that it needs to be registered with
  6867. * {@link Ext.ClassManager#registerPostprocessor} before this
  6868. * @param {String} offset The insertion position. Four possible values are:
  6869. * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument)
  6870. * @param {String} relativeName
  6871. * @return {Ext.ClassManager} this
  6872. */
  6873. setDefaultPostprocessorPosition: function(name, offset, relativeName) {
  6874. var defaultPostprocessors = this.defaultPostprocessors,
  6875. index;
  6876. if (typeof offset == 'string') {
  6877. if (offset === 'first') {
  6878. defaultPostprocessors.unshift(name);
  6879. return this;
  6880. }
  6881. else if (offset === 'last') {
  6882. defaultPostprocessors.push(name);
  6883. return this;
  6884. }
  6885. offset = (offset === 'after') ? 1 : -1;
  6886. }
  6887. index = Ext.Array.indexOf(defaultPostprocessors, relativeName);
  6888. if (index !== -1) {
  6889. Ext.Array.splice(defaultPostprocessors, Math.max(0, index + offset), 0, name);
  6890. }
  6891. return this;
  6892. },
  6893. /**
  6894. * Converts a string expression to an array of matching class names. An expression can either refers to class aliases
  6895. * or class names. Expressions support wildcards:
  6896. *
  6897. * // returns ['Ext.window.Window']
  6898. * var window = Ext.ClassManager.getNamesByExpression('widget.window');
  6899. *
  6900. * // returns ['widget.panel', 'widget.window', ...]
  6901. * var allWidgets = Ext.ClassManager.getNamesByExpression('widget.*');
  6902. *
  6903. * // returns ['Ext.data.Store', 'Ext.data.ArrayProxy', ...]
  6904. * var allData = Ext.ClassManager.getNamesByExpression('Ext.data.*');
  6905. *
  6906. * @param {String} expression
  6907. * @return {String[]} classNames
  6908. */
  6909. getNamesByExpression: function(expression) {
  6910. var nameToAliasesMap = this.maps.nameToAliases,
  6911. names = [],
  6912. name, alias, aliases, possibleName, regex, i, ln;
  6913. if (expression.indexOf('*') !== -1) {
  6914. expression = expression.replace(/\*/g, '(.*?)');
  6915. regex = new RegExp('^' + expression + '$');
  6916. for (name in nameToAliasesMap) {
  6917. if (nameToAliasesMap.hasOwnProperty(name)) {
  6918. aliases = nameToAliasesMap[name];
  6919. if (name.search(regex) !== -1) {
  6920. names.push(name);
  6921. }
  6922. else {
  6923. for (i = 0, ln = aliases.length; i < ln; i++) {
  6924. alias = aliases[i];
  6925. if (alias.search(regex) !== -1) {
  6926. names.push(name);
  6927. break;
  6928. }
  6929. }
  6930. }
  6931. }
  6932. }
  6933. } else {
  6934. possibleName = this.getNameByAlias(expression);
  6935. if (possibleName) {
  6936. names.push(possibleName);
  6937. } else {
  6938. possibleName = this.getNameByAlternate(expression);
  6939. if (possibleName) {
  6940. names.push(possibleName);
  6941. } else {
  6942. names.push(expression);
  6943. }
  6944. }
  6945. }
  6946. return names;
  6947. }
  6948. };
  6949. /**
  6950. * @cfg {String[]} alias
  6951. * @member Ext.Class
  6952. * List of short aliases for class names. Most useful for defining xtypes for widgets:
  6953. *
  6954. * Ext.define('MyApp.CoolPanel', {
  6955. * extend: 'Ext.panel.Panel',
  6956. * alias: ['widget.coolpanel'],
  6957. * title: 'Yeah!'
  6958. * });
  6959. *
  6960. * // Using Ext.create
  6961. * Ext.create('widget.coolpanel');
  6962. *
  6963. * // Using the shorthand for defining widgets by xtype
  6964. * Ext.widget('panel', {
  6965. * items: [
  6966. * {xtype: 'coolpanel', html: 'Foo'},
  6967. * {xtype: 'coolpanel', html: 'Bar'}
  6968. * ]
  6969. * });
  6970. *
  6971. * Besides "widget" for xtype there are alias namespaces like "feature" for ftype and "plugin" for ptype.
  6972. */
  6973. Manager.registerPostprocessor('alias', function(name, cls, data) {
  6974. var aliases = data.alias,
  6975. i, ln;
  6976. for (i = 0,ln = aliases.length; i < ln; i++) {
  6977. alias = aliases[i];
  6978. this.setAlias(cls, alias);
  6979. }
  6980. }, ['xtype', 'alias']);
  6981. /**
  6982. * @cfg {Boolean} singleton
  6983. * @member Ext.Class
  6984. * When set to true, the class will be instantiated as singleton. For example:
  6985. *
  6986. * Ext.define('Logger', {
  6987. * singleton: true,
  6988. * log: function(msg) {
  6989. * console.log(msg);
  6990. * }
  6991. * });
  6992. *
  6993. * Logger.log('Hello');
  6994. */
  6995. Manager.registerPostprocessor('singleton', function(name, cls, data, fn) {
  6996. fn.call(this, name, new cls(), data);
  6997. return false;
  6998. });
  6999. /**
  7000. * @cfg {String/String[]} alternateClassName
  7001. * @member Ext.Class
  7002. * Defines alternate names for this class. For example:
  7003. *
  7004. * Ext.define('Developer', {
  7005. * alternateClassName: ['Coder', 'Hacker'],
  7006. * code: function(msg) {
  7007. * alert('Typing... ' + msg);
  7008. * }
  7009. * });
  7010. *
  7011. * var joe = Ext.create('Developer');
  7012. * joe.code('stackoverflow');
  7013. *
  7014. * var rms = Ext.create('Hacker');
  7015. * rms.code('hack hack');
  7016. */
  7017. Manager.registerPostprocessor('alternateClassName', function(name, cls, data) {
  7018. var alternates = data.alternateClassName,
  7019. i, ln, alternate;
  7020. if (!(alternates instanceof Array)) {
  7021. alternates = [alternates];
  7022. }
  7023. for (i = 0, ln = alternates.length; i < ln; i++) {
  7024. alternate = alternates[i];
  7025. this.set(alternate, cls);
  7026. }
  7027. });
  7028. Ext.apply(Ext, {
  7029. /**
  7030. * Instantiate a class by either full name, alias or alternate name.
  7031. *
  7032. * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has
  7033. * not been defined yet, it will attempt to load the class via synchronous loading.
  7034. *
  7035. * For example, all these three lines return the same result:
  7036. *
  7037. * // alias
  7038. * var window = Ext.create('widget.window', {
  7039. * width: 600,
  7040. * height: 800,
  7041. * ...
  7042. * });
  7043. *
  7044. * // alternate name
  7045. * var window = Ext.create('Ext.Window', {
  7046. * width: 600,
  7047. * height: 800,
  7048. * ...
  7049. * });
  7050. *
  7051. * // full class name
  7052. * var window = Ext.create('Ext.window.Window', {
  7053. * width: 600,
  7054. * height: 800,
  7055. * ...
  7056. * });
  7057. *
  7058. * // single object with xclass property:
  7059. * var window = Ext.create({
  7060. * xclass: 'Ext.window.Window', // any valid value for 'name' (above)
  7061. * width: 600,
  7062. * height: 800,
  7063. * ...
  7064. * });
  7065. *
  7066. * @param {String} [name] The class name or alias. Can be specified as `xclass`
  7067. * property if only one object parameter is specified.
  7068. * @param {Object...} [args] Additional arguments after the name will be passed to
  7069. * the class' constructor.
  7070. * @return {Object} instance
  7071. * @member Ext
  7072. * @method create
  7073. */
  7074. create: alias(Manager, 'instantiate'),
  7075. /**
  7076. * Convenient shorthand to create a widget by its xtype or a config object.
  7077. * See also {@link Ext.ClassManager#instantiateByAlias}.
  7078. *
  7079. * var button = Ext.widget('button'); // Equivalent to Ext.create('widget.button');
  7080. *
  7081. * var panel = Ext.widget('panel', { // Equivalent to Ext.create('widget.panel')
  7082. * title: 'Panel'
  7083. * });
  7084. *
  7085. * var grid = Ext.widget({
  7086. * xtype: 'grid',
  7087. * ...
  7088. * });
  7089. *
  7090. * If a {@link Ext.Component component} instance is passed, it is simply returned.
  7091. *
  7092. * @member Ext
  7093. * @param {String} [name] The xtype of the widget to create.
  7094. * @param {Object} [config] The configuration object for the widget constructor.
  7095. * @return {Object} The widget instance
  7096. */
  7097. widget: function(name, config) {
  7098. // forms:
  7099. // 1: (xtype)
  7100. // 2: (xtype, config)
  7101. // 3: (config)
  7102. // 4: (xtype, component)
  7103. // 5: (component)
  7104. //
  7105. var xtype = name,
  7106. alias, className, T, load;
  7107. if (typeof xtype != 'string') { // if (form 3 or 5)
  7108. // first arg is config or component
  7109. config = name; // arguments[0]
  7110. if (config.isComponent) {
  7111. return config;
  7112. }
  7113. xtype = config.xtype;
  7114. }
  7115. alias = 'widget.' + xtype;
  7116. className = Manager.getNameByAlias(alias);
  7117. // this is needed to support demand loading of the class
  7118. if (!className) {
  7119. load = true;
  7120. }
  7121. T = Manager.get(className);
  7122. if (load || !T) {
  7123. return Manager.instantiateByAlias(alias, config || {});
  7124. }
  7125. return new T(config);
  7126. },
  7127. /**
  7128. * Convenient shorthand, see {@link Ext.ClassManager#instantiateByAlias}
  7129. * @member Ext
  7130. * @method createByAlias
  7131. */
  7132. createByAlias: alias(Manager, 'instantiateByAlias'),
  7133. /**
  7134. * @method
  7135. * Defines a class or override. A basic class is defined like this:
  7136. *
  7137. * Ext.define('My.awesome.Class', {
  7138. * someProperty: 'something',
  7139. *
  7140. * someMethod: function() {
  7141. * alert(s + this.someProperty);
  7142. * }
  7143. *
  7144. * ...
  7145. * });
  7146. *
  7147. * var obj = new My.awesome.Class();
  7148. *
  7149. * obj.someMethod('Say '); // alerts 'Say something'
  7150. *
  7151. * To defines an override, include the `override` property. The content of an
  7152. * override is aggregated with the specified class in order to extend or modify
  7153. * that class. This can be as simple as setting default property values or it can
  7154. * extend and/or replace methods. This can also extend the statics of the class.
  7155. *
  7156. * One use for an override is to break a large class into manageable pieces.
  7157. *
  7158. * // File: /src/app/Panel.js
  7159. *
  7160. * Ext.define('My.app.Panel', {
  7161. * extend: 'Ext.panel.Panel',
  7162. * requires: [
  7163. * 'My.app.PanelPart2',
  7164. * 'My.app.PanelPart3'
  7165. * ]
  7166. *
  7167. * constructor: function (config) {
  7168. * this.callParent(arguments); // calls Ext.panel.Panel's constructor
  7169. * //...
  7170. * },
  7171. *
  7172. * statics: {
  7173. * method: function () {
  7174. * return 'abc';
  7175. * }
  7176. * }
  7177. * });
  7178. *
  7179. * // File: /src/app/PanelPart2.js
  7180. * Ext.define('My.app.PanelPart2', {
  7181. * override: 'My.app.Panel',
  7182. *
  7183. * constructor: function (config) {
  7184. * this.callParent(arguments); // calls My.app.Panel's constructor
  7185. * //...
  7186. * }
  7187. * });
  7188. *
  7189. * Another use of overrides is to provide optional parts of classes that can be
  7190. * independently required. In this case, the class may even be unaware of the
  7191. * override altogether.
  7192. *
  7193. * Ext.define('My.ux.CoolTip', {
  7194. * override: 'Ext.tip.ToolTip',
  7195. *
  7196. * constructor: function (config) {
  7197. * this.callParent(arguments); // calls Ext.tip.ToolTip's constructor
  7198. * //...
  7199. * }
  7200. * });
  7201. *
  7202. * The above override can now be required as normal.
  7203. *
  7204. * Ext.define('My.app.App', {
  7205. * requires: [
  7206. * 'My.ux.CoolTip'
  7207. * ]
  7208. * });
  7209. *
  7210. * Overrides can also contain statics:
  7211. *
  7212. * Ext.define('My.app.BarMod', {
  7213. * override: 'Ext.foo.Bar',
  7214. *
  7215. * statics: {
  7216. * method: function (x) {
  7217. * return this.callParent([x * 2]); // call Ext.foo.Bar.method
  7218. * }
  7219. * }
  7220. * });
  7221. *
  7222. * IMPORTANT: An override is only included in a build if the class it overrides is
  7223. * required. Otherwise, the override, like the target class, is not included.
  7224. *
  7225. * @param {String} className The class name to create in string dot-namespaced format, for example:
  7226. * 'My.very.awesome.Class', 'FeedViewer.plugin.CoolPager'
  7227. * It is highly recommended to follow this simple convention:
  7228. * - The root and the class name are 'CamelCased'
  7229. * - Everything else is lower-cased
  7230. * @param {Object} data The key - value pairs of properties to apply to this class. Property names can be of any valid
  7231. * strings, except those in the reserved listed below:
  7232. * - `mixins`
  7233. * - `statics`
  7234. * - `config`
  7235. * - `alias`
  7236. * - `self`
  7237. * - `singleton`
  7238. * - `alternateClassName`
  7239. * - `override`
  7240. *
  7241. * @param {Function} createdFn Optional callback to execute after the class is created, the execution scope of which
  7242. * (`this`) will be the newly created class itself.
  7243. * @return {Ext.Base}
  7244. * @markdown
  7245. * @member Ext
  7246. * @method define
  7247. */
  7248. define: function (className, data, createdFn) {
  7249. if (data.override) {
  7250. return Manager.createOverride.apply(Manager, arguments);
  7251. }
  7252. return Manager.create.apply(Manager, arguments);
  7253. },
  7254. /**
  7255. * Convenient shorthand, see {@link Ext.ClassManager#getName}
  7256. * @member Ext
  7257. * @method getClassName
  7258. */
  7259. getClassName: alias(Manager, 'getName'),
  7260. /**
  7261. * Returns the displayName property or className or object. When all else fails, returns "Anonymous".
  7262. * @param {Object} object
  7263. * @return {String}
  7264. */
  7265. getDisplayName: function(object) {
  7266. if (object) {
  7267. if (object.displayName) {
  7268. return object.displayName;
  7269. }
  7270. if (object.$name && object.$class) {
  7271. return Ext.getClassName(object.$class) + '#' + object.$name;
  7272. }
  7273. if (object.$className) {
  7274. return object.$className;
  7275. }
  7276. }
  7277. return 'Anonymous';
  7278. },
  7279. /**
  7280. * Convenient shorthand, see {@link Ext.ClassManager#getClass}
  7281. * @member Ext
  7282. * @method getClass
  7283. */
  7284. getClass: alias(Manager, 'getClass'),
  7285. /**
  7286. * Creates namespaces to be used for scoping variables and classes so that they are not global.
  7287. * Specifying the last node of a namespace implicitly creates all other nodes. Usage:
  7288. *
  7289. * Ext.namespace('Company', 'Company.data');
  7290. *
  7291. * // equivalent and preferable to the above syntax
  7292. * Ext.ns('Company.data');
  7293. *
  7294. * Company.Widget = function() { ... };
  7295. *
  7296. * Company.data.CustomStore = function(config) { ... };
  7297. *
  7298. * @param {String...} namespaces
  7299. * @return {Object} The namespace object.
  7300. * (If multiple arguments are passed, this will be the last namespace created)
  7301. * @member Ext
  7302. * @method namespace
  7303. */
  7304. namespace: alias(Manager, 'createNamespaces')
  7305. });
  7306. /**
  7307. * Old name for {@link Ext#widget}.
  7308. * @deprecated 4.0.0 Use {@link Ext#widget} instead.
  7309. * @method createWidget
  7310. * @member Ext
  7311. */
  7312. Ext.createWidget = Ext.widget;
  7313. /**
  7314. * Convenient alias for {@link Ext#namespace Ext.namespace}.
  7315. * @inheritdoc Ext#namespace
  7316. * @member Ext
  7317. * @method ns
  7318. */
  7319. Ext.ns = Ext.namespace;
  7320. Class.registerPreprocessor('className', function(cls, data) {
  7321. if (data.$className) {
  7322. cls.$className = data.$className;
  7323. }
  7324. }, true, 'first');
  7325. Class.registerPreprocessor('alias', function(cls, data) {
  7326. var prototype = cls.prototype,
  7327. xtypes = arrayFrom(data.xtype),
  7328. aliases = arrayFrom(data.alias),
  7329. widgetPrefix = 'widget.',
  7330. widgetPrefixLength = widgetPrefix.length,
  7331. xtypesChain = Array.prototype.slice.call(prototype.xtypesChain || []),
  7332. xtypesMap = Ext.merge({}, prototype.xtypesMap || {}),
  7333. i, ln, alias, xtype;
  7334. for (i = 0,ln = aliases.length; i < ln; i++) {
  7335. alias = aliases[i];
  7336. if (alias.substring(0, widgetPrefixLength) === widgetPrefix) {
  7337. xtype = alias.substring(widgetPrefixLength);
  7338. Ext.Array.include(xtypes, xtype);
  7339. }
  7340. }
  7341. cls.xtype = data.xtype = xtypes[0];
  7342. data.xtypes = xtypes;
  7343. for (i = 0,ln = xtypes.length; i < ln; i++) {
  7344. xtype = xtypes[i];
  7345. if (!xtypesMap[xtype]) {
  7346. xtypesMap[xtype] = true;
  7347. xtypesChain.push(xtype);
  7348. }
  7349. }
  7350. data.xtypesChain = xtypesChain;
  7351. data.xtypesMap = xtypesMap;
  7352. Ext.Function.interceptAfter(data, 'onClassCreated', function() {
  7353. var mixins = prototype.mixins,
  7354. key, mixin;
  7355. for (key in mixins) {
  7356. if (mixins.hasOwnProperty(key)) {
  7357. mixin = mixins[key];
  7358. xtypes = mixin.xtypes;
  7359. if (xtypes) {
  7360. for (i = 0,ln = xtypes.length; i < ln; i++) {
  7361. xtype = xtypes[i];
  7362. if (!xtypesMap[xtype]) {
  7363. xtypesMap[xtype] = true;
  7364. xtypesChain.push(xtype);
  7365. }
  7366. }
  7367. }
  7368. }
  7369. }
  7370. });
  7371. for (i = 0,ln = xtypes.length; i < ln; i++) {
  7372. xtype = xtypes[i];
  7373. Ext.Array.include(aliases, widgetPrefix + xtype);
  7374. }
  7375. data.alias = aliases;
  7376. }, ['xtype', 'alias']);
  7377. })(Ext.Class, Ext.Function.alias, Array.prototype.slice, Ext.Array.from, Ext.global);
  7378. /**
  7379. * @author Jacky Nguyen <jacky@sencha.com>
  7380. * @docauthor Jacky Nguyen <jacky@sencha.com>
  7381. * @class Ext.Loader
  7382. *
  7383. * Ext.Loader is the heart of the new dynamic dependency loading capability in Ext JS 4+. It is most commonly used
  7384. * via the {@link Ext#require} shorthand. Ext.Loader supports both asynchronous and synchronous loading
  7385. * approaches, and leverage their advantages for the best development flow. We'll discuss about the pros and cons of each approach:
  7386. *
  7387. * # Asynchronous Loading #
  7388. *
  7389. * - Advantages:
  7390. * + Cross-domain
  7391. * + No web server needed: you can run the application via the file system protocol (i.e: `file://path/to/your/index
  7392. * .html`)
  7393. * + Best possible debugging experience: error messages come with the exact file name and line number
  7394. *
  7395. * - Disadvantages:
  7396. * + Dependencies need to be specified before-hand
  7397. *
  7398. * ### Method 1: Explicitly include what you need: ###
  7399. *
  7400. * // Syntax
  7401. * Ext.require({String/Array} expressions);
  7402. *
  7403. * // Example: Single alias
  7404. * Ext.require('widget.window');
  7405. *
  7406. * // Example: Single class name
  7407. * Ext.require('Ext.window.Window');
  7408. *
  7409. * // Example: Multiple aliases / class names mix
  7410. * Ext.require(['widget.window', 'layout.border', 'Ext.data.Connection']);
  7411. *
  7412. * // Wildcards
  7413. * Ext.require(['widget.*', 'layout.*', 'Ext.data.*']);
  7414. *
  7415. * ### Method 2: Explicitly exclude what you don't need: ###
  7416. *
  7417. * // Syntax: Note that it must be in this chaining format.
  7418. * Ext.exclude({String/Array} expressions)
  7419. * .require({String/Array} expressions);
  7420. *
  7421. * // Include everything except Ext.data.*
  7422. * Ext.exclude('Ext.data.*').require('*');
  7423. *
  7424. * // Include all widgets except widget.checkbox*,
  7425. * // which will match widget.checkbox, widget.checkboxfield, widget.checkboxgroup, etc.
  7426. * Ext.exclude('widget.checkbox*').require('widget.*');
  7427. *
  7428. * # Synchronous Loading on Demand #
  7429. *
  7430. * - Advantages:
  7431. * + There's no need to specify dependencies before-hand, which is always the convenience of including ext-all.js
  7432. * before
  7433. *
  7434. * - Disadvantages:
  7435. * + Not as good debugging experience since file name won't be shown (except in Firebug at the moment)
  7436. * + Must be from the same domain due to XHR restriction
  7437. * + Need a web server, same reason as above
  7438. *
  7439. * There's one simple rule to follow: Instantiate everything with Ext.create instead of the `new` keyword
  7440. *
  7441. * Ext.create('widget.window', { ... }); // Instead of new Ext.window.Window({...});
  7442. *
  7443. * Ext.create('Ext.window.Window', {}); // Same as above, using full class name instead of alias
  7444. *
  7445. * Ext.widget('window', {}); // Same as above, all you need is the traditional `xtype`
  7446. *
  7447. * Behind the scene, {@link Ext.ClassManager} will automatically check whether the given class name / alias has already
  7448. * existed on the page. If it's not, Ext.Loader will immediately switch itself to synchronous mode and automatic load the given
  7449. * class and all its dependencies.
  7450. *
  7451. * # Hybrid Loading - The Best of Both Worlds #
  7452. *
  7453. * It has all the advantages combined from asynchronous and synchronous loading. The development flow is simple:
  7454. *
  7455. * ### Step 1: Start writing your application using synchronous approach.
  7456. *
  7457. * Ext.Loader will automatically fetch all dependencies on demand as they're needed during run-time. For example:
  7458. *
  7459. * Ext.onReady(function(){
  7460. * var window = Ext.createWidget('window', {
  7461. * width: 500,
  7462. * height: 300,
  7463. * layout: {
  7464. * type: 'border',
  7465. * padding: 5
  7466. * },
  7467. * title: 'Hello Dialog',
  7468. * items: [{
  7469. * title: 'Navigation',
  7470. * collapsible: true,
  7471. * region: 'west',
  7472. * width: 200,
  7473. * html: 'Hello',
  7474. * split: true
  7475. * }, {
  7476. * title: 'TabPanel',
  7477. * region: 'center'
  7478. * }]
  7479. * });
  7480. *
  7481. * window.show();
  7482. * })
  7483. *
  7484. * ### Step 2: Along the way, when you need better debugging ability, watch the console for warnings like these: ###
  7485. *
  7486. * [Ext.Loader] Synchronously loading 'Ext.window.Window'; consider adding Ext.require('Ext.window.Window') before your application's code
  7487. * ClassManager.js:432
  7488. * [Ext.Loader] Synchronously loading 'Ext.layout.container.Border'; consider adding Ext.require('Ext.layout.container.Border') before your application's code
  7489. *
  7490. * Simply copy and paste the suggested code above `Ext.onReady`, i.e:
  7491. *
  7492. * Ext.require('Ext.window.Window');
  7493. * Ext.require('Ext.layout.container.Border');
  7494. *
  7495. * Ext.onReady(...);
  7496. *
  7497. * Everything should now load via asynchronous mode.
  7498. *
  7499. * # Deployment #
  7500. *
  7501. * It's important to note that dynamic loading should only be used during development on your local machines.
  7502. * During production, all dependencies should be combined into one single JavaScript file. Ext.Loader makes
  7503. * the whole process of transitioning from / to between development / maintenance and production as easy as
  7504. * possible. Internally {@link Ext.Loader#history Ext.Loader.history} maintains the list of all dependencies your application
  7505. * needs in the exact loading sequence. It's as simple as concatenating all files in this array into one,
  7506. * then include it on top of your application.
  7507. *
  7508. * This process will be automated with Sencha Command, to be released and documented towards Ext JS 4 Final.
  7509. *
  7510. * @singleton
  7511. */
  7512. (function(Manager, Class, flexSetter, alias, pass, arrayFrom, arrayErase, arrayInclude) {
  7513. var
  7514. dependencyProperties = ['extend', 'mixins', 'requires'],
  7515. Loader;
  7516. Loader = Ext.Loader = {
  7517. /**
  7518. * @private
  7519. */
  7520. isInHistory: {},
  7521. /**
  7522. * An array of class names to keep track of the dependency loading order.
  7523. * This is not guaranteed to be the same everytime due to the asynchronous
  7524. * nature of the Loader.
  7525. *
  7526. * @property {Array} history
  7527. */
  7528. history: [],
  7529. /**
  7530. * Configuration
  7531. * @private
  7532. */
  7533. config: {
  7534. /**
  7535. * @cfg {Boolean} enabled
  7536. * Whether or not to enable the dynamic dependency loading feature.
  7537. */
  7538. enabled: false,
  7539. /**
  7540. * @cfg {Boolean} disableCaching
  7541. * Appends current timestamp to script files to prevent caching.
  7542. */
  7543. disableCaching: true,
  7544. /**
  7545. * @cfg {String} disableCachingParam
  7546. * The get parameter name for the cache buster's timestamp.
  7547. */
  7548. disableCachingParam: '_dc',
  7549. /**
  7550. * @cfg {Object} paths
  7551. * The mapping from namespaces to file paths
  7552. *
  7553. * {
  7554. * 'Ext': '.', // This is set by default, Ext.layout.container.Container will be
  7555. * // loaded from ./layout/Container.js
  7556. *
  7557. * 'My': './src/my_own_folder' // My.layout.Container will be loaded from
  7558. * // ./src/my_own_folder/layout/Container.js
  7559. * }
  7560. *
  7561. * Note that all relative paths are relative to the current HTML document.
  7562. * If not being specified, for example, <code>Other.awesome.Class</code>
  7563. * will simply be loaded from <code>./Other/awesome/Class.js</code>
  7564. */
  7565. paths: {
  7566. 'Ext': '.'
  7567. }
  7568. },
  7569. /**
  7570. * Set the configuration for the loader. This should be called right after ext-(debug).js
  7571. * is included in the page, and before Ext.onReady. i.e:
  7572. *
  7573. * <script type="text/javascript" src="ext-core-debug.js"></script>
  7574. * <script type="text/javascript">
  7575. * Ext.Loader.setConfig({
  7576. * enabled: true,
  7577. * paths: {
  7578. * 'My': 'my_own_path'
  7579. * }
  7580. * });
  7581. * </script>
  7582. * <script type="text/javascript">
  7583. * Ext.require(...);
  7584. *
  7585. * Ext.onReady(function() {
  7586. * // application code here
  7587. * });
  7588. * </script>
  7589. *
  7590. * Refer to config options of {@link Ext.Loader} for the list of possible properties
  7591. *
  7592. * @param {Object} config The config object to override the default values
  7593. * @return {Ext.Loader} this
  7594. */
  7595. setConfig: function(name, value) {
  7596. if (Ext.isObject(name) && arguments.length === 1) {
  7597. Ext.merge(this.config, name);
  7598. }
  7599. else {
  7600. this.config[name] = (Ext.isObject(value)) ? Ext.merge(this.config[name], value) : value;
  7601. }
  7602. return this;
  7603. },
  7604. /**
  7605. * Get the config value corresponding to the specified name. If no name is given, will return the config object
  7606. * @param {String} name The config property name
  7607. * @return {Object}
  7608. */
  7609. getConfig: function(name) {
  7610. if (name) {
  7611. return this.config[name];
  7612. }
  7613. return this.config;
  7614. },
  7615. /**
  7616. * Sets the path of a namespace.
  7617. * For Example:
  7618. *
  7619. * Ext.Loader.setPath('Ext', '.');
  7620. *
  7621. * @param {String/Object} name See {@link Ext.Function#flexSetter flexSetter}
  7622. * @param {String} path See {@link Ext.Function#flexSetter flexSetter}
  7623. * @return {Ext.Loader} this
  7624. * @method
  7625. */
  7626. setPath: flexSetter(function(name, path) {
  7627. this.config.paths[name] = path;
  7628. return this;
  7629. }),
  7630. /**
  7631. * Translates a className to a file path by adding the
  7632. * the proper prefix and converting the .'s to /'s. For example:
  7633. *
  7634. * Ext.Loader.setPath('My', '/path/to/My');
  7635. *
  7636. * alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/path/to/My/awesome/Class.js'
  7637. *
  7638. * Note that the deeper namespace levels, if explicitly set, are always resolved first. For example:
  7639. *
  7640. * Ext.Loader.setPath({
  7641. * 'My': '/path/to/lib',
  7642. * 'My.awesome': '/other/path/for/awesome/stuff',
  7643. * 'My.awesome.more': '/more/awesome/path'
  7644. * });
  7645. *
  7646. * alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/other/path/for/awesome/stuff/Class.js'
  7647. *
  7648. * alert(Ext.Loader.getPath('My.awesome.more.Class')); // alerts '/more/awesome/path/Class.js'
  7649. *
  7650. * alert(Ext.Loader.getPath('My.cool.Class')); // alerts '/path/to/lib/cool/Class.js'
  7651. *
  7652. * alert(Ext.Loader.getPath('Unknown.strange.Stuff')); // alerts 'Unknown/strange/Stuff.js'
  7653. *
  7654. * @param {String} className
  7655. * @return {String} path
  7656. */
  7657. getPath: function(className) {
  7658. var path = '',
  7659. paths = this.config.paths,
  7660. prefix = this.getPrefix(className);
  7661. if (prefix.length > 0) {
  7662. if (prefix === className) {
  7663. return paths[prefix];
  7664. }
  7665. path = paths[prefix];
  7666. className = className.substring(prefix.length + 1);
  7667. }
  7668. if (path.length > 0) {
  7669. path += '/';
  7670. }
  7671. return path.replace(/\/\.\//g, '/') + className.replace(/\./g, "/") + '.js';
  7672. },
  7673. /**
  7674. * @private
  7675. * @param {String} className
  7676. */
  7677. getPrefix: function(className) {
  7678. var paths = this.config.paths,
  7679. prefix, deepestPrefix = '';
  7680. if (paths.hasOwnProperty(className)) {
  7681. return className;
  7682. }
  7683. for (prefix in paths) {
  7684. if (paths.hasOwnProperty(prefix) && prefix + '.' === className.substring(0, prefix.length + 1)) {
  7685. if (prefix.length > deepestPrefix.length) {
  7686. deepestPrefix = prefix;
  7687. }
  7688. }
  7689. }
  7690. return deepestPrefix;
  7691. },
  7692. /**
  7693. * Loads all classes by the given names and all their direct dependencies; optionally executes the given callback function when
  7694. * finishes, within the optional scope. This method is aliased by {@link Ext#require Ext.require} for convenience
  7695. * @param {String/Array} expressions Can either be a string or an array of string
  7696. * @param {Function} fn (Optional) The callback function
  7697. * @param {Object} scope (Optional) The execution scope (`this`) of the callback function
  7698. * @param {String/Array} excludes (Optional) Classes to be excluded, useful when being used with expressions
  7699. */
  7700. require: function(expressions, fn, scope, excludes) {
  7701. if (fn) {
  7702. fn.call(scope);
  7703. }
  7704. },
  7705. /**
  7706. * Synchronously loads all classes by the given names and all their direct dependencies; optionally executes the given callback function when finishes, within the optional scope. This method is aliased by {@link Ext#syncRequire} for convenience
  7707. * @param {String/Array} expressions Can either be a string or an array of string
  7708. * @param {Function} fn (Optional) The callback function
  7709. * @param {Object} scope (Optional) The execution scope (`this`) of the callback function
  7710. * @param {String/Array} excludes (Optional) Classes to be excluded, useful when being used with expressions
  7711. */
  7712. syncRequire: function() {},
  7713. /**
  7714. * Explicitly exclude files from being loaded. Useful when used in conjunction with a broad include expression.
  7715. * Can be chained with more `require` and `exclude` methods, eg:
  7716. *
  7717. * Ext.exclude('Ext.data.*').require('*');
  7718. *
  7719. * Ext.exclude('widget.button*').require('widget.*');
  7720. *
  7721. * @param {Array} excludes
  7722. * @return {Object} object contains `require` method for chaining
  7723. */
  7724. exclude: function(excludes) {
  7725. var me = this;
  7726. return {
  7727. require: function(expressions, fn, scope) {
  7728. return me.require(expressions, fn, scope, excludes);
  7729. },
  7730. syncRequire: function(expressions, fn, scope) {
  7731. return me.syncRequire(expressions, fn, scope, excludes);
  7732. }
  7733. };
  7734. },
  7735. /**
  7736. * Add a new listener to be executed when all required scripts are fully loaded
  7737. *
  7738. * @param {Function} fn The function callback to be executed
  7739. * @param {Object} scope The execution scope (<code>this</code>) of the callback function
  7740. * @param {Boolean} withDomReady Whether or not to wait for document dom ready as well
  7741. */
  7742. onReady: function(fn, scope, withDomReady, options) {
  7743. var oldFn;
  7744. if (withDomReady !== false && Ext.onDocumentReady) {
  7745. oldFn = fn;
  7746. fn = function() {
  7747. Ext.onDocumentReady(oldFn, scope, options);
  7748. };
  7749. }
  7750. fn.call(scope);
  7751. }
  7752. };
  7753. Ext.apply(Loader, {
  7754. /**
  7755. * @private
  7756. */
  7757. documentHead: typeof document != 'undefined' && (document.head || document.getElementsByTagName('head')[0]),
  7758. /**
  7759. * Flag indicating whether there are still files being loaded
  7760. * @private
  7761. */
  7762. isLoading: false,
  7763. /**
  7764. * Maintain the queue for all dependencies. Each item in the array is an object of the format:
  7765. *
  7766. * {
  7767. * requires: [...], // The required classes for this queue item
  7768. * callback: function() { ... } // The function to execute when all classes specified in requires exist
  7769. * }
  7770. *
  7771. * @private
  7772. */
  7773. queue: [],
  7774. /**
  7775. * Maintain the list of files that have already been handled so that they never get double-loaded
  7776. * @private
  7777. */
  7778. isClassFileLoaded: {},
  7779. /**
  7780. * @private
  7781. */
  7782. isFileLoaded: {},
  7783. /**
  7784. * Maintain the list of listeners to execute when all required scripts are fully loaded
  7785. * @private
  7786. */
  7787. readyListeners: [],
  7788. /**
  7789. * Contains optional dependencies to be loaded last
  7790. * @private
  7791. */
  7792. optionalRequires: [],
  7793. /**
  7794. * Map of fully qualified class names to an array of dependent classes.
  7795. * @private
  7796. */
  7797. requiresMap: {},
  7798. /**
  7799. * @private
  7800. */
  7801. numPendingFiles: 0,
  7802. /**
  7803. * @private
  7804. */
  7805. numLoadedFiles: 0,
  7806. /** @private */
  7807. hasFileLoadError: false,
  7808. /**
  7809. * @private
  7810. */
  7811. classNameToFilePathMap: {},
  7812. /**
  7813. * @private
  7814. */
  7815. syncModeEnabled: false,
  7816. scriptElements: {},
  7817. /**
  7818. * Refresh all items in the queue. If all dependencies for an item exist during looping,
  7819. * it will execute the callback and call refreshQueue again. Triggers onReady when the queue is
  7820. * empty
  7821. * @private
  7822. */
  7823. refreshQueue: function() {
  7824. var queue = this.queue,
  7825. ln = queue.length,
  7826. i, item, j, requires, references;
  7827. if (ln === 0) {
  7828. this.triggerReady();
  7829. return;
  7830. }
  7831. for (i = 0; i < ln; i++) {
  7832. item = queue[i];
  7833. if (item) {
  7834. requires = item.requires;
  7835. references = item.references;
  7836. // Don't bother checking when the number of files loaded
  7837. // is still less than the array length
  7838. if (requires.length > this.numLoadedFiles) {
  7839. continue;
  7840. }
  7841. j = 0;
  7842. do {
  7843. if (Manager.isCreated(requires[j])) {
  7844. // Take out from the queue
  7845. arrayErase(requires, j, 1);
  7846. }
  7847. else {
  7848. j++;
  7849. }
  7850. } while (j < requires.length);
  7851. if (item.requires.length === 0) {
  7852. arrayErase(queue, i, 1);
  7853. item.callback.call(item.scope);
  7854. this.refreshQueue();
  7855. break;
  7856. }
  7857. }
  7858. }
  7859. return this;
  7860. },
  7861. /**
  7862. * Inject a script element to document's head, call onLoad and onError accordingly
  7863. * @private
  7864. */
  7865. injectScriptElement: function(url, onLoad, onError, scope) {
  7866. var script = document.createElement('script'),
  7867. me = this,
  7868. onLoadFn = function() {
  7869. me.cleanupScriptElement(script);
  7870. onLoad.call(scope);
  7871. },
  7872. onErrorFn = function() {
  7873. me.cleanupScriptElement(script);
  7874. onError.call(scope);
  7875. };
  7876. script.type = 'text/javascript';
  7877. script.src = url;
  7878. script.onload = onLoadFn;
  7879. script.onerror = onErrorFn;
  7880. script.onreadystatechange = function() {
  7881. if (this.readyState === 'loaded' || this.readyState === 'complete') {
  7882. onLoadFn();
  7883. }
  7884. };
  7885. this.documentHead.appendChild(script);
  7886. return script;
  7887. },
  7888. removeScriptElement: function(url) {
  7889. var scriptElements = this.scriptElements;
  7890. if (scriptElements[url]) {
  7891. this.cleanupScriptElement(scriptElements[url], true);
  7892. delete scriptElements[url];
  7893. }
  7894. return this;
  7895. },
  7896. /**
  7897. * @private
  7898. */
  7899. cleanupScriptElement: function(script, remove) {
  7900. script.onload = null;
  7901. script.onreadystatechange = null;
  7902. script.onerror = null;
  7903. if (remove) {
  7904. this.documentHead.removeChild(script);
  7905. }
  7906. return this;
  7907. },
  7908. /**
  7909. * Load a script file, supports both asynchronous and synchronous approaches
  7910. * @private
  7911. */
  7912. loadScriptFile: function(url, onLoad, onError, scope, synchronous) {
  7913. var me = this,
  7914. isFileLoaded = this.isFileLoaded,
  7915. scriptElements = this.scriptElements,
  7916. noCacheUrl = url + (this.getConfig('disableCaching') ? ('?' + this.getConfig('disableCachingParam') + '=' + Ext.Date.now()) : ''),
  7917. isCrossOriginRestricted = false,
  7918. xhr, status, onScriptError;
  7919. if (isFileLoaded[url]) {
  7920. return this;
  7921. }
  7922. scope = scope || this;
  7923. this.isLoading = true;
  7924. if (!synchronous) {
  7925. onScriptError = function() {
  7926. };
  7927. if (!Ext.isReady && Ext.onDocumentReady) {
  7928. Ext.onDocumentReady(function() {
  7929. if (!isFileLoaded[url]) {
  7930. scriptElements[url] = me.injectScriptElement(noCacheUrl, onLoad, onScriptError, scope);
  7931. }
  7932. });
  7933. }
  7934. else {
  7935. scriptElements[url] = this.injectScriptElement(noCacheUrl, onLoad, onScriptError, scope);
  7936. }
  7937. }
  7938. else {
  7939. if (typeof XMLHttpRequest != 'undefined') {
  7940. xhr = new XMLHttpRequest();
  7941. } else {
  7942. xhr = new ActiveXObject('Microsoft.XMLHTTP');
  7943. }
  7944. try {
  7945. xhr.open('GET', noCacheUrl, false);
  7946. xhr.send(null);
  7947. } catch (e) {
  7948. isCrossOriginRestricted = true;
  7949. }
  7950. status = (xhr.status === 1223) ? 204 : xhr.status;
  7951. if (!isCrossOriginRestricted) {
  7952. isCrossOriginRestricted = (status === 0);
  7953. }
  7954. if (isCrossOriginRestricted
  7955. ) {
  7956. }
  7957. else if (status >= 200 && status < 300
  7958. ) {
  7959. // Debugger friendly, file names are still shown even though they're eval'ed code
  7960. // Breakpoints work on both Firebug and Chrome's Web Inspector
  7961. Ext.globalEval(xhr.responseText + "\n//@ sourceURL=" + url);
  7962. onLoad.call(scope);
  7963. }
  7964. else {
  7965. }
  7966. // Prevent potential IE memory leak
  7967. xhr = null;
  7968. }
  7969. },
  7970. // documented above
  7971. syncRequire: function() {
  7972. var syncModeEnabled = this.syncModeEnabled;
  7973. if (!syncModeEnabled) {
  7974. this.syncModeEnabled = true;
  7975. }
  7976. this.require.apply(this, arguments);
  7977. if (!syncModeEnabled) {
  7978. this.syncModeEnabled = false;
  7979. }
  7980. this.refreshQueue();
  7981. },
  7982. // documented above
  7983. require: function(expressions, fn, scope, excludes) {
  7984. var excluded = {},
  7985. included = {},
  7986. queue = this.queue,
  7987. classNameToFilePathMap = this.classNameToFilePathMap,
  7988. isClassFileLoaded = this.isClassFileLoaded,
  7989. excludedClassNames = [],
  7990. possibleClassNames = [],
  7991. classNames = [],
  7992. references = [],
  7993. callback,
  7994. syncModeEnabled,
  7995. filePath, expression, exclude, className,
  7996. possibleClassName, i, j, ln, subLn;
  7997. if (excludes) {
  7998. excludes = arrayFrom(excludes);
  7999. for (i = 0,ln = excludes.length; i < ln; i++) {
  8000. exclude = excludes[i];
  8001. if (typeof exclude == 'string' && exclude.length > 0) {
  8002. excludedClassNames = Manager.getNamesByExpression(exclude);
  8003. for (j = 0,subLn = excludedClassNames.length; j < subLn; j++) {
  8004. excluded[excludedClassNames[j]] = true;
  8005. }
  8006. }
  8007. }
  8008. }
  8009. expressions = arrayFrom(expressions);
  8010. if (fn) {
  8011. if (fn.length > 0) {
  8012. callback = function() {
  8013. var classes = [],
  8014. i, ln, name;
  8015. for (i = 0,ln = references.length; i < ln; i++) {
  8016. name = references[i];
  8017. classes.push(Manager.get(name));
  8018. }
  8019. return fn.apply(this, classes);
  8020. };
  8021. }
  8022. else {
  8023. callback = fn;
  8024. }
  8025. }
  8026. else {
  8027. callback = Ext.emptyFn;
  8028. }
  8029. scope = scope || Ext.global;
  8030. for (i = 0,ln = expressions.length; i < ln; i++) {
  8031. expression = expressions[i];
  8032. if (typeof expression == 'string' && expression.length > 0) {
  8033. possibleClassNames = Manager.getNamesByExpression(expression);
  8034. subLn = possibleClassNames.length;
  8035. for (j = 0; j < subLn; j++) {
  8036. possibleClassName = possibleClassNames[j];
  8037. if (excluded[possibleClassName] !== true) {
  8038. references.push(possibleClassName);
  8039. if (!Manager.isCreated(possibleClassName) && !included[possibleClassName]) {
  8040. included[possibleClassName] = true;
  8041. classNames.push(possibleClassName);
  8042. }
  8043. }
  8044. }
  8045. }
  8046. }
  8047. // If the dynamic dependency feature is not being used, throw an error
  8048. // if the dependencies are not defined
  8049. if (classNames.length > 0) {
  8050. if (!this.config.enabled) {
  8051. throw new Error("Ext.Loader is not enabled, so dependencies cannot be resolved dynamically. " +
  8052. "Missing required class" + ((classNames.length > 1) ? "es" : "") + ": " + classNames.join(', '));
  8053. }
  8054. }
  8055. else {
  8056. callback.call(scope);
  8057. return this;
  8058. }
  8059. syncModeEnabled = this.syncModeEnabled;
  8060. if (!syncModeEnabled) {
  8061. queue.push({
  8062. requires: classNames.slice(), // this array will be modified as the queue is processed,
  8063. // so we need a copy of it
  8064. callback: callback,
  8065. scope: scope
  8066. });
  8067. }
  8068. ln = classNames.length;
  8069. for (i = 0; i < ln; i++) {
  8070. className = classNames[i];
  8071. filePath = this.getPath(className);
  8072. // If we are synchronously loading a file that has already been asychronously loaded before
  8073. // we need to destroy the script tag and revert the count
  8074. // This file will then be forced loaded in synchronous
  8075. if (syncModeEnabled && isClassFileLoaded.hasOwnProperty(className)) {
  8076. this.numPendingFiles--;
  8077. this.removeScriptElement(filePath);
  8078. delete isClassFileLoaded[className];
  8079. }
  8080. if (!isClassFileLoaded.hasOwnProperty(className)) {
  8081. isClassFileLoaded[className] = false;
  8082. classNameToFilePathMap[className] = filePath;
  8083. this.numPendingFiles++;
  8084. this.loadScriptFile(
  8085. filePath,
  8086. pass(this.onFileLoaded, [className, filePath], this),
  8087. pass(this.onFileLoadError, [className, filePath], this),
  8088. this,
  8089. syncModeEnabled
  8090. );
  8091. }
  8092. }
  8093. if (syncModeEnabled) {
  8094. callback.call(scope);
  8095. if (ln === 1) {
  8096. return Manager.get(className);
  8097. }
  8098. }
  8099. return this;
  8100. },
  8101. /**
  8102. * @private
  8103. * @param {String} className
  8104. * @param {String} filePath
  8105. */
  8106. onFileLoaded: function(className, filePath) {
  8107. this.numLoadedFiles++;
  8108. this.isClassFileLoaded[className] = true;
  8109. this.isFileLoaded[filePath] = true;
  8110. this.numPendingFiles--;
  8111. if (this.numPendingFiles === 0) {
  8112. this.refreshQueue();
  8113. }
  8114. },
  8115. /**
  8116. * @private
  8117. */
  8118. onFileLoadError: function(className, filePath, errorMessage, isSynchronous) {
  8119. this.numPendingFiles--;
  8120. this.hasFileLoadError = true;
  8121. },
  8122. /**
  8123. * @private
  8124. */
  8125. addOptionalRequires: function(requires) {
  8126. var optionalRequires = this.optionalRequires,
  8127. i, ln, require;
  8128. requires = arrayFrom(requires);
  8129. for (i = 0, ln = requires.length; i < ln; i++) {
  8130. require = requires[i];
  8131. arrayInclude(optionalRequires, require);
  8132. }
  8133. return this;
  8134. },
  8135. /**
  8136. * @private
  8137. */
  8138. triggerReady: function(force) {
  8139. var readyListeners = this.readyListeners,
  8140. optionalRequires = this.optionalRequires,
  8141. listener;
  8142. if (this.isLoading || force) {
  8143. this.isLoading = false;
  8144. if (optionalRequires.length !== 0) {
  8145. // Clone then empty the array to eliminate potential recursive loop issue
  8146. optionalRequires = optionalRequires.slice();
  8147. // Empty the original array
  8148. this.optionalRequires.length = 0;
  8149. this.require(optionalRequires, pass(this.triggerReady, [true], this), this);
  8150. return this;
  8151. }
  8152. while (readyListeners.length) {
  8153. listener = readyListeners.shift();
  8154. listener.fn.call(listener.scope);
  8155. if (this.isLoading) {
  8156. return this;
  8157. }
  8158. }
  8159. }
  8160. return this;
  8161. },
  8162. // Documented above already
  8163. onReady: function(fn, scope, withDomReady, options) {
  8164. var oldFn;
  8165. if (withDomReady !== false && Ext.onDocumentReady) {
  8166. oldFn = fn;
  8167. fn = function() {
  8168. Ext.onDocumentReady(oldFn, scope, options);
  8169. };
  8170. }
  8171. if (!this.isLoading) {
  8172. fn.call(scope);
  8173. }
  8174. else {
  8175. this.readyListeners.push({
  8176. fn: fn,
  8177. scope: scope
  8178. });
  8179. }
  8180. },
  8181. /**
  8182. * @private
  8183. * @param {String} className
  8184. */
  8185. historyPush: function(className) {
  8186. var isInHistory = this.isInHistory;
  8187. if (className && this.isClassFileLoaded.hasOwnProperty(className) && !isInHistory[className]) {
  8188. isInHistory[className] = true;
  8189. this.history.push(className);
  8190. }
  8191. return this;
  8192. }
  8193. });
  8194. /**
  8195. * Turns on or off the "cache buster" applied to dynamically loaded scripts. Normally
  8196. * dynamically loaded scripts have an extra query parameter appended to avoid stale
  8197. * cached scripts. This method can be used to disable this mechanism, and is primarily
  8198. * useful for testing. This is done using a cookie.
  8199. * @param {Boolean} disable True to disable the cache buster.
  8200. * @param {String} [path="/"] An optional path to scope the cookie.
  8201. * @private
  8202. */
  8203. Ext.disableCacheBuster = function (disable, path) {
  8204. var date = new Date();
  8205. date.setTime(date.getTime() + (disable ? 10*365 : -1) * 24*60*60*1000);
  8206. date = date.toGMTString();
  8207. document.cookie = 'ext-cache=1; expires=' + date + '; path='+(path || '/');
  8208. };
  8209. /**
  8210. * Convenient alias of {@link Ext.Loader#require}. Please see the introduction documentation of
  8211. * {@link Ext.Loader} for examples.
  8212. * @member Ext
  8213. * @method require
  8214. */
  8215. Ext.require = alias(Loader, 'require');
  8216. /**
  8217. * Synchronous version of {@link Ext#require}, convenient alias of {@link Ext.Loader#syncRequire}.
  8218. *
  8219. * @member Ext
  8220. * @method syncRequire
  8221. */
  8222. Ext.syncRequire = alias(Loader, 'syncRequire');
  8223. /**
  8224. * Convenient shortcut to {@link Ext.Loader#exclude}
  8225. * @member Ext
  8226. * @method exclude
  8227. */
  8228. Ext.exclude = alias(Loader, 'exclude');
  8229. /**
  8230. * @member Ext
  8231. * @method onReady
  8232. */
  8233. Ext.onReady = function(fn, scope, options) {
  8234. Loader.onReady(fn, scope, true, options);
  8235. };
  8236. /**
  8237. * @cfg {String[]} requires
  8238. * @member Ext.Class
  8239. * List of classes that have to be loaded before instantiating this class.
  8240. * For example:
  8241. *
  8242. * Ext.define('Mother', {
  8243. * requires: ['Child'],
  8244. * giveBirth: function() {
  8245. * // we can be sure that child class is available.
  8246. * return new Child();
  8247. * }
  8248. * });
  8249. */
  8250. Class.registerPreprocessor('loader', function(cls, data, hooks, continueFn) {
  8251. var me = this,
  8252. dependencies = [],
  8253. className = Manager.getName(cls),
  8254. i, j, ln, subLn, value, propertyName, propertyValue;
  8255. /*
  8256. Loop through the dependencyProperties, look for string class names and push
  8257. them into a stack, regardless of whether the property's value is a string, array or object. For example:
  8258. {
  8259. extend: 'Ext.MyClass',
  8260. requires: ['Ext.some.OtherClass'],
  8261. mixins: {
  8262. observable: 'Ext.util.Observable';
  8263. }
  8264. }
  8265. which will later be transformed into:
  8266. {
  8267. extend: Ext.MyClass,
  8268. requires: [Ext.some.OtherClass],
  8269. mixins: {
  8270. observable: Ext.util.Observable;
  8271. }
  8272. }
  8273. */
  8274. for (i = 0,ln = dependencyProperties.length; i < ln; i++) {
  8275. propertyName = dependencyProperties[i];
  8276. if (data.hasOwnProperty(propertyName)) {
  8277. propertyValue = data[propertyName];
  8278. if (typeof propertyValue == 'string') {
  8279. dependencies.push(propertyValue);
  8280. }
  8281. else if (propertyValue instanceof Array) {
  8282. for (j = 0, subLn = propertyValue.length; j < subLn; j++) {
  8283. value = propertyValue[j];
  8284. if (typeof value == 'string') {
  8285. dependencies.push(value);
  8286. }
  8287. }
  8288. }
  8289. else if (typeof propertyValue != 'function') {
  8290. for (j in propertyValue) {
  8291. if (propertyValue.hasOwnProperty(j)) {
  8292. value = propertyValue[j];
  8293. if (typeof value == 'string') {
  8294. dependencies.push(value);
  8295. }
  8296. }
  8297. }
  8298. }
  8299. }
  8300. }
  8301. if (dependencies.length === 0) {
  8302. return;
  8303. }
  8304. Loader.require(dependencies, function() {
  8305. for (i = 0,ln = dependencyProperties.length; i < ln; i++) {
  8306. propertyName = dependencyProperties[i];
  8307. if (data.hasOwnProperty(propertyName)) {
  8308. propertyValue = data[propertyName];
  8309. if (typeof propertyValue == 'string') {
  8310. data[propertyName] = Manager.get(propertyValue);
  8311. }
  8312. else if (propertyValue instanceof Array) {
  8313. for (j = 0, subLn = propertyValue.length; j < subLn; j++) {
  8314. value = propertyValue[j];
  8315. if (typeof value == 'string') {
  8316. data[propertyName][j] = Manager.get(value);
  8317. }
  8318. }
  8319. }
  8320. else if (typeof propertyValue != 'function') {
  8321. for (var k in propertyValue) {
  8322. if (propertyValue.hasOwnProperty(k)) {
  8323. value = propertyValue[k];
  8324. if (typeof value == 'string') {
  8325. data[propertyName][k] = Manager.get(value);
  8326. }
  8327. }
  8328. }
  8329. }
  8330. }
  8331. }
  8332. continueFn.call(me, cls, data, hooks);
  8333. });
  8334. return false;
  8335. }, true, 'after', 'className');
  8336. /**
  8337. * @cfg {String[]} uses
  8338. * @member Ext.Class
  8339. * List of optional classes to load together with this class. These aren't neccessarily loaded before
  8340. * this class is created, but are guaranteed to be available before Ext.onReady listeners are
  8341. * invoked. For example:
  8342. *
  8343. * Ext.define('Mother', {
  8344. * uses: ['Child'],
  8345. * giveBirth: function() {
  8346. * // This code might, or might not work:
  8347. * // return new Child();
  8348. *
  8349. * // Instead use Ext.create() to load the class at the spot if not loaded already:
  8350. * return Ext.create('Child');
  8351. * }
  8352. * });
  8353. */
  8354. Manager.registerPostprocessor('uses', function(name, cls, data) {
  8355. var uses = arrayFrom(data.uses),
  8356. items = [],
  8357. i, ln, item;
  8358. for (i = 0,ln = uses.length; i < ln; i++) {
  8359. item = uses[i];
  8360. if (typeof item == 'string') {
  8361. items.push(item);
  8362. }
  8363. }
  8364. Loader.addOptionalRequires(items);
  8365. });
  8366. Manager.onCreated(function(className) {
  8367. this.historyPush(className);
  8368. }, Loader);
  8369. })(Ext.ClassManager, Ext.Class, Ext.Function.flexSetter, Ext.Function.alias,
  8370. Ext.Function.pass, Ext.Array.from, Ext.Array.erase, Ext.Array.include);
  8371. /**
  8372. * @author Brian Moeskau <brian@sencha.com>
  8373. * @docauthor Brian Moeskau <brian@sencha.com>
  8374. *
  8375. * A wrapper class for the native JavaScript Error object that adds a few useful capabilities for handling
  8376. * errors in an Ext application. When you use Ext.Error to {@link #raise} an error from within any class that
  8377. * uses the Ext 4 class system, the Error class can automatically add the source class and method from which
  8378. * the error was raised. It also includes logic to automatically log the eroor to the console, if available,
  8379. * with additional metadata about the error. In all cases, the error will always be thrown at the end so that
  8380. * execution will halt.
  8381. *
  8382. * Ext.Error also offers a global error {@link #handle handling} method that can be overridden in order to
  8383. * handle application-wide errors in a single spot. You can optionally {@link #ignore} errors altogether,
  8384. * although in a real application it's usually a better idea to override the handling function and perform
  8385. * logging or some other method of reporting the errors in a way that is meaningful to the application.
  8386. *
  8387. * At its simplest you can simply raise an error as a simple string from within any code:
  8388. *
  8389. * Example usage:
  8390. *
  8391. * Ext.Error.raise('Something bad happened!');
  8392. *
  8393. * If raised from plain JavaScript code, the error will be logged to the console (if available) and the message
  8394. * displayed. In most cases however you'll be raising errors from within a class, and it may often be useful to add
  8395. * additional metadata about the error being raised. The {@link #raise} method can also take a config object.
  8396. * In this form the `msg` attribute becomes the error description, and any other data added to the config gets
  8397. * added to the error object and, if the console is available, logged to the console for inspection.
  8398. *
  8399. * Example usage:
  8400. *
  8401. * Ext.define('Ext.Foo', {
  8402. * doSomething: function(option){
  8403. * if (someCondition === false) {
  8404. * Ext.Error.raise({
  8405. * msg: 'You cannot do that!',
  8406. * option: option, // whatever was passed into the method
  8407. * 'error code': 100 // other arbitrary info
  8408. * });
  8409. * }
  8410. * }
  8411. * });
  8412. *
  8413. * If a console is available (that supports the `console.dir` function) you'll see console output like:
  8414. *
  8415. * An error was raised with the following data:
  8416. * option: Object { foo: "bar"}
  8417. * foo: "bar"
  8418. * error code: 100
  8419. * msg: "You cannot do that!"
  8420. * sourceClass: "Ext.Foo"
  8421. * sourceMethod: "doSomething"
  8422. *
  8423. * uncaught exception: You cannot do that!
  8424. *
  8425. * As you can see, the error will report exactly where it was raised and will include as much information as the
  8426. * raising code can usefully provide.
  8427. *
  8428. * If you want to handle all application errors globally you can simply override the static {@link #handle} method
  8429. * and provide whatever handling logic you need. If the method returns true then the error is considered handled
  8430. * and will not be thrown to the browser. If anything but true is returned then the error will be thrown normally.
  8431. *
  8432. * Example usage:
  8433. *
  8434. * Ext.Error.handle = function(err) {
  8435. * if (err.someProperty == 'NotReallyAnError') {
  8436. * // maybe log something to the application here if applicable
  8437. * return true;
  8438. * }
  8439. * // any non-true return value (including none) will cause the error to be thrown
  8440. * }
  8441. *
  8442. */
  8443. Ext.Error = Ext.extend(Error, {
  8444. statics: {
  8445. /**
  8446. * @property {Boolean} ignore
  8447. * Static flag that can be used to globally disable error reporting to the browser if set to true
  8448. * (defaults to false). Note that if you ignore Ext errors it's likely that some other code may fail
  8449. * and throw a native JavaScript error thereafter, so use with caution. In most cases it will probably
  8450. * be preferable to supply a custom error {@link #handle handling} function instead.
  8451. *
  8452. * Example usage:
  8453. *
  8454. * Ext.Error.ignore = true;
  8455. *
  8456. * @static
  8457. */
  8458. ignore: false,
  8459. /**
  8460. * @property {Boolean} notify
  8461. * Static flag that can be used to globally control error notification to the user. Unlike
  8462. * Ex.Error.ignore, this does not effect exceptions. They are still thrown. This value can be
  8463. * set to false to disable the alert notification (default is true for IE6 and IE7).
  8464. *
  8465. * Only the first error will generate an alert. Internally this flag is set to false when the
  8466. * first error occurs prior to displaying the alert.
  8467. *
  8468. * This flag is not used in a release build.
  8469. *
  8470. * Example usage:
  8471. *
  8472. * Ext.Error.notify = false;
  8473. *
  8474. * @static
  8475. */
  8476. //notify: Ext.isIE6 || Ext.isIE7,
  8477. /**
  8478. * Raise an error that can include additional data and supports automatic console logging if available.
  8479. * You can pass a string error message or an object with the `msg` attribute which will be used as the
  8480. * error message. The object can contain any other name-value attributes (or objects) to be logged
  8481. * along with the error.
  8482. *
  8483. * Note that after displaying the error message a JavaScript error will ultimately be thrown so that
  8484. * execution will halt.
  8485. *
  8486. * Example usage:
  8487. *
  8488. * Ext.Error.raise('A simple string error message');
  8489. *
  8490. * // or...
  8491. *
  8492. * Ext.define('Ext.Foo', {
  8493. * doSomething: function(option){
  8494. * if (someCondition === false) {
  8495. * Ext.Error.raise({
  8496. * msg: 'You cannot do that!',
  8497. * option: option, // whatever was passed into the method
  8498. * 'error code': 100 // other arbitrary info
  8499. * });
  8500. * }
  8501. * }
  8502. * });
  8503. *
  8504. * @param {String/Object} err The error message string, or an object containing the attribute "msg" that will be
  8505. * used as the error message. Any other data included in the object will also be logged to the browser console,
  8506. * if available.
  8507. * @static
  8508. */
  8509. raise: function(err){
  8510. err = err || {};
  8511. if (Ext.isString(err)) {
  8512. err = { msg: err };
  8513. }
  8514. var method = this.raise.caller;
  8515. if (method) {
  8516. if (method.$name) {
  8517. err.sourceMethod = method.$name;
  8518. }
  8519. if (method.$owner) {
  8520. err.sourceClass = method.$owner.$className;
  8521. }
  8522. }
  8523. if (Ext.Error.handle(err) !== true) {
  8524. var msg = Ext.Error.prototype.toString.call(err);
  8525. Ext.log({
  8526. msg: msg,
  8527. level: 'error',
  8528. dump: err,
  8529. stack: true
  8530. });
  8531. throw new Ext.Error(err);
  8532. }
  8533. },
  8534. /**
  8535. * Globally handle any Ext errors that may be raised, optionally providing custom logic to
  8536. * handle different errors individually. Return true from the function to bypass throwing the
  8537. * error to the browser, otherwise the error will be thrown and execution will halt.
  8538. *
  8539. * Example usage:
  8540. *
  8541. * Ext.Error.handle = function(err) {
  8542. * if (err.someProperty == 'NotReallyAnError') {
  8543. * // maybe log something to the application here if applicable
  8544. * return true;
  8545. * }
  8546. * // any non-true return value (including none) will cause the error to be thrown
  8547. * }
  8548. *
  8549. * @param {Ext.Error} err The Ext.Error object being raised. It will contain any attributes that were originally
  8550. * raised with it, plus properties about the method and class from which the error originated (if raised from a
  8551. * class that uses the Ext 4 class system).
  8552. * @static
  8553. */
  8554. handle: function(){
  8555. return Ext.Error.ignore;
  8556. }
  8557. },
  8558. // This is the standard property that is the name of the constructor.
  8559. name: 'Ext.Error',
  8560. /**
  8561. * Creates new Error object.
  8562. * @param {String/Object} config The error message string, or an object containing the
  8563. * attribute "msg" that will be used as the error message. Any other data included in
  8564. * the object will be applied to the error instance and logged to the browser console, if available.
  8565. */
  8566. constructor: function(config){
  8567. if (Ext.isString(config)) {
  8568. config = { msg: config };
  8569. }
  8570. var me = this;
  8571. Ext.apply(me, config);
  8572. me.message = me.message || me.msg; // 'message' is standard ('msg' is non-standard)
  8573. // note: the above does not work in old WebKit (me.message is readonly) (Safari 4)
  8574. },
  8575. /**
  8576. * Provides a custom string representation of the error object. This is an override of the base JavaScript
  8577. * `Object.toString` method, which is useful so that when logged to the browser console, an error object will
  8578. * be displayed with a useful message instead of `[object Object]`, the default `toString` result.
  8579. *
  8580. * The default implementation will include the error message along with the raising class and method, if available,
  8581. * but this can be overridden with a custom implementation either at the prototype level (for all errors) or on
  8582. * a particular error instance, if you want to provide a custom description that will show up in the console.
  8583. * @return {String} The error message. If raised from within the Ext 4 class system, the error message will also
  8584. * include the raising class and method names, if available.
  8585. */
  8586. toString: function(){
  8587. var me = this,
  8588. className = me.className ? me.className : '',
  8589. methodName = me.methodName ? '.' + me.methodName + '(): ' : '',
  8590. msg = me.msg || '(No description provided)';
  8591. return className + methodName + msg;
  8592. }
  8593. });
  8594. /*
  8595. * Create a function that will throw an error if called (in debug mode) with a message that
  8596. * indicates the method has been removed.
  8597. * @param {String} suggestion Optional text to include in the message (a workaround perhaps).
  8598. * @return {Function} The generated function.
  8599. * @private
  8600. */
  8601. Ext.deprecated = function (suggestion) {
  8602. return Ext.emptyFn;
  8603. };
  8604. /*
  8605. * This mechanism is used to notify the user of the first error encountered on the page. This
  8606. * was previously internal to Ext.Error.raise and is a desirable feature since errors often
  8607. * slip silently under the radar. It cannot live in Ext.Error.raise since there are times
  8608. * where exceptions are handled in a try/catch.
  8609. */
  8610. /**
  8611. * @class Ext.JSON
  8612. * Modified version of Douglas Crockford's JSON.js that doesn't
  8613. * mess with the Object prototype
  8614. * http://www.json.org/js.html
  8615. * @singleton
  8616. */
  8617. Ext.JSON = new(function() {
  8618. var me = this,
  8619. encodingFunction,
  8620. decodingFunction,
  8621. useNative = null,
  8622. useHasOwn = !! {}.hasOwnProperty,
  8623. isNative = function() {
  8624. if (useNative === null) {
  8625. useNative = Ext.USE_NATIVE_JSON && window.JSON && JSON.toString() == '[object JSON]';
  8626. }
  8627. return useNative;
  8628. },
  8629. pad = function(n) {
  8630. return n < 10 ? "0" + n : n;
  8631. },
  8632. doDecode = function(json) {
  8633. return eval("(" + json + ')');
  8634. },
  8635. doEncode = function(o, newline) {
  8636. // http://jsperf.com/is-undefined
  8637. if (o === null || o === undefined) {
  8638. return "null";
  8639. } else if (Ext.isDate(o)) {
  8640. return Ext.JSON.encodeDate(o);
  8641. } else if (Ext.isString(o)) {
  8642. return encodeString(o);
  8643. }
  8644. // Allow custom zerialization by adding a toJSON method to any object type.
  8645. // Date/String have a toJSON in some environments, so check these first.
  8646. else if (o.toJSON) {
  8647. return o.toJSON();
  8648. } else if (Ext.isArray(o)) {
  8649. return encodeArray(o, newline);
  8650. } else if (typeof o == "number") {
  8651. //don't use isNumber here, since finite checks happen inside isNumber
  8652. return isFinite(o) ? String(o) : "null";
  8653. } else if (Ext.isBoolean(o)) {
  8654. return String(o);
  8655. } else if (Ext.isObject(o)) {
  8656. return encodeObject(o, newline);
  8657. } else if (typeof o === "function") {
  8658. return "null";
  8659. }
  8660. return 'undefined';
  8661. },
  8662. m = {
  8663. "\b": '\\b',
  8664. "\t": '\\t',
  8665. "\n": '\\n',
  8666. "\f": '\\f',
  8667. "\r": '\\r',
  8668. '"': '\\"',
  8669. "\\": '\\\\',
  8670. '\x0b': '\\u000b' //ie doesn't handle \v
  8671. },
  8672. charToReplace = /[\\\"\x00-\x1f\x7f-\uffff]/g,
  8673. encodeString = function(s) {
  8674. return '"' + s.replace(charToReplace, function(a) {
  8675. var c = m[a];
  8676. return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  8677. }) + '"';
  8678. },
  8679. encodeArray = function(o, newline) {
  8680. var a = ["[", ""], // Note empty string in case there are no serializable members.
  8681. len = o.length,
  8682. i;
  8683. for (i = 0; i < len; i += 1) {
  8684. a.push(doEncode(o[i]), ',');
  8685. }
  8686. // Overwrite trailing comma (or empty string)
  8687. a[a.length - 1] = ']';
  8688. return a.join("");
  8689. },
  8690. encodeObject = function(o, newline) {
  8691. var a = ["{", ""], // Note empty string in case there are no serializable members.
  8692. i;
  8693. for (i in o) {
  8694. if (!useHasOwn || o.hasOwnProperty(i)) {
  8695. a.push(doEncode(i), ":", doEncode(o[i]), ',');
  8696. }
  8697. }
  8698. // Overwrite trailing comma (or empty string)
  8699. a[a.length - 1] = '}';
  8700. return a.join("");
  8701. };
  8702. /**
  8703. * The function which {@link #encode} uses to encode all javascript values to their JSON representations
  8704. * when {@link Ext#USE_NATIVE_JSON} is `false`.
  8705. *
  8706. * This is made public so that it can be replaced with a custom implementation.
  8707. *
  8708. * @param {Object} o Any javascript value to be converted to its JSON representation
  8709. * @return {String} The JSON representation of the passed value.
  8710. * @method
  8711. */
  8712. me.encodeValue = doEncode;
  8713. /**
  8714. * Encodes a Date. This returns the actual string which is inserted into the JSON string as the literal expression.
  8715. * **The returned value includes enclosing double quotation marks.**
  8716. *
  8717. * The default return format is "yyyy-mm-ddThh:mm:ss".
  8718. *
  8719. * To override this:
  8720. * Ext.JSON.encodeDate = function(d) {
  8721. * return Ext.Date.format(d, '"Y-m-d"');
  8722. * };
  8723. *
  8724. * @param {Date} d The Date to encode
  8725. * @return {String} The string literal to use in a JSON string.
  8726. */
  8727. me.encodeDate = function(o) {
  8728. return '"' + o.getFullYear() + "-"
  8729. + pad(o.getMonth() + 1) + "-"
  8730. + pad(o.getDate()) + "T"
  8731. + pad(o.getHours()) + ":"
  8732. + pad(o.getMinutes()) + ":"
  8733. + pad(o.getSeconds()) + '"';
  8734. };
  8735. /**
  8736. * Encodes an Object, Array or other value.
  8737. *
  8738. * If the environment's native JSON encoding is not being used ({@link Ext#USE_NATIVE_JSON} is not set, or the environment does not support it), then
  8739. * ExtJS's encoding will be used. This allows the developer to add a `toJSON` method to their classes which need serializing to return a valid
  8740. * JSON representation of the object.
  8741. *
  8742. * @param {Object} o The variable to encode
  8743. * @return {String} The JSON string
  8744. */
  8745. me.encode = function(o) {
  8746. if (!encodingFunction) {
  8747. // setup encoding function on first access
  8748. encodingFunction = isNative() ? JSON.stringify : me.encodeValue;
  8749. }
  8750. return encodingFunction(o);
  8751. };
  8752. /**
  8753. * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError unless the safe option is set.
  8754. * @param {String} json The JSON string
  8755. * @param {Boolean} safe (optional) Whether to return null or throw an exception if the JSON is invalid.
  8756. * @return {Object} The resulting object
  8757. */
  8758. me.decode = function(json, safe) {
  8759. if (!decodingFunction) {
  8760. // setup decoding function on first access
  8761. decodingFunction = isNative() ? JSON.parse : doDecode;
  8762. }
  8763. try {
  8764. return decodingFunction(json);
  8765. } catch (e) {
  8766. if (safe === true) {
  8767. return null;
  8768. }
  8769. Ext.Error.raise({
  8770. sourceClass: "Ext.JSON",
  8771. sourceMethod: "decode",
  8772. msg: "You're trying to decode an invalid JSON String: " + json
  8773. });
  8774. }
  8775. };
  8776. })();
  8777. /**
  8778. * Shorthand for {@link Ext.JSON#encode}
  8779. * @member Ext
  8780. * @method encode
  8781. * @inheritdoc Ext.JSON#encode
  8782. */
  8783. Ext.encode = Ext.JSON.encode;
  8784. /**
  8785. * Shorthand for {@link Ext.JSON#decode}
  8786. * @member Ext
  8787. * @method decode
  8788. * @inheritdoc Ext.JSON#decode
  8789. */
  8790. Ext.decode = Ext.JSON.decode;
  8791. /**
  8792. * @class Ext
  8793. *
  8794. * The Ext namespace (global object) encapsulates all classes, singletons, and
  8795. * utility methods provided by Sencha's libraries.
  8796. *
  8797. * Most user interface Components are at a lower level of nesting in the namespace,
  8798. * but many common utility functions are provided as direct properties of the Ext namespace.
  8799. *
  8800. * Also many frequently used methods from other classes are provided as shortcuts
  8801. * within the Ext namespace. For example {@link Ext#getCmp Ext.getCmp} aliases
  8802. * {@link Ext.ComponentManager#get Ext.ComponentManager.get}.
  8803. *
  8804. * Many applications are initiated with {@link Ext#onReady Ext.onReady} which is
  8805. * called once the DOM is ready. This ensures all scripts have been loaded,
  8806. * preventing dependency issues. For example:
  8807. *
  8808. * Ext.onReady(function(){
  8809. * new Ext.Component({
  8810. * renderTo: document.body,
  8811. * html: 'DOM ready!'
  8812. * });
  8813. * });
  8814. *
  8815. * For more information about how to use the Ext classes, see:
  8816. *
  8817. * - <a href="http://www.sencha.com/learn/">The Learning Center</a>
  8818. * - <a href="http://www.sencha.com/learn/Ext_FAQ">The FAQ</a>
  8819. * - <a href="http://www.sencha.com/forum/">The forums</a>
  8820. *
  8821. * @singleton
  8822. */
  8823. Ext.apply(Ext, {
  8824. userAgent: navigator.userAgent.toLowerCase(),
  8825. cache: {},
  8826. idSeed: 1000,
  8827. windowId: 'ext-window',
  8828. documentId: 'ext-document',
  8829. /**
  8830. * True when the document is fully initialized and ready for action
  8831. */
  8832. isReady: false,
  8833. /**
  8834. * True to automatically uncache orphaned Ext.Elements periodically
  8835. */
  8836. enableGarbageCollector: true,
  8837. /**
  8838. * True to automatically purge event listeners during garbageCollection.
  8839. */
  8840. enableListenerCollection: true,
  8841. /**
  8842. * Generates unique ids. If the element already has an id, it is unchanged
  8843. * @param {HTMLElement/Ext.Element} [el] The element to generate an id for
  8844. * @param {String} prefix (optional) Id prefix (defaults "ext-gen")
  8845. * @return {String} The generated Id.
  8846. */
  8847. id: function(el, prefix) {
  8848. var me = this,
  8849. sandboxPrefix = '';
  8850. el = Ext.getDom(el, true) || {};
  8851. if (el === document) {
  8852. el.id = me.documentId;
  8853. }
  8854. else if (el === window) {
  8855. el.id = me.windowId;
  8856. }
  8857. if (!el.id) {
  8858. if (me.isSandboxed) {
  8859. sandboxPrefix = Ext.sandboxName.toLowerCase() + '-';
  8860. }
  8861. el.id = sandboxPrefix + (prefix || "ext-gen") + (++Ext.idSeed);
  8862. }
  8863. return el.id;
  8864. },
  8865. /**
  8866. * Returns the current document body as an {@link Ext.Element}.
  8867. * @return Ext.Element The document body
  8868. */
  8869. getBody: function() {
  8870. var body;
  8871. return function() {
  8872. return body || (body = Ext.get(document.body));
  8873. };
  8874. }(),
  8875. /**
  8876. * Returns the current document head as an {@link Ext.Element}.
  8877. * @return Ext.Element The document head
  8878. * @method
  8879. */
  8880. getHead: function() {
  8881. var head;
  8882. return function() {
  8883. return head || (head = Ext.get(document.getElementsByTagName("head")[0]));
  8884. };
  8885. }(),
  8886. /**
  8887. * Returns the current HTML document object as an {@link Ext.Element}.
  8888. * @return Ext.Element The document
  8889. */
  8890. getDoc: function() {
  8891. var doc;
  8892. return function() {
  8893. return doc || (doc = Ext.get(document));
  8894. };
  8895. }(),
  8896. /**
  8897. * This is shorthand reference to {@link Ext.ComponentManager#get}.
  8898. * Looks up an existing {@link Ext.Component Component} by {@link Ext.Component#id id}
  8899. *
  8900. * @param {String} id The component {@link Ext.Component#id id}
  8901. * @return Ext.Component The Component, `undefined` if not found, or `null` if a
  8902. * Class was found.
  8903. */
  8904. getCmp: function(id) {
  8905. return Ext.ComponentManager.get(id);
  8906. },
  8907. /**
  8908. * Returns the current orientation of the mobile device
  8909. * @return {String} Either 'portrait' or 'landscape'
  8910. */
  8911. getOrientation: function() {
  8912. return window.innerHeight > window.innerWidth ? 'portrait' : 'landscape';
  8913. },
  8914. /**
  8915. * Attempts to destroy any objects passed to it by removing all event listeners, removing them from the
  8916. * DOM (if applicable) and calling their destroy functions (if available). This method is primarily
  8917. * intended for arguments of type {@link Ext.Element} and {@link Ext.Component}, but any subclass of
  8918. * {@link Ext.util.Observable} can be passed in. Any number of elements and/or components can be
  8919. * passed into this function in a single call as separate arguments.
  8920. *
  8921. * @param {Ext.Element/Ext.Component/Ext.Element[]/Ext.Component[]...} args
  8922. * An {@link Ext.Element}, {@link Ext.Component}, or an Array of either of these to destroy
  8923. */
  8924. destroy: function() {
  8925. var ln = arguments.length,
  8926. i, arg;
  8927. for (i = 0; i < ln; i++) {
  8928. arg = arguments[i];
  8929. if (arg) {
  8930. if (Ext.isArray(arg)) {
  8931. this.destroy.apply(this, arg);
  8932. }
  8933. else if (Ext.isFunction(arg.destroy)) {
  8934. arg.destroy();
  8935. }
  8936. else if (arg.dom) {
  8937. arg.remove();
  8938. }
  8939. }
  8940. }
  8941. },
  8942. /**
  8943. * Execute a callback function in a particular scope. If no function is passed the call is ignored.
  8944. *
  8945. * For example, these lines are equivalent:
  8946. *
  8947. * Ext.callback(myFunc, this, [arg1, arg2]);
  8948. * Ext.isFunction(myFunc) && myFunc.apply(this, [arg1, arg2]);
  8949. *
  8950. * @param {Function} callback The callback to execute
  8951. * @param {Object} [scope] The scope to execute in
  8952. * @param {Array} [args] The arguments to pass to the function
  8953. * @param {Number} [delay] Pass a number to delay the call by a number of milliseconds.
  8954. */
  8955. callback: function(callback, scope, args, delay){
  8956. if(Ext.isFunction(callback)){
  8957. args = args || [];
  8958. scope = scope || window;
  8959. if (delay) {
  8960. Ext.defer(callback, delay, scope, args);
  8961. } else {
  8962. callback.apply(scope, args);
  8963. }
  8964. }
  8965. },
  8966. /**
  8967. * Alias for {@link Ext.String#htmlEncode}.
  8968. * @inheritdoc Ext.String#htmlEncode
  8969. */
  8970. htmlEncode : function(value) {
  8971. return Ext.String.htmlEncode(value);
  8972. },
  8973. /**
  8974. * Alias for {@link Ext.String#htmlDecode}.
  8975. * @inheritdoc Ext.String#htmlDecode
  8976. */
  8977. htmlDecode : function(value) {
  8978. return Ext.String.htmlDecode(value);
  8979. },
  8980. /**
  8981. * Alias for {@link Ext.String#urlAppend}.
  8982. * @inheritdoc Ext.String#urlAppend
  8983. */
  8984. urlAppend : function(url, s) {
  8985. return Ext.String.urlAppend(url, s);
  8986. }
  8987. });
  8988. Ext.ns = Ext.namespace;
  8989. // for old browsers
  8990. window.undefined = window.undefined;
  8991. /**
  8992. * @class Ext
  8993. */
  8994. (function(){
  8995. /*
  8996. FF 3.6 - Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.17) Gecko/20110420 Firefox/3.6.17
  8997. FF 4.0.1 - Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1
  8998. FF 5.0 - Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0
  8999. IE6 - Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1;)
  9000. IE7 - Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1;)
  9001. IE8 - Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)
  9002. IE9 - Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
  9003. Chrome 11 - Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.60 Safari/534.24
  9004. Safari 5 - Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1
  9005. Opera 11.11 - Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11
  9006. */
  9007. var check = function(regex){
  9008. return regex.test(Ext.userAgent);
  9009. },
  9010. isStrict = document.compatMode == "CSS1Compat",
  9011. version = function (is, regex) {
  9012. var m;
  9013. return (is && (m = regex.exec(Ext.userAgent))) ? parseFloat(m[1]) : 0;
  9014. },
  9015. docMode = document.documentMode,
  9016. isOpera = check(/opera/),
  9017. isOpera10_5 = isOpera && check(/version\/10\.5/),
  9018. isChrome = check(/\bchrome\b/),
  9019. isWebKit = check(/webkit/),
  9020. isSafari = !isChrome && check(/safari/),
  9021. isSafari2 = isSafari && check(/applewebkit\/4/), // unique to Safari 2
  9022. isSafari3 = isSafari && check(/version\/3/),
  9023. isSafari4 = isSafari && check(/version\/4/),
  9024. isSafari5 = isSafari && check(/version\/5/),
  9025. isIE = !isOpera && check(/msie/),
  9026. isIE7 = isIE && ((check(/msie 7/) && docMode != 8 && docMode != 9) || docMode == 7),
  9027. isIE8 = isIE && ((check(/msie 8/) && docMode != 7 && docMode != 9) || docMode == 8),
  9028. isIE9 = isIE && ((check(/msie 9/) && docMode != 7 && docMode != 8) || docMode == 9),
  9029. isIE6 = isIE && check(/msie 6/),
  9030. isGecko = !isWebKit && check(/gecko/),
  9031. isGecko3 = isGecko && check(/rv:1\.9/),
  9032. isGecko4 = isGecko && check(/rv:2\.0/),
  9033. isGecko5 = isGecko && check(/rv:5\./),
  9034. isGecko10 = isGecko && check(/rv:10\./),
  9035. isFF3_0 = isGecko3 && check(/rv:1\.9\.0/),
  9036. isFF3_5 = isGecko3 && check(/rv:1\.9\.1/),
  9037. isFF3_6 = isGecko3 && check(/rv:1\.9\.2/),
  9038. isWindows = check(/windows|win32/),
  9039. isMac = check(/macintosh|mac os x/),
  9040. isLinux = check(/linux/),
  9041. scrollbarSize = null,
  9042. chromeVersion = version(true, /\bchrome\/(\d+\.\d+)/),
  9043. firefoxVersion = version(true, /\bfirefox\/(\d+\.\d+)/),
  9044. ieVersion = version(isIE, /msie (\d+\.\d+)/),
  9045. operaVersion = version(isOpera, /version\/(\d+\.\d+)/),
  9046. safariVersion = version(isSafari, /version\/(\d+\.\d+)/),
  9047. webKitVersion = version(isWebKit, /webkit\/(\d+\.\d+)/),
  9048. isSecure = /^https/i.test(window.location.protocol);
  9049. // remove css image flicker
  9050. try {
  9051. document.execCommand("BackgroundImageCache", false, true);
  9052. } catch(e) {}
  9053. var nullLog = function () {};
  9054. nullLog.info = nullLog.warn = nullLog.error = Ext.emptyFn;
  9055. Ext.setVersion('extjs', '4.1.0');
  9056. Ext.apply(Ext, {
  9057. /**
  9058. * @property {String} SSL_SECURE_URL
  9059. * URL to a blank file used by Ext when in secure mode for iframe src and onReady src
  9060. * to prevent the IE insecure content warning (`'about:blank'`, except for IE
  9061. * in secure mode, which is `'javascript:""'`).
  9062. */
  9063. SSL_SECURE_URL : isSecure && isIE ? 'javascript:\'\'' : 'about:blank',
  9064. /**
  9065. * @property {Boolean} enableFx
  9066. * True if the {@link Ext.fx.Anim} Class is available.
  9067. */
  9068. /**
  9069. * @property {Boolean} scopeResetCSS
  9070. * True to scope the reset CSS to be just applied to Ext components. Note that this
  9071. * wraps root containers with an additional element. Also remember that when you turn
  9072. * on this option, you have to use ext-all-scoped (unless you use the bootstrap.js to
  9073. * load your javascript, in which case it will be handled for you).
  9074. */
  9075. scopeResetCSS : Ext.buildSettings.scopeResetCSS,
  9076. /**
  9077. * @property {String} resetCls
  9078. * The css class used to wrap Ext components when the {@link #scopeResetCSS} option
  9079. * is used.
  9080. */
  9081. resetCls: Ext.buildSettings.baseCSSPrefix + 'reset',
  9082. /**
  9083. * @property {Boolean} enableNestedListenerRemoval
  9084. * **Experimental.** True to cascade listener removal to child elements when an element
  9085. * is removed. Currently not optimized for performance.
  9086. */
  9087. enableNestedListenerRemoval : false,
  9088. /**
  9089. * @property {Boolean} USE_NATIVE_JSON
  9090. * Indicates whether to use native browser parsing for JSON methods.
  9091. * This option is ignored if the browser does not support native JSON methods.
  9092. *
  9093. * **Note:** Native JSON methods will not work with objects that have functions.
  9094. * Also, property names must be quoted, otherwise the data will not parse.
  9095. */
  9096. USE_NATIVE_JSON : false,
  9097. /**
  9098. * Returns the dom node for the passed String (id), dom node, or Ext.Element.
  9099. * Optional 'strict' flag is needed for IE since it can return 'name' and
  9100. * 'id' elements by using getElementById.
  9101. *
  9102. * Here are some examples:
  9103. *
  9104. * // gets dom node based on id
  9105. * var elDom = Ext.getDom('elId');
  9106. * // gets dom node based on the dom node
  9107. * var elDom1 = Ext.getDom(elDom);
  9108. *
  9109. * // If we don&#39;t know if we are working with an
  9110. * // Ext.Element or a dom node use Ext.getDom
  9111. * function(el){
  9112. * var dom = Ext.getDom(el);
  9113. * // do something with the dom node
  9114. * }
  9115. *
  9116. * **Note:** the dom node to be found actually needs to exist (be rendered, etc)
  9117. * when this method is called to be successful.
  9118. *
  9119. * @param {String/HTMLElement/Ext.Element} el
  9120. * @return HTMLElement
  9121. */
  9122. getDom : function(el, strict) {
  9123. if (!el || !document) {
  9124. return null;
  9125. }
  9126. if (el.dom) {
  9127. return el.dom;
  9128. } else {
  9129. if (typeof el == 'string') {
  9130. var e = Ext.getElementById(el);
  9131. // IE returns elements with the 'name' and 'id' attribute.
  9132. // we do a strict check to return the element with only the id attribute
  9133. if (e && isIE && strict) {
  9134. if (el == e.getAttribute('id')) {
  9135. return e;
  9136. } else {
  9137. return null;
  9138. }
  9139. }
  9140. return e;
  9141. } else {
  9142. return el;
  9143. }
  9144. }
  9145. },
  9146. /**
  9147. * Removes a DOM node from the document.
  9148. *
  9149. * Removes this element from the document, removes all DOM event listeners, and
  9150. * deletes the cache reference. All DOM event listeners are removed from this element.
  9151. * If {@link Ext#enableNestedListenerRemoval Ext.enableNestedListenerRemoval} is
  9152. * `true`, then DOM event listeners are also removed from all child nodes.
  9153. * The body node will be ignored if passed in.
  9154. *
  9155. * @param {HTMLElement} node The node to remove
  9156. * @method
  9157. */
  9158. removeNode : isIE6 || isIE7 ? function() {
  9159. var d;
  9160. return function(n){
  9161. if(n && n.tagName != 'BODY'){
  9162. (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n) : Ext.EventManager.removeAll(n);
  9163. d = d || document.createElement('div');
  9164. d.appendChild(n);
  9165. d.innerHTML = '';
  9166. delete Ext.cache[n.id];
  9167. }
  9168. };
  9169. }() : function(n) {
  9170. if (n && n.parentNode && n.tagName != 'BODY') {
  9171. (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n) : Ext.EventManager.removeAll(n);
  9172. n.parentNode.removeChild(n);
  9173. delete Ext.cache[n.id];
  9174. }
  9175. },
  9176. isStrict: isStrict,
  9177. isIEQuirks: isIE && !isStrict,
  9178. /**
  9179. * True if the detected browser is Opera.
  9180. * @type Boolean
  9181. */
  9182. isOpera : isOpera,
  9183. /**
  9184. * True if the detected browser is Opera 10.5x.
  9185. * @type Boolean
  9186. */
  9187. isOpera10_5 : isOpera10_5,
  9188. /**
  9189. * True if the detected browser uses WebKit.
  9190. * @type Boolean
  9191. */
  9192. isWebKit : isWebKit,
  9193. /**
  9194. * True if the detected browser is Chrome.
  9195. * @type Boolean
  9196. */
  9197. isChrome : isChrome,
  9198. /**
  9199. * True if the detected browser is Safari.
  9200. * @type Boolean
  9201. */
  9202. isSafari : isSafari,
  9203. /**
  9204. * True if the detected browser is Safari 3.x.
  9205. * @type Boolean
  9206. */
  9207. isSafari3 : isSafari3,
  9208. /**
  9209. * True if the detected browser is Safari 4.x.
  9210. * @type Boolean
  9211. */
  9212. isSafari4 : isSafari4,
  9213. /**
  9214. * True if the detected browser is Safari 5.x.
  9215. * @type Boolean
  9216. */
  9217. isSafari5 : isSafari5,
  9218. /**
  9219. * True if the detected browser is Safari 2.x.
  9220. * @type Boolean
  9221. */
  9222. isSafari2 : isSafari2,
  9223. /**
  9224. * True if the detected browser is Internet Explorer.
  9225. * @type Boolean
  9226. */
  9227. isIE : isIE,
  9228. /**
  9229. * True if the detected browser is Internet Explorer 6.x.
  9230. * @type Boolean
  9231. */
  9232. isIE6 : isIE6,
  9233. /**
  9234. * True if the detected browser is Internet Explorer 7.x.
  9235. * @type Boolean
  9236. */
  9237. isIE7 : isIE7,
  9238. /**
  9239. * True if the detected browser is Internet Explorer 8.x.
  9240. * @type Boolean
  9241. */
  9242. isIE8 : isIE8,
  9243. /**
  9244. * True if the detected browser is Internet Explorer 9.x.
  9245. * @type Boolean
  9246. */
  9247. isIE9 : isIE9,
  9248. /**
  9249. * True if the detected browser uses the Gecko layout engine (e.g. Mozilla, Firefox).
  9250. * @type Boolean
  9251. */
  9252. isGecko : isGecko,
  9253. /**
  9254. * True if the detected browser uses a Gecko 1.9+ layout engine (e.g. Firefox 3.x).
  9255. * @type Boolean
  9256. */
  9257. isGecko3 : isGecko3,
  9258. /**
  9259. * True if the detected browser uses a Gecko 2.0+ layout engine (e.g. Firefox 4.x).
  9260. * @type Boolean
  9261. */
  9262. isGecko4 : isGecko4,
  9263. /**
  9264. * True if the detected browser uses a Gecko 5.0+ layout engine (e.g. Firefox 5.x).
  9265. * @type Boolean
  9266. */
  9267. isGecko5 : isGecko5,
  9268. /**
  9269. * True if the detected browser uses a Gecko 5.0+ layout engine (e.g. Firefox 5.x).
  9270. * @type Boolean
  9271. */
  9272. isGecko10 : isGecko10,
  9273. /**
  9274. * True if the detected browser uses FireFox 3.0
  9275. * @type Boolean
  9276. */
  9277. isFF3_0 : isFF3_0,
  9278. /**
  9279. * True if the detected browser uses FireFox 3.5
  9280. * @type Boolean
  9281. */
  9282. isFF3_5 : isFF3_5,
  9283. /**
  9284. * True if the detected browser uses FireFox 3.6
  9285. * @type Boolean
  9286. */
  9287. isFF3_6 : isFF3_6,
  9288. /**
  9289. * True if the detected browser uses FireFox 4
  9290. * @type Boolean
  9291. */
  9292. isFF4 : 4 <= firefoxVersion && firefoxVersion < 5,
  9293. /**
  9294. * True if the detected browser uses FireFox 5
  9295. * @type Boolean
  9296. */
  9297. isFF5 : 5 <= firefoxVersion && firefoxVersion < 6,
  9298. /**
  9299. * True if the detected browser uses FireFox 10
  9300. * @type Boolean
  9301. */
  9302. isFF10 : 10 <= firefoxVersion && firefoxVersion < 11,
  9303. /**
  9304. * True if the detected platform is Linux.
  9305. * @type Boolean
  9306. */
  9307. isLinux : isLinux,
  9308. /**
  9309. * True if the detected platform is Windows.
  9310. * @type Boolean
  9311. */
  9312. isWindows : isWindows,
  9313. /**
  9314. * True if the detected platform is Mac OS.
  9315. * @type Boolean
  9316. */
  9317. isMac : isMac,
  9318. /**
  9319. * The current version of Chrome (0 if the browser is not Chrome).
  9320. * @type Number
  9321. */
  9322. chromeVersion: chromeVersion,
  9323. /**
  9324. * The current version of Firefox (0 if the browser is not Firefox).
  9325. * @type Number
  9326. */
  9327. firefoxVersion: firefoxVersion,
  9328. /**
  9329. * The current version of IE (0 if the browser is not IE). This does not account
  9330. * for the documentMode of the current page, which is factored into {@link #isIE7},
  9331. * {@link #isIE8} and {@link #isIE9}. Thus this is not always true:
  9332. *
  9333. * Ext.isIE8 == (Ext.ieVersion == 8)
  9334. *
  9335. * @type Number
  9336. */
  9337. ieVersion: ieVersion,
  9338. /**
  9339. * The current version of Opera (0 if the browser is not Opera).
  9340. * @type Number
  9341. */
  9342. operaVersion: operaVersion,
  9343. /**
  9344. * The current version of Safari (0 if the browser is not Safari).
  9345. * @type Number
  9346. */
  9347. safariVersion: safariVersion,
  9348. /**
  9349. * The current version of WebKit (0 if the browser does not use WebKit).
  9350. * @type Number
  9351. */
  9352. webKitVersion: webKitVersion,
  9353. /**
  9354. * True if the page is running over SSL
  9355. * @type Boolean
  9356. */
  9357. isSecure: isSecure,
  9358. /**
  9359. * URL to a 1x1 transparent gif image used by Ext to create inline icons with
  9360. * CSS background images. In older versions of IE, this defaults to
  9361. * "http://sencha.com/s.gif" and you should change this to a URL on your server.
  9362. * For other browsers it uses an inline data URL.
  9363. * @type String
  9364. */
  9365. BLANK_IMAGE_URL : (isIE6 || isIE7) ? '/' + '/www.sencha.com/s.gif' : 'data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==',
  9366. /**
  9367. * Utility method for returning a default value if the passed value is empty.
  9368. *
  9369. * The value is deemed to be empty if it is:
  9370. *
  9371. * - null
  9372. * - undefined
  9373. * - an empty array
  9374. * - a zero length string (Unless the `allowBlank` parameter is `true`)
  9375. *
  9376. * @param {Object} value The value to test
  9377. * @param {Object} defaultValue The value to return if the original value is empty
  9378. * @param {Boolean} [allowBlank=false] true to allow zero length strings to qualify as non-empty.
  9379. * @return {Object} value, if non-empty, else defaultValue
  9380. * @deprecated 4.0.0 Use {@link Ext#valueFrom} instead
  9381. */
  9382. value : function(v, defaultValue, allowBlank){
  9383. return Ext.isEmpty(v, allowBlank) ? defaultValue : v;
  9384. },
  9385. /**
  9386. * Escapes the passed string for use in a regular expression.
  9387. * @param {String} str
  9388. * @return {String}
  9389. * @deprecated 4.0.0 Use {@link Ext.String#escapeRegex} instead
  9390. */
  9391. escapeRe : function(s) {
  9392. return s.replace(/([-.*+?^${}()|[\]\/\\])/g, "\\$1");
  9393. },
  9394. /**
  9395. * Applies event listeners to elements by selectors when the document is ready.
  9396. * The event name is specified with an `@` suffix.
  9397. *
  9398. * Ext.addBehaviors({
  9399. * // add a listener for click on all anchors in element with id foo
  9400. * '#foo a@click' : function(e, t){
  9401. * // do something
  9402. * },
  9403. *
  9404. * // add the same listener to multiple selectors (separated by comma BEFORE the @)
  9405. * '#foo a, #bar span.some-class@mouseover' : function(){
  9406. * // do something
  9407. * }
  9408. * });
  9409. *
  9410. * @param {Object} obj The list of behaviors to apply
  9411. */
  9412. addBehaviors : function(o){
  9413. if(!Ext.isReady){
  9414. Ext.onReady(function(){
  9415. Ext.addBehaviors(o);
  9416. });
  9417. } else {
  9418. var cache = {}, // simple cache for applying multiple behaviors to same selector does query multiple times
  9419. parts,
  9420. b,
  9421. s;
  9422. for (b in o) {
  9423. if ((parts = b.split('@'))[1]) { // for Object prototype breakers
  9424. s = parts[0];
  9425. if(!cache[s]){
  9426. cache[s] = Ext.select(s);
  9427. }
  9428. cache[s].on(parts[1], o[b]);
  9429. }
  9430. }
  9431. cache = null;
  9432. }
  9433. },
  9434. /**
  9435. * Returns the size of the browser scrollbars. This can differ depending on
  9436. * operating system settings, such as the theme or font size.
  9437. * @param {Boolean} [force] true to force a recalculation of the value.
  9438. * @return {Object} An object containing scrollbar sizes.
  9439. * @return.width {Number} The width of the vertical scrollbar.
  9440. * @return.height {Number} The height of the horizontal scrollbar.
  9441. */
  9442. getScrollbarSize: function (force) {
  9443. if (!Ext.isReady) {
  9444. return {};
  9445. }
  9446. if (force || !scrollbarSize) {
  9447. var db = document.body,
  9448. div = document.createElement('div');
  9449. div.style.width = div.style.height = '100px';
  9450. div.style.overflow = 'scroll';
  9451. div.style.position = 'absolute';
  9452. db.appendChild(div); // now we can measure the div...
  9453. // at least in iE9 the div is not 100px - the scrollbar size is removed!
  9454. scrollbarSize = {
  9455. width: div.offsetWidth - div.clientWidth,
  9456. height: div.offsetHeight - div.clientHeight
  9457. };
  9458. db.removeChild(div);
  9459. }
  9460. return scrollbarSize;
  9461. },
  9462. /**
  9463. * Utility method for getting the width of the browser's vertical scrollbar. This
  9464. * can differ depending on operating system settings, such as the theme or font size.
  9465. *
  9466. * This method is deprected in favor of {@link #getScrollbarSize}.
  9467. *
  9468. * @param {Boolean} [force] true to force a recalculation of the value.
  9469. * @return {Number} The width of a vertical scrollbar.
  9470. * @deprecated
  9471. */
  9472. getScrollBarWidth: function(force){
  9473. var size = Ext.getScrollbarSize(force);
  9474. return size.width + 2; // legacy fudge factor
  9475. },
  9476. /**
  9477. * Copies a set of named properties fom the source object to the destination object.
  9478. *
  9479. * Example:
  9480. *
  9481. * ImageComponent = Ext.extend(Ext.Component, {
  9482. * initComponent: function() {
  9483. * this.autoEl = { tag: 'img' };
  9484. * MyComponent.superclass.initComponent.apply(this, arguments);
  9485. * this.initialBox = Ext.copyTo({}, this.initialConfig, 'x,y,width,height');
  9486. * }
  9487. * });
  9488. *
  9489. * Important note: To borrow class prototype methods, use {@link Ext.Base#borrow} instead.
  9490. *
  9491. * @param {Object} dest The destination object.
  9492. * @param {Object} source The source object.
  9493. * @param {String/String[]} names Either an Array of property names, or a comma-delimited list
  9494. * of property names to copy.
  9495. * @param {Boolean} [usePrototypeKeys] Defaults to false. Pass true to copy keys off of the
  9496. * prototype as well as the instance.
  9497. * @return {Object} The modified object.
  9498. */
  9499. copyTo : function(dest, source, names, usePrototypeKeys){
  9500. if(typeof names == 'string'){
  9501. names = names.split(/[,;\s]/);
  9502. }
  9503. var n,
  9504. nLen = names.length,
  9505. name;
  9506. for(n = 0; n < nLen; n++) {
  9507. name = names[n];
  9508. if(usePrototypeKeys || source.hasOwnProperty(name)){
  9509. dest[name] = source[name];
  9510. }
  9511. }
  9512. return dest;
  9513. },
  9514. /**
  9515. * Attempts to destroy and then remove a set of named properties of the passed object.
  9516. * @param {Object} o The object (most likely a Component) who's properties you wish to destroy.
  9517. * @param {String...} args One or more names of the properties to destroy and remove from the object.
  9518. */
  9519. destroyMembers : function(o){
  9520. for (var i = 1, a = arguments, len = a.length; i < len; i++) {
  9521. Ext.destroy(o[a[i]]);
  9522. delete o[a[i]];
  9523. }
  9524. },
  9525. /**
  9526. * Logs a message. If a console is present it will be used. On Opera, the method
  9527. * "opera.postError" is called. In other cases, the message is logged to an array
  9528. * "Ext.log.out". An attached debugger can watch this array and view the log. The
  9529. * log buffer is limited to a maximum of "Ext.log.max" entries (defaults to 250).
  9530. * The `Ext.log.out` array can also be written to a popup window by entering the
  9531. * following in the URL bar (a "bookmarklet"):
  9532. *
  9533. * javascript:void(Ext.log.show());
  9534. *
  9535. * If additional parameters are passed, they are joined and appended to the message.
  9536. * A technique for tracing entry and exit of a function is this:
  9537. *
  9538. * function foo () {
  9539. * Ext.log({ indent: 1 }, '>> foo');
  9540. *
  9541. * // log statements in here or methods called from here will be indented
  9542. * // by one step
  9543. *
  9544. * Ext.log({ outdent: 1 }, '<< foo');
  9545. * }
  9546. *
  9547. * This method does nothing in a release build.
  9548. *
  9549. * @param {String/Object} message The message to log or an options object with any
  9550. * of the following properties:
  9551. *
  9552. * - `msg`: The message to log (required).
  9553. * - `level`: One of: "error", "warn", "info" or "log" (the default is "log").
  9554. * - `dump`: An object to dump to the log as part of the message.
  9555. * - `stack`: True to include a stack trace in the log.
  9556. * - `indent`: Cause subsequent log statements to be indented one step.
  9557. * - `outdent`: Cause this and following statements to be one step less indented.
  9558. *
  9559. * @method
  9560. */
  9561. log :
  9562. nullLog,
  9563. /**
  9564. * Partitions the set into two sets: a true set and a false set.
  9565. *
  9566. * Example 1:
  9567. *
  9568. * Ext.partition([true, false, true, true, false]);
  9569. * // returns [[true, true, true], [false, false]]
  9570. *
  9571. * Example 2:
  9572. *
  9573. * Ext.partition(
  9574. * Ext.query("p"),
  9575. * function(val){
  9576. * return val.className == "class1"
  9577. * }
  9578. * );
  9579. * // true are those paragraph elements with a className of "class1",
  9580. * // false set are those that do not have that className.
  9581. *
  9582. * @param {Array/NodeList} arr The array to partition
  9583. * @param {Function} truth (optional) a function to determine truth.
  9584. * If this is omitted the element itself must be able to be evaluated for its truthfulness.
  9585. * @return {Array} [array of truish values, array of falsy values]
  9586. * @deprecated 4.0.0 Will be removed in the next major version
  9587. */
  9588. partition : function(arr, truth){
  9589. var ret = [[],[]],
  9590. a, v,
  9591. aLen = arr.length;
  9592. for (a = 0; a < aLen; a++) {
  9593. v = arr[a];
  9594. ret[ (truth && truth(v, a, arr)) || (!truth && v) ? 0 : 1].push(v);
  9595. }
  9596. return ret;
  9597. },
  9598. /**
  9599. * Invokes a method on each item in an Array.
  9600. *
  9601. * Example:
  9602. *
  9603. * Ext.invoke(Ext.query("p"), "getAttribute", "id");
  9604. * // [el1.getAttribute("id"), el2.getAttribute("id"), ..., elN.getAttribute("id")]
  9605. *
  9606. * @param {Array/NodeList} arr The Array of items to invoke the method on.
  9607. * @param {String} methodName The method name to invoke.
  9608. * @param {Object...} args Arguments to send into the method invocation.
  9609. * @return {Array} The results of invoking the method on each item in the array.
  9610. * @deprecated 4.0.0 Will be removed in the next major version
  9611. */
  9612. invoke : function(arr, methodName){
  9613. var ret = [],
  9614. args = Array.prototype.slice.call(arguments, 2),
  9615. a, v,
  9616. aLen = arr.length;
  9617. for (a = 0; a < aLen; a++) {
  9618. v = arr[a];
  9619. if (v && typeof v[methodName] == 'function') {
  9620. ret.push(v[methodName].apply(v, args));
  9621. } else {
  9622. ret.push(undefined);
  9623. }
  9624. }
  9625. return ret;
  9626. },
  9627. /**
  9628. * Zips N sets together.
  9629. *
  9630. * Example 1:
  9631. *
  9632. * Ext.zip([1,2,3],[4,5,6]); // [[1,4],[2,5],[3,6]]
  9633. *
  9634. * Example 2:
  9635. *
  9636. * Ext.zip(
  9637. * [ "+", "-", "+"],
  9638. * [ 12, 10, 22],
  9639. * [ 43, 15, 96],
  9640. * function(a, b, c){
  9641. * return "$" + a + "" + b + "." + c
  9642. * }
  9643. * ); // ["$+12.43", "$-10.15", "$+22.96"]
  9644. *
  9645. * @param {Array/NodeList...} arr This argument may be repeated. Array(s)
  9646. * to contribute values.
  9647. * @param {Function} zipper (optional) The last item in the argument list.
  9648. * This will drive how the items are zipped together.
  9649. * @return {Array} The zipped set.
  9650. * @deprecated 4.0.0 Will be removed in the next major version
  9651. */
  9652. zip : function(){
  9653. var parts = Ext.partition(arguments, function( val ){ return typeof val != 'function'; }),
  9654. arrs = parts[0],
  9655. fn = parts[1][0],
  9656. len = Ext.max(Ext.pluck(arrs, "length")),
  9657. ret = [];
  9658. for (var i = 0; i < len; i++) {
  9659. ret[i] = [];
  9660. if(fn){
  9661. ret[i] = fn.apply(fn, Ext.pluck(arrs, i));
  9662. }else{
  9663. for (var j = 0, aLen = arrs.length; j < aLen; j++){
  9664. ret[i].push( arrs[j][i] );
  9665. }
  9666. }
  9667. }
  9668. return ret;
  9669. },
  9670. /**
  9671. * Turns an array into a sentence, joined by a specified connector - e.g.:
  9672. *
  9673. * Ext.toSentence(['Adama', 'Tigh', 'Roslin']); //'Adama, Tigh and Roslin'
  9674. * Ext.toSentence(['Adama', 'Tigh', 'Roslin'], 'or'); //'Adama, Tigh or Roslin'
  9675. *
  9676. * @param {String[]} items The array to create a sentence from
  9677. * @param {String} connector The string to use to connect the last two words.
  9678. * Usually 'and' or 'or' - defaults to 'and'.
  9679. * @return {String} The sentence string
  9680. * @deprecated 4.0.0 Will be removed in the next major version
  9681. */
  9682. toSentence: function(items, connector) {
  9683. var length = items.length;
  9684. if (length <= 1) {
  9685. return items[0];
  9686. } else {
  9687. var head = items.slice(0, length - 1),
  9688. tail = items[length - 1];
  9689. return Ext.util.Format.format("{0} {1} {2}", head.join(", "), connector || 'and', tail);
  9690. }
  9691. },
  9692. /**
  9693. * @property {Boolean} useShims
  9694. * By default, Ext intelligently decides whether floating elements should be shimmed.
  9695. * If you are using flash, you may want to set this to true.
  9696. */
  9697. useShims: isIE6
  9698. });
  9699. })();
  9700. /**
  9701. * Loads Ext.app.Application class and starts it up with given configuration after the page is ready.
  9702. *
  9703. * See Ext.app.Application for details.
  9704. *
  9705. * @param {Object} config
  9706. */
  9707. Ext.application = function(config) {
  9708. Ext.require('Ext.app.Application');
  9709. Ext.onReady(function() {
  9710. new Ext.app.Application(config);
  9711. });
  9712. };
  9713. //<localeInfo useApply="true" />
  9714. /**
  9715. * @class Ext.util.Format
  9716. This class is a centralized place for formatting functions. It includes
  9717. functions to format various different types of data, such as text, dates and numeric values.
  9718. __Localization__
  9719. This class contains several options for localization. These can be set once the library has loaded,
  9720. all calls to the functions from that point will use the locale settings that were specified.
  9721. Options include:
  9722. - thousandSeparator
  9723. - decimalSeparator
  9724. - currenyPrecision
  9725. - currencySign
  9726. - currencyAtEnd
  9727. This class also uses the default date format defined here: {@link Ext.Date#defaultFormat}.
  9728. __Using with renderers__
  9729. There are two helper functions that return a new function that can be used in conjunction with
  9730. grid renderers:
  9731. columns: [{
  9732. dataIndex: 'date',
  9733. renderer: Ext.util.Format.dateRenderer('Y-m-d')
  9734. }, {
  9735. dataIndex: 'time',
  9736. renderer: Ext.util.Format.numberRenderer('0.000')
  9737. }]
  9738. Functions that only take a single argument can also be passed directly:
  9739. columns: [{
  9740. dataIndex: 'cost',
  9741. renderer: Ext.util.Format.usMoney
  9742. }, {
  9743. dataIndex: 'productCode',
  9744. renderer: Ext.util.Format.uppercase
  9745. }]
  9746. __Using with XTemplates__
  9747. XTemplates can also directly use Ext.util.Format functions:
  9748. new Ext.XTemplate([
  9749. 'Date: {startDate:date("Y-m-d")}',
  9750. 'Cost: {cost:usMoney}'
  9751. ]);
  9752. * @markdown
  9753. * @singleton
  9754. */
  9755. (function() {
  9756. Ext.ns('Ext.util');
  9757. Ext.util.Format = {};
  9758. var UtilFormat = Ext.util.Format,
  9759. stripTagsRE = /<\/?[^>]+>/gi,
  9760. stripScriptsRe = /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,
  9761. nl2brRe = /\r?\n/g,
  9762. // A RegExp to remove from a number format string, all characters except digits and '.'
  9763. formatCleanRe = /[^\d\.]/g,
  9764. // A RegExp to remove from a number format string, all characters except digits and the local decimal separator.
  9765. // Created on first use. The local decimal separator character must be initialized for this to be created.
  9766. I18NFormatCleanRe;
  9767. Ext.apply(UtilFormat, {
  9768. /**
  9769. * @property {String} thousandSeparator
  9770. * <p>The character that the {@link #number} function uses as a thousand separator.</p>
  9771. * <p>This may be overridden in a locale file.</p>
  9772. */
  9773. //<locale>
  9774. thousandSeparator: ',',
  9775. //</locale>
  9776. /**
  9777. * @property {String} decimalSeparator
  9778. * <p>The character that the {@link #number} function uses as a decimal point.</p>
  9779. * <p>This may be overridden in a locale file.</p>
  9780. */
  9781. //<locale>
  9782. decimalSeparator: '.',
  9783. //</locale>
  9784. /**
  9785. * @property {Number} currencyPrecision
  9786. * <p>The number of decimal places that the {@link #currency} function displays.</p>
  9787. * <p>This may be overridden in a locale file.</p>
  9788. */
  9789. //<locale>
  9790. currencyPrecision: 2,
  9791. //</locale>
  9792. /**
  9793. * @property {String} currencySign
  9794. * <p>The currency sign that the {@link #currency} function displays.</p>
  9795. * <p>This may be overridden in a locale file.</p>
  9796. */
  9797. //<locale>
  9798. currencySign: '$',
  9799. //</locale>
  9800. /**
  9801. * @property {Boolean} currencyAtEnd
  9802. * <p>This may be set to <code>true</code> to make the {@link #currency} function
  9803. * append the currency sign to the formatted value.</p>
  9804. * <p>This may be overridden in a locale file.</p>
  9805. */
  9806. //<locale>
  9807. currencyAtEnd: false,
  9808. //</locale>
  9809. /**
  9810. * Checks a reference and converts it to empty string if it is undefined
  9811. * @param {Object} value Reference to check
  9812. * @return {Object} Empty string if converted, otherwise the original value
  9813. */
  9814. undef : function(value) {
  9815. return value !== undefined ? value : "";
  9816. },
  9817. /**
  9818. * Checks a reference and converts it to the default value if it's empty
  9819. * @param {Object} value Reference to check
  9820. * @param {String} defaultValue The value to insert of it's undefined (defaults to "")
  9821. * @return {String}
  9822. */
  9823. defaultValue : function(value, defaultValue) {
  9824. return value !== undefined && value !== '' ? value : defaultValue;
  9825. },
  9826. /**
  9827. * Returns a substring from within an original string
  9828. * @param {String} value The original text
  9829. * @param {Number} start The start index of the substring
  9830. * @param {Number} length The length of the substring
  9831. * @return {String} The substring
  9832. */
  9833. substr : function(value, start, length) {
  9834. return String(value).substr(start, length);
  9835. },
  9836. /**
  9837. * Converts a string to all lower case letters
  9838. * @param {String} value The text to convert
  9839. * @return {String} The converted text
  9840. */
  9841. lowercase : function(value) {
  9842. return String(value).toLowerCase();
  9843. },
  9844. /**
  9845. * Converts a string to all upper case letters
  9846. * @param {String} value The text to convert
  9847. * @return {String} The converted text
  9848. */
  9849. uppercase : function(value) {
  9850. return String(value).toUpperCase();
  9851. },
  9852. /**
  9853. * Format a number as US currency
  9854. * @param {Number/String} value The numeric value to format
  9855. * @return {String} The formatted currency string
  9856. */
  9857. usMoney : function(v) {
  9858. return UtilFormat.currency(v, '$', 2);
  9859. },
  9860. /**
  9861. * Format a number as a currency
  9862. * @param {Number/String} value The numeric value to format
  9863. * @param {String} sign The currency sign to use (defaults to {@link #currencySign})
  9864. * @param {Number} decimals The number of decimals to use for the currency (defaults to {@link #currencyPrecision})
  9865. * @param {Boolean} end True if the currency sign should be at the end of the string (defaults to {@link #currencyAtEnd})
  9866. * @return {String} The formatted currency string
  9867. */
  9868. currency: function(v, currencySign, decimals, end) {
  9869. var negativeSign = '',
  9870. format = ",0",
  9871. i = 0;
  9872. v = v - 0;
  9873. if (v < 0) {
  9874. v = -v;
  9875. negativeSign = '-';
  9876. }
  9877. decimals = Ext.isDefined(decimals) ? decimals : UtilFormat.currencyPrecision;
  9878. format += format + (decimals > 0 ? '.' : '');
  9879. for (; i < decimals; i++) {
  9880. format += '0';
  9881. }
  9882. v = UtilFormat.number(v, format);
  9883. if ((end || UtilFormat.currencyAtEnd) === true) {
  9884. return Ext.String.format("{0}{1}{2}", negativeSign, v, currencySign || UtilFormat.currencySign);
  9885. } else {
  9886. return Ext.String.format("{0}{1}{2}", negativeSign, currencySign || UtilFormat.currencySign, v);
  9887. }
  9888. },
  9889. /**
  9890. * Formats the passed date using the specified format pattern.
  9891. * @param {String/Date} value The value to format. If a string is passed, it is converted to a Date by the Javascript
  9892. * Date object's <a href="http://www.w3schools.com/jsref/jsref_parse.asp">parse()</a> method.
  9893. * @param {String} format (Optional) Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
  9894. * @return {String} The formatted date string.
  9895. */
  9896. date: function(v, format) {
  9897. if (!v) {
  9898. return "";
  9899. }
  9900. if (!Ext.isDate(v)) {
  9901. v = new Date(Date.parse(v));
  9902. }
  9903. return Ext.Date.dateFormat(v, format || Ext.Date.defaultFormat);
  9904. },
  9905. /**
  9906. * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
  9907. * @param {String} format Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
  9908. * @return {Function} The date formatting function
  9909. */
  9910. dateRenderer : function(format) {
  9911. return function(v) {
  9912. return UtilFormat.date(v, format);
  9913. };
  9914. },
  9915. /**
  9916. * Strips all HTML tags
  9917. * @param {Object} value The text from which to strip tags
  9918. * @return {String} The stripped text
  9919. */
  9920. stripTags : function(v) {
  9921. return !v ? v : String(v).replace(stripTagsRE, "");
  9922. },
  9923. /**
  9924. * Strips all script tags
  9925. * @param {Object} value The text from which to strip script tags
  9926. * @return {String} The stripped text
  9927. */
  9928. stripScripts : function(v) {
  9929. return !v ? v : String(v).replace(stripScriptsRe, "");
  9930. },
  9931. /**
  9932. * Simple format for a file size (xxx bytes, xxx KB, xxx MB)
  9933. * @param {Number/String} size The numeric value to format
  9934. * @return {String} The formatted file size
  9935. */
  9936. fileSize : function(size) {
  9937. if (size < 1024) {
  9938. return size + " bytes";
  9939. } else if (size < 1048576) {
  9940. return (Math.round(((size*10) / 1024))/10) + " KB";
  9941. } else {
  9942. return (Math.round(((size*10) / 1048576))/10) + " MB";
  9943. }
  9944. },
  9945. /**
  9946. * It does simple math for use in a template, for example:<pre><code>
  9947. * var tpl = new Ext.Template('{value} * 10 = {value:math("* 10")}');
  9948. * </code></pre>
  9949. * @return {Function} A function that operates on the passed value.
  9950. * @method
  9951. */
  9952. math : function(){
  9953. var fns = {};
  9954. return function(v, a){
  9955. if (!fns[a]) {
  9956. fns[a] = Ext.functionFactory('v', 'return v ' + a + ';');
  9957. }
  9958. return fns[a](v);
  9959. };
  9960. }(),
  9961. /**
  9962. * Rounds the passed number to the required decimal precision.
  9963. * @param {Number/String} value The numeric value to round.
  9964. * @param {Number} precision The number of decimal places to which to round the first parameter's value.
  9965. * @return {Number} The rounded value.
  9966. */
  9967. round : function(value, precision) {
  9968. var result = Number(value);
  9969. if (typeof precision == 'number') {
  9970. precision = Math.pow(10, precision);
  9971. result = Math.round(value * precision) / precision;
  9972. }
  9973. return result;
  9974. },
  9975. /**
  9976. * <p>Formats the passed number according to the passed format string.</p>
  9977. * <p>The number of digits after the decimal separator character specifies the number of
  9978. * decimal places in the resulting string. The <u>local-specific</u> decimal character is used in the result.</p>
  9979. * <p>The <i>presence</i> of a thousand separator character in the format string specifies that
  9980. * the <u>locale-specific</u> thousand separator (if any) is inserted separating thousand groups.</p>
  9981. * <p>By default, "," is expected as the thousand separator, and "." is expected as the decimal separator.</p>
  9982. * <p><b>New to Ext JS 4</b></p>
  9983. * <p>Locale-specific characters are always used in the formatted output when inserting
  9984. * thousand and decimal separators.</p>
  9985. * <p>The format string must specify separator characters according to US/UK conventions ("," as the
  9986. * thousand separator, and "." as the decimal separator)</p>
  9987. * <p>To allow specification of format strings according to local conventions for separator characters, add
  9988. * the string <code>/i</code> to the end of the format string.</p>
  9989. * <div style="margin-left:40px">examples (123456.789):
  9990. * <div style="margin-left:10px">
  9991. * 0 - (123456) show only digits, no precision<br>
  9992. * 0.00 - (123456.78) show only digits, 2 precision<br>
  9993. * 0.0000 - (123456.7890) show only digits, 4 precision<br>
  9994. * 0,000 - (123,456) show comma and digits, no precision<br>
  9995. * 0,000.00 - (123,456.78) show comma and digits, 2 precision<br>
  9996. * 0,0.00 - (123,456.78) shortcut method, show comma and digits, 2 precision<br>
  9997. * To allow specification of the formatting string using UK/US grouping characters (,) and decimal (.) for international numbers, add /i to the end.
  9998. * For example: 0.000,00/i
  9999. * </div></div>
  10000. * @param {Number} v The number to format.
  10001. * @param {String} format The way you would like to format this text.
  10002. * @return {String} The formatted number.
  10003. */
  10004. number : function(v, formatString) {
  10005. if (!formatString) {
  10006. return v;
  10007. }
  10008. v = Ext.Number.from(v, NaN);
  10009. if (isNaN(v)) {
  10010. return '';
  10011. }
  10012. var comma = UtilFormat.thousandSeparator,
  10013. dec = UtilFormat.decimalSeparator,
  10014. i18n = false,
  10015. neg = v < 0,
  10016. hasComma,
  10017. psplit;
  10018. v = Math.abs(v);
  10019. // The "/i" suffix allows caller to use a locale-specific formatting string.
  10020. // Clean the format string by removing all but numerals and the decimal separator.
  10021. // Then split the format string into pre and post decimal segments according to *what* the
  10022. // decimal separator is. If they are specifying "/i", they are using the local convention in the format string.
  10023. if (formatString.substr(formatString.length - 2) == '/i') {
  10024. if (!I18NFormatCleanRe) {
  10025. I18NFormatCleanRe = new RegExp('[^\\d\\' + UtilFormat.decimalSeparator + ']','g');
  10026. }
  10027. formatString = formatString.substr(0, formatString.length - 2);
  10028. i18n = true;
  10029. hasComma = formatString.indexOf(comma) != -1;
  10030. psplit = formatString.replace(I18NFormatCleanRe, '').split(dec);
  10031. } else {
  10032. hasComma = formatString.indexOf(',') != -1;
  10033. psplit = formatString.replace(formatCleanRe, '').split('.');
  10034. }
  10035. if (psplit.length > 2) {
  10036. } else if (psplit.length > 1) {
  10037. v = Ext.Number.toFixed(v, psplit[1].length);
  10038. } else {
  10039. v = Ext.Number.toFixed(v, 0);
  10040. }
  10041. var fnum = v.toString();
  10042. psplit = fnum.split('.');
  10043. if (hasComma) {
  10044. var cnum = psplit[0],
  10045. parr = [],
  10046. j = cnum.length,
  10047. m = Math.floor(j / 3),
  10048. n = cnum.length % 3 || 3,
  10049. i;
  10050. for (i = 0; i < j; i += n) {
  10051. if (i !== 0) {
  10052. n = 3;
  10053. }
  10054. parr[parr.length] = cnum.substr(i, n);
  10055. m -= 1;
  10056. }
  10057. fnum = parr.join(comma);
  10058. if (psplit[1]) {
  10059. fnum += dec + psplit[1];
  10060. }
  10061. } else {
  10062. if (psplit[1]) {
  10063. fnum = psplit[0] + dec + psplit[1];
  10064. }
  10065. }
  10066. if (neg) {
  10067. /*
  10068. * Edge case. If we have a very small negative number it will get rounded to 0,
  10069. * however the initial check at the top will still report as negative. Replace
  10070. * everything but 1-9 and check if the string is empty to determine a 0 value.
  10071. */
  10072. neg = fnum.replace(/[^1-9]/g, '') !== '';
  10073. }
  10074. return (neg ? '-' : '') + formatString.replace(/[\d,?\.?]+/, fnum);
  10075. },
  10076. /**
  10077. * Returns a number rendering function that can be reused to apply a number format multiple times efficiently
  10078. * @param {String} format Any valid number format string for {@link #number}
  10079. * @return {Function} The number formatting function
  10080. */
  10081. numberRenderer : function(format) {
  10082. return function(v) {
  10083. return UtilFormat.number(v, format);
  10084. };
  10085. },
  10086. /**
  10087. * Selectively do a plural form of a word based on a numeric value. For example, in a template,
  10088. * {commentCount:plural("Comment")} would result in "1 Comment" if commentCount was 1 or would be "x Comments"
  10089. * if the value is 0 or greater than 1.
  10090. * @param {Number} value The value to compare against
  10091. * @param {String} singular The singular form of the word
  10092. * @param {String} plural (optional) The plural form of the word (defaults to the singular with an "s")
  10093. */
  10094. plural : function(v, s, p) {
  10095. return v +' ' + (v == 1 ? s : (p ? p : s+'s'));
  10096. },
  10097. /**
  10098. * Converts newline characters to the HTML tag &lt;br/>
  10099. * @param {String} The string value to format.
  10100. * @return {String} The string with embedded &lt;br/> tags in place of newlines.
  10101. */
  10102. nl2br : function(v) {
  10103. return Ext.isEmpty(v) ? '' : v.replace(nl2brRe, '<br/>');
  10104. },
  10105. /**
  10106. * Alias for {@link Ext.String#capitalize}.
  10107. * @method
  10108. * @inheritdoc Ext.String#capitalize
  10109. */
  10110. capitalize: Ext.String.capitalize,
  10111. /**
  10112. * Alias for {@link Ext.String#ellipsis}.
  10113. * @method
  10114. * @inheritdoc Ext.String#ellipsis
  10115. */
  10116. ellipsis: Ext.String.ellipsis,
  10117. /**
  10118. * Alias for {@link Ext.String#format}.
  10119. * @method
  10120. * @inheritdoc Ext.String#format
  10121. */
  10122. format: Ext.String.format,
  10123. /**
  10124. * Alias for {@link Ext.String#htmlDecode}.
  10125. * @method
  10126. * @inheritdoc Ext.String#htmlDecode
  10127. */
  10128. htmlDecode: Ext.String.htmlDecode,
  10129. /**
  10130. * Alias for {@link Ext.String#htmlEncode}.
  10131. * @method
  10132. * @inheritdoc Ext.String#htmlEncode
  10133. */
  10134. htmlEncode: Ext.String.htmlEncode,
  10135. /**
  10136. * Alias for {@link Ext.String#leftPad}.
  10137. * @method
  10138. * @inheritdoc Ext.String#leftPad
  10139. */
  10140. leftPad: Ext.String.leftPad,
  10141. /**
  10142. * Alias for {@link Ext.String#trim}.
  10143. * @method
  10144. * @inheritdoc Ext.String#trim
  10145. */
  10146. trim : Ext.String.trim,
  10147. /**
  10148. * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations
  10149. * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result)
  10150. * @param {Number/String} v The encoded margins
  10151. * @return {Object} An object with margin sizes for top, right, bottom and left
  10152. */
  10153. parseBox : function(box) {
  10154. box = Ext.isEmpty(box) ? '' : box;
  10155. if (Ext.isNumber(box)) {
  10156. box = box.toString();
  10157. }
  10158. var parts = box.split(' '),
  10159. ln = parts.length;
  10160. if (ln == 1) {
  10161. parts[1] = parts[2] = parts[3] = parts[0];
  10162. }
  10163. else if (ln == 2) {
  10164. parts[2] = parts[0];
  10165. parts[3] = parts[1];
  10166. }
  10167. else if (ln == 3) {
  10168. parts[3] = parts[1];
  10169. }
  10170. return {
  10171. top :parseInt(parts[0], 10) || 0,
  10172. right :parseInt(parts[1], 10) || 0,
  10173. bottom:parseInt(parts[2], 10) || 0,
  10174. left :parseInt(parts[3], 10) || 0
  10175. };
  10176. },
  10177. /**
  10178. * Escapes the passed string for use in a regular expression
  10179. * @param {String} str
  10180. * @return {String}
  10181. */
  10182. escapeRegex : function(s) {
  10183. return s.replace(/([\-.*+?\^${}()|\[\]\/\\])/g, "\\$1");
  10184. }
  10185. });
  10186. })();
  10187. /**
  10188. * Provides the ability to execute one or more arbitrary tasks in a asynchronous manner.
  10189. * Generally, you can use the singleton {@link Ext.TaskManager} instead, but if needed,
  10190. * you can create separate instances of TaskRunner. Any number of separate tasks can be
  10191. * started at any time and will run independently of each other.
  10192. *
  10193. * Example usage:
  10194. *
  10195. * // Start a simple clock task that updates a div once per second
  10196. * var updateClock = function () {
  10197. * Ext.fly('clock').update(new Date().format('g:i:s A'));
  10198. * }
  10199. *
  10200. * var runner = new Ext.util.TaskRunner();
  10201. * var task = runner.start({
  10202. * run: updateClock,
  10203. * interval: 1000
  10204. * }
  10205. *
  10206. * The equivalent using TaskManager:
  10207. *
  10208. * var task = Ext.TaskManager.start({
  10209. * run: updateClock,
  10210. * interval: 1000
  10211. * });
  10212. *
  10213. * To end a running task:
  10214. *
  10215. * task.destroy();
  10216. *
  10217. * If a task needs to be started and stopped repeated over time, you can create a
  10218. * {@link Ext.util.TaskRunner.Task Task} instance.
  10219. *
  10220. * var task = runner.newTask({
  10221. * run: function () {
  10222. * // useful code
  10223. * },
  10224. * interval: 1000
  10225. * });
  10226. *
  10227. * task.start();
  10228. *
  10229. * // ...
  10230. *
  10231. * task.stop();
  10232. *
  10233. * // ...
  10234. *
  10235. * task.start();
  10236. *
  10237. * A re-usable, one-shot task can be managed similar to the above:
  10238. *
  10239. * var task = runner.newTask({
  10240. * run: function () {
  10241. * // useful code to run once
  10242. * },
  10243. * repeat: 1
  10244. * });
  10245. *
  10246. * task.start();
  10247. *
  10248. * // ...
  10249. *
  10250. * task.start();
  10251. *
  10252. * See the {@link #start} method for details about how to configure a task object.
  10253. *
  10254. * Also see {@link Ext.util.DelayedTask}.
  10255. *
  10256. * @constructor
  10257. * @param {Number/Object} [interval=10] The minimum precision in milliseconds supported by this
  10258. * TaskRunner instance. Alternatively, a config object to apply to the new instance.
  10259. */
  10260. Ext.define('Ext.util.TaskRunner', {
  10261. /**
  10262. * @cfg interval
  10263. * The timer resolution.
  10264. */
  10265. interval: 10,
  10266. /**
  10267. * @property timerId
  10268. * The id of the current timer.
  10269. * @private
  10270. */
  10271. timerId: null,
  10272. constructor: function (interval) {
  10273. var me = this;
  10274. if (typeof interval == 'number') {
  10275. me.interval = interval;
  10276. } else if (interval) {
  10277. Ext.apply(me, interval);
  10278. }
  10279. me.tasks = [];
  10280. me.timerFn = Ext.Function.bind(me.onTick, me);
  10281. },
  10282. /**
  10283. * Creates a new {@link Ext.util.TaskRunner.Task Task} instance. These instances can
  10284. * be easily started and stopped.
  10285. * @param {Object} config The config object. For details on the supported properties,
  10286. * see {@link #start}.
  10287. */
  10288. newTask: function (config) {
  10289. var task = new Ext.util.TaskRunner.Task(config);
  10290. task.manager = this;
  10291. return task;
  10292. },
  10293. /**
  10294. * Starts a new task.
  10295. *
  10296. * Before each invocation, Ext injects the property `taskRunCount` into the task object
  10297. * so that calculations based on the repeat count can be performed.
  10298. *
  10299. * The returned task will contain a `destroy` method that can be used to destroy the
  10300. * task and cancel further calls. This is equivalent to the {@link #stop} method.
  10301. *
  10302. * @param {Object} task A config object that supports the following properties:
  10303. * @param {Function} task.run The function to execute each time the task is invoked. The
  10304. * function will be called at each interval and passed the `args` argument if specified,
  10305. * and the current invocation count if not.
  10306. *
  10307. * If a particular scope (`this` reference) is required, be sure to specify it using
  10308. * the `scope` argument.
  10309. *
  10310. * @param {Boolean} task.run.return `false` from this function to terminate the task.
  10311. *
  10312. * @param {Number} task.interval The frequency in milliseconds with which the task
  10313. * should be invoked.
  10314. *
  10315. * @param {Object[]} task.args An array of arguments to be passed to the function
  10316. * specified by `run`. If not specified, the current invocation count is passed.
  10317. *
  10318. * @param {Object} task.scope The scope (`this` reference) in which to execute the
  10319. * `run` function. Defaults to the task config object.
  10320. *
  10321. * @param {Number} task.duration The length of time in milliseconds to invoke the task
  10322. * before stopping automatically (defaults to indefinite).
  10323. *
  10324. * @param {Number} task.repeat The number of times to invoke the task before stopping
  10325. * automatically (defaults to indefinite).
  10326. * @return {Object} The task
  10327. */
  10328. start: function(task) {
  10329. var me = this,
  10330. now = new Date().getTime();
  10331. if (!task.pending) {
  10332. me.tasks.push(task);
  10333. task.pending = true; // don't allow the task to be added to me.tasks again
  10334. }
  10335. task.stopped = false; // might have been previously stopped...
  10336. task.taskRunTime = task.taskStartTime = now;
  10337. task.taskRunCount = 0;
  10338. if (!me.firing) {
  10339. me.startTimer(task.interval, now);
  10340. }
  10341. return task;
  10342. },
  10343. /**
  10344. * Stops an existing running task.
  10345. * @param {Object} task The task to stop
  10346. * @return {Object} The task
  10347. */
  10348. stop: function(task) {
  10349. // NOTE: we don't attempt to remove the task from me.tasks at this point because
  10350. // this could be called from inside a task which would then corrupt the state of
  10351. // the loop in onTick
  10352. if (!task.stopped) {
  10353. task.stopped = true;
  10354. if (task.onStop) {
  10355. task.onStop.call(task.scope || task);
  10356. }
  10357. }
  10358. return task;
  10359. },
  10360. /**
  10361. * Stops all tasks that are currently running.
  10362. */
  10363. stopAll: function() {
  10364. // onTick will take care of cleaning up the mess after this point...
  10365. Ext.each(this.tasks, this.stop, this);
  10366. },
  10367. //-------------------------------------------------------------------------
  10368. firing: false,
  10369. nextExpires: 1e99,
  10370. // private
  10371. onTick: function () {
  10372. var me = this,
  10373. tasks = me.tasks,
  10374. now = new Date().getTime(),
  10375. nextExpires = 1e99,
  10376. len = tasks.length,
  10377. expires, newTasks, i, task, rt, remove;
  10378. me.timerId = null;
  10379. me.firing = true; // ensure we don't startTimer during this loop...
  10380. // tasks.length can be > len if start is called during a task.run call... so we
  10381. // first check len to avoid tasks.length reference but eventually we need to also
  10382. // check tasks.length. we avoid repeating use of tasks.length by setting len at
  10383. // that time (to help the next loop)
  10384. for (i = 0; i < len || i < (len = tasks.length); ++i) {
  10385. task = tasks[i];
  10386. if (!(remove = task.stopped)) {
  10387. expires = task.taskRunTime + task.interval;
  10388. if (expires <= now) {
  10389. rt = task.run.apply(task.scope || task, task.args || [++task.taskRunCount]);
  10390. task.taskRunTime = now;
  10391. if (rt === false || task.taskRunCount === task.repeat) {
  10392. me.stop(task);
  10393. remove = true;
  10394. } else {
  10395. remove = task.stopped; // in case stop was called by run
  10396. expires = now + task.interval;
  10397. }
  10398. }
  10399. if (!remove && task.duration && task.duration <= (now - task.taskStartTime)) {
  10400. me.stop(task);
  10401. remove = true;
  10402. }
  10403. }
  10404. if (remove) {
  10405. task.pending = false; // allow the task to be added to me.tasks again
  10406. // once we detect that a task needs to be removed, we copy the tasks that
  10407. // will carry forward into newTasks... this way we avoid O(N*N) to remove
  10408. // each task from the tasks array (and ripple the array down) and also the
  10409. // potentially wasted effort of making a new tasks[] even if all tasks are
  10410. // going into the next wave.
  10411. if (!newTasks) {
  10412. newTasks = tasks.slice(0, i);
  10413. // we don't set me.tasks here because callbacks can also start tasks,
  10414. // which get added to me.tasks... so we will visit them in this loop
  10415. // and account for their expirations in nextExpires...
  10416. }
  10417. } else {
  10418. if (newTasks) {
  10419. newTasks.push(task); // we've cloned the tasks[], so keep this one...
  10420. }
  10421. if (nextExpires > expires) {
  10422. nextExpires = expires; // track the nearest expiration time
  10423. }
  10424. }
  10425. }
  10426. if (newTasks) {
  10427. // only now can we copy the newTasks to me.tasks since no user callbacks can
  10428. // take place
  10429. me.tasks = newTasks;
  10430. }
  10431. me.firing = false; // we're done, so allow startTimer afterwards
  10432. if (me.tasks.length) {
  10433. // we create a new Date here because all the callbacks could have taken a long
  10434. // time... we want to base the next timeout on the current time (after the
  10435. // callback storm):
  10436. me.startTimer(nextExpires - now, new Date().getTime());
  10437. }
  10438. },
  10439. // private
  10440. startTimer: function (timeout, now) {
  10441. var me = this,
  10442. expires = now + timeout,
  10443. timerId = me.timerId;
  10444. // Check to see if this request is enough in advance of the current timer. If so,
  10445. // we reschedule the timer based on this new expiration.
  10446. if (timerId && me.nextExpires - expires > me.interval) {
  10447. clearTimeout(timerId);
  10448. timerId = null;
  10449. }
  10450. if (!timerId) {
  10451. if (timeout < me.interval) {
  10452. timeout = me.interval;
  10453. }
  10454. me.timerId = setTimeout(me.timerFn, timeout);
  10455. me.nextExpires = expires;
  10456. }
  10457. }
  10458. },
  10459. function () {
  10460. var me = this,
  10461. proto = me.prototype;
  10462. /**
  10463. * Destroys this instance, stopping all tasks that are currently running.
  10464. * @method destroy
  10465. */
  10466. proto.destroy = proto.stopAll;
  10467. /**
  10468. * @class Ext.TaskManager
  10469. * @extends Ext.util.TaskRunner
  10470. * @singleton
  10471. *
  10472. * A static {@link Ext.util.TaskRunner} instance that can be used to start and stop
  10473. * arbitrary tasks. See {@link Ext.util.TaskRunner} for supported methods and task
  10474. * config properties.
  10475. *
  10476. * // Start a simple clock task that updates a div once per second
  10477. * var task = {
  10478. * run: function(){
  10479. * Ext.fly('clock').update(new Date().format('g:i:s A'));
  10480. * },
  10481. * interval: 1000 //1 second
  10482. * }
  10483. *
  10484. * Ext.TaskManager.start(task);
  10485. *
  10486. * See the {@link #start} method for details about how to configure a task object.
  10487. */
  10488. Ext.util.TaskManager = Ext.TaskManager = new me();
  10489. /**
  10490. * Instances of this class are created by {@link Ext.util.TaskRunner#newTask} method.
  10491. *
  10492. * For details on config properties, see {@link Ext.util.TaskRunner#start}.
  10493. * @class Ext.util.TaskRunner.Task
  10494. */
  10495. me.Task = new Ext.Class({
  10496. isTask: true,
  10497. /**
  10498. * This flag is set to `true` by {@link #stop}.
  10499. * @private
  10500. */
  10501. stopped: true, // this avoids the odd combination of !stopped && !pending
  10502. constructor: function (config) {
  10503. Ext.apply(this, config);
  10504. },
  10505. /**
  10506. * Restarts this task, clearing it duration, expiration and run count.
  10507. * @param {Number} [interval] Optionally reset this task's interval.
  10508. */
  10509. restart: function (interval) {
  10510. if (interval !== undefined) {
  10511. this.interval = interval;
  10512. }
  10513. this.manager.start(this);
  10514. },
  10515. /**
  10516. * Starts this task if it is not already started.
  10517. * @param {Number} [interval] Optionally reset this task's interval.
  10518. */
  10519. start: function (interval) {
  10520. if (this.stopped) {
  10521. this.restart(interval);
  10522. }
  10523. },
  10524. /**
  10525. * Stops this task.
  10526. */
  10527. stop: function () {
  10528. this.manager.stop(this);
  10529. }
  10530. });
  10531. proto = me.Task.prototype;
  10532. /**
  10533. * Destroys this instance, stopping this task's execution.
  10534. * @method destroy
  10535. */
  10536. proto.destroy = proto.stop;
  10537. });
  10538. /**
  10539. * @class Ext.perf.Accumulator
  10540. * @private
  10541. */
  10542. Ext.define('Ext.perf.Accumulator', function () {
  10543. var currentFrame = null,
  10544. khrome = Ext.global['chrome'],
  10545. formatTpl,
  10546. // lazy init on first request for timestamp (avoids infobar in IE until needed)
  10547. // Also avoids kicking off Chrome's microsecond timer until first needed
  10548. getTimestamp = function () {
  10549. getTimestamp = function () {
  10550. return new Date().getTime();
  10551. }
  10552. // If Chrome is started with the --enable-benchmarking switch
  10553. if (Ext.isChrome && khrome && khrome.Interval) {
  10554. var interval = new khrome.Interval();
  10555. interval.start();
  10556. getTimestamp = function () {
  10557. return interval.microseconds() / 1000;
  10558. }
  10559. }
  10560. else if (window.ActiveXObject) {
  10561. try {
  10562. // the above technique is not very accurate for small intervals...
  10563. var toolbox = new ActiveXObject('SenchaToolbox.Toolbox');
  10564. getTimestamp = function () {
  10565. return toolbox.milliseconds;
  10566. };
  10567. } catch (e) {
  10568. // ignore
  10569. }
  10570. } else if (Date.now) {
  10571. getTimestamp = Date.now;
  10572. }
  10573. Ext.perf.getTimestamp = Ext.perf.Accumulator.getTimestamp = getTimestamp;
  10574. return getTimestamp();
  10575. };
  10576. function adjustSet (set, time) {
  10577. set.sum += time;
  10578. set.min = Math.min(set.min, time);
  10579. set.max = Math.max(set.max, time);
  10580. }
  10581. function leaveFrame (time) {
  10582. var totalTime = time ? time : (getTimestamp() - this.time), // do this first
  10583. me = this, // me = frame
  10584. accum = me.accum;
  10585. ++accum.count;
  10586. if (! --accum.depth) {
  10587. adjustSet(accum.total, totalTime);
  10588. }
  10589. adjustSet(accum.pure, totalTime - me.childTime);
  10590. currentFrame = me.parent;
  10591. if (currentFrame) {
  10592. ++currentFrame.accum.childCount;
  10593. currentFrame.childTime += totalTime;
  10594. }
  10595. }
  10596. function makeSet () {
  10597. return {
  10598. min: Number.MAX_VALUE,
  10599. max: 0,
  10600. sum: 0
  10601. }
  10602. }
  10603. function makeTap (me, fn) {
  10604. return function () {
  10605. var frame = me.enter(),
  10606. ret = fn.apply(this, arguments);
  10607. frame.leave();
  10608. return ret;
  10609. };
  10610. }
  10611. function round (x) {
  10612. return Math.round(x * 100) / 100;
  10613. }
  10614. function setToJSON (count, childCount, calibration, set) {
  10615. var data = {
  10616. avg: 0,
  10617. min: set.min,
  10618. max: set.max,
  10619. sum: 0
  10620. };
  10621. if (count) {
  10622. calibration = calibration || 0;
  10623. data.sum = set.sum - childCount * calibration;
  10624. data.avg = data.sum / count;
  10625. // min and max cannot be easily corrected since we don't know the number of
  10626. // child calls for them.
  10627. }
  10628. return data;
  10629. }
  10630. return {
  10631. constructor: function (name) {
  10632. var me = this;
  10633. me.count = me.childCount = me.depth = me.maxDepth = 0;
  10634. me.pure = makeSet();
  10635. me.total = makeSet();
  10636. me.name = name;
  10637. },
  10638. statics: {
  10639. getTimestamp: getTimestamp
  10640. },
  10641. format: function (calibration) {
  10642. if (!formatTpl) {
  10643. formatTpl = new Ext.XTemplate([
  10644. '{name} - {count} call(s)',
  10645. '<tpl if="count">',
  10646. '<tpl if="childCount">',
  10647. ' ({childCount} children)',
  10648. '</tpl>',
  10649. '<tpl if="depth - 1">',
  10650. ' ({depth} deep)',
  10651. '</tpl>',
  10652. '<tpl for="times">',
  10653. ', {type}: {[this.time(values.sum)]} msec (',
  10654. //'min={[this.time(values.min)]}, ',
  10655. 'avg={[this.time(values.sum / parent.count)]}',
  10656. //', max={[this.time(values.max)]}',
  10657. ')',
  10658. '</tpl>',
  10659. '</tpl>'
  10660. ].join(''), {
  10661. time: function (t) {
  10662. return Math.round(t * 100) / 100;
  10663. }
  10664. });
  10665. }
  10666. var data = this.getData(calibration);
  10667. data.name = this.name;
  10668. data.pure.type = 'Pure';
  10669. data.total.type = 'Total';
  10670. data.times = [data.pure, data.total];
  10671. return formatTpl.apply(data);
  10672. },
  10673. getData: function (calibration) {
  10674. var me = this;
  10675. return {
  10676. count: me.count,
  10677. childCount: me.childCount,
  10678. depth: me.maxDepth,
  10679. pure: setToJSON(me.count, me.childCount, calibration, me.pure),
  10680. total: setToJSON(me.count, me.childCount, calibration, me.total)
  10681. };
  10682. },
  10683. enter: function () {
  10684. var me = this,
  10685. frame = {
  10686. accum: me,
  10687. leave: leaveFrame,
  10688. childTime: 0,
  10689. parent: currentFrame
  10690. };
  10691. ++me.depth;
  10692. if (me.maxDepth < me.depth) {
  10693. me.maxDepth = me.depth;
  10694. }
  10695. currentFrame = frame;
  10696. frame.time = getTimestamp(); // do this last
  10697. return frame;
  10698. },
  10699. monitor: function (fn, scope, args) {
  10700. var frame = this.enter();
  10701. if (args) {
  10702. fn.apply(scope, args);
  10703. } else {
  10704. fn.call(scope);
  10705. }
  10706. frame.leave();
  10707. },
  10708. report: function () {
  10709. Ext.log(this.format());
  10710. },
  10711. tap: function (className, methodName) {
  10712. var me = this,
  10713. methods = typeof methodName == 'string' ? [methodName] : methodName,
  10714. klass, statik, i, parts, length, name, src;
  10715. var tapFunc = function(){
  10716. if (typeof className == 'string') {
  10717. klass = Ext.global;
  10718. parts = className.split('.');
  10719. for (i = 0, length = parts.length; i < length; ++i) {
  10720. klass = klass[parts[i]];
  10721. }
  10722. } else {
  10723. klass = className;
  10724. }
  10725. for (i = 0, length = methods.length; i < length; ++i) {
  10726. name = methods[i];
  10727. statik = name.charAt(0) == '!';
  10728. if (statik) {
  10729. name = name.substring(1);
  10730. } else {
  10731. statik = !(name in klass.prototype);
  10732. }
  10733. src = statik ? klass : klass.prototype;
  10734. src[name] = makeTap(me, src[name]);
  10735. }
  10736. };
  10737. Ext.ClassManager.onCreated(tapFunc, me, className);
  10738. return me;
  10739. }
  10740. };
  10741. }(),
  10742. function () {
  10743. Ext.perf.getTimestamp = this.getTimestamp;
  10744. });
  10745. /**
  10746. * @class Ext.perf.Monitor
  10747. * @singleton
  10748. * @private
  10749. */
  10750. Ext.define('Ext.perf.Monitor', {
  10751. singleton: true,
  10752. alternateClassName: 'Ext.Perf',
  10753. requires: [
  10754. 'Ext.perf.Accumulator'
  10755. ],
  10756. constructor: function () {
  10757. this.accumulators = [];
  10758. this.accumulatorsByName = {};
  10759. },
  10760. calibrate: function () {
  10761. var accum = new Ext.perf.Accumulator('$'),
  10762. total = accum.total,
  10763. getTimestamp = Ext.perf.Accumulator.getTimestamp,
  10764. count = 0,
  10765. frame,
  10766. endTime,
  10767. startTime;
  10768. startTime = getTimestamp();
  10769. do {
  10770. frame = accum.enter();
  10771. frame.leave();
  10772. ++count;
  10773. } while (total.sum < 100);
  10774. endTime = getTimestamp();
  10775. return (endTime - startTime) / count;
  10776. },
  10777. get: function (name) {
  10778. var me = this,
  10779. accum = me.accumulatorsByName[name];
  10780. if (!accum) {
  10781. me.accumulatorsByName[name] = accum = new Ext.perf.Accumulator(name);
  10782. me.accumulators.push(accum);
  10783. }
  10784. return accum;
  10785. },
  10786. enter: function (name) {
  10787. return this.get(name).enter();
  10788. },
  10789. monitor: function (name, fn, scope) {
  10790. this.get(name).monitor(fn, scope);
  10791. },
  10792. report: function () {
  10793. var me = this,
  10794. accumulators = me.accumulators,
  10795. calibration = me.calibrate(),
  10796. report = ['Calibration: ' + Math.round(calibration * 100) / 100 + ' msec/sample'];
  10797. accumulators.sort(function (a, b) {
  10798. return (a.name < b.name) ? -1 : ((b.name < a.name) ? 1 : 0);
  10799. });
  10800. Ext.each(accumulators, function (accum) {
  10801. report.push(accum.format(calibration));
  10802. });
  10803. Ext.log(report.join('\n'));
  10804. },
  10805. getData: function (all) {
  10806. var ret = {},
  10807. accumulators = this.accumulators;
  10808. Ext.each(accumulators, function (accum) {
  10809. if (all || accum.count) {
  10810. ret[accum.name] = accum.getData();
  10811. }
  10812. });
  10813. return ret;
  10814. },
  10815. setup: function (config) {
  10816. if (!config) {
  10817. config = {
  10818. /*insertHtml: {
  10819. 'Ext.dom.Helper': 'insertHtml'
  10820. },*/
  10821. /*xtplCompile: {
  10822. 'Ext.XTemplateCompiler': 'compile'
  10823. },*/
  10824. // doInsert: {
  10825. // 'Ext.Template': 'doInsert'
  10826. // },
  10827. // applyOut: {
  10828. // 'Ext.XTemplate': 'applyOut'
  10829. // },
  10830. render: {
  10831. 'Ext.AbstractComponent': 'render'
  10832. },
  10833. // fnishRender: {
  10834. // 'Ext.AbstractComponent': 'finishRender'
  10835. // },
  10836. // renderSelectors: {
  10837. // 'Ext.AbstractComponent': 'applyRenderSelectors'
  10838. // },
  10839. // compAddCls: {
  10840. // 'Ext.AbstractComponent': 'addCls'
  10841. // },
  10842. // compRemoveCls: {
  10843. // 'Ext.AbstractComponent': 'removeCls'
  10844. // },
  10845. // getStyle: {
  10846. // 'Ext.core.Element': 'getStyle'
  10847. // },
  10848. // setStyle: {
  10849. // 'Ext.core.Element': 'setStyle'
  10850. // },
  10851. // addCls: {
  10852. // 'Ext.core.Element': 'addCls'
  10853. // },
  10854. // removeCls: {
  10855. // 'Ext.core.Element': 'removeCls'
  10856. // },
  10857. // measure: {
  10858. // 'Ext.layout.component.Component': 'measureAutoDimensions'
  10859. // },
  10860. // moveItem: {
  10861. // 'Ext.layout.Layout': 'moveItem'
  10862. // },
  10863. // layoutFlush: {
  10864. // 'Ext.layout.Context': 'flush'
  10865. // },
  10866. layout: {
  10867. 'Ext.layout.Context': 'run'
  10868. }
  10869. };
  10870. }
  10871. this.currentConfig = config;
  10872. var key, prop;
  10873. for (key in config) {
  10874. if (config.hasOwnProperty(key)) {
  10875. prop = config[key];
  10876. var accum = Ext.Perf.get(key),
  10877. className, methods;
  10878. for (className in prop) {
  10879. if (prop.hasOwnProperty(className)) {
  10880. methods = prop[className];
  10881. accum.tap(className, methods);
  10882. }
  10883. }
  10884. }
  10885. }
  10886. }
  10887. });
  10888. /**
  10889. * @class Ext.is
  10890. *
  10891. * Determines information about the current platform the application is running on.
  10892. *
  10893. * @singleton
  10894. */
  10895. Ext.is = {
  10896. init : function(navigator) {
  10897. var platforms = this.platforms,
  10898. ln = platforms.length,
  10899. i, platform;
  10900. navigator = navigator || window.navigator;
  10901. for (i = 0; i < ln; i++) {
  10902. platform = platforms[i];
  10903. this[platform.identity] = platform.regex.test(navigator[platform.property]);
  10904. }
  10905. /**
  10906. * @property Desktop True if the browser is running on a desktop machine
  10907. * @type {Boolean}
  10908. */
  10909. this.Desktop = this.Mac || this.Windows || (this.Linux && !this.Android);
  10910. /**
  10911. * @property Tablet True if the browser is running on a tablet (iPad)
  10912. */
  10913. this.Tablet = this.iPad;
  10914. /**
  10915. * @property Phone True if the browser is running on a phone.
  10916. * @type {Boolean}
  10917. */
  10918. this.Phone = !this.Desktop && !this.Tablet;
  10919. /**
  10920. * @property iOS True if the browser is running on iOS
  10921. * @type {Boolean}
  10922. */
  10923. this.iOS = this.iPhone || this.iPad || this.iPod;
  10924. /**
  10925. * @property Standalone Detects when application has been saved to homescreen.
  10926. * @type {Boolean}
  10927. */
  10928. this.Standalone = !!window.navigator.standalone;
  10929. },
  10930. /**
  10931. * @property iPhone True when the browser is running on a iPhone
  10932. * @type {Boolean}
  10933. */
  10934. platforms: [{
  10935. property: 'platform',
  10936. regex: /iPhone/i,
  10937. identity: 'iPhone'
  10938. },
  10939. /**
  10940. * @property iPod True when the browser is running on a iPod
  10941. * @type {Boolean}
  10942. */
  10943. {
  10944. property: 'platform',
  10945. regex: /iPod/i,
  10946. identity: 'iPod'
  10947. },
  10948. /**
  10949. * @property iPad True when the browser is running on a iPad
  10950. * @type {Boolean}
  10951. */
  10952. {
  10953. property: 'userAgent',
  10954. regex: /iPad/i,
  10955. identity: 'iPad'
  10956. },
  10957. /**
  10958. * @property Blackberry True when the browser is running on a Blackberry
  10959. * @type {Boolean}
  10960. */
  10961. {
  10962. property: 'userAgent',
  10963. regex: /Blackberry/i,
  10964. identity: 'Blackberry'
  10965. },
  10966. /**
  10967. * @property Android True when the browser is running on an Android device
  10968. * @type {Boolean}
  10969. */
  10970. {
  10971. property: 'userAgent',
  10972. regex: /Android/i,
  10973. identity: 'Android'
  10974. },
  10975. /**
  10976. * @property Mac True when the browser is running on a Mac
  10977. * @type {Boolean}
  10978. */
  10979. {
  10980. property: 'platform',
  10981. regex: /Mac/i,
  10982. identity: 'Mac'
  10983. },
  10984. /**
  10985. * @property Windows True when the browser is running on Windows
  10986. * @type {Boolean}
  10987. */
  10988. {
  10989. property: 'platform',
  10990. regex: /Win/i,
  10991. identity: 'Windows'
  10992. },
  10993. /**
  10994. * @property Linux True when the browser is running on Linux
  10995. * @type {Boolean}
  10996. */
  10997. {
  10998. property: 'platform',
  10999. regex: /Linux/i,
  11000. identity: 'Linux'
  11001. }]
  11002. };
  11003. Ext.is.init();
  11004. /**
  11005. * @class Ext.supports
  11006. *
  11007. * Determines information about features are supported in the current environment
  11008. *
  11009. * @singleton
  11010. */
  11011. Ext.supports = {
  11012. /**
  11013. * Runs feature detection routines and sets the various flags. This is called when
  11014. * the scripts loads (very early) and again at {@link Ext#onReady}. Some detections
  11015. * are flagged as `early` and run immediately. Others that require the document body
  11016. * will not run until ready.
  11017. *
  11018. * Each test is run only once, so calling this method from an onReady function is safe
  11019. * and ensures that all flags have been set.
  11020. * @markdown
  11021. * @private
  11022. */
  11023. init : function() {
  11024. var me = this,
  11025. doc = document,
  11026. tests = me.tests,
  11027. n = tests.length,
  11028. div = n && Ext.isReady && doc.createElement('div'),
  11029. test, notRun = [];
  11030. if (div) {
  11031. div.innerHTML = [
  11032. '<div style="height:30px;width:50px;">',
  11033. '<div style="height:20px;width:20px;"></div>',
  11034. '</div>',
  11035. '<div style="width: 200px; height: 200px; position: relative; padding: 5px;">',
  11036. '<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></div>',
  11037. '</div>',
  11038. '<div style="position: absolute; left: 10%; top: 10%;"></div>',
  11039. '<div style="float:left; background-color:transparent;"></div>'
  11040. ].join('');
  11041. doc.body.appendChild(div);
  11042. }
  11043. while (n--) {
  11044. test = tests[n];
  11045. if (div || test.early) {
  11046. me[test.identity] = test.fn.call(me, doc, div);
  11047. } else {
  11048. notRun.push(test);
  11049. }
  11050. }
  11051. if (div) {
  11052. doc.body.removeChild(div);
  11053. }
  11054. me.tests = notRun;
  11055. },
  11056. /**
  11057. * @property PointerEvents True if document environment supports the CSS3 pointer-events style.
  11058. * @type {Boolean}
  11059. */
  11060. PointerEvents: 'pointerEvents' in document.documentElement.style,
  11061. /**
  11062. * @property CSS3BoxShadow True if document environment supports the CSS3 box-shadow style.
  11063. * @type {Boolean}
  11064. */
  11065. CSS3BoxShadow: 'boxShadow' in document.documentElement.style,
  11066. /**
  11067. * @property ClassList True if document environment supports the HTML5 classList API.
  11068. * @type {Boolean}
  11069. */
  11070. ClassList: !!document.documentElement.classList,
  11071. /**
  11072. * @property OrientationChange True if the device supports orientation change
  11073. * @type {Boolean}
  11074. */
  11075. OrientationChange: ((typeof window.orientation != 'undefined') && ('onorientationchange' in window)),
  11076. /**
  11077. * @property DeviceMotion True if the device supports device motion (acceleration and rotation rate)
  11078. * @type {Boolean}
  11079. */
  11080. DeviceMotion: ('ondevicemotion' in window),
  11081. /**
  11082. * @property Touch True if the device supports touch
  11083. * @type {Boolean}
  11084. */
  11085. // is.Desktop is needed due to the bug in Chrome 5.0.375, Safari 3.1.2
  11086. // and Safari 4.0 (they all have 'ontouchstart' in the window object).
  11087. Touch: ('ontouchstart' in window) && (!Ext.is.Desktop),
  11088. tests: [
  11089. /**
  11090. * @property Transitions True if the device supports CSS3 Transitions
  11091. * @type {Boolean}
  11092. */
  11093. {
  11094. identity: 'Transitions',
  11095. fn: function(doc, div) {
  11096. var prefix = [
  11097. 'webkit',
  11098. 'Moz',
  11099. 'o',
  11100. 'ms',
  11101. 'khtml'
  11102. ],
  11103. TE = 'TransitionEnd',
  11104. transitionEndName = [
  11105. prefix[0] + TE,
  11106. 'transitionend', //Moz bucks the prefixing convention
  11107. prefix[2] + TE,
  11108. prefix[3] + TE,
  11109. prefix[4] + TE
  11110. ],
  11111. ln = prefix.length,
  11112. i = 0,
  11113. out = false;
  11114. div = Ext.get(div);
  11115. for (; i < ln; i++) {
  11116. if (div.getStyle(prefix[i] + "TransitionProperty")) {
  11117. Ext.supports.CSS3Prefix = prefix[i];
  11118. Ext.supports.CSS3TransitionEnd = transitionEndName[i];
  11119. out = true;
  11120. break;
  11121. }
  11122. }
  11123. return out;
  11124. }
  11125. },
  11126. /**
  11127. * @property RightMargin True if the device supports right margin.
  11128. * See https://bugs.webkit.org/show_bug.cgi?id=13343 for why this is needed.
  11129. * @type {Boolean}
  11130. */
  11131. {
  11132. identity: 'RightMargin',
  11133. fn: function(doc, div) {
  11134. var view = doc.defaultView;
  11135. return !(view && view.getComputedStyle(div.firstChild.firstChild, null).marginRight != '0px');
  11136. }
  11137. },
  11138. /**
  11139. * @property DisplayChangeInputSelectionBug True if INPUT elements lose their
  11140. * selection when their display style is changed. Essentially, if a text input
  11141. * has focus and its display style is changed, the I-beam disappears.
  11142. *
  11143. * This bug is encountered due to the work around in place for the {@link #RightMargin}
  11144. * bug. This has been observed in Safari 4.0.4 and older, and appears to be fixed
  11145. * in Safari 5. It's not clear if Safari 4.1 has the bug, but it has the same WebKit
  11146. * version number as Safari 5 (according to http://unixpapa.com/js/gecko.html).
  11147. */
  11148. {
  11149. identity: 'DisplayChangeInputSelectionBug',
  11150. early: true,
  11151. fn: function() {
  11152. var webKitVersion = Ext.webKitVersion;
  11153. // WebKit but older than Safari 5 or Chrome 6:
  11154. return 0 < webKitVersion && webKitVersion < 533;
  11155. }
  11156. },
  11157. /**
  11158. * @property DisplayChangeTextAreaSelectionBug True if TEXTAREA elements lose their
  11159. * selection when their display style is changed. Essentially, if a text area has
  11160. * focus and its display style is changed, the I-beam disappears.
  11161. *
  11162. * This bug is encountered due to the work around in place for the {@link #RightMargin}
  11163. * bug. This has been observed in Chrome 10 and Safari 5 and older, and appears to
  11164. * be fixed in Chrome 11.
  11165. */
  11166. {
  11167. identity: 'DisplayChangeTextAreaSelectionBug',
  11168. early: true,
  11169. fn: function() {
  11170. var webKitVersion = Ext.webKitVersion;
  11171. /*
  11172. Has bug w/textarea:
  11173. (Chrome) Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-US)
  11174. AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.127
  11175. Safari/534.16
  11176. (Safari) Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-us)
  11177. AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5
  11178. Safari/533.21.1
  11179. No bug:
  11180. (Chrome) Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_7)
  11181. AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.57
  11182. Safari/534.24
  11183. */
  11184. return 0 < webKitVersion && webKitVersion < 534.24;
  11185. }
  11186. },
  11187. /**
  11188. * @property TransparentColor True if the device supports transparent color
  11189. * @type {Boolean}
  11190. */
  11191. {
  11192. identity: 'TransparentColor',
  11193. fn: function(doc, div, view) {
  11194. view = doc.defaultView;
  11195. return !(view && view.getComputedStyle(div.lastChild, null).backgroundColor != 'transparent');
  11196. }
  11197. },
  11198. /**
  11199. * @property ComputedStyle True if the browser supports document.defaultView.getComputedStyle()
  11200. * @type {Boolean}
  11201. */
  11202. {
  11203. identity: 'ComputedStyle',
  11204. fn: function(doc, div, view) {
  11205. view = doc.defaultView;
  11206. return view && view.getComputedStyle;
  11207. }
  11208. },
  11209. /**
  11210. * @property SVG True if the device supports SVG
  11211. * @type {Boolean}
  11212. */
  11213. {
  11214. identity: 'Svg',
  11215. fn: function(doc) {
  11216. return !!doc.createElementNS && !!doc.createElementNS( "http:/" + "/www.w3.org/2000/svg", "svg").createSVGRect;
  11217. }
  11218. },
  11219. /**
  11220. * @property Canvas True if the device supports Canvas
  11221. * @type {Boolean}
  11222. */
  11223. {
  11224. identity: 'Canvas',
  11225. fn: function(doc) {
  11226. return !!doc.createElement('canvas').getContext;
  11227. }
  11228. },
  11229. /**
  11230. * @property VML True if the device supports VML
  11231. * @type {Boolean}
  11232. */
  11233. {
  11234. identity: 'Vml',
  11235. fn: function(doc) {
  11236. var d = doc.createElement("div");
  11237. d.innerHTML = "<!--[if vml]><br><br><![endif]-->";
  11238. return (d.childNodes.length == 2);
  11239. }
  11240. },
  11241. /**
  11242. * @property Float True if the device supports CSS float
  11243. * @type {Boolean}
  11244. */
  11245. {
  11246. identity: 'Float',
  11247. fn: function(doc, div) {
  11248. return !!div.lastChild.style.cssFloat;
  11249. }
  11250. },
  11251. /**
  11252. * @property AudioTag True if the device supports the HTML5 audio tag
  11253. * @type {Boolean}
  11254. */
  11255. {
  11256. identity: 'AudioTag',
  11257. fn: function(doc) {
  11258. return !!doc.createElement('audio').canPlayType;
  11259. }
  11260. },
  11261. /**
  11262. * @property History True if the device supports HTML5 history
  11263. * @type {Boolean}
  11264. */
  11265. {
  11266. identity: 'History',
  11267. fn: function() {
  11268. var history = window.history;
  11269. return !!(history && history.pushState);
  11270. }
  11271. },
  11272. /**
  11273. * @property CSS3DTransform True if the device supports CSS3DTransform
  11274. * @type {Boolean}
  11275. */
  11276. {
  11277. identity: 'CSS3DTransform',
  11278. fn: function() {
  11279. return (typeof WebKitCSSMatrix != 'undefined' && new WebKitCSSMatrix().hasOwnProperty('m41'));
  11280. }
  11281. },
  11282. /**
  11283. * @property CSS3LinearGradient True if the device supports CSS3 linear gradients
  11284. * @type {Boolean}
  11285. */
  11286. {
  11287. identity: 'CSS3LinearGradient',
  11288. fn: function(doc, div) {
  11289. var property = 'background-image:',
  11290. webkit = '-webkit-gradient(linear, left top, right bottom, from(black), to(white))',
  11291. w3c = 'linear-gradient(left top, black, white)',
  11292. moz = '-moz-' + w3c,
  11293. opera = '-o-' + w3c,
  11294. options = [property + webkit, property + w3c, property + moz, property + opera];
  11295. div.style.cssText = options.join(';');
  11296. return ("" + div.style.backgroundImage).indexOf('gradient') !== -1;
  11297. }
  11298. },
  11299. /**
  11300. * @property CSS3BorderRadius True if the device supports CSS3 border radius
  11301. * @type {Boolean}
  11302. */
  11303. {
  11304. identity: 'CSS3BorderRadius',
  11305. fn: function(doc, div) {
  11306. var domPrefixes = ['borderRadius', 'BorderRadius', 'MozBorderRadius', 'WebkitBorderRadius', 'OBorderRadius', 'KhtmlBorderRadius'],
  11307. pass = false,
  11308. i;
  11309. for (i = 0; i < domPrefixes.length; i++) {
  11310. if (document.body.style[domPrefixes[i]] !== undefined) {
  11311. return true;
  11312. }
  11313. }
  11314. return pass;
  11315. }
  11316. },
  11317. /**
  11318. * @property GeoLocation True if the device supports GeoLocation
  11319. * @type {Boolean}
  11320. */
  11321. {
  11322. identity: 'GeoLocation',
  11323. fn: function() {
  11324. return (typeof navigator != 'undefined' && typeof navigator.geolocation != 'undefined') || (typeof google != 'undefined' && typeof google.gears != 'undefined');
  11325. }
  11326. },
  11327. /**
  11328. * @property MouseEnterLeave True if the browser supports mouseenter and mouseleave events
  11329. * @type {Boolean}
  11330. */
  11331. {
  11332. identity: 'MouseEnterLeave',
  11333. fn: function(doc, div){
  11334. return ('onmouseenter' in div && 'onmouseleave' in div);
  11335. }
  11336. },
  11337. /**
  11338. * @property MouseWheel True if the browser supports the mousewheel event
  11339. * @type {Boolean}
  11340. */
  11341. {
  11342. identity: 'MouseWheel',
  11343. fn: function(doc, div) {
  11344. return ('onmousewheel' in div);
  11345. }
  11346. },
  11347. /**
  11348. * @property Opacity True if the browser supports normal css opacity
  11349. * @type {Boolean}
  11350. */
  11351. {
  11352. identity: 'Opacity',
  11353. fn: function(doc, div){
  11354. // Not a strict equal comparison in case opacity can be converted to a number.
  11355. if (Ext.isIE6 || Ext.isIE7 || Ext.isIE8) {
  11356. return false;
  11357. }
  11358. div.firstChild.style.cssText = 'opacity:0.73';
  11359. return div.firstChild.style.opacity == '0.73';
  11360. }
  11361. },
  11362. /**
  11363. * @property Placeholder True if the browser supports the HTML5 placeholder attribute on inputs
  11364. * @type {Boolean}
  11365. */
  11366. {
  11367. identity: 'Placeholder',
  11368. fn: function(doc) {
  11369. return 'placeholder' in doc.createElement('input');
  11370. }
  11371. },
  11372. /**
  11373. * @property Direct2DBug True if when asking for an element's dimension via offsetWidth or offsetHeight,
  11374. * getBoundingClientRect, etc. the browser returns the subpixel width rounded to the nearest pixel.
  11375. * @type {Boolean}
  11376. */
  11377. {
  11378. identity: 'Direct2DBug',
  11379. fn: function() {
  11380. return Ext.isString(document.body.style.msTransformOrigin);
  11381. }
  11382. },
  11383. /**
  11384. * @property BoundingClientRect True if the browser supports the getBoundingClientRect method on elements
  11385. * @type {Boolean}
  11386. */
  11387. {
  11388. identity: 'BoundingClientRect',
  11389. fn: function(doc, div) {
  11390. return Ext.isFunction(div.getBoundingClientRect);
  11391. }
  11392. },
  11393. {
  11394. identity: 'IncludePaddingInWidthCalculation',
  11395. fn: function(doc, div){
  11396. var el = Ext.get(div.childNodes[1].firstChild);
  11397. return el.getWidth() == 210;
  11398. }
  11399. },
  11400. {
  11401. identity: 'IncludePaddingInHeightCalculation',
  11402. fn: function(doc, div){
  11403. var el = Ext.get(div.childNodes[1].firstChild);
  11404. return el.getHeight() == 210;
  11405. }
  11406. },
  11407. /**
  11408. * @property ArraySort True if the Array sort native method isn't bugged.
  11409. * @type {Boolean}
  11410. */
  11411. {
  11412. identity: 'ArraySort',
  11413. fn: function() {
  11414. var a = [1,2,3,4,5].sort(function(){ return 0; });
  11415. return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5;
  11416. }
  11417. },
  11418. /**
  11419. * @property Range True if browser support document.createRange native method.
  11420. * @type {Boolean}
  11421. */
  11422. {
  11423. identity: 'Range',
  11424. fn: function() {
  11425. return !!document.createRange;
  11426. }
  11427. },
  11428. /**
  11429. * @property CreateContextualFragment True if browser support CreateContextualFragment range native methods.
  11430. * @type {Boolean}
  11431. */
  11432. {
  11433. identity: 'CreateContextualFragment',
  11434. fn: function() {
  11435. var range = Ext.supports.Range ? document.createRange() : false;
  11436. return range && !!range.createContextualFragment;
  11437. }
  11438. },
  11439. /**
  11440. * @property WindowOnError True if browser supports window.onerror.
  11441. * @type {Boolean}
  11442. */
  11443. {
  11444. identity: 'WindowOnError',
  11445. fn: function () {
  11446. // sadly, we cannot feature detect this...
  11447. return Ext.isIE || Ext.isGecko || Ext.webKitVersion >= 534.16; // Chrome 10+
  11448. }
  11449. },
  11450. /**
  11451. * @property TextAreaMaxLength True if the browser supports maxlength on textareas.
  11452. * @type {Boolean}
  11453. */
  11454. {
  11455. identity: 'TextAreaMaxLength',
  11456. fn: function(){
  11457. var el = document.createElement('textarea');
  11458. return ('maxlength' in el);
  11459. }
  11460. },
  11461. /**
  11462. * @property GetPositionPercentage True if the browser will return the left/top/right/bottom
  11463. * position as a percentage when explicitly set as a percentage value.
  11464. * @type {Boolean}
  11465. */
  11466. // Related bug: https://bugzilla.mozilla.org/show_bug.cgi?id=707691#c7
  11467. {
  11468. identity: 'GetPositionPercentage',
  11469. fn: function(doc, div){
  11470. return Ext.get(div.childNodes[2]).getStyle('left') == '10%';
  11471. }
  11472. }
  11473. ]
  11474. };
  11475. Ext.supports.init(); // run the "early" detections now
  11476. /**
  11477. * @class Ext.util.DelayedTask
  11478. *
  11479. * The DelayedTask class provides a convenient way to "buffer" the execution of a method,
  11480. * performing setTimeout where a new timeout cancels the old timeout. When called, the
  11481. * task will wait the specified time period before executing. If durng that time period,
  11482. * the task is called again, the original call will be cancelled. This continues so that
  11483. * the function is only called a single time for each iteration.
  11484. *
  11485. * This method is especially useful for things like detecting whether a user has finished
  11486. * typing in a text field. An example would be performing validation on a keypress. You can
  11487. * use this class to buffer the keypress events for a certain number of milliseconds, and
  11488. * perform only if they stop for that amount of time.
  11489. *
  11490. * ## Usage
  11491. *
  11492. * var task = new Ext.util.DelayedTask(function(){
  11493. * alert(Ext.getDom('myInputField').value.length);
  11494. * });
  11495. *
  11496. * // Wait 500ms before calling our function. If the user presses another key
  11497. * // during that 500ms, it will be cancelled and we'll wait another 500ms.
  11498. * Ext.get('myInputField').on('keypress', function(){
  11499. * task.{@link #delay}(500);
  11500. * });
  11501. *
  11502. * Note that we are using a DelayedTask here to illustrate a point. The configuration
  11503. * option `buffer` for {@link Ext.util.Observable#addListener addListener/on} will
  11504. * also setup a delayed task for you to buffer events.
  11505. *
  11506. * @constructor The parameters to this constructor serve as defaults and are not required.
  11507. * @param {Function} fn (optional) The default function to call. If not specified here, it must be specified during the {@link #delay} call.
  11508. * @param {Object} scope (optional) The default scope (The <code><b>this</b></code> reference) in which the
  11509. * function is called. If not specified, <code>this</code> will refer to the browser window.
  11510. * @param {Array} args (optional) The default Array of arguments.
  11511. */
  11512. Ext.util.DelayedTask = function(fn, scope, args) {
  11513. var me = this,
  11514. id,
  11515. call = function() {
  11516. clearInterval(id);
  11517. id = null;
  11518. fn.apply(scope, args || []);
  11519. };
  11520. /**
  11521. * Cancels any pending timeout and queues a new one
  11522. * @param {Number} delay The milliseconds to delay
  11523. * @param {Function} newFn (optional) Overrides function passed to constructor
  11524. * @param {Object} newScope (optional) Overrides scope passed to constructor. Remember that if no scope
  11525. * is specified, <code>this</code> will refer to the browser window.
  11526. * @param {Array} newArgs (optional) Overrides args passed to constructor
  11527. */
  11528. this.delay = function(delay, newFn, newScope, newArgs) {
  11529. me.cancel();
  11530. fn = newFn || fn;
  11531. scope = newScope || scope;
  11532. args = newArgs || args;
  11533. id = setInterval(call, delay);
  11534. };
  11535. /**
  11536. * Cancel the last queued timeout
  11537. */
  11538. this.cancel = function(){
  11539. if (id) {
  11540. clearInterval(id);
  11541. id = null;
  11542. }
  11543. };
  11544. };
  11545. Ext.require('Ext.util.DelayedTask', function() {
  11546. /**
  11547. * Represents single event type that an Observable object listens to.
  11548. * All actual listeners are tracked inside here. When the event fires,
  11549. * it calls all the registered listener functions.
  11550. *
  11551. * @private
  11552. */
  11553. Ext.util.Event = Ext.extend(Object, (function() {
  11554. function createBuffered(handler, listener, o, scope) {
  11555. listener.task = new Ext.util.DelayedTask();
  11556. return function() {
  11557. listener.task.delay(o.buffer, handler, scope, Ext.Array.toArray(arguments));
  11558. };
  11559. }
  11560. function createDelayed(handler, listener, o, scope) {
  11561. return function() {
  11562. var task = new Ext.util.DelayedTask();
  11563. if (!listener.tasks) {
  11564. listener.tasks = [];
  11565. }
  11566. listener.tasks.push(task);
  11567. task.delay(o.delay || 10, handler, scope, Ext.Array.toArray(arguments));
  11568. };
  11569. }
  11570. function createSingle(handler, listener, o, scope) {
  11571. return function() {
  11572. var event = listener.ev;
  11573. if (event.removeListener(listener.fn, scope) && event.observable) {
  11574. // Removing from a regular Observable-owned, named event (not an anonymous
  11575. // event such as Ext's readyEvent): Decrement the listeners count
  11576. event.observable.hasListeners[event.name]--;
  11577. }
  11578. return handler.apply(scope, arguments);
  11579. };
  11580. }
  11581. return {
  11582. /**
  11583. * @property {Boolean} isEvent
  11584. * `true` in this class to identify an objact as an instantiated Event, or subclass thereof.
  11585. */
  11586. isEvent: true,
  11587. constructor: function(observable, name) {
  11588. this.name = name;
  11589. this.observable = observable;
  11590. this.listeners = [];
  11591. },
  11592. addListener: function(fn, scope, options) {
  11593. var me = this,
  11594. listener;
  11595. scope = scope || me.observable;
  11596. if (!me.isListening(fn, scope)) {
  11597. listener = me.createListener(fn, scope, options);
  11598. if (me.firing) {
  11599. // if we are currently firing this event, don't disturb the listener loop
  11600. me.listeners = me.listeners.slice(0);
  11601. }
  11602. me.listeners.push(listener);
  11603. }
  11604. },
  11605. createListener: function(fn, scope, o) {
  11606. o = o || {};
  11607. scope = scope || this.observable;
  11608. var listener = {
  11609. fn: fn,
  11610. scope: scope,
  11611. o: o,
  11612. ev: this
  11613. },
  11614. handler = fn;
  11615. // The order is important. The 'single' wrapper must be wrapped by the 'buffer' and 'delayed' wrapper
  11616. // because the event removal that the single listener does destroys the listener's DelayedTask(s)
  11617. if (o.single) {
  11618. handler = createSingle(handler, listener, o, scope);
  11619. }
  11620. if (o.delay) {
  11621. handler = createDelayed(handler, listener, o, scope);
  11622. }
  11623. if (o.buffer) {
  11624. handler = createBuffered(handler, listener, o, scope);
  11625. }
  11626. listener.fireFn = handler;
  11627. return listener;
  11628. },
  11629. findListener: function(fn, scope) {
  11630. var listeners = this.listeners,
  11631. i = listeners.length,
  11632. listener,
  11633. s;
  11634. while (i--) {
  11635. listener = listeners[i];
  11636. if (listener) {
  11637. s = listener.scope;
  11638. if (listener.fn == fn && (s == scope || s == this.observable)) {
  11639. return i;
  11640. }
  11641. }
  11642. }
  11643. return - 1;
  11644. },
  11645. isListening: function(fn, scope) {
  11646. return this.findListener(fn, scope) !== -1;
  11647. },
  11648. removeListener: function(fn, scope) {
  11649. var me = this,
  11650. index,
  11651. listener,
  11652. k;
  11653. index = me.findListener(fn, scope);
  11654. if (index != -1) {
  11655. listener = me.listeners[index];
  11656. if (me.firing) {
  11657. me.listeners = me.listeners.slice(0);
  11658. }
  11659. // cancel and remove a buffered handler that hasn't fired yet
  11660. if (listener.task) {
  11661. listener.task.cancel();
  11662. delete listener.task;
  11663. }
  11664. // cancel and remove all delayed handlers that haven't fired yet
  11665. k = listener.tasks && listener.tasks.length;
  11666. if (k) {
  11667. while (k--) {
  11668. listener.tasks[k].cancel();
  11669. }
  11670. delete listener.tasks;
  11671. }
  11672. // remove this listener from the listeners array
  11673. Ext.Array.erase(me.listeners, index, 1);
  11674. return true;
  11675. }
  11676. return false;
  11677. },
  11678. // Iterate to stop any buffered/delayed events
  11679. clearListeners: function() {
  11680. var listeners = this.listeners,
  11681. i = listeners.length;
  11682. while (i--) {
  11683. this.removeListener(listeners[i].fn, listeners[i].scope);
  11684. }
  11685. },
  11686. fire: function() {
  11687. var me = this,
  11688. listeners = me.listeners,
  11689. count = listeners.length,
  11690. i,
  11691. args,
  11692. listener;
  11693. if (count > 0) {
  11694. me.firing = true;
  11695. for (i = 0; i < count; i++) {
  11696. listener = listeners[i];
  11697. args = arguments.length ? Array.prototype.slice.call(arguments, 0) : [];
  11698. if (listener.o) {
  11699. args.push(listener.o);
  11700. }
  11701. if (listener && listener.fireFn.apply(listener.scope || me.observable, args) === false) {
  11702. return (me.firing = false);
  11703. }
  11704. }
  11705. }
  11706. me.firing = false;
  11707. return true;
  11708. }
  11709. };
  11710. })());
  11711. });
  11712. /**
  11713. * @class Ext.EventManager
  11714. * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
  11715. * several useful events directly.
  11716. * See {@link Ext.EventObject} for more details on normalized event objects.
  11717. * @singleton
  11718. */
  11719. Ext.EventManager = new function() {
  11720. var EventManager = this,
  11721. doc = document,
  11722. win = window,
  11723. initExtCss = function() {
  11724. // find the body element
  11725. var bd = doc.body || doc.getElementsByTagName('body')[0],
  11726. baseCSSPrefix = Ext.baseCSSPrefix,
  11727. cls = [baseCSSPrefix + 'body'],
  11728. htmlCls = [],
  11729. html;
  11730. if (!bd) {
  11731. return false;
  11732. }
  11733. html = bd.parentNode;
  11734. function add (c) {
  11735. cls.push(baseCSSPrefix + c);
  11736. }
  11737. //Let's keep this human readable!
  11738. if (Ext.isIE) {
  11739. add('ie');
  11740. // very often CSS needs to do checks like "IE7+" or "IE6 or 7". To help
  11741. // reduce the clutter (since CSS/SCSS cannot do these tests), we add some
  11742. // additional classes:
  11743. //
  11744. // x-ie7p : IE7+ : 7 <= ieVer
  11745. // x-ie7m : IE7- : ieVer <= 7
  11746. // x-ie8p : IE8+ : 8 <= ieVer
  11747. // x-ie8m : IE8- : ieVer <= 8
  11748. // x-ie9p : IE9+ : 9 <= ieVer
  11749. // x-ie78 : IE7 or 8 : 7 <= ieVer <= 8
  11750. //
  11751. if (Ext.isIE6) {
  11752. add('ie6');
  11753. } else { // ignore pre-IE6 :)
  11754. add('ie7p');
  11755. if (Ext.isIE7) {
  11756. add('ie7');
  11757. } else {
  11758. add('ie8p');
  11759. if (Ext.isIE8) {
  11760. add('ie8');
  11761. } else {
  11762. add('ie9p');
  11763. if (Ext.isIE9) {
  11764. add('ie9');
  11765. }
  11766. }
  11767. }
  11768. }
  11769. if (Ext.isIE6 || Ext.isIE7) {
  11770. add('ie7m');
  11771. }
  11772. if (Ext.isIE6 || Ext.isIE7 || Ext.isIE8) {
  11773. add('ie8m');
  11774. }
  11775. if (Ext.isIE7 || Ext.isIE8) {
  11776. add('ie78');
  11777. }
  11778. }
  11779. if (Ext.isGecko) {
  11780. add('gecko');
  11781. if (Ext.isGecko3) {
  11782. add('gecko3');
  11783. }
  11784. if (Ext.isGecko4) {
  11785. add('gecko4');
  11786. }
  11787. if (Ext.isGecko5) {
  11788. add('gecko5');
  11789. }
  11790. }
  11791. if (Ext.isOpera) {
  11792. add('opera');
  11793. }
  11794. if (Ext.isWebKit) {
  11795. add('webkit');
  11796. }
  11797. if (Ext.isSafari) {
  11798. add('safari');
  11799. if (Ext.isSafari2) {
  11800. add('safari2');
  11801. }
  11802. if (Ext.isSafari3) {
  11803. add('safari3');
  11804. }
  11805. if (Ext.isSafari4) {
  11806. add('safari4');
  11807. }
  11808. if (Ext.isSafari5) {
  11809. add('safari5');
  11810. }
  11811. }
  11812. if (Ext.isChrome) {
  11813. add('chrome');
  11814. }
  11815. if (Ext.isMac) {
  11816. add('mac');
  11817. }
  11818. if (Ext.isLinux) {
  11819. add('linux');
  11820. }
  11821. if (!Ext.supports.CSS3BorderRadius) {
  11822. add('nbr');
  11823. }
  11824. if (!Ext.supports.CSS3LinearGradient) {
  11825. add('nlg');
  11826. }
  11827. if (!Ext.scopeResetCSS) {
  11828. add('reset');
  11829. }
  11830. // add to the parent to allow for selectors x-strict x-border-box, also set the isBorderBox property correctly
  11831. if (html) {
  11832. if (Ext.isStrict && (Ext.isIE6 || Ext.isIE7)) {
  11833. Ext.isBorderBox = false;
  11834. }
  11835. else {
  11836. Ext.isBorderBox = true;
  11837. }
  11838. if(Ext.isBorderBox) {
  11839. htmlCls.push(baseCSSPrefix + 'border-box');
  11840. }
  11841. if (Ext.isStrict) {
  11842. htmlCls.push(baseCSSPrefix + 'strict');
  11843. } else {
  11844. htmlCls.push(baseCSSPrefix + 'quirks');
  11845. }
  11846. Ext.fly(html, '_internal').addCls(htmlCls);
  11847. }
  11848. Ext.fly(bd, '_internal').addCls(cls);
  11849. return true;
  11850. };
  11851. Ext.apply(EventManager, {
  11852. /**
  11853. * Check if we have bound our global onReady listener
  11854. * @private
  11855. */
  11856. hasBoundOnReady: false,
  11857. /**
  11858. * Check if fireDocReady has been called
  11859. * @private
  11860. */
  11861. hasFiredReady: false,
  11862. /**
  11863. * Additionally, allow the 'DOM' listener thread to complete (usually desirable with mobWebkit, Gecko)
  11864. * before firing the entire onReady chain (high stack load on Loader) by specifying a delay value
  11865. * @default 1ms
  11866. * @private
  11867. */
  11868. deferReadyEvent : 1,
  11869. /*
  11870. * diags: a list of event names passed to onReadyEvent (in chron order)
  11871. * @private
  11872. */
  11873. onReadyChain : [],
  11874. /**
  11875. * Holds references to any onReady functions
  11876. * @private
  11877. */
  11878. readyEvent:
  11879. (function () {
  11880. var event = new Ext.util.Event();
  11881. event.fire = function () {
  11882. if (!/[?&]ext-pauseReadyFire\b/i.test(location.search) || Ext._continueFireReady) {
  11883. Ext._beforeReadyTime = new Date().getTime();
  11884. event.self.prototype.fire.apply(event, arguments);
  11885. Ext._afterReadytime = new Date().getTime();
  11886. }
  11887. }
  11888. return event;
  11889. })(),
  11890. /**
  11891. * Fires when a DOM event handler finishes its run, just before returning to browser control.
  11892. * This can be useful for performing cleanup, or upfdate tasks which need to happen only
  11893. * after all code in an event handler has been run, but which should not be executed in a timer
  11894. * due to the intervening browser reflow/repaint which would take place.
  11895. *
  11896. */
  11897. idleEvent: new Ext.util.Event(),
  11898. /**
  11899. * Binds the appropriate browser event for checking if the DOM has loaded.
  11900. * @private
  11901. */
  11902. bindReadyEvent: function() {
  11903. if (EventManager.hasBoundOnReady) {
  11904. return;
  11905. }
  11906. // Test scenario where Core is dynamically loaded AFTER window.load
  11907. if ( doc.readyState == 'complete' ) { // Firefox4+ got support for this state, others already do.
  11908. EventManager.onReadyEvent({
  11909. type: doc.readyState || 'body'
  11910. });
  11911. } else {
  11912. document.addEventListener('DOMContentLoaded', EventManager.onReadyEvent, false);
  11913. window.addEventListener('load', EventManager.onReadyEvent, false);
  11914. EventManager.hasBoundOnReady = true;
  11915. }
  11916. },
  11917. onReadyEvent : function(e) {
  11918. if (e && e.type) {
  11919. EventManager.onReadyChain.push(e.type);
  11920. }
  11921. if (EventManager.hasBoundOnReady) {
  11922. document.removeEventListener('DOMContentLoaded', EventManager.onReadyEvent, false);
  11923. window.removeEventListener('load', EventManager.onReadyEvent, false);
  11924. }
  11925. if (!Ext.isReady) {
  11926. EventManager.fireDocReady();
  11927. }
  11928. },
  11929. /**
  11930. * We know the document is loaded, so trigger any onReady events.
  11931. * @private
  11932. */
  11933. fireDocReady: function() {
  11934. if (!Ext.isReady) {
  11935. Ext._readyTime = new Date().getTime();
  11936. Ext.isReady = true;
  11937. Ext.supports.init();
  11938. EventManager.onWindowUnload();
  11939. EventManager.readyEvent.onReadyChain = EventManager.onReadyChain; //diags report
  11940. if (Ext.isNumber(EventManager.deferReadyEvent)) {
  11941. Ext.Function.defer(EventManager.readyEvent.fire, EventManager.deferReadyEvent, EventManager.readyEvent);
  11942. } else {
  11943. EventManager.readyEvent.fire();
  11944. }
  11945. EventManager.hasFiredReady = true;
  11946. }
  11947. },
  11948. /**
  11949. * Adds a listener to be notified when the document is ready (before onload and before images are loaded). Can be
  11950. * accessed shorthanded as Ext.onReady().
  11951. * @param {Function} fn The method the event invokes.
  11952. * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
  11953. * @param {Boolean} options (optional) Options object as passed to {@link Ext.Element#addListener}.
  11954. */
  11955. onDocumentReady: function(fn, scope, options) {
  11956. options = options || {};
  11957. var readyEvent = EventManager.readyEvent;
  11958. // force single to be true so our event is only ever fired once.
  11959. options.single = true;
  11960. readyEvent.addListener(fn, scope, options);
  11961. // Document already loaded, let's just fire it
  11962. if (Ext.isReady) {
  11963. readyEvent.fire();
  11964. } else {
  11965. EventManager.bindReadyEvent();
  11966. }
  11967. },
  11968. // --------------------- event binding ---------------------
  11969. /**
  11970. * Contains a list of all document mouse downs, so we can ensure they fire even when stopEvent is called.
  11971. * @private
  11972. */
  11973. stoppedMouseDownEvent: new Ext.util.Event(),
  11974. /**
  11975. * Options to parse for the 4th argument to addListener.
  11976. * @private
  11977. */
  11978. propRe: /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate|freezeEvent)$/,
  11979. /**
  11980. * Get the id of the element. If one has not been assigned, automatically assign it.
  11981. * @param {HTMLElement/Ext.Element} element The element to get the id for.
  11982. * @return {String} id
  11983. */
  11984. getId : function(element) {
  11985. var skipGarbageCollection = false,
  11986. id;
  11987. element = Ext.getDom(element);
  11988. if (element === doc || element === win) {
  11989. id = element === doc ? Ext.documentId : Ext.windowId;
  11990. }
  11991. else {
  11992. id = Ext.id(element);
  11993. }
  11994. // skip garbage collection for special elements (window, document, iframes)
  11995. if (element && (element.getElementById || element.navigator)) {
  11996. skipGarbageCollection = true;
  11997. }
  11998. if (!Ext.cache[id]) {
  11999. Ext.Element.addToCache(new Ext.Element(element), id);
  12000. if (skipGarbageCollection) {
  12001. Ext.cache[id].skipGarbageCollection = true;
  12002. }
  12003. }
  12004. return id;
  12005. },
  12006. /**
  12007. * Convert a "config style" listener into a set of flat arguments so they can be passed to addListener
  12008. * @private
  12009. * @param {Object} element The element the event is for
  12010. * @param {Object} event The event configuration
  12011. * @param {Object} isRemove True if a removal should be performed, otherwise an add will be done.
  12012. */
  12013. prepareListenerConfig: function(element, config, isRemove) {
  12014. var propRe = EventManager.propRe,
  12015. key, value, args;
  12016. // loop over all the keys in the object
  12017. for (key in config) {
  12018. if (config.hasOwnProperty(key)) {
  12019. // if the key is something else then an event option
  12020. if (!propRe.test(key)) {
  12021. value = config[key];
  12022. // if the value is a function it must be something like click: function() {}, scope: this
  12023. // which means that there might be multiple event listeners with shared options
  12024. if (typeof value == 'function') {
  12025. // shared options
  12026. args = [element, key, value, config.scope, config];
  12027. } else {
  12028. // if its not a function, it must be an object like click: {fn: function() {}, scope: this}
  12029. args = [element, key, value.fn, value.scope, value];
  12030. }
  12031. if (isRemove) {
  12032. EventManager.removeListener.apply(EventManager, args);
  12033. } else {
  12034. EventManager.addListener.apply(EventManager, args);
  12035. }
  12036. }
  12037. }
  12038. }
  12039. },
  12040. mouseEnterLeaveRe: /mouseenter|mouseleave/,
  12041. /**
  12042. * Normalize cross browser event differences
  12043. * @private
  12044. * @param {Object} eventName The event name
  12045. * @param {Object} fn The function to execute
  12046. * @return {Object} The new event name/function
  12047. */
  12048. normalizeEvent: function(eventName, fn) {
  12049. if (EventManager.mouseEnterLeaveRe.test(eventName) && !Ext.supports.MouseEnterLeave) {
  12050. if (fn) {
  12051. fn = Ext.Function.createInterceptor(fn, EventManager.contains);
  12052. }
  12053. eventName = eventName == 'mouseenter' ? 'mouseover' : 'mouseout';
  12054. } else if (eventName == 'mousewheel' && !Ext.supports.MouseWheel && !Ext.isOpera) {
  12055. eventName = 'DOMMouseScroll';
  12056. }
  12057. return {
  12058. eventName: eventName,
  12059. fn: fn
  12060. };
  12061. },
  12062. /**
  12063. * Checks whether the event's relatedTarget is contained inside (or <b>is</b>) the element.
  12064. * @private
  12065. * @param {Object} event
  12066. */
  12067. contains: function(event) {
  12068. var parent = event.browserEvent.currentTarget,
  12069. child = EventManager.getRelatedTarget(event);
  12070. if (parent && parent.firstChild) {
  12071. while (child) {
  12072. if (child === parent) {
  12073. return false;
  12074. }
  12075. child = child.parentNode;
  12076. if (child && (child.nodeType != 1)) {
  12077. child = null;
  12078. }
  12079. }
  12080. }
  12081. return true;
  12082. },
  12083. /**
  12084. * Appends an event handler to an element. The shorthand version {@link #on} is equivalent. Typically you will
  12085. * use {@link Ext.Element#addListener} directly on an Element in favor of calling this version.
  12086. * @param {String/HTMLElement} el The html element or id to assign the event handler to.
  12087. * @param {String} eventName The name of the event to listen for.
  12088. * @param {Function} handler The handler function the event invokes. This function is passed
  12089. * the following parameters:<ul>
  12090. * <li>evt : EventObject<div class="sub-desc">The {@link Ext.EventObject EventObject} describing the event.</div></li>
  12091. * <li>t : Element<div class="sub-desc">The {@link Ext.Element Element} which was the target of the event.
  12092. * Note that this may be filtered by using the <tt>delegate</tt> option.</div></li>
  12093. * <li>o : Object<div class="sub-desc">The options object from the addListener call.</div></li>
  12094. * </ul>
  12095. * @param {Object} scope (optional) The scope (<b><code>this</code></b> reference) in which the handler function is executed. <b>Defaults to the Element</b>.
  12096. * @param {Object} options (optional) An object containing handler configuration properties.
  12097. * This may contain any of the following properties:<ul>
  12098. * <li>scope : Object<div class="sub-desc">The scope (<b><code>this</code></b> reference) in which the handler function is executed. <b>Defaults to the Element</b>.</div></li>
  12099. * <li>delegate : String<div class="sub-desc">A simple selector to filter the target or look for a descendant of the target</div></li>
  12100. * <li>stopEvent : Boolean<div class="sub-desc">True to stop the event. That is stop propagation, and prevent the default action.</div></li>
  12101. * <li>preventDefault : Boolean<div class="sub-desc">True to prevent the default action</div></li>
  12102. * <li>stopPropagation : Boolean<div class="sub-desc">True to prevent event propagation</div></li>
  12103. * <li>normalized : Boolean<div class="sub-desc">False to pass a browser event to the handler function instead of an Ext.EventObject</div></li>
  12104. * <li>delay : Number<div class="sub-desc">The number of milliseconds to delay the invocation of the handler after te event fires.</div></li>
  12105. * <li>single : Boolean<div class="sub-desc">True to add a handler to handle just the next firing of the event, and then remove itself.</div></li>
  12106. * <li>buffer : Number<div class="sub-desc">Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed
  12107. * by the specified number of milliseconds. If the event fires again within that time, the original
  12108. * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</div></li>
  12109. * <li>target : Element<div class="sub-desc">Only call the handler if the event was fired on the target Element, <i>not</i> if the event was bubbled up from a child node.</div></li>
  12110. * </ul><br>
  12111. * <p>See {@link Ext.Element#addListener} for examples of how to use these options.</p>
  12112. */
  12113. addListener: function(element, eventName, fn, scope, options) {
  12114. // Check if we've been passed a "config style" event.
  12115. if (typeof eventName !== 'string') {
  12116. EventManager.prepareListenerConfig(element, eventName);
  12117. return;
  12118. }
  12119. var dom = element.dom || Ext.getDom(element),
  12120. bind, wrap;
  12121. // create the wrapper function
  12122. options = options || {};
  12123. bind = EventManager.normalizeEvent(eventName, fn);
  12124. wrap = EventManager.createListenerWrap(dom, eventName, bind.fn, scope, options);
  12125. if (dom.attachEvent) {
  12126. dom.attachEvent('on' + bind.eventName, wrap);
  12127. } else {
  12128. dom.addEventListener(bind.eventName, wrap, options.capture || false);
  12129. }
  12130. if (dom == doc && eventName == 'mousedown') {
  12131. EventManager.stoppedMouseDownEvent.addListener(wrap);
  12132. }
  12133. // add all required data into the event cache
  12134. EventManager.getEventListenerCache(element.dom ? element : dom, eventName).push({
  12135. fn: fn,
  12136. wrap: wrap,
  12137. scope: scope
  12138. });
  12139. },
  12140. /**
  12141. * Removes an event handler from an element. The shorthand version {@link #un} is equivalent. Typically
  12142. * you will use {@link Ext.Element#removeListener} directly on an Element in favor of calling this version.
  12143. * @param {String/HTMLElement} el The id or html element from which to remove the listener.
  12144. * @param {String} eventName The name of the event.
  12145. * @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
  12146. * @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
  12147. * then this must refer to the same object.
  12148. */
  12149. removeListener : function(element, eventName, fn, scope) {
  12150. // handle our listener config object syntax
  12151. if (typeof eventName !== 'string') {
  12152. EventManager.prepareListenerConfig(element, eventName, true);
  12153. return;
  12154. }
  12155. var dom = Ext.getDom(element),
  12156. el = element.dom ? element : Ext.get(dom),
  12157. cache = EventManager.getEventListenerCache(el, eventName),
  12158. bindName = EventManager.normalizeEvent(eventName).eventName,
  12159. i = cache.length, j,
  12160. listener, wrap, tasks;
  12161. while (i--) {
  12162. listener = cache[i];
  12163. if (listener && (!fn || listener.fn == fn) && (!scope || listener.scope === scope)) {
  12164. wrap = listener.wrap;
  12165. // clear buffered calls
  12166. if (wrap.task) {
  12167. clearTimeout(wrap.task);
  12168. delete wrap.task;
  12169. }
  12170. // clear delayed calls
  12171. j = wrap.tasks && wrap.tasks.length;
  12172. if (j) {
  12173. while (j--) {
  12174. clearTimeout(wrap.tasks[j]);
  12175. }
  12176. delete wrap.tasks;
  12177. }
  12178. if (dom.detachEvent) {
  12179. dom.detachEvent('on' + bindName, wrap);
  12180. } else {
  12181. dom.removeEventListener(bindName, wrap, false);
  12182. }
  12183. if (wrap && dom == doc && eventName == 'mousedown') {
  12184. EventManager.stoppedMouseDownEvent.removeListener(wrap);
  12185. }
  12186. // remove listener from cache
  12187. Ext.Array.erase(cache, i, 1);
  12188. }
  12189. }
  12190. },
  12191. /**
  12192. * Removes all event handers from an element. Typically you will use {@link Ext.Element#removeAllListeners}
  12193. * directly on an Element in favor of calling this version.
  12194. * @param {String/HTMLElement} el The id or html element from which to remove all event handlers.
  12195. */
  12196. removeAll : function(element) {
  12197. var el = element.dom ? element : Ext.get(element),
  12198. cache, events, eventName;
  12199. if (!el) {
  12200. return;
  12201. }
  12202. cache = (el.$cache || el.getCache());
  12203. events = cache.events;
  12204. for (eventName in events) {
  12205. if (events.hasOwnProperty(eventName)) {
  12206. EventManager.removeListener(el, eventName);
  12207. }
  12208. }
  12209. cache.events = {};
  12210. },
  12211. /**
  12212. * Recursively removes all previous added listeners from an element and its children. Typically you will use {@link Ext.Element#purgeAllListeners}
  12213. * directly on an Element in favor of calling this version.
  12214. * @param {String/HTMLElement} el The id or html element from which to remove all event handlers.
  12215. * @param {String} eventName (optional) The name of the event.
  12216. */
  12217. purgeElement : function(element, eventName) {
  12218. var dom = Ext.getDom(element),
  12219. i = 0, len;
  12220. if (eventName) {
  12221. EventManager.removeListener(element, eventName);
  12222. }
  12223. else {
  12224. EventManager.removeAll(element);
  12225. }
  12226. if (dom && dom.childNodes) {
  12227. for (len = element.childNodes.length; i < len; i++) {
  12228. EventManager.purgeElement(element.childNodes[i], eventName);
  12229. }
  12230. }
  12231. },
  12232. /**
  12233. * Create the wrapper function for the event
  12234. * @private
  12235. * @param {HTMLElement} dom The dom element
  12236. * @param {String} ename The event name
  12237. * @param {Function} fn The function to execute
  12238. * @param {Object} scope The scope to execute callback in
  12239. * @param {Object} options The options
  12240. * @return {Function} the wrapper function
  12241. */
  12242. createListenerWrap : function(dom, ename, fn, scope, options) {
  12243. options = options || {};
  12244. var f, gen, wrap = function(e, args) {
  12245. // Compile the implementation upon first firing
  12246. if (!gen) {
  12247. f = ['if(!' + Ext.name + ') {return;}'];
  12248. if(options.buffer || options.delay || options.freezeEvent) {
  12249. f.push('e = new X.EventObjectImpl(e, ' + (options.freezeEvent ? 'true' : 'false' ) + ');');
  12250. } else {
  12251. f.push('e = X.EventObject.setEvent(e);');
  12252. }
  12253. if (options.delegate) {
  12254. f.push('var t = e.getTarget("' + options.delegate + '", this);');
  12255. f.push('if(!t) {return;}');
  12256. } else {
  12257. f.push('var t = e.target;');
  12258. }
  12259. if (options.target) {
  12260. f.push('if(e.target !== options.target) {return;}');
  12261. }
  12262. if(options.stopEvent) {
  12263. f.push('e.stopEvent();');
  12264. } else {
  12265. if(options.preventDefault) {
  12266. f.push('e.preventDefault();');
  12267. }
  12268. if(options.stopPropagation) {
  12269. f.push('e.stopPropagation();');
  12270. }
  12271. }
  12272. if(options.normalized === false) {
  12273. f.push('e = e.browserEvent;');
  12274. }
  12275. if(options.buffer) {
  12276. f.push('(wrap.task && clearTimeout(wrap.task));');
  12277. f.push('wrap.task = setTimeout(function() {');
  12278. }
  12279. if(options.delay) {
  12280. f.push('wrap.tasks = wrap.tasks || [];');
  12281. f.push('wrap.tasks.push(setTimeout(function() {');
  12282. }
  12283. // finally call the actual handler fn
  12284. f.push('fn.call(scope || dom, e, t, options);');
  12285. if(options.single) {
  12286. f.push('evtMgr.removeListener(dom, ename, fn, scope);');
  12287. }
  12288. // Fire the global idle event for all events except mousemove which is too common, and
  12289. // fires too frequently and fast to be use in tiggering onIdle processing.
  12290. if (ename !== 'mousemove') {
  12291. f.push('if (evtMgr.idleEvent.listeners.length) {');
  12292. f.push('evtMgr.idleEvent.fire();');
  12293. f.push('}');
  12294. }
  12295. if(options.delay) {
  12296. f.push('}, ' + options.delay + '));');
  12297. }
  12298. if(options.buffer) {
  12299. f.push('}, ' + options.buffer + ');');
  12300. }
  12301. gen = Ext.cacheableFunctionFactory('e', 'options', 'fn', 'scope', 'ename', 'dom', 'wrap', 'args', 'X', 'evtMgr', f.join('\n'));
  12302. }
  12303. gen.call(dom, e, options, fn, scope, ename, dom, wrap, args, Ext, EventManager);
  12304. };
  12305. return wrap;
  12306. },
  12307. /**
  12308. * Get the event cache for a particular element for a particular event
  12309. * @private
  12310. * @param {HTMLElement} element The element
  12311. * @param {Object} eventName The event name
  12312. * @return {Array} The events for the element
  12313. */
  12314. getEventListenerCache : function(element, eventName) {
  12315. var elementCache, eventCache, id;
  12316. if (!element) {
  12317. return [];
  12318. }
  12319. if (element.$cache) {
  12320. elementCache = element.$cache;
  12321. } else {
  12322. elementCache = Ext.cache[id = EventManager.getId(element)] || (Ext.cache[id] = {});
  12323. }
  12324. eventCache = elementCache.events || (elementCache.events = {});
  12325. return eventCache[eventName] || (eventCache[eventName] = []);
  12326. },
  12327. // --------------------- utility methods ---------------------
  12328. mouseLeaveRe: /(mouseout|mouseleave)/,
  12329. mouseEnterRe: /(mouseover|mouseenter)/,
  12330. /**
  12331. * Stop the event (preventDefault and stopPropagation)
  12332. * @param {Event} The event to stop
  12333. */
  12334. stopEvent: function(event) {
  12335. EventManager.stopPropagation(event);
  12336. EventManager.preventDefault(event);
  12337. },
  12338. /**
  12339. * Cancels bubbling of the event.
  12340. * @param {Event} The event to stop bubbling.
  12341. */
  12342. stopPropagation: function(event) {
  12343. event = event.browserEvent || event;
  12344. if (event.stopPropagation) {
  12345. event.stopPropagation();
  12346. } else {
  12347. event.cancelBubble = true;
  12348. }
  12349. },
  12350. /**
  12351. * Prevents the browsers default handling of the event.
  12352. * @param {Event} The event to prevent the default
  12353. */
  12354. preventDefault: function(event) {
  12355. event = event.browserEvent || event;
  12356. if (event.preventDefault) {
  12357. event.preventDefault();
  12358. } else {
  12359. event.returnValue = false;
  12360. // Some keys events require setting the keyCode to -1 to be prevented
  12361. try {
  12362. // all ctrl + X and F1 -> F12
  12363. if (event.ctrlKey || event.keyCode > 111 && event.keyCode < 124) {
  12364. event.keyCode = -1;
  12365. }
  12366. } catch (e) {
  12367. // see this outdated document http://support.microsoft.com/kb/934364/en-us for more info
  12368. }
  12369. }
  12370. },
  12371. /**
  12372. * Gets the related target from the event.
  12373. * @param {Object} event The event
  12374. * @return {HTMLElement} The related target.
  12375. */
  12376. getRelatedTarget: function(event) {
  12377. event = event.browserEvent || event;
  12378. var target = event.relatedTarget;
  12379. if (!target) {
  12380. if (EventManager.mouseLeaveRe.test(event.type)) {
  12381. target = event.toElement;
  12382. } else if (EventManager.mouseEnterRe.test(event.type)) {
  12383. target = event.fromElement;
  12384. }
  12385. }
  12386. return EventManager.resolveTextNode(target);
  12387. },
  12388. /**
  12389. * Gets the x coordinate from the event
  12390. * @param {Object} event The event
  12391. * @return {Number} The x coordinate
  12392. */
  12393. getPageX: function(event) {
  12394. return EventManager.getPageXY(event)[0];
  12395. },
  12396. /**
  12397. * Gets the y coordinate from the event
  12398. * @param {Object} event The event
  12399. * @return {Number} The y coordinate
  12400. */
  12401. getPageY: function(event) {
  12402. return EventManager.getPageXY(event)[1];
  12403. },
  12404. /**
  12405. * Gets the x & y coordinate from the event
  12406. * @param {Object} event The event
  12407. * @return {Number[]} The x/y coordinate
  12408. */
  12409. getPageXY: function(event) {
  12410. event = event.browserEvent || event;
  12411. var x = event.pageX,
  12412. y = event.pageY,
  12413. docEl = doc.documentElement,
  12414. body = doc.body;
  12415. // pageX/pageY not available (undefined, not null), use clientX/clientY instead
  12416. if (!x && x !== 0) {
  12417. x = event.clientX + (docEl && docEl.scrollLeft || body && body.scrollLeft || 0) - (docEl && docEl.clientLeft || body && body.clientLeft || 0);
  12418. y = event.clientY + (docEl && docEl.scrollTop || body && body.scrollTop || 0) - (docEl && docEl.clientTop || body && body.clientTop || 0);
  12419. }
  12420. return [x, y];
  12421. },
  12422. /**
  12423. * Gets the target of the event.
  12424. * @param {Object} event The event
  12425. * @return {HTMLElement} target
  12426. */
  12427. getTarget: function(event) {
  12428. event = event.browserEvent || event;
  12429. return EventManager.resolveTextNode(event.target || event.srcElement);
  12430. },
  12431. /**
  12432. * Resolve any text nodes accounting for browser differences.
  12433. * @private
  12434. * @param {HTMLElement} node The node
  12435. * @return {HTMLElement} The resolved node
  12436. */
  12437. // technically no need to browser sniff this, however it makes no sense to check this every time, for every event, whether the string is equal.
  12438. resolveTextNode: Ext.isGecko ?
  12439. function(node) {
  12440. if (!node) {
  12441. return;
  12442. }
  12443. // work around firefox bug, https://bugzilla.mozilla.org/show_bug.cgi?id=101197
  12444. var s = HTMLElement.prototype.toString.call(node);
  12445. if (s == '[xpconnect wrapped native prototype]' || s == '[object XULElement]') {
  12446. return;
  12447. }
  12448. return node.nodeType == 3 ? node.parentNode: node;
  12449. }: function(node) {
  12450. return node && node.nodeType == 3 ? node.parentNode: node;
  12451. },
  12452. // --------------------- custom event binding ---------------------
  12453. // Keep track of the current width/height
  12454. curWidth: 0,
  12455. curHeight: 0,
  12456. /**
  12457. * Adds a listener to be notified when the browser window is resized and provides resize event buffering (100 milliseconds),
  12458. * passes new viewport width and height to handlers.
  12459. * @param {Function} fn The handler function the window resize event invokes.
  12460. * @param {Object} scope The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
  12461. * @param {Boolean} options Options object as passed to {@link Ext.Element#addListener}
  12462. */
  12463. onWindowResize: function(fn, scope, options) {
  12464. var resize = EventManager.resizeEvent;
  12465. if (!resize) {
  12466. EventManager.resizeEvent = resize = new Ext.util.Event();
  12467. EventManager.on(win, 'resize', EventManager.fireResize, null, {buffer: 100});
  12468. }
  12469. resize.addListener(fn, scope, options);
  12470. },
  12471. /**
  12472. * Fire the resize event.
  12473. * @private
  12474. */
  12475. fireResize: function() {
  12476. var w = Ext.Element.getViewWidth(),
  12477. h = Ext.Element.getViewHeight();
  12478. //whacky problem in IE where the resize event will sometimes fire even though the w/h are the same.
  12479. if (EventManager.curHeight != h || EventManager.curWidth != w) {
  12480. EventManager.curHeight = h;
  12481. EventManager.curWidth = w;
  12482. EventManager.resizeEvent.fire(w, h);
  12483. }
  12484. },
  12485. /**
  12486. * Removes the passed window resize listener.
  12487. * @param {Function} fn The method the event invokes
  12488. * @param {Object} scope The scope of handler
  12489. */
  12490. removeResizeListener: function(fn, scope) {
  12491. var resize = EventManager.resizeEvent;
  12492. if (resize) {
  12493. resize.removeListener(fn, scope);
  12494. }
  12495. },
  12496. /**
  12497. * Adds a listener to be notified when the browser window is unloaded.
  12498. * @param {Function} fn The handler function the window unload event invokes.
  12499. * @param {Object} scope The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
  12500. * @param {Boolean} options Options object as passed to {@link Ext.Element#addListener}
  12501. */
  12502. onWindowUnload: function(fn, scope, options) {
  12503. var unload = EventManager.unloadEvent;
  12504. if (!unload) {
  12505. EventManager.unloadEvent = unload = new Ext.util.Event();
  12506. EventManager.addListener(win, 'unload', EventManager.fireUnload);
  12507. }
  12508. if (fn) {
  12509. unload.addListener(fn, scope, options);
  12510. }
  12511. },
  12512. /**
  12513. * Fires the unload event for items bound with onWindowUnload
  12514. * @private
  12515. */
  12516. fireUnload: function() {
  12517. // wrap in a try catch, could have some problems during unload
  12518. try {
  12519. // relinquish references.
  12520. doc = win = undefined;
  12521. EventManager.unloadEvent.fire();
  12522. // Work around FF3 remembering the last scroll position when refreshing the grid and then losing grid view
  12523. if (Ext.isGecko3) {
  12524. var gridviews = Ext.ComponentQuery.query('gridview'),
  12525. i = 0,
  12526. ln = gridviews.length;
  12527. for (; i < ln; i++) {
  12528. gridviews[i].scrollToTop();
  12529. }
  12530. }
  12531. // Purge all elements in the cache
  12532. var el,
  12533. cache = Ext.cache;
  12534. for (el in cache) {
  12535. if (cache.hasOwnProperty(el)) {
  12536. EventManager.removeAll(el);
  12537. }
  12538. }
  12539. } catch(e) {
  12540. }
  12541. },
  12542. /**
  12543. * Removes the passed window unload listener.
  12544. * @param {Function} fn The method the event invokes
  12545. * @param {Object} scope The scope of handler
  12546. */
  12547. removeUnloadListener: function(fn, scope) {
  12548. var unload = EventManager.unloadEvent;
  12549. if (unload) {
  12550. unload.removeListener(fn, scope);
  12551. }
  12552. },
  12553. /**
  12554. * note 1: IE fires ONLY the keydown event on specialkey autorepeat
  12555. * note 2: Safari < 3.1, Gecko (Mac/Linux) & Opera fire only the keypress event on specialkey autorepeat
  12556. * (research done by Jan Wolter at http://unixpapa.com/js/key.html)
  12557. * @private
  12558. */
  12559. useKeyDown: Ext.isWebKit ?
  12560. parseInt(navigator.userAgent.match(/AppleWebKit\/(\d+)/)[1], 10) >= 525 :
  12561. !((Ext.isGecko && !Ext.isWindows) || Ext.isOpera),
  12562. /**
  12563. * Indicates which event to use for getting key presses.
  12564. * @return {String} The appropriate event name.
  12565. */
  12566. getKeyEvent: function() {
  12567. return EventManager.useKeyDown ? 'keydown' : 'keypress';
  12568. }
  12569. });
  12570. // route "< ie9-Standards" to a legacy IE onReady implementation
  12571. if(!('addEventListener' in document) && document.attachEvent) {
  12572. Ext.apply( EventManager, {
  12573. /* Customized implementation for Legacy IE. The default implementation is configured for use
  12574. * with all other 'standards compliant' agents.
  12575. * References: http://javascript.nwbox.com/IEContentLoaded/
  12576. * licensed courtesy of http://developer.yahoo.com/yui/license.html
  12577. */
  12578. /**
  12579. * This strategy has minimal benefits for Sencha solutions that build themselves (ie. minimal initial page markup).
  12580. * However, progressively-enhanced pages (with image content and/or embedded frames) will benefit the most from it.
  12581. * Browser timer resolution is too poor to ensure a doScroll check more than once on a page loaded with minimal
  12582. * assets (the readystatechange event 'complete' usually beats the doScroll timer on a 'lightly-loaded' initial document).
  12583. */
  12584. pollScroll : function() {
  12585. var scrollable = true;
  12586. try {
  12587. document.documentElement.doScroll('left');
  12588. } catch(e) {
  12589. scrollable = false;
  12590. }
  12591. if (scrollable) {
  12592. EventManager.onReadyEvent({
  12593. type:'doScroll'
  12594. });