PageRenderTime 121ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 1ms

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

https://bitbucket.org/srogerf/javascript
JavaScript | 14030 lines | 7599 code | 1129 blank | 5302 comment | 1308 complexity | cd31a3bae62ba15b08ea7e8779ed7476 MD5 | raw file
  1. /*
  2. This file is part of Ext JS 4
  3. Copyright (c) 2011 Sencha Inc
  4. Contact: http://www.sencha.com/contact
  5. GNU General Public License Usage
  6. This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
  7. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
  8. */
  9. /**
  10. * @class Ext
  11. * @singleton
  12. */
  13. (function() {
  14. var global = this,
  15. objectPrototype = Object.prototype,
  16. toString = objectPrototype.toString,
  17. enumerables = true,
  18. enumerablesTest = { toString: 1 },
  19. i;
  20. if (typeof Ext === 'undefined') {
  21. global.Ext = {};
  22. }
  23. Ext.global = global;
  24. for (i in enumerablesTest) {
  25. enumerables = null;
  26. }
  27. if (enumerables) {
  28. enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable',
  29. 'toLocaleString', 'toString', 'constructor'];
  30. }
  31. /**
  32. * An array containing extra enumerables for old browsers
  33. * @property {String[]}
  34. */
  35. Ext.enumerables = enumerables;
  36. /**
  37. * Copies all the properties of config to the specified object.
  38. * Note that if recursive merging and cloning without referencing the original objects / arrays is needed, use
  39. * {@link Ext.Object#merge} instead.
  40. * @param {Object} object The receiver of the properties
  41. * @param {Object} config The source of the properties
  42. * @param {Object} defaults A different object that will also be applied for default values
  43. * @return {Object} returns obj
  44. */
  45. Ext.apply = function(object, config, defaults) {
  46. if (defaults) {
  47. Ext.apply(object, defaults);
  48. }
  49. if (object && config && typeof config === 'object') {
  50. var i, j, k;
  51. for (i in config) {
  52. object[i] = config[i];
  53. }
  54. if (enumerables) {
  55. for (j = enumerables.length; j--;) {
  56. k = enumerables[j];
  57. if (config.hasOwnProperty(k)) {
  58. object[k] = config[k];
  59. }
  60. }
  61. }
  62. }
  63. return object;
  64. };
  65. Ext.buildSettings = Ext.apply({
  66. baseCSSPrefix: 'x-',
  67. scopeResetCSS: false
  68. }, Ext.buildSettings || {});
  69. Ext.apply(Ext, {
  70. /**
  71. * A reusable empty function
  72. */
  73. emptyFn: function() {},
  74. baseCSSPrefix: Ext.buildSettings.baseCSSPrefix,
  75. /**
  76. * Copies all the properties of config to object if they don't already exist.
  77. * @param {Object} object The receiver of the properties
  78. * @param {Object} config The source of the properties
  79. * @return {Object} returns obj
  80. */
  81. applyIf: function(object, config) {
  82. var property;
  83. if (object) {
  84. for (property in config) {
  85. if (object[property] === undefined) {
  86. object[property] = config[property];
  87. }
  88. }
  89. }
  90. return object;
  91. },
  92. /**
  93. * Iterates either an array or an object. This method delegates to
  94. * {@link Ext.Array#each Ext.Array.each} if the given value is iterable, and {@link Ext.Object#each Ext.Object.each} otherwise.
  95. *
  96. * @param {Object/Array} object The object or array to be iterated.
  97. * @param {Function} fn The function to be called for each iteration. See and {@link Ext.Array#each Ext.Array.each} and
  98. * {@link Ext.Object#each Ext.Object.each} for detailed lists of arguments passed to this function depending on the given object
  99. * type that is being iterated.
  100. * @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed.
  101. * Defaults to the object being iterated itself.
  102. * @markdown
  103. */
  104. iterate: function(object, fn, scope) {
  105. if (Ext.isEmpty(object)) {
  106. return;
  107. }
  108. if (scope === undefined) {
  109. scope = object;
  110. }
  111. if (Ext.isIterable(object)) {
  112. Ext.Array.each.call(Ext.Array, object, fn, scope);
  113. }
  114. else {
  115. Ext.Object.each.call(Ext.Object, object, fn, scope);
  116. }
  117. }
  118. });
  119. Ext.apply(Ext, {
  120. /**
  121. * This method deprecated. Use {@link Ext#define Ext.define} instead.
  122. * @method
  123. * @param {Function} superclass
  124. * @param {Object} overrides
  125. * @return {Function} The subclass constructor from the <tt>overrides</tt> parameter, or a generated one if not provided.
  126. * @deprecated 4.0.0 Use {@link Ext#define Ext.define} instead
  127. */
  128. extend: function() {
  129. // inline overrides
  130. var objectConstructor = objectPrototype.constructor,
  131. inlineOverrides = function(o) {
  132. for (var m in o) {
  133. if (!o.hasOwnProperty(m)) {
  134. continue;
  135. }
  136. this[m] = o[m];
  137. }
  138. };
  139. return function(subclass, superclass, overrides) {
  140. // First we check if the user passed in just the superClass with overrides
  141. if (Ext.isObject(superclass)) {
  142. overrides = superclass;
  143. superclass = subclass;
  144. subclass = overrides.constructor !== objectConstructor ? overrides.constructor : function() {
  145. superclass.apply(this, arguments);
  146. };
  147. }
  148. // We create a new temporary class
  149. var F = function() {},
  150. subclassProto, superclassProto = superclass.prototype;
  151. F.prototype = superclassProto;
  152. subclassProto = subclass.prototype = new F();
  153. subclassProto.constructor = subclass;
  154. subclass.superclass = superclassProto;
  155. if (superclassProto.constructor === objectConstructor) {
  156. superclassProto.constructor = superclass;
  157. }
  158. subclass.override = function(overrides) {
  159. Ext.override(subclass, overrides);
  160. };
  161. subclassProto.override = inlineOverrides;
  162. subclassProto.proto = subclassProto;
  163. subclass.override(overrides);
  164. subclass.extend = function(o) {
  165. return Ext.extend(subclass, o);
  166. };
  167. return subclass;
  168. };
  169. }(),
  170. /**
  171. * Proxy to {@link Ext.Base#override}. Please refer {@link Ext.Base#override} for further details.
  172. Ext.define('My.cool.Class', {
  173. sayHi: function() {
  174. alert('Hi!');
  175. }
  176. }
  177. Ext.override(My.cool.Class, {
  178. sayHi: function() {
  179. alert('About to say...');
  180. this.callOverridden();
  181. }
  182. });
  183. var cool = new My.cool.Class();
  184. cool.sayHi(); // alerts 'About to say...'
  185. // alerts 'Hi!'
  186. * Please note that `this.callOverridden()` only works if the class was previously
  187. * created with {@link Ext#define)
  188. *
  189. * @param {Object} cls The class to override
  190. * @param {Object} overrides The list of functions to add to origClass. This should be specified as an object literal
  191. * containing one or more methods.
  192. * @method override
  193. * @markdown
  194. */
  195. override: function(cls, overrides) {
  196. if (cls.prototype.$className) {
  197. return cls.override(overrides);
  198. }
  199. else {
  200. Ext.apply(cls.prototype, overrides);
  201. }
  202. }
  203. });
  204. // A full set of static methods to do type checking
  205. Ext.apply(Ext, {
  206. /**
  207. * Returns the given value itself if it's not empty, as described in {@link Ext#isEmpty}; returns the default
  208. * value (second argument) otherwise.
  209. *
  210. * @param {Object} value The value to test
  211. * @param {Object} defaultValue The value to return if the original value is empty
  212. * @param {Boolean} allowBlank (optional) true to allow zero length strings to qualify as non-empty (defaults to false)
  213. * @return {Object} value, if non-empty, else defaultValue
  214. */
  215. valueFrom: function(value, defaultValue, allowBlank){
  216. return Ext.isEmpty(value, allowBlank) ? defaultValue : value;
  217. },
  218. /**
  219. * Returns the type of the given variable in string format. List of possible values are:
  220. *
  221. * - `undefined`: If the given value is `undefined`
  222. * - `null`: If the given value is `null`
  223. * - `string`: If the given value is a string
  224. * - `number`: If the given value is a number
  225. * - `boolean`: If the given value is a boolean value
  226. * - `date`: If the given value is a `Date` object
  227. * - `function`: If the given value is a function reference
  228. * - `object`: If the given value is an object
  229. * - `array`: If the given value is an array
  230. * - `regexp`: If the given value is a regular expression
  231. * - `element`: If the given value is a DOM Element
  232. * - `textnode`: If the given value is a DOM text node and contains something other than whitespace
  233. * - `whitespace`: If the given value is a DOM text node and contains only whitespace
  234. *
  235. * @param {Object} value
  236. * @return {String}
  237. * @markdown
  238. */
  239. typeOf: function(value) {
  240. if (value === null) {
  241. return 'null';
  242. }
  243. var type = typeof value;
  244. if (type === 'undefined' || type === 'string' || type === 'number' || type === 'boolean') {
  245. return type;
  246. }
  247. var typeToString = toString.call(value);
  248. switch(typeToString) {
  249. case '[object Array]':
  250. return 'array';
  251. case '[object Date]':
  252. return 'date';
  253. case '[object Boolean]':
  254. return 'boolean';
  255. case '[object Number]':
  256. return 'number';
  257. case '[object RegExp]':
  258. return 'regexp';
  259. }
  260. if (type === 'function') {
  261. return 'function';
  262. }
  263. if (type === 'object') {
  264. if (value.nodeType !== undefined) {
  265. if (value.nodeType === 3) {
  266. return (/\S/).test(value.nodeValue) ? 'textnode' : 'whitespace';
  267. }
  268. else {
  269. return 'element';
  270. }
  271. }
  272. return 'object';
  273. }
  274. },
  275. /**
  276. * Returns true if the passed value is empty, false otherwise. The value is deemed to be empty if it is either:
  277. *
  278. * - `null`
  279. * - `undefined`
  280. * - a zero-length array
  281. * - a zero-length string (Unless the `allowEmptyString` parameter is set to `true`)
  282. *
  283. * @param {Object} value The value to test
  284. * @param {Boolean} allowEmptyString (optional) true to allow empty strings (defaults to false)
  285. * @return {Boolean}
  286. * @markdown
  287. */
  288. isEmpty: function(value, allowEmptyString) {
  289. return (value === null) || (value === undefined) || (!allowEmptyString ? value === '' : false) || (Ext.isArray(value) && value.length === 0);
  290. },
  291. /**
  292. * Returns true if the passed value is a JavaScript Array, false otherwise.
  293. *
  294. * @param {Object} target The target to test
  295. * @return {Boolean}
  296. * @method
  297. */
  298. isArray: ('isArray' in Array) ? Array.isArray : function(value) {
  299. return toString.call(value) === '[object Array]';
  300. },
  301. /**
  302. * Returns true if the passed value is a JavaScript Date object, false otherwise.
  303. * @param {Object} object The object to test
  304. * @return {Boolean}
  305. */
  306. isDate: function(value) {
  307. return toString.call(value) === '[object Date]';
  308. },
  309. /**
  310. * Returns true if the passed value is a JavaScript Object, false otherwise.
  311. * @param {Object} value The value to test
  312. * @return {Boolean}
  313. * @method
  314. */
  315. isObject: (toString.call(null) === '[object Object]') ?
  316. function(value) {
  317. // check ownerDocument here as well to exclude DOM nodes
  318. return value !== null && value !== undefined && toString.call(value) === '[object Object]' && value.ownerDocument === undefined;
  319. } :
  320. function(value) {
  321. return toString.call(value) === '[object Object]';
  322. },
  323. /**
  324. * Returns true if the passed value is a JavaScript 'primitive', a string, number or boolean.
  325. * @param {Object} value The value to test
  326. * @return {Boolean}
  327. */
  328. isPrimitive: function(value) {
  329. var type = typeof value;
  330. return type === 'string' || type === 'number' || type === 'boolean';
  331. },
  332. /**
  333. * Returns true if the passed value is a JavaScript Function, false otherwise.
  334. * @param {Object} value The value to test
  335. * @return {Boolean}
  336. * @method
  337. */
  338. isFunction:
  339. // Safari 3.x and 4.x returns 'function' for typeof <NodeList>, hence we need to fall back to using
  340. // Object.prorotype.toString (slower)
  341. (typeof document !== 'undefined' && typeof document.getElementsByTagName('body') === 'function') ? function(value) {
  342. return toString.call(value) === '[object Function]';
  343. } : function(value) {
  344. return typeof value === 'function';
  345. },
  346. /**
  347. * Returns true if the passed value is a number. Returns false for non-finite numbers.
  348. * @param {Object} value The value to test
  349. * @return {Boolean}
  350. */
  351. isNumber: function(value) {
  352. return typeof value === 'number' && isFinite(value);
  353. },
  354. /**
  355. * Validates that a value is numeric.
  356. * @param {Object} value Examples: 1, '1', '2.34'
  357. * @return {Boolean} True if numeric, false otherwise
  358. */
  359. isNumeric: function(value) {
  360. return !isNaN(parseFloat(value)) && isFinite(value);
  361. },
  362. /**
  363. * Returns true if the passed value is a string.
  364. * @param {Object} value The value to test
  365. * @return {Boolean}
  366. */
  367. isString: function(value) {
  368. return typeof value === 'string';
  369. },
  370. /**
  371. * Returns true if the passed value is a boolean.
  372. *
  373. * @param {Object} value The value to test
  374. * @return {Boolean}
  375. */
  376. isBoolean: function(value) {
  377. return typeof value === 'boolean';
  378. },
  379. /**
  380. * Returns true if the passed value is an HTMLElement
  381. * @param {Object} value The value to test
  382. * @return {Boolean}
  383. */
  384. isElement: function(value) {
  385. return value ? value.nodeType === 1 : false;
  386. },
  387. /**
  388. * Returns true if the passed value is a TextNode
  389. * @param {Object} value The value to test
  390. * @return {Boolean}
  391. */
  392. isTextNode: function(value) {
  393. return value ? value.nodeName === "#text" : false;
  394. },
  395. /**
  396. * Returns true if the passed value is defined.
  397. * @param {Object} value The value to test
  398. * @return {Boolean}
  399. */
  400. isDefined: function(value) {
  401. return typeof value !== 'undefined';
  402. },
  403. /**
  404. * Returns true if the passed value is iterable, false otherwise
  405. * @param {Object} value The value to test
  406. * @return {Boolean}
  407. */
  408. isIterable: function(value) {
  409. return (value && typeof value !== 'string') ? value.length !== undefined : false;
  410. }
  411. });
  412. Ext.apply(Ext, {
  413. /**
  414. * Clone almost any type of variable including array, object, DOM nodes and Date without keeping the old reference
  415. * @param {Object} item The variable to clone
  416. * @return {Object} clone
  417. */
  418. clone: function(item) {
  419. if (item === null || item === undefined) {
  420. return item;
  421. }
  422. // DOM nodes
  423. // TODO proxy this to Ext.Element.clone to handle automatic id attribute changing
  424. // recursively
  425. if (item.nodeType && item.cloneNode) {
  426. return item.cloneNode(true);
  427. }
  428. var type = toString.call(item);
  429. // Date
  430. if (type === '[object Date]') {
  431. return new Date(item.getTime());
  432. }
  433. var i, j, k, clone, key;
  434. // Array
  435. if (type === '[object Array]') {
  436. i = item.length;
  437. clone = [];
  438. while (i--) {
  439. clone[i] = Ext.clone(item[i]);
  440. }
  441. }
  442. // Object
  443. else if (type === '[object Object]' && item.constructor === Object) {
  444. clone = {};
  445. for (key in item) {
  446. clone[key] = Ext.clone(item[key]);
  447. }
  448. if (enumerables) {
  449. for (j = enumerables.length; j--;) {
  450. k = enumerables[j];
  451. clone[k] = item[k];
  452. }
  453. }
  454. }
  455. return clone || item;
  456. },
  457. /**
  458. * @private
  459. * Generate a unique reference of Ext in the global scope, useful for sandboxing
  460. */
  461. getUniqueGlobalNamespace: function() {
  462. var uniqueGlobalNamespace = this.uniqueGlobalNamespace;
  463. if (uniqueGlobalNamespace === undefined) {
  464. var i = 0;
  465. do {
  466. uniqueGlobalNamespace = 'ExtBox' + (++i);
  467. } while (Ext.global[uniqueGlobalNamespace] !== undefined);
  468. Ext.global[uniqueGlobalNamespace] = Ext;
  469. this.uniqueGlobalNamespace = uniqueGlobalNamespace;
  470. }
  471. return uniqueGlobalNamespace;
  472. },
  473. /**
  474. * @private
  475. */
  476. functionFactory: function() {
  477. var args = Array.prototype.slice.call(arguments);
  478. if (args.length > 0) {
  479. args[args.length - 1] = 'var Ext=window.' + this.getUniqueGlobalNamespace() + ';' +
  480. args[args.length - 1];
  481. }
  482. return Function.prototype.constructor.apply(Function.prototype, args);
  483. }
  484. });
  485. /**
  486. * Old alias to {@link Ext#typeOf}
  487. * @deprecated 4.0.0 Use {@link Ext#typeOf} instead
  488. * @method
  489. * @alias Ext#typeOf
  490. */
  491. Ext.type = Ext.typeOf;
  492. })();
  493. /**
  494. * @author Jacky Nguyen <jacky@sencha.com>
  495. * @docauthor Jacky Nguyen <jacky@sencha.com>
  496. * @class Ext.Version
  497. *
  498. * A utility class that wrap around a string version number and provide convenient
  499. * method to perform comparison. See also: {@link Ext.Version#compare compare}. Example:
  500. var version = new Ext.Version('1.0.2beta');
  501. console.log("Version is " + version); // Version is 1.0.2beta
  502. console.log(version.getMajor()); // 1
  503. console.log(version.getMinor()); // 0
  504. console.log(version.getPatch()); // 2
  505. console.log(version.getBuild()); // 0
  506. console.log(version.getRelease()); // beta
  507. console.log(version.isGreaterThan('1.0.1')); // True
  508. console.log(version.isGreaterThan('1.0.2alpha')); // True
  509. console.log(version.isGreaterThan('1.0.2RC')); // False
  510. console.log(version.isGreaterThan('1.0.2')); // False
  511. console.log(version.isLessThan('1.0.2')); // True
  512. console.log(version.match(1.0)); // True
  513. console.log(version.match('1.0.2')); // True
  514. * @markdown
  515. */
  516. (function() {
  517. // Current core version
  518. var version = '4.0.7', Version;
  519. Ext.Version = Version = Ext.extend(Object, {
  520. /**
  521. * @param {String/Number} version The version number in the follow standard format: major[.minor[.patch[.build[release]]]]
  522. * Examples: 1.0 or 1.2.3beta or 1.2.3.4RC
  523. * @return {Ext.Version} this
  524. */
  525. constructor: function(version) {
  526. var parts, releaseStartIndex;
  527. if (version instanceof Version) {
  528. return version;
  529. }
  530. this.version = this.shortVersion = String(version).toLowerCase().replace(/_/g, '.').replace(/[\-+]/g, '');
  531. releaseStartIndex = this.version.search(/([^\d\.])/);
  532. if (releaseStartIndex !== -1) {
  533. this.release = this.version.substr(releaseStartIndex, version.length);
  534. this.shortVersion = this.version.substr(0, releaseStartIndex);
  535. }
  536. this.shortVersion = this.shortVersion.replace(/[^\d]/g, '');
  537. parts = this.version.split('.');
  538. this.major = parseInt(parts.shift() || 0, 10);
  539. this.minor = parseInt(parts.shift() || 0, 10);
  540. this.patch = parseInt(parts.shift() || 0, 10);
  541. this.build = parseInt(parts.shift() || 0, 10);
  542. return this;
  543. },
  544. /**
  545. * Override the native toString method
  546. * @private
  547. * @return {String} version
  548. */
  549. toString: function() {
  550. return this.version;
  551. },
  552. /**
  553. * Override the native valueOf method
  554. * @private
  555. * @return {String} version
  556. */
  557. valueOf: function() {
  558. return this.version;
  559. },
  560. /**
  561. * Returns the major component value
  562. * @return {Number} major
  563. */
  564. getMajor: function() {
  565. return this.major || 0;
  566. },
  567. /**
  568. * Returns the minor component value
  569. * @return {Number} minor
  570. */
  571. getMinor: function() {
  572. return this.minor || 0;
  573. },
  574. /**
  575. * Returns the patch component value
  576. * @return {Number} patch
  577. */
  578. getPatch: function() {
  579. return this.patch || 0;
  580. },
  581. /**
  582. * Returns the build component value
  583. * @return {Number} build
  584. */
  585. getBuild: function() {
  586. return this.build || 0;
  587. },
  588. /**
  589. * Returns the release component value
  590. * @return {Number} release
  591. */
  592. getRelease: function() {
  593. return this.release || '';
  594. },
  595. /**
  596. * Returns whether this version if greater than the supplied argument
  597. * @param {String/Number} target The version to compare with
  598. * @return {Boolean} True if this version if greater than the target, false otherwise
  599. */
  600. isGreaterThan: function(target) {
  601. return Version.compare(this.version, target) === 1;
  602. },
  603. /**
  604. * Returns whether this version if smaller than the supplied argument
  605. * @param {String/Number} target The version to compare with
  606. * @return {Boolean} True if this version if smaller than the target, false otherwise
  607. */
  608. isLessThan: function(target) {
  609. return Version.compare(this.version, target) === -1;
  610. },
  611. /**
  612. * Returns whether this version equals to the supplied argument
  613. * @param {String/Number} target The version to compare with
  614. * @return {Boolean} True if this version equals to the target, false otherwise
  615. */
  616. equals: function(target) {
  617. return Version.compare(this.version, target) === 0;
  618. },
  619. /**
  620. * Returns whether this version matches the supplied argument. Example:
  621. * <pre><code>
  622. * var version = new Ext.Version('1.0.2beta');
  623. * console.log(version.match(1)); // True
  624. * console.log(version.match(1.0)); // True
  625. * console.log(version.match('1.0.2')); // True
  626. * console.log(version.match('1.0.2RC')); // False
  627. * </code></pre>
  628. * @param {String/Number} target The version to compare with
  629. * @return {Boolean} True if this version matches the target, false otherwise
  630. */
  631. match: function(target) {
  632. target = String(target);
  633. return this.version.substr(0, target.length) === target;
  634. },
  635. /**
  636. * Returns this format: [major, minor, patch, build, release]. Useful for comparison
  637. * @return {Number[]}
  638. */
  639. toArray: function() {
  640. return [this.getMajor(), this.getMinor(), this.getPatch(), this.getBuild(), this.getRelease()];
  641. },
  642. /**
  643. * Returns shortVersion version without dots and release
  644. * @return {String}
  645. */
  646. getShortVersion: function() {
  647. return this.shortVersion;
  648. }
  649. });
  650. Ext.apply(Version, {
  651. // @private
  652. releaseValueMap: {
  653. 'dev': -6,
  654. 'alpha': -5,
  655. 'a': -5,
  656. 'beta': -4,
  657. 'b': -4,
  658. 'rc': -3,
  659. '#': -2,
  660. 'p': -1,
  661. 'pl': -1
  662. },
  663. /**
  664. * Converts a version component to a comparable value
  665. *
  666. * @static
  667. * @param {Object} value The value to convert
  668. * @return {Object}
  669. */
  670. getComponentValue: function(value) {
  671. return !value ? 0 : (isNaN(value) ? this.releaseValueMap[value] || value : parseInt(value, 10));
  672. },
  673. /**
  674. * Compare 2 specified versions, starting from left to right. If a part contains special version strings,
  675. * they are handled in the following order:
  676. * 'dev' < 'alpha' = 'a' < 'beta' = 'b' < 'RC' = 'rc' < '#' < 'pl' = 'p' < 'anything else'
  677. *
  678. * @static
  679. * @param {String} current The current version to compare to
  680. * @param {String} target The target version to compare to
  681. * @return {Number} Returns -1 if the current version is smaller than the target version, 1 if greater, and 0 if they're equivalent
  682. */
  683. compare: function(current, target) {
  684. var currentValue, targetValue, i;
  685. current = new Version(current).toArray();
  686. target = new Version(target).toArray();
  687. for (i = 0; i < Math.max(current.length, target.length); i++) {
  688. currentValue = this.getComponentValue(current[i]);
  689. targetValue = this.getComponentValue(target[i]);
  690. if (currentValue < targetValue) {
  691. return -1;
  692. } else if (currentValue > targetValue) {
  693. return 1;
  694. }
  695. }
  696. return 0;
  697. }
  698. });
  699. Ext.apply(Ext, {
  700. /**
  701. * @private
  702. */
  703. versions: {},
  704. /**
  705. * @private
  706. */
  707. lastRegisteredVersion: null,
  708. /**
  709. * Set version number for the given package name.
  710. *
  711. * @param {String} packageName The package name, for example: 'core', 'touch', 'extjs'
  712. * @param {String/Ext.Version} version The version, for example: '1.2.3alpha', '2.4.0-dev'
  713. * @return {Ext}
  714. */
  715. setVersion: function(packageName, version) {
  716. Ext.versions[packageName] = new Version(version);
  717. Ext.lastRegisteredVersion = Ext.versions[packageName];
  718. return this;
  719. },
  720. /**
  721. * Get the version number of the supplied package name; will return the last registered version
  722. * (last Ext.setVersion call) if there's no package name given.
  723. *
  724. * @param {String} packageName (Optional) The package name, for example: 'core', 'touch', 'extjs'
  725. * @return {Ext.Version} The version
  726. */
  727. getVersion: function(packageName) {
  728. if (packageName === undefined) {
  729. return Ext.lastRegisteredVersion;
  730. }
  731. return Ext.versions[packageName];
  732. },
  733. /**
  734. * Create a closure for deprecated code.
  735. *
  736. // This means Ext.oldMethod is only supported in 4.0.0beta and older.
  737. // If Ext.getVersion('extjs') returns a version that is later than '4.0.0beta', for example '4.0.0RC',
  738. // the closure will not be invoked
  739. Ext.deprecate('extjs', '4.0.0beta', function() {
  740. Ext.oldMethod = Ext.newMethod;
  741. ...
  742. });
  743. * @param {String} packageName The package name
  744. * @param {String} since The last version before it's deprecated
  745. * @param {Function} closure The callback function to be executed with the specified version is less than the current version
  746. * @param {Object} scope The execution scope (<tt>this</tt>) if the closure
  747. * @markdown
  748. */
  749. deprecate: function(packageName, since, closure, scope) {
  750. if (Version.compare(Ext.getVersion(packageName), since) < 1) {
  751. closure.call(scope);
  752. }
  753. }
  754. }); // End Versioning
  755. Ext.setVersion('core', version);
  756. })();
  757. /**
  758. * @class Ext.String
  759. *
  760. * A collection of useful static methods to deal with strings
  761. * @singleton
  762. */
  763. Ext.String = {
  764. trimRegex: /^[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+|[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+$/g,
  765. escapeRe: /('|\\)/g,
  766. formatRe: /\{(\d+)\}/g,
  767. escapeRegexRe: /([-.*+?^${}()|[\]\/\\])/g,
  768. /**
  769. * Convert certain characters (&, <, >, and ") to their HTML character equivalents for literal display in web pages.
  770. * @param {String} value The string to encode
  771. * @return {String} The encoded text
  772. * @method
  773. */
  774. htmlEncode: (function() {
  775. var entities = {
  776. '&': '&amp;',
  777. '>': '&gt;',
  778. '<': '&lt;',
  779. '"': '&quot;'
  780. }, keys = [], p, regex;
  781. for (p in entities) {
  782. keys.push(p);
  783. }
  784. regex = new RegExp('(' + keys.join('|') + ')', 'g');
  785. return function(value) {
  786. return (!value) ? value : String(value).replace(regex, function(match, capture) {
  787. return entities[capture];
  788. });
  789. };
  790. })(),
  791. /**
  792. * Convert certain characters (&, <, >, and ") from their HTML character equivalents.
  793. * @param {String} value The string to decode
  794. * @return {String} The decoded text
  795. * @method
  796. */
  797. htmlDecode: (function() {
  798. var entities = {
  799. '&amp;': '&',
  800. '&gt;': '>',
  801. '&lt;': '<',
  802. '&quot;': '"'
  803. }, keys = [], p, regex;
  804. for (p in entities) {
  805. keys.push(p);
  806. }
  807. regex = new RegExp('(' + keys.join('|') + '|&#[0-9]{1,5};' + ')', 'g');
  808. return function(value) {
  809. return (!value) ? value : String(value).replace(regex, function(match, capture) {
  810. if (capture in entities) {
  811. return entities[capture];
  812. } else {
  813. return String.fromCharCode(parseInt(capture.substr(2), 10));
  814. }
  815. });
  816. };
  817. })(),
  818. /**
  819. * Appends content to the query string of a URL, handling logic for whether to place
  820. * a question mark or ampersand.
  821. * @param {String} url The URL to append to.
  822. * @param {String} string The content to append to the URL.
  823. * @return (String) The resulting URL
  824. */
  825. urlAppend : function(url, string) {
  826. if (!Ext.isEmpty(string)) {
  827. return url + (url.indexOf('?') === -1 ? '?' : '&') + string;
  828. }
  829. return url;
  830. },
  831. /**
  832. * Trims whitespace from either end of a string, leaving spaces within the string intact. Example:
  833. * @example
  834. var s = ' foo bar ';
  835. alert('-' + s + '-'); //alerts "- foo bar -"
  836. alert('-' + Ext.String.trim(s) + '-'); //alerts "-foo bar-"
  837. * @param {String} string The string to escape
  838. * @return {String} The trimmed string
  839. */
  840. trim: function(string) {
  841. return string.replace(Ext.String.trimRegex, "");
  842. },
  843. /**
  844. * Capitalize the given string
  845. * @param {String} string
  846. * @return {String}
  847. */
  848. capitalize: function(string) {
  849. return string.charAt(0).toUpperCase() + string.substr(1);
  850. },
  851. /**
  852. * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
  853. * @param {String} value The string to truncate
  854. * @param {Number} length The maximum length to allow before truncating
  855. * @param {Boolean} word True to try to find a common word break
  856. * @return {String} The converted text
  857. */
  858. ellipsis: function(value, len, word) {
  859. if (value && value.length > len) {
  860. if (word) {
  861. var vs = value.substr(0, len - 2),
  862. index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?'));
  863. if (index !== -1 && index >= (len - 15)) {
  864. return vs.substr(0, index) + "...";
  865. }
  866. }
  867. return value.substr(0, len - 3) + "...";
  868. }
  869. return value;
  870. },
  871. /**
  872. * Escapes the passed string for use in a regular expression
  873. * @param {String} string
  874. * @return {String}
  875. */
  876. escapeRegex: function(string) {
  877. return string.replace(Ext.String.escapeRegexRe, "\\$1");
  878. },
  879. /**
  880. * Escapes the passed string for ' and \
  881. * @param {String} string The string to escape
  882. * @return {String} The escaped string
  883. */
  884. escape: function(string) {
  885. return string.replace(Ext.String.escapeRe, "\\$1");
  886. },
  887. /**
  888. * Utility function that allows you to easily switch a string between two alternating values. The passed value
  889. * is compared to the current string, and if they are equal, the other value that was passed in is returned. If
  890. * they are already different, the first value passed in is returned. Note that this method returns the new value
  891. * but does not change the current string.
  892. * <pre><code>
  893. // alternate sort directions
  894. sort = Ext.String.toggle(sort, 'ASC', 'DESC');
  895. // instead of conditional logic:
  896. sort = (sort == 'ASC' ? 'DESC' : 'ASC');
  897. </code></pre>
  898. * @param {String} string The current string
  899. * @param {String} value The value to compare to the current string
  900. * @param {String} other The new value to use if the string already equals the first value passed in
  901. * @return {String} The new value
  902. */
  903. toggle: function(string, value, other) {
  904. return string === value ? other : value;
  905. },
  906. /**
  907. * Pads the left side of a string with a specified character. This is especially useful
  908. * for normalizing number and date strings. Example usage:
  909. *
  910. * <pre><code>
  911. var s = Ext.String.leftPad('123', 5, '0');
  912. // s now contains the string: '00123'
  913. </code></pre>
  914. * @param {String} string The original string
  915. * @param {Number} size The total length of the output string
  916. * @param {String} character (optional) The character with which to pad the original string (defaults to empty string " ")
  917. * @return {String} The padded string
  918. */
  919. leftPad: function(string, size, character) {
  920. var result = String(string);
  921. character = character || " ";
  922. while (result.length < size) {
  923. result = character + result;
  924. }
  925. return result;
  926. },
  927. /**
  928. * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
  929. * token must be unique, and must increment in the format {0}, {1}, etc. Example usage:
  930. * <pre><code>
  931. var cls = 'my-class', text = 'Some text';
  932. var s = Ext.String.format('&lt;div class="{0}">{1}&lt;/div>', cls, text);
  933. // s now contains the string: '&lt;div class="my-class">Some text&lt;/div>'
  934. </code></pre>
  935. * @param {String} string The tokenized string to be formatted
  936. * @param {String} value1 The value to replace token {0}
  937. * @param {String} value2 Etc...
  938. * @return {String} The formatted string
  939. */
  940. format: function(format) {
  941. var args = Ext.Array.toArray(arguments, 1);
  942. return format.replace(Ext.String.formatRe, function(m, i) {
  943. return args[i];
  944. });
  945. },
  946. /**
  947. * Returns a string with a specified number of repititions a given string pattern.
  948. * The pattern be separated by a different string.
  949. *
  950. * var s = Ext.String.repeat('---', 4); // = '------------'
  951. * var t = Ext.String.repeat('--', 3, '/'); // = '--/--/--'
  952. *
  953. * @param {String} pattern The pattern to repeat.
  954. * @param {Number} count The number of times to repeat the pattern (may be 0).
  955. * @param {String} sep An option string to separate each pattern.
  956. */
  957. repeat: function(pattern, count, sep) {
  958. for (var buf = [], i = count; i--; ) {
  959. buf.push(pattern);
  960. }
  961. return buf.join(sep || '');
  962. }
  963. };
  964. /**
  965. * @class Ext.Number
  966. *
  967. * A collection of useful static methods to deal with numbers
  968. * @singleton
  969. */
  970. (function() {
  971. var isToFixedBroken = (0.9).toFixed() !== '1';
  972. Ext.Number = {
  973. /**
  974. * Checks whether or not the passed number is within a desired range. If the number is already within the
  975. * range it is returned, otherwise the min or max value is returned depending on which side of the range is
  976. * exceeded. Note that this method returns the constrained value but does not change the current number.
  977. * @param {Number} number The number to check
  978. * @param {Number} min The minimum number in the range
  979. * @param {Number} max The maximum number in the range
  980. * @return {Number} The constrained value if outside the range, otherwise the current value
  981. */
  982. constrain: function(number, min, max) {
  983. number = parseFloat(number);
  984. if (!isNaN(min)) {
  985. number = Math.max(number, min);
  986. }
  987. if (!isNaN(max)) {
  988. number = Math.min(number, max);
  989. }
  990. return number;
  991. },
  992. /**
  993. * Snaps the passed number between stopping points based upon a passed increment value.
  994. * @param {Number} value The unsnapped value.
  995. * @param {Number} increment The increment by which the value must move.
  996. * @param {Number} minValue The minimum value to which the returned value must be constrained. Overrides the increment..
  997. * @param {Number} maxValue The maximum value to which the returned value must be constrained. Overrides the increment..
  998. * @return {Number} The value of the nearest snap target.
  999. */
  1000. snap : function(value, increment, minValue, maxValue) {
  1001. var newValue = value,
  1002. m;
  1003. if (!(increment && value)) {
  1004. return value;
  1005. }
  1006. m = value % increment;
  1007. if (m !== 0) {
  1008. newValue -= m;
  1009. if (m * 2 >= increment) {
  1010. newValue += increment;
  1011. } else if (m * 2 < -increment) {
  1012. newValue -= increment;
  1013. }
  1014. }
  1015. return Ext.Number.constrain(newValue, minValue, maxValue);
  1016. },
  1017. /**
  1018. * Formats a number using fixed-point notation
  1019. * @param {Number} value The number to format
  1020. * @param {Number} precision The number of digits to show after the decimal point
  1021. */
  1022. toFixed: function(value, precision) {
  1023. if (isToFixedBroken) {
  1024. precision = precision || 0;
  1025. var pow = Math.pow(10, precision);
  1026. return (Math.round(value * pow) / pow).toFixed(precision);
  1027. }
  1028. return value.toFixed(precision);
  1029. },
  1030. /**
  1031. * Validate that a value is numeric and convert it to a number if necessary. Returns the specified default value if
  1032. * it is not.
  1033. Ext.Number.from('1.23', 1); // returns 1.23
  1034. Ext.Number.from('abc', 1); // returns 1
  1035. * @param {Object} value
  1036. * @param {Number} defaultValue The value to return if the original value is non-numeric
  1037. * @return {Number} value, if numeric, defaultValue otherwise
  1038. */
  1039. from: function(value, defaultValue) {
  1040. if (isFinite(value)) {
  1041. value = parseFloat(value);
  1042. }
  1043. return !isNaN(value) ? value : defaultValue;
  1044. }
  1045. };
  1046. })();
  1047. /**
  1048. * @deprecated 4.0.0 Please use {@link Ext.Number#from} instead.
  1049. * @member Ext
  1050. * @method num
  1051. * @alias Ext.Number#from
  1052. */
  1053. Ext.num = function() {
  1054. return Ext.Number.from.apply(this, arguments);
  1055. };
  1056. /**
  1057. * @class Ext.Array
  1058. * @singleton
  1059. * @author Jacky Nguyen <jacky@sencha.com>
  1060. * @docauthor Jacky Nguyen <jacky@sencha.com>
  1061. *
  1062. * A set of useful static methods to deal with arrays; provide missing methods for older browsers.
  1063. */
  1064. (function() {
  1065. var arrayPrototype = Array.prototype,
  1066. slice = arrayPrototype.slice,
  1067. supportsSplice = function () {
  1068. var array = [],
  1069. lengthBefore,
  1070. j = 20;
  1071. if (!array.splice) {
  1072. return false;
  1073. }
  1074. // This detects a bug in IE8 splice method:
  1075. // see http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/6e946d03-e09f-4b22-a4dd-cd5e276bf05a/
  1076. while (j--) {
  1077. array.push("A");
  1078. }
  1079. array.splice(15, 0, "F", "F", "F", "F", "F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F");
  1080. lengthBefore = array.length; //41
  1081. array.splice(13, 0, "XXX"); // add one element
  1082. if (lengthBefore+1 != array.length) {
  1083. return false;
  1084. }
  1085. // end IE8 bug
  1086. return true;
  1087. }(),
  1088. supportsForEach = 'forEach' in arrayPrototype,
  1089. supportsMap = 'map' in arrayPrototype,
  1090. supportsIndexOf = 'indexOf' in arrayPrototype,
  1091. supportsEvery = 'every' in arrayPrototype,
  1092. supportsSome = 'some' in arrayPrototype,
  1093. supportsFilter = 'filter' in arrayPrototype,
  1094. supportsSort = function() {
  1095. var a = [1,2,3,4,5].sort(function(){ return 0; });
  1096. return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5;
  1097. }(),
  1098. supportsSliceOnNodeList = true,
  1099. ExtArray;
  1100. try {
  1101. // IE 6 - 8 will throw an error when using Array.prototype.slice on NodeList
  1102. if (typeof document !== 'undefined') {
  1103. slice.call(document.getElementsByTagName('body'));
  1104. }
  1105. } catch (e) {
  1106. supportsSliceOnNodeList = false;
  1107. }
  1108. function fixArrayIndex (array, index) {
  1109. return (index < 0) ? Math.max(0, array.length + index)
  1110. : Math.min(array.length, index);
  1111. }
  1112. /*
  1113. Does the same work as splice, but with a slightly more convenient signature. The splice
  1114. method has bugs in IE8, so this is the implementation we use on that platform.
  1115. The rippling of items in the array can be tricky. Consider two use cases:
  1116. index=2
  1117. removeCount=2
  1118. /=====\
  1119. +---+---+---+---+---+---+---+---+
  1120. | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
  1121. +---+---+---+---+---+---+---+---+
  1122. / \/ \/ \/ \
  1123. / /\ /\ /\ \
  1124. / / \/ \/ \ +--------------------------+
  1125. / / /\ /\ +--------------------------+ \
  1126. / / / \/ +--------------------------+ \ \
  1127. / / / /+--------------------------+ \ \ \
  1128. / / / / \ \ \ \
  1129. v v v v v v v v
  1130. +---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+---+
  1131. | 0 | 1 | 4 | 5 | 6 | 7 | | 0 | 1 | a | b | c | 4 | 5 | 6 | 7 |
  1132. +---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+---+
  1133. A B \=========/
  1134. insert=[a,b,c]
  1135. In case A, it is obvious that copying of [4,5,6,7] must be left-to-right so
  1136. that we don't end up with [0,1,6,7,6,7]. In case B, we have the opposite; we
  1137. must go right-to-left or else we would end up with [0,1,a,b,c,4,4,4,4].
  1138. */
  1139. function replaceSim (array, index, removeCount, insert) {
  1140. var add = insert ? insert.length : 0,
  1141. length = array.length,
  1142. pos = fixArrayIndex(array, index);
  1143. // we try to use Array.push when we can for efficiency...
  1144. if (pos === length) {
  1145. if (add) {
  1146. array.push.apply(array, insert);
  1147. }
  1148. } else {
  1149. var remove = Math.min(removeCount, length - pos),
  1150. tailOldPos = pos + remove,
  1151. tailNewPos = tailOldPos + add - remove,
  1152. tailCount = length - tailOldPos,
  1153. lengthAfterRemove = length - remove,
  1154. i;
  1155. if (tailNewPos < tailOldPos) { // case A
  1156. for (i = 0; i < tailCount; ++i) {
  1157. array[tailNewPos+i] = array[tailOldPos+i];
  1158. }
  1159. } else if (tailNewPos > tailOldPos) { // case B
  1160. for (i = tailCount; i--; ) {
  1161. array[tailNewPos+i] = array[tailOldPos+i];
  1162. }
  1163. } // else, add == remove (nothing to do)
  1164. if (add && pos === lengthAfterRemove) {
  1165. array.length = lengthAfterRemove; // truncate array
  1166. array.push.apply(array, insert);
  1167. } else {
  1168. array.length = lengthAfterRemove + add; // reserves space
  1169. for (i = 0; i < add; ++i) {
  1170. array[pos+i] = insert[i];
  1171. }
  1172. }
  1173. }
  1174. return array;
  1175. }
  1176. function replaceNative (array, index, removeCount, insert) {
  1177. if (insert && insert.length) {
  1178. if (index < array.length) {
  1179. array.splice.apply(array, [index, removeCount].concat(insert));
  1180. } else {
  1181. array.push.apply(array, insert);
  1182. }
  1183. } else {
  1184. array.splice(index, removeCount);
  1185. }
  1186. return array;
  1187. }
  1188. function eraseSim (array, index, removeCount) {
  1189. return replaceSim(array, index, removeCount);
  1190. }
  1191. function eraseNative (array, index, removeCount) {
  1192. array.splice(index, removeCount);
  1193. return array;
  1194. }
  1195. function spliceSim (array, index, removeCount) {
  1196. var pos = fixArrayIndex(array, index),
  1197. removed = array.slice(index, fixArrayIndex(array, pos+removeCount));
  1198. if (arguments.length < 4) {
  1199. replaceSim(array, pos, removeCount);
  1200. } else {
  1201. replaceSim(array, pos, removeCount, slice.call(arguments, 3));
  1202. }
  1203. return removed;
  1204. }
  1205. function spliceNative (array) {
  1206. return array.splice.apply(array, slice.call(arguments, 1));
  1207. }
  1208. var erase = supportsSplice ? eraseNative : eraseSim,
  1209. replace = supportsSplice ? replaceNative : replaceSim,
  1210. splice = supportsSplice ? spliceNative : spliceSim;
  1211. // NOTE: from here on, use erase, replace or splice (not native methods)...
  1212. ExtArray = Ext.Array = {
  1213. /**
  1214. * Iterates an array or an iterable value and invoke the given callback function for each item.
  1215. *
  1216. * var countries = ['Vietnam', 'Singapore', 'United States', 'Russia'];
  1217. *
  1218. * Ext.Array.each(countries, function(name, index, countriesItSelf) {
  1219. * console.log(name);
  1220. * });
  1221. *
  1222. * var sum = function() {
  1223. * var sum = 0;
  1224. *
  1225. * Ext.Array.each(arguments, function(value) {
  1226. * sum += value;
  1227. * });
  1228. *
  1229. * return sum;
  1230. * };
  1231. *
  1232. * sum(1, 2, 3); // returns 6
  1233. *
  1234. * The iteration can be stopped by returning false in the function callback.
  1235. *
  1236. * Ext.Array.each(countries, function(name, index, countriesItSelf) {
  1237. * if (name === 'Singapore') {
  1238. * return false; // break here
  1239. * }
  1240. * });
  1241. *
  1242. * {@link Ext#each Ext.each} is alias for {@link Ext.Array#each Ext.Array.each}
  1243. *
  1244. * @param {Array/NodeList/Object} iterable The value to be iterated. If this
  1245. * argument is not iterable, the callback function is called once.
  1246. * @param {Function} fn The callback function. If it returns false, the iteration stops and this method returns
  1247. * the current `index`.
  1248. * @param {Object} fn.item The item at the current `index` in the passed `array`
  1249. * @param {Number} fn.index The current `index` within the `array`
  1250. * @param {Array} fn.allItems The `array` itself which was passed as the first argument
  1251. * @param {Boolean} fn.return Return false to stop iteration.
  1252. * @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed.
  1253. * @param {Boolean} reverse (Optional) Reverse the iteration order (loop from the end to the beginning)
  1254. * Defaults false
  1255. * @return {Boolean} See description for the `fn` parameter.
  1256. */
  1257. each: function(array, fn, scope, reverse) {
  1258. array = ExtArray.from(array);
  1259. var i,
  1260. ln = array.length;
  1261. if (reverse !== true) {
  1262. for (i = 0; i < ln; i++) {
  1263. if (fn.call(scope || array[i], array[i], i, array) === false) {
  1264. return i;
  1265. }
  1266. }
  1267. }
  1268. else {
  1269. for (i = ln - 1; i > -1; i--) {
  1270. if (fn.call(scope || array[i], array[i], i, array) === false) {
  1271. return i;
  1272. }
  1273. }
  1274. }
  1275. return true;
  1276. },
  1277. /**
  1278. * Iterates an array and invoke the given callback function for each item. Note that this will simply
  1279. * delegate to the native Array.prototype.forEach method if supported. It doesn't support stopping the
  1280. * iteration by returning false in the callback function like {@link Ext.Array#each}. However, performance
  1281. * could be much better in modern browsers comparing with {@link Ext.Array#each}
  1282. *
  1283. * @param {Array} array The array to iterate
  1284. * @param {Function} fn The callback function.
  1285. * @param {Object} fn.item The item at the current `index` in the passed `array`
  1286. * @param {Number} fn.index The current `index` within the `array`
  1287. * @param {Array} fn.allItems The `array` itself which was passed as the first argument
  1288. * @param {Object} scope (Optional) The execution scope (`this`) in which the specified function is executed.
  1289. */
  1290. forEach: function(array, fn, scope) {
  1291. if (supportsForEach) {
  1292. return array.forEach(fn, scope);
  1293. }
  1294. var i = 0,
  1295. ln = array.length;
  1296. for (; i < ln; i++) {
  1297. fn.call(scope, array[i], i, array);
  1298. }
  1299. },
  1300. /**
  1301. * Get the index of the provided `item` in the given `array`, a supplement for the
  1302. * missing arrayPrototype.indexOf in Internet Explorer.
  1303. *
  1304. * @param {Array} array The array to check
  1305. * @param {Object} item The item to look for
  1306. * @param {Number} from (Optional) The index at which to begin the search
  1307. * @return {Number} The index of item in the array (or -1 if it is not found)
  1308. */
  1309. indexOf: function(array, item, from) {
  1310. if (supportsIndexOf) {
  1311. return array.indexOf(item, from);
  1312. }
  1313. var i, length = array.length;
  1314. for (i = (from < 0) ? Math.max(0, length + from) : from || 0; i < length; i++) {
  1315. if (array[i] === item) {
  1316. return i;
  1317. }
  1318. }
  1319. return -1;
  1320. },
  1321. /**
  1322. * Checks whether or not the given `array` contains the specified `item`
  1323. *
  1324. * @param {Array} array The array to check
  1325. * @param {Object} item The item to look for
  1326. * @return {Boolean} True if the array contains the item, false otherwise
  1327. */
  1328. contains: function(array, item) {
  1329. if (supportsIndexOf) {
  1330. return array.indexOf(item) !== -1;
  1331. }
  1332. var i, ln;
  1333. for (i = 0, ln = array.length; i < ln; i++) {
  1334. if (array[i] === item) {
  1335. return true;
  1336. }
  1337. }
  1338. return false;
  1339. },
  1340. /**
  1341. * Converts any iterable (numeric indices and a length property) into a true array.
  1342. *
  1343. * function test() {
  1344. * var args = Ext.Array.toArray(arguments),
  1345. * fromSecondToLastArgs = Ext.Array.toArray(arguments, 1);
  1346. *
  1347. * alert(args.join(' '));
  1348. * alert(fromSecondToLastArgs.join(' '));
  1349. * }
  1350. *
  1351. * test('just', 'testing', 'here'); // alerts 'just testing here';
  1352. * // alerts 'testing here';
  1353. *
  1354. * Ext.Array.toArray(document.getElementsByTagName('div')); // will convert the NodeList into an array
  1355. * Ext.Array.toArray('splitted'); // returns ['s', 'p', 'l', 'i', 't', 't', 'e', 'd']
  1356. * Ext.Array.toArray('splitted', 0, 3); // returns ['s', 'p', 'l', 'i']
  1357. *
  1358. * {@link Ext#toArray Ext.toArray} is alias for {@link Ext.Array#toArray Ext.Array.toArray}
  1359. *
  1360. * @param {Object} iterable the iterable object to be turned into a true Array.
  1361. * @param {Number} start (Optional) a zero-based index that specifies the start of extraction. Defaults to 0
  1362. * @param {Number} end (Optional) a zero-based index that specifies the end of extraction. Defaults to the last
  1363. * index of the iterable value
  1364. * @return {Array} array
  1365. */
  1366. toArray: function(iterable, start, end){
  1367. if (!iterable || !iterable.length) {
  1368. return [];
  1369. }
  1370. if (typeof iterable === 'string') {
  1371. iterable = iterable.split('');
  1372. }
  1373. if (supportsSliceOnNodeList) {
  1374. return slice.call(iterable, start || 0, end || iterable.length);
  1375. }
  1376. var array = [],
  1377. i;
  1378. start = start || 0;
  1379. end = end ? ((end < 0) ? iterable.length + end : end) : iterable.length;
  1380. for (i = start; i < end; i++) {
  1381. array.push(iterable[i]);
  1382. }
  1383. return array;
  1384. },
  1385. /**
  1386. * Plucks the value of a property from each item in the Array. Example:
  1387. *
  1388. * Ext.Array.pluck(Ext.query("p"), "className"); // [el1.className, el2.className, ..., elN.className]
  1389. *
  1390. * @param {Array/NodeList} array The Array of items to pluck the value from.
  1391. * @param {String} propertyName The property name to pluck from each element.
  1392. * @return {Array} The value from each item in the Array.
  1393. */
  1394. pluck: function(array, propertyName) {
  1395. var ret = [],
  1396. i, ln, item;
  1397. for (i = 0, ln = array.length; i < ln; i++) {
  1398. item = array[i];
  1399. ret.push(item[propertyName]);
  1400. }
  1401. return ret;
  1402. },
  1403. /**
  1404. * Creates a new array with the results of calling a provided function on every element in this array.
  1405. *
  1406. * @param {Array} array
  1407. * @param {Function} fn Callback function for each item
  1408. * @param {Object} scope Callback function scope
  1409. * @return {Array} results
  1410. */
  1411. map: function(array, fn, scope) {
  1412. if (supportsMap) {
  1413. return array.map(fn, scope);
  1414. }
  1415. var results = [],
  1416. i = 0,
  1417. len = array.length;
  1418. for (; i < len; i++) {
  1419. results[i] = fn.call(scope, array[i], i, array);
  1420. }
  1421. return results;
  1422. },
  1423. /**
  1424. * Executes the specified function for each array element until the function returns a falsy value.
  1425. * If such an item is found, the function will return false immediately.
  1426. * Otherwise, it will return true.
  1427. *
  1428. * @param {Array} array
  1429. * @param {Function} fn Callback function for each item
  1430. * @param {Object} scope Callback function scope
  1431. * @return {Boolean} True if no false value is returned by the callback function.
  1432. */
  1433. every: function(array, fn, scope) {
  1434. if (supportsEvery) {
  1435. return array.every(fn, scope);
  1436. }
  1437. var i = 0,
  1438. ln = array.length;
  1439. for (; i < ln; ++i) {
  1440. if (!fn.call(scope, array[i], i, array)) {
  1441. return false;
  1442. }
  1443. }
  1444. return true;
  1445. },
  1446. /**
  1447. * Executes the specified function for each array element until the function returns a truthy value.
  1448. * If such an item is found, the function will return true immediately. Otherwise, it will return false.
  1449. *
  1450. * @param {Array} array
  1451. * @param {Function} fn Callback function for each item
  1452. * @param {Object} scope Callback function scope
  1453. * @return {Boolean} True if the callback function returns a truthy value.
  1454. */
  1455. some: function(array, fn, scope) {
  1456. if (supportsSome) {
  1457. return array.some(fn, scope);
  1458. }
  1459. var i = 0,
  1460. ln = array.length;
  1461. for (; i < ln; ++i) {
  1462. if (fn.call(scope, array[i], i, array)) {
  1463. return true;
  1464. }
  1465. }
  1466. return false;
  1467. },
  1468. /**
  1469. * Filter through an array and remove empty item as defined in {@link Ext#isEmpty Ext.isEmpty}
  1470. *
  1471. * See {@link Ext.Array#filter}
  1472. *
  1473. * @param {Array} array
  1474. * @return {Array} results
  1475. */
  1476. clean: function(array) {
  1477. var results = [],
  1478. i = 0,
  1479. ln = array.length,
  1480. item;
  1481. for (; i < ln; i++) {
  1482. item = array[i];
  1483. if (!Ext.isEmpty(item)) {
  1484. results.push(item);
  1485. }
  1486. }
  1487. return results;
  1488. },
  1489. /**
  1490. * Returns a new array with unique items
  1491. *
  1492. * @param {Array} array
  1493. * @return {Array} results
  1494. */
  1495. unique: function(array) {
  1496. var clone = [],
  1497. i = 0,
  1498. ln = array.length,
  1499. item;
  1500. for (; i < ln; i++) {
  1501. item = array[i];
  1502. if (ExtArray.indexOf(clone, item) === -1) {
  1503. clone.push(item);
  1504. }
  1505. }
  1506. return clone;
  1507. },
  1508. /**
  1509. * Creates a new array with all of the elements of this array for which
  1510. * the provided filtering function returns true.
  1511. *
  1512. * @param {Array} array
  1513. * @param {Function} fn Callback function for each item
  1514. * @param {Object} scope Callback function scope
  1515. * @return {Array} results
  1516. */
  1517. filter: function(array, fn, scope) {
  1518. if (supportsFilter) {
  1519. return array.filter(fn, scope);
  1520. }
  1521. var results = [],
  1522. i = 0,
  1523. ln = array.length;
  1524. for (; i < ln; i++) {
  1525. if (fn.call(scope, array[i], i, array)) {
  1526. results.push(array[i]);
  1527. }
  1528. }
  1529. return results;
  1530. },
  1531. /**
  1532. * Converts a value to an array if it's not already an array; returns:
  1533. *
  1534. * - An empty array if given value is `undefined` or `null`
  1535. * - Itself if given value is already an array
  1536. * - An array copy if given value is {@link Ext#isIterable iterable} (arguments, NodeList and alike)
  1537. * - An array with one item which is the given value, otherwise
  1538. *
  1539. * @param {Object} value The value to convert to an array if it's not already is an array
  1540. * @param {Boolean} newReference (Optional) True to clone the given array and return a new reference if necessary,
  1541. * defaults to false
  1542. * @return {Array} array
  1543. */
  1544. from: function(value, newReference) {
  1545. if (value === undefined || value === null) {
  1546. return [];
  1547. }
  1548. if (Ext.isArray(value)) {
  1549. return (newReference) ? slice.call(value) : value;
  1550. }
  1551. if (value && value.length !== undefined && typeof value !== 'string') {
  1552. return Ext.toArray(value);
  1553. }
  1554. return [value];
  1555. },
  1556. /**
  1557. * Removes the specified item from the array if it exists
  1558. *
  1559. * @param {Array} array The array
  1560. * @param {Object} item The item to remove
  1561. * @return {Array} The passed array itself
  1562. */
  1563. remove: function(array, item) {
  1564. var index = ExtArray.indexOf(array, item);
  1565. if (index !== -1) {
  1566. erase(array, index, 1);
  1567. }
  1568. return array;
  1569. },
  1570. /**
  1571. * Push an item into the array only if the array doesn't contain it yet
  1572. *
  1573. * @param {Array} array The array
  1574. * @param {Object} item The item to include
  1575. */
  1576. include: function(array, item) {
  1577. if (!ExtArray.contains(array, item)) {
  1578. array.push(item);
  1579. }
  1580. },
  1581. /**
  1582. * Clone a flat array without referencing the previous one. Note that this is different
  1583. * from Ext.clone since it doesn't handle recursive cloning. It's simply a convenient, easy-to-remember method
  1584. * for Array.prototype.slice.call(array)
  1585. *
  1586. * @param {Array} array The array
  1587. * @return {Array} The clone array
  1588. */
  1589. clone: function(array) {
  1590. return slice.call(array);
  1591. },
  1592. /**
  1593. * Merge multiple arrays into one with unique items.
  1594. *
  1595. * {@link Ext.Array#union} is alias for {@link Ext.Array#merge}
  1596. *
  1597. * @param {Array} array1
  1598. * @param {Array} array2
  1599. * @param {Array} etc
  1600. * @return {Array} merged
  1601. */
  1602. merge: function() {
  1603. var args = slice.call(arguments),
  1604. array = [],
  1605. i, ln;
  1606. for (i = 0, ln = args.length; i < ln; i++) {
  1607. array = array.concat(args[i]);
  1608. }
  1609. return ExtArray.unique(array);
  1610. },
  1611. /**
  1612. * Merge multiple arrays into one with unique items that exist in all of the arrays.
  1613. *
  1614. * @param {Array} array1
  1615. * @param {Array} array2
  1616. * @param {Array} etc
  1617. * @return {Array} intersect
  1618. */
  1619. intersect: function() {
  1620. var intersect = [],
  1621. arrays = slice.call(arguments),
  1622. i, j, k, minArray, array, x, y, ln, arraysLn, arrayLn;
  1623. if (!arrays.length) {
  1624. return intersect;
  1625. }
  1626. // Find the smallest array
  1627. for (i = x = 0,ln = arrays.length; i < ln,array = arrays[i]; i++) {
  1628. if (!minArray || array.length < minArray.length) {
  1629. minArray = array;
  1630. x = i;
  1631. }
  1632. }
  1633. minArray = ExtArray.unique(minArray);
  1634. erase(arrays, x, 1);
  1635. // Use the smallest unique'd array as the anchor loop. If the other array(s) do contain
  1636. // an item in the small array, we're likely to find it before reaching the end
  1637. // of the inner loop and can terminate the search early.
  1638. for (i = 0,ln = minArray.length; i < ln,x = minArray[i]; i++) {
  1639. var count = 0;
  1640. for (j = 0,arraysLn = arrays.length; j < arraysLn,array = arrays[j]; j++) {
  1641. for (k = 0,arrayLn = array.length; k < arrayLn,y = array[k]; k++) {
  1642. if (x === y) {
  1643. count++;
  1644. break;
  1645. }
  1646. }
  1647. }
  1648. if (count === arraysLn) {
  1649. intersect.push(x);
  1650. }
  1651. }
  1652. return intersect;
  1653. },
  1654. /**
  1655. * Perform a set difference A-B by subtracting all items in array B from array A.
  1656. *
  1657. * @param {Array} arrayA
  1658. * @param {Array} arrayB
  1659. * @return {Array} difference
  1660. */
  1661. difference: function(arrayA, arrayB) {
  1662. var clone = slice.call(arrayA),
  1663. ln = clone.length,
  1664. i, j, lnB;
  1665. for (i = 0,lnB = arrayB.length; i < lnB; i++) {
  1666. for (j = 0; j < ln; j++) {
  1667. if (clone[j] === arrayB[i]) {
  1668. erase(clone, j, 1);
  1669. j--;
  1670. ln--;
  1671. }
  1672. }
  1673. }
  1674. return clone;
  1675. },
  1676. /**
  1677. * Returns a shallow copy of a part of an array. This is equivalent to the native
  1678. * call "Array.prototype.slice.call(array, begin, end)". This is often used when "array"
  1679. * is "arguments" since the arguments object does not supply a slice method but can
  1680. * be the context object to Array.prototype.slice.
  1681. *
  1682. * @param {Array} array The array (or arguments object).
  1683. * @param {Number} begin The index at which to begin. Negative values are offsets from
  1684. * the end of the array.
  1685. * @param {Number} end The index at which to end. The copied items do not include
  1686. * end. Negative values are offsets from the end of the array. If end is omitted,
  1687. * all items up to the end of the array are copied.
  1688. * @return {Array} The copied piece of the array.
  1689. */
  1690. // Note: IE6 will return [] on slice.call(x, undefined).
  1691. slice: ([1,2].slice(1, undefined).length ?
  1692. function (array, begin, end) {
  1693. return slice.call(array, begin, end);
  1694. } :
  1695. // at least IE6 uses arguments.length for variadic signature
  1696. function (array, begin, end) {
  1697. // After tested for IE 6, the one below is of the best performance
  1698. // see http://jsperf.com/slice-fix
  1699. if (typeof begin === 'undefined') {
  1700. return slice.call(array);
  1701. }
  1702. if (typeof end === 'undefined') {
  1703. return slice.call(array, begin);
  1704. }
  1705. return slice.call(array, begin, end);
  1706. }
  1707. ),
  1708. /**
  1709. * Sorts the elements of an Array.
  1710. * By default, this method sorts the elements alphabetically and ascending.
  1711. *
  1712. * @param {Array} array The array to sort.
  1713. * @param {Function} sortFn (optional) The comparison function.
  1714. * @return {Array} The sorted array.
  1715. */
  1716. sort: function(array, sortFn) {
  1717. if (supportsSort) {
  1718. if (sortFn) {
  1719. return array.sort(sortFn);
  1720. } else {
  1721. return array.sort();
  1722. }
  1723. }
  1724. var length = array.length,
  1725. i = 0,
  1726. comparison,
  1727. j, min, tmp;
  1728. for (; i < length; i++) {
  1729. min = i;
  1730. for (j = i + 1; j < length; j++) {
  1731. if (sortFn) {
  1732. comparison = sortFn(array[j], array[min]);
  1733. if (comparison < 0) {
  1734. min = j;
  1735. }
  1736. } else if (array[j] < array[min]) {
  1737. min = j;
  1738. }
  1739. }
  1740. if (min !== i) {
  1741. tmp = array[i];
  1742. array[i] = array[min];
  1743. array[min] = tmp;
  1744. }
  1745. }
  1746. return array;
  1747. },
  1748. /**
  1749. * Recursively flattens into 1-d Array. Injects Arrays inline.
  1750. *
  1751. * @param {Array} array The array to flatten
  1752. * @return {Array} The 1-d array.
  1753. */
  1754. flatten: function(array) {
  1755. var worker = [];
  1756. function rFlatten(a) {
  1757. var i, ln, v;
  1758. for (i = 0, ln = a.length; i < ln; i++) {
  1759. v = a[i];
  1760. if (Ext.isArray(v)) {
  1761. rFlatten(v);
  1762. } else {
  1763. worker.push(v);
  1764. }
  1765. }
  1766. return worker;
  1767. }
  1768. return rFlatten(array);
  1769. },
  1770. /**
  1771. * Returns the minimum value in the Array.
  1772. *
  1773. * @param {Array/NodeList} array The Array from which to select the minimum value.
  1774. * @param {Function} comparisonFn (optional) a function to perform the comparision which determines minimization.
  1775. * If omitted the "<" operator will be used. Note: gt = 1; eq = 0; lt = -1
  1776. * @return {Object} minValue The minimum value
  1777. */
  1778. min: function(array, comparisonFn) {
  1779. var min = array[0],
  1780. i, ln, item;
  1781. for (i = 0, ln = array.length; i < ln; i++) {
  1782. item = array[i];
  1783. if (comparisonFn) {
  1784. if (comparisonFn(min, item) === 1) {
  1785. min = item;
  1786. }
  1787. }
  1788. else {
  1789. if (item < min) {
  1790. min = item;
  1791. }
  1792. }
  1793. }
  1794. return min;
  1795. },
  1796. /**
  1797. * Returns the maximum value in the Array.
  1798. *
  1799. * @param {Array/NodeList} array The Array from which to select the maximum value.
  1800. * @param {Function} comparisonFn (optional) a function to perform the comparision which determines maximization.
  1801. * If omitted the ">" operator will be used. Note: gt = 1; eq = 0; lt = -1
  1802. * @return {Object} maxValue The maximum value
  1803. */
  1804. max: function(array, comparisonFn) {
  1805. var max = array[0],
  1806. i, ln, item;
  1807. for (i = 0, ln = array.length; i < ln; i++) {
  1808. item = array[i];
  1809. if (comparisonFn) {
  1810. if (comparisonFn(max, item) === -1) {
  1811. max = item;
  1812. }
  1813. }
  1814. else {
  1815. if (item > max) {
  1816. max = item;
  1817. }
  1818. }
  1819. }
  1820. return max;
  1821. },
  1822. /**
  1823. * Calculates the mean of all items in the array.
  1824. *
  1825. * @param {Array} array The Array to calculate the mean value of.
  1826. * @return {Number} The mean.
  1827. */
  1828. mean: function(array) {
  1829. return array.length > 0 ? ExtArray.sum(array) / array.length : undefined;
  1830. },
  1831. /**
  1832. * Calculates the sum of all items in the given array.
  1833. *
  1834. * @param {Array} array The Array to calculate the sum value of.
  1835. * @return {Number} The sum.
  1836. */
  1837. sum: function(array) {
  1838. var sum = 0,
  1839. i, ln, item;
  1840. for (i = 0,ln = array.length; i < ln; i++) {
  1841. item = array[i];
  1842. sum += item;
  1843. }
  1844. return sum;
  1845. },
  1846. /**
  1847. * Removes items from an array. This is functionally equivalent to the splice method
  1848. * of Array, but works around bugs in IE8's splice method and does not copy the
  1849. * removed elements in order to return them (because very often they are ignored).
  1850. *
  1851. * @param {Array} array The Array on which to replace.
  1852. * @param {Number} index The index in the array at which to operate.
  1853. * @param {Number} removeCount The number of items to remove at index.
  1854. * @return {Array} The array passed.
  1855. * @method
  1856. */
  1857. erase: erase,
  1858. /**
  1859. * Inserts items in to an array.
  1860. *
  1861. * @param {Array} array The Array on which to replace.
  1862. * @param {Number} index The index in the array at which to operate.
  1863. * @param {Array} items The array of items to insert at index.
  1864. * @return {Array} The array passed.
  1865. */
  1866. insert: function (array, index, items) {
  1867. return replace(array, index, 0, items);
  1868. },
  1869. /**
  1870. * Replaces items in an array. This is functionally equivalent to the splice method
  1871. * of Array, but works around bugs in IE8's splice method and is often more convenient
  1872. * to call because it accepts an array of items to insert rather than use a variadic
  1873. * argument list.
  1874. *
  1875. * @param {Array} array The Array on which to replace.
  1876. * @param {Number} index The index in the array at which to operate.
  1877. * @param {Number} removeCount The number of items to remove at index (can be 0).
  1878. * @param {Array} insert (optional) An array of items to insert at index.
  1879. * @return {Array} The array passed.
  1880. * @method
  1881. */
  1882. replace: replace,
  1883. /**
  1884. * Replaces items in an array. This is equivalent to the splice method of Array, but
  1885. * works around bugs in IE8's splice method. The signature is exactly the same as the
  1886. * splice method except that the array is the first argument. All arguments following
  1887. * removeCount are inserted in the array at index.
  1888. *
  1889. * @param {Array} array The Array on which to replace.
  1890. * @param {Number} index The index in the array at which to operate.
  1891. * @param {Number} removeCount The number of items to remove at index (can be 0).
  1892. * @return {Array} An array containing the removed items.
  1893. * @method
  1894. */
  1895. splice: splice
  1896. };
  1897. /**
  1898. * @method
  1899. * @member Ext
  1900. * @alias Ext.Array#each
  1901. */
  1902. Ext.each = ExtArray.each;
  1903. /**
  1904. * @method
  1905. * @member Ext.Array
  1906. * @alias Ext.Array#merge
  1907. */
  1908. ExtArray.union = ExtArray.merge;
  1909. /**
  1910. * Old alias to {@link Ext.Array#min}
  1911. * @deprecated 4.0.0 Use {@link Ext.Array#min} instead
  1912. * @method
  1913. * @member Ext
  1914. * @alias Ext.Array#min
  1915. */
  1916. Ext.min = ExtArray.min;
  1917. /**
  1918. * Old alias to {@link Ext.Array#max}
  1919. * @deprecated 4.0.0 Use {@link Ext.Array#max} instead
  1920. * @method
  1921. * @member Ext
  1922. * @alias Ext.Array#max
  1923. */
  1924. Ext.max = ExtArray.max;
  1925. /**
  1926. * Old alias to {@link Ext.Array#sum}
  1927. * @deprecated 4.0.0 Use {@link Ext.Array#sum} instead
  1928. * @method
  1929. * @member Ext
  1930. * @alias Ext.Array#sum
  1931. */
  1932. Ext.sum = ExtArray.sum;
  1933. /**
  1934. * Old alias to {@link Ext.Array#mean}
  1935. * @deprecated 4.0.0 Use {@link Ext.Array#mean} instead
  1936. * @method
  1937. * @member Ext
  1938. * @alias Ext.Array#mean
  1939. */
  1940. Ext.mean = ExtArray.mean;
  1941. /**
  1942. * Old alias to {@link Ext.Array#flatten}
  1943. * @deprecated 4.0.0 Use {@link Ext.Array#flatten} instead
  1944. * @method
  1945. * @member Ext
  1946. * @alias Ext.Array#flatten
  1947. */
  1948. Ext.flatten = ExtArray.flatten;
  1949. /**
  1950. * Old alias to {@link Ext.Array#clean}
  1951. * @deprecated 4.0.0 Use {@link Ext.Array#clean} instead
  1952. * @method
  1953. * @member Ext
  1954. * @alias Ext.Array#clean
  1955. */
  1956. Ext.clean = ExtArray.clean;
  1957. /**
  1958. * Old alias to {@link Ext.Array#unique}
  1959. * @deprecated 4.0.0 Use {@link Ext.Array#unique} instead
  1960. * @method
  1961. * @member Ext
  1962. * @alias Ext.Array#unique
  1963. */
  1964. Ext.unique = ExtArray.unique;
  1965. /**
  1966. * Old alias to {@link Ext.Array#pluck Ext.Array.pluck}
  1967. * @deprecated 4.0.0 Use {@link Ext.Array#pluck Ext.Array.pluck} instead
  1968. * @method
  1969. * @member Ext
  1970. * @alias Ext.Array#pluck
  1971. */
  1972. Ext.pluck = ExtArray.pluck;
  1973. /**
  1974. * @method
  1975. * @member Ext
  1976. * @alias Ext.Array#toArray
  1977. */
  1978. Ext.toArray = function() {
  1979. return ExtArray.toArray.apply(ExtArray, arguments);
  1980. };
  1981. })();
  1982. /**
  1983. * @class Ext.Function
  1984. *
  1985. * A collection of useful static methods to deal with function callbacks
  1986. * @singleton
  1987. */
  1988. Ext.Function = {
  1989. /**
  1990. * A very commonly used method throughout the framework. It acts as a wrapper around another method
  1991. * which originally accepts 2 arguments for `name` and `value`.
  1992. * The wrapped function then allows "flexible" value setting of either:
  1993. *
  1994. * - `name` and `value` as 2 arguments
  1995. * - one single object argument with multiple key - value pairs
  1996. *
  1997. * For example:
  1998. *
  1999. * var setValue = Ext.Function.flexSetter(function(name, value) {
  2000. * this[name] = value;
  2001. * });
  2002. *
  2003. * // Afterwards
  2004. * // Setting a single name - value
  2005. * setValue('name1', 'value1');
  2006. *
  2007. * // Settings multiple name - value pairs
  2008. * setValue({
  2009. * name1: 'value1',
  2010. * name2: 'value2',
  2011. * name3: 'value3'
  2012. * });
  2013. *
  2014. * @param {Function} setter
  2015. * @returns {Function} flexSetter
  2016. */
  2017. flexSetter: function(fn) {
  2018. return function(a, b) {
  2019. var k, i;
  2020. if (a === null) {
  2021. return this;
  2022. }
  2023. if (typeof a !== 'string') {
  2024. for (k in a) {
  2025. if (a.hasOwnProperty(k)) {
  2026. fn.call(this, k, a[k]);
  2027. }
  2028. }
  2029. if (Ext.enumerables) {
  2030. for (i = Ext.enumerables.length; i--;) {
  2031. k = Ext.enumerables[i];
  2032. if (a.hasOwnProperty(k)) {
  2033. fn.call(this, k, a[k]);
  2034. }
  2035. }
  2036. }
  2037. } else {
  2038. fn.call(this, a, b);
  2039. }
  2040. return this;
  2041. };
  2042. },
  2043. /**
  2044. * Create a new function from the provided `fn`, change `this` to the provided scope, optionally
  2045. * overrides arguments for the call. (Defaults to the arguments passed by the caller)
  2046. *
  2047. * {@link Ext#bind Ext.bind} is alias for {@link Ext.Function#bind Ext.Function.bind}
  2048. *
  2049. * @param {Function} fn The function to delegate.
  2050. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
  2051. * **If omitted, defaults to the browser window.**
  2052. * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
  2053. * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
  2054. * if a number the args are inserted at the specified position
  2055. * @return {Function} The new function
  2056. */
  2057. bind: function(fn, scope, args, appendArgs) {
  2058. if (arguments.length === 2) {
  2059. return function() {
  2060. return fn.apply(scope, arguments);
  2061. }
  2062. }
  2063. var method = fn,
  2064. slice = Array.prototype.slice;
  2065. return function() {
  2066. var callArgs = args || arguments;
  2067. if (appendArgs === true) {
  2068. callArgs = slice.call(arguments, 0);
  2069. callArgs = callArgs.concat(args);
  2070. }
  2071. else if (typeof appendArgs == 'number') {
  2072. callArgs = slice.call(arguments, 0); // copy arguments first
  2073. Ext.Array.insert(callArgs, appendArgs, args);
  2074. }
  2075. return method.apply(scope || window, callArgs);
  2076. };
  2077. },
  2078. /**
  2079. * Create a new function from the provided `fn`, the arguments of which are pre-set to `args`.
  2080. * New arguments passed to the newly created callback when it's invoked are appended after the pre-set ones.
  2081. * This is especially useful when creating callbacks.
  2082. *
  2083. * For example:
  2084. *
  2085. * var originalFunction = function(){
  2086. * alert(Ext.Array.from(arguments).join(' '));
  2087. * };
  2088. *
  2089. * var callback = Ext.Function.pass(originalFunction, ['Hello', 'World']);
  2090. *
  2091. * callback(); // alerts 'Hello World'
  2092. * callback('by Me'); // alerts 'Hello World by Me'
  2093. *
  2094. * {@link Ext#pass Ext.pass} is alias for {@link Ext.Function#pass Ext.Function.pass}
  2095. *
  2096. * @param {Function} fn The original function
  2097. * @param {Array} args The arguments to pass to new callback
  2098. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
  2099. * @return {Function} The new callback function
  2100. */
  2101. pass: function(fn, args, scope) {
  2102. if (args) {
  2103. args = Ext.Array.from(args);
  2104. }
  2105. return function() {
  2106. return fn.apply(scope, args.concat(Ext.Array.toArray(arguments)));
  2107. };
  2108. },
  2109. /**
  2110. * Create an alias to the provided method property with name `methodName` of `object`.
  2111. * Note that the execution scope will still be bound to the provided `object` itself.
  2112. *
  2113. * @param {Object/Function} object
  2114. * @param {String} methodName
  2115. * @return {Function} aliasFn
  2116. */
  2117. alias: function(object, methodName) {
  2118. return function() {
  2119. return object[methodName].apply(object, arguments);
  2120. };
  2121. },
  2122. /**
  2123. * Creates an interceptor function. The passed function is called before the original one. If it returns false,
  2124. * the original one is not called. The resulting function returns the results of the original function.
  2125. * The passed function is called with the parameters of the original function. Example usage:
  2126. *
  2127. * var sayHi = function(name){
  2128. * alert('Hi, ' + name);
  2129. * }
  2130. *
  2131. * sayHi('Fred'); // alerts "Hi, Fred"
  2132. *
  2133. * // create a new function that validates input without
  2134. * // directly modifying the original function:
  2135. * var sayHiToFriend = Ext.Function.createInterceptor(sayHi, function(name){
  2136. * return name == 'Brian';
  2137. * });
  2138. *
  2139. * sayHiToFriend('Fred'); // no alert
  2140. * sayHiToFriend('Brian'); // alerts "Hi, Brian"
  2141. *
  2142. * @param {Function} origFn The original function.
  2143. * @param {Function} newFn The function to call before the original
  2144. * @param {Object} scope (optional) The scope (`this` reference) in which the passed function is executed.
  2145. * **If omitted, defaults to the scope in which the original function is called or the browser window.**
  2146. * @param {Object} returnValue (optional) The value to return if the passed function return false (defaults to null).
  2147. * @return {Function} The new function
  2148. */
  2149. createInterceptor: function(origFn, newFn, scope, returnValue) {
  2150. var method = origFn;
  2151. if (!Ext.isFunction(newFn)) {
  2152. return origFn;
  2153. }
  2154. else {
  2155. return function() {
  2156. var me = this,
  2157. args = arguments;
  2158. newFn.target = me;
  2159. newFn.method = origFn;
  2160. return (newFn.apply(scope || me || window, args) !== false) ? origFn.apply(me || window, args) : returnValue || null;
  2161. };
  2162. }
  2163. },
  2164. /**
  2165. * Creates a delegate (callback) which, when called, executes after a specific delay.
  2166. *
  2167. * @param {Function} fn The function which will be called on a delay when the returned function is called.
  2168. * Optionally, a replacement (or additional) argument list may be specified.
  2169. * @param {Number} delay The number of milliseconds to defer execution by whenever called.
  2170. * @param {Object} scope (optional) The scope (`this` reference) used by the function at execution time.
  2171. * @param {Array} args (optional) Override arguments for the call. (Defaults to the arguments passed by the caller)
  2172. * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
  2173. * if a number the args are inserted at the specified position.
  2174. * @return {Function} A function which, when called, executes the original function after the specified delay.
  2175. */
  2176. createDelayed: function(fn, delay, scope, args, appendArgs) {
  2177. if (scope || args) {
  2178. fn = Ext.Function.bind(fn, scope, args, appendArgs);
  2179. }
  2180. return function() {
  2181. var me = this;
  2182. setTimeout(function() {
  2183. fn.apply(me, arguments);
  2184. }, delay);
  2185. };
  2186. },
  2187. /**
  2188. * Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage:
  2189. *
  2190. * var sayHi = function(name){
  2191. * alert('Hi, ' + name);
  2192. * }
  2193. *
  2194. * // executes immediately:
  2195. * sayHi('Fred');
  2196. *
  2197. * // executes after 2 seconds:
  2198. * Ext.Function.defer(sayHi, 2000, this, ['Fred']);
  2199. *
  2200. * // this syntax is sometimes useful for deferring
  2201. * // execution of an anonymous function:
  2202. * Ext.Function.defer(function(){
  2203. * alert('Anonymous');
  2204. * }, 100);
  2205. *
  2206. * {@link Ext#defer Ext.defer} is alias for {@link Ext.Function#defer Ext.Function.defer}
  2207. *
  2208. * @param {Function} fn The function to defer.
  2209. * @param {Number} millis The number of milliseconds for the setTimeout call
  2210. * (if less than or equal to 0 the function is executed immediately)
  2211. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
  2212. * **If omitted, defaults to the browser window.**
  2213. * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
  2214. * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
  2215. * if a number the args are inserted at the specified position
  2216. * @return {Number} The timeout id that can be used with clearTimeout
  2217. */
  2218. defer: function(fn, millis, obj, args, appendArgs) {
  2219. fn = Ext.Function.bind(fn, obj, args, appendArgs);
  2220. if (millis > 0) {
  2221. return setTimeout(fn, millis);
  2222. }
  2223. fn();
  2224. return 0;
  2225. },
  2226. /**
  2227. * Create a combined function call sequence of the original function + the passed function.
  2228. * The resulting function returns the results of the original function.
  2229. * The passed function is called with the parameters of the original function. Example usage:
  2230. *
  2231. * var sayHi = function(name){
  2232. * alert('Hi, ' + name);
  2233. * }
  2234. *
  2235. * sayHi('Fred'); // alerts "Hi, Fred"
  2236. *
  2237. * var sayGoodbye = Ext.Function.createSequence(sayHi, function(name){
  2238. * alert('Bye, ' + name);
  2239. * });
  2240. *
  2241. * sayGoodbye('Fred'); // both alerts show
  2242. *
  2243. * @param {Function} origFn The original function.
  2244. * @param {Function} newFn The function to sequence
  2245. * @param {Object} scope (optional) The scope (`this` reference) in which the passed function is executed.
  2246. * If omitted, defaults to the scope in which the original function is called or the browser window.
  2247. * @return {Function} The new function
  2248. */
  2249. createSequence: function(origFn, newFn, scope) {
  2250. if (!Ext.isFunction(newFn)) {
  2251. return origFn;
  2252. }
  2253. else {
  2254. return function() {
  2255. var retval = origFn.apply(this || window, arguments);
  2256. newFn.apply(scope || this || window, arguments);
  2257. return retval;
  2258. };
  2259. }
  2260. },
  2261. /**
  2262. * Creates a delegate function, optionally with a bound scope which, when called, buffers
  2263. * the execution of the passed function for the configured number of milliseconds.
  2264. * If called again within that period, the impending invocation will be canceled, and the
  2265. * timeout period will begin again.
  2266. *
  2267. * @param {Function} fn The function to invoke on a buffered timer.
  2268. * @param {Number} buffer The number of milliseconds by which to buffer the invocation of the
  2269. * function.
  2270. * @param {Object} scope (optional) The scope (`this` reference) in which
  2271. * the passed function is executed. If omitted, defaults to the scope specified by the caller.
  2272. * @param {Array} args (optional) Override arguments for the call. Defaults to the arguments
  2273. * passed by the caller.
  2274. * @return {Function} A function which invokes the passed function after buffering for the specified time.
  2275. */
  2276. createBuffered: function(fn, buffer, scope, args) {
  2277. return function(){
  2278. var timerId;
  2279. return function() {
  2280. var me = this;
  2281. if (timerId) {
  2282. clearTimeout(timerId);
  2283. timerId = null;
  2284. }
  2285. timerId = setTimeout(function(){
  2286. fn.apply(scope || me, args || arguments);
  2287. }, buffer);
  2288. };
  2289. }();
  2290. },
  2291. /**
  2292. * Creates a throttled version of the passed function which, when called repeatedly and
  2293. * rapidly, invokes the passed function only after a certain interval has elapsed since the
  2294. * previous invocation.
  2295. *
  2296. * This is useful for wrapping functions which may be called repeatedly, such as
  2297. * a handler of a mouse move event when the processing is expensive.
  2298. *
  2299. * @param {Function} fn The function to execute at a regular time interval.
  2300. * @param {Number} interval The interval **in milliseconds** on which the passed function is executed.
  2301. * @param {Object} scope (optional) The scope (`this` reference) in which
  2302. * the passed function is executed. If omitted, defaults to the scope specified by the caller.
  2303. * @returns {Function} A function which invokes the passed function at the specified interval.
  2304. */
  2305. createThrottled: function(fn, interval, scope) {
  2306. var lastCallTime, elapsed, lastArgs, timer, execute = function() {
  2307. fn.apply(scope || this, lastArgs);
  2308. lastCallTime = new Date().getTime();
  2309. };
  2310. return function() {
  2311. elapsed = new Date().getTime() - lastCallTime;
  2312. lastArgs = arguments;
  2313. clearTimeout(timer);
  2314. if (!lastCallTime || (elapsed >= interval)) {
  2315. execute();
  2316. } else {
  2317. timer = setTimeout(execute, interval - elapsed);
  2318. }
  2319. };
  2320. },
  2321. /**
  2322. * Adds behavior to an existing method that is executed before the
  2323. * original behavior of the function. For example:
  2324. *
  2325. * var soup = {
  2326. * contents: [],
  2327. * add: function(ingredient) {
  2328. * this.contents.push(ingredient);
  2329. * }
  2330. * };
  2331. * Ext.Function.interceptBefore(soup, "add", function(ingredient){
  2332. * if (!this.contents.length && ingredient !== "water") {
  2333. * // Always add water to start with
  2334. * this.contents.push("water");
  2335. * }
  2336. * });
  2337. * soup.add("onions");
  2338. * soup.add("salt");
  2339. * soup.contents; // will contain: water, onions, salt
  2340. *
  2341. * @param {Object} object The target object
  2342. * @param {String} methodName Name of the method to override
  2343. * @param {Function} fn Function with the new behavior. It will
  2344. * be called with the same arguments as the original method. The
  2345. * return value of this function will be the return value of the
  2346. * new method.
  2347. * @return {Function} The new function just created.
  2348. */
  2349. interceptBefore: function(object, methodName, fn) {
  2350. var method = object[methodName] || Ext.emptyFn;
  2351. return object[methodName] = function() {
  2352. var ret = fn.apply(this, arguments);
  2353. method.apply(this, arguments);
  2354. return ret;
  2355. };
  2356. },
  2357. /**
  2358. * Adds behavior to an existing method that is executed after the
  2359. * original behavior of the function. For example:
  2360. *
  2361. * var soup = {
  2362. * contents: [],
  2363. * add: function(ingredient) {
  2364. * this.contents.push(ingredient);
  2365. * }
  2366. * };
  2367. * Ext.Function.interceptAfter(soup, "add", function(ingredient){
  2368. * // Always add a bit of extra salt
  2369. * this.contents.push("salt");
  2370. * });
  2371. * soup.add("water");
  2372. * soup.add("onions");
  2373. * soup.contents; // will contain: water, salt, onions, salt
  2374. *
  2375. * @param {Object} object The target object
  2376. * @param {String} methodName Name of the method to override
  2377. * @param {Function} fn Function with the new behavior. It will
  2378. * be called with the same arguments as the original method. The
  2379. * return value of this function will be the return value of the
  2380. * new method.
  2381. * @return {Function} The new function just created.
  2382. */
  2383. interceptAfter: function(object, methodName, fn) {
  2384. var method = object[methodName] || Ext.emptyFn;
  2385. return object[methodName] = function() {
  2386. method.apply(this, arguments);
  2387. return fn.apply(this, arguments);
  2388. };
  2389. }
  2390. };
  2391. /**
  2392. * @method
  2393. * @member Ext
  2394. * @alias Ext.Function#defer
  2395. */
  2396. Ext.defer = Ext.Function.alias(Ext.Function, 'defer');
  2397. /**
  2398. * @method
  2399. * @member Ext
  2400. * @alias Ext.Function#pass
  2401. */
  2402. Ext.pass = Ext.Function.alias(Ext.Function, 'pass');
  2403. /**
  2404. * @method
  2405. * @member Ext
  2406. * @alias Ext.Function#bind
  2407. */
  2408. Ext.bind = Ext.Function.alias(Ext.Function, 'bind');
  2409. /**
  2410. * @author Jacky Nguyen <jacky@sencha.com>
  2411. * @docauthor Jacky Nguyen <jacky@sencha.com>
  2412. * @class Ext.Object
  2413. *
  2414. * A collection of useful static methods to deal with objects.
  2415. *
  2416. * @singleton
  2417. */
  2418. (function() {
  2419. var ExtObject = Ext.Object = {
  2420. /**
  2421. * Converts a `name` - `value` pair to an array of objects with support for nested structures. Useful to construct
  2422. * query strings. For example:
  2423. *
  2424. * var objects = Ext.Object.toQueryObjects('hobbies', ['reading', 'cooking', 'swimming']);
  2425. *
  2426. * // objects then equals:
  2427. * [
  2428. * { name: 'hobbies', value: 'reading' },
  2429. * { name: 'hobbies', value: 'cooking' },
  2430. * { name: 'hobbies', value: 'swimming' },
  2431. * ];
  2432. *
  2433. * var objects = Ext.Object.toQueryObjects('dateOfBirth', {
  2434. * day: 3,
  2435. * month: 8,
  2436. * year: 1987,
  2437. * extra: {
  2438. * hour: 4
  2439. * minute: 30
  2440. * }
  2441. * }, true); // Recursive
  2442. *
  2443. * // objects then equals:
  2444. * [
  2445. * { name: 'dateOfBirth[day]', value: 3 },
  2446. * { name: 'dateOfBirth[month]', value: 8 },
  2447. * { name: 'dateOfBirth[year]', value: 1987 },
  2448. * { name: 'dateOfBirth[extra][hour]', value: 4 },
  2449. * { name: 'dateOfBirth[extra][minute]', value: 30 },
  2450. * ];
  2451. *
  2452. * @param {String} name
  2453. * @param {Object/Array} value
  2454. * @param {Boolean} [recursive=false] True to traverse object recursively
  2455. * @return {Array}
  2456. */
  2457. toQueryObjects: function(name, value, recursive) {
  2458. var self = ExtObject.toQueryObjects,
  2459. objects = [],
  2460. i, ln;
  2461. if (Ext.isArray(value)) {
  2462. for (i = 0, ln = value.length; i < ln; i++) {
  2463. if (recursive) {
  2464. objects = objects.concat(self(name + '[' + i + ']', value[i], true));
  2465. }
  2466. else {
  2467. objects.push({
  2468. name: name,
  2469. value: value[i]
  2470. });
  2471. }
  2472. }
  2473. }
  2474. else if (Ext.isObject(value)) {
  2475. for (i in value) {
  2476. if (value.hasOwnProperty(i)) {
  2477. if (recursive) {
  2478. objects = objects.concat(self(name + '[' + i + ']', value[i], true));
  2479. }
  2480. else {
  2481. objects.push({
  2482. name: name,
  2483. value: value[i]
  2484. });
  2485. }
  2486. }
  2487. }
  2488. }
  2489. else {
  2490. objects.push({
  2491. name: name,
  2492. value: value
  2493. });
  2494. }
  2495. return objects;
  2496. },
  2497. /**
  2498. * Takes an object and converts it to an encoded query string.
  2499. *
  2500. * Non-recursive:
  2501. *
  2502. * Ext.Object.toQueryString({foo: 1, bar: 2}); // returns "foo=1&bar=2"
  2503. * Ext.Object.toQueryString({foo: null, bar: 2}); // returns "foo=&bar=2"
  2504. * Ext.Object.toQueryString({'some price': '$300'}); // returns "some%20price=%24300"
  2505. * Ext.Object.toQueryString({date: new Date(2011, 0, 1)}); // returns "date=%222011-01-01T00%3A00%3A00%22"
  2506. * Ext.Object.toQueryString({colors: ['red', 'green', 'blue']}); // returns "colors=red&colors=green&colors=blue"
  2507. *
  2508. * Recursive:
  2509. *
  2510. * Ext.Object.toQueryString({
  2511. * username: 'Jacky',
  2512. * dateOfBirth: {
  2513. * day: 1,
  2514. * month: 2,
  2515. * year: 1911
  2516. * },
  2517. * hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']]
  2518. * }, true); // returns the following string (broken down and url-decoded for ease of reading purpose):
  2519. * // username=Jacky
  2520. * // &dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911
  2521. * // &hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&hobbies[3][0]=nested&hobbies[3][1]=stuff
  2522. *
  2523. * @param {Object} object The object to encode
  2524. * @param {Boolean} [recursive=false] Whether or not to interpret the object in recursive format.
  2525. * (PHP / Ruby on Rails servers and similar).
  2526. * @return {String} queryString
  2527. */
  2528. toQueryString: function(object, recursive) {
  2529. var paramObjects = [],
  2530. params = [],
  2531. i, j, ln, paramObject, value;
  2532. for (i in object) {
  2533. if (object.hasOwnProperty(i)) {
  2534. paramObjects = paramObjects.concat(ExtObject.toQueryObjects(i, object[i], recursive));
  2535. }
  2536. }
  2537. for (j = 0, ln = paramObjects.length; j < ln; j++) {
  2538. paramObject = paramObjects[j];
  2539. value = paramObject.value;
  2540. if (Ext.isEmpty(value)) {
  2541. value = '';
  2542. }
  2543. else if (Ext.isDate(value)) {
  2544. value = Ext.Date.toString(value);
  2545. }
  2546. params.push(encodeURIComponent(paramObject.name) + '=' + encodeURIComponent(String(value)));
  2547. }
  2548. return params.join('&');
  2549. },
  2550. /**
  2551. * Converts a query string back into an object.
  2552. *
  2553. * Non-recursive:
  2554. *
  2555. * Ext.Object.fromQueryString(foo=1&bar=2); // returns {foo: 1, bar: 2}
  2556. * Ext.Object.fromQueryString(foo=&bar=2); // returns {foo: null, bar: 2}
  2557. * Ext.Object.fromQueryString(some%20price=%24300); // returns {'some price': '$300'}
  2558. * Ext.Object.fromQueryString(colors=red&colors=green&colors=blue); // returns {colors: ['red', 'green', 'blue']}
  2559. *
  2560. * Recursive:
  2561. *
  2562. * Ext.Object.fromQueryString("username=Jacky&dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911&hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&hobbies[3][0]=nested&hobbies[3][1]=stuff", true);
  2563. * // returns
  2564. * {
  2565. * username: 'Jacky',
  2566. * dateOfBirth: {
  2567. * day: '1',
  2568. * month: '2',
  2569. * year: '1911'
  2570. * },
  2571. * hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']]
  2572. * }
  2573. *
  2574. * @param {String} queryString The query string to decode
  2575. * @param {Boolean} [recursive=false] Whether or not to recursively decode the string. This format is supported by
  2576. * PHP / Ruby on Rails servers and similar.
  2577. * @return {Object}
  2578. */
  2579. fromQueryString: function(queryString, recursive) {
  2580. var parts = queryString.replace(/^\?/, '').split('&'),
  2581. object = {},
  2582. temp, components, name, value, i, ln,
  2583. part, j, subLn, matchedKeys, matchedName,
  2584. keys, key, nextKey;
  2585. for (i = 0, ln = parts.length; i < ln; i++) {
  2586. part = parts[i];
  2587. if (part.length > 0) {
  2588. components = part.split('=');
  2589. name = decodeURIComponent(components[0]);
  2590. value = (components[1] !== undefined) ? decodeURIComponent(components[1]) : '';
  2591. if (!recursive) {
  2592. if (object.hasOwnProperty(name)) {
  2593. if (!Ext.isArray(object[name])) {
  2594. object[name] = [object[name]];
  2595. }
  2596. object[name].push(value);
  2597. }
  2598. else {
  2599. object[name] = value;
  2600. }
  2601. }
  2602. else {
  2603. matchedKeys = name.match(/(\[):?([^\]]*)\]/g);
  2604. matchedName = name.match(/^([^\[]+)/);
  2605. name = matchedName[0];
  2606. keys = [];
  2607. if (matchedKeys === null) {
  2608. object[name] = value;
  2609. continue;
  2610. }
  2611. for (j = 0, subLn = matchedKeys.length; j < subLn; j++) {
  2612. key = matchedKeys[j];
  2613. key = (key.length === 2) ? '' : key.substring(1, key.length - 1);
  2614. keys.push(key);
  2615. }
  2616. keys.unshift(name);
  2617. temp = object;
  2618. for (j = 0, subLn = keys.length; j < subLn; j++) {
  2619. key = keys[j];
  2620. if (j === subLn - 1) {
  2621. if (Ext.isArray(temp) && key === '') {
  2622. temp.push(value);
  2623. }
  2624. else {
  2625. temp[key] = value;
  2626. }
  2627. }
  2628. else {
  2629. if (temp[key] === undefined || typeof temp[key] === 'string') {
  2630. nextKey = keys[j+1];
  2631. temp[key] = (Ext.isNumeric(nextKey) || nextKey === '') ? [] : {};
  2632. }
  2633. temp = temp[key];
  2634. }
  2635. }
  2636. }
  2637. }
  2638. }
  2639. return object;
  2640. },
  2641. /**
  2642. * Iterates through an object and invokes the given callback function for each iteration.
  2643. * The iteration can be stopped by returning `false` in the callback function. For example:
  2644. *
  2645. * var person = {
  2646. * name: 'Jacky'
  2647. * hairColor: 'black'
  2648. * loves: ['food', 'sleeping', 'wife']
  2649. * };
  2650. *
  2651. * Ext.Object.each(person, function(key, value, myself) {
  2652. * console.log(key + ":" + value);
  2653. *
  2654. * if (key === 'hairColor') {
  2655. * return false; // stop the iteration
  2656. * }
  2657. * });
  2658. *
  2659. * @param {Object} object The object to iterate
  2660. * @param {Function} fn The callback function.
  2661. * @param {String} fn.key
  2662. * @param {Object} fn.value
  2663. * @param {Object} fn.object The object itself
  2664. * @param {Object} [scope] The execution scope (`this`) of the callback function
  2665. */
  2666. each: function(object, fn, scope) {
  2667. for (var property in object) {
  2668. if (object.hasOwnProperty(property)) {
  2669. if (fn.call(scope || object, property, object[property], object) === false) {
  2670. return;
  2671. }
  2672. }
  2673. }
  2674. },
  2675. /**
  2676. * Merges any number of objects recursively without referencing them or their children.
  2677. *
  2678. * var extjs = {
  2679. * companyName: 'Ext JS',
  2680. * products: ['Ext JS', 'Ext GWT', 'Ext Designer'],
  2681. * isSuperCool: true
  2682. * office: {
  2683. * size: 2000,
  2684. * location: 'Palo Alto',
  2685. * isFun: true
  2686. * }
  2687. * };
  2688. *
  2689. * var newStuff = {
  2690. * companyName: 'Sencha Inc.',
  2691. * products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'],
  2692. * office: {
  2693. * size: 40000,
  2694. * location: 'Redwood City'
  2695. * }
  2696. * };
  2697. *
  2698. * var sencha = Ext.Object.merge(extjs, newStuff);
  2699. *
  2700. * // extjs and sencha then equals to
  2701. * {
  2702. * companyName: 'Sencha Inc.',
  2703. * products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'],
  2704. * isSuperCool: true
  2705. * office: {
  2706. * size: 30000,
  2707. * location: 'Redwood City'
  2708. * isFun: true
  2709. * }
  2710. * }
  2711. *
  2712. * @param {Object...} object Any number of objects to merge.
  2713. * @return {Object} merged The object that is created as a result of merging all the objects passed in.
  2714. */
  2715. merge: function(source, key, value) {
  2716. if (typeof key === 'string') {
  2717. if (value && value.constructor === Object) {
  2718. if (source[key] && source[key].constructor === Object) {
  2719. ExtObject.merge(source[key], value);
  2720. }
  2721. else {
  2722. source[key] = Ext.clone(value);
  2723. }
  2724. }
  2725. else {
  2726. source[key] = value;
  2727. }
  2728. return source;
  2729. }
  2730. var i = 1,
  2731. ln = arguments.length,
  2732. object, property;
  2733. for (; i < ln; i++) {
  2734. object = arguments[i];
  2735. for (property in object) {
  2736. if (object.hasOwnProperty(property)) {
  2737. ExtObject.merge(source, property, object[property]);
  2738. }
  2739. }
  2740. }
  2741. return source;
  2742. },
  2743. /**
  2744. * Returns the first matching key corresponding to the given value.
  2745. * If no matching value is found, null is returned.
  2746. *
  2747. * var person = {
  2748. * name: 'Jacky',
  2749. * loves: 'food'
  2750. * };
  2751. *
  2752. * alert(Ext.Object.getKey(person, 'food')); // alerts 'loves'
  2753. *
  2754. * @param {Object} object
  2755. * @param {Object} value The value to find
  2756. */
  2757. getKey: function(object, value) {
  2758. for (var property in object) {
  2759. if (object.hasOwnProperty(property) && object[property] === value) {
  2760. return property;
  2761. }
  2762. }
  2763. return null;
  2764. },
  2765. /**
  2766. * Gets all values of the given object as an array.
  2767. *
  2768. * var values = Ext.Object.getValues({
  2769. * name: 'Jacky',
  2770. * loves: 'food'
  2771. * }); // ['Jacky', 'food']
  2772. *
  2773. * @param {Object} object
  2774. * @return {Array} An array of values from the object
  2775. */
  2776. getValues: function(object) {
  2777. var values = [],
  2778. property;
  2779. for (property in object) {
  2780. if (object.hasOwnProperty(property)) {
  2781. values.push(object[property]);
  2782. }
  2783. }
  2784. return values;
  2785. },
  2786. /**
  2787. * Gets all keys of the given object as an array.
  2788. *
  2789. * var values = Ext.Object.getKeys({
  2790. * name: 'Jacky',
  2791. * loves: 'food'
  2792. * }); // ['name', 'loves']
  2793. *
  2794. * @param {Object} object
  2795. * @return {String[]} An array of keys from the object
  2796. * @method
  2797. */
  2798. getKeys: ('keys' in Object.prototype) ? Object.keys : function(object) {
  2799. var keys = [],
  2800. property;
  2801. for (property in object) {
  2802. if (object.hasOwnProperty(property)) {
  2803. keys.push(property);
  2804. }
  2805. }
  2806. return keys;
  2807. },
  2808. /**
  2809. * Gets the total number of this object's own properties
  2810. *
  2811. * var size = Ext.Object.getSize({
  2812. * name: 'Jacky',
  2813. * loves: 'food'
  2814. * }); // size equals 2
  2815. *
  2816. * @param {Object} object
  2817. * @return {Number} size
  2818. */
  2819. getSize: function(object) {
  2820. var size = 0,
  2821. property;
  2822. for (property in object) {
  2823. if (object.hasOwnProperty(property)) {
  2824. size++;
  2825. }
  2826. }
  2827. return size;
  2828. }
  2829. };
  2830. /**
  2831. * A convenient alias method for {@link Ext.Object#merge}.
  2832. *
  2833. * @member Ext
  2834. * @method merge
  2835. * @alias Ext.Object#merge
  2836. */
  2837. Ext.merge = Ext.Object.merge;
  2838. /**
  2839. * Alias for {@link Ext.Object#toQueryString}.
  2840. *
  2841. * @member Ext
  2842. * @method urlEncode
  2843. * @alias Ext.Object#toQueryString
  2844. * @deprecated 4.0.0 Use {@link Ext.Object#toQueryString} instead
  2845. */
  2846. Ext.urlEncode = function() {
  2847. var args = Ext.Array.from(arguments),
  2848. prefix = '';
  2849. // Support for the old `pre` argument
  2850. if ((typeof args[1] === 'string')) {
  2851. prefix = args[1] + '&';
  2852. args[1] = false;
  2853. }
  2854. return prefix + Ext.Object.toQueryString.apply(Ext.Object, args);
  2855. };
  2856. /**
  2857. * Alias for {@link Ext.Object#fromQueryString}.
  2858. *
  2859. * @member Ext
  2860. * @method urlDecode
  2861. * @alias Ext.Object#fromQueryString
  2862. * @deprecated 4.0.0 Use {@link Ext.Object#fromQueryString} instead
  2863. */
  2864. Ext.urlDecode = function() {
  2865. return Ext.Object.fromQueryString.apply(Ext.Object, arguments);
  2866. };
  2867. })();
  2868. /**
  2869. * @class Ext.Date
  2870. * A set of useful static methods to deal with date
  2871. * Note that if Ext.Date is required and loaded, it will copy all methods / properties to
  2872. * this object for convenience
  2873. *
  2874. * The date parsing and formatting syntax contains a subset of
  2875. * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
  2876. * supported will provide results equivalent to their PHP versions.
  2877. *
  2878. * The following is a list of all currently supported formats:
  2879. * <pre class="">
  2880. Format Description Example returned values
  2881. ------ ----------------------------------------------------------------------- -----------------------
  2882. d Day of the month, 2 digits with leading zeros 01 to 31
  2883. D A short textual representation of the day of the week Mon to Sun
  2884. j Day of the month without leading zeros 1 to 31
  2885. l A full textual representation of the day of the week Sunday to Saturday
  2886. N ISO-8601 numeric representation of the day of the week 1 (for Monday) through 7 (for Sunday)
  2887. S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
  2888. w Numeric representation of the day of the week 0 (for Sunday) to 6 (for Saturday)
  2889. z The day of the year (starting from 0) 0 to 364 (365 in leap years)
  2890. W ISO-8601 week number of year, weeks starting on Monday 01 to 53
  2891. F A full textual representation of a month, such as January or March January to December
  2892. m Numeric representation of a month, with leading zeros 01 to 12
  2893. M A short textual representation of a month Jan to Dec
  2894. n Numeric representation of a month, without leading zeros 1 to 12
  2895. t Number of days in the given month 28 to 31
  2896. L Whether it&#39;s a leap year 1 if it is a leap year, 0 otherwise.
  2897. o ISO-8601 year number (identical to (Y), but if the ISO week number (W) Examples: 1998 or 2004
  2898. belongs to the previous or next year, that year is used instead)
  2899. Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
  2900. y A two digit representation of a year Examples: 99 or 03
  2901. a Lowercase Ante meridiem and Post meridiem am or pm
  2902. A Uppercase Ante meridiem and Post meridiem AM or PM
  2903. g 12-hour format of an hour without leading zeros 1 to 12
  2904. G 24-hour format of an hour without leading zeros 0 to 23
  2905. h 12-hour format of an hour with leading zeros 01 to 12
  2906. H 24-hour format of an hour with leading zeros 00 to 23
  2907. i Minutes, with leading zeros 00 to 59
  2908. s Seconds, with leading zeros 00 to 59
  2909. u Decimal fraction of a second Examples:
  2910. (minimum 1 digit, arbitrary number of digits allowed) 001 (i.e. 0.001s) or
  2911. 100 (i.e. 0.100s) or
  2912. 999 (i.e. 0.999s) or
  2913. 999876543210 (i.e. 0.999876543210s)
  2914. O Difference to Greenwich time (GMT) in hours and minutes Example: +1030
  2915. P Difference to Greenwich time (GMT) with colon between hours and minutes Example: -08:00
  2916. T Timezone abbreviation of the machine running the code Examples: EST, MDT, PDT ...
  2917. Z Timezone offset in seconds (negative if west of UTC, positive if east) -43200 to 50400
  2918. c ISO 8601 date
  2919. Notes: Examples:
  2920. 1) If unspecified, the month / day defaults to the current month / day, 1991 or
  2921. the time defaults to midnight, while the timezone defaults to the 1992-10 or
  2922. browser's timezone. If a time is specified, it must include both hours 1993-09-20 or
  2923. and minutes. The "T" delimiter, seconds, milliseconds and timezone 1994-08-19T16:20+01:00 or
  2924. are optional. 1995-07-18T17:21:28-02:00 or
  2925. 2) The decimal fraction of a second, if specified, must contain at 1996-06-17T18:22:29.98765+03:00 or
  2926. least 1 digit (there is no limit to the maximum number 1997-05-16T19:23:30,12345-0400 or
  2927. of digits allowed), and may be delimited by either a '.' or a ',' 1998-04-15T20:24:31.2468Z or
  2928. Refer to the examples on the right for the various levels of 1999-03-14T20:24:32Z or
  2929. date-time granularity which are supported, or see 2000-02-13T21:25:33
  2930. http://www.w3.org/TR/NOTE-datetime for more info. 2001-01-12 22:26:34
  2931. U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) 1193432466 or -2138434463
  2932. MS Microsoft AJAX serialized dates \/Date(1238606590509)\/ (i.e. UTC milliseconds since epoch) or
  2933. \/Date(1238606590509+0800)\/
  2934. </pre>
  2935. *
  2936. * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
  2937. * <pre><code>
  2938. // Sample date:
  2939. // 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
  2940. var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
  2941. console.log(Ext.Date.format(dt, 'Y-m-d')); // 2007-01-10
  2942. console.log(Ext.Date.format(dt, 'F j, Y, g:i a')); // January 10, 2007, 3:05 pm
  2943. console.log(Ext.Date.format(dt, 'l, \\t\\he jS \\of F Y h:i:s A')); // Wednesday, the 10th of January 2007 03:05:01 PM
  2944. </code></pre>
  2945. *
  2946. * Here are some standard date/time patterns that you might find helpful. They
  2947. * are not part of the source of Ext.Date, but to use them you can simply copy this
  2948. * block of code into any script that is included after Ext.Date and they will also become
  2949. * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
  2950. * <pre><code>
  2951. Ext.Date.patterns = {
  2952. ISO8601Long:"Y-m-d H:i:s",
  2953. ISO8601Short:"Y-m-d",
  2954. ShortDate: "n/j/Y",
  2955. LongDate: "l, F d, Y",
  2956. FullDateTime: "l, F d, Y g:i:s A",
  2957. MonthDay: "F d",
  2958. ShortTime: "g:i A",
  2959. LongTime: "g:i:s A",
  2960. SortableDateTime: "Y-m-d\\TH:i:s",
  2961. UniversalSortableDateTime: "Y-m-d H:i:sO",
  2962. YearMonth: "F, Y"
  2963. };
  2964. </code></pre>
  2965. *
  2966. * Example usage:
  2967. * <pre><code>
  2968. var dt = new Date();
  2969. console.log(Ext.Date.format(dt, Ext.Date.patterns.ShortDate));
  2970. </code></pre>
  2971. * <p>Developer-written, custom formats may be used by supplying both a formatting and a parsing function
  2972. * which perform to specialized requirements. The functions are stored in {@link #parseFunctions} and {@link #formatFunctions}.</p>
  2973. * @singleton
  2974. */
  2975. /*
  2976. * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
  2977. * (see http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/)
  2978. * They generate precompiled functions from format patterns instead of parsing and
  2979. * processing each pattern every time a date is formatted. These functions are available
  2980. * on every Date object.
  2981. */
  2982. (function() {
  2983. // create private copy of Ext's Ext.util.Format.format() method
  2984. // - to remove unnecessary dependency
  2985. // - to resolve namespace conflict with MS-Ajax's implementation
  2986. function xf(format) {
  2987. var args = Array.prototype.slice.call(arguments, 1);
  2988. return format.replace(/\{(\d+)\}/g, function(m, i) {
  2989. return args[i];
  2990. });
  2991. }
  2992. Ext.Date = {
  2993. /**
  2994. * Returns the current timestamp
  2995. * @return {Date} The current timestamp
  2996. * @method
  2997. */
  2998. now: Date.now || function() {
  2999. return +new Date();
  3000. },
  3001. /**
  3002. * @private
  3003. * Private for now
  3004. */
  3005. toString: function(date) {
  3006. var pad = Ext.String.leftPad;
  3007. return date.getFullYear() + "-"
  3008. + pad(date.getMonth() + 1, 2, '0') + "-"
  3009. + pad(date.getDate(), 2, '0') + "T"
  3010. + pad(date.getHours(), 2, '0') + ":"
  3011. + pad(date.getMinutes(), 2, '0') + ":"
  3012. + pad(date.getSeconds(), 2, '0');
  3013. },
  3014. /**
  3015. * Returns the number of milliseconds between two dates
  3016. * @param {Date} dateA The first date
  3017. * @param {Date} dateB (optional) The second date, defaults to now
  3018. * @return {Number} The difference in milliseconds
  3019. */
  3020. getElapsed: function(dateA, dateB) {
  3021. return Math.abs(dateA - (dateB || new Date()));
  3022. },
  3023. /**
  3024. * Global flag which determines if strict date parsing should be used.
  3025. * Strict date parsing will not roll-over invalid dates, which is the
  3026. * default behaviour of javascript Date objects.
  3027. * (see {@link #parse} for more information)
  3028. * Defaults to <tt>false</tt>.
  3029. * @type Boolean
  3030. */
  3031. useStrict: false,
  3032. // private
  3033. formatCodeToRegex: function(character, currentGroup) {
  3034. // Note: currentGroup - position in regex result array (see notes for Ext.Date.parseCodes below)
  3035. var p = utilDate.parseCodes[character];
  3036. if (p) {
  3037. p = typeof p == 'function'? p() : p;
  3038. utilDate.parseCodes[character] = p; // reassign function result to prevent repeated execution
  3039. }
  3040. return p ? Ext.applyIf({
  3041. c: p.c ? xf(p.c, currentGroup || "{0}") : p.c
  3042. }, p) : {
  3043. g: 0,
  3044. c: null,
  3045. s: Ext.String.escapeRegex(character) // treat unrecognised characters as literals
  3046. };
  3047. },
  3048. /**
  3049. * <p>An object hash in which each property is a date parsing function. The property name is the
  3050. * format string which that function parses.</p>
  3051. * <p>This object is automatically populated with date parsing functions as
  3052. * date formats are requested for Ext standard formatting strings.</p>
  3053. * <p>Custom parsing functions may be inserted into this object, keyed by a name which from then on
  3054. * may be used as a format string to {@link #parse}.<p>
  3055. * <p>Example:</p><pre><code>
  3056. Ext.Date.parseFunctions['x-date-format'] = myDateParser;
  3057. </code></pre>
  3058. * <p>A parsing function should return a Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
  3059. * <li><code>date</code> : String<div class="sub-desc">The date string to parse.</div></li>
  3060. * <li><code>strict</code> : Boolean<div class="sub-desc">True to validate date strings while parsing
  3061. * (i.e. prevent javascript Date "rollover") (The default must be false).
  3062. * Invalid date strings should return null when parsed.</div></li>
  3063. * </ul></div></p>
  3064. * <p>To enable Dates to also be <i>formatted</i> according to that format, a corresponding
  3065. * formatting function must be placed into the {@link #formatFunctions} property.
  3066. * @property parseFunctions
  3067. * @type Object
  3068. */
  3069. parseFunctions: {
  3070. "MS": function(input, strict) {
  3071. // note: the timezone offset is ignored since the MS Ajax server sends
  3072. // a UTC milliseconds-since-Unix-epoch value (negative values are allowed)
  3073. var re = new RegExp('\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/');
  3074. var r = (input || '').match(re);
  3075. return r? new Date(((r[1] || '') + r[2]) * 1) : null;
  3076. }
  3077. },
  3078. parseRegexes: [],
  3079. /**
  3080. * <p>An object hash in which each property is a date formatting function. The property name is the
  3081. * format string which corresponds to the produced formatted date string.</p>
  3082. * <p>This object is automatically populated with date formatting functions as
  3083. * date formats are requested for Ext standard formatting strings.</p>
  3084. * <p>Custom formatting functions may be inserted into this object, keyed by a name which from then on
  3085. * may be used as a format string to {@link #format}. Example:</p><pre><code>
  3086. Ext.Date.formatFunctions['x-date-format'] = myDateFormatter;
  3087. </code></pre>
  3088. * <p>A formatting function should return a string representation of the passed Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
  3089. * <li><code>date</code> : Date<div class="sub-desc">The Date to format.</div></li>
  3090. * </ul></div></p>
  3091. * <p>To enable date strings to also be <i>parsed</i> according to that format, a corresponding
  3092. * parsing function must be placed into the {@link #parseFunctions} property.
  3093. * @property formatFunctions
  3094. * @type Object
  3095. */
  3096. formatFunctions: {
  3097. "MS": function() {
  3098. // UTC milliseconds since Unix epoch (MS-AJAX serialized date format (MRSF))
  3099. return '\\/Date(' + this.getTime() + ')\\/';
  3100. }
  3101. },
  3102. y2kYear : 50,
  3103. /**
  3104. * Date interval constant
  3105. * @type String
  3106. */
  3107. MILLI : "ms",
  3108. /**
  3109. * Date interval constant
  3110. * @type String
  3111. */
  3112. SECOND : "s",
  3113. /**
  3114. * Date interval constant
  3115. * @type String
  3116. */
  3117. MINUTE : "mi",
  3118. /** Date interval constant
  3119. * @type String
  3120. */
  3121. HOUR : "h",
  3122. /**
  3123. * Date interval constant
  3124. * @type String
  3125. */
  3126. DAY : "d",
  3127. /**
  3128. * Date interval constant
  3129. * @type String
  3130. */
  3131. MONTH : "mo",
  3132. /**
  3133. * Date interval constant
  3134. * @type String
  3135. */
  3136. YEAR : "y",
  3137. /**
  3138. * <p>An object hash containing default date values used during date parsing.</p>
  3139. * <p>The following properties are available:<div class="mdetail-params"><ul>
  3140. * <li><code>y</code> : Number<div class="sub-desc">The default year value. (defaults to undefined)</div></li>
  3141. * <li><code>m</code> : Number<div class="sub-desc">The default 1-based month value. (defaults to undefined)</div></li>
  3142. * <li><code>d</code> : Number<div class="sub-desc">The default day value. (defaults to undefined)</div></li>
  3143. * <li><code>h</code> : Number<div class="sub-desc">The default hour value. (defaults to undefined)</div></li>
  3144. * <li><code>i</code> : Number<div class="sub-desc">The default minute value. (defaults to undefined)</div></li>
  3145. * <li><code>s</code> : Number<div class="sub-desc">The default second value. (defaults to undefined)</div></li>
  3146. * <li><code>ms</code> : Number<div class="sub-desc">The default millisecond value. (defaults to undefined)</div></li>
  3147. * </ul></div></p>
  3148. * <p>Override these properties to customize the default date values used by the {@link #parse} method.</p>
  3149. * <p><b>Note: In countries which experience Daylight Saving Time (i.e. DST), the <tt>h</tt>, <tt>i</tt>, <tt>s</tt>
  3150. * and <tt>ms</tt> properties may coincide with the exact time in which DST takes effect.
  3151. * It is the responsiblity of the developer to account for this.</b></p>
  3152. * Example Usage:
  3153. * <pre><code>
  3154. // set default day value to the first day of the month
  3155. Ext.Date.defaults.d = 1;
  3156. // parse a February date string containing only year and month values.
  3157. // setting the default day value to 1 prevents weird date rollover issues
  3158. // when attempting to parse the following date string on, for example, March 31st 2009.
  3159. Ext.Date.parse('2009-02', 'Y-m'); // returns a Date object representing February 1st 2009
  3160. </code></pre>
  3161. * @property defaults
  3162. * @type Object
  3163. */
  3164. defaults: {},
  3165. /**
  3166. * @property {String[]} dayNames
  3167. * An array of textual day names.
  3168. * Override these values for international dates.
  3169. * Example:
  3170. * <pre><code>
  3171. Ext.Date.dayNames = [
  3172. 'SundayInYourLang',
  3173. 'MondayInYourLang',
  3174. ...
  3175. ];
  3176. </code></pre>
  3177. */
  3178. dayNames : [
  3179. "Sunday",
  3180. "Monday",
  3181. "Tuesday",
  3182. "Wednesday",
  3183. "Thursday",
  3184. "Friday",
  3185. "Saturday"
  3186. ],
  3187. /**
  3188. * @property {String[]} monthNames
  3189. * An array of textual month names.
  3190. * Override these values for international dates.
  3191. * Example:
  3192. * <pre><code>
  3193. Ext.Date.monthNames = [
  3194. 'JanInYourLang',
  3195. 'FebInYourLang',
  3196. ...
  3197. ];
  3198. </code></pre>
  3199. */
  3200. monthNames : [
  3201. "January",
  3202. "February",
  3203. "March",
  3204. "April",
  3205. "May",
  3206. "June",
  3207. "July",
  3208. "August",
  3209. "September",
  3210. "October",
  3211. "November",
  3212. "December"
  3213. ],
  3214. /**
  3215. * @property {Object} monthNumbers
  3216. * An object hash of zero-based javascript month numbers (with short month names as keys. note: keys are case-sensitive).
  3217. * Override these values for international dates.
  3218. * Example:
  3219. * <pre><code>
  3220. Ext.Date.monthNumbers = {
  3221. 'ShortJanNameInYourLang':0,
  3222. 'ShortFebNameInYourLang':1,
  3223. ...
  3224. };
  3225. </code></pre>
  3226. */
  3227. monthNumbers : {
  3228. Jan:0,
  3229. Feb:1,
  3230. Mar:2,
  3231. Apr:3,
  3232. May:4,
  3233. Jun:5,
  3234. Jul:6,
  3235. Aug:7,
  3236. Sep:8,
  3237. Oct:9,
  3238. Nov:10,
  3239. Dec:11
  3240. },
  3241. /**
  3242. * @property {String} defaultFormat
  3243. * <p>The date format string that the {@link Ext.util.Format#dateRenderer}
  3244. * and {@link Ext.util.Format#date} functions use. See {@link Ext.Date} for details.</p>
  3245. * <p>This may be overridden in a locale file.</p>
  3246. */
  3247. defaultFormat : "m/d/Y",
  3248. /**
  3249. * Get the short month name for the given month number.
  3250. * Override this function for international dates.
  3251. * @param {Number} month A zero-based javascript month number.
  3252. * @return {String} The short month name.
  3253. */
  3254. getShortMonthName : function(month) {
  3255. return utilDate.monthNames[month].substring(0, 3);
  3256. },
  3257. /**
  3258. * Get the short day name for the given day number.
  3259. * Override this function for international dates.
  3260. * @param {Number} day A zero-based javascript day number.
  3261. * @return {String} The short day name.
  3262. */
  3263. getShortDayName : function(day) {
  3264. return utilDate.dayNames[day].substring(0, 3);
  3265. },
  3266. /**
  3267. * Get the zero-based javascript month number for the given short/full month name.
  3268. * Override this function for international dates.
  3269. * @param {String} name The short/full month name.
  3270. * @return {Number} The zero-based javascript month number.
  3271. */
  3272. getMonthNumber : function(name) {
  3273. // handle camel casing for english month names (since the keys for the Ext.Date.monthNumbers hash are case sensitive)
  3274. return utilDate.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()];
  3275. },
  3276. /**
  3277. * Checks if the specified format contains hour information
  3278. * @param {String} format The format to check
  3279. * @return {Boolean} True if the format contains hour information
  3280. * @method
  3281. */
  3282. formatContainsHourInfo : (function(){
  3283. var stripEscapeRe = /(\\.)/g,
  3284. hourInfoRe = /([gGhHisucUOPZ]|MS)/;
  3285. return function(format){
  3286. return hourInfoRe.test(format.replace(stripEscapeRe, ''));
  3287. };
  3288. })(),
  3289. /**
  3290. * Checks if the specified format contains information about
  3291. * anything other than the time.
  3292. * @param {String} format The format to check
  3293. * @return {Boolean} True if the format contains information about
  3294. * date/day information.
  3295. * @method
  3296. */
  3297. formatContainsDateInfo : (function(){
  3298. var stripEscapeRe = /(\\.)/g,
  3299. dateInfoRe = /([djzmnYycU]|MS)/;
  3300. return function(format){
  3301. return dateInfoRe.test(format.replace(stripEscapeRe, ''));
  3302. };
  3303. })(),
  3304. /**
  3305. * The base format-code to formatting-function hashmap used by the {@link #format} method.
  3306. * Formatting functions are strings (or functions which return strings) which
  3307. * will return the appropriate value when evaluated in the context of the Date object
  3308. * from which the {@link #format} method is called.
  3309. * Add to / override these mappings for custom date formatting.
  3310. * Note: Ext.Date.format() treats characters as literals if an appropriate mapping cannot be found.
  3311. * Example:
  3312. * <pre><code>
  3313. Ext.Date.formatCodes.x = "Ext.util.Format.leftPad(this.getDate(), 2, '0')";
  3314. console.log(Ext.Date.format(new Date(), 'X'); // returns the current day of the month
  3315. </code></pre>
  3316. * @type Object
  3317. */
  3318. formatCodes : {
  3319. d: "Ext.String.leftPad(this.getDate(), 2, '0')",
  3320. D: "Ext.Date.getShortDayName(this.getDay())", // get localised short day name
  3321. j: "this.getDate()",
  3322. l: "Ext.Date.dayNames[this.getDay()]",
  3323. N: "(this.getDay() ? this.getDay() : 7)",
  3324. S: "Ext.Date.getSuffix(this)",
  3325. w: "this.getDay()",
  3326. z: "Ext.Date.getDayOfYear(this)",
  3327. W: "Ext.String.leftPad(Ext.Date.getWeekOfYear(this), 2, '0')",
  3328. F: "Ext.Date.monthNames[this.getMonth()]",
  3329. m: "Ext.String.leftPad(this.getMonth() + 1, 2, '0')",
  3330. M: "Ext.Date.getShortMonthName(this.getMonth())", // get localised short month name
  3331. n: "(this.getMonth() + 1)",
  3332. t: "Ext.Date.getDaysInMonth(this)",
  3333. L: "(Ext.Date.isLeapYear(this) ? 1 : 0)",
  3334. o: "(this.getFullYear() + (Ext.Date.getWeekOfYear(this) == 1 && this.getMonth() > 0 ? +1 : (Ext.Date.getWeekOfYear(this) >= 52 && this.getMonth() < 11 ? -1 : 0)))",
  3335. Y: "Ext.String.leftPad(this.getFullYear(), 4, '0')",
  3336. y: "('' + this.getFullYear()).substring(2, 4)",
  3337. a: "(this.getHours() < 12 ? 'am' : 'pm')",
  3338. A: "(this.getHours() < 12 ? 'AM' : 'PM')",
  3339. g: "((this.getHours() % 12) ? this.getHours() % 12 : 12)",
  3340. G: "this.getHours()",
  3341. h: "Ext.String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')",
  3342. H: "Ext.String.leftPad(this.getHours(), 2, '0')",
  3343. i: "Ext.String.leftPad(this.getMinutes(), 2, '0')",
  3344. s: "Ext.String.leftPad(this.getSeconds(), 2, '0')",
  3345. u: "Ext.String.leftPad(this.getMilliseconds(), 3, '0')",
  3346. O: "Ext.Date.getGMTOffset(this)",
  3347. P: "Ext.Date.getGMTOffset(this, true)",
  3348. T: "Ext.Date.getTimezone(this)",
  3349. Z: "(this.getTimezoneOffset() * -60)",
  3350. c: function() { // ISO-8601 -- GMT format
  3351. for (var c = "Y-m-dTH:i:sP", code = [], i = 0, l = c.length; i < l; ++i) {
  3352. var e = c.charAt(i);
  3353. code.push(e == "T" ? "'T'" : utilDate.getFormatCode(e)); // treat T as a character literal
  3354. }
  3355. return code.join(" + ");
  3356. },
  3357. /*
  3358. c: function() { // ISO-8601 -- UTC format
  3359. return [
  3360. "this.getUTCFullYear()", "'-'",
  3361. "Ext.util.Format.leftPad(this.getUTCMonth() + 1, 2, '0')", "'-'",
  3362. "Ext.util.Format.leftPad(this.getUTCDate(), 2, '0')",
  3363. "'T'",
  3364. "Ext.util.Format.leftPad(this.getUTCHours(), 2, '0')", "':'",
  3365. "Ext.util.Format.leftPad(this.getUTCMinutes(), 2, '0')", "':'",
  3366. "Ext.util.Format.leftPad(this.getUTCSeconds(), 2, '0')",
  3367. "'Z'"
  3368. ].join(" + ");
  3369. },
  3370. */
  3371. U: "Math.round(this.getTime() / 1000)"
  3372. },
  3373. /**
  3374. * Checks if the passed Date parameters will cause a javascript Date "rollover".
  3375. * @param {Number} year 4-digit year
  3376. * @param {Number} month 1-based month-of-year
  3377. * @param {Number} day Day of month
  3378. * @param {Number} hour (optional) Hour
  3379. * @param {Number} minute (optional) Minute
  3380. * @param {Number} second (optional) Second
  3381. * @param {Number} millisecond (optional) Millisecond
  3382. * @return {Boolean} true if the passed parameters do not cause a Date "rollover", false otherwise.
  3383. */
  3384. isValid : function(y, m, d, h, i, s, ms) {
  3385. // setup defaults
  3386. h = h || 0;
  3387. i = i || 0;
  3388. s = s || 0;
  3389. ms = ms || 0;
  3390. // Special handling for year < 100
  3391. var dt = utilDate.add(new Date(y < 100 ? 100 : y, m - 1, d, h, i, s, ms), utilDate.YEAR, y < 100 ? y - 100 : 0);
  3392. return y == dt.getFullYear() &&
  3393. m == dt.getMonth() + 1 &&
  3394. d == dt.getDate() &&
  3395. h == dt.getHours() &&
  3396. i == dt.getMinutes() &&
  3397. s == dt.getSeconds() &&
  3398. ms == dt.getMilliseconds();
  3399. },
  3400. /**
  3401. * Parses the passed string using the specified date format.
  3402. * Note that this function expects normal calendar dates, meaning that months are 1-based (i.e. 1 = January).
  3403. * The {@link #defaults} hash will be used for any date value (i.e. year, month, day, hour, minute, second or millisecond)
  3404. * which cannot be found in the passed string. If a corresponding default date value has not been specified in the {@link #defaults} hash,
  3405. * the current date's year, month, day or DST-adjusted zero-hour time value will be used instead.
  3406. * Keep in mind that the input date string must precisely match the specified format string
  3407. * in order for the parse operation to be successful (failed parse operations return a null value).
  3408. * <p>Example:</p><pre><code>
  3409. //dt = Fri May 25 2007 (current date)
  3410. var dt = new Date();
  3411. //dt = Thu May 25 2006 (today&#39;s month/day in 2006)
  3412. dt = Ext.Date.parse("2006", "Y");
  3413. //dt = Sun Jan 15 2006 (all date parts specified)
  3414. dt = Ext.Date.parse("2006-01-15", "Y-m-d");
  3415. //dt = Sun Jan 15 2006 15:20:01
  3416. dt = Ext.Date.parse("2006-01-15 3:20:01 PM", "Y-m-d g:i:s A");
  3417. // attempt to parse Sun Feb 29 2006 03:20:01 in strict mode
  3418. dt = Ext.Date.parse("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
  3419. </code></pre>
  3420. * @param {String} input The raw date string.
  3421. * @param {String} format The expected date string format.
  3422. * @param {Boolean} strict (optional) True to validate date strings while parsing (i.e. prevents javascript Date "rollover")
  3423. (defaults to false). Invalid date strings will return null when parsed.
  3424. * @return {Date} The parsed Date.
  3425. */
  3426. parse : function(input, format, strict) {
  3427. var p = utilDate.parseFunctions;
  3428. if (p[format] == null) {
  3429. utilDate.createParser(format);
  3430. }
  3431. return p[format](input, Ext.isDefined(strict) ? strict : utilDate.useStrict);
  3432. },
  3433. // Backwards compat
  3434. parseDate: function(input, format, strict){
  3435. return utilDate.parse(input, format, strict);
  3436. },
  3437. // private
  3438. getFormatCode : function(character) {
  3439. var f = utilDate.formatCodes[character];
  3440. if (f) {
  3441. f = typeof f == 'function'? f() : f;
  3442. utilDate.formatCodes[character] = f; // reassign function result to prevent repeated execution
  3443. }
  3444. // note: unknown characters are treated as literals
  3445. return f || ("'" + Ext.String.escape(character) + "'");
  3446. },
  3447. // private
  3448. createFormat : function(format) {
  3449. var code = [],
  3450. special = false,
  3451. ch = '';
  3452. for (var i = 0; i < format.length; ++i) {
  3453. ch = format.charAt(i);
  3454. if (!special && ch == "\\") {
  3455. special = true;
  3456. } else if (special) {
  3457. special = false;
  3458. code.push("'" + Ext.String.escape(ch) + "'");
  3459. } else {
  3460. code.push(utilDate.getFormatCode(ch));
  3461. }
  3462. }
  3463. utilDate.formatFunctions[format] = Ext.functionFactory("return " + code.join('+'));
  3464. },
  3465. // private
  3466. createParser : (function() {
  3467. var code = [
  3468. "var dt, y, m, d, h, i, s, ms, o, z, zz, u, v,",
  3469. "def = Ext.Date.defaults,",
  3470. "results = String(input).match(Ext.Date.parseRegexes[{0}]);", // either null, or an array of matched strings
  3471. "if(results){",
  3472. "{1}",
  3473. "if(u != null){", // i.e. unix time is defined
  3474. "v = new Date(u * 1000);", // give top priority to UNIX time
  3475. "}else{",
  3476. // create Date object representing midnight of the current day;
  3477. // this will provide us with our date defaults
  3478. // (note: clearTime() handles Daylight Saving Time automatically)
  3479. "dt = Ext.Date.clearTime(new Date);",
  3480. // date calculations (note: these calculations create a dependency on Ext.Number.from())
  3481. "y = Ext.Number.from(y, Ext.Number.from(def.y, dt.getFullYear()));",
  3482. "m = Ext.Number.from(m, Ext.Number.from(def.m - 1, dt.getMonth()));",
  3483. "d = Ext.Number.from(d, Ext.Number.from(def.d, dt.getDate()));",
  3484. // time calculations (note: these calculations create a dependency on Ext.Number.from())
  3485. "h = Ext.Number.from(h, Ext.Number.from(def.h, dt.getHours()));",
  3486. "i = Ext.Number.from(i, Ext.Number.from(def.i, dt.getMinutes()));",
  3487. "s = Ext.Number.from(s, Ext.Number.from(def.s, dt.getSeconds()));",
  3488. "ms = Ext.Number.from(ms, Ext.Number.from(def.ms, dt.getMilliseconds()));",
  3489. "if(z >= 0 && y >= 0){",
  3490. // both the year and zero-based day of year are defined and >= 0.
  3491. // these 2 values alone provide sufficient info to create a full date object
  3492. // create Date object representing January 1st for the given year
  3493. // handle years < 100 appropriately
  3494. "v = Ext.Date.add(new Date(y < 100 ? 100 : y, 0, 1, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
  3495. // then add day of year, checking for Date "rollover" if necessary
  3496. "v = !strict? v : (strict === true && (z <= 364 || (Ext.Date.isLeapYear(v) && z <= 365))? Ext.Date.add(v, Ext.Date.DAY, z) : null);",
  3497. "}else if(strict === true && !Ext.Date.isValid(y, m + 1, d, h, i, s, ms)){", // check for Date "rollover"
  3498. "v = null;", // invalid date, so return null
  3499. "}else{",
  3500. // plain old Date object
  3501. // handle years < 100 properly
  3502. "v = Ext.Date.add(new Date(y < 100 ? 100 : y, m, d, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
  3503. "}",
  3504. "}",
  3505. "}",
  3506. "if(v){",
  3507. // favour UTC offset over GMT offset
  3508. "if(zz != null){",
  3509. // reset to UTC, then add offset
  3510. "v = Ext.Date.add(v, Ext.Date.SECOND, -v.getTimezoneOffset() * 60 - zz);",
  3511. "}else if(o){",
  3512. // reset to GMT, then add offset
  3513. "v = Ext.Date.add(v, Ext.Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));",
  3514. "}",
  3515. "}",
  3516. "return v;"
  3517. ].join('\n');
  3518. return function(format) {
  3519. var regexNum = utilDate.parseRegexes.length,
  3520. currentGroup = 1,
  3521. calc = [],
  3522. regex = [],
  3523. special = false,
  3524. ch = "";
  3525. for (var i = 0; i < format.length; ++i) {
  3526. ch = format.charAt(i);
  3527. if (!special && ch == "\\") {
  3528. special = true;
  3529. } else if (special) {
  3530. special = false;
  3531. regex.push(Ext.String.escape(ch));
  3532. } else {
  3533. var obj = utilDate.formatCodeToRegex(ch, currentGroup);
  3534. currentGroup += obj.g;
  3535. regex.push(obj.s);
  3536. if (obj.g && obj.c) {
  3537. calc.push(obj.c);
  3538. }
  3539. }
  3540. }
  3541. utilDate.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$", 'i');
  3542. utilDate.parseFunctions[format] = Ext.functionFactory("input", "strict", xf(code, regexNum, calc.join('')));
  3543. };
  3544. })(),
  3545. // private
  3546. parseCodes : {
  3547. /*
  3548. * Notes:
  3549. * g = {Number} calculation group (0 or 1. only group 1 contributes to date calculations.)
  3550. * c = {String} calculation method (required for group 1. null for group 0. {0} = currentGroup - position in regex result array)
  3551. * s = {String} regex pattern. all matches are stored in results[], and are accessible by the calculation mapped to 'c'
  3552. */
  3553. d: {
  3554. g:1,
  3555. c:"d = parseInt(results[{0}], 10);\n",
  3556. s:"(\\d{2})" // day of month with leading zeroes (01 - 31)
  3557. },
  3558. j: {
  3559. g:1,
  3560. c:"d = parseInt(results[{0}], 10);\n",
  3561. s:"(\\d{1,2})" // day of month without leading zeroes (1 - 31)
  3562. },
  3563. D: function() {
  3564. for (var a = [], i = 0; i < 7; a.push(utilDate.getShortDayName(i)), ++i); // get localised short day names
  3565. return {
  3566. g:0,
  3567. c:null,
  3568. s:"(?:" + a.join("|") +")"
  3569. };
  3570. },
  3571. l: function() {
  3572. return {
  3573. g:0,
  3574. c:null,
  3575. s:"(?:" + utilDate.dayNames.join("|") + ")"
  3576. };
  3577. },
  3578. N: {
  3579. g:0,
  3580. c:null,
  3581. s:"[1-7]" // ISO-8601 day number (1 (monday) - 7 (sunday))
  3582. },
  3583. S: {
  3584. g:0,
  3585. c:null,
  3586. s:"(?:st|nd|rd|th)"
  3587. },
  3588. w: {
  3589. g:0,
  3590. c:null,
  3591. s:"[0-6]" // javascript day number (0 (sunday) - 6 (saturday))
  3592. },
  3593. z: {
  3594. g:1,
  3595. c:"z = parseInt(results[{0}], 10);\n",
  3596. s:"(\\d{1,3})" // day of the year (0 - 364 (365 in leap years))
  3597. },
  3598. W: {
  3599. g:0,
  3600. c:null,
  3601. s:"(?:\\d{2})" // ISO-8601 week number (with leading zero)
  3602. },
  3603. F: function() {
  3604. return {
  3605. g:1,
  3606. c:"m = parseInt(Ext.Date.getMonthNumber(results[{0}]), 10);\n", // get localised month number
  3607. s:"(" + utilDate.monthNames.join("|") + ")"
  3608. };
  3609. },
  3610. M: function() {
  3611. for (var a = [], i = 0; i < 12; a.push(utilDate.getShortMonthName(i)), ++i); // get localised short month names
  3612. return Ext.applyIf({
  3613. s:"(" + a.join("|") + ")"
  3614. }, utilDate.formatCodeToRegex("F"));
  3615. },
  3616. m: {
  3617. g:1,
  3618. c:"m = parseInt(results[{0}], 10) - 1;\n",
  3619. s:"(\\d{2})" // month number with leading zeros (01 - 12)
  3620. },
  3621. n: {
  3622. g:1,
  3623. c:"m = parseInt(results[{0}], 10) - 1;\n",
  3624. s:"(\\d{1,2})" // month number without leading zeros (1 - 12)
  3625. },
  3626. t: {
  3627. g:0,
  3628. c:null,
  3629. s:"(?:\\d{2})" // no. of days in the month (28 - 31)
  3630. },
  3631. L: {
  3632. g:0,
  3633. c:null,
  3634. s:"(?:1|0)"
  3635. },
  3636. o: function() {
  3637. return utilDate.formatCodeToRegex("Y");
  3638. },
  3639. Y: {
  3640. g:1,
  3641. c:"y = parseInt(results[{0}], 10);\n",
  3642. s:"(\\d{4})" // 4-digit year
  3643. },
  3644. y: {
  3645. g:1,
  3646. c:"var ty = parseInt(results[{0}], 10);\n"
  3647. + "y = ty > Ext.Date.y2kYear ? 1900 + ty : 2000 + ty;\n", // 2-digit year
  3648. s:"(\\d{1,2})"
  3649. },
  3650. /*
  3651. * In the am/pm parsing routines, we allow both upper and lower case
  3652. * even though it doesn't exactly match the spec. It gives much more flexibility
  3653. * in being able to specify case insensitive regexes.
  3654. */
  3655. a: {
  3656. g:1,
  3657. c:"if (/(am)/i.test(results[{0}])) {\n"
  3658. + "if (!h || h == 12) { h = 0; }\n"
  3659. + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
  3660. s:"(am|pm|AM|PM)"
  3661. },
  3662. A: {
  3663. g:1,
  3664. c:"if (/(am)/i.test(results[{0}])) {\n"
  3665. + "if (!h || h == 12) { h = 0; }\n"
  3666. + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
  3667. s:"(AM|PM|am|pm)"
  3668. },
  3669. g: function() {
  3670. return utilDate.formatCodeToRegex("G");
  3671. },
  3672. G: {
  3673. g:1,
  3674. c:"h = parseInt(results[{0}], 10);\n",
  3675. s:"(\\d{1,2})" // 24-hr format of an hour without leading zeroes (0 - 23)
  3676. },
  3677. h: function() {
  3678. return utilDate.formatCodeToRegex("H");
  3679. },
  3680. H: {
  3681. g:1,
  3682. c:"h = parseInt(results[{0}], 10);\n",
  3683. s:"(\\d{2})" // 24-hr format of an hour with leading zeroes (00 - 23)
  3684. },
  3685. i: {
  3686. g:1,
  3687. c:"i = parseInt(results[{0}], 10);\n",
  3688. s:"(\\d{2})" // minutes with leading zeros (00 - 59)
  3689. },
  3690. s: {
  3691. g:1,
  3692. c:"s = parseInt(results[{0}], 10);\n",
  3693. s:"(\\d{2})" // seconds with leading zeros (00 - 59)
  3694. },
  3695. u: {
  3696. g:1,
  3697. c:"ms = results[{0}]; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n",
  3698. s:"(\\d+)" // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
  3699. },
  3700. O: {
  3701. g:1,
  3702. c:[
  3703. "o = results[{0}];",
  3704. "var sn = o.substring(0,1),", // get + / - sign
  3705. "hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
  3706. "mn = o.substring(3,5) % 60;", // get minutes
  3707. "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.String.leftPad(hr, 2, '0') + Ext.String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs
  3708. ].join("\n"),
  3709. s: "([+\-]\\d{4})" // GMT offset in hrs and mins
  3710. },
  3711. P: {
  3712. g:1,
  3713. c:[
  3714. "o = results[{0}];",
  3715. "var sn = o.substring(0,1),", // get + / - sign
  3716. "hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
  3717. "mn = o.substring(4,6) % 60;", // get minutes
  3718. "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.String.leftPad(hr, 2, '0') + Ext.String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs
  3719. ].join("\n"),
  3720. s: "([+\-]\\d{2}:\\d{2})" // GMT offset in hrs and mins (with colon separator)
  3721. },
  3722. T: {
  3723. g:0,
  3724. c:null,
  3725. s:"[A-Z]{1,4}" // timezone abbrev. may be between 1 - 4 chars
  3726. },
  3727. Z: {
  3728. g:1,
  3729. c:"zz = results[{0}] * 1;\n" // -43200 <= UTC offset <= 50400
  3730. + "zz = (-43200 <= zz && zz <= 50400)? zz : null;\n",
  3731. s:"([+\-]?\\d{1,5})" // leading '+' sign is optional for UTC offset
  3732. },
  3733. c: function() {
  3734. var calc = [],
  3735. arr = [
  3736. utilDate.formatCodeToRegex("Y", 1), // year
  3737. utilDate.formatCodeToRegex("m", 2), // month
  3738. utilDate.formatCodeToRegex("d", 3), // day
  3739. utilDate.formatCodeToRegex("h", 4), // hour
  3740. utilDate.formatCodeToRegex("i", 5), // minute
  3741. utilDate.formatCodeToRegex("s", 6), // second
  3742. {c:"ms = results[7] || '0'; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n"}, // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
  3743. {c:[ // allow either "Z" (i.e. UTC) or "-0530" or "+08:00" (i.e. UTC offset) timezone delimiters. assumes local timezone if no timezone is specified
  3744. "if(results[8]) {", // timezone specified
  3745. "if(results[8] == 'Z'){",
  3746. "zz = 0;", // UTC
  3747. "}else if (results[8].indexOf(':') > -1){",
  3748. utilDate.formatCodeToRegex("P", 8).c, // timezone offset with colon separator
  3749. "}else{",
  3750. utilDate.formatCodeToRegex("O", 8).c, // timezone offset without colon separator
  3751. "}",
  3752. "}"
  3753. ].join('\n')}
  3754. ];
  3755. for (var i = 0, l = arr.length; i < l; ++i) {
  3756. calc.push(arr[i].c);
  3757. }
  3758. return {
  3759. g:1,
  3760. c:calc.join(""),
  3761. s:[
  3762. arr[0].s, // year (required)
  3763. "(?:", "-", arr[1].s, // month (optional)
  3764. "(?:", "-", arr[2].s, // day (optional)
  3765. "(?:",
  3766. "(?:T| )?", // time delimiter -- either a "T" or a single blank space
  3767. arr[3].s, ":", arr[4].s, // hour AND minute, delimited by a single colon (optional). MUST be preceded by either a "T" or a single blank space
  3768. "(?::", arr[5].s, ")?", // seconds (optional)
  3769. "(?:(?:\\.|,)(\\d+))?", // decimal fraction of a second (e.g. ",12345" or ".98765") (optional)
  3770. "(Z|(?:[-+]\\d{2}(?::)?\\d{2}))?", // "Z" (UTC) or "-0530" (UTC offset without colon delimiter) or "+08:00" (UTC offset with colon delimiter) (optional)
  3771. ")?",
  3772. ")?",
  3773. ")?"
  3774. ].join("")
  3775. };
  3776. },
  3777. U: {
  3778. g:1,
  3779. c:"u = parseInt(results[{0}], 10);\n",
  3780. s:"(-?\\d+)" // leading minus sign indicates seconds before UNIX epoch
  3781. }
  3782. },
  3783. //Old Ext.Date prototype methods.
  3784. // private
  3785. dateFormat: function(date, format) {
  3786. return utilDate.format(date, format);
  3787. },
  3788. /**
  3789. * Formats a date given the supplied format string.
  3790. * @param {Date} date The date to format
  3791. * @param {String} format The format string
  3792. * @return {String} The formatted date
  3793. */
  3794. format: function(date, format) {
  3795. if (utilDate.formatFunctions[format] == null) {
  3796. utilDate.createFormat(format);
  3797. }
  3798. var result = utilDate.formatFunctions[format].call(date);
  3799. return result + '';
  3800. },
  3801. /**
  3802. * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
  3803. *
  3804. * Note: The date string returned by the javascript Date object's toString() method varies
  3805. * between browsers (e.g. FF vs IE) and system region settings (e.g. IE in Asia vs IE in America).
  3806. * For a given date string e.g. "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)",
  3807. * getTimezone() first tries to get the timezone abbreviation from between a pair of parentheses
  3808. * (which may or may not be present), failing which it proceeds to get the timezone abbreviation
  3809. * from the GMT offset portion of the date string.
  3810. * @param {Date} date The date
  3811. * @return {String} The abbreviated timezone name (e.g. 'CST', 'PDT', 'EDT', 'MPST' ...).
  3812. */
  3813. getTimezone : function(date) {
  3814. // the following list shows the differences between date strings from different browsers on a WinXP SP2 machine from an Asian locale:
  3815. //
  3816. // Opera : "Thu, 25 Oct 2007 22:53:45 GMT+0800" -- shortest (weirdest) date string of the lot
  3817. // Safari : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone (same as FF)
  3818. // FF : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone
  3819. // IE : "Thu Oct 25 22:54:35 UTC+0800 2007" -- (Asian system setting) look for 3-4 letter timezone abbrev
  3820. // IE : "Thu Oct 25 17:06:37 PDT 2007" -- (American system setting) look for 3-4 letter timezone abbrev
  3821. //
  3822. // this crazy regex attempts to guess the correct timezone abbreviation despite these differences.
  3823. // step 1: (?:\((.*)\) -- find timezone in parentheses
  3824. // step 2: ([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?) -- if nothing was found in step 1, find timezone from timezone offset portion of date string
  3825. // step 3: remove all non uppercase characters found in step 1 and 2
  3826. return date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, "");
  3827. },
  3828. /**
  3829. * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
  3830. * @param {Date} date The date
  3831. * @param {Boolean} colon (optional) true to separate the hours and minutes with a colon (defaults to false).
  3832. * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600').
  3833. */
  3834. getGMTOffset : function(date, colon) {
  3835. var offset = date.getTimezoneOffset();
  3836. return (offset > 0 ? "-" : "+")
  3837. + Ext.String.leftPad(Math.floor(Math.abs(offset) / 60), 2, "0")
  3838. + (colon ? ":" : "")
  3839. + Ext.String.leftPad(Math.abs(offset % 60), 2, "0");
  3840. },
  3841. /**
  3842. * Get the numeric day number of the year, adjusted for leap year.
  3843. * @param {Date} date The date
  3844. * @return {Number} 0 to 364 (365 in leap years).
  3845. */
  3846. getDayOfYear: function(date) {
  3847. var num = 0,
  3848. d = Ext.Date.clone(date),
  3849. m = date.getMonth(),
  3850. i;
  3851. for (i = 0, d.setDate(1), d.setMonth(0); i < m; d.setMonth(++i)) {
  3852. num += utilDate.getDaysInMonth(d);
  3853. }
  3854. return num + date.getDate() - 1;
  3855. },
  3856. /**
  3857. * Get the numeric ISO-8601 week number of the year.
  3858. * (equivalent to the format specifier 'W', but without a leading zero).
  3859. * @param {Date} date The date
  3860. * @return {Number} 1 to 53
  3861. * @method
  3862. */
  3863. getWeekOfYear : (function() {
  3864. // adapted from http://www.merlyn.demon.co.uk/weekcalc.htm
  3865. var ms1d = 864e5, // milliseconds in a day
  3866. ms7d = 7 * ms1d; // milliseconds in a week
  3867. return function(date) { // return a closure so constants get calculated only once
  3868. var DC3 = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate() + 3) / ms1d, // an Absolute Day Number
  3869. AWN = Math.floor(DC3 / 7), // an Absolute Week Number
  3870. Wyr = new Date(AWN * ms7d).getUTCFullYear();
  3871. return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1;
  3872. };
  3873. })(),
  3874. /**
  3875. * Checks if the current date falls within a leap year.
  3876. * @param {Date} date The date
  3877. * @return {Boolean} True if the current date falls within a leap year, false otherwise.
  3878. */
  3879. isLeapYear : function(date) {
  3880. var year = date.getFullYear();
  3881. return !!((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
  3882. },
  3883. /**
  3884. * Get the first day of the current month, adjusted for leap year. The returned value
  3885. * is the numeric day index within the week (0-6) which can be used in conjunction with
  3886. * the {@link #monthNames} array to retrieve the textual day name.
  3887. * Example:
  3888. * <pre><code>
  3889. var dt = new Date('1/10/2007'),
  3890. firstDay = Ext.Date.getFirstDayOfMonth(dt);
  3891. console.log(Ext.Date.dayNames[firstDay]); //output: 'Monday'
  3892. * </code></pre>
  3893. * @param {Date} date The date
  3894. * @return {Number} The day number (0-6).
  3895. */
  3896. getFirstDayOfMonth : function(date) {
  3897. var day = (date.getDay() - (date.getDate() - 1)) % 7;
  3898. return (day < 0) ? (day + 7) : day;
  3899. },
  3900. /**
  3901. * Get the last day of the current month, adjusted for leap year. The returned value
  3902. * is the numeric day index within the week (0-6) which can be used in conjunction with
  3903. * the {@link #monthNames} array to retrieve the textual day name.
  3904. * Example:
  3905. * <pre><code>
  3906. var dt = new Date('1/10/2007'),
  3907. lastDay = Ext.Date.getLastDayOfMonth(dt);
  3908. console.log(Ext.Date.dayNames[lastDay]); //output: 'Wednesday'
  3909. * </code></pre>
  3910. * @param {Date} date The date
  3911. * @return {Number} The day number (0-6).
  3912. */
  3913. getLastDayOfMonth : function(date) {
  3914. return utilDate.getLastDateOfMonth(date).getDay();
  3915. },
  3916. /**
  3917. * Get the date of the first day of the month in which this date resides.
  3918. * @param {Date} date The date
  3919. * @return {Date}
  3920. */
  3921. getFirstDateOfMonth : function(date) {
  3922. return new Date(date.getFullYear(), date.getMonth(), 1);
  3923. },
  3924. /**
  3925. * Get the date of the last day of the month in which this date resides.
  3926. * @param {Date} date The date
  3927. * @return {Date}
  3928. */
  3929. getLastDateOfMonth : function(date) {
  3930. return new Date(date.getFullYear(), date.getMonth(), utilDate.getDaysInMonth(date));
  3931. },
  3932. /**
  3933. * Get the number of days in the current month, adjusted for leap year.
  3934. * @param {Date} date The date
  3935. * @return {Number} The number of days in the month.
  3936. * @method
  3937. */
  3938. getDaysInMonth: (function() {
  3939. var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  3940. return function(date) { // return a closure for efficiency
  3941. var m = date.getMonth();
  3942. return m == 1 && utilDate.isLeapYear(date) ? 29 : daysInMonth[m];
  3943. };
  3944. })(),
  3945. /**
  3946. * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
  3947. * @param {Date} date The date
  3948. * @return {String} 'st, 'nd', 'rd' or 'th'.
  3949. */
  3950. getSuffix : function(date) {
  3951. switch (date.getDate()) {
  3952. case 1:
  3953. case 21:
  3954. case 31:
  3955. return "st";
  3956. case 2:
  3957. case 22:
  3958. return "nd";
  3959. case 3:
  3960. case 23:
  3961. return "rd";
  3962. default:
  3963. return "th";
  3964. }
  3965. },
  3966. /**
  3967. * Creates and returns a new Date instance with the exact same date value as the called instance.
  3968. * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
  3969. * variable will also be changed. When the intention is to create a new variable that will not
  3970. * modify the original instance, you should create a clone.
  3971. *
  3972. * Example of correctly cloning a date:
  3973. * <pre><code>
  3974. //wrong way:
  3975. var orig = new Date('10/1/2006');
  3976. var copy = orig;
  3977. copy.setDate(5);
  3978. console.log(orig); //returns 'Thu Oct 05 2006'!
  3979. //correct way:
  3980. var orig = new Date('10/1/2006'),
  3981. copy = Ext.Date.clone(orig);
  3982. copy.setDate(5);
  3983. console.log(orig); //returns 'Thu Oct 01 2006'
  3984. * </code></pre>
  3985. * @param {Date} date The date
  3986. * @return {Date} The new Date instance.
  3987. */
  3988. clone : function(date) {
  3989. return new Date(date.getTime());
  3990. },
  3991. /**
  3992. * Checks if the current date is affected by Daylight Saving Time (DST).
  3993. * @param {Date} date The date
  3994. * @return {Boolean} True if the current date is affected by DST.
  3995. */
  3996. isDST : function(date) {
  3997. // adapted from http://sencha.com/forum/showthread.php?p=247172#post247172
  3998. // courtesy of @geoffrey.mcgill
  3999. return new Date(date.getFullYear(), 0, 1).getTimezoneOffset() != date.getTimezoneOffset();
  4000. },
  4001. /**
  4002. * Attempts to clear all time information from this Date by setting the time to midnight of the same day,
  4003. * automatically adjusting for Daylight Saving Time (DST) where applicable.
  4004. * (note: DST timezone information for the browser's host operating system is assumed to be up-to-date)
  4005. * @param {Date} date The date
  4006. * @param {Boolean} clone true to create a clone of this date, clear the time and return it (defaults to false).
  4007. * @return {Date} this or the clone.
  4008. */
  4009. clearTime : function(date, clone) {
  4010. if (clone) {
  4011. return Ext.Date.clearTime(Ext.Date.clone(date));
  4012. }
  4013. // get current date before clearing time
  4014. var d = date.getDate();
  4015. // clear time
  4016. date.setHours(0);
  4017. date.setMinutes(0);
  4018. date.setSeconds(0);
  4019. date.setMilliseconds(0);
  4020. if (date.getDate() != d) { // account for DST (i.e. day of month changed when setting hour = 0)
  4021. // note: DST adjustments are assumed to occur in multiples of 1 hour (this is almost always the case)
  4022. // refer to http://www.timeanddate.com/time/aboutdst.html for the (rare) exceptions to this rule
  4023. // increment hour until cloned date == current date
  4024. for (var hr = 1, c = utilDate.add(date, Ext.Date.HOUR, hr); c.getDate() != d; hr++, c = utilDate.add(date, Ext.Date.HOUR, hr));
  4025. date.setDate(d);
  4026. date.setHours(c.getHours());
  4027. }
  4028. return date;
  4029. },
  4030. /**
  4031. * Provides a convenient method for performing basic date arithmetic. This method
  4032. * does not modify the Date instance being called - it creates and returns
  4033. * a new Date instance containing the resulting date value.
  4034. *
  4035. * Examples:
  4036. * <pre><code>
  4037. // Basic usage:
  4038. var dt = Ext.Date.add(new Date('10/29/2006'), Ext.Date.DAY, 5);
  4039. console.log(dt); //returns 'Fri Nov 03 2006 00:00:00'
  4040. // Negative values will be subtracted:
  4041. var dt2 = Ext.Date.add(new Date('10/1/2006'), Ext.Date.DAY, -5);
  4042. console.log(dt2); //returns 'Tue Sep 26 2006 00:00:00'
  4043. * </code></pre>
  4044. *
  4045. * @param {Date} date The date to modify
  4046. * @param {String} interval A valid date interval enum value.
  4047. * @param {Number} value The amount to add to the current date.
  4048. * @return {Date} The new Date instance.
  4049. */
  4050. add : function(date, interval, value) {
  4051. var d = Ext.Date.clone(date),
  4052. Date = Ext.Date;
  4053. if (!interval || value === 0) return d;
  4054. switch(interval.toLowerCase()) {
  4055. case Ext.Date.MILLI:
  4056. d.setMilliseconds(d.getMilliseconds() + value);
  4057. break;
  4058. case Ext.Date.SECOND:
  4059. d.setSeconds(d.getSeconds() + value);
  4060. break;
  4061. case Ext.Date.MINUTE:
  4062. d.setMinutes(d.getMinutes() + value);
  4063. break;
  4064. case Ext.Date.HOUR:
  4065. d.setHours(d.getHours() + value);
  4066. break;
  4067. case Ext.Date.DAY:
  4068. d.setDate(d.getDate() + value);
  4069. break;
  4070. case Ext.Date.MONTH:
  4071. var day = date.getDate();
  4072. if (day > 28) {
  4073. day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), 'mo', value)).getDate());
  4074. }
  4075. d.setDate(day);
  4076. d.setMonth(date.getMonth() + value);
  4077. break;
  4078. case Ext.Date.YEAR:
  4079. d.setFullYear(date.getFullYear() + value);
  4080. break;
  4081. }
  4082. return d;
  4083. },
  4084. /**
  4085. * Checks if a date falls on or between the given start and end dates.
  4086. * @param {Date} date The date to check
  4087. * @param {Date} start Start date
  4088. * @param {Date} end End date
  4089. * @return {Boolean} true if this date falls on or between the given start and end dates.
  4090. */
  4091. between : function(date, start, end) {
  4092. var t = date.getTime();
  4093. return start.getTime() <= t && t <= end.getTime();
  4094. },
  4095. //Maintains compatibility with old static and prototype window.Date methods.
  4096. compat: function() {
  4097. var nativeDate = window.Date,
  4098. p, u,
  4099. statics = ['useStrict', 'formatCodeToRegex', 'parseFunctions', 'parseRegexes', 'formatFunctions', 'y2kYear', 'MILLI', 'SECOND', 'MINUTE', 'HOUR', 'DAY', 'MONTH', 'YEAR', 'defaults', 'dayNames', 'monthNames', 'monthNumbers', 'getShortMonthName', 'getShortDayName', 'getMonthNumber', 'formatCodes', 'isValid', 'parseDate', 'getFormatCode', 'createFormat', 'createParser', 'parseCodes'],
  4100. proto = ['dateFormat', 'format', 'getTimezone', 'getGMTOffset', 'getDayOfYear', 'getWeekOfYear', 'isLeapYear', 'getFirstDayOfMonth', 'getLastDayOfMonth', 'getDaysInMonth', 'getSuffix', 'clone', 'isDST', 'clearTime', 'add', 'between'];
  4101. //Append statics
  4102. Ext.Array.forEach(statics, function(s) {
  4103. nativeDate[s] = utilDate[s];
  4104. });
  4105. //Append to prototype
  4106. Ext.Array.forEach(proto, function(s) {
  4107. nativeDate.prototype[s] = function() {
  4108. var args = Array.prototype.slice.call(arguments);
  4109. args.unshift(this);
  4110. return utilDate[s].apply(utilDate, args);
  4111. };
  4112. });
  4113. }
  4114. };
  4115. var utilDate = Ext.Date;
  4116. })();
  4117. /**
  4118. * @author Jacky Nguyen <jacky@sencha.com>
  4119. * @docauthor Jacky Nguyen <jacky@sencha.com>
  4120. * @class Ext.Base
  4121. *
  4122. * The root of all classes created with {@link Ext#define}.
  4123. *
  4124. * Ext.Base is the building block of all Ext classes. All classes in Ext inherit from Ext.Base.
  4125. * All prototype and static members of this class are inherited by all other classes.
  4126. */
  4127. (function(flexSetter) {
  4128. var Base = Ext.Base = function() {};
  4129. Base.prototype = {
  4130. $className: 'Ext.Base',
  4131. $class: Base,
  4132. /**
  4133. * Get the reference to the current class from which this object was instantiated. Unlike {@link Ext.Base#statics},
  4134. * `this.self` is scope-dependent and it's meant to be used for dynamic inheritance. See {@link Ext.Base#statics}
  4135. * for a detailed comparison
  4136. *
  4137. * Ext.define('My.Cat', {
  4138. * statics: {
  4139. * speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
  4140. * },
  4141. *
  4142. * constructor: function() {
  4143. * alert(this.self.speciesName); / dependent on 'this'
  4144. *
  4145. * return this;
  4146. * },
  4147. *
  4148. * clone: function() {
  4149. * return new this.self();
  4150. * }
  4151. * });
  4152. *
  4153. *
  4154. * Ext.define('My.SnowLeopard', {
  4155. * extend: 'My.Cat',
  4156. * statics: {
  4157. * speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
  4158. * }
  4159. * });
  4160. *
  4161. * var cat = new My.Cat(); // alerts 'Cat'
  4162. * var snowLeopard = new My.SnowLeopard(); // alerts 'Snow Leopard'
  4163. *
  4164. * var clone = snowLeopard.clone();
  4165. * alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard'
  4166. *
  4167. * @type Ext.Class
  4168. * @protected
  4169. */
  4170. self: Base,
  4171. // Default constructor, simply returns `this`
  4172. constructor: function() {
  4173. return this;
  4174. },
  4175. //<feature classSystem.config>
  4176. /**
  4177. * Initialize configuration for this class. a typical example:
  4178. *
  4179. * Ext.define('My.awesome.Class', {
  4180. * // The default config
  4181. * config: {
  4182. * name: 'Awesome',
  4183. * isAwesome: true
  4184. * },
  4185. *
  4186. * constructor: function(config) {
  4187. * this.initConfig(config);
  4188. *
  4189. * return this;
  4190. * }
  4191. * });
  4192. *
  4193. * var awesome = new My.awesome.Class({
  4194. * name: 'Super Awesome'
  4195. * });
  4196. *
  4197. * alert(awesome.getName()); // 'Super Awesome'
  4198. *
  4199. * @protected
  4200. * @param {Object} config
  4201. * @return {Object} mixins The mixin prototypes as key - value pairs
  4202. */
  4203. initConfig: function(config) {
  4204. if (!this.$configInited) {
  4205. this.config = Ext.Object.merge({}, this.config || {}, config || {});
  4206. this.applyConfig(this.config);
  4207. this.$configInited = true;
  4208. }
  4209. return this;
  4210. },
  4211. /**
  4212. * @private
  4213. */
  4214. setConfig: function(config) {
  4215. this.applyConfig(config || {});
  4216. return this;
  4217. },
  4218. /**
  4219. * @private
  4220. */
  4221. applyConfig: flexSetter(function(name, value) {
  4222. var setter = 'set' + Ext.String.capitalize(name);
  4223. if (typeof this[setter] === 'function') {
  4224. this[setter].call(this, value);
  4225. }
  4226. return this;
  4227. }),
  4228. //</feature>
  4229. /**
  4230. * Call the parent's overridden method. For example:
  4231. *
  4232. * Ext.define('My.own.A', {
  4233. * constructor: function(test) {
  4234. * alert(test);
  4235. * }
  4236. * });
  4237. *
  4238. * Ext.define('My.own.B', {
  4239. * extend: 'My.own.A',
  4240. *
  4241. * constructor: function(test) {
  4242. * alert(test);
  4243. *
  4244. * this.callParent([test + 1]);
  4245. * }
  4246. * });
  4247. *
  4248. * Ext.define('My.own.C', {
  4249. * extend: 'My.own.B',
  4250. *
  4251. * constructor: function() {
  4252. * alert("Going to call parent's overriden constructor...");
  4253. *
  4254. * this.callParent(arguments);
  4255. * }
  4256. * });
  4257. *
  4258. * var a = new My.own.A(1); // alerts '1'
  4259. * var b = new My.own.B(1); // alerts '1', then alerts '2'
  4260. * var c = new My.own.C(2); // alerts "Going to call parent's overriden constructor..."
  4261. * // alerts '2', then alerts '3'
  4262. *
  4263. * @protected
  4264. * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
  4265. * from the current method, for example: `this.callParent(arguments)`
  4266. * @return {Object} Returns the result from the superclass' method
  4267. */
  4268. callParent: function(args) {
  4269. var method = this.callParent.caller,
  4270. parentClass, methodName;
  4271. if (!method.$owner) {
  4272. method = method.caller;
  4273. }
  4274. parentClass = method.$owner.superclass;
  4275. methodName = method.$name;
  4276. return parentClass[methodName].apply(this, args || []);
  4277. },
  4278. /**
  4279. * Get the reference to the class from which this object was instantiated. Note that unlike {@link Ext.Base#self},
  4280. * `this.statics()` is scope-independent and it always returns the class from which it was called, regardless of what
  4281. * `this` points to during run-time
  4282. *
  4283. * Ext.define('My.Cat', {
  4284. * statics: {
  4285. * totalCreated: 0,
  4286. * speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
  4287. * },
  4288. *
  4289. * constructor: function() {
  4290. * var statics = this.statics();
  4291. *
  4292. * alert(statics.speciesName); // always equals to 'Cat' no matter what 'this' refers to
  4293. * // equivalent to: My.Cat.speciesName
  4294. *
  4295. * alert(this.self.speciesName); // dependent on 'this'
  4296. *
  4297. * statics.totalCreated++;
  4298. *
  4299. * return this;
  4300. * },
  4301. *
  4302. * clone: function() {
  4303. * var cloned = new this.self; // dependent on 'this'
  4304. *
  4305. * cloned.groupName = this.statics().speciesName; // equivalent to: My.Cat.speciesName
  4306. *
  4307. * return cloned;
  4308. * }
  4309. * });
  4310. *
  4311. *
  4312. * Ext.define('My.SnowLeopard', {
  4313. * extend: 'My.Cat',
  4314. *
  4315. * statics: {
  4316. * speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
  4317. * },
  4318. *
  4319. * constructor: function() {
  4320. * this.callParent();
  4321. * }
  4322. * });
  4323. *
  4324. * var cat = new My.Cat(); // alerts 'Cat', then alerts 'Cat'
  4325. *
  4326. * var snowLeopard = new My.SnowLeopard(); // alerts 'Cat', then alerts 'Snow Leopard'
  4327. *
  4328. * var clone = snowLeopard.clone();
  4329. * alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard'
  4330. * alert(clone.groupName); // alerts 'Cat'
  4331. *
  4332. * alert(My.Cat.totalCreated); // alerts 3
  4333. *
  4334. * @protected
  4335. * @return {Ext.Class}
  4336. */
  4337. statics: function() {
  4338. var method = this.statics.caller,
  4339. self = this.self;
  4340. if (!method) {
  4341. return self;
  4342. }
  4343. return method.$owner;
  4344. },
  4345. /**
  4346. * Call the original method that was previously overridden with {@link Ext.Base#override}
  4347. *
  4348. * Ext.define('My.Cat', {
  4349. * constructor: function() {
  4350. * alert("I'm a cat!");
  4351. *
  4352. * return this;
  4353. * }
  4354. * });
  4355. *
  4356. * My.Cat.override({
  4357. * constructor: function() {
  4358. * alert("I'm going to be a cat!");
  4359. *
  4360. * var instance = this.callOverridden();
  4361. *
  4362. * alert("Meeeeoooowwww");
  4363. *
  4364. * return instance;
  4365. * }
  4366. * });
  4367. *
  4368. * var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
  4369. * // alerts "I'm a cat!"
  4370. * // alerts "Meeeeoooowwww"
  4371. *
  4372. * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
  4373. * @return {Object} Returns the result after calling the overridden method
  4374. * @protected
  4375. */
  4376. callOverridden: function(args) {
  4377. var method = this.callOverridden.caller;
  4378. return method.$previous.apply(this, args || []);
  4379. },
  4380. destroy: function() {}
  4381. };
  4382. // These static properties will be copied to every newly created class with {@link Ext#define}
  4383. Ext.apply(Ext.Base, {
  4384. /**
  4385. * Create a new instance of this Class.
  4386. *
  4387. * Ext.define('My.cool.Class', {
  4388. * ...
  4389. * });
  4390. *
  4391. * My.cool.Class.create({
  4392. * someConfig: true
  4393. * });
  4394. *
  4395. * All parameters are passed to the constructor of the class.
  4396. *
  4397. * @return {Object} the created instance.
  4398. * @static
  4399. * @inheritable
  4400. */
  4401. create: function() {
  4402. return Ext.create.apply(Ext, [this].concat(Array.prototype.slice.call(arguments, 0)));
  4403. },
  4404. /**
  4405. * @private
  4406. * @inheritable
  4407. */
  4408. own: function(name, value) {
  4409. if (typeof value == 'function') {
  4410. this.ownMethod(name, value);
  4411. }
  4412. else {
  4413. this.prototype[name] = value;
  4414. }
  4415. },
  4416. /**
  4417. * @private
  4418. * @inheritable
  4419. */
  4420. ownMethod: function(name, fn) {
  4421. var originalFn;
  4422. if (typeof fn.$owner !== 'undefined' && fn !== Ext.emptyFn) {
  4423. originalFn = fn;
  4424. fn = function() {
  4425. return originalFn.apply(this, arguments);
  4426. };
  4427. }
  4428. fn.$owner = this;
  4429. fn.$name = name;
  4430. this.prototype[name] = fn;
  4431. },
  4432. /**
  4433. * Add / override static properties of this class.
  4434. *
  4435. * Ext.define('My.cool.Class', {
  4436. * ...
  4437. * });
  4438. *
  4439. * My.cool.Class.addStatics({
  4440. * someProperty: 'someValue', // My.cool.Class.someProperty = 'someValue'
  4441. * method1: function() { ... }, // My.cool.Class.method1 = function() { ... };
  4442. * method2: function() { ... } // My.cool.Class.method2 = function() { ... };
  4443. * });
  4444. *
  4445. * @param {Object} members
  4446. * @return {Ext.Base} this
  4447. * @static
  4448. * @inheritable
  4449. */
  4450. addStatics: function(members) {
  4451. for (var name in members) {
  4452. if (members.hasOwnProperty(name)) {
  4453. this[name] = members[name];
  4454. }
  4455. }
  4456. return this;
  4457. },
  4458. /**
  4459. * @private
  4460. * @param {Object} members
  4461. */
  4462. addInheritableStatics: function(members) {
  4463. var inheritableStatics,
  4464. hasInheritableStatics,
  4465. prototype = this.prototype,
  4466. name, member;
  4467. inheritableStatics = prototype.$inheritableStatics;
  4468. hasInheritableStatics = prototype.$hasInheritableStatics;
  4469. if (!inheritableStatics) {
  4470. inheritableStatics = prototype.$inheritableStatics = [];
  4471. hasInheritableStatics = prototype.$hasInheritableStatics = {};
  4472. }
  4473. for (name in members) {
  4474. if (members.hasOwnProperty(name)) {
  4475. member = members[name];
  4476. this[name] = member;
  4477. if (!hasInheritableStatics[name]) {
  4478. hasInheritableStatics[name] = true;
  4479. inheritableStatics.push(name);
  4480. }
  4481. }
  4482. }
  4483. return this;
  4484. },
  4485. /**
  4486. * Add methods / properties to the prototype of this class.
  4487. *
  4488. * Ext.define('My.awesome.Cat', {
  4489. * constructor: function() {
  4490. * ...
  4491. * }
  4492. * });
  4493. *
  4494. * My.awesome.Cat.implement({
  4495. * meow: function() {
  4496. * alert('Meowww...');
  4497. * }
  4498. * });
  4499. *
  4500. * var kitty = new My.awesome.Cat;
  4501. * kitty.meow();
  4502. *
  4503. * @param {Object} members
  4504. * @static
  4505. * @inheritable
  4506. */
  4507. implement: function(members) {
  4508. var prototype = this.prototype,
  4509. enumerables = Ext.enumerables,
  4510. name, i, member;
  4511. for (name in members) {
  4512. if (members.hasOwnProperty(name)) {
  4513. member = members[name];
  4514. if (typeof member === 'function') {
  4515. member.$owner = this;
  4516. member.$name = name;
  4517. }
  4518. prototype[name] = member;
  4519. }
  4520. }
  4521. if (enumerables) {
  4522. for (i = enumerables.length; i--;) {
  4523. name = enumerables[i];
  4524. if (members.hasOwnProperty(name)) {
  4525. member = members[name];
  4526. member.$owner = this;
  4527. member.$name = name;
  4528. prototype[name] = member;
  4529. }
  4530. }
  4531. }
  4532. },
  4533. /**
  4534. * Borrow another class' members to the prototype of this class.
  4535. *
  4536. * Ext.define('Bank', {
  4537. * money: '$$$',
  4538. * printMoney: function() {
  4539. * alert('$$$$$$$');
  4540. * }
  4541. * });
  4542. *
  4543. * Ext.define('Thief', {
  4544. * ...
  4545. * });
  4546. *
  4547. * Thief.borrow(Bank, ['money', 'printMoney']);
  4548. *
  4549. * var steve = new Thief();
  4550. *
  4551. * alert(steve.money); // alerts '$$$'
  4552. * steve.printMoney(); // alerts '$$$$$$$'
  4553. *
  4554. * @param {Ext.Base} fromClass The class to borrow members from
  4555. * @param {String/String[]} members The names of the members to borrow
  4556. * @return {Ext.Base} this
  4557. * @static
  4558. * @inheritable
  4559. */
  4560. borrow: function(fromClass, members) {
  4561. var fromPrototype = fromClass.prototype,
  4562. i, ln, member;
  4563. members = Ext.Array.from(members);
  4564. for (i = 0, ln = members.length; i < ln; i++) {
  4565. member = members[i];
  4566. this.own(member, fromPrototype[member]);
  4567. }
  4568. return this;
  4569. },
  4570. /**
  4571. * Override prototype members of this class. Overridden methods can be invoked via
  4572. * {@link Ext.Base#callOverridden}
  4573. *
  4574. * Ext.define('My.Cat', {
  4575. * constructor: function() {
  4576. * alert("I'm a cat!");
  4577. *
  4578. * return this;
  4579. * }
  4580. * });
  4581. *
  4582. * My.Cat.override({
  4583. * constructor: function() {
  4584. * alert("I'm going to be a cat!");
  4585. *
  4586. * var instance = this.callOverridden();
  4587. *
  4588. * alert("Meeeeoooowwww");
  4589. *
  4590. * return instance;
  4591. * }
  4592. * });
  4593. *
  4594. * var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
  4595. * // alerts "I'm a cat!"
  4596. * // alerts "Meeeeoooowwww"
  4597. *
  4598. * @param {Object} members
  4599. * @return {Ext.Base} this
  4600. * @static
  4601. * @inheritable
  4602. */
  4603. override: function(members) {
  4604. var prototype = this.prototype,
  4605. enumerables = Ext.enumerables,
  4606. name, i, member, previous;
  4607. if (arguments.length === 2) {
  4608. name = members;
  4609. member = arguments[1];
  4610. if (typeof member == 'function') {
  4611. if (typeof prototype[name] == 'function') {
  4612. previous = prototype[name];
  4613. member.$previous = previous;
  4614. }
  4615. this.ownMethod(name, member);
  4616. }
  4617. else {
  4618. prototype[name] = member;
  4619. }
  4620. return this;
  4621. }
  4622. for (name in members) {
  4623. if (members.hasOwnProperty(name)) {
  4624. member = members[name];
  4625. if (typeof member === 'function') {
  4626. if (typeof prototype[name] === 'function') {
  4627. previous = prototype[name];
  4628. member.$previous = previous;
  4629. }
  4630. this.ownMethod(name, member);
  4631. }
  4632. else {
  4633. prototype[name] = member;
  4634. }
  4635. }
  4636. }
  4637. if (enumerables) {
  4638. for (i = enumerables.length; i--;) {
  4639. name = enumerables[i];
  4640. if (members.hasOwnProperty(name)) {
  4641. if (typeof prototype[name] !== 'undefined') {
  4642. previous = prototype[name];
  4643. members[name].$previous = previous;
  4644. }
  4645. this.ownMethod(name, members[name]);
  4646. }
  4647. }
  4648. }
  4649. return this;
  4650. },
  4651. //<feature classSystem.mixins>
  4652. /**
  4653. * Used internally by the mixins pre-processor
  4654. * @private
  4655. * @inheritable
  4656. */
  4657. mixin: function(name, cls) {
  4658. var mixin = cls.prototype,
  4659. my = this.prototype,
  4660. key, fn;
  4661. for (key in mixin) {
  4662. if (mixin.hasOwnProperty(key)) {
  4663. if (typeof my[key] === 'undefined' && key !== 'mixins' && key !== 'mixinId') {
  4664. if (typeof mixin[key] === 'function') {
  4665. fn = mixin[key];
  4666. if (typeof fn.$owner === 'undefined') {
  4667. this.ownMethod(key, fn);
  4668. }
  4669. else {
  4670. my[key] = fn;
  4671. }
  4672. }
  4673. else {
  4674. my[key] = mixin[key];
  4675. }
  4676. }
  4677. //<feature classSystem.config>
  4678. else if (key === 'config' && my.config && mixin.config) {
  4679. Ext.Object.merge(my.config, mixin.config);
  4680. }
  4681. //</feature>
  4682. }
  4683. }
  4684. if (typeof mixin.onClassMixedIn !== 'undefined') {
  4685. mixin.onClassMixedIn.call(cls, this);
  4686. }
  4687. if (!my.hasOwnProperty('mixins')) {
  4688. if ('mixins' in my) {
  4689. my.mixins = Ext.Object.merge({}, my.mixins);
  4690. }
  4691. else {
  4692. my.mixins = {};
  4693. }
  4694. }
  4695. my.mixins[name] = mixin;
  4696. },
  4697. //</feature>
  4698. /**
  4699. * Get the current class' name in string format.
  4700. *
  4701. * Ext.define('My.cool.Class', {
  4702. * constructor: function() {
  4703. * alert(this.self.getName()); // alerts 'My.cool.Class'
  4704. * }
  4705. * });
  4706. *
  4707. * My.cool.Class.getName(); // 'My.cool.Class'
  4708. *
  4709. * @return {String} className
  4710. * @static
  4711. * @inheritable
  4712. */
  4713. getName: function() {
  4714. return Ext.getClassName(this);
  4715. },
  4716. /**
  4717. * Create aliases for existing prototype methods. Example:
  4718. *
  4719. * Ext.define('My.cool.Class', {
  4720. * method1: function() { ... },
  4721. * method2: function() { ... }
  4722. * });
  4723. *
  4724. * var test = new My.cool.Class();
  4725. *
  4726. * My.cool.Class.createAlias({
  4727. * method3: 'method1',
  4728. * method4: 'method2'
  4729. * });
  4730. *
  4731. * test.method3(); // test.method1()
  4732. *
  4733. * My.cool.Class.createAlias('method5', 'method3');
  4734. *
  4735. * test.method5(); // test.method3() -> test.method1()
  4736. *
  4737. * @param {String/Object} alias The new method name, or an object to set multiple aliases. See
  4738. * {@link Ext.Function#flexSetter flexSetter}
  4739. * @param {String/Object} origin The original method name
  4740. * @static
  4741. * @inheritable
  4742. * @method
  4743. */
  4744. createAlias: flexSetter(function(alias, origin) {
  4745. this.prototype[alias] = function() {
  4746. return this[origin].apply(this, arguments);
  4747. }
  4748. })
  4749. });
  4750. })(Ext.Function.flexSetter);
  4751. /**
  4752. * @author Jacky Nguyen <jacky@sencha.com>
  4753. * @docauthor Jacky Nguyen <jacky@sencha.com>
  4754. * @class Ext.Class
  4755. *
  4756. * Handles class creation throughout the framework. This is a low level factory that is used by Ext.ClassManager and generally
  4757. * should not be used directly. If you choose to use Ext.Class you will lose out on the namespace, aliasing and depency loading
  4758. * features made available by Ext.ClassManager. The only time you would use Ext.Class directly is to create an anonymous class.
  4759. *
  4760. * If you wish to create a class you should use {@link Ext#define Ext.define} which aliases
  4761. * {@link Ext.ClassManager#create Ext.ClassManager.create} to enable namespacing and dynamic dependency resolution.
  4762. *
  4763. * Ext.Class is the factory and **not** the superclass of everything. For the base class that **all** Ext classes inherit
  4764. * from, see {@link Ext.Base}.
  4765. */
  4766. (function() {
  4767. var Class,
  4768. Base = Ext.Base,
  4769. baseStaticProperties = [],
  4770. baseStaticProperty;
  4771. for (baseStaticProperty in Base) {
  4772. if (Base.hasOwnProperty(baseStaticProperty)) {
  4773. baseStaticProperties.push(baseStaticProperty);
  4774. }
  4775. }
  4776. /**
  4777. * @method constructor
  4778. * Creates new class.
  4779. * @param {Object} classData An object represent the properties of this class
  4780. * @param {Function} createdFn (Optional) The callback function to be executed when this class is fully created.
  4781. * Note that the creation process can be asynchronous depending on the pre-processors used.
  4782. * @return {Ext.Base} The newly created class
  4783. */
  4784. Ext.Class = Class = function(newClass, classData, onClassCreated) {
  4785. if (typeof newClass != 'function') {
  4786. onClassCreated = classData;
  4787. classData = newClass;
  4788. newClass = function() {
  4789. return this.constructor.apply(this, arguments);
  4790. };
  4791. }
  4792. if (!classData) {
  4793. classData = {};
  4794. }
  4795. var preprocessorStack = classData.preprocessors || Class.getDefaultPreprocessors(),
  4796. registeredPreprocessors = Class.getPreprocessors(),
  4797. index = 0,
  4798. preprocessors = [],
  4799. preprocessor, staticPropertyName, process, i, j, ln;
  4800. for (i = 0, ln = baseStaticProperties.length; i < ln; i++) {
  4801. staticPropertyName = baseStaticProperties[i];
  4802. newClass[staticPropertyName] = Base[staticPropertyName];
  4803. }
  4804. delete classData.preprocessors;
  4805. for (j = 0, ln = preprocessorStack.length; j < ln; j++) {
  4806. preprocessor = preprocessorStack[j];
  4807. if (typeof preprocessor == 'string') {
  4808. preprocessor = registeredPreprocessors[preprocessor];
  4809. if (!preprocessor.always) {
  4810. if (classData.hasOwnProperty(preprocessor.name)) {
  4811. preprocessors.push(preprocessor.fn);
  4812. }
  4813. }
  4814. else {
  4815. preprocessors.push(preprocessor.fn);
  4816. }
  4817. }
  4818. else {
  4819. preprocessors.push(preprocessor);
  4820. }
  4821. }
  4822. classData.onClassCreated = onClassCreated || Ext.emptyFn;
  4823. classData.onBeforeClassCreated = function(cls, data) {
  4824. onClassCreated = data.onClassCreated;
  4825. delete data.onBeforeClassCreated;
  4826. delete data.onClassCreated;
  4827. cls.implement(data);
  4828. onClassCreated.call(cls, cls);
  4829. };
  4830. process = function(cls, data) {
  4831. preprocessor = preprocessors[index++];
  4832. if (!preprocessor) {
  4833. data.onBeforeClassCreated.apply(this, arguments);
  4834. return;
  4835. }
  4836. if (preprocessor.call(this, cls, data, process) !== false) {
  4837. process.apply(this, arguments);
  4838. }
  4839. };
  4840. process.call(Class, newClass, classData);
  4841. return newClass;
  4842. };
  4843. Ext.apply(Class, {
  4844. /** @private */
  4845. preprocessors: {},
  4846. /**
  4847. * Register a new pre-processor to be used during the class creation process
  4848. *
  4849. * @member Ext.Class
  4850. * @param {String} name The pre-processor's name
  4851. * @param {Function} fn The callback function to be executed. Typical format:
  4852. *
  4853. * function(cls, data, fn) {
  4854. * // Your code here
  4855. *
  4856. * // Execute this when the processing is finished.
  4857. * // Asynchronous processing is perfectly ok
  4858. * if (fn) {
  4859. * fn.call(this, cls, data);
  4860. * }
  4861. * });
  4862. *
  4863. * @param {Function} fn.cls The created class
  4864. * @param {Object} fn.data The set of properties passed in {@link Ext.Class} constructor
  4865. * @param {Function} fn.fn The callback function that **must** to be executed when this pre-processor finishes,
  4866. * regardless of whether the processing is synchronous or aynchronous
  4867. *
  4868. * @return {Ext.Class} this
  4869. * @static
  4870. */
  4871. registerPreprocessor: function(name, fn, always) {
  4872. this.preprocessors[name] = {
  4873. name: name,
  4874. always: always || false,
  4875. fn: fn
  4876. };
  4877. return this;
  4878. },
  4879. /**
  4880. * Retrieve a pre-processor callback function by its name, which has been registered before
  4881. *
  4882. * @param {String} name
  4883. * @return {Function} preprocessor
  4884. * @static
  4885. */
  4886. getPreprocessor: function(name) {
  4887. return this.preprocessors[name];
  4888. },
  4889. getPreprocessors: function() {
  4890. return this.preprocessors;
  4891. },
  4892. /**
  4893. * Retrieve the array stack of default pre-processors
  4894. *
  4895. * @return {Function[]} defaultPreprocessors
  4896. * @static
  4897. */
  4898. getDefaultPreprocessors: function() {
  4899. return this.defaultPreprocessors || [];
  4900. },
  4901. /**
  4902. * Set the default array stack of default pre-processors
  4903. *
  4904. * @param {Function/Function[]} preprocessors
  4905. * @return {Ext.Class} this
  4906. * @static
  4907. */
  4908. setDefaultPreprocessors: function(preprocessors) {
  4909. this.defaultPreprocessors = Ext.Array.from(preprocessors);
  4910. return this;
  4911. },
  4912. /**
  4913. * Inserts this pre-processor at a specific position in the stack, optionally relative to
  4914. * any existing pre-processor. For example:
  4915. *
  4916. * Ext.Class.registerPreprocessor('debug', function(cls, data, fn) {
  4917. * // Your code here
  4918. *
  4919. * if (fn) {
  4920. * fn.call(this, cls, data);
  4921. * }
  4922. * }).setDefaultPreprocessorPosition('debug', 'last');
  4923. *
  4924. * @param {String} name The pre-processor name. Note that it needs to be registered with
  4925. * {@link #registerPreprocessor registerPreprocessor} before this
  4926. * @param {String} offset The insertion position. Four possible values are:
  4927. * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument)
  4928. * @param {String} relativeName
  4929. * @return {Ext.Class} this
  4930. * @static
  4931. */
  4932. setDefaultPreprocessorPosition: function(name, offset, relativeName) {
  4933. var defaultPreprocessors = this.defaultPreprocessors,
  4934. index;
  4935. if (typeof offset == 'string') {
  4936. if (offset === 'first') {
  4937. defaultPreprocessors.unshift(name);
  4938. return this;
  4939. }
  4940. else if (offset === 'last') {
  4941. defaultPreprocessors.push(name);
  4942. return this;
  4943. }
  4944. offset = (offset === 'after') ? 1 : -1;
  4945. }
  4946. index = Ext.Array.indexOf(defaultPreprocessors, relativeName);
  4947. if (index !== -1) {
  4948. Ext.Array.splice(defaultPreprocessors, Math.max(0, index + offset), 0, name);
  4949. }
  4950. return this;
  4951. }
  4952. });
  4953. /**
  4954. * @cfg {String} extend
  4955. * The parent class that this class extends. For example:
  4956. *
  4957. * Ext.define('Person', {
  4958. * say: function(text) { alert(text); }
  4959. * });
  4960. *
  4961. * Ext.define('Developer', {
  4962. * extend: 'Person',
  4963. * say: function(text) { this.callParent(["print "+text]); }
  4964. * });
  4965. */
  4966. Class.registerPreprocessor('extend', function(cls, data) {
  4967. var extend = data.extend,
  4968. base = Ext.Base,
  4969. basePrototype = base.prototype,
  4970. prototype = function() {},
  4971. parent, i, k, ln, staticName, parentStatics,
  4972. parentPrototype, clsPrototype;
  4973. if (extend && extend !== Object) {
  4974. parent = extend;
  4975. }
  4976. else {
  4977. parent = base;
  4978. }
  4979. parentPrototype = parent.prototype;
  4980. prototype.prototype = parentPrototype;
  4981. clsPrototype = cls.prototype = new prototype();
  4982. if (!('$class' in parent)) {
  4983. for (i in basePrototype) {
  4984. if (!parentPrototype[i]) {
  4985. parentPrototype[i] = basePrototype[i];
  4986. }
  4987. }
  4988. }
  4989. clsPrototype.self = cls;
  4990. cls.superclass = clsPrototype.superclass = parentPrototype;
  4991. delete data.extend;
  4992. //<feature classSystem.inheritableStatics>
  4993. // Statics inheritance
  4994. parentStatics = parentPrototype.$inheritableStatics;
  4995. if (parentStatics) {
  4996. for (k = 0, ln = parentStatics.length; k < ln; k++) {
  4997. staticName = parentStatics[k];
  4998. if (!cls.hasOwnProperty(staticName)) {
  4999. cls[staticName] = parent[staticName];
  5000. }
  5001. }
  5002. }
  5003. //</feature>
  5004. //<feature classSystem.config>
  5005. // Merge the parent class' config object without referencing it
  5006. if (parentPrototype.config) {
  5007. clsPrototype.config = Ext.Object.merge({}, parentPrototype.config);
  5008. }
  5009. else {
  5010. clsPrototype.config = {};
  5011. }
  5012. //</feature>
  5013. //<feature classSystem.onClassExtended>
  5014. if (clsPrototype.$onExtended) {
  5015. clsPrototype.$onExtended.call(cls, cls, data);
  5016. }
  5017. if (data.onClassExtended) {
  5018. clsPrototype.$onExtended = data.onClassExtended;
  5019. delete data.onClassExtended;
  5020. }
  5021. //</feature>
  5022. }, true);
  5023. //<feature classSystem.statics>
  5024. /**
  5025. * @cfg {Object} statics
  5026. * List of static methods for this class. For example:
  5027. *
  5028. * Ext.define('Computer', {
  5029. * statics: {
  5030. * factory: function(brand) {
  5031. * // 'this' in static methods refer to the class itself
  5032. * return new this(brand);
  5033. * }
  5034. * },
  5035. *
  5036. * constructor: function() { ... }
  5037. * });
  5038. *
  5039. * var dellComputer = Computer.factory('Dell');
  5040. */
  5041. Class.registerPreprocessor('statics', function(cls, data) {
  5042. cls.addStatics(data.statics);
  5043. delete data.statics;
  5044. });
  5045. //</feature>
  5046. //<feature classSystem.inheritableStatics>
  5047. /**
  5048. * @cfg {Object} inheritableStatics
  5049. * List of inheritable static methods for this class.
  5050. * Otherwise just like {@link #statics} but subclasses inherit these methods.
  5051. */
  5052. Class.registerPreprocessor('inheritableStatics', function(cls, data) {
  5053. cls.addInheritableStatics(data.inheritableStatics);
  5054. delete data.inheritableStatics;
  5055. });
  5056. //</feature>
  5057. //<feature classSystem.config>
  5058. /**
  5059. * @cfg {Object} config
  5060. * List of configuration options with their default values, for which automatically
  5061. * accessor methods are generated. For example:
  5062. *
  5063. * Ext.define('SmartPhone', {
  5064. * config: {
  5065. * hasTouchScreen: false,
  5066. * operatingSystem: 'Other',
  5067. * price: 500
  5068. * },
  5069. * constructor: function(cfg) {
  5070. * this.initConfig(cfg);
  5071. * }
  5072. * });
  5073. *
  5074. * var iPhone = new SmartPhone({
  5075. * hasTouchScreen: true,
  5076. * operatingSystem: 'iOS'
  5077. * });
  5078. *
  5079. * iPhone.getPrice(); // 500;
  5080. * iPhone.getOperatingSystem(); // 'iOS'
  5081. * iPhone.getHasTouchScreen(); // true;
  5082. * iPhone.hasTouchScreen(); // true
  5083. */
  5084. Class.registerPreprocessor('config', function(cls, data) {
  5085. var prototype = cls.prototype;
  5086. Ext.Object.each(data.config, function(name) {
  5087. var cName = name.charAt(0).toUpperCase() + name.substr(1),
  5088. pName = name,
  5089. apply = 'apply' + cName,
  5090. setter = 'set' + cName,
  5091. getter = 'get' + cName;
  5092. if (!(apply in prototype) && !data.hasOwnProperty(apply)) {
  5093. data[apply] = function(val) {
  5094. return val;
  5095. };
  5096. }
  5097. if (!(setter in prototype) && !data.hasOwnProperty(setter)) {
  5098. data[setter] = function(val) {
  5099. var ret = this[apply].call(this, val, this[pName]);
  5100. if (typeof ret != 'undefined') {
  5101. this[pName] = ret;
  5102. }
  5103. return this;
  5104. };
  5105. }
  5106. if (!(getter in prototype) && !data.hasOwnProperty(getter)) {
  5107. data[getter] = function() {
  5108. return this[pName];
  5109. };
  5110. }
  5111. });
  5112. Ext.Object.merge(prototype.config, data.config);
  5113. delete data.config;
  5114. });
  5115. //</feature>
  5116. //<feature classSystem.mixins>
  5117. /**
  5118. * @cfg {Object} mixins
  5119. * List of classes to mix into this class. For example:
  5120. *
  5121. * Ext.define('CanSing', {
  5122. * sing: function() {
  5123. * alert("I'm on the highway to hell...")
  5124. * }
  5125. * });
  5126. *
  5127. * Ext.define('Musician', {
  5128. * extend: 'Person',
  5129. *
  5130. * mixins: {
  5131. * canSing: 'CanSing'
  5132. * }
  5133. * })
  5134. */
  5135. Class.registerPreprocessor('mixins', function(cls, data) {
  5136. var mixins = data.mixins,
  5137. name, mixin, i, ln;
  5138. delete data.mixins;
  5139. Ext.Function.interceptBefore(data, 'onClassCreated', function(cls) {
  5140. if (mixins instanceof Array) {
  5141. for (i = 0,ln = mixins.length; i < ln; i++) {
  5142. mixin = mixins[i];
  5143. name = mixin.prototype.mixinId || mixin.$className;
  5144. cls.mixin(name, mixin);
  5145. }
  5146. }
  5147. else {
  5148. for (name in mixins) {
  5149. if (mixins.hasOwnProperty(name)) {
  5150. cls.mixin(name, mixins[name]);
  5151. }
  5152. }
  5153. }
  5154. });
  5155. });
  5156. //</feature>
  5157. Class.setDefaultPreprocessors([
  5158. 'extend'
  5159. //<feature classSystem.statics>
  5160. ,'statics'
  5161. //</feature>
  5162. //<feature classSystem.inheritableStatics>
  5163. ,'inheritableStatics'
  5164. //</feature>
  5165. //<feature classSystem.config>
  5166. ,'config'
  5167. //</feature>
  5168. //<feature classSystem.mixins>
  5169. ,'mixins'
  5170. //</feature>
  5171. ]);
  5172. //<feature classSystem.backwardsCompatible>
  5173. // Backwards compatible
  5174. Ext.extend = function(subclass, superclass, members) {
  5175. if (arguments.length === 2 && Ext.isObject(superclass)) {
  5176. members = superclass;
  5177. superclass = subclass;
  5178. subclass = null;
  5179. }
  5180. var cls;
  5181. if (!superclass) {
  5182. Ext.Error.raise("Attempting to extend from a class which has not been loaded on the page.");
  5183. }
  5184. members.extend = superclass;
  5185. members.preprocessors = [
  5186. 'extend'
  5187. //<feature classSystem.statics>
  5188. ,'statics'
  5189. //</feature>
  5190. //<feature classSystem.inheritableStatics>
  5191. ,'inheritableStatics'
  5192. //</feature>
  5193. //<feature classSystem.mixins>
  5194. ,'mixins'
  5195. //</feature>
  5196. //<feature classSystem.config>
  5197. ,'config'
  5198. //</feature>
  5199. ];
  5200. if (subclass) {
  5201. cls = new Class(subclass, members);
  5202. }
  5203. else {
  5204. cls = new Class(members);
  5205. }
  5206. cls.prototype.override = function(o) {
  5207. for (var m in o) {
  5208. if (o.hasOwnProperty(m)) {
  5209. this[m] = o[m];
  5210. }
  5211. }
  5212. };
  5213. return cls;
  5214. };
  5215. //</feature>
  5216. })();
  5217. /**
  5218. * @author Jacky Nguyen <jacky@sencha.com>
  5219. * @docauthor Jacky Nguyen <jacky@sencha.com>
  5220. * @class Ext.ClassManager
  5221. *
  5222. * Ext.ClassManager manages all classes and handles mapping from string class name to
  5223. * actual class objects throughout the whole framework. It is not generally accessed directly, rather through
  5224. * these convenient shorthands:
  5225. *
  5226. * - {@link Ext#define Ext.define}
  5227. * - {@link Ext#create Ext.create}
  5228. * - {@link Ext#widget Ext.widget}
  5229. * - {@link Ext#getClass Ext.getClass}
  5230. * - {@link Ext#getClassName Ext.getClassName}
  5231. *
  5232. * # Basic syntax:
  5233. *
  5234. * Ext.define(className, properties);
  5235. *
  5236. * in which `properties` is an object represent a collection of properties that apply to the class. See
  5237. * {@link Ext.ClassManager#create} for more detailed instructions.
  5238. *
  5239. * Ext.define('Person', {
  5240. * name: 'Unknown',
  5241. *
  5242. * constructor: function(name) {
  5243. * if (name) {
  5244. * this.name = name;
  5245. * }
  5246. *
  5247. * return this;
  5248. * },
  5249. *
  5250. * eat: function(foodType) {
  5251. * alert("I'm eating: " + foodType);
  5252. *
  5253. * return this;
  5254. * }
  5255. * });
  5256. *
  5257. * var aaron = new Person("Aaron");
  5258. * aaron.eat("Sandwich"); // alert("I'm eating: Sandwich");
  5259. *
  5260. * Ext.Class has a powerful set of extensible {@link Ext.Class#registerPreprocessor pre-processors} which takes care of
  5261. * everything related to class creation, including but not limited to inheritance, mixins, configuration, statics, etc.
  5262. *
  5263. * # Inheritance:
  5264. *
  5265. * Ext.define('Developer', {
  5266. * extend: 'Person',
  5267. *
  5268. * constructor: function(name, isGeek) {
  5269. * this.isGeek = isGeek;
  5270. *
  5271. * // Apply a method from the parent class' prototype
  5272. * this.callParent([name]);
  5273. *
  5274. * return this;
  5275. *
  5276. * },
  5277. *
  5278. * code: function(language) {
  5279. * alert("I'm coding in: " + language);
  5280. *
  5281. * this.eat("Bugs");
  5282. *
  5283. * return this;
  5284. * }
  5285. * });
  5286. *
  5287. * var jacky = new Developer("Jacky", true);
  5288. * jacky.code("JavaScript"); // alert("I'm coding in: JavaScript");
  5289. * // alert("I'm eating: Bugs");
  5290. *
  5291. * See {@link Ext.Base#callParent} for more details on calling superclass' methods
  5292. *
  5293. * # Mixins:
  5294. *
  5295. * Ext.define('CanPlayGuitar', {
  5296. * playGuitar: function() {
  5297. * alert("F#...G...D...A");
  5298. * }
  5299. * });
  5300. *
  5301. * Ext.define('CanComposeSongs', {
  5302. * composeSongs: function() { ... }
  5303. * });
  5304. *
  5305. * Ext.define('CanSing', {
  5306. * sing: function() {
  5307. * alert("I'm on the highway to hell...")
  5308. * }
  5309. * });
  5310. *
  5311. * Ext.define('Musician', {
  5312. * extend: 'Person',
  5313. *
  5314. * mixins: {
  5315. * canPlayGuitar: 'CanPlayGuitar',
  5316. * canComposeSongs: 'CanComposeSongs',
  5317. * canSing: 'CanSing'
  5318. * }
  5319. * })
  5320. *
  5321. * Ext.define('CoolPerson', {
  5322. * extend: 'Person',
  5323. *
  5324. * mixins: {
  5325. * canPlayGuitar: 'CanPlayGuitar',
  5326. * canSing: 'CanSing'
  5327. * },
  5328. *
  5329. * sing: function() {
  5330. * alert("Ahem....");
  5331. *
  5332. * this.mixins.canSing.sing.call(this);
  5333. *
  5334. * alert("[Playing guitar at the same time...]");
  5335. *
  5336. * this.playGuitar();
  5337. * }
  5338. * });
  5339. *
  5340. * var me = new CoolPerson("Jacky");
  5341. *
  5342. * me.sing(); // alert("Ahem...");
  5343. * // alert("I'm on the highway to hell...");
  5344. * // alert("[Playing guitar at the same time...]");
  5345. * // alert("F#...G...D...A");
  5346. *
  5347. * # Config:
  5348. *
  5349. * Ext.define('SmartPhone', {
  5350. * config: {
  5351. * hasTouchScreen: false,
  5352. * operatingSystem: 'Other',
  5353. * price: 500
  5354. * },
  5355. *
  5356. * isExpensive: false,
  5357. *
  5358. * constructor: function(config) {
  5359. * this.initConfig(config);
  5360. *
  5361. * return this;
  5362. * },
  5363. *
  5364. * applyPrice: function(price) {
  5365. * this.isExpensive = (price > 500);
  5366. *
  5367. * return price;
  5368. * },
  5369. *
  5370. * applyOperatingSystem: function(operatingSystem) {
  5371. * if (!(/^(iOS|Android|BlackBerry)$/i).test(operatingSystem)) {
  5372. * return 'Other';
  5373. * }
  5374. *
  5375. * return operatingSystem;
  5376. * }
  5377. * });
  5378. *
  5379. * var iPhone = new SmartPhone({
  5380. * hasTouchScreen: true,
  5381. * operatingSystem: 'iOS'
  5382. * });
  5383. *
  5384. * iPhone.getPrice(); // 500;
  5385. * iPhone.getOperatingSystem(); // 'iOS'
  5386. * iPhone.getHasTouchScreen(); // true;
  5387. * iPhone.hasTouchScreen(); // true
  5388. *
  5389. * iPhone.isExpensive; // false;
  5390. * iPhone.setPrice(600);
  5391. * iPhone.getPrice(); // 600
  5392. * iPhone.isExpensive; // true;
  5393. *
  5394. * iPhone.setOperatingSystem('AlienOS');
  5395. * iPhone.getOperatingSystem(); // 'Other'
  5396. *
  5397. * # Statics:
  5398. *
  5399. * Ext.define('Computer', {
  5400. * statics: {
  5401. * factory: function(brand) {
  5402. * // 'this' in static methods refer to the class itself
  5403. * return new this(brand);
  5404. * }
  5405. * },
  5406. *
  5407. * constructor: function() { ... }
  5408. * });
  5409. *
  5410. * var dellComputer = Computer.factory('Dell');
  5411. *
  5412. * Also see {@link Ext.Base#statics} and {@link Ext.Base#self} for more details on accessing
  5413. * static properties within class methods
  5414. *
  5415. * @singleton
  5416. */
  5417. (function(Class, alias) {
  5418. var slice = Array.prototype.slice;
  5419. var Manager = Ext.ClassManager = {
  5420. /**
  5421. * @property {Object} classes
  5422. * All classes which were defined through the ClassManager. Keys are the
  5423. * name of the classes and the values are references to the classes.
  5424. * @private
  5425. */
  5426. classes: {},
  5427. /**
  5428. * @private
  5429. */
  5430. existCache: {},
  5431. /**
  5432. * @private
  5433. */
  5434. namespaceRewrites: [{
  5435. from: 'Ext.',
  5436. to: Ext
  5437. }],
  5438. /**
  5439. * @private
  5440. */
  5441. maps: {
  5442. alternateToName: {},
  5443. aliasToName: {},
  5444. nameToAliases: {}
  5445. },
  5446. /** @private */
  5447. enableNamespaceParseCache: true,
  5448. /** @private */
  5449. namespaceParseCache: {},
  5450. /** @private */
  5451. instantiators: [],
  5452. /**
  5453. * Checks if a class has already been created.
  5454. *
  5455. * @param {String} className
  5456. * @return {Boolean} exist
  5457. */
  5458. isCreated: function(className) {
  5459. var i, ln, part, root, parts;
  5460. if (this.classes.hasOwnProperty(className) || this.existCache.hasOwnProperty(className)) {
  5461. return true;
  5462. }
  5463. root = Ext.global;
  5464. parts = this.parseNamespace(className);
  5465. for (i = 0, ln = parts.length; i < ln; i++) {
  5466. part = parts[i];
  5467. if (typeof part !== 'string') {
  5468. root = part;
  5469. } else {
  5470. if (!root || !root[part]) {
  5471. return false;
  5472. }
  5473. root = root[part];
  5474. }
  5475. }
  5476. Ext.Loader.historyPush(className);
  5477. this.existCache[className] = true;
  5478. return true;
  5479. },
  5480. /**
  5481. * Supports namespace rewriting
  5482. * @private
  5483. */
  5484. parseNamespace: function(namespace) {
  5485. var cache = this.namespaceParseCache;
  5486. if (this.enableNamespaceParseCache) {
  5487. if (cache.hasOwnProperty(namespace)) {
  5488. return cache[namespace];
  5489. }
  5490. }
  5491. var parts = [],
  5492. rewrites = this.namespaceRewrites,
  5493. rewrite, from, to, i, ln, root = Ext.global;
  5494. for (i = 0, ln = rewrites.length; i < ln; i++) {
  5495. rewrite = rewrites[i];
  5496. from = rewrite.from;
  5497. to = rewrite.to;
  5498. if (namespace === from || namespace.substring(0, from.length) === from) {
  5499. namespace = namespace.substring(from.length);
  5500. if (typeof to !== 'string') {
  5501. root = to;
  5502. } else {
  5503. parts = parts.concat(to.split('.'));
  5504. }
  5505. break;
  5506. }
  5507. }
  5508. parts.push(root);
  5509. parts = parts.concat(namespace.split('.'));
  5510. if (this.enableNamespaceParseCache) {
  5511. cache[namespace] = parts;
  5512. }
  5513. return parts;
  5514. },
  5515. /**
  5516. * Creates a namespace and assign the `value` to the created object
  5517. *
  5518. * Ext.ClassManager.setNamespace('MyCompany.pkg.Example', someObject);
  5519. *
  5520. * alert(MyCompany.pkg.Example === someObject); // alerts true
  5521. *
  5522. * @param {String} name
  5523. * @param {Object} value
  5524. */
  5525. setNamespace: function(name, value) {
  5526. var root = Ext.global,
  5527. parts = this.parseNamespace(name),
  5528. ln = parts.length - 1,
  5529. leaf = parts[ln],
  5530. i, part;
  5531. for (i = 0; i < ln; i++) {
  5532. part = parts[i];
  5533. if (typeof part !== 'string') {
  5534. root = part;
  5535. } else {
  5536. if (!root[part]) {
  5537. root[part] = {};
  5538. }
  5539. root = root[part];
  5540. }
  5541. }
  5542. root[leaf] = value;
  5543. return root[leaf];
  5544. },
  5545. /**
  5546. * The new Ext.ns, supports namespace rewriting
  5547. * @private
  5548. */
  5549. createNamespaces: function() {
  5550. var root = Ext.global,
  5551. parts, part, i, j, ln, subLn;
  5552. for (i = 0, ln = arguments.length; i < ln; i++) {
  5553. parts = this.parseNamespace(arguments[i]);
  5554. for (j = 0, subLn = parts.length; j < subLn; j++) {
  5555. part = parts[j];
  5556. if (typeof part !== 'string') {
  5557. root = part;
  5558. } else {
  5559. if (!root[part]) {
  5560. root[part] = {};
  5561. }
  5562. root = root[part];
  5563. }
  5564. }
  5565. }
  5566. return root;
  5567. },
  5568. /**
  5569. * Sets a name reference to a class.
  5570. *
  5571. * @param {String} name
  5572. * @param {Object} value
  5573. * @return {Ext.ClassManager} this
  5574. */
  5575. set: function(name, value) {
  5576. var targetName = this.getName(value);
  5577. this.classes[name] = this.setNamespace(name, value);
  5578. if (targetName && targetName !== name) {
  5579. this.maps.alternateToName[name] = targetName;
  5580. }
  5581. return this;
  5582. },
  5583. /**
  5584. * Retrieve a class by its name.
  5585. *
  5586. * @param {String} name
  5587. * @return {Ext.Class} class
  5588. */
  5589. get: function(name) {
  5590. if (this.classes.hasOwnProperty(name)) {
  5591. return this.classes[name];
  5592. }
  5593. var root = Ext.global,
  5594. parts = this.parseNamespace(name),
  5595. part, i, ln;
  5596. for (i = 0, ln = parts.length; i < ln; i++) {
  5597. part = parts[i];
  5598. if (typeof part !== 'string') {
  5599. root = part;
  5600. } else {
  5601. if (!root || !root[part]) {
  5602. return null;
  5603. }
  5604. root = root[part];
  5605. }
  5606. }
  5607. return root;
  5608. },
  5609. /**
  5610. * Register the alias for a class.
  5611. *
  5612. * @param {Ext.Class/String} cls a reference to a class or a className
  5613. * @param {String} alias Alias to use when referring to this class
  5614. */
  5615. setAlias: function(cls, alias) {
  5616. var aliasToNameMap = this.maps.aliasToName,
  5617. nameToAliasesMap = this.maps.nameToAliases,
  5618. className;
  5619. if (typeof cls === 'string') {
  5620. className = cls;
  5621. } else {
  5622. className = this.getName(cls);
  5623. }
  5624. if (alias && aliasToNameMap[alias] !== className) {
  5625. aliasToNameMap[alias] = className;
  5626. }
  5627. if (!nameToAliasesMap[className]) {
  5628. nameToAliasesMap[className] = [];
  5629. }
  5630. if (alias) {
  5631. Ext.Array.include(nameToAliasesMap[className], alias);
  5632. }
  5633. return this;
  5634. },
  5635. /**
  5636. * Get a reference to the class by its alias.
  5637. *
  5638. * @param {String} alias
  5639. * @return {Ext.Class} class
  5640. */
  5641. getByAlias: function(alias) {
  5642. return this.get(this.getNameByAlias(alias));
  5643. },
  5644. /**
  5645. * Get the name of a class by its alias.
  5646. *
  5647. * @param {String} alias
  5648. * @return {String} className
  5649. */
  5650. getNameByAlias: function(alias) {
  5651. return this.maps.aliasToName[alias] || '';
  5652. },
  5653. /**
  5654. * Get the name of a class by its alternate name.
  5655. *
  5656. * @param {String} alternate
  5657. * @return {String} className
  5658. */
  5659. getNameByAlternate: function(alternate) {
  5660. return this.maps.alternateToName[alternate] || '';
  5661. },
  5662. /**
  5663. * Get the aliases of a class by the class name
  5664. *
  5665. * @param {String} name
  5666. * @return {String[]} aliases
  5667. */
  5668. getAliasesByName: function(name) {
  5669. return this.maps.nameToAliases[name] || [];
  5670. },
  5671. /**
  5672. * Get the name of the class by its reference or its instance.
  5673. *
  5674. * Ext.ClassManager.getName(Ext.Action); // returns "Ext.Action"
  5675. *
  5676. * {@link Ext#getClassName Ext.getClassName} is alias for {@link Ext.ClassManager#getName Ext.ClassManager.getName}.
  5677. *
  5678. * @param {Ext.Class/Object} object
  5679. * @return {String} className
  5680. */
  5681. getName: function(object) {
  5682. return object && object.$className || '';
  5683. },
  5684. /**
  5685. * Get the class of the provided object; returns null if it's not an instance
  5686. * of any class created with Ext.define.
  5687. *
  5688. * var component = new Ext.Component();
  5689. *
  5690. * Ext.ClassManager.getClass(component); // returns Ext.Component
  5691. *
  5692. * {@link Ext#getClass Ext.getClass} is alias for {@link Ext.ClassManager#getClass Ext.ClassManager.getClass}.
  5693. *
  5694. * @param {Object} object
  5695. * @return {Ext.Class} class
  5696. */
  5697. getClass: function(object) {
  5698. return object && object.self || null;
  5699. },
  5700. /**
  5701. * Defines a class.
  5702. *
  5703. * {@link Ext#define Ext.define} and {@link Ext.ClassManager#create Ext.ClassManager.create} are almost aliases
  5704. * of each other, with the only exception that Ext.define allows definition of {@link Ext.Class#override overrides}.
  5705. * To avoid trouble, always use Ext.define.
  5706. *
  5707. * Ext.define('My.awesome.Class', {
  5708. * someProperty: 'something',
  5709. * someMethod: function() { ... }
  5710. * ...
  5711. *
  5712. * }, function() {
  5713. * alert('Created!');
  5714. * alert(this === My.awesome.Class); // alerts true
  5715. *
  5716. * var myInstance = new this();
  5717. * });
  5718. *
  5719. * @param {String} className The class name to create in string dot-namespaced format, for example:
  5720. * `My.very.awesome.Class`, `FeedViewer.plugin.CoolPager`. It is highly recommended to follow this simple convention:
  5721. *
  5722. * - The root and the class name are 'CamelCased'
  5723. * - Everything else is lower-cased
  5724. *
  5725. * @param {Object} data The key-value pairs of properties to apply to this class. Property names can be of any valid
  5726. * strings, except those in the reserved list below:
  5727. *
  5728. * - {@link Ext.Base#self self}
  5729. * - {@link Ext.Class#alias alias}
  5730. * - {@link Ext.Class#alternateClassName alternateClassName}
  5731. * - {@link Ext.Class#config config}
  5732. * - {@link Ext.Class#extend extend}
  5733. * - {@link Ext.Class#inheritableStatics inheritableStatics}
  5734. * - {@link Ext.Class#mixins mixins}
  5735. * - {@link Ext.Class#override override} (only when using {@link Ext#define Ext.define})
  5736. * - {@link Ext.Class#requires requires}
  5737. * - {@link Ext.Class#singleton singleton}
  5738. * - {@link Ext.Class#statics statics}
  5739. * - {@link Ext.Class#uses uses}
  5740. *
  5741. * @param {Function} [createdFn] callback to execute after the class is created, the execution scope of which
  5742. * (`this`) will be the newly created class itself.
  5743. *
  5744. * @return {Ext.Base}
  5745. */
  5746. create: function(className, data, createdFn) {
  5747. var manager = this;
  5748. data.$className = className;
  5749. return new Class(data, function() {
  5750. var postprocessorStack = data.postprocessors || manager.defaultPostprocessors,
  5751. registeredPostprocessors = manager.postprocessors,
  5752. index = 0,
  5753. postprocessors = [],
  5754. postprocessor, process, i, ln;
  5755. delete data.postprocessors;
  5756. for (i = 0, ln = postprocessorStack.length; i < ln; i++) {
  5757. postprocessor = postprocessorStack[i];
  5758. if (typeof postprocessor === 'string') {
  5759. postprocessor = registeredPostprocessors[postprocessor];
  5760. if (!postprocessor.always) {
  5761. if (data[postprocessor.name] !== undefined) {
  5762. postprocessors.push(postprocessor.fn);
  5763. }
  5764. }
  5765. else {
  5766. postprocessors.push(postprocessor.fn);
  5767. }
  5768. }
  5769. else {
  5770. postprocessors.push(postprocessor);
  5771. }
  5772. }
  5773. process = function(clsName, cls, clsData) {
  5774. postprocessor = postprocessors[index++];
  5775. if (!postprocessor) {
  5776. manager.set(className, cls);
  5777. Ext.Loader.historyPush(className);
  5778. if (createdFn) {
  5779. createdFn.call(cls, cls);
  5780. }
  5781. return;
  5782. }
  5783. if (postprocessor.call(this, clsName, cls, clsData, process) !== false) {
  5784. process.apply(this, arguments);
  5785. }
  5786. };
  5787. process.call(manager, className, this, data);
  5788. });
  5789. },
  5790. /**
  5791. * Instantiate a class by its alias.
  5792. *
  5793. * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has not been defined yet, it will
  5794. * attempt to load the class via synchronous loading.
  5795. *
  5796. * var window = Ext.ClassManager.instantiateByAlias('widget.window', { width: 600, height: 800, ... });
  5797. *
  5798. * {@link Ext#createByAlias Ext.createByAlias} is alias for {@link Ext.ClassManager#instantiateByAlias Ext.ClassManager.instantiateByAlias}.
  5799. *
  5800. * @param {String} alias
  5801. * @param {Object...} args Additional arguments after the alias will be passed to the
  5802. * class constructor.
  5803. * @return {Object} instance
  5804. */
  5805. instantiateByAlias: function() {
  5806. var alias = arguments[0],
  5807. args = slice.call(arguments),
  5808. className = this.getNameByAlias(alias);
  5809. if (!className) {
  5810. className = this.maps.aliasToName[alias];
  5811. Ext.syncRequire(className);
  5812. }
  5813. args[0] = className;
  5814. return this.instantiate.apply(this, args);
  5815. },
  5816. /**
  5817. * Instantiate a class by either full name, alias or alternate name.
  5818. *
  5819. * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has not been defined yet, it will
  5820. * attempt to load the class via synchronous loading.
  5821. *
  5822. * For example, all these three lines return the same result:
  5823. *
  5824. * // alias
  5825. * var window = Ext.ClassManager.instantiate('widget.window', { width: 600, height: 800, ... });
  5826. *
  5827. * // alternate name
  5828. * var window = Ext.ClassManager.instantiate('Ext.Window', { width: 600, height: 800, ... });
  5829. *
  5830. * // full class name
  5831. * var window = Ext.ClassManager.instantiate('Ext.window.Window', { width: 600, height: 800, ... });
  5832. *
  5833. * {@link Ext#create Ext.create} is alias for {@link Ext.ClassManager#instantiate Ext.ClassManager.instantiate}.
  5834. *
  5835. * @param {String} name
  5836. * @param {Object...} args Additional arguments after the name will be passed to the class' constructor.
  5837. * @return {Object} instance
  5838. */
  5839. instantiate: function() {
  5840. var name = arguments[0],
  5841. args = slice.call(arguments, 1),
  5842. alias = name,
  5843. possibleName, cls;
  5844. if (typeof name !== 'function') {
  5845. cls = this.get(name);
  5846. }
  5847. else {
  5848. cls = name;
  5849. }
  5850. // No record of this class name, it's possibly an alias, so look it up
  5851. if (!cls) {
  5852. possibleName = this.getNameByAlias(name);
  5853. if (possibleName) {
  5854. name = possibleName;
  5855. cls = this.get(name);
  5856. }
  5857. }
  5858. // Still no record of this class name, it's possibly an alternate name, so look it up
  5859. if (!cls) {
  5860. possibleName = this.getNameByAlternate(name);
  5861. if (possibleName) {
  5862. name = possibleName;
  5863. cls = this.get(name);
  5864. }
  5865. }
  5866. // Still not existing at this point, try to load it via synchronous mode as the last resort
  5867. if (!cls) {
  5868. Ext.syncRequire(name);
  5869. cls = this.get(name);
  5870. }
  5871. return this.getInstantiator(args.length)(cls, args);
  5872. },
  5873. /**
  5874. * @private
  5875. * @param name
  5876. * @param args
  5877. */
  5878. dynInstantiate: function(name, args) {
  5879. args = Ext.Array.from(args, true);
  5880. args.unshift(name);
  5881. return this.instantiate.apply(this, args);
  5882. },
  5883. /**
  5884. * @private
  5885. * @param length
  5886. */
  5887. getInstantiator: function(length) {
  5888. if (!this.instantiators[length]) {
  5889. var i = length,
  5890. args = [];
  5891. for (i = 0; i < length; i++) {
  5892. args.push('a['+i+']');
  5893. }
  5894. this.instantiators[length] = new Function('c', 'a', 'return new c('+args.join(',')+')');
  5895. }
  5896. return this.instantiators[length];
  5897. },
  5898. /**
  5899. * @private
  5900. */
  5901. postprocessors: {},
  5902. /**
  5903. * @private
  5904. */
  5905. defaultPostprocessors: [],
  5906. /**
  5907. * Register a post-processor function.
  5908. *
  5909. * @param {String} name
  5910. * @param {Function} postprocessor
  5911. */
  5912. registerPostprocessor: function(name, fn, always) {
  5913. this.postprocessors[name] = {
  5914. name: name,
  5915. always: always || false,
  5916. fn: fn
  5917. };
  5918. return this;
  5919. },
  5920. /**
  5921. * Set the default post processors array stack which are applied to every class.
  5922. *
  5923. * @param {String/String[]} The name of a registered post processor or an array of registered names.
  5924. * @return {Ext.ClassManager} this
  5925. */
  5926. setDefaultPostprocessors: function(postprocessors) {
  5927. this.defaultPostprocessors = Ext.Array.from(postprocessors);
  5928. return this;
  5929. },
  5930. /**
  5931. * Insert this post-processor at a specific position in the stack, optionally relative to
  5932. * any existing post-processor
  5933. *
  5934. * @param {String} name The post-processor name. Note that it needs to be registered with
  5935. * {@link Ext.ClassManager#registerPostprocessor} before this
  5936. * @param {String} offset The insertion position. Four possible values are:
  5937. * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument)
  5938. * @param {String} relativeName
  5939. * @return {Ext.ClassManager} this
  5940. */
  5941. setDefaultPostprocessorPosition: function(name, offset, relativeName) {
  5942. var defaultPostprocessors = this.defaultPostprocessors,
  5943. index;
  5944. if (typeof offset === 'string') {
  5945. if (offset === 'first') {
  5946. defaultPostprocessors.unshift(name);
  5947. return this;
  5948. }
  5949. else if (offset === 'last') {
  5950. defaultPostprocessors.push(name);
  5951. return this;
  5952. }
  5953. offset = (offset === 'after') ? 1 : -1;
  5954. }
  5955. index = Ext.Array.indexOf(defaultPostprocessors, relativeName);
  5956. if (index !== -1) {
  5957. Ext.Array.splice(defaultPostprocessors, Math.max(0, index + offset), 0, name);
  5958. }
  5959. return this;
  5960. },
  5961. /**
  5962. * Converts a string expression to an array of matching class names. An expression can either refers to class aliases
  5963. * or class names. Expressions support wildcards:
  5964. *
  5965. * // returns ['Ext.window.Window']
  5966. * var window = Ext.ClassManager.getNamesByExpression('widget.window');
  5967. *
  5968. * // returns ['widget.panel', 'widget.window', ...]
  5969. * var allWidgets = Ext.ClassManager.getNamesByExpression('widget.*');
  5970. *
  5971. * // returns ['Ext.data.Store', 'Ext.data.ArrayProxy', ...]
  5972. * var allData = Ext.ClassManager.getNamesByExpression('Ext.data.*');
  5973. *
  5974. * @param {String} expression
  5975. * @return {String[]} classNames
  5976. */
  5977. getNamesByExpression: function(expression) {
  5978. var nameToAliasesMap = this.maps.nameToAliases,
  5979. names = [],
  5980. name, alias, aliases, possibleName, regex, i, ln;
  5981. if (expression.indexOf('*') !== -1) {
  5982. expression = expression.replace(/\*/g, '(.*?)');
  5983. regex = new RegExp('^' + expression + '$');
  5984. for (name in nameToAliasesMap) {
  5985. if (nameToAliasesMap.hasOwnProperty(name)) {
  5986. aliases = nameToAliasesMap[name];
  5987. if (name.search(regex) !== -1) {
  5988. names.push(name);
  5989. }
  5990. else {
  5991. for (i = 0, ln = aliases.length; i < ln; i++) {
  5992. alias = aliases[i];
  5993. if (alias.search(regex) !== -1) {
  5994. names.push(name);
  5995. break;
  5996. }
  5997. }
  5998. }
  5999. }
  6000. }
  6001. } else {
  6002. possibleName = this.getNameByAlias(expression);
  6003. if (possibleName) {
  6004. names.push(possibleName);
  6005. } else {
  6006. possibleName = this.getNameByAlternate(expression);
  6007. if (possibleName) {
  6008. names.push(possibleName);
  6009. } else {
  6010. names.push(expression);
  6011. }
  6012. }
  6013. }
  6014. return names;
  6015. }
  6016. };
  6017. var defaultPostprocessors = Manager.defaultPostprocessors;
  6018. //<feature classSystem.alias>
  6019. /**
  6020. * @cfg {String[]} alias
  6021. * @member Ext.Class
  6022. * List of short aliases for class names. Most useful for defining xtypes for widgets:
  6023. *
  6024. * Ext.define('MyApp.CoolPanel', {
  6025. * extend: 'Ext.panel.Panel',
  6026. * alias: ['widget.coolpanel'],
  6027. * title: 'Yeah!'
  6028. * });
  6029. *
  6030. * // Using Ext.create
  6031. * Ext.widget('widget.coolpanel');
  6032. * // Using the shorthand for widgets and in xtypes
  6033. * Ext.widget('panel', {
  6034. * items: [
  6035. * {xtype: 'coolpanel', html: 'Foo'},
  6036. * {xtype: 'coolpanel', html: 'Bar'}
  6037. * ]
  6038. * });
  6039. */
  6040. Manager.registerPostprocessor('alias', function(name, cls, data) {
  6041. var aliases = data.alias,
  6042. i, ln;
  6043. delete data.alias;
  6044. for (i = 0, ln = aliases.length; i < ln; i++) {
  6045. alias = aliases[i];
  6046. this.setAlias(cls, alias);
  6047. }
  6048. });
  6049. /**
  6050. * @cfg {Boolean} singleton
  6051. * @member Ext.Class
  6052. * When set to true, the class will be instantiated as singleton. For example:
  6053. *
  6054. * Ext.define('Logger', {
  6055. * singleton: true,
  6056. * log: function(msg) {
  6057. * console.log(msg);
  6058. * }
  6059. * });
  6060. *
  6061. * Logger.log('Hello');
  6062. */
  6063. Manager.registerPostprocessor('singleton', function(name, cls, data, fn) {
  6064. fn.call(this, name, new cls(), data);
  6065. return false;
  6066. });
  6067. /**
  6068. * @cfg {String/String[]} alternateClassName
  6069. * @member Ext.Class
  6070. * Defines alternate names for this class. For example:
  6071. *
  6072. * Ext.define('Developer', {
  6073. * alternateClassName: ['Coder', 'Hacker'],
  6074. * code: function(msg) {
  6075. * alert('Typing... ' + msg);
  6076. * }
  6077. * });
  6078. *
  6079. * var joe = Ext.create('Developer');
  6080. * joe.code('stackoverflow');
  6081. *
  6082. * var rms = Ext.create('Hacker');
  6083. * rms.code('hack hack');
  6084. */
  6085. Manager.registerPostprocessor('alternateClassName', function(name, cls, data) {
  6086. var alternates = data.alternateClassName,
  6087. i, ln, alternate;
  6088. if (!(alternates instanceof Array)) {
  6089. alternates = [alternates];
  6090. }
  6091. for (i = 0, ln = alternates.length; i < ln; i++) {
  6092. alternate = alternates[i];
  6093. this.set(alternate, cls);
  6094. }
  6095. });
  6096. Manager.setDefaultPostprocessors(['alias', 'singleton', 'alternateClassName']);
  6097. Ext.apply(Ext, {
  6098. /**
  6099. * @method
  6100. * @member Ext
  6101. * @alias Ext.ClassManager#instantiate
  6102. */
  6103. create: alias(Manager, 'instantiate'),
  6104. /**
  6105. * @private
  6106. * API to be stablized
  6107. *
  6108. * @param {Object} item
  6109. * @param {String} namespace
  6110. */
  6111. factory: function(item, namespace) {
  6112. if (item instanceof Array) {
  6113. var i, ln;
  6114. for (i = 0, ln = item.length; i < ln; i++) {
  6115. item[i] = Ext.factory(item[i], namespace);
  6116. }
  6117. return item;
  6118. }
  6119. var isString = (typeof item === 'string');
  6120. if (isString || (item instanceof Object && item.constructor === Object)) {
  6121. var name, config = {};
  6122. if (isString) {
  6123. name = item;
  6124. }
  6125. else {
  6126. name = item.className;
  6127. config = item;
  6128. delete config.className;
  6129. }
  6130. if (namespace !== undefined && name.indexOf(namespace) === -1) {
  6131. name = namespace + '.' + Ext.String.capitalize(name);
  6132. }
  6133. return Ext.create(name, config);
  6134. }
  6135. if (typeof item === 'function') {
  6136. return Ext.create(item);
  6137. }
  6138. return item;
  6139. },
  6140. /**
  6141. * Convenient shorthand to create a widget by its xtype, also see {@link Ext.ClassManager#instantiateByAlias}
  6142. *
  6143. * var button = Ext.widget('button'); // Equivalent to Ext.create('widget.button')
  6144. * var panel = Ext.widget('panel'); // Equivalent to Ext.create('widget.panel')
  6145. *
  6146. * @method
  6147. * @member Ext
  6148. * @param {String} name xtype of the widget to create.
  6149. * @param {Object...} args arguments for the widget constructor.
  6150. * @return {Object} widget instance
  6151. */
  6152. widget: function(name) {
  6153. var args = slice.call(arguments);
  6154. args[0] = 'widget.' + name;
  6155. return Manager.instantiateByAlias.apply(Manager, args);
  6156. },
  6157. /**
  6158. * @method
  6159. * @member Ext
  6160. * @alias Ext.ClassManager#instantiateByAlias
  6161. */
  6162. createByAlias: alias(Manager, 'instantiateByAlias'),
  6163. /**
  6164. * @cfg {String} override
  6165. * @member Ext.Class
  6166. *
  6167. * Defines an override applied to a class. Note that **overrides can only be created using
  6168. * {@link Ext#define}.** {@link Ext.ClassManager#create} only creates classes.
  6169. *
  6170. * To define an override, include the override property. The content of an override is
  6171. * aggregated with the specified class in order to extend or modify that class. This can be
  6172. * as simple as setting default property values or it can extend and/or replace methods.
  6173. * This can also extend the statics of the class.
  6174. *
  6175. * One use for an override is to break a large class into manageable pieces.
  6176. *
  6177. * // File: /src/app/Panel.js
  6178. *
  6179. * Ext.define('My.app.Panel', {
  6180. * extend: 'Ext.panel.Panel',
  6181. * requires: [
  6182. * 'My.app.PanelPart2',
  6183. * 'My.app.PanelPart3'
  6184. * ]
  6185. *
  6186. * constructor: function (config) {
  6187. * this.callSuper(arguments); // calls Ext.panel.Panel's constructor
  6188. * //...
  6189. * },
  6190. *
  6191. * statics: {
  6192. * method: function () {
  6193. * return 'abc';
  6194. * }
  6195. * }
  6196. * });
  6197. *
  6198. * // File: /src/app/PanelPart2.js
  6199. * Ext.define('My.app.PanelPart2', {
  6200. * override: 'My.app.Panel',
  6201. *
  6202. * constructor: function (config) {
  6203. * this.callSuper(arguments); // calls My.app.Panel's constructor
  6204. * //...
  6205. * }
  6206. * });
  6207. *
  6208. * Another use of overrides is to provide optional parts of classes that can be
  6209. * independently required. In this case, the class may even be unaware of the
  6210. * override altogether.
  6211. *
  6212. * Ext.define('My.ux.CoolTip', {
  6213. * override: 'Ext.tip.ToolTip',
  6214. *
  6215. * constructor: function (config) {
  6216. * this.callSuper(arguments); // calls Ext.tip.ToolTip's constructor
  6217. * //...
  6218. * }
  6219. * });
  6220. *
  6221. * The above override can now be required as normal.
  6222. *
  6223. * Ext.define('My.app.App', {
  6224. * requires: [
  6225. * 'My.ux.CoolTip'
  6226. * ]
  6227. * });
  6228. *
  6229. * Overrides can also contain statics:
  6230. *
  6231. * Ext.define('My.app.BarMod', {
  6232. * override: 'Ext.foo.Bar',
  6233. *
  6234. * statics: {
  6235. * method: function (x) {
  6236. * return this.callSuper([x * 2]); // call Ext.foo.Bar.method
  6237. * }
  6238. * }
  6239. * });
  6240. *
  6241. * IMPORTANT: An override is only included in a build if the class it overrides is
  6242. * required. Otherwise, the override, like the target class, is not included.
  6243. */
  6244. /**
  6245. * @method
  6246. *
  6247. * @member Ext
  6248. * @alias Ext.ClassManager#create
  6249. */
  6250. define: function (className, data, createdFn) {
  6251. if (!data.override) {
  6252. return Manager.create.apply(Manager, arguments);
  6253. }
  6254. var requires = data.requires,
  6255. uses = data.uses,
  6256. overrideName = className;
  6257. className = data.override;
  6258. // hoist any 'requires' or 'uses' from the body onto the faux class:
  6259. data = Ext.apply({}, data);
  6260. delete data.requires;
  6261. delete data.uses;
  6262. delete data.override;
  6263. // make sure className is in the requires list:
  6264. if (typeof requires == 'string') {
  6265. requires = [ className, requires ];
  6266. } else if (requires) {
  6267. requires = requires.slice(0);
  6268. requires.unshift(className);
  6269. } else {
  6270. requires = [ className ];
  6271. }
  6272. // TODO - we need to rework this to allow the override to not require the target class
  6273. // and rather 'wait' for it in such a way that if the target class is not in the build,
  6274. // neither are any of its overrides.
  6275. //
  6276. // Also, this should process the overrides for a class ASAP (ideally before any derived
  6277. // classes) if the target class 'requires' the overrides. Without some special handling, the
  6278. // overrides so required will be processed before the class and have to be bufferred even
  6279. // in a build.
  6280. //
  6281. // TODO - we should probably support the "config" processor on an override (to config new
  6282. // functionaliy like Aria) and maybe inheritableStatics (although static is now supported
  6283. // by callSuper). If inheritableStatics causes those statics to be included on derived class
  6284. // constructors, that probably means "no" to this since an override can come after other
  6285. // classes extend the target.
  6286. return Manager.create(overrideName, {
  6287. requires: requires,
  6288. uses: uses,
  6289. isPartial: true,
  6290. constructor: function () {
  6291. }
  6292. }, function () {
  6293. var cls = Manager.get(className);
  6294. if (cls.override) { // if (normal class)
  6295. cls.override(data);
  6296. } else { // else (singleton)
  6297. cls.self.override(data);
  6298. }
  6299. if (createdFn) {
  6300. // called once the override is applied and with the context of the
  6301. // overridden class (the override itself is a meaningless, name-only
  6302. // thing).
  6303. createdFn.call(cls);
  6304. }
  6305. });
  6306. },
  6307. /**
  6308. * @method
  6309. * @member Ext
  6310. * @alias Ext.ClassManager#getName
  6311. */
  6312. getClassName: alias(Manager, 'getName'),
  6313. /**
  6314. * Returns the displayName property or className or object.
  6315. * When all else fails, returns "Anonymous".
  6316. * @param {Object} object
  6317. * @return {String}
  6318. */
  6319. getDisplayName: function(object) {
  6320. if (object.displayName) {
  6321. return object.displayName;
  6322. }
  6323. if (object.$name && object.$class) {
  6324. return Ext.getClassName(object.$class) + '#' + object.$name;
  6325. }
  6326. if (object.$className) {
  6327. return object.$className;
  6328. }
  6329. return 'Anonymous';
  6330. },
  6331. /**
  6332. * @method
  6333. * @member Ext
  6334. * @alias Ext.ClassManager#getClass
  6335. */
  6336. getClass: alias(Manager, 'getClass'),
  6337. /**
  6338. * Creates namespaces to be used for scoping variables and classes so that they are not global.
  6339. * Specifying the last node of a namespace implicitly creates all other nodes. Usage:
  6340. *
  6341. * Ext.namespace('Company', 'Company.data');
  6342. *
  6343. * // equivalent and preferable to the above syntax
  6344. * Ext.namespace('Company.data');
  6345. *
  6346. * Company.Widget = function() { ... };
  6347. *
  6348. * Company.data.CustomStore = function(config) { ... };
  6349. *
  6350. * @method
  6351. * @member Ext
  6352. * @param {String} namespace1
  6353. * @param {String} namespace2
  6354. * @param {String} etc
  6355. * @return {Object} The namespace object. (If multiple arguments are passed, this will be the last namespace created)
  6356. */
  6357. namespace: alias(Manager, 'createNamespaces')
  6358. });
  6359. /**
  6360. * Old name for {@link Ext#widget}.
  6361. * @deprecated 4.0.0 Use {@link Ext#widget} instead.
  6362. * @method
  6363. * @member Ext
  6364. * @alias Ext#widget
  6365. */
  6366. Ext.createWidget = Ext.widget;
  6367. /**
  6368. * Convenient alias for {@link Ext#namespace Ext.namespace}
  6369. * @method
  6370. * @member Ext
  6371. * @alias Ext#namespace
  6372. */
  6373. Ext.ns = Ext.namespace;
  6374. Class.registerPreprocessor('className', function(cls, data) {
  6375. if (data.$className) {
  6376. cls.$className = data.$className;
  6377. }
  6378. }, true);
  6379. Class.setDefaultPreprocessorPosition('className', 'first');
  6380. Class.registerPreprocessor('xtype', function(cls, data) {
  6381. var xtypes = Ext.Array.from(data.xtype),
  6382. widgetPrefix = 'widget.',
  6383. aliases = Ext.Array.from(data.alias),
  6384. i, ln, xtype;
  6385. data.xtype = xtypes[0];
  6386. data.xtypes = xtypes;
  6387. aliases = data.alias = Ext.Array.from(data.alias);
  6388. for (i = 0,ln = xtypes.length; i < ln; i++) {
  6389. xtype = xtypes[i];
  6390. aliases.push(widgetPrefix + xtype);
  6391. }
  6392. data.alias = aliases;
  6393. });
  6394. Class.setDefaultPreprocessorPosition('xtype', 'last');
  6395. Class.registerPreprocessor('alias', function(cls, data) {
  6396. var aliases = Ext.Array.from(data.alias),
  6397. xtypes = Ext.Array.from(data.xtypes),
  6398. widgetPrefix = 'widget.',
  6399. widgetPrefixLength = widgetPrefix.length,
  6400. i, ln, alias, xtype;
  6401. for (i = 0, ln = aliases.length; i < ln; i++) {
  6402. alias = aliases[i];
  6403. if (alias.substring(0, widgetPrefixLength) === widgetPrefix) {
  6404. xtype = alias.substring(widgetPrefixLength);
  6405. Ext.Array.include(xtypes, xtype);
  6406. if (!cls.xtype) {
  6407. cls.xtype = data.xtype = xtype;
  6408. }
  6409. }
  6410. }
  6411. data.alias = aliases;
  6412. data.xtypes = xtypes;
  6413. });
  6414. Class.setDefaultPreprocessorPosition('alias', 'last');
  6415. })(Ext.Class, Ext.Function.alias);
  6416. /**
  6417. * @class Ext.Loader
  6418. * @singleton
  6419. * @author Jacky Nguyen <jacky@sencha.com>
  6420. * @docauthor Jacky Nguyen <jacky@sencha.com>
  6421. *
  6422. * Ext.Loader is the heart of the new dynamic dependency loading capability in Ext JS 4+. It is most commonly used
  6423. * via the {@link Ext#require} shorthand. Ext.Loader supports both asynchronous and synchronous loading
  6424. * approaches, and leverage their advantages for the best development flow. We'll discuss about the pros and cons
  6425. * of each approach:
  6426. *
  6427. * # Asynchronous Loading
  6428. *
  6429. * - Advantages:
  6430. * + Cross-domain
  6431. * + No web server needed: you can run the application via the file system protocol
  6432. * (i.e: `file://path/to/your/index.html`)
  6433. * + Best possible debugging experience: error messages come with the exact file name and line number
  6434. *
  6435. * - Disadvantages:
  6436. * + Dependencies need to be specified before-hand
  6437. *
  6438. * ### Method 1: Explicitly include what you need:
  6439. *
  6440. * // Syntax
  6441. * Ext.require({String/Array} expressions);
  6442. *
  6443. * // Example: Single alias
  6444. * Ext.require('widget.window');
  6445. *
  6446. * // Example: Single class name
  6447. * Ext.require('Ext.window.Window');
  6448. *
  6449. * // Example: Multiple aliases / class names mix
  6450. * Ext.require(['widget.window', 'layout.border', 'Ext.data.Connection']);
  6451. *
  6452. * // Wildcards
  6453. * Ext.require(['widget.*', 'layout.*', 'Ext.data.*']);
  6454. *
  6455. * ### Method 2: Explicitly exclude what you don't need:
  6456. *
  6457. * // Syntax: Note that it must be in this chaining format.
  6458. * Ext.exclude({String/Array} expressions)
  6459. * .require({String/Array} expressions);
  6460. *
  6461. * // Include everything except Ext.data.*
  6462. * Ext.exclude('Ext.data.*').require('*'); 
  6463. *
  6464. * // Include all widgets except widget.checkbox*,
  6465. * // which will match widget.checkbox, widget.checkboxfield, widget.checkboxgroup, etc.
  6466. * Ext.exclude('widget.checkbox*').require('widget.*');
  6467. *
  6468. * # Synchronous Loading on Demand
  6469. *
  6470. * - Advantages:
  6471. * + There's no need to specify dependencies before-hand, which is always the convenience of including
  6472. * ext-all.js before
  6473. *
  6474. * - Disadvantages:
  6475. * + Not as good debugging experience since file name won't be shown (except in Firebug at the moment)
  6476. * + Must be from the same domain due to XHR restriction
  6477. * + Need a web server, same reason as above
  6478. *
  6479. * There's one simple rule to follow: Instantiate everything with Ext.create instead of the `new` keyword
  6480. *
  6481. * Ext.create('widget.window', { ... }); // Instead of new Ext.window.Window({...});
  6482. *
  6483. * Ext.create('Ext.window.Window', {}); // Same as above, using full class name instead of alias
  6484. *
  6485. * Ext.widget('window', {}); // Same as above, all you need is the traditional `xtype`
  6486. *
  6487. * Behind the scene, {@link Ext.ClassManager} will automatically check whether the given class name / alias has already
  6488. * existed on the page. If it's not, Ext.Loader will immediately switch itself to synchronous mode and automatic load
  6489. * the given class and all its dependencies.
  6490. *
  6491. * # Hybrid Loading - The Best of Both Worlds
  6492. *
  6493. * It has all the advantages combined from asynchronous and synchronous loading. The development flow is simple:
  6494. *
  6495. * ### Step 1: Start writing your application using synchronous approach.
  6496. *
  6497. * Ext.Loader will automatically fetch all dependencies on demand as they're needed during run-time. For example:
  6498. *
  6499. * Ext.onReady(function(){
  6500. * var window = Ext.createWidget('window', {
  6501. * width: 500,
  6502. * height: 300,
  6503. * layout: {
  6504. * type: 'border',
  6505. * padding: 5
  6506. * },
  6507. * title: 'Hello Dialog',
  6508. * items: [{
  6509. * title: 'Navigation',
  6510. * collapsible: true,
  6511. * region: 'west',
  6512. * width: 200,
  6513. * html: 'Hello',
  6514. * split: true
  6515. * }, {
  6516. * title: 'TabPanel',
  6517. * region: 'center'
  6518. * }]
  6519. * });
  6520. *
  6521. * window.show();
  6522. * })
  6523. *
  6524. * ### Step 2: Along the way, when you need better debugging ability, watch the console for warnings like these:
  6525. *
  6526. * [Ext.Loader] Synchronously loading 'Ext.window.Window'; consider adding Ext.require('Ext.window.Window') before your application's code ClassManager.js:432
  6527. * [Ext.Loader] Synchronously loading 'Ext.layout.container.Border'; consider adding Ext.require('Ext.layout.container.Border') before your application's code
  6528. *
  6529. * Simply copy and paste the suggested code above `Ext.onReady`, e.g.:
  6530. *
  6531. * Ext.require('Ext.window.Window');
  6532. * Ext.require('Ext.layout.container.Border');
  6533. *
  6534. * Ext.onReady(...);
  6535. *
  6536. * Everything should now load via asynchronous mode.
  6537. *
  6538. * # Deployment
  6539. *
  6540. * It's important to note that dynamic loading should only be used during development on your local machines.
  6541. * During production, all dependencies should be combined into one single JavaScript file. Ext.Loader makes
  6542. * the whole process of transitioning from / to between development / maintenance and production as easy as
  6543. * possible. Internally {@link Ext.Loader#history Ext.Loader.history} maintains the list of all dependencies
  6544. * your application needs in the exact loading sequence. It's as simple as concatenating all files in this
  6545. * array into one, then include it on top of your application.
  6546. *
  6547. * This process will be automated with Sencha Command, to be released and documented towards Ext JS 4 Final.
  6548. */
  6549. (function(Manager, Class, flexSetter, alias) {
  6550. var
  6551. dependencyProperties = ['extend', 'mixins', 'requires'],
  6552. Loader;
  6553. Loader = Ext.Loader = {
  6554. /**
  6555. * @private
  6556. */
  6557. documentHead: typeof document !== 'undefined' && (document.head || document.getElementsByTagName('head')[0]),
  6558. /**
  6559. * Flag indicating whether there are still files being loaded
  6560. * @private
  6561. */
  6562. isLoading: false,
  6563. /**
  6564. * Maintain the queue for all dependencies. Each item in the array is an object of the format:
  6565. * {
  6566. * requires: [...], // The required classes for this queue item
  6567. * callback: function() { ... } // The function to execute when all classes specified in requires exist
  6568. * }
  6569. * @private
  6570. */
  6571. queue: [],
  6572. /**
  6573. * Maintain the list of files that have already been handled so that they never get double-loaded
  6574. * @private
  6575. */
  6576. isFileLoaded: {},
  6577. /**
  6578. * Maintain the list of listeners to execute when all required scripts are fully loaded
  6579. * @private
  6580. */
  6581. readyListeners: [],
  6582. /**
  6583. * Contains optional dependencies to be loaded last
  6584. * @private
  6585. */
  6586. optionalRequires: [],
  6587. /**
  6588. * Map of fully qualified class names to an array of dependent classes.
  6589. * @private
  6590. */
  6591. requiresMap: {},
  6592. /**
  6593. * @private
  6594. */
  6595. numPendingFiles: 0,
  6596. /**
  6597. * @private
  6598. */
  6599. numLoadedFiles: 0,
  6600. /** @private */
  6601. hasFileLoadError: false,
  6602. /**
  6603. * @private
  6604. */
  6605. classNameToFilePathMap: {},
  6606. /**
  6607. * @property {String[]} history
  6608. * An array of class names to keep track of the dependency loading order.
  6609. * This is not guaranteed to be the same everytime due to the asynchronous nature of the Loader.
  6610. */
  6611. history: [],
  6612. /**
  6613. * Configuration
  6614. * @private
  6615. */
  6616. config: {
  6617. /**
  6618. * @cfg {Boolean} enabled
  6619. * Whether or not to enable the dynamic dependency loading feature.
  6620. */
  6621. enabled: false,
  6622. /**
  6623. * @cfg {Boolean} disableCaching
  6624. * Appends current timestamp to script files to prevent caching.
  6625. */
  6626. disableCaching: true,
  6627. /**
  6628. * @cfg {String} disableCachingParam
  6629. * The get parameter name for the cache buster's timestamp.
  6630. */
  6631. disableCachingParam: '_dc',
  6632. /**
  6633. * @cfg {Object} paths
  6634. * The mapping from namespaces to file paths
  6635. *
  6636. * {
  6637. * 'Ext': '.', // This is set by default, Ext.layout.container.Container will be
  6638. * // loaded from ./layout/Container.js
  6639. *
  6640. * 'My': './src/my_own_folder' // My.layout.Container will be loaded from
  6641. * // ./src/my_own_folder/layout/Container.js
  6642. * }
  6643. *
  6644. * Note that all relative paths are relative to the current HTML document.
  6645. * If not being specified, for example, `Other.awesome.Class`
  6646. * will simply be loaded from `./Other/awesome/Class.js`
  6647. */
  6648. paths: {
  6649. 'Ext': '.'
  6650. }
  6651. },
  6652. /**
  6653. * Set the configuration for the loader. This should be called right after ext-core.js
  6654. * (or ext-core-debug.js) is included in the page, e.g.:
  6655. *
  6656. * <script type="text/javascript" src="ext-core-debug.js"></script>
  6657. * <script type="text/javascript">
  6658. * Ext.Loader.setConfig({
  6659. * enabled: true,
  6660. * paths: {
  6661. * 'My': 'my_own_path'
  6662. * }
  6663. * });
  6664. * <script>
  6665. * <script type="text/javascript">
  6666. * Ext.require(...);
  6667. *
  6668. * Ext.onReady(function() {
  6669. * // application code here
  6670. * });
  6671. * </script>
  6672. *
  6673. * Refer to config options of {@link Ext.Loader} for the list of possible properties.
  6674. *
  6675. * @param {String/Object} name Name of the value to override, or a config object to override multiple values.
  6676. * @param {Object} value (optional) The new value to set, needed if first parameter is String.
  6677. * @return {Ext.Loader} this
  6678. */
  6679. setConfig: function(name, value) {
  6680. if (Ext.isObject(name) && arguments.length === 1) {
  6681. Ext.Object.merge(this.config, name);
  6682. }
  6683. else {
  6684. this.config[name] = (Ext.isObject(value)) ? Ext.Object.merge(this.config[name], value) : value;
  6685. }
  6686. return this;
  6687. },
  6688. /**
  6689. * Get the config value corresponding to the specified name.
  6690. * If no name is given, will return the config object.
  6691. * @param {String} name The config property name
  6692. * @return {Object}
  6693. */
  6694. getConfig: function(name) {
  6695. if (name) {
  6696. return this.config[name];
  6697. }
  6698. return this.config;
  6699. },
  6700. /**
  6701. * Sets the path of a namespace. For Example:
  6702. *
  6703. * Ext.Loader.setPath('Ext', '.');
  6704. *
  6705. * @param {String/Object} name See {@link Ext.Function#flexSetter flexSetter}
  6706. * @param {String} path See {@link Ext.Function#flexSetter flexSetter}
  6707. * @return {Ext.Loader} this
  6708. * @method
  6709. */
  6710. setPath: flexSetter(function(name, path) {
  6711. this.config.paths[name] = path;
  6712. return this;
  6713. }),
  6714. /**
  6715. * Translates a className to a file path by adding the the proper prefix and converting the .'s to /'s.
  6716. * For example:
  6717. *
  6718. * Ext.Loader.setPath('My', '/path/to/My');
  6719. *
  6720. * alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/path/to/My/awesome/Class.js'
  6721. *
  6722. * Note that the deeper namespace levels, if explicitly set, are always resolved first. For example:
  6723. *
  6724. * Ext.Loader.setPath({
  6725. * 'My': '/path/to/lib',
  6726. * 'My.awesome': '/other/path/for/awesome/stuff',
  6727. * 'My.awesome.more': '/more/awesome/path'
  6728. * });
  6729. *
  6730. * alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/other/path/for/awesome/stuff/Class.js'
  6731. *
  6732. * alert(Ext.Loader.getPath('My.awesome.more.Class')); // alerts '/more/awesome/path/Class.js'
  6733. *
  6734. * alert(Ext.Loader.getPath('My.cool.Class')); // alerts '/path/to/lib/cool/Class.js'
  6735. *
  6736. * alert(Ext.Loader.getPath('Unknown.strange.Stuff')); // alerts 'Unknown/strange/Stuff.js'
  6737. *
  6738. * @param {String} className
  6739. * @return {String} path
  6740. */
  6741. getPath: function(className) {
  6742. var path = '',
  6743. paths = this.config.paths,
  6744. prefix = this.getPrefix(className);
  6745. if (prefix.length > 0) {
  6746. if (prefix === className) {
  6747. return paths[prefix];
  6748. }
  6749. path = paths[prefix];
  6750. className = className.substring(prefix.length + 1);
  6751. }
  6752. if (path.length > 0) {
  6753. path += '/';
  6754. }
  6755. return path.replace(/\/\.\//g, '/') + className.replace(/\./g, "/") + '.js';
  6756. },
  6757. /**
  6758. * @private
  6759. * @param {String} className
  6760. */
  6761. getPrefix: function(className) {
  6762. var paths = this.config.paths,
  6763. prefix, deepestPrefix = '';
  6764. if (paths.hasOwnProperty(className)) {
  6765. return className;
  6766. }
  6767. for (prefix in paths) {
  6768. if (paths.hasOwnProperty(prefix) && prefix + '.' === className.substring(0, prefix.length + 1)) {
  6769. if (prefix.length > deepestPrefix.length) {
  6770. deepestPrefix = prefix;
  6771. }
  6772. }
  6773. }
  6774. return deepestPrefix;
  6775. },
  6776. /**
  6777. * Refresh all items in the queue. If all dependencies for an item exist during looping,
  6778. * it will execute the callback and call refreshQueue again. Triggers onReady when the queue is
  6779. * empty
  6780. * @private
  6781. */
  6782. refreshQueue: function() {
  6783. var ln = this.queue.length,
  6784. i, item, j, requires;
  6785. if (ln === 0) {
  6786. this.triggerReady();
  6787. return;
  6788. }
  6789. for (i = 0; i < ln; i++) {
  6790. item = this.queue[i];
  6791. if (item) {
  6792. requires = item.requires;
  6793. // Don't bother checking when the number of files loaded
  6794. // is still less than the array length
  6795. if (requires.length > this.numLoadedFiles) {
  6796. continue;
  6797. }
  6798. j = 0;
  6799. do {
  6800. if (Manager.isCreated(requires[j])) {
  6801. // Take out from the queue
  6802. Ext.Array.erase(requires, j, 1);
  6803. }
  6804. else {
  6805. j++;
  6806. }
  6807. } while (j < requires.length);
  6808. if (item.requires.length === 0) {
  6809. Ext.Array.erase(this.queue, i, 1);
  6810. item.callback.call(item.scope);
  6811. this.refreshQueue();
  6812. break;
  6813. }
  6814. }
  6815. }
  6816. return this;
  6817. },
  6818. /**
  6819. * Inject a script element to document's head, call onLoad and onError accordingly
  6820. * @private
  6821. */
  6822. injectScriptElement: function(url, onLoad, onError, scope) {
  6823. var script = document.createElement('script'),
  6824. me = this,
  6825. onLoadFn = function() {
  6826. me.cleanupScriptElement(script);
  6827. onLoad.call(scope);
  6828. },
  6829. onErrorFn = function() {
  6830. me.cleanupScriptElement(script);
  6831. onError.call(scope);
  6832. };
  6833. script.type = 'text/javascript';
  6834. script.src = url;
  6835. script.onload = onLoadFn;
  6836. script.onerror = onErrorFn;
  6837. script.onreadystatechange = function() {
  6838. if (this.readyState === 'loaded' || this.readyState === 'complete') {
  6839. onLoadFn();
  6840. }
  6841. };
  6842. this.documentHead.appendChild(script);
  6843. return script;
  6844. },
  6845. /**
  6846. * @private
  6847. */
  6848. cleanupScriptElement: function(script) {
  6849. script.onload = null;
  6850. script.onreadystatechange = null;
  6851. script.onerror = null;
  6852. return this;
  6853. },
  6854. /**
  6855. * Load a script file, supports both asynchronous and synchronous approaches
  6856. *
  6857. * @param {String} url
  6858. * @param {Function} onLoad
  6859. * @param {Object} scope
  6860. * @param {Boolean} synchronous
  6861. * @private
  6862. */
  6863. loadScriptFile: function(url, onLoad, onError, scope, synchronous) {
  6864. var me = this,
  6865. noCacheUrl = url + (this.getConfig('disableCaching') ? ('?' + this.getConfig('disableCachingParam') + '=' + Ext.Date.now()) : ''),
  6866. fileName = url.split('/').pop(),
  6867. isCrossOriginRestricted = false,
  6868. xhr, status, onScriptError;
  6869. scope = scope || this;
  6870. this.isLoading = true;
  6871. if (!synchronous) {
  6872. onScriptError = function() {
  6873. onError.call(scope, "Failed loading '" + url + "', please verify that the file exists", synchronous);
  6874. };
  6875. if (!Ext.isReady && Ext.onDocumentReady) {
  6876. Ext.onDocumentReady(function() {
  6877. me.injectScriptElement(noCacheUrl, onLoad, onScriptError, scope);
  6878. });
  6879. }
  6880. else {
  6881. this.injectScriptElement(noCacheUrl, onLoad, onScriptError, scope);
  6882. }
  6883. }
  6884. else {
  6885. if (typeof XMLHttpRequest !== 'undefined') {
  6886. xhr = new XMLHttpRequest();
  6887. } else {
  6888. xhr = new ActiveXObject('Microsoft.XMLHTTP');
  6889. }
  6890. try {
  6891. xhr.open('GET', noCacheUrl, false);
  6892. xhr.send(null);
  6893. } catch (e) {
  6894. isCrossOriginRestricted = true;
  6895. }
  6896. status = (xhr.status === 1223) ? 204 : xhr.status;
  6897. if (!isCrossOriginRestricted) {
  6898. isCrossOriginRestricted = (status === 0);
  6899. }
  6900. if (isCrossOriginRestricted
  6901. ) {
  6902. onError.call(this, "Failed loading synchronously via XHR: '" + url + "'; It's likely that the file is either " +
  6903. "being loaded from a different domain or from the local file system whereby cross origin " +
  6904. "requests are not allowed due to security reasons. Use asynchronous loading with " +
  6905. "Ext.require instead.", synchronous);
  6906. }
  6907. else if (status >= 200 && status < 300
  6908. ) {
  6909. // Firebug friendly, file names are still shown even though they're eval'ed code
  6910. new Function(xhr.responseText + "\n//@ sourceURL=" + fileName)();
  6911. onLoad.call(scope);
  6912. }
  6913. else {
  6914. onError.call(this, "Failed loading synchronously via XHR: '" + url + "'; please " +
  6915. "verify that the file exists. " +
  6916. "XHR status code: " + status, synchronous);
  6917. }
  6918. // Prevent potential IE memory leak
  6919. xhr = null;
  6920. }
  6921. },
  6922. /**
  6923. * Explicitly exclude files from being loaded. Useful when used in conjunction with a broad include expression.
  6924. * Can be chained with more `require` and `exclude` methods, e.g.:
  6925. *
  6926. * Ext.exclude('Ext.data.*').require('*');
  6927. *
  6928. * Ext.exclude('widget.button*').require('widget.*');
  6929. *
  6930. * {@link Ext#exclude Ext.exclude} is alias for {@link Ext.Loader#exclude Ext.Loader.exclude} for convenience.
  6931. *
  6932. * @param {String/String[]} excludes
  6933. * @return {Object} object contains `require` method for chaining
  6934. */
  6935. exclude: function(excludes) {
  6936. var me = this;
  6937. return {
  6938. require: function(expressions, fn, scope) {
  6939. return me.require(expressions, fn, scope, excludes);
  6940. },
  6941. syncRequire: function(expressions, fn, scope) {
  6942. return me.syncRequire(expressions, fn, scope, excludes);
  6943. }
  6944. };
  6945. },
  6946. /**
  6947. * Synchronously loads all classes by the given names and all their direct dependencies;
  6948. * optionally executes the given callback function when finishes, within the optional scope.
  6949. *
  6950. * {@link Ext#syncRequire Ext.syncRequire} is alias for {@link Ext.Loader#syncRequire Ext.Loader.syncRequire} for convenience.
  6951. *
  6952. * @param {String/String[]} expressions Can either be a string or an array of string
  6953. * @param {Function} fn (Optional) The callback function
  6954. * @param {Object} scope (Optional) The execution scope (`this`) of the callback function
  6955. * @param {String/String[]} excludes (Optional) Classes to be excluded, useful when being used with expressions
  6956. */
  6957. syncRequire: function() {
  6958. this.syncModeEnabled = true;
  6959. this.require.apply(this, arguments);
  6960. this.refreshQueue();
  6961. this.syncModeEnabled = false;
  6962. },
  6963. /**
  6964. * Loads all classes by the given names and all their direct dependencies;
  6965. * optionally executes the given callback function when finishes, within the optional scope.
  6966. *
  6967. * {@link Ext#require Ext.require} is alias for {@link Ext.Loader#require Ext.Loader.require} for convenience.
  6968. *
  6969. * @param {String/String[]} expressions Can either be a string or an array of string
  6970. * @param {Function} fn (Optional) The callback function
  6971. * @param {Object} scope (Optional) The execution scope (`this`) of the callback function
  6972. * @param {String/String[]} excludes (Optional) Classes to be excluded, useful when being used with expressions
  6973. */
  6974. require: function(expressions, fn, scope, excludes) {
  6975. var filePath, expression, exclude, className, excluded = {},
  6976. excludedClassNames = [],
  6977. possibleClassNames = [],
  6978. possibleClassName, classNames = [],
  6979. i, j, ln, subLn;
  6980. expressions = Ext.Array.from(expressions);
  6981. excludes = Ext.Array.from(excludes);
  6982. fn = fn || Ext.emptyFn;
  6983. scope = scope || Ext.global;
  6984. for (i = 0, ln = excludes.length; i < ln; i++) {
  6985. exclude = excludes[i];
  6986. if (typeof exclude === 'string' && exclude.length > 0) {
  6987. excludedClassNames = Manager.getNamesByExpression(exclude);
  6988. for (j = 0, subLn = excludedClassNames.length; j < subLn; j++) {
  6989. excluded[excludedClassNames[j]] = true;
  6990. }
  6991. }
  6992. }
  6993. for (i = 0, ln = expressions.length; i < ln; i++) {
  6994. expression = expressions[i];
  6995. if (typeof expression === 'string' && expression.length > 0) {
  6996. possibleClassNames = Manager.getNamesByExpression(expression);
  6997. for (j = 0, subLn = possibleClassNames.length; j < subLn; j++) {
  6998. possibleClassName = possibleClassNames[j];
  6999. if (!excluded.hasOwnProperty(possibleClassName) && !Manager.isCreated(possibleClassName)) {
  7000. Ext.Array.include(classNames, possibleClassName);
  7001. }
  7002. }
  7003. }
  7004. }
  7005. // If the dynamic dependency feature is not being used, throw an error
  7006. // if the dependencies are not defined
  7007. if (!this.config.enabled) {
  7008. if (classNames.length > 0) {
  7009. Ext.Error.raise({
  7010. sourceClass: "Ext.Loader",
  7011. sourceMethod: "require",
  7012. msg: "Ext.Loader is not enabled, so dependencies cannot be resolved dynamically. " +
  7013. "Missing required class" + ((classNames.length > 1) ? "es" : "") + ": " + classNames.join(', ')
  7014. });
  7015. }
  7016. }
  7017. if (classNames.length === 0) {
  7018. fn.call(scope);
  7019. return this;
  7020. }
  7021. this.queue.push({
  7022. requires: classNames,
  7023. callback: fn,
  7024. scope: scope
  7025. });
  7026. classNames = classNames.slice();
  7027. for (i = 0, ln = classNames.length; i < ln; i++) {
  7028. className = classNames[i];
  7029. if (!this.isFileLoaded.hasOwnProperty(className)) {
  7030. this.isFileLoaded[className] = false;
  7031. filePath = this.getPath(className);
  7032. this.classNameToFilePathMap[className] = filePath;
  7033. this.numPendingFiles++;
  7034. this.loadScriptFile(
  7035. filePath,
  7036. Ext.Function.pass(this.onFileLoaded, [className, filePath], this),
  7037. Ext.Function.pass(this.onFileLoadError, [className, filePath]),
  7038. this,
  7039. this.syncModeEnabled
  7040. );
  7041. }
  7042. }
  7043. return this;
  7044. },
  7045. /**
  7046. * @private
  7047. * @param {String} className
  7048. * @param {String} filePath
  7049. */
  7050. onFileLoaded: function(className, filePath) {
  7051. this.numLoadedFiles++;
  7052. this.isFileLoaded[className] = true;
  7053. this.numPendingFiles--;
  7054. if (this.numPendingFiles === 0) {
  7055. this.refreshQueue();
  7056. }
  7057. },
  7058. /**
  7059. * @private
  7060. */
  7061. onFileLoadError: function(className, filePath, errorMessage, isSynchronous) {
  7062. this.numPendingFiles--;
  7063. this.hasFileLoadError = true;
  7064. },
  7065. /**
  7066. * @private
  7067. */
  7068. addOptionalRequires: function(requires) {
  7069. var optionalRequires = this.optionalRequires,
  7070. i, ln, require;
  7071. requires = Ext.Array.from(requires);
  7072. for (i = 0, ln = requires.length; i < ln; i++) {
  7073. require = requires[i];
  7074. Ext.Array.include(optionalRequires, require);
  7075. }
  7076. return this;
  7077. },
  7078. /**
  7079. * @private
  7080. */
  7081. triggerReady: function(force) {
  7082. var readyListeners = this.readyListeners,
  7083. optionalRequires, listener;
  7084. if (this.isLoading || force) {
  7085. this.isLoading = false;
  7086. if (this.optionalRequires.length) {
  7087. // Clone then empty the array to eliminate potential recursive loop issue
  7088. optionalRequires = Ext.Array.clone(this.optionalRequires);
  7089. // Empty the original array
  7090. this.optionalRequires.length = 0;
  7091. this.require(optionalRequires, Ext.Function.pass(this.triggerReady, [true], this), this);
  7092. return this;
  7093. }
  7094. while (readyListeners.length) {
  7095. listener = readyListeners.shift();
  7096. listener.fn.call(listener.scope);
  7097. if (this.isLoading) {
  7098. return this;
  7099. }
  7100. }
  7101. }
  7102. return this;
  7103. },
  7104. /**
  7105. * Adds new listener to be executed when all required scripts are fully loaded.
  7106. *
  7107. * @param {Function} fn The function callback to be executed
  7108. * @param {Object} scope The execution scope (`this`) of the callback function
  7109. * @param {Boolean} withDomReady Whether or not to wait for document dom ready as well
  7110. */
  7111. onReady: function(fn, scope, withDomReady, options) {
  7112. var oldFn;
  7113. if (withDomReady !== false && Ext.onDocumentReady) {
  7114. oldFn = fn;
  7115. fn = function() {
  7116. Ext.onDocumentReady(oldFn, scope, options);
  7117. };
  7118. }
  7119. if (!this.isLoading) {
  7120. fn.call(scope);
  7121. }
  7122. else {
  7123. this.readyListeners.push({
  7124. fn: fn,
  7125. scope: scope
  7126. });
  7127. }
  7128. },
  7129. /**
  7130. * @private
  7131. * @param {String} className
  7132. */
  7133. historyPush: function(className) {
  7134. if (className && this.isFileLoaded.hasOwnProperty(className)) {
  7135. Ext.Array.include(this.history, className);
  7136. }
  7137. return this;
  7138. }
  7139. };
  7140. /**
  7141. * @member Ext
  7142. * @method require
  7143. * @alias Ext.Loader#require
  7144. */
  7145. Ext.require = alias(Loader, 'require');
  7146. /**
  7147. * @member Ext
  7148. * @method syncRequire
  7149. * @alias Ext.Loader#syncRequire
  7150. */
  7151. Ext.syncRequire = alias(Loader, 'syncRequire');
  7152. /**
  7153. * @member Ext
  7154. * @method exclude
  7155. * @alias Ext.Loader#exclude
  7156. */
  7157. Ext.exclude = alias(Loader, 'exclude');
  7158. /**
  7159. * @member Ext
  7160. * @method onReady
  7161. * @alias Ext.Loader#onReady
  7162. */
  7163. Ext.onReady = function(fn, scope, options) {
  7164. Loader.onReady(fn, scope, true, options);
  7165. };
  7166. /**
  7167. * @cfg {String[]} requires
  7168. * @member Ext.Class
  7169. * List of classes that have to be loaded before instantiating this class.
  7170. * For example:
  7171. *
  7172. * Ext.define('Mother', {
  7173. * requires: ['Child'],
  7174. * giveBirth: function() {
  7175. * // we can be sure that child class is available.
  7176. * return new Child();
  7177. * }
  7178. * });
  7179. */
  7180. Class.registerPreprocessor('loader', function(cls, data, continueFn) {
  7181. var me = this,
  7182. dependencies = [],
  7183. className = Manager.getName(cls),
  7184. i, j, ln, subLn, value, propertyName, propertyValue;
  7185. /*
  7186. Basically loop through the dependencyProperties, look for string class names and push
  7187. them into a stack, regardless of whether the property's value is a string, array or object. For example:
  7188. {
  7189. extend: 'Ext.MyClass',
  7190. requires: ['Ext.some.OtherClass'],
  7191. mixins: {
  7192. observable: 'Ext.util.Observable';
  7193. }
  7194. }
  7195. which will later be transformed into:
  7196. {
  7197. extend: Ext.MyClass,
  7198. requires: [Ext.some.OtherClass],
  7199. mixins: {
  7200. observable: Ext.util.Observable;
  7201. }
  7202. }
  7203. */
  7204. for (i = 0, ln = dependencyProperties.length; i < ln; i++) {
  7205. propertyName = dependencyProperties[i];
  7206. if (data.hasOwnProperty(propertyName)) {
  7207. propertyValue = data[propertyName];
  7208. if (typeof propertyValue === 'string') {
  7209. dependencies.push(propertyValue);
  7210. }
  7211. else if (propertyValue instanceof Array) {
  7212. for (j = 0, subLn = propertyValue.length; j < subLn; j++) {
  7213. value = propertyValue[j];
  7214. if (typeof value === 'string') {
  7215. dependencies.push(value);
  7216. }
  7217. }
  7218. }
  7219. else if (typeof propertyValue != 'function') {
  7220. for (j in propertyValue) {
  7221. if (propertyValue.hasOwnProperty(j)) {
  7222. value = propertyValue[j];
  7223. if (typeof value === 'string') {
  7224. dependencies.push(value);
  7225. }
  7226. }
  7227. }
  7228. }
  7229. }
  7230. }
  7231. if (dependencies.length === 0) {
  7232. // Loader.historyPush(className);
  7233. return;
  7234. }
  7235. Loader.require(dependencies, function() {
  7236. for (i = 0, ln = dependencyProperties.length; i < ln; i++) {
  7237. propertyName = dependencyProperties[i];
  7238. if (data.hasOwnProperty(propertyName)) {
  7239. propertyValue = data[propertyName];
  7240. if (typeof propertyValue === 'string') {
  7241. data[propertyName] = Manager.get(propertyValue);
  7242. }
  7243. else if (propertyValue instanceof Array) {
  7244. for (j = 0, subLn = propertyValue.length; j < subLn; j++) {
  7245. value = propertyValue[j];
  7246. if (typeof value === 'string') {
  7247. data[propertyName][j] = Manager.get(value);
  7248. }
  7249. }
  7250. }
  7251. else if (typeof propertyValue != 'function') {
  7252. for (var k in propertyValue) {
  7253. if (propertyValue.hasOwnProperty(k)) {
  7254. value = propertyValue[k];
  7255. if (typeof value === 'string') {
  7256. data[propertyName][k] = Manager.get(value);
  7257. }
  7258. }
  7259. }
  7260. }
  7261. }
  7262. }
  7263. continueFn.call(me, cls, data);
  7264. });
  7265. return false;
  7266. }, true);
  7267. Class.setDefaultPreprocessorPosition('loader', 'after', 'className');
  7268. /**
  7269. * @cfg {String[]} uses
  7270. * @member Ext.Class
  7271. * List of classes to load together with this class. These aren't neccessarily loaded before
  7272. * this class is instantiated. For example:
  7273. *
  7274. * Ext.define('Mother', {
  7275. * uses: ['Child'],
  7276. * giveBirth: function() {
  7277. * // This code might, or might not work:
  7278. * // return new Child();
  7279. *
  7280. * // Instead use Ext.create() to load the class at the spot if not loaded already:
  7281. * return Ext.create('Child');
  7282. * }
  7283. * });
  7284. */
  7285. Manager.registerPostprocessor('uses', function(name, cls, data) {
  7286. var uses = Ext.Array.from(data.uses),
  7287. items = [],
  7288. i, ln, item;
  7289. for (i = 0, ln = uses.length; i < ln; i++) {
  7290. item = uses[i];
  7291. if (typeof item === 'string') {
  7292. items.push(item);
  7293. }
  7294. }
  7295. Loader.addOptionalRequires(items);
  7296. });
  7297. Manager.setDefaultPostprocessorPosition('uses', 'last');
  7298. })(Ext.ClassManager, Ext.Class, Ext.Function.flexSetter, Ext.Function.alias);
  7299. /**
  7300. * @author Brian Moeskau <brian@sencha.com>
  7301. * @docauthor Brian Moeskau <brian@sencha.com>
  7302. *
  7303. * A wrapper class for the native JavaScript Error object that adds a few useful capabilities for handling
  7304. * errors in an Ext application. When you use Ext.Error to {@link #raise} an error from within any class that
  7305. * uses the Ext 4 class system, the Error class can automatically add the source class and method from which
  7306. * the error was raised. It also includes logic to automatically log the eroor to the console, if available,
  7307. * with additional metadata about the error. In all cases, the error will always be thrown at the end so that
  7308. * execution will halt.
  7309. *
  7310. * Ext.Error also offers a global error {@link #handle handling} method that can be overridden in order to
  7311. * handle application-wide errors in a single spot. You can optionally {@link #ignore} errors altogether,
  7312. * although in a real application it's usually a better idea to override the handling function and perform
  7313. * logging or some other method of reporting the errors in a way that is meaningful to the application.
  7314. *
  7315. * At its simplest you can simply raise an error as a simple string from within any code:
  7316. *
  7317. * Example usage:
  7318. *
  7319. * Ext.Error.raise('Something bad happened!');
  7320. *
  7321. * If raised from plain JavaScript code, the error will be logged to the console (if available) and the message
  7322. * displayed. In most cases however you'll be raising errors from within a class, and it may often be useful to add
  7323. * additional metadata about the error being raised. The {@link #raise} method can also take a config object.
  7324. * In this form the `msg` attribute becomes the error description, and any other data added to the config gets
  7325. * added to the error object and, if the console is available, logged to the console for inspection.
  7326. *
  7327. * Example usage:
  7328. *
  7329. * Ext.define('Ext.Foo', {
  7330. * doSomething: function(option){
  7331. * if (someCondition === false) {
  7332. * Ext.Error.raise({
  7333. * msg: 'You cannot do that!',
  7334. * option: option, // whatever was passed into the method
  7335. * 'error code': 100 // other arbitrary info
  7336. * });
  7337. * }
  7338. * }
  7339. * });
  7340. *
  7341. * If a console is available (that supports the `console.dir` function) you'll see console output like:
  7342. *
  7343. * An error was raised with the following data:
  7344. * option: Object { foo: "bar"}
  7345. * foo: "bar"
  7346. * error code: 100
  7347. * msg: "You cannot do that!"
  7348. * sourceClass: "Ext.Foo"
  7349. * sourceMethod: "doSomething"
  7350. *
  7351. * uncaught exception: You cannot do that!
  7352. *
  7353. * As you can see, the error will report exactly where it was raised and will include as much information as the
  7354. * raising code can usefully provide.
  7355. *
  7356. * If you want to handle all application errors globally you can simply override the static {@link #handle} method
  7357. * and provide whatever handling logic you need. If the method returns true then the error is considered handled
  7358. * and will not be thrown to the browser. If anything but true is returned then the error will be thrown normally.
  7359. *
  7360. * Example usage:
  7361. *
  7362. * Ext.Error.handle = function(err) {
  7363. * if (err.someProperty == 'NotReallyAnError') {
  7364. * // maybe log something to the application here if applicable
  7365. * return true;
  7366. * }
  7367. * // any non-true return value (including none) will cause the error to be thrown
  7368. * }
  7369. *
  7370. */
  7371. Ext.Error = Ext.extend(Error, {
  7372. statics: {
  7373. /**
  7374. * @property {Boolean} ignore
  7375. * Static flag that can be used to globally disable error reporting to the browser if set to true
  7376. * (defaults to false). Note that if you ignore Ext errors it's likely that some other code may fail
  7377. * and throw a native JavaScript error thereafter, so use with caution. In most cases it will probably
  7378. * be preferable to supply a custom error {@link #handle handling} function instead.
  7379. *
  7380. * Example usage:
  7381. *
  7382. * Ext.Error.ignore = true;
  7383. *
  7384. * @static
  7385. */
  7386. ignore: false,
  7387. /**
  7388. * @property {Boolean} notify
  7389. * Static flag that can be used to globally control error notification to the user. Unlike
  7390. * Ex.Error.ignore, this does not effect exceptions. They are still thrown. This value can be
  7391. * set to false to disable the alert notification (default is true for IE6 and IE7).
  7392. *
  7393. * Only the first error will generate an alert. Internally this flag is set to false when the
  7394. * first error occurs prior to displaying the alert.
  7395. *
  7396. * This flag is not used in a release build.
  7397. *
  7398. * Example usage:
  7399. *
  7400. * Ext.Error.notify = false;
  7401. *
  7402. * @static
  7403. */
  7404. //notify: Ext.isIE6 || Ext.isIE7,
  7405. /**
  7406. * Raise an error that can include additional data and supports automatic console logging if available.
  7407. * You can pass a string error message or an object with the `msg` attribute which will be used as the
  7408. * error message. The object can contain any other name-value attributes (or objects) to be logged
  7409. * along with the error.
  7410. *
  7411. * Note that after displaying the error message a JavaScript error will ultimately be thrown so that
  7412. * execution will halt.
  7413. *
  7414. * Example usage:
  7415. *
  7416. * Ext.Error.raise('A simple string error message');
  7417. *
  7418. * // or...
  7419. *
  7420. * Ext.define('Ext.Foo', {
  7421. * doSomething: function(option){
  7422. * if (someCondition === false) {
  7423. * Ext.Error.raise({
  7424. * msg: 'You cannot do that!',
  7425. * option: option, // whatever was passed into the method
  7426. * 'error code': 100 // other arbitrary info
  7427. * });
  7428. * }
  7429. * }
  7430. * });
  7431. *
  7432. * @param {String/Object} err The error message string, or an object containing the attribute "msg" that will be
  7433. * used as the error message. Any other data included in the object will also be logged to the browser console,
  7434. * if available.
  7435. * @static
  7436. */
  7437. raise: function(err){
  7438. err = err || {};
  7439. if (Ext.isString(err)) {
  7440. err = { msg: err };
  7441. }
  7442. var method = this.raise.caller;
  7443. if (method) {
  7444. if (method.$name) {
  7445. err.sourceMethod = method.$name;
  7446. }
  7447. if (method.$owner) {
  7448. err.sourceClass = method.$owner.$className;
  7449. }
  7450. }
  7451. if (Ext.Error.handle(err) !== true) {
  7452. var msg = Ext.Error.prototype.toString.call(err);
  7453. Ext.log({
  7454. msg: msg,
  7455. level: 'error',
  7456. dump: err,
  7457. stack: true
  7458. });
  7459. throw new Ext.Error(err);
  7460. }
  7461. },
  7462. /**
  7463. * Globally handle any Ext errors that may be raised, optionally providing custom logic to
  7464. * handle different errors individually. Return true from the function to bypass throwing the
  7465. * error to the browser, otherwise the error will be thrown and execution will halt.
  7466. *
  7467. * Example usage:
  7468. *
  7469. * Ext.Error.handle = function(err) {
  7470. * if (err.someProperty == 'NotReallyAnError') {
  7471. * // maybe log something to the application here if applicable
  7472. * return true;
  7473. * }
  7474. * // any non-true return value (including none) will cause the error to be thrown
  7475. * }
  7476. *
  7477. * @param {Ext.Error} err The Ext.Error object being raised. It will contain any attributes that were originally
  7478. * raised with it, plus properties about the method and class from which the error originated (if raised from a
  7479. * class that uses the Ext 4 class system).
  7480. * @static
  7481. */
  7482. handle: function(){
  7483. return Ext.Error.ignore;
  7484. }
  7485. },
  7486. // This is the standard property that is the name of the constructor.
  7487. name: 'Ext.Error',
  7488. /**
  7489. * Creates new Error object.
  7490. * @param {String/Object} config The error message string, or an object containing the
  7491. * attribute "msg" that will be used as the error message. Any other data included in
  7492. * the object will be applied to the error instance and logged to the browser console, if available.
  7493. */
  7494. constructor: function(config){
  7495. if (Ext.isString(config)) {
  7496. config = { msg: config };
  7497. }
  7498. var me = this;
  7499. Ext.apply(me, config);
  7500. me.message = me.message || me.msg; // 'message' is standard ('msg' is non-standard)
  7501. // note: the above does not work in old WebKit (me.message is readonly) (Safari 4)
  7502. },
  7503. /**
  7504. * Provides a custom string representation of the error object. This is an override of the base JavaScript
  7505. * `Object.toString` method, which is useful so that when logged to the browser console, an error object will
  7506. * be displayed with a useful message instead of `[object Object]`, the default `toString` result.
  7507. *
  7508. * The default implementation will include the error message along with the raising class and method, if available,
  7509. * but this can be overridden with a custom implementation either at the prototype level (for all errors) or on
  7510. * a particular error instance, if you want to provide a custom description that will show up in the console.
  7511. * @return {String} The error message. If raised from within the Ext 4 class system, the error message will also
  7512. * include the raising class and method names, if available.
  7513. */
  7514. toString: function(){
  7515. var me = this,
  7516. className = me.className ? me.className : '',
  7517. methodName = me.methodName ? '.' + me.methodName + '(): ' : '',
  7518. msg = me.msg || '(No description provided)';
  7519. return className + methodName + msg;
  7520. }
  7521. });
  7522. /*
  7523. * This mechanism is used to notify the user of the first error encountered on the page. This
  7524. * was previously internal to Ext.Error.raise and is a desirable feature since errors often
  7525. * slip silently under the radar. It cannot live in Ext.Error.raise since there are times
  7526. * where exceptions are handled in a try/catch.
  7527. */
  7528. /*
  7529. This file is part of Ext JS 4
  7530. Copyright (c) 2011 Sencha Inc
  7531. Contact: http://www.sencha.com/contact
  7532. GNU General Public License Usage
  7533. This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
  7534. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
  7535. */
  7536. /**
  7537. * @class Ext.JSON
  7538. * Modified version of Douglas Crockford's JSON.js that doesn't
  7539. * mess with the Object prototype
  7540. * http://www.json.org/js.html
  7541. * @singleton
  7542. */
  7543. Ext.JSON = new(function() {
  7544. var useHasOwn = !! {}.hasOwnProperty,
  7545. isNative = function() {
  7546. var useNative = null;
  7547. return function() {
  7548. if (useNative === null) {
  7549. useNative = Ext.USE_NATIVE_JSON && window.JSON && JSON.toString() == '[object JSON]';
  7550. }
  7551. return useNative;
  7552. };
  7553. }(),
  7554. pad = function(n) {
  7555. return n < 10 ? "0" + n : n;
  7556. },
  7557. doDecode = function(json) {
  7558. return eval("(" + json + ')');
  7559. },
  7560. doEncode = function(o) {
  7561. if (!Ext.isDefined(o) || o === null) {
  7562. return "null";
  7563. } else if (Ext.isArray(o)) {
  7564. return encodeArray(o);
  7565. } else if (Ext.isDate(o)) {
  7566. return Ext.JSON.encodeDate(o);
  7567. } else if (Ext.isString(o)) {
  7568. return encodeString(o);
  7569. } else if (typeof o == "number") {
  7570. //don't use isNumber here, since finite checks happen inside isNumber
  7571. return isFinite(o) ? String(o) : "null";
  7572. } else if (Ext.isBoolean(o)) {
  7573. return String(o);
  7574. } else if (Ext.isObject(o)) {
  7575. return encodeObject(o);
  7576. } else if (typeof o === "function") {
  7577. return "null";
  7578. }
  7579. return 'undefined';
  7580. },
  7581. m = {
  7582. "\b": '\\b',
  7583. "\t": '\\t',
  7584. "\n": '\\n',
  7585. "\f": '\\f',
  7586. "\r": '\\r',
  7587. '"': '\\"',
  7588. "\\": '\\\\',
  7589. '\x0b': '\\u000b' //ie doesn't handle \v
  7590. },
  7591. charToReplace = /[\\\"\x00-\x1f\x7f-\uffff]/g,
  7592. encodeString = function(s) {
  7593. return '"' + s.replace(charToReplace, function(a) {
  7594. var c = m[a];
  7595. return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  7596. }) + '"';
  7597. },
  7598. encodeArray = function(o) {
  7599. var a = ["[", ""],
  7600. // Note empty string in case there are no serializable members.
  7601. len = o.length,
  7602. i;
  7603. for (i = 0; i < len; i += 1) {
  7604. a.push(doEncode(o[i]), ',');
  7605. }
  7606. // Overwrite trailing comma (or empty string)
  7607. a[a.length - 1] = ']';
  7608. return a.join("");
  7609. },
  7610. encodeObject = function(o) {
  7611. var a = ["{", ""],
  7612. // Note empty string in case there are no serializable members.
  7613. i;
  7614. for (i in o) {
  7615. if (!useHasOwn || o.hasOwnProperty(i)) {
  7616. a.push(doEncode(i), ":", doEncode(o[i]), ',');
  7617. }
  7618. }
  7619. // Overwrite trailing comma (or empty string)
  7620. a[a.length - 1] = '}';
  7621. return a.join("");
  7622. };
  7623. /**
  7624. * <p>Encodes a Date. This returns the actual string which is inserted into the JSON string as the literal expression.
  7625. * <b>The returned value includes enclosing double quotation marks.</b></p>
  7626. * <p>The default return format is "yyyy-mm-ddThh:mm:ss".</p>
  7627. * <p>To override this:</p><pre><code>
  7628. Ext.JSON.encodeDate = function(d) {
  7629. return Ext.Date.format(d, '"Y-m-d"');
  7630. };
  7631. </code></pre>
  7632. * @param {Date} d The Date to encode
  7633. * @return {String} The string literal to use in a JSON string.
  7634. */
  7635. this.encodeDate = function(o) {
  7636. return '"' + o.getFullYear() + "-"
  7637. + pad(o.getMonth() + 1) + "-"
  7638. + pad(o.getDate()) + "T"
  7639. + pad(o.getHours()) + ":"
  7640. + pad(o.getMinutes()) + ":"
  7641. + pad(o.getSeconds()) + '"';
  7642. };
  7643. /**
  7644. * Encodes an Object, Array or other value
  7645. * @param {Object} o The variable to encode
  7646. * @return {String} The JSON string
  7647. */
  7648. this.encode = function() {
  7649. var ec;
  7650. return function(o) {
  7651. if (!ec) {
  7652. // setup encoding function on first access
  7653. ec = isNative() ? JSON.stringify : doEncode;
  7654. }
  7655. return ec(o);
  7656. };
  7657. }();
  7658. /**
  7659. * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError unless the safe option is set.
  7660. * @param {String} json The JSON string
  7661. * @param {Boolean} safe (optional) Whether to return null or throw an exception if the JSON is invalid.
  7662. * @return {Object} The resulting object
  7663. */
  7664. this.decode = function() {
  7665. var dc;
  7666. return function(json, safe) {
  7667. if (!dc) {
  7668. // setup decoding function on first access
  7669. dc = isNative() ? JSON.parse : doDecode;
  7670. }
  7671. try {
  7672. return dc(json);
  7673. } catch (e) {
  7674. if (safe === true) {
  7675. return null;
  7676. }
  7677. Ext.Error.raise({
  7678. sourceClass: "Ext.JSON",
  7679. sourceMethod: "decode",
  7680. msg: "You're trying to decode an invalid JSON String: " + json
  7681. });
  7682. }
  7683. };
  7684. }();
  7685. })();
  7686. /**
  7687. * Shorthand for {@link Ext.JSON#encode}
  7688. * @member Ext
  7689. * @method encode
  7690. * @alias Ext.JSON#encode
  7691. */
  7692. Ext.encode = Ext.JSON.encode;
  7693. /**
  7694. * Shorthand for {@link Ext.JSON#decode}
  7695. * @member Ext
  7696. * @method decode
  7697. * @alias Ext.JSON#decode
  7698. */
  7699. Ext.decode = Ext.JSON.decode;
  7700. /**
  7701. * @class Ext
  7702. The Ext namespace (global object) encapsulates all classes, singletons, and utility methods provided by Sencha's libraries.</p>
  7703. Most user interface Components are at a lower level of nesting in the namespace, but many common utility functions are provided
  7704. as direct properties of the Ext namespace.
  7705. Also many frequently used methods from other classes are provided as shortcuts within the Ext namespace.
  7706. For example {@link Ext#getCmp Ext.getCmp} aliases {@link Ext.ComponentManager#get Ext.ComponentManager.get}.
  7707. Many applications are initiated with {@link Ext#onReady Ext.onReady} which is called once the DOM is ready.
  7708. This ensures all scripts have been loaded, preventing dependency issues. For example
  7709. Ext.onReady(function(){
  7710. new Ext.Component({
  7711. renderTo: document.body,
  7712. html: 'DOM ready!'
  7713. });
  7714. });
  7715. For more information about how to use the Ext classes, see
  7716. - <a href="http://www.sencha.com/learn/">The Learning Center</a>
  7717. - <a href="http://www.sencha.com/learn/Ext_FAQ">The FAQ</a>
  7718. - <a href="http://www.sencha.com/forum/">The forums</a>
  7719. * @singleton
  7720. * @markdown
  7721. */
  7722. Ext.apply(Ext, {
  7723. userAgent: navigator.userAgent.toLowerCase(),
  7724. cache: {},
  7725. idSeed: 1000,
  7726. windowId: 'ext-window',
  7727. documentId: 'ext-document',
  7728. /**
  7729. * True when the document is fully initialized and ready for action
  7730. * @type Boolean
  7731. */
  7732. isReady: false,
  7733. /**
  7734. * True to automatically uncache orphaned Ext.Elements periodically
  7735. * @type Boolean
  7736. */
  7737. enableGarbageCollector: true,
  7738. /**
  7739. * True to automatically purge event listeners during garbageCollection.
  7740. * @type Boolean
  7741. */
  7742. enableListenerCollection: true,
  7743. /**
  7744. * Generates unique ids. If the element already has an id, it is unchanged
  7745. * @param {HTMLElement/Ext.Element} el (optional) The element to generate an id for
  7746. * @param {String} prefix (optional) Id prefix (defaults "ext-gen")
  7747. * @return {String} The generated Id.
  7748. */
  7749. id: function(el, prefix) {
  7750. var me = this,
  7751. sandboxPrefix = '';
  7752. el = Ext.getDom(el, true) || {};
  7753. if (el === document) {
  7754. el.id = me.documentId;
  7755. }
  7756. else if (el === window) {
  7757. el.id = me.windowId;
  7758. }
  7759. if (!el.id) {
  7760. if (me.isSandboxed) {
  7761. if (!me.uniqueGlobalNamespace) {
  7762. me.getUniqueGlobalNamespace();
  7763. }
  7764. sandboxPrefix = me.uniqueGlobalNamespace + '-';
  7765. }
  7766. el.id = sandboxPrefix + (prefix || "ext-gen") + (++Ext.idSeed);
  7767. }
  7768. return el.id;
  7769. },
  7770. /**
  7771. * Returns the current document body as an {@link Ext.Element}.
  7772. * @return Ext.Element The document body
  7773. */
  7774. getBody: function() {
  7775. return Ext.get(document.body || false);
  7776. },
  7777. /**
  7778. * Returns the current document head as an {@link Ext.Element}.
  7779. * @return Ext.Element The document head
  7780. * @method
  7781. */
  7782. getHead: function() {
  7783. var head;
  7784. return function() {
  7785. if (head == undefined) {
  7786. head = Ext.get(document.getElementsByTagName("head")[0]);
  7787. }
  7788. return head;
  7789. };
  7790. }(),
  7791. /**
  7792. * Returns the current HTML document object as an {@link Ext.Element}.
  7793. * @return Ext.Element The document
  7794. */
  7795. getDoc: function() {
  7796. return Ext.get(document);
  7797. },
  7798. /**
  7799. * This is shorthand reference to {@link Ext.ComponentManager#get}.
  7800. * Looks up an existing {@link Ext.Component Component} by {@link Ext.Component#id id}
  7801. * @param {String} id The component {@link Ext.Component#id id}
  7802. * @return Ext.Component The Component, <tt>undefined</tt> if not found, or <tt>null</tt> if a
  7803. * Class was found.
  7804. */
  7805. getCmp: function(id) {
  7806. return Ext.ComponentManager.get(id);
  7807. },
  7808. /**
  7809. * Returns the current orientation of the mobile device
  7810. * @return {String} Either 'portrait' or 'landscape'
  7811. */
  7812. getOrientation: function() {
  7813. return window.innerHeight > window.innerWidth ? 'portrait' : 'landscape';
  7814. },
  7815. /**
  7816. * Attempts to destroy any objects passed to it by removing all event listeners, removing them from the
  7817. * DOM (if applicable) and calling their destroy functions (if available). This method is primarily
  7818. * intended for arguments of type {@link Ext.Element} and {@link Ext.Component}, but any subclass of
  7819. * {@link Ext.util.Observable} can be passed in. Any number of elements and/or components can be
  7820. * passed into this function in a single call as separate arguments.
  7821. * @param {Ext.Element/Ext.Component/Ext.Element[]/Ext.Component[]...} arg1
  7822. * An {@link Ext.Element}, {@link Ext.Component}, or an Array of either of these to destroy
  7823. */
  7824. destroy: function() {
  7825. var ln = arguments.length,
  7826. i, arg;
  7827. for (i = 0; i < ln; i++) {
  7828. arg = arguments[i];
  7829. if (arg) {
  7830. if (Ext.isArray(arg)) {
  7831. this.destroy.apply(this, arg);
  7832. }
  7833. else if (Ext.isFunction(arg.destroy)) {
  7834. arg.destroy();
  7835. }
  7836. else if (arg.dom) {
  7837. arg.remove();
  7838. }
  7839. }
  7840. }
  7841. },
  7842. /**
  7843. * Execute a callback function in a particular scope. If no function is passed the call is ignored.
  7844. *
  7845. * For example, these lines are equivalent:
  7846. *
  7847. * Ext.callback(myFunc, this, [arg1, arg2]);
  7848. * Ext.isFunction(myFunc) && myFunc.apply(this, [arg1, arg2]);
  7849. *
  7850. * @param {Function} callback The callback to execute
  7851. * @param {Object} scope (optional) The scope to execute in
  7852. * @param {Array} args (optional) The arguments to pass to the function
  7853. * @param {Number} delay (optional) Pass a number to delay the call by a number of milliseconds.
  7854. */
  7855. callback: function(callback, scope, args, delay){
  7856. if(Ext.isFunction(callback)){
  7857. args = args || [];
  7858. scope = scope || window;
  7859. if (delay) {
  7860. Ext.defer(callback, delay, scope, args);
  7861. } else {
  7862. callback.apply(scope, args);
  7863. }
  7864. }
  7865. },
  7866. /**
  7867. * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
  7868. * @param {String} value The string to encode
  7869. * @return {String} The encoded text
  7870. */
  7871. htmlEncode : function(value) {
  7872. return Ext.String.htmlEncode(value);
  7873. },
  7874. /**
  7875. * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
  7876. * @param {String} value The string to decode
  7877. * @return {String} The decoded text
  7878. */
  7879. htmlDecode : function(value) {
  7880. return Ext.String.htmlDecode(value);
  7881. },
  7882. /**
  7883. * Appends content to the query string of a URL, handling logic for whether to place
  7884. * a question mark or ampersand.
  7885. * @param {String} url The URL to append to.
  7886. * @param {String} s The content to append to the URL.
  7887. * @return (String) The resulting URL
  7888. */
  7889. urlAppend : function(url, s) {
  7890. if (!Ext.isEmpty(s)) {
  7891. return url + (url.indexOf('?') === -1 ? '?' : '&') + s;
  7892. }
  7893. return url;
  7894. }
  7895. });
  7896. Ext.ns = Ext.namespace;
  7897. // for old browsers
  7898. window.undefined = window.undefined;
  7899. /**
  7900. * @class Ext
  7901. * Ext core utilities and functions.
  7902. * @singleton
  7903. */
  7904. (function(){
  7905. /*
  7906. FF 3.6 - Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.17) Gecko/20110420 Firefox/3.6.17
  7907. FF 4.0.1 - Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1
  7908. FF 5.0 - Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0
  7909. IE6 - Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1;)
  7910. IE7 - Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1;)
  7911. IE8 - Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)
  7912. IE9 - Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
  7913. Chrome 11 - Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.60 Safari/534.24
  7914. Safari 5 - Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1
  7915. Opera 11.11 - Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11
  7916. */
  7917. var check = function(regex){
  7918. return regex.test(Ext.userAgent);
  7919. },
  7920. isStrict = document.compatMode == "CSS1Compat",
  7921. version = function (is, regex) {
  7922. var m;
  7923. return (is && (m = regex.exec(Ext.userAgent))) ? parseFloat(m[1]) : 0;
  7924. },
  7925. docMode = document.documentMode,
  7926. isOpera = check(/opera/),
  7927. isOpera10_5 = isOpera && check(/version\/10\.5/),
  7928. isChrome = check(/\bchrome\b/),
  7929. isWebKit = check(/webkit/),
  7930. isSafari = !isChrome && check(/safari/),
  7931. isSafari2 = isSafari && check(/applewebkit\/4/), // unique to Safari 2
  7932. isSafari3 = isSafari && check(/version\/3/),
  7933. isSafari4 = isSafari && check(/version\/4/),
  7934. isSafari5 = isSafari && check(/version\/5/),
  7935. isIE = !isOpera && check(/msie/),
  7936. isIE7 = isIE && (check(/msie 7/) || docMode == 7),
  7937. isIE8 = isIE && (check(/msie 8/) && docMode != 7 && docMode != 9 || docMode == 8),
  7938. isIE9 = isIE && (check(/msie 9/) && docMode != 7 && docMode != 8 || docMode == 9),
  7939. isIE6 = isIE && check(/msie 6/),
  7940. isGecko = !isWebKit && check(/gecko/),
  7941. isGecko3 = isGecko && check(/rv:1\.9/),
  7942. isGecko4 = isGecko && check(/rv:2\.0/),
  7943. isGecko5 = isGecko && check(/rv:5\./),
  7944. isFF3_0 = isGecko3 && check(/rv:1\.9\.0/),
  7945. isFF3_5 = isGecko3 && check(/rv:1\.9\.1/),
  7946. isFF3_6 = isGecko3 && check(/rv:1\.9\.2/),
  7947. isWindows = check(/windows|win32/),
  7948. isMac = check(/macintosh|mac os x/),
  7949. isLinux = check(/linux/),
  7950. scrollbarSize = null,
  7951. chromeVersion = version(true, /\bchrome\/(\d+\.\d+)/),
  7952. firefoxVersion = version(true, /\bfirefox\/(\d+\.\d+)/),
  7953. ieVersion = version(isIE, /msie (\d+\.\d+)/),
  7954. operaVersion = version(isOpera, /version\/(\d+\.\d+)/),
  7955. safariVersion = version(isSafari, /version\/(\d+\.\d+)/),
  7956. webKitVersion = version(isWebKit, /webkit\/(\d+\.\d+)/),
  7957. isSecure = /^https/i.test(window.location.protocol);
  7958. // remove css image flicker
  7959. try {
  7960. document.execCommand("BackgroundImageCache", false, true);
  7961. } catch(e) {}
  7962. Ext.setVersion('extjs', '4.0.7');
  7963. Ext.apply(Ext, {
  7964. /**
  7965. * URL to a blank file used by Ext when in secure mode for iframe src and onReady src to prevent
  7966. * the IE insecure content warning (<tt>'about:blank'</tt>, except for IE in secure mode, which is <tt>'javascript:""'</tt>).
  7967. * @type String
  7968. */
  7969. SSL_SECURE_URL : isSecure && isIE ? 'javascript:""' : 'about:blank',
  7970. /**
  7971. * True if the {@link Ext.fx.Anim} Class is available
  7972. * @type Boolean
  7973. * @property enableFx
  7974. */
  7975. /**
  7976. * True to scope the reset CSS to be just applied to Ext components. Note that this wraps root containers
  7977. * with an additional element. Also remember that when you turn on this option, you have to use ext-all-scoped {
  7978. * unless you use the bootstrap.js to load your javascript, in which case it will be handled for you.
  7979. * @type Boolean
  7980. */
  7981. scopeResetCSS : Ext.buildSettings.scopeResetCSS,
  7982. /**
  7983. * EXPERIMENTAL - True to cascade listener removal to child elements when an element is removed.
  7984. * Currently not optimized for performance.
  7985. * @type Boolean
  7986. */
  7987. enableNestedListenerRemoval : false,
  7988. /**
  7989. * Indicates whether to use native browser parsing for JSON methods.
  7990. * This option is ignored if the browser does not support native JSON methods.
  7991. * <b>Note: Native JSON methods will not work with objects that have functions.
  7992. * Also, property names must be quoted, otherwise the data will not parse.</b> (Defaults to false)
  7993. * @type Boolean
  7994. */
  7995. USE_NATIVE_JSON : false,
  7996. /**
  7997. * Return the dom node for the passed String (id), dom node, or Ext.Element.
  7998. * Optional 'strict' flag is needed for IE since it can return 'name' and
  7999. * 'id' elements by using getElementById.
  8000. * Here are some examples:
  8001. * <pre><code>
  8002. // gets dom node based on id
  8003. var elDom = Ext.getDom('elId');
  8004. // gets dom node based on the dom node
  8005. var elDom1 = Ext.getDom(elDom);
  8006. // If we don&#39;t know if we are working with an
  8007. // Ext.Element or a dom node use Ext.getDom
  8008. function(el){
  8009. var dom = Ext.getDom(el);
  8010. // do something with the dom node
  8011. }
  8012. * </code></pre>
  8013. * <b>Note</b>: the dom node to be found actually needs to exist (be rendered, etc)
  8014. * when this method is called to be successful.
  8015. * @param {String/HTMLElement/Ext.Element} el
  8016. * @return HTMLElement
  8017. */
  8018. getDom : function(el, strict) {
  8019. if (!el || !document) {
  8020. return null;
  8021. }
  8022. if (el.dom) {
  8023. return el.dom;
  8024. } else {
  8025. if (typeof el == 'string') {
  8026. var e = document.getElementById(el);
  8027. // IE returns elements with the 'name' and 'id' attribute.
  8028. // we do a strict check to return the element with only the id attribute
  8029. if (e && isIE && strict) {
  8030. if (el == e.getAttribute('id')) {
  8031. return e;
  8032. } else {
  8033. return null;
  8034. }
  8035. }
  8036. return e;
  8037. } else {
  8038. return el;
  8039. }
  8040. }
  8041. },
  8042. /**
  8043. * Removes a DOM node from the document.
  8044. * <p>Removes this element from the document, removes all DOM event listeners, and deletes the cache reference.
  8045. * All DOM event listeners are removed from this element. If {@link Ext#enableNestedListenerRemoval Ext.enableNestedListenerRemoval} is
  8046. * <code>true</code>, then DOM event listeners are also removed from all child nodes. The body node
  8047. * will be ignored if passed in.</p>
  8048. * @param {HTMLElement} node The node to remove
  8049. * @method
  8050. */
  8051. removeNode : isIE6 || isIE7 ? function() {
  8052. var d;
  8053. return function(n){
  8054. if(n && n.tagName != 'BODY'){
  8055. (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n) : Ext.EventManager.removeAll(n);
  8056. d = d || document.createElement('div');
  8057. d.appendChild(n);
  8058. d.innerHTML = '';
  8059. delete Ext.cache[n.id];
  8060. }
  8061. };
  8062. }() : function(n) {
  8063. if (n && n.parentNode && n.tagName != 'BODY') {
  8064. (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n) : Ext.EventManager.removeAll(n);
  8065. n.parentNode.removeChild(n);
  8066. delete Ext.cache[n.id];
  8067. }
  8068. },
  8069. isStrict: isStrict,
  8070. isIEQuirks: isIE && !isStrict,
  8071. /**
  8072. * True if the detected browser is Opera.
  8073. * @type Boolean
  8074. */
  8075. isOpera : isOpera,
  8076. /**
  8077. * True if the detected browser is Opera 10.5x.
  8078. * @type Boolean
  8079. */
  8080. isOpera10_5 : isOpera10_5,
  8081. /**
  8082. * True if the detected browser uses WebKit.
  8083. * @type Boolean
  8084. */
  8085. isWebKit : isWebKit,
  8086. /**
  8087. * True if the detected browser is Chrome.
  8088. * @type Boolean
  8089. */
  8090. isChrome : isChrome,
  8091. /**
  8092. * True if the detected browser is Safari.
  8093. * @type Boolean
  8094. */
  8095. isSafari : isSafari,
  8096. /**
  8097. * True if the detected browser is Safari 3.x.
  8098. * @type Boolean
  8099. */
  8100. isSafari3 : isSafari3,
  8101. /**
  8102. * True if the detected browser is Safari 4.x.
  8103. * @type Boolean
  8104. */
  8105. isSafari4 : isSafari4,
  8106. /**
  8107. * True if the detected browser is Safari 5.x.
  8108. * @type Boolean
  8109. */
  8110. isSafari5 : isSafari5,
  8111. /**
  8112. * True if the detected browser is Safari 2.x.
  8113. * @type Boolean
  8114. */
  8115. isSafari2 : isSafari2,
  8116. /**
  8117. * True if the detected browser is Internet Explorer.
  8118. * @type Boolean
  8119. */
  8120. isIE : isIE,
  8121. /**
  8122. * True if the detected browser is Internet Explorer 6.x.
  8123. * @type Boolean
  8124. */
  8125. isIE6 : isIE6,
  8126. /**
  8127. * True if the detected browser is Internet Explorer 7.x.
  8128. * @type Boolean
  8129. */
  8130. isIE7 : isIE7,
  8131. /**
  8132. * True if the detected browser is Internet Explorer 8.x.
  8133. * @type Boolean
  8134. */
  8135. isIE8 : isIE8,
  8136. /**
  8137. * True if the detected browser is Internet Explorer 9.x.
  8138. * @type Boolean
  8139. */
  8140. isIE9 : isIE9,
  8141. /**
  8142. * True if the detected browser uses the Gecko layout engine (e.g. Mozilla, Firefox).
  8143. * @type Boolean
  8144. */
  8145. isGecko : isGecko,
  8146. /**
  8147. * True if the detected browser uses a Gecko 1.9+ layout engine (e.g. Firefox 3.x).
  8148. * @type Boolean
  8149. */
  8150. isGecko3 : isGecko3,
  8151. /**
  8152. * True if the detected browser uses a Gecko 2.0+ layout engine (e.g. Firefox 4.x).
  8153. * @type Boolean
  8154. */
  8155. isGecko4 : isGecko4,
  8156. /**
  8157. * True if the detected browser uses a Gecko 5.0+ layout engine (e.g. Firefox 5.x).
  8158. * @type Boolean
  8159. */
  8160. isGecko5 : isGecko5,
  8161. /**
  8162. * True if the detected browser uses FireFox 3.0
  8163. * @type Boolean
  8164. */
  8165. isFF3_0 : isFF3_0,
  8166. /**
  8167. * True if the detected browser uses FireFox 3.5
  8168. * @type Boolean
  8169. */
  8170. isFF3_5 : isFF3_5,
  8171. /**
  8172. * True if the detected browser uses FireFox 3.6
  8173. * @type Boolean
  8174. */
  8175. isFF3_6 : isFF3_6,
  8176. /**
  8177. * True if the detected browser uses FireFox 4
  8178. * @type Boolean
  8179. */
  8180. isFF4 : 4 <= firefoxVersion && firefoxVersion < 5,
  8181. /**
  8182. * True if the detected browser uses FireFox 5
  8183. * @type Boolean
  8184. */
  8185. isFF5 : 5 <= firefoxVersion && firefoxVersion < 6,
  8186. /**
  8187. * True if the detected platform is Linux.
  8188. * @type Boolean
  8189. */
  8190. isLinux : isLinux,
  8191. /**
  8192. * True if the detected platform is Windows.
  8193. * @type Boolean
  8194. */
  8195. isWindows : isWindows,
  8196. /**
  8197. * True if the detected platform is Mac OS.
  8198. * @type Boolean
  8199. */
  8200. isMac : isMac,
  8201. /**
  8202. * The current version of Chrome (0 if the browser is not Chrome).
  8203. * @type Number
  8204. */
  8205. chromeVersion: chromeVersion,
  8206. /**
  8207. * The current version of Firefox (0 if the browser is not Firefox).
  8208. * @type Number
  8209. */
  8210. firefoxVersion: firefoxVersion,
  8211. /**
  8212. * The current version of IE (0 if the browser is not IE). This does not account
  8213. * for the documentMode of the current page, which is factored into {@link #isIE7},
  8214. * {@link #isIE8} and {@link #isIE9}. Thus this is not always true:
  8215. *
  8216. * Ext.isIE8 == (Ext.ieVersion == 8)
  8217. *
  8218. * @type Number
  8219. * @markdown
  8220. */
  8221. ieVersion: ieVersion,
  8222. /**
  8223. * The current version of Opera (0 if the browser is not Opera).
  8224. * @type Number
  8225. */
  8226. operaVersion: operaVersion,
  8227. /**
  8228. * The current version of Safari (0 if the browser is not Safari).
  8229. * @type Number
  8230. */
  8231. safariVersion: safariVersion,
  8232. /**
  8233. * The current version of WebKit (0 if the browser does not use WebKit).
  8234. * @type Number
  8235. */
  8236. webKitVersion: webKitVersion,
  8237. /**
  8238. * True if the page is running over SSL
  8239. * @type Boolean
  8240. */
  8241. isSecure: isSecure,
  8242. /**
  8243. * URL to a 1x1 transparent gif image used by Ext to create inline icons with CSS background images.
  8244. * In older versions of IE, this defaults to "http://sencha.com/s.gif" and you should change this to a URL on your server.
  8245. * For other browsers it uses an inline data URL.
  8246. * @type String
  8247. */
  8248. BLANK_IMAGE_URL : (isIE6 || isIE7) ? '/' + '/www.sencha.com/s.gif' : 'data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==',
  8249. /**
  8250. * <p>Utility method for returning a default value if the passed value is empty.</p>
  8251. * <p>The value is deemed to be empty if it is<div class="mdetail-params"><ul>
  8252. * <li>null</li>
  8253. * <li>undefined</li>
  8254. * <li>an empty array</li>
  8255. * <li>a zero length string (Unless the <tt>allowBlank</tt> parameter is <tt>true</tt>)</li>
  8256. * </ul></div>
  8257. * @param {Object} value The value to test
  8258. * @param {Object} defaultValue The value to return if the original value is empty
  8259. * @param {Boolean} allowBlank (optional) true to allow zero length strings to qualify as non-empty (defaults to false)
  8260. * @return {Object} value, if non-empty, else defaultValue
  8261. * @deprecated 4.0.0 Use {@link Ext#valueFrom} instead
  8262. */
  8263. value : function(v, defaultValue, allowBlank){
  8264. return Ext.isEmpty(v, allowBlank) ? defaultValue : v;
  8265. },
  8266. /**
  8267. * Escapes the passed string for use in a regular expression
  8268. * @param {String} str
  8269. * @return {String}
  8270. * @deprecated 4.0.0 Use {@link Ext.String#escapeRegex} instead
  8271. */
  8272. escapeRe : function(s) {
  8273. return s.replace(/([-.*+?^${}()|[\]\/\\])/g, "\\$1");
  8274. },
  8275. /**
  8276. * Applies event listeners to elements by selectors when the document is ready.
  8277. * The event name is specified with an <tt>&#64;</tt> suffix.
  8278. * <pre><code>
  8279. Ext.addBehaviors({
  8280. // add a listener for click on all anchors in element with id foo
  8281. '#foo a&#64;click' : function(e, t){
  8282. // do something
  8283. },
  8284. // add the same listener to multiple selectors (separated by comma BEFORE the &#64;)
  8285. '#foo a, #bar span.some-class&#64;mouseover' : function(){
  8286. // do something
  8287. }
  8288. });
  8289. * </code></pre>
  8290. * @param {Object} obj The list of behaviors to apply
  8291. */
  8292. addBehaviors : function(o){
  8293. if(!Ext.isReady){
  8294. Ext.onReady(function(){
  8295. Ext.addBehaviors(o);
  8296. });
  8297. } else {
  8298. var cache = {}, // simple cache for applying multiple behaviors to same selector does query multiple times
  8299. parts,
  8300. b,
  8301. s;
  8302. for (b in o) {
  8303. if ((parts = b.split('@'))[1]) { // for Object prototype breakers
  8304. s = parts[0];
  8305. if(!cache[s]){
  8306. cache[s] = Ext.select(s);
  8307. }
  8308. cache[s].on(parts[1], o[b]);
  8309. }
  8310. }
  8311. cache = null;
  8312. }
  8313. },
  8314. /**
  8315. * Returns the size of the browser scrollbars. This can differ depending on
  8316. * operating system settings, such as the theme or font size.
  8317. * @param {Boolean} force (optional) true to force a recalculation of the value.
  8318. * @return {Object} An object containing the width of a vertical scrollbar and the
  8319. * height of a horizontal scrollbar.
  8320. */
  8321. getScrollbarSize: function (force) {
  8322. if(!Ext.isReady){
  8323. return 0;
  8324. }
  8325. if(force === true || scrollbarSize === null){
  8326. // BrowserBug: IE9
  8327. // When IE9 positions an element offscreen via offsets, the offsetWidth is
  8328. // inaccurately reported. For IE9 only, we render on screen before removing.
  8329. var cssClass = Ext.isIE9 ? '' : Ext.baseCSSPrefix + 'hide-offsets',
  8330. // Append our div, do our calculation and then remove it
  8331. div = Ext.getBody().createChild('<div class="' + cssClass + '" style="width:100px;height:50px;overflow:hidden;"><div style="height:200px;"></div></div>'),
  8332. child = div.child('div', true),
  8333. w1 = child.offsetWidth;
  8334. div.setStyle('overflow', (Ext.isWebKit || Ext.isGecko) ? 'auto' : 'scroll');
  8335. var w2 = child.offsetWidth, width = w1 - w2;
  8336. div.remove();
  8337. // We assume width == height for now. TODO: is this always true?
  8338. scrollbarSize = { width: width, height: width };
  8339. }
  8340. return scrollbarSize;
  8341. },
  8342. /**
  8343. * Utility method for getting the width of the browser's vertical scrollbar. This
  8344. * can differ depending on operating system settings, such as the theme or font size.
  8345. *
  8346. * This method is deprected in favor of {@link #getScrollbarSize}.
  8347. *
  8348. * @param {Boolean} force (optional) true to force a recalculation of the value.
  8349. * @return {Number} The width of a vertical scrollbar.
  8350. * @deprecated
  8351. */
  8352. getScrollBarWidth: function(force){
  8353. var size = Ext.getScrollbarSize(force);
  8354. return size.width + 2; // legacy fudge factor
  8355. },
  8356. /**
  8357. * Copies a set of named properties fom the source object to the destination object.
  8358. *
  8359. * Example:
  8360. *
  8361. * ImageComponent = Ext.extend(Ext.Component, {
  8362. * initComponent: function() {
  8363. * this.autoEl = { tag: 'img' };
  8364. * MyComponent.superclass.initComponent.apply(this, arguments);
  8365. * this.initialBox = Ext.copyTo({}, this.initialConfig, 'x,y,width,height');
  8366. * }
  8367. * });
  8368. *
  8369. * Important note: To borrow class prototype methods, use {@link Ext.Base#borrow} instead.
  8370. *
  8371. * @param {Object} dest The destination object.
  8372. * @param {Object} source The source object.
  8373. * @param {String/String[]} names Either an Array of property names, or a comma-delimited list
  8374. * of property names to copy.
  8375. * @param {Boolean} usePrototypeKeys (Optional) Defaults to false. Pass true to copy keys off of the prototype as well as the instance.
  8376. * @return {Object} The modified object.
  8377. */
  8378. copyTo : function(dest, source, names, usePrototypeKeys){
  8379. if(typeof names == 'string'){
  8380. names = names.split(/[,;\s]/);
  8381. }
  8382. Ext.each(names, function(name){
  8383. if(usePrototypeKeys || source.hasOwnProperty(name)){
  8384. dest[name] = source[name];
  8385. }
  8386. }, this);
  8387. return dest;
  8388. },
  8389. /**
  8390. * Attempts to destroy and then remove a set of named properties of the passed object.
  8391. * @param {Object} o The object (most likely a Component) who's properties you wish to destroy.
  8392. * @param {String...} args One or more names of the properties to destroy and remove from the object.
  8393. */
  8394. destroyMembers : function(o){
  8395. for (var i = 1, a = arguments, len = a.length; i < len; i++) {
  8396. Ext.destroy(o[a[i]]);
  8397. delete o[a[i]];
  8398. }
  8399. },
  8400. /**
  8401. * Logs a message. If a console is present it will be used. On Opera, the method
  8402. * "opera.postError" is called. In other cases, the message is logged to an array
  8403. * "Ext.log.out". An attached debugger can watch this array and view the log. The
  8404. * log buffer is limited to a maximum of "Ext.log.max" entries (defaults to 250).
  8405. * The `Ext.log.out` array can also be written to a popup window by entering the
  8406. * following in the URL bar (a "bookmarklet"):
  8407. *
  8408. * javascript:void(Ext.log.show());
  8409. *
  8410. * If additional parameters are passed, they are joined and appended to the message.
  8411. * A technique for tracing entry and exit of a function is this:
  8412. *
  8413. * function foo () {
  8414. * Ext.log({ indent: 1 }, '>> foo');
  8415. *
  8416. * // log statements in here or methods called from here will be indented
  8417. * // by one step
  8418. *
  8419. * Ext.log({ outdent: 1 }, '<< foo');
  8420. * }
  8421. *
  8422. * This method does nothing in a release build.
  8423. *
  8424. * @param {String/Object} message The message to log or an options object with any
  8425. * of the following properties:
  8426. *
  8427. * - `msg`: The message to log (required).
  8428. * - `level`: One of: "error", "warn", "info" or "log" (the default is "log").
  8429. * - `dump`: An object to dump to the log as part of the message.
  8430. * - `stack`: True to include a stack trace in the log.
  8431. * - `indent`: Cause subsequent log statements to be indented one step.
  8432. * - `outdent`: Cause this and following statements to be one step less indented.
  8433. * @markdown
  8434. */
  8435. log :
  8436. Ext.emptyFn,
  8437. /**
  8438. * Partitions the set into two sets: a true set and a false set.
  8439. * Example:
  8440. * Example2:
  8441. * <pre><code>
  8442. // Example 1:
  8443. Ext.partition([true, false, true, true, false]); // [[true, true, true], [false, false]]
  8444. // Example 2:
  8445. Ext.partition(
  8446. Ext.query("p"),
  8447. function(val){
  8448. return val.className == "class1"
  8449. }
  8450. );
  8451. // true are those paragraph elements with a className of "class1",
  8452. // false set are those that do not have that className.
  8453. * </code></pre>
  8454. * @param {Array/NodeList} arr The array to partition
  8455. * @param {Function} truth (optional) a function to determine truth. If this is omitted the element
  8456. * itself must be able to be evaluated for its truthfulness.
  8457. * @return {Array} [array of truish values, array of falsy values]
  8458. * @deprecated 4.0.0 Will be removed in the next major version
  8459. */
  8460. partition : function(arr, truth){
  8461. var ret = [[],[]];
  8462. Ext.each(arr, function(v, i, a) {
  8463. ret[ (truth && truth(v, i, a)) || (!truth && v) ? 0 : 1].push(v);
  8464. });
  8465. return ret;
  8466. },
  8467. /**
  8468. * Invokes a method on each item in an Array.
  8469. * <pre><code>
  8470. // Example:
  8471. Ext.invoke(Ext.query("p"), "getAttribute", "id");
  8472. // [el1.getAttribute("id"), el2.getAttribute("id"), ..., elN.getAttribute("id")]
  8473. * </code></pre>
  8474. * @param {Array/NodeList} arr The Array of items to invoke the method on.
  8475. * @param {String} methodName The method name to invoke.
  8476. * @param {Object...} args Arguments to send into the method invocation.
  8477. * @return {Array} The results of invoking the method on each item in the array.
  8478. * @deprecated 4.0.0 Will be removed in the next major version
  8479. */
  8480. invoke : function(arr, methodName){
  8481. var ret = [],
  8482. args = Array.prototype.slice.call(arguments, 2);
  8483. Ext.each(arr, function(v,i) {
  8484. if (v && typeof v[methodName] == 'function') {
  8485. ret.push(v[methodName].apply(v, args));
  8486. } else {
  8487. ret.push(undefined);
  8488. }
  8489. });
  8490. return ret;
  8491. },
  8492. /**
  8493. * <p>Zips N sets together.</p>
  8494. * <pre><code>
  8495. // Example 1:
  8496. Ext.zip([1,2,3],[4,5,6]); // [[1,4],[2,5],[3,6]]
  8497. // Example 2:
  8498. Ext.zip(
  8499. [ "+", "-", "+"],
  8500. [ 12, 10, 22],
  8501. [ 43, 15, 96],
  8502. function(a, b, c){
  8503. return "$" + a + "" + b + "." + c
  8504. }
  8505. ); // ["$+12.43", "$-10.15", "$+22.96"]
  8506. * </code></pre>
  8507. * @param {Array/NodeList...} arr This argument may be repeated. Array(s) to contribute values.
  8508. * @param {Function} zipper (optional) The last item in the argument list. This will drive how the items are zipped together.
  8509. * @return {Array} The zipped set.
  8510. * @deprecated 4.0.0 Will be removed in the next major version
  8511. */
  8512. zip : function(){
  8513. var parts = Ext.partition(arguments, function( val ){ return typeof val != 'function'; }),
  8514. arrs = parts[0],
  8515. fn = parts[1][0],
  8516. len = Ext.max(Ext.pluck(arrs, "length")),
  8517. ret = [];
  8518. for (var i = 0; i < len; i++) {
  8519. ret[i] = [];
  8520. if(fn){
  8521. ret[i] = fn.apply(fn, Ext.pluck(arrs, i));
  8522. }else{
  8523. for (var j = 0, aLen = arrs.length; j < aLen; j++){
  8524. ret[i].push( arrs[j][i] );
  8525. }
  8526. }
  8527. }
  8528. return ret;
  8529. },
  8530. /**
  8531. * Turns an array into a sentence, joined by a specified connector - e.g.:
  8532. * Ext.toSentence(['Adama', 'Tigh', 'Roslin']); //'Adama, Tigh and Roslin'
  8533. * Ext.toSentence(['Adama', 'Tigh', 'Roslin'], 'or'); //'Adama, Tigh or Roslin'
  8534. * @param {String[]} items The array to create a sentence from
  8535. * @param {String} connector The string to use to connect the last two words. Usually 'and' or 'or' - defaults to 'and'.
  8536. * @return {String} The sentence string
  8537. * @deprecated 4.0.0 Will be removed in the next major version
  8538. */
  8539. toSentence: function(items, connector) {
  8540. var length = items.length;
  8541. if (length <= 1) {
  8542. return items[0];
  8543. } else {
  8544. var head = items.slice(0, length - 1),
  8545. tail = items[length - 1];
  8546. return Ext.util.Format.format("{0} {1} {2}", head.join(", "), connector || 'and', tail);
  8547. }
  8548. },
  8549. /**
  8550. * By default, Ext intelligently decides whether floating elements should be shimmed. If you are using flash,
  8551. * you may want to set this to true.
  8552. * @type Boolean
  8553. */
  8554. useShims: isIE6
  8555. });
  8556. })();
  8557. /**
  8558. * Loads Ext.app.Application class and starts it up with given configuration after the page is ready.
  8559. *
  8560. * See Ext.app.Application for details.
  8561. *
  8562. * @param {Object} config
  8563. */
  8564. Ext.application = function(config) {
  8565. Ext.require('Ext.app.Application');
  8566. Ext.onReady(function() {
  8567. Ext.create('Ext.app.Application', config);
  8568. });
  8569. };
  8570. /**
  8571. * @class Ext.util.Format
  8572. This class is a centralized place for formatting functions. It includes
  8573. functions to format various different types of data, such as text, dates and numeric values.
  8574. __Localization__
  8575. This class contains several options for localization. These can be set once the library has loaded,
  8576. all calls to the functions from that point will use the locale settings that were specified.
  8577. Options include:
  8578. - thousandSeparator
  8579. - decimalSeparator
  8580. - currenyPrecision
  8581. - currencySign
  8582. - currencyAtEnd
  8583. This class also uses the default date format defined here: {@link Ext.Date#defaultFormat}.
  8584. __Using with renderers__
  8585. There are two helper functions that return a new function that can be used in conjunction with
  8586. grid renderers:
  8587. columns: [{
  8588. dataIndex: 'date',
  8589. renderer: Ext.util.Format.dateRenderer('Y-m-d')
  8590. }, {
  8591. dataIndex: 'time',
  8592. renderer: Ext.util.Format.numberRenderer('0.000')
  8593. }]
  8594. Functions that only take a single argument can also be passed directly:
  8595. columns: [{
  8596. dataIndex: 'cost',
  8597. renderer: Ext.util.Format.usMoney
  8598. }, {
  8599. dataIndex: 'productCode',
  8600. renderer: Ext.util.Format.uppercase
  8601. }]
  8602. __Using with XTemplates__
  8603. XTemplates can also directly use Ext.util.Format functions:
  8604. new Ext.XTemplate([
  8605. 'Date: {startDate:date("Y-m-d")}',
  8606. 'Cost: {cost:usMoney}'
  8607. ]);
  8608. * @markdown
  8609. * @singleton
  8610. */
  8611. (function() {
  8612. Ext.ns('Ext.util');
  8613. Ext.util.Format = {};
  8614. var UtilFormat = Ext.util.Format,
  8615. stripTagsRE = /<\/?[^>]+>/gi,
  8616. stripScriptsRe = /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,
  8617. nl2brRe = /\r?\n/g,
  8618. // A RegExp to remove from a number format string, all characters except digits and '.'
  8619. formatCleanRe = /[^\d\.]/g,
  8620. // A RegExp to remove from a number format string, all characters except digits and the local decimal separator.
  8621. // Created on first use. The local decimal separator character must be initialized for this to be created.
  8622. I18NFormatCleanRe;
  8623. Ext.apply(UtilFormat, {
  8624. /**
  8625. * @property {String} thousandSeparator
  8626. * <p>The character that the {@link #number} function uses as a thousand separator.</p>
  8627. * <p>This may be overridden in a locale file.</p>
  8628. */
  8629. thousandSeparator: ',',
  8630. /**
  8631. * @property {String} decimalSeparator
  8632. * <p>The character that the {@link #number} function uses as a decimal point.</p>
  8633. * <p>This may be overridden in a locale file.</p>
  8634. */
  8635. decimalSeparator: '.',
  8636. /**
  8637. * @property {Number} currencyPrecision
  8638. * <p>The number of decimal places that the {@link #currency} function displays.</p>
  8639. * <p>This may be overridden in a locale file.</p>
  8640. */
  8641. currencyPrecision: 2,
  8642. /**
  8643. * @property {String} currencySign
  8644. * <p>The currency sign that the {@link #currency} function displays.</p>
  8645. * <p>This may be overridden in a locale file.</p>
  8646. */
  8647. currencySign: '$',
  8648. /**
  8649. * @property {Boolean} currencyAtEnd
  8650. * <p>This may be set to <code>true</code> to make the {@link #currency} function
  8651. * append the currency sign to the formatted value.</p>
  8652. * <p>This may be overridden in a locale file.</p>
  8653. */
  8654. currencyAtEnd: false,
  8655. /**
  8656. * Checks a reference and converts it to empty string if it is undefined
  8657. * @param {Object} value Reference to check
  8658. * @return {Object} Empty string if converted, otherwise the original value
  8659. */
  8660. undef : function(value) {
  8661. return value !== undefined ? value : "";
  8662. },
  8663. /**
  8664. * Checks a reference and converts it to the default value if it's empty
  8665. * @param {Object} value Reference to check
  8666. * @param {String} defaultValue The value to insert of it's undefined (defaults to "")
  8667. * @return {String}
  8668. */
  8669. defaultValue : function(value, defaultValue) {
  8670. return value !== undefined && value !== '' ? value : defaultValue;
  8671. },
  8672. /**
  8673. * Returns a substring from within an original string
  8674. * @param {String} value The original text
  8675. * @param {Number} start The start index of the substring
  8676. * @param {Number} length The length of the substring
  8677. * @return {String} The substring
  8678. */
  8679. substr : function(value, start, length) {
  8680. return String(value).substr(start, length);
  8681. },
  8682. /**
  8683. * Converts a string to all lower case letters
  8684. * @param {String} value The text to convert
  8685. * @return {String} The converted text
  8686. */
  8687. lowercase : function(value) {
  8688. return String(value).toLowerCase();
  8689. },
  8690. /**
  8691. * Converts a string to all upper case letters
  8692. * @param {String} value The text to convert
  8693. * @return {String} The converted text
  8694. */
  8695. uppercase : function(value) {
  8696. return String(value).toUpperCase();
  8697. },
  8698. /**
  8699. * Format a number as US currency
  8700. * @param {Number/String} value The numeric value to format
  8701. * @return {String} The formatted currency string
  8702. */
  8703. usMoney : function(v) {
  8704. return UtilFormat.currency(v, '$', 2);
  8705. },
  8706. /**
  8707. * Format a number as a currency
  8708. * @param {Number/String} value The numeric value to format
  8709. * @param {String} sign The currency sign to use (defaults to {@link #currencySign})
  8710. * @param {Number} decimals The number of decimals to use for the currency (defaults to {@link #currencyPrecision})
  8711. * @param {Boolean} end True if the currency sign should be at the end of the string (defaults to {@link #currencyAtEnd})
  8712. * @return {String} The formatted currency string
  8713. */
  8714. currency: function(v, currencySign, decimals, end) {
  8715. var negativeSign = '',
  8716. format = ",0",
  8717. i = 0;
  8718. v = v - 0;
  8719. if (v < 0) {
  8720. v = -v;
  8721. negativeSign = '-';
  8722. }
  8723. decimals = decimals || UtilFormat.currencyPrecision;
  8724. format += format + (decimals > 0 ? '.' : '');
  8725. for (; i < decimals; i++) {
  8726. format += '0';
  8727. }
  8728. v = UtilFormat.number(v, format);
  8729. if ((end || UtilFormat.currencyAtEnd) === true) {
  8730. return Ext.String.format("{0}{1}{2}", negativeSign, v, currencySign || UtilFormat.currencySign);
  8731. } else {
  8732. return Ext.String.format("{0}{1}{2}", negativeSign, currencySign || UtilFormat.currencySign, v);
  8733. }
  8734. },
  8735. /**
  8736. * Formats the passed date using the specified format pattern.
  8737. * @param {String/Date} value The value to format. If a string is passed, it is converted to a Date by the Javascript
  8738. * Date object's <a href="http://www.w3schools.com/jsref/jsref_parse.asp">parse()</a> method.
  8739. * @param {String} format (Optional) Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
  8740. * @return {String} The formatted date string.
  8741. */
  8742. date: function(v, format) {
  8743. if (!v) {
  8744. return "";
  8745. }
  8746. if (!Ext.isDate(v)) {
  8747. v = new Date(Date.parse(v));
  8748. }
  8749. return Ext.Date.dateFormat(v, format || Ext.Date.defaultFormat);
  8750. },
  8751. /**
  8752. * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
  8753. * @param {String} format Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
  8754. * @return {Function} The date formatting function
  8755. */
  8756. dateRenderer : function(format) {
  8757. return function(v) {
  8758. return UtilFormat.date(v, format);
  8759. };
  8760. },
  8761. /**
  8762. * Strips all HTML tags
  8763. * @param {Object} value The text from which to strip tags
  8764. * @return {String} The stripped text
  8765. */
  8766. stripTags : function(v) {
  8767. return !v ? v : String(v).replace(stripTagsRE, "");
  8768. },
  8769. /**
  8770. * Strips all script tags
  8771. * @param {Object} value The text from which to strip script tags
  8772. * @return {String} The stripped text
  8773. */
  8774. stripScripts : function(v) {
  8775. return !v ? v : String(v).replace(stripScriptsRe, "");
  8776. },
  8777. /**
  8778. * Simple format for a file size (xxx bytes, xxx KB, xxx MB)
  8779. * @param {Number/String} size The numeric value to format
  8780. * @return {String} The formatted file size
  8781. */
  8782. fileSize : function(size) {
  8783. if (size < 1024) {
  8784. return size + " bytes";
  8785. } else if (size < 1048576) {
  8786. return (Math.round(((size*10) / 1024))/10) + " KB";
  8787. } else {
  8788. return (Math.round(((size*10) / 1048576))/10) + " MB";
  8789. }
  8790. },
  8791. /**
  8792. * It does simple math for use in a template, for example:<pre><code>
  8793. * var tpl = new Ext.Template('{value} * 10 = {value:math("* 10")}');
  8794. * </code></pre>
  8795. * @return {Function} A function that operates on the passed value.
  8796. * @method
  8797. */
  8798. math : function(){
  8799. var fns = {};
  8800. return function(v, a){
  8801. if (!fns[a]) {
  8802. fns[a] = Ext.functionFactory('v', 'return v ' + a + ';');
  8803. }
  8804. return fns[a](v);
  8805. };
  8806. }(),
  8807. /**
  8808. * Rounds the passed number to the required decimal precision.
  8809. * @param {Number/String} value The numeric value to round.
  8810. * @param {Number} precision The number of decimal places to which to round the first parameter's value.
  8811. * @return {Number} The rounded value.
  8812. */
  8813. round : function(value, precision) {
  8814. var result = Number(value);
  8815. if (typeof precision == 'number') {
  8816. precision = Math.pow(10, precision);
  8817. result = Math.round(value * precision) / precision;
  8818. }
  8819. return result;
  8820. },
  8821. /**
  8822. * <p>Formats the passed number according to the passed format string.</p>
  8823. * <p>The number of digits after the decimal separator character specifies the number of
  8824. * decimal places in the resulting string. The <u>local-specific</u> decimal character is used in the result.</p>
  8825. * <p>The <i>presence</i> of a thousand separator character in the format string specifies that
  8826. * the <u>locale-specific</u> thousand separator (if any) is inserted separating thousand groups.</p>
  8827. * <p>By default, "," is expected as the thousand separator, and "." is expected as the decimal separator.</p>
  8828. * <p><b>New to Ext JS 4</b></p>
  8829. * <p>Locale-specific characters are always used in the formatted output when inserting
  8830. * thousand and decimal separators.</p>
  8831. * <p>The format string must specify separator characters according to US/UK conventions ("," as the
  8832. * thousand separator, and "." as the decimal separator)</p>
  8833. * <p>To allow specification of format strings according to local conventions for separator characters, add
  8834. * the string <code>/i</code> to the end of the format string.</p>
  8835. * <div style="margin-left:40px">examples (123456.789):
  8836. * <div style="margin-left:10px">
  8837. * 0 - (123456) show only digits, no precision<br>
  8838. * 0.00 - (123456.78) show only digits, 2 precision<br>
  8839. * 0.0000 - (123456.7890) show only digits, 4 precision<br>
  8840. * 0,000 - (123,456) show comma and digits, no precision<br>
  8841. * 0,000.00 - (123,456.78) show comma and digits, 2 precision<br>
  8842. * 0,0.00 - (123,456.78) shortcut method, show comma and digits, 2 precision<br>
  8843. * To allow specification of the formatting string using UK/US grouping characters (,) and decimal (.) for international numbers, add /i to the end.
  8844. * For example: 0.000,00/i
  8845. * </div></div>
  8846. * @param {Number} v The number to format.
  8847. * @param {String} format The way you would like to format this text.
  8848. * @return {String} The formatted number.
  8849. */
  8850. number: function(v, formatString) {
  8851. if (!formatString) {
  8852. return v;
  8853. }
  8854. v = Ext.Number.from(v, NaN);
  8855. if (isNaN(v)) {
  8856. return '';
  8857. }
  8858. var comma = UtilFormat.thousandSeparator,
  8859. dec = UtilFormat.decimalSeparator,
  8860. i18n = false,
  8861. neg = v < 0,
  8862. hasComma,
  8863. psplit;
  8864. v = Math.abs(v);
  8865. // The "/i" suffix allows caller to use a locale-specific formatting string.
  8866. // Clean the format string by removing all but numerals and the decimal separator.
  8867. // Then split the format string into pre and post decimal segments according to *what* the
  8868. // decimal separator is. If they are specifying "/i", they are using the local convention in the format string.
  8869. if (formatString.substr(formatString.length - 2) == '/i') {
  8870. if (!I18NFormatCleanRe) {
  8871. I18NFormatCleanRe = new RegExp('[^\\d\\' + UtilFormat.decimalSeparator + ']','g');
  8872. }
  8873. formatString = formatString.substr(0, formatString.length - 2);
  8874. i18n = true;
  8875. hasComma = formatString.indexOf(comma) != -1;
  8876. psplit = formatString.replace(I18NFormatCleanRe, '').split(dec);
  8877. } else {
  8878. hasComma = formatString.indexOf(',') != -1;
  8879. psplit = formatString.replace(formatCleanRe, '').split('.');
  8880. }
  8881. if (1 < psplit.length) {
  8882. v = v.toFixed(psplit[1].length);
  8883. } else if(2 < psplit.length) {
  8884. } else {
  8885. v = v.toFixed(0);
  8886. }
  8887. var fnum = v.toString();
  8888. psplit = fnum.split('.');
  8889. if (hasComma) {
  8890. var cnum = psplit[0],
  8891. parr = [],
  8892. j = cnum.length,
  8893. m = Math.floor(j / 3),
  8894. n = cnum.length % 3 || 3,
  8895. i;
  8896. for (i = 0; i < j; i += n) {
  8897. if (i !== 0) {
  8898. n = 3;
  8899. }
  8900. parr[parr.length] = cnum.substr(i, n);
  8901. m -= 1;
  8902. }
  8903. fnum = parr.join(comma);
  8904. if (psplit[1]) {
  8905. fnum += dec + psplit[1];
  8906. }
  8907. } else {
  8908. if (psplit[1]) {
  8909. fnum = psplit[0] + dec + psplit[1];
  8910. }
  8911. }
  8912. if (neg) {
  8913. /*
  8914. * Edge case. If we have a very small negative number it will get rounded to 0,
  8915. * however the initial check at the top will still report as negative. Replace
  8916. * everything but 1-9 and check if the string is empty to determine a 0 value.
  8917. */
  8918. neg = fnum.replace(/[^1-9]/g, '') !== '';
  8919. }
  8920. return (neg ? '-' : '') + formatString.replace(/[\d,?\.?]+/, fnum);
  8921. },
  8922. /**
  8923. * Returns a number rendering function that can be reused to apply a number format multiple times efficiently
  8924. * @param {String} format Any valid number format string for {@link #number}
  8925. * @return {Function} The number formatting function
  8926. */
  8927. numberRenderer : function(format) {
  8928. return function(v) {
  8929. return UtilFormat.number(v, format);
  8930. };
  8931. },
  8932. /**
  8933. * Selectively do a plural form of a word based on a numeric value. For example, in a template,
  8934. * {commentCount:plural("Comment")} would result in "1 Comment" if commentCount was 1 or would be "x Comments"
  8935. * if the value is 0 or greater than 1.
  8936. * @param {Number} value The value to compare against
  8937. * @param {String} singular The singular form of the word
  8938. * @param {String} plural (optional) The plural form of the word (defaults to the singular with an "s")
  8939. */
  8940. plural : function(v, s, p) {
  8941. return v +' ' + (v == 1 ? s : (p ? p : s+'s'));
  8942. },
  8943. /**
  8944. * Converts newline characters to the HTML tag &lt;br/>
  8945. * @param {String} The string value to format.
  8946. * @return {String} The string with embedded &lt;br/> tags in place of newlines.
  8947. */
  8948. nl2br : function(v) {
  8949. return Ext.isEmpty(v) ? '' : v.replace(nl2brRe, '<br/>');
  8950. },
  8951. /**
  8952. * Alias for {@link Ext.String#capitalize}.
  8953. * @method
  8954. * @alias Ext.String#capitalize
  8955. */
  8956. capitalize: Ext.String.capitalize,
  8957. /**
  8958. * Alias for {@link Ext.String#ellipsis}.
  8959. * @method
  8960. * @alias Ext.String#ellipsis
  8961. */
  8962. ellipsis: Ext.String.ellipsis,
  8963. /**
  8964. * Alias for {@link Ext.String#format}.
  8965. * @method
  8966. * @alias Ext.String#format
  8967. */
  8968. format: Ext.String.format,
  8969. /**
  8970. * Alias for {@link Ext.String#htmlDecode}.
  8971. * @method
  8972. * @alias Ext.String#htmlDecode
  8973. */
  8974. htmlDecode: Ext.String.htmlDecode,
  8975. /**
  8976. * Alias for {@link Ext.String#htmlEncode}.
  8977. * @method
  8978. * @alias Ext.String#htmlEncode
  8979. */
  8980. htmlEncode: Ext.String.htmlEncode,
  8981. /**
  8982. * Alias for {@link Ext.String#leftPad}.
  8983. * @method
  8984. * @alias Ext.String#leftPad
  8985. */
  8986. leftPad: Ext.String.leftPad,
  8987. /**
  8988. * Alias for {@link Ext.String#trim}.
  8989. * @method
  8990. * @alias Ext.String#trim
  8991. */
  8992. trim : Ext.String.trim,
  8993. /**
  8994. * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations
  8995. * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result)
  8996. * @param {Number/String} v The encoded margins
  8997. * @return {Object} An object with margin sizes for top, right, bottom and left
  8998. */
  8999. parseBox : function(box) {
  9000. if (Ext.isNumber(box)) {
  9001. box = box.toString();
  9002. }
  9003. var parts = box.split(' '),
  9004. ln = parts.length;
  9005. if (ln == 1) {
  9006. parts[1] = parts[2] = parts[3] = parts[0];
  9007. }
  9008. else if (ln == 2) {
  9009. parts[2] = parts[0];
  9010. parts[3] = parts[1];
  9011. }
  9012. else if (ln == 3) {
  9013. parts[3] = parts[1];
  9014. }
  9015. return {
  9016. top :parseInt(parts[0], 10) || 0,
  9017. right :parseInt(parts[1], 10) || 0,
  9018. bottom:parseInt(parts[2], 10) || 0,
  9019. left :parseInt(parts[3], 10) || 0
  9020. };
  9021. },
  9022. /**
  9023. * Escapes the passed string for use in a regular expression
  9024. * @param {String} str
  9025. * @return {String}
  9026. */
  9027. escapeRegex : function(s) {
  9028. return s.replace(/([\-.*+?\^${}()|\[\]\/\\])/g, "\\$1");
  9029. }
  9030. });
  9031. })();
  9032. /**
  9033. * @class Ext.util.TaskRunner
  9034. * Provides the ability to execute one or more arbitrary tasks in a multithreaded
  9035. * manner. Generally, you can use the singleton {@link Ext.TaskManager} instead, but
  9036. * if needed, you can create separate instances of TaskRunner. Any number of
  9037. * separate tasks can be started at any time and will run independently of each
  9038. * other. Example usage:
  9039. * <pre><code>
  9040. // Start a simple clock task that updates a div once per second
  9041. var updateClock = function(){
  9042. Ext.fly('clock').update(new Date().format('g:i:s A'));
  9043. }
  9044. var task = {
  9045. run: updateClock,
  9046. interval: 1000 //1 second
  9047. }
  9048. var runner = new Ext.util.TaskRunner();
  9049. runner.start(task);
  9050. // equivalent using TaskManager
  9051. Ext.TaskManager.start({
  9052. run: updateClock,
  9053. interval: 1000
  9054. });
  9055. * </code></pre>
  9056. * <p>See the {@link #start} method for details about how to configure a task object.</p>
  9057. * Also see {@link Ext.util.DelayedTask}.
  9058. *
  9059. * @constructor
  9060. * @param {Number} [interval=10] The minimum precision in milliseconds supported by this TaskRunner instance
  9061. */
  9062. Ext.ns('Ext.util');
  9063. Ext.util.TaskRunner = function(interval) {
  9064. interval = interval || 10;
  9065. var tasks = [],
  9066. removeQueue = [],
  9067. id = 0,
  9068. running = false,
  9069. // private
  9070. stopThread = function() {
  9071. running = false;
  9072. clearInterval(id);
  9073. id = 0;
  9074. },
  9075. // private
  9076. startThread = function() {
  9077. if (!running) {
  9078. running = true;
  9079. id = setInterval(runTasks, interval);
  9080. }
  9081. },
  9082. // private
  9083. removeTask = function(t) {
  9084. removeQueue.push(t);
  9085. if (t.onStop) {
  9086. t.onStop.apply(t.scope || t);
  9087. }
  9088. },
  9089. // private
  9090. runTasks = function() {
  9091. var rqLen = removeQueue.length,
  9092. now = new Date().getTime(),
  9093. i;
  9094. if (rqLen > 0) {
  9095. for (i = 0; i < rqLen; i++) {
  9096. Ext.Array.remove(tasks, removeQueue[i]);
  9097. }
  9098. removeQueue = [];
  9099. if (tasks.length < 1) {
  9100. stopThread();
  9101. return;
  9102. }
  9103. }
  9104. i = 0;
  9105. var t,
  9106. itime,
  9107. rt,
  9108. len = tasks.length;
  9109. for (; i < len; ++i) {
  9110. t = tasks[i];
  9111. itime = now - t.taskRunTime;
  9112. if (t.interval <= itime) {
  9113. rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
  9114. t.taskRunTime = now;
  9115. if (rt === false || t.taskRunCount === t.repeat) {
  9116. removeTask(t);
  9117. return;
  9118. }
  9119. }
  9120. if (t.duration && t.duration <= (now - t.taskStartTime)) {
  9121. removeTask(t);
  9122. }
  9123. }
  9124. };
  9125. /**
  9126. * Starts a new task.
  9127. * @method start
  9128. * @param {Object} task <p>A config object that supports the following properties:<ul>
  9129. * <li><code>run</code> : Function<div class="sub-desc"><p>The function to execute each time the task is invoked. The
  9130. * function will be called at each interval and passed the <code>args</code> argument if specified, and the
  9131. * current invocation count if not.</p>
  9132. * <p>If a particular scope (<code>this</code> reference) is required, be sure to specify it using the <code>scope</code> argument.</p>
  9133. * <p>Return <code>false</code> from this function to terminate the task.</p></div></li>
  9134. * <li><code>interval</code> : Number<div class="sub-desc">The frequency in milliseconds with which the task
  9135. * should be invoked.</div></li>
  9136. * <li><code>args</code> : Array<div class="sub-desc">(optional) An array of arguments to be passed to the function
  9137. * specified by <code>run</code>. If not specified, the current invocation count is passed.</div></li>
  9138. * <li><code>scope</code> : Object<div class="sub-desc">(optional) The scope (<tt>this</tt> reference) in which to execute the
  9139. * <code>run</code> function. Defaults to the task config object.</div></li>
  9140. * <li><code>duration</code> : Number<div class="sub-desc">(optional) The length of time in milliseconds to invoke
  9141. * the task before stopping automatically (defaults to indefinite).</div></li>
  9142. * <li><code>repeat</code> : Number<div class="sub-desc">(optional) The number of times to invoke the task before
  9143. * stopping automatically (defaults to indefinite).</div></li>
  9144. * </ul></p>
  9145. * <p>Before each invocation, Ext injects the property <code>taskRunCount</code> into the task object so
  9146. * that calculations based on the repeat count can be performed.</p>
  9147. * @return {Object} The task
  9148. */
  9149. this.start = function(task) {
  9150. tasks.push(task);
  9151. task.taskStartTime = new Date().getTime();
  9152. task.taskRunTime = 0;
  9153. task.taskRunCount = 0;
  9154. startThread();
  9155. return task;
  9156. };
  9157. /**
  9158. * Stops an existing running task.
  9159. * @method stop
  9160. * @param {Object} task The task to stop
  9161. * @return {Object} The task
  9162. */
  9163. this.stop = function(task) {
  9164. removeTask(task);
  9165. return task;
  9166. };
  9167. /**
  9168. * Stops all tasks that are currently running.
  9169. * @method stopAll
  9170. */
  9171. this.stopAll = function() {
  9172. stopThread();
  9173. for (var i = 0, len = tasks.length; i < len; i++) {
  9174. if (tasks[i].onStop) {
  9175. tasks[i].onStop();
  9176. }
  9177. }
  9178. tasks = [];
  9179. removeQueue = [];
  9180. };
  9181. };
  9182. /**
  9183. * @class Ext.TaskManager
  9184. * @extends Ext.util.TaskRunner
  9185. * A static {@link Ext.util.TaskRunner} instance that can be used to start and stop arbitrary tasks. See
  9186. * {@link Ext.util.TaskRunner} for supported methods and task config properties.
  9187. * <pre><code>
  9188. // Start a simple clock task that updates a div once per second
  9189. var task = {
  9190. run: function(){
  9191. Ext.fly('clock').update(new Date().format('g:i:s A'));
  9192. },
  9193. interval: 1000 //1 second
  9194. }
  9195. Ext.TaskManager.start(task);
  9196. </code></pre>
  9197. * <p>See the {@link #start} method for details about how to configure a task object.</p>
  9198. * @singleton
  9199. */
  9200. Ext.TaskManager = Ext.create('Ext.util.TaskRunner');
  9201. /**
  9202. * @class Ext.is
  9203. *
  9204. * Determines information about the current platform the application is running on.
  9205. *
  9206. * @singleton
  9207. */
  9208. Ext.is = {
  9209. init : function(navigator) {
  9210. var platforms = this.platforms,
  9211. ln = platforms.length,
  9212. i, platform;
  9213. navigator = navigator || window.navigator;
  9214. for (i = 0; i < ln; i++) {
  9215. platform = platforms[i];
  9216. this[platform.identity] = platform.regex.test(navigator[platform.property]);
  9217. }
  9218. /**
  9219. * @property Desktop True if the browser is running on a desktop machine
  9220. * @type {Boolean}
  9221. */
  9222. this.Desktop = this.Mac || this.Windows || (this.Linux && !this.Android);
  9223. /**
  9224. * @property Tablet True if the browser is running on a tablet (iPad)
  9225. */
  9226. this.Tablet = this.iPad;
  9227. /**
  9228. * @property Phone True if the browser is running on a phone.
  9229. * @type {Boolean}
  9230. */
  9231. this.Phone = !this.Desktop && !this.Tablet;
  9232. /**
  9233. * @property iOS True if the browser is running on iOS
  9234. * @type {Boolean}
  9235. */
  9236. this.iOS = this.iPhone || this.iPad || this.iPod;
  9237. /**
  9238. * @property Standalone Detects when application has been saved to homescreen.
  9239. * @type {Boolean}
  9240. */
  9241. this.Standalone = !!window.navigator.standalone;
  9242. },
  9243. /**
  9244. * @property iPhone True when the browser is running on a iPhone
  9245. * @type {Boolean}
  9246. */
  9247. platforms: [{
  9248. property: 'platform',
  9249. regex: /iPhone/i,
  9250. identity: 'iPhone'
  9251. },
  9252. /**
  9253. * @property iPod True when the browser is running on a iPod
  9254. * @type {Boolean}
  9255. */
  9256. {
  9257. property: 'platform',
  9258. regex: /iPod/i,
  9259. identity: 'iPod'
  9260. },
  9261. /**
  9262. * @property iPad True when the browser is running on a iPad
  9263. * @type {Boolean}
  9264. */
  9265. {
  9266. property: 'userAgent',
  9267. regex: /iPad/i,
  9268. identity: 'iPad'
  9269. },
  9270. /**
  9271. * @property Blackberry True when the browser is running on a Blackberry
  9272. * @type {Boolean}
  9273. */
  9274. {
  9275. property: 'userAgent',
  9276. regex: /Blackberry/i,
  9277. identity: 'Blackberry'
  9278. },
  9279. /**
  9280. * @property Android True when the browser is running on an Android device
  9281. * @type {Boolean}
  9282. */
  9283. {
  9284. property: 'userAgent',
  9285. regex: /Android/i,
  9286. identity: 'Android'
  9287. },
  9288. /**
  9289. * @property Mac True when the browser is running on a Mac
  9290. * @type {Boolean}
  9291. */
  9292. {
  9293. property: 'platform',
  9294. regex: /Mac/i,
  9295. identity: 'Mac'
  9296. },
  9297. /**
  9298. * @property Windows True when the browser is running on Windows
  9299. * @type {Boolean}
  9300. */
  9301. {
  9302. property: 'platform',
  9303. regex: /Win/i,
  9304. identity: 'Windows'
  9305. },
  9306. /**
  9307. * @property Linux True when the browser is running on Linux
  9308. * @type {Boolean}
  9309. */
  9310. {
  9311. property: 'platform',
  9312. regex: /Linux/i,
  9313. identity: 'Linux'
  9314. }]
  9315. };
  9316. Ext.is.init();
  9317. /**
  9318. * @class Ext.supports
  9319. *
  9320. * Determines information about features are supported in the current environment
  9321. *
  9322. * @singleton
  9323. */
  9324. Ext.supports = {
  9325. init : function() {
  9326. var doc = document,
  9327. div = doc.createElement('div'),
  9328. tests = this.tests,
  9329. ln = tests.length,
  9330. i, test;
  9331. div.innerHTML = [
  9332. '<div style="height:30px;width:50px;">',
  9333. '<div style="height:20px;width:20px;"></div>',
  9334. '</div>',
  9335. '<div style="width: 200px; height: 200px; position: relative; padding: 5px;">',
  9336. '<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></div>',
  9337. '</div>',
  9338. '<div style="float:left; background-color:transparent;"></div>'
  9339. ].join('');
  9340. doc.body.appendChild(div);
  9341. for (i = 0; i < ln; i++) {
  9342. test = tests[i];
  9343. this[test.identity] = test.fn.call(this, doc, div);
  9344. }
  9345. doc.body.removeChild(div);
  9346. },
  9347. /**
  9348. * @property CSS3BoxShadow True if document environment supports the CSS3 box-shadow style.
  9349. * @type {Boolean}
  9350. */
  9351. CSS3BoxShadow: Ext.isDefined(document.documentElement.style.boxShadow),
  9352. /**
  9353. * @property ClassList True if document environment supports the HTML5 classList API.
  9354. * @type {Boolean}
  9355. */
  9356. ClassList: !!document.documentElement.classList,
  9357. /**
  9358. * @property OrientationChange True if the device supports orientation change
  9359. * @type {Boolean}
  9360. */
  9361. OrientationChange: ((typeof window.orientation != 'undefined') && ('onorientationchange' in window)),
  9362. /**
  9363. * @property DeviceMotion True if the device supports device motion (acceleration and rotation rate)
  9364. * @type {Boolean}
  9365. */
  9366. DeviceMotion: ('ondevicemotion' in window),
  9367. /**
  9368. * @property Touch True if the device supports touch
  9369. * @type {Boolean}
  9370. */
  9371. // is.Desktop is needed due to the bug in Chrome 5.0.375, Safari 3.1.2
  9372. // and Safari 4.0 (they all have 'ontouchstart' in the window object).
  9373. Touch: ('ontouchstart' in window) && (!Ext.is.Desktop),
  9374. tests: [
  9375. /**
  9376. * @property Transitions True if the device supports CSS3 Transitions
  9377. * @type {Boolean}
  9378. */
  9379. {
  9380. identity: 'Transitions',
  9381. fn: function(doc, div) {
  9382. var prefix = [
  9383. 'webkit',
  9384. 'Moz',
  9385. 'o',
  9386. 'ms',
  9387. 'khtml'
  9388. ],
  9389. TE = 'TransitionEnd',
  9390. transitionEndName = [
  9391. prefix[0] + TE,
  9392. 'transitionend', //Moz bucks the prefixing convention
  9393. prefix[2] + TE,
  9394. prefix[3] + TE,
  9395. prefix[4] + TE
  9396. ],
  9397. ln = prefix.length,
  9398. i = 0,
  9399. out = false;
  9400. div = Ext.get(div);
  9401. for (; i < ln; i++) {
  9402. if (div.getStyle(prefix[i] + "TransitionProperty")) {
  9403. Ext.supports.CSS3Prefix = prefix[i];
  9404. Ext.supports.CSS3TransitionEnd = transitionEndName[i];
  9405. out = true;
  9406. break;
  9407. }
  9408. }
  9409. return out;
  9410. }
  9411. },
  9412. /**
  9413. * @property RightMargin True if the device supports right margin.
  9414. * See https://bugs.webkit.org/show_bug.cgi?id=13343 for why this is needed.
  9415. * @type {Boolean}
  9416. */
  9417. {
  9418. identity: 'RightMargin',
  9419. fn: function(doc, div) {
  9420. var view = doc.defaultView;
  9421. return !(view && view.getComputedStyle(div.firstChild.firstChild, null).marginRight != '0px');
  9422. }
  9423. },
  9424. /**
  9425. * @property DisplayChangeInputSelectionBug True if INPUT elements lose their
  9426. * selection when their display style is changed. Essentially, if a text input
  9427. * has focus and its display style is changed, the I-beam disappears.
  9428. *
  9429. * This bug is encountered due to the work around in place for the {@link #RightMargin}
  9430. * bug. This has been observed in Safari 4.0.4 and older, and appears to be fixed
  9431. * in Safari 5. It's not clear if Safari 4.1 has the bug, but it has the same WebKit
  9432. * version number as Safari 5 (according to http://unixpapa.com/js/gecko.html).
  9433. */
  9434. {
  9435. identity: 'DisplayChangeInputSelectionBug',
  9436. fn: function() {
  9437. var webKitVersion = Ext.webKitVersion;
  9438. // WebKit but older than Safari 5 or Chrome 6:
  9439. return 0 < webKitVersion && webKitVersion < 533;
  9440. }
  9441. },
  9442. /**
  9443. * @property DisplayChangeTextAreaSelectionBug True if TEXTAREA elements lose their
  9444. * selection when their display style is changed. Essentially, if a text area has
  9445. * focus and its display style is changed, the I-beam disappears.
  9446. *
  9447. * This bug is encountered due to the work around in place for the {@link #RightMargin}
  9448. * bug. This has been observed in Chrome 10 and Safari 5 and older, and appears to
  9449. * be fixed in Chrome 11.
  9450. */
  9451. {
  9452. identity: 'DisplayChangeTextAreaSelectionBug',
  9453. fn: function() {
  9454. var webKitVersion = Ext.webKitVersion;
  9455. /*
  9456. Has bug w/textarea:
  9457. (Chrome) Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-US)
  9458. AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.127
  9459. Safari/534.16
  9460. (Safari) Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-us)
  9461. AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5
  9462. Safari/533.21.1
  9463. No bug:
  9464. (Chrome) Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_7)
  9465. AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.57
  9466. Safari/534.24
  9467. */
  9468. return 0 < webKitVersion && webKitVersion < 534.24;
  9469. }
  9470. },
  9471. /**
  9472. * @property TransparentColor True if the device supports transparent color
  9473. * @type {Boolean}
  9474. */
  9475. {
  9476. identity: 'TransparentColor',
  9477. fn: function(doc, div, view) {
  9478. view = doc.defaultView;
  9479. return !(view && view.getComputedStyle(div.lastChild, null).backgroundColor != 'transparent');
  9480. }
  9481. },
  9482. /**
  9483. * @property ComputedStyle True if the browser supports document.defaultView.getComputedStyle()
  9484. * @type {Boolean}
  9485. */
  9486. {
  9487. identity: 'ComputedStyle',
  9488. fn: function(doc, div, view) {
  9489. view = doc.defaultView;
  9490. return view && view.getComputedStyle;
  9491. }
  9492. },
  9493. /**
  9494. * @property SVG True if the device supports SVG
  9495. * @type {Boolean}
  9496. */
  9497. {
  9498. identity: 'Svg',
  9499. fn: function(doc) {
  9500. return !!doc.createElementNS && !!doc.createElementNS( "http:/" + "/www.w3.org/2000/svg", "svg").createSVGRect;
  9501. }
  9502. },
  9503. /**
  9504. * @property Canvas True if the device supports Canvas
  9505. * @type {Boolean}
  9506. */
  9507. {
  9508. identity: 'Canvas',
  9509. fn: function(doc) {
  9510. return !!doc.createElement('canvas').getContext;
  9511. }
  9512. },
  9513. /**
  9514. * @property VML True if the device supports VML
  9515. * @type {Boolean}
  9516. */
  9517. {
  9518. identity: 'Vml',
  9519. fn: function(doc) {
  9520. var d = doc.createElement("div");
  9521. d.innerHTML = "<!--[if vml]><br><br><![endif]-->";
  9522. return (d.childNodes.length == 2);
  9523. }
  9524. },
  9525. /**
  9526. * @property Float True if the device supports CSS float
  9527. * @type {Boolean}
  9528. */
  9529. {
  9530. identity: 'Float',
  9531. fn: function(doc, div) {
  9532. return !!div.lastChild.style.cssFloat;
  9533. }
  9534. },
  9535. /**
  9536. * @property AudioTag True if the device supports the HTML5 audio tag
  9537. * @type {Boolean}
  9538. */
  9539. {
  9540. identity: 'AudioTag',
  9541. fn: function(doc) {
  9542. return !!doc.createElement('audio').canPlayType;
  9543. }
  9544. },
  9545. /**
  9546. * @property History True if the device supports HTML5 history
  9547. * @type {Boolean}
  9548. */
  9549. {
  9550. identity: 'History',
  9551. fn: function() {
  9552. return !!(window.history && history.pushState);
  9553. }
  9554. },
  9555. /**
  9556. * @property CSS3DTransform True if the device supports CSS3DTransform
  9557. * @type {Boolean}
  9558. */
  9559. {
  9560. identity: 'CSS3DTransform',
  9561. fn: function() {
  9562. return (typeof WebKitCSSMatrix != 'undefined' && new WebKitCSSMatrix().hasOwnProperty('m41'));
  9563. }
  9564. },
  9565. /**
  9566. * @property CSS3LinearGradient True if the device supports CSS3 linear gradients
  9567. * @type {Boolean}
  9568. */
  9569. {
  9570. identity: 'CSS3LinearGradient',
  9571. fn: function(doc, div) {
  9572. var property = 'background-image:',
  9573. webkit = '-webkit-gradient(linear, left top, right bottom, from(black), to(white))',
  9574. w3c = 'linear-gradient(left top, black, white)',
  9575. moz = '-moz-' + w3c,
  9576. options = [property + webkit, property + w3c, property + moz];
  9577. div.style.cssText = options.join(';');
  9578. return ("" + div.style.backgroundImage).indexOf('gradient') !== -1;
  9579. }
  9580. },
  9581. /**
  9582. * @property CSS3BorderRadius True if the device supports CSS3 border radius
  9583. * @type {Boolean}
  9584. */
  9585. {
  9586. identity: 'CSS3BorderRadius',
  9587. fn: function(doc, div) {
  9588. var domPrefixes = ['borderRadius', 'BorderRadius', 'MozBorderRadius', 'WebkitBorderRadius', 'OBorderRadius', 'KhtmlBorderRadius'],
  9589. pass = false,
  9590. i;
  9591. for (i = 0; i < domPrefixes.length; i++) {
  9592. if (document.body.style[domPrefixes[i]] !== undefined) {
  9593. return true;
  9594. }
  9595. }
  9596. return pass;
  9597. }
  9598. },
  9599. /**
  9600. * @property GeoLocation True if the device supports GeoLocation
  9601. * @type {Boolean}
  9602. */
  9603. {
  9604. identity: 'GeoLocation',
  9605. fn: function() {
  9606. return (typeof navigator != 'undefined' && typeof navigator.geolocation != 'undefined') || (typeof google != 'undefined' && typeof google.gears != 'undefined');
  9607. }
  9608. },
  9609. /**
  9610. * @property MouseEnterLeave True if the browser supports mouseenter and mouseleave events
  9611. * @type {Boolean}
  9612. */
  9613. {
  9614. identity: 'MouseEnterLeave',
  9615. fn: function(doc, div){
  9616. return ('onmouseenter' in div && 'onmouseleave' in div);
  9617. }
  9618. },
  9619. /**
  9620. * @property MouseWheel True if the browser supports the mousewheel event
  9621. * @type {Boolean}
  9622. */
  9623. {
  9624. identity: 'MouseWheel',
  9625. fn: function(doc, div) {
  9626. return ('onmousewheel' in div);
  9627. }
  9628. },
  9629. /**
  9630. * @property Opacity True if the browser supports normal css opacity
  9631. * @type {Boolean}
  9632. */
  9633. {
  9634. identity: 'Opacity',
  9635. fn: function(doc, div){
  9636. // Not a strict equal comparison in case opacity can be converted to a number.
  9637. if (Ext.isIE6 || Ext.isIE7 || Ext.isIE8) {
  9638. return false;
  9639. }
  9640. div.firstChild.style.cssText = 'opacity:0.73';
  9641. return div.firstChild.style.opacity == '0.73';
  9642. }
  9643. },
  9644. /**
  9645. * @property Placeholder True if the browser supports the HTML5 placeholder attribute on inputs
  9646. * @type {Boolean}
  9647. */
  9648. {
  9649. identity: 'Placeholder',
  9650. fn: function(doc) {
  9651. return 'placeholder' in doc.createElement('input');
  9652. }
  9653. },
  9654. /**
  9655. * @property Direct2DBug True if when asking for an element's dimension via offsetWidth or offsetHeight,
  9656. * getBoundingClientRect, etc. the browser returns the subpixel width rounded to the nearest pixel.
  9657. * @type {Boolean}
  9658. */
  9659. {
  9660. identity: 'Direct2DBug',
  9661. fn: function() {
  9662. return Ext.isString(document.body.style.msTransformOrigin);
  9663. }
  9664. },
  9665. /**
  9666. * @property BoundingClientRect True if the browser supports the getBoundingClientRect method on elements
  9667. * @type {Boolean}
  9668. */
  9669. {
  9670. identity: 'BoundingClientRect',
  9671. fn: function(doc, div) {
  9672. return Ext.isFunction(div.getBoundingClientRect);
  9673. }
  9674. },
  9675. {
  9676. identity: 'IncludePaddingInWidthCalculation',
  9677. fn: function(doc, div){
  9678. var el = Ext.get(div.childNodes[1].firstChild);
  9679. return el.getWidth() == 210;
  9680. }
  9681. },
  9682. {
  9683. identity: 'IncludePaddingInHeightCalculation',
  9684. fn: function(doc, div){
  9685. var el = Ext.get(div.childNodes[1].firstChild);
  9686. return el.getHeight() == 210;
  9687. }
  9688. },
  9689. /**
  9690. * @property ArraySort True if the Array sort native method isn't bugged.
  9691. * @type {Boolean}
  9692. */
  9693. {
  9694. identity: 'ArraySort',
  9695. fn: function() {
  9696. var a = [1,2,3,4,5].sort(function(){ return 0; });
  9697. return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5;
  9698. }
  9699. },
  9700. /**
  9701. * @property Range True if browser support document.createRange native method.
  9702. * @type {Boolean}
  9703. */
  9704. {
  9705. identity: 'Range',
  9706. fn: function() {
  9707. return !!document.createRange;
  9708. }
  9709. },
  9710. /**
  9711. * @property CreateContextualFragment True if browser support CreateContextualFragment range native methods.
  9712. * @type {Boolean}
  9713. */
  9714. {
  9715. identity: 'CreateContextualFragment',
  9716. fn: function() {
  9717. var range = Ext.supports.Range ? document.createRange() : false;
  9718. return range && !!range.createContextualFragment;
  9719. }
  9720. },
  9721. /**
  9722. * @property WindowOnError True if browser supports window.onerror.
  9723. * @type {Boolean}
  9724. */
  9725. {
  9726. identity: 'WindowOnError',
  9727. fn: function () {
  9728. // sadly, we cannot feature detect this...
  9729. return Ext.isIE || Ext.isGecko || Ext.webKitVersion >= 534.16; // Chrome 10+
  9730. }
  9731. }
  9732. ]
  9733. };
  9734. /*
  9735. This file is part of Ext JS 4
  9736. Copyright (c) 2011 Sencha Inc
  9737. Contact: http://www.sencha.com/contact
  9738. GNU General Public License Usage
  9739. This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
  9740. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
  9741. */
  9742. /**
  9743. * @class Ext.DomHelper
  9744. * @alternateClassName Ext.core.DomHelper
  9745. *
  9746. * <p>The DomHelper class provides a layer of abstraction from DOM and transparently supports creating
  9747. * elements via DOM or using HTML fragments. It also has the ability to create HTML fragment templates
  9748. * from your DOM building code.</p>
  9749. *
  9750. * <p><b><u>DomHelper element specification object</u></b></p>
  9751. * <p>A specification object is used when creating elements. Attributes of this object
  9752. * are assumed to be element attributes, except for 4 special attributes:
  9753. * <div class="mdetail-params"><ul>
  9754. * <li><b><tt>tag</tt></b> : <div class="sub-desc">The tag name of the element</div></li>
  9755. * <li><b><tt>children</tt></b> : or <tt>cn</tt><div class="sub-desc">An array of the
  9756. * same kind of element definition objects to be created and appended. These can be nested
  9757. * as deep as you want.</div></li>
  9758. * <li><b><tt>cls</tt></b> : <div class="sub-desc">The class attribute of the element.
  9759. * This will end up being either the "class" attribute on a HTML fragment or className
  9760. * for a DOM node, depending on whether DomHelper is using fragments or DOM.</div></li>
  9761. * <li><b><tt>html</tt></b> : <div class="sub-desc">The innerHTML for the element</div></li>
  9762. * </ul></div></p>
  9763. * <p><b>NOTE:</b> For other arbitrary attributes, the value will currently <b>not</b> be automatically
  9764. * HTML-escaped prior to building the element's HTML string. This means that if your attribute value
  9765. * contains special characters that would not normally be allowed in a double-quoted attribute value,
  9766. * you <b>must</b> manually HTML-encode it beforehand (see {@link Ext.String#htmlEncode}) or risk
  9767. * malformed HTML being created. This behavior may change in a future release.</p>
  9768. *
  9769. * <p><b><u>Insertion methods</u></b></p>
  9770. * <p>Commonly used insertion methods:
  9771. * <div class="mdetail-params"><ul>
  9772. * <li><tt>{@link #append}</tt> : <div class="sub-desc"></div></li>
  9773. * <li><tt>{@link #insertBefore}</tt> : <div class="sub-desc"></div></li>
  9774. * <li><tt>{@link #insertAfter}</tt> : <div class="sub-desc"></div></li>
  9775. * <li><tt>{@link #overwrite}</tt> : <div class="sub-desc"></div></li>
  9776. * <li><tt>{@link #createTemplate}</tt> : <div class="sub-desc"></div></li>
  9777. * <li><tt>{@link #insertHtml}</tt> : <div class="sub-desc"></div></li>
  9778. * </ul></div></p>
  9779. *
  9780. * <p><b><u>Example</u></b></p>
  9781. * <p>This is an example, where an unordered list with 3 children items is appended to an existing
  9782. * element with id <tt>'my-div'</tt>:<br>
  9783. <pre><code>
  9784. var dh = Ext.DomHelper; // create shorthand alias
  9785. // specification object
  9786. var spec = {
  9787. id: 'my-ul',
  9788. tag: 'ul',
  9789. cls: 'my-list',
  9790. // append children after creating
  9791. children: [ // may also specify 'cn' instead of 'children'
  9792. {tag: 'li', id: 'item0', html: 'List Item 0'},
  9793. {tag: 'li', id: 'item1', html: 'List Item 1'},
  9794. {tag: 'li', id: 'item2', html: 'List Item 2'}
  9795. ]
  9796. };
  9797. var list = dh.append(
  9798. 'my-div', // the context element 'my-div' can either be the id or the actual node
  9799. spec // the specification object
  9800. );
  9801. </code></pre></p>
  9802. * <p>Element creation specification parameters in this class may also be passed as an Array of
  9803. * specification objects. This can be used to insert multiple sibling nodes into an existing
  9804. * container very efficiently. For example, to add more list items to the example above:<pre><code>
  9805. dh.append('my-ul', [
  9806. {tag: 'li', id: 'item3', html: 'List Item 3'},
  9807. {tag: 'li', id: 'item4', html: 'List Item 4'}
  9808. ]);
  9809. * </code></pre></p>
  9810. *
  9811. * <p><b><u>Templating</u></b></p>
  9812. * <p>The real power is in the built-in templating. Instead of creating or appending any elements,
  9813. * <tt>{@link #createTemplate}</tt> returns a Template object which can be used over and over to
  9814. * insert new elements. Revisiting the example above, we could utilize templating this time:
  9815. * <pre><code>
  9816. // create the node
  9817. var list = dh.append('my-div', {tag: 'ul', cls: 'my-list'});
  9818. // get template
  9819. var tpl = dh.createTemplate({tag: 'li', id: 'item{0}', html: 'List Item {0}'});
  9820. for(var i = 0; i < 5, i++){
  9821. tpl.append(list, [i]); // use template to append to the actual node
  9822. }
  9823. * </code></pre></p>
  9824. * <p>An example using a template:<pre><code>
  9825. var html = '<a id="{0}" href="{1}" class="nav">{2}</a>';
  9826. var tpl = new Ext.DomHelper.createTemplate(html);
  9827. tpl.append('blog-roll', ['link1', 'http://www.edspencer.net/', "Ed&#39;s Site"]);
  9828. tpl.append('blog-roll', ['link2', 'http://www.dustindiaz.com/', "Dustin&#39;s Site"]);
  9829. * </code></pre></p>
  9830. *
  9831. * <p>The same example using named parameters:<pre><code>
  9832. var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
  9833. var tpl = new Ext.DomHelper.createTemplate(html);
  9834. tpl.append('blog-roll', {
  9835. id: 'link1',
  9836. url: 'http://www.edspencer.net/',
  9837. text: "Ed&#39;s Site"
  9838. });
  9839. tpl.append('blog-roll', {
  9840. id: 'link2',
  9841. url: 'http://www.dustindiaz.com/',
  9842. text: "Dustin&#39;s Site"
  9843. });
  9844. * </code></pre></p>
  9845. *
  9846. * <p><b><u>Compiling Templates</u></b></p>
  9847. * <p>Templates are applied using regular expressions. The performance is great, but if
  9848. * you are adding a bunch of DOM elements using the same template, you can increase
  9849. * performance even further by {@link Ext.Template#compile "compiling"} the template.
  9850. * The way "{@link Ext.Template#compile compile()}" works is the template is parsed and
  9851. * broken up at the different variable points and a dynamic function is created and eval'ed.
  9852. * The generated function performs string concatenation of these parts and the passed
  9853. * variables instead of using regular expressions.
  9854. * <pre><code>
  9855. var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
  9856. var tpl = new Ext.DomHelper.createTemplate(html);
  9857. tpl.compile();
  9858. //... use template like normal
  9859. * </code></pre></p>
  9860. *
  9861. * <p><b><u>Performance Boost</u></b></p>
  9862. * <p>DomHelper will transparently create HTML fragments when it can. Using HTML fragments instead
  9863. * of DOM can significantly boost performance.</p>
  9864. * <p>Element creation specification parameters may also be strings. If {@link #useDom} is <tt>false</tt>,
  9865. * then the string is used as innerHTML. If {@link #useDom} is <tt>true</tt>, a string specification
  9866. * results in the creation of a text node. Usage:</p>
  9867. * <pre><code>
  9868. Ext.DomHelper.useDom = true; // force it to use DOM; reduces performance
  9869. * </code></pre>
  9870. * @singleton
  9871. */
  9872. Ext.ns('Ext.core');
  9873. Ext.core.DomHelper = Ext.DomHelper = function(){
  9874. var tempTableEl = null,
  9875. emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i,
  9876. tableRe = /^table|tbody|tr|td$/i,
  9877. confRe = /tag|children|cn|html$/i,
  9878. tableElRe = /td|tr|tbody/i,
  9879. endRe = /end/i,
  9880. pub,
  9881. // kill repeat to save bytes
  9882. afterbegin = 'afterbegin',
  9883. afterend = 'afterend',
  9884. beforebegin = 'beforebegin',
  9885. beforeend = 'beforeend',
  9886. ts = '<table>',
  9887. te = '</table>',
  9888. tbs = ts+'<tbody>',
  9889. tbe = '</tbody>'+te,
  9890. trs = tbs + '<tr>',
  9891. tre = '</tr>'+tbe;
  9892. // private
  9893. function doInsert(el, o, returnElement, pos, sibling, append){
  9894. el = Ext.getDom(el);
  9895. var newNode;
  9896. if (pub.useDom) {
  9897. newNode = createDom(o, null);
  9898. if (append) {
  9899. el.appendChild(newNode);
  9900. } else {
  9901. (sibling == 'firstChild' ? el : el.parentNode).insertBefore(newNode, el[sibling] || el);
  9902. }
  9903. } else {
  9904. newNode = Ext.DomHelper.insertHtml(pos, el, Ext.DomHelper.createHtml(o));
  9905. }
  9906. return returnElement ? Ext.get(newNode, true) : newNode;
  9907. }
  9908. function createDom(o, parentNode){
  9909. var el,
  9910. doc = document,
  9911. useSet,
  9912. attr,
  9913. val,
  9914. cn;
  9915. if (Ext.isArray(o)) { // Allow Arrays of siblings to be inserted
  9916. el = doc.createDocumentFragment(); // in one shot using a DocumentFragment
  9917. for (var i = 0, l = o.length; i < l; i++) {
  9918. createDom(o[i], el);
  9919. }
  9920. } else if (typeof o == 'string') { // Allow a string as a child spec.
  9921. el = doc.createTextNode(o);
  9922. } else {
  9923. el = doc.createElement( o.tag || 'div' );
  9924. useSet = !!el.setAttribute; // In IE some elements don't have setAttribute
  9925. for (attr in o) {
  9926. if(!confRe.test(attr)){
  9927. val = o[attr];
  9928. if(attr == 'cls'){
  9929. el.className = val;
  9930. }else{
  9931. if(useSet){
  9932. el.setAttribute(attr, val);
  9933. }else{
  9934. el[attr] = val;
  9935. }
  9936. }
  9937. }
  9938. }
  9939. Ext.DomHelper.applyStyles(el, o.style);
  9940. if ((cn = o.children || o.cn)) {
  9941. createDom(cn, el);
  9942. } else if (o.html) {
  9943. el.innerHTML = o.html;
  9944. }
  9945. }
  9946. if(parentNode){
  9947. parentNode.appendChild(el);
  9948. }
  9949. return el;
  9950. }
  9951. // build as innerHTML where available
  9952. function createHtml(o){
  9953. var b = '',
  9954. attr,
  9955. val,
  9956. key,
  9957. cn,
  9958. i;
  9959. if(typeof o == "string"){
  9960. b = o;
  9961. } else if (Ext.isArray(o)) {
  9962. for (i=0; i < o.length; i++) {
  9963. if(o[i]) {
  9964. b += createHtml(o[i]);
  9965. }
  9966. }
  9967. } else {
  9968. b += '<' + (o.tag = o.tag || 'div');
  9969. for (attr in o) {
  9970. val = o[attr];
  9971. if(!confRe.test(attr)){
  9972. if (typeof val == "object") {
  9973. b += ' ' + attr + '="';
  9974. for (key in val) {
  9975. b += key + ':' + val[key] + ';';
  9976. }
  9977. b += '"';
  9978. }else{
  9979. b += ' ' + ({cls : 'class', htmlFor : 'for'}[attr] || attr) + '="' + val + '"';
  9980. }
  9981. }
  9982. }
  9983. // Now either just close the tag or try to add children and close the tag.
  9984. if (emptyTags.test(o.tag)) {
  9985. b += '/>';
  9986. } else {
  9987. b += '>';
  9988. if ((cn = o.children || o.cn)) {
  9989. b += createHtml(cn);
  9990. } else if(o.html){
  9991. b += o.html;
  9992. }
  9993. b += '</' + o.tag + '>';
  9994. }
  9995. }
  9996. return b;
  9997. }
  9998. function ieTable(depth, s, h, e){
  9999. tempTableEl.innerHTML = [s, h, e].join('');
  10000. var i = -1,
  10001. el = tempTableEl,
  10002. ns;
  10003. while(++i < depth){
  10004. el = el.firstChild;
  10005. }
  10006. // If the result is multiple siblings, then encapsulate them into one fragment.
  10007. ns = el.nextSibling;
  10008. if (ns){
  10009. var df = document.createDocumentFragment();
  10010. while(el){
  10011. ns = el.nextSibling;
  10012. df.appendChild(el);
  10013. el = ns;
  10014. }
  10015. el = df;
  10016. }
  10017. return el;
  10018. }
  10019. /**
  10020. * @ignore
  10021. * Nasty code for IE's broken table implementation
  10022. */
  10023. function insertIntoTable(tag, where, el, html) {
  10024. var node,
  10025. before;
  10026. tempTableEl = tempTableEl || document.createElement('div');
  10027. if(tag == 'td' && (where == afterbegin || where == beforeend) ||
  10028. !tableElRe.test(tag) && (where == beforebegin || where == afterend)) {
  10029. return null;
  10030. }
  10031. before = where == beforebegin ? el :
  10032. where == afterend ? el.nextSibling :
  10033. where == afterbegin ? el.firstChild : null;
  10034. if (where == beforebegin || where == afterend) {
  10035. el = el.parentNode;
  10036. }
  10037. if (tag == 'td' || (tag == 'tr' && (where == beforeend || where == afterbegin))) {
  10038. node = ieTable(4, trs, html, tre);
  10039. } else if ((tag == 'tbody' && (where == beforeend || where == afterbegin)) ||
  10040. (tag == 'tr' && (where == beforebegin || where == afterend))) {
  10041. node = ieTable(3, tbs, html, tbe);
  10042. } else {
  10043. node = ieTable(2, ts, html, te);
  10044. }
  10045. el.insertBefore(node, before);
  10046. return node;
  10047. }
  10048. /**
  10049. * @ignore
  10050. * Fix for IE9 createContextualFragment missing method
  10051. */
  10052. function createContextualFragment(html){
  10053. var div = document.createElement("div"),
  10054. fragment = document.createDocumentFragment(),
  10055. i = 0,
  10056. length, childNodes;
  10057. div.innerHTML = html;
  10058. childNodes = div.childNodes;
  10059. length = childNodes.length;
  10060. for (; i < length; i++) {
  10061. fragment.appendChild(childNodes[i].cloneNode(true));
  10062. }
  10063. return fragment;
  10064. }
  10065. pub = {
  10066. /**
  10067. * Returns the markup for the passed Element(s) config.
  10068. * @param {Object} o The DOM object spec (and children)
  10069. * @return {String}
  10070. */
  10071. markup : function(o){
  10072. return createHtml(o);
  10073. },
  10074. /**
  10075. * Applies a style specification to an element.
  10076. * @param {String/HTMLElement} el The element to apply styles to
  10077. * @param {String/Object/Function} styles A style specification string e.g. 'width:100px', or object in the form {width:'100px'}, or
  10078. * a function which returns such a specification.
  10079. */
  10080. applyStyles : function(el, styles){
  10081. if (styles) {
  10082. el = Ext.fly(el);
  10083. if (typeof styles == "function") {
  10084. styles = styles.call();
  10085. }
  10086. if (typeof styles == "string") {
  10087. styles = Ext.Element.parseStyles(styles);
  10088. }
  10089. if (typeof styles == "object") {
  10090. el.setStyle(styles);
  10091. }
  10092. }
  10093. },
  10094. /**
  10095. * Inserts an HTML fragment into the DOM.
  10096. * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
  10097. *
  10098. * For example take the following HTML: `<div>Contents</div>`
  10099. *
  10100. * Using different `where` values inserts element to the following places:
  10101. *
  10102. * - beforeBegin: `<HERE><div>Contents</div>`
  10103. * - afterBegin: `<div><HERE>Contents</div>`
  10104. * - beforeEnd: `<div>Contents<HERE></div>`
  10105. * - afterEnd: `<div>Contents</div><HERE>`
  10106. *
  10107. * @param {HTMLElement/TextNode} el The context element
  10108. * @param {String} html The HTML fragment
  10109. * @return {HTMLElement} The new node
  10110. */
  10111. insertHtml : function(where, el, html){
  10112. var hash = {},
  10113. hashVal,
  10114. range,
  10115. rangeEl,
  10116. setStart,
  10117. frag,
  10118. rs;
  10119. where = where.toLowerCase();
  10120. // add these here because they are used in both branches of the condition.
  10121. hash[beforebegin] = ['BeforeBegin', 'previousSibling'];
  10122. hash[afterend] = ['AfterEnd', 'nextSibling'];
  10123. // if IE and context element is an HTMLElement
  10124. if (el.insertAdjacentHTML) {
  10125. if(tableRe.test(el.tagName) && (rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html))){
  10126. return rs;
  10127. }
  10128. // add these two to the hash.
  10129. hash[afterbegin] = ['AfterBegin', 'firstChild'];
  10130. hash[beforeend] = ['BeforeEnd', 'lastChild'];
  10131. if ((hashVal = hash[where])) {
  10132. el.insertAdjacentHTML(hashVal[0], html);
  10133. return el[hashVal[1]];
  10134. }
  10135. // if (not IE and context element is an HTMLElement) or TextNode
  10136. } else {
  10137. // we cannot insert anything inside a textnode so...
  10138. if (Ext.isTextNode(el)) {
  10139. where = where === 'afterbegin' ? 'beforebegin' : where;
  10140. where = where === 'beforeend' ? 'afterend' : where;
  10141. }
  10142. range = Ext.supports.CreateContextualFragment ? el.ownerDocument.createRange() : undefined;
  10143. setStart = 'setStart' + (endRe.test(where) ? 'After' : 'Before');
  10144. if (hash[where]) {
  10145. if (range) {
  10146. range[setStart](el);
  10147. frag = range.createContextualFragment(html);
  10148. } else {
  10149. frag = createContextualFragment(html);
  10150. }
  10151. el.parentNode.insertBefore(frag, where == beforebegin ? el : el.nextSibling);
  10152. return el[(where == beforebegin ? 'previous' : 'next') + 'Sibling'];
  10153. } else {
  10154. rangeEl = (where == afterbegin ? 'first' : 'last') + 'Child';
  10155. if (el.firstChild) {
  10156. if (range) {
  10157. range[setStart](el[rangeEl]);
  10158. frag = range.createContextualFragment(html);
  10159. } else {
  10160. frag = createContextualFragment(html);
  10161. }
  10162. if(where == afterbegin){
  10163. el.insertBefore(frag, el.firstChild);
  10164. }else{
  10165. el.appendChild(frag);
  10166. }
  10167. } else {
  10168. el.innerHTML = html;
  10169. }
  10170. return el[rangeEl];
  10171. }
  10172. }
  10173. },
  10174. /**
  10175. * Creates new DOM element(s) and inserts them before el.
  10176. * @param {String/HTMLElement/Ext.Element} el The context element
  10177. * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
  10178. * @param {Boolean} returnElement (optional) true to return a Ext.Element
  10179. * @return {HTMLElement/Ext.Element} The new node
  10180. */
  10181. insertBefore : function(el, o, returnElement){
  10182. return doInsert(el, o, returnElement, beforebegin);
  10183. },
  10184. /**
  10185. * Creates new DOM element(s) and inserts them after el.
  10186. * @param {String/HTMLElement/Ext.Element} el The context element
  10187. * @param {Object} o The DOM object spec (and children)
  10188. * @param {Boolean} returnElement (optional) true to return a Ext.Element
  10189. * @return {HTMLElement/Ext.Element} The new node
  10190. */
  10191. insertAfter : function(el, o, returnElement){
  10192. return doInsert(el, o, returnElement, afterend, 'nextSibling');
  10193. },
  10194. /**
  10195. * Creates new DOM element(s) and inserts them as the first child of el.
  10196. * @param {String/HTMLElement/Ext.Element} el The context element
  10197. * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
  10198. * @param {Boolean} returnElement (optional) true to return a Ext.Element
  10199. * @return {HTMLElement/Ext.Element} The new node
  10200. */
  10201. insertFirst : function(el, o, returnElement){
  10202. return doInsert(el, o, returnElement, afterbegin, 'firstChild');
  10203. },
  10204. /**
  10205. * Creates new DOM element(s) and appends them to el.
  10206. * @param {String/HTMLElement/Ext.Element} el The context element
  10207. * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
  10208. * @param {Boolean} returnElement (optional) true to return a Ext.Element
  10209. * @return {HTMLElement/Ext.Element} The new node
  10210. */
  10211. append : function(el, o, returnElement){
  10212. return doInsert(el, o, returnElement, beforeend, '', true);
  10213. },
  10214. /**
  10215. * Creates new DOM element(s) and overwrites the contents of el with them.
  10216. * @param {String/HTMLElement/Ext.Element} el The context element
  10217. * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
  10218. * @param {Boolean} returnElement (optional) true to return a Ext.Element
  10219. * @return {HTMLElement/Ext.Element} The new node
  10220. */
  10221. overwrite : function(el, o, returnElement){
  10222. el = Ext.getDom(el);
  10223. el.innerHTML = createHtml(o);
  10224. return returnElement ? Ext.get(el.firstChild) : el.firstChild;
  10225. },
  10226. createHtml : createHtml,
  10227. /**
  10228. * Creates new DOM element(s) without inserting them to the document.
  10229. * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
  10230. * @return {HTMLElement} The new uninserted node
  10231. * @method
  10232. */
  10233. createDom: createDom,
  10234. /** True to force the use of DOM instead of html fragments @type Boolean */
  10235. useDom : false,
  10236. /**
  10237. * Creates a new Ext.Template from the DOM object spec.
  10238. * @param {Object} o The DOM object spec (and children)
  10239. * @return {Ext.Template} The new template
  10240. */
  10241. createTemplate : function(o){
  10242. var html = Ext.DomHelper.createHtml(o);
  10243. return Ext.create('Ext.Template', html);
  10244. }
  10245. };
  10246. return pub;
  10247. }();
  10248. /*
  10249. * This is code is also distributed under MIT license for use
  10250. * with jQuery and prototype JavaScript libraries.
  10251. */
  10252. /**
  10253. * @class Ext.DomQuery
  10254. Provides high performance selector/xpath processing by compiling queries into reusable functions. New pseudo classes and matchers can be plugged. It works on HTML and XML documents (if a content node is passed in).
  10255. <p>
  10256. DomQuery supports most of the <a href="http://www.w3.org/TR/2005/WD-css3-selectors-20051215/#selectors">CSS3 selectors spec</a>, along with some custom selectors and basic XPath.</p>
  10257. <p>
  10258. All selectors, attribute filters and pseudos below can be combined infinitely in any order. For example "div.foo:nth-child(odd)[@foo=bar].bar:first" would be a perfectly valid selector. Node filters are processed in the order in which they appear, which allows you to optimize your queries for your document structure.
  10259. </p>
  10260. <h4>Element Selectors:</h4>
  10261. <ul class="list">
  10262. <li> <b>*</b> any element</li>
  10263. <li> <b>E</b> an element with the tag E</li>
  10264. <li> <b>E F</b> All descendent elements of E that have the tag F</li>
  10265. <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
  10266. <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
  10267. <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
  10268. </ul>
  10269. <h4>Attribute Selectors:</h4>
  10270. <p>The use of &#64; and quotes are optional. For example, div[&#64;foo='bar'] is also a valid attribute selector.</p>
  10271. <ul class="list">
  10272. <li> <b>E[foo]</b> has an attribute "foo"</li>
  10273. <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
  10274. <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
  10275. <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
  10276. <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
  10277. <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
  10278. <li> <b>E[foo!=bar]</b> attribute "foo" does not equal "bar"</li>
  10279. </ul>
  10280. <h4>Pseudo Classes:</h4>
  10281. <ul class="list">
  10282. <li> <b>E:first-child</b> E is the first child of its parent</li>
  10283. <li> <b>E:last-child</b> E is the last child of its parent</li>
  10284. <li> <b>E:nth-child(<i>n</i>)</b> E is the <i>n</i>th child of its parent (1 based as per the spec)</li>
  10285. <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
  10286. <li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
  10287. <li> <b>E:only-child</b> E is the only child of its parent</li>
  10288. <li> <b>E:checked</b> E is an element that is has a checked attribute that is true (e.g. a radio or checkbox) </li>
  10289. <li> <b>E:first</b> the first E in the resultset</li>
  10290. <li> <b>E:last</b> the last E in the resultset</li>
  10291. <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
  10292. <li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
  10293. <li> <b>E:even</b> shortcut for :nth-child(even)</li>
  10294. <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
  10295. <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
  10296. <li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
  10297. <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
  10298. <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
  10299. <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
  10300. <li> <b>E:any(S1|S2|S2)</b> an E element which matches any of the simple selectors S1, S2 or S3//\\</li>
  10301. </ul>
  10302. <h4>CSS Value Selectors:</h4>
  10303. <ul class="list">
  10304. <li> <b>E{display=none}</b> css value "display" that equals "none"</li>
  10305. <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
  10306. <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
  10307. <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
  10308. <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
  10309. <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
  10310. </ul>
  10311. * @singleton
  10312. */
  10313. Ext.ns('Ext.core');
  10314. Ext.core.DomQuery = Ext.DomQuery = function(){
  10315. var cache = {},
  10316. simpleCache = {},
  10317. valueCache = {},
  10318. nonSpace = /\S/,
  10319. trimRe = /^\s+|\s+$/g,
  10320. tplRe = /\{(\d+)\}/g,
  10321. modeRe = /^(\s?[\/>+~]\s?|\s|$)/,
  10322. tagTokenRe = /^(#)?([\w-\*]+)/,
  10323. nthRe = /(\d*)n\+?(\d*)/,
  10324. nthRe2 = /\D/,
  10325. startIdRe = /^\s*\#/,
  10326. // This is for IE MSXML which does not support expandos.
  10327. // IE runs the same speed using setAttribute, however FF slows way down
  10328. // and Safari completely fails so they need to continue to use expandos.
  10329. isIE = window.ActiveXObject ? true : false,
  10330. key = 30803;
  10331. // this eval is stop the compressor from
  10332. // renaming the variable to something shorter
  10333. eval("var batch = 30803;");
  10334. // Retrieve the child node from a particular
  10335. // parent at the specified index.
  10336. function child(parent, index){
  10337. var i = 0,
  10338. n = parent.firstChild;
  10339. while(n){
  10340. if(n.nodeType == 1){
  10341. if(++i == index){
  10342. return n;
  10343. }
  10344. }
  10345. n = n.nextSibling;
  10346. }
  10347. return null;
  10348. }
  10349. // retrieve the next element node
  10350. function next(n){
  10351. while((n = n.nextSibling) && n.nodeType != 1);
  10352. return n;
  10353. }
  10354. // retrieve the previous element node
  10355. function prev(n){
  10356. while((n = n.previousSibling) && n.nodeType != 1);
  10357. return n;
  10358. }
  10359. // Mark each child node with a nodeIndex skipping and
  10360. // removing empty text nodes.
  10361. function children(parent){
  10362. var n = parent.firstChild,
  10363. nodeIndex = -1,
  10364. nextNode;
  10365. while(n){
  10366. nextNode = n.nextSibling;
  10367. // clean worthless empty nodes.
  10368. if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
  10369. parent.removeChild(n);
  10370. }else{
  10371. // add an expando nodeIndex
  10372. n.nodeIndex = ++nodeIndex;
  10373. }
  10374. n = nextNode;
  10375. }
  10376. return this;
  10377. }
  10378. // nodeSet - array of nodes
  10379. // cls - CSS Class
  10380. function byClassName(nodeSet, cls){
  10381. if(!cls){
  10382. return nodeSet;
  10383. }
  10384. var result = [], ri = -1;
  10385. for(var i = 0, ci; ci = nodeSet[i]; i++){
  10386. if((' '+ci.className+' ').indexOf(cls) != -1){
  10387. result[++ri] = ci;
  10388. }
  10389. }
  10390. return result;
  10391. };
  10392. function attrValue(n, attr){
  10393. // if its an array, use the first node.
  10394. if(!n.tagName && typeof n.length != "undefined"){
  10395. n = n[0];
  10396. }
  10397. if(!n){
  10398. return null;
  10399. }
  10400. if(attr == "for"){
  10401. return n.htmlFor;
  10402. }
  10403. if(attr == "class" || attr == "className"){
  10404. return n.className;
  10405. }
  10406. return n.getAttribute(attr) || n[attr];
  10407. };
  10408. // ns - nodes
  10409. // mode - false, /, >, +, ~
  10410. // tagName - defaults to "*"
  10411. function getNodes(ns, mode, tagName){
  10412. var result = [], ri = -1, cs;
  10413. if(!ns){
  10414. return result;
  10415. }
  10416. tagName = tagName || "*";
  10417. // convert to array
  10418. if(typeof ns.getElementsByTagName != "undefined"){
  10419. ns = [ns];
  10420. }
  10421. // no mode specified, grab all elements by tagName
  10422. // at any depth
  10423. if(!mode){
  10424. for(var i = 0, ni; ni = ns[i]; i++){
  10425. cs = ni.getElementsByTagName(tagName);
  10426. for(var j = 0, ci; ci = cs[j]; j++){
  10427. result[++ri] = ci;
  10428. }
  10429. }
  10430. // Direct Child mode (/ or >)
  10431. // E > F or E/F all direct children elements of E that have the tag
  10432. } else if(mode == "/" || mode == ">"){
  10433. var utag = tagName.toUpperCase();
  10434. for(var i = 0, ni, cn; ni = ns[i]; i++){
  10435. cn = ni.childNodes;
  10436. for(var j = 0, cj; cj = cn[j]; j++){
  10437. if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){
  10438. result[++ri] = cj;
  10439. }
  10440. }
  10441. }
  10442. // Immediately Preceding mode (+)
  10443. // E + F all elements with the tag F that are immediately preceded by an element with the tag E
  10444. }else if(mode == "+"){
  10445. var utag = tagName.toUpperCase();
  10446. for(var i = 0, n; n = ns[i]; i++){
  10447. while((n = n.nextSibling) && n.nodeType != 1);
  10448. if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
  10449. result[++ri] = n;
  10450. }
  10451. }
  10452. // Sibling mode (~)
  10453. // E ~ F all elements with the tag F that are preceded by a sibling element with the tag E
  10454. }else if(mode == "~"){
  10455. var utag = tagName.toUpperCase();
  10456. for(var i = 0, n; n = ns[i]; i++){
  10457. while((n = n.nextSibling)){
  10458. if (n.nodeName == utag || n.nodeName == tagName || tagName == '*'){
  10459. result[++ri] = n;
  10460. }
  10461. }
  10462. }
  10463. }
  10464. return result;
  10465. }
  10466. function concat(a, b){
  10467. if(b.slice){
  10468. return a.concat(b);
  10469. }
  10470. for(var i = 0, l = b.length; i < l; i++){
  10471. a[a.length] = b[i];
  10472. }
  10473. return a;
  10474. }
  10475. function byTag(cs, tagName){
  10476. if(cs.tagName || cs == document){
  10477. cs = [cs];
  10478. }
  10479. if(!tagName){
  10480. return cs;
  10481. }
  10482. var result = [], ri = -1;
  10483. tagName = tagName.toLowerCase();
  10484. for(var i = 0, ci; ci = cs[i]; i++){
  10485. if(ci.nodeType == 1 && ci.tagName.toLowerCase() == tagName){
  10486. result[++ri] = ci;
  10487. }
  10488. }
  10489. return result;
  10490. }
  10491. function byId(cs, id){
  10492. if(cs.tagName || cs == document){
  10493. cs = [cs];
  10494. }
  10495. if(!id){
  10496. return cs;
  10497. }
  10498. var result = [], ri = -1;
  10499. for(var i = 0, ci; ci = cs[i]; i++){
  10500. if(ci && ci.id == id){
  10501. result[++ri] = ci;
  10502. return result;
  10503. }
  10504. }
  10505. return result;
  10506. }
  10507. // operators are =, !=, ^=, $=, *=, %=, |= and ~=
  10508. // custom can be "{"
  10509. function byAttribute(cs, attr, value, op, custom){
  10510. var result = [],
  10511. ri = -1,
  10512. useGetStyle = custom == "{",
  10513. fn = Ext.DomQuery.operators[op],
  10514. a,
  10515. xml,
  10516. hasXml;
  10517. for(var i = 0, ci; ci = cs[i]; i++){
  10518. // skip non-element nodes.
  10519. if(ci.nodeType != 1){
  10520. continue;
  10521. }
  10522. // only need to do this for the first node
  10523. if(!hasXml){
  10524. xml = Ext.DomQuery.isXml(ci);
  10525. hasXml = true;
  10526. }
  10527. // we only need to change the property names if we're dealing with html nodes, not XML
  10528. if(!xml){
  10529. if(useGetStyle){
  10530. a = Ext.DomQuery.getStyle(ci, attr);
  10531. } else if (attr == "class" || attr == "className"){
  10532. a = ci.className;
  10533. } else if (attr == "for"){
  10534. a = ci.htmlFor;
  10535. } else if (attr == "href"){
  10536. // getAttribute href bug
  10537. // http://www.glennjones.net/Post/809/getAttributehrefbug.htm
  10538. a = ci.getAttribute("href", 2);
  10539. } else{
  10540. a = ci.getAttribute(attr);
  10541. }
  10542. }else{
  10543. a = ci.getAttribute(attr);
  10544. }
  10545. if((fn && fn(a, value)) || (!fn && a)){
  10546. result[++ri] = ci;
  10547. }
  10548. }
  10549. return result;
  10550. }
  10551. function byPseudo(cs, name, value){
  10552. return Ext.DomQuery.pseudos[name](cs, value);
  10553. }
  10554. function nodupIEXml(cs){
  10555. var d = ++key,
  10556. r;
  10557. cs[0].setAttribute("_nodup", d);
  10558. r = [cs[0]];
  10559. for(var i = 1, len = cs.length; i < len; i++){
  10560. var c = cs[i];
  10561. if(!c.getAttribute("_nodup") != d){
  10562. c.setAttribute("_nodup", d);
  10563. r[r.length] = c;
  10564. }
  10565. }
  10566. for(var i = 0, len = cs.length; i < len; i++){
  10567. cs[i].removeAttribute("_nodup");
  10568. }
  10569. return r;
  10570. }
  10571. function nodup(cs){
  10572. if(!cs){
  10573. return [];
  10574. }
  10575. var len = cs.length, c, i, r = cs, cj, ri = -1;
  10576. if(!len || typeof cs.nodeType != "undefined" || len == 1){
  10577. return cs;
  10578. }
  10579. if(isIE && typeof cs[0].selectSingleNode != "undefined"){
  10580. return nodupIEXml(cs);
  10581. }
  10582. var d = ++key;
  10583. cs[0]._nodup = d;
  10584. for(i = 1; c = cs[i]; i++){
  10585. if(c._nodup != d){
  10586. c._nodup = d;
  10587. }else{
  10588. r = [];
  10589. for(var j = 0; j < i; j++){
  10590. r[++ri] = cs[j];
  10591. }
  10592. for(j = i+1; cj = cs[j]; j++){
  10593. if(cj._nodup != d){
  10594. cj._nodup = d;
  10595. r[++ri] = cj;
  10596. }
  10597. }
  10598. return r;
  10599. }
  10600. }
  10601. return r;
  10602. }
  10603. function quickDiffIEXml(c1, c2){
  10604. var d = ++key,
  10605. r = [];
  10606. for(var i = 0, len = c1.length; i < len; i++){
  10607. c1[i].setAttribute("_qdiff", d);
  10608. }
  10609. for(var i = 0, len = c2.length; i < len; i++){
  10610. if(c2[i].getAttribute("_qdiff") != d){
  10611. r[r.length] = c2[i];
  10612. }
  10613. }
  10614. for(var i = 0, len = c1.length; i < len; i++){
  10615. c1[i].removeAttribute("_qdiff");
  10616. }
  10617. return r;
  10618. }
  10619. function quickDiff(c1, c2){
  10620. var len1 = c1.length,
  10621. d = ++key,
  10622. r = [];
  10623. if(!len1){
  10624. return c2;
  10625. }
  10626. if(isIE && typeof c1[0].selectSingleNode != "undefined"){
  10627. return quickDiffIEXml(c1, c2);
  10628. }
  10629. for(var i = 0; i < len1; i++){
  10630. c1[i]._qdiff = d;
  10631. }
  10632. for(var i = 0, len = c2.length; i < len; i++){
  10633. if(c2[i]._qdiff != d){
  10634. r[r.length] = c2[i];
  10635. }
  10636. }
  10637. return r;
  10638. }
  10639. function quickId(ns, mode, root, id){
  10640. if(ns == root){
  10641. var d = root.ownerDocument || root;
  10642. return d.getElementById(id);
  10643. }
  10644. ns = getNodes(ns, mode, "*");
  10645. return byId(ns, id);
  10646. }
  10647. return {
  10648. getStyle : function(el, name){
  10649. return Ext.fly(el).getStyle(name);
  10650. },
  10651. /**
  10652. * Compiles a selector/xpath query into a reusable function. The returned function
  10653. * takes one parameter "root" (optional), which is the context node from where the query should start.
  10654. * @param {String} selector The selector/xpath query
  10655. * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
  10656. * @return {Function}
  10657. */
  10658. compile : function(path, type){
  10659. type = type || "select";
  10660. // setup fn preamble
  10661. var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"],
  10662. mode,
  10663. lastPath,
  10664. matchers = Ext.DomQuery.matchers,
  10665. matchersLn = matchers.length,
  10666. modeMatch,
  10667. // accept leading mode switch
  10668. lmode = path.match(modeRe);
  10669. if(lmode && lmode[1]){
  10670. fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
  10671. path = path.replace(lmode[1], "");
  10672. }
  10673. // strip leading slashes
  10674. while(path.substr(0, 1)=="/"){
  10675. path = path.substr(1);
  10676. }
  10677. while(path && lastPath != path){
  10678. lastPath = path;
  10679. var tokenMatch = path.match(tagTokenRe);
  10680. if(type == "select"){
  10681. if(tokenMatch){
  10682. // ID Selector
  10683. if(tokenMatch[1] == "#"){
  10684. fn[fn.length] = 'n = quickId(n, mode, root, "'+tokenMatch[2]+'");';
  10685. }else{
  10686. fn[fn.length] = 'n = getNodes(n, mode, "'+tokenMatch[2]+'");';
  10687. }
  10688. path = path.replace(tokenMatch[0], "");
  10689. }else if(path.substr(0, 1) != '@'){
  10690. fn[fn.length] = 'n = getNodes(n, mode, "*");';
  10691. }
  10692. // type of "simple"
  10693. }else{
  10694. if(tokenMatch){
  10695. if(tokenMatch[1] == "#"){
  10696. fn[fn.length] = 'n = byId(n, "'+tokenMatch[2]+'");';
  10697. }else{
  10698. fn[fn.length] = 'n = byTag(n, "'+tokenMatch[2]+'");';
  10699. }
  10700. path = path.replace(tokenMatch[0], "");
  10701. }
  10702. }
  10703. while(!(modeMatch = path.match(modeRe))){
  10704. var matched = false;
  10705. for(var j = 0; j < matchersLn; j++){
  10706. var t = matchers[j];
  10707. var m = path.match(t.re);
  10708. if(m){
  10709. fn[fn.length] = t.select.replace(tplRe, function(x, i){
  10710. return m[i];
  10711. });
  10712. path = path.replace(m[0], "");
  10713. matched = true;
  10714. break;
  10715. }
  10716. }
  10717. // prevent infinite loop on bad selector
  10718. if(!matched){
  10719. }
  10720. }
  10721. if(modeMatch[1]){
  10722. fn[fn.length] = 'mode="'+modeMatch[1].replace(trimRe, "")+'";';
  10723. path = path.replace(modeMatch[1], "");
  10724. }
  10725. }
  10726. // close fn out
  10727. fn[fn.length] = "return nodup(n);\n}";
  10728. // eval fn and return it
  10729. eval(fn.join(""));
  10730. return f;
  10731. },
  10732. /**
  10733. * Selects an array of DOM nodes using JavaScript-only implementation.
  10734. *
  10735. * Use {@link #select} to take advantage of browsers built-in support for CSS selectors.
  10736. *
  10737. * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
  10738. * @param {HTMLElement/String} root (optional) The start of the query (defaults to document).
  10739. * @return {HTMLElement[]} An Array of DOM elements which match the selector. If there are
  10740. * no matches, and empty Array is returned.
  10741. */
  10742. jsSelect: function(path, root, type){
  10743. // set root to doc if not specified.
  10744. root = root || document;
  10745. if(typeof root == "string"){
  10746. root = document.getElementById(root);
  10747. }
  10748. var paths = path.split(","),
  10749. results = [];
  10750. // loop over each selector
  10751. for(var i = 0, len = paths.length; i < len; i++){
  10752. var subPath = paths[i].replace(trimRe, "");
  10753. // compile and place in cache
  10754. if(!cache[subPath]){
  10755. cache[subPath] = Ext.DomQuery.compile(subPath);
  10756. if(!cache[subPath]){
  10757. }
  10758. }
  10759. var result = cache[subPath](root);
  10760. if(result && result != document){
  10761. results = results.concat(result);
  10762. }
  10763. }
  10764. // if there were multiple selectors, make sure dups
  10765. // are eliminated
  10766. if(paths.length > 1){
  10767. return nodup(results);
  10768. }
  10769. return results;
  10770. },
  10771. isXml: function(el) {
  10772. var docEl = (el ? el.ownerDocument || el : 0).documentElement;
  10773. return docEl ? docEl.nodeName !== "HTML" : false;
  10774. },
  10775. /**
  10776. * Selects an array of DOM nodes by CSS/XPath selector.
  10777. *
  10778. * Uses [document.querySelectorAll][0] if browser supports that, otherwise falls back to
  10779. * {@link Ext.DomQuery#jsSelect} to do the work.
  10780. *
  10781. * Aliased as {@link Ext#query}.
  10782. *
  10783. * [0]: https://developer.mozilla.org/en/DOM/document.querySelectorAll
  10784. *
  10785. * @param {String} path The selector/xpath query
  10786. * @param {HTMLElement} root (optional) The start of the query (defaults to document).
  10787. * @return {HTMLElement[]} An array of DOM elements (not a NodeList as returned by `querySelectorAll`).
  10788. * Empty array when no matches.
  10789. * @method
  10790. */
  10791. select : document.querySelectorAll ? function(path, root, type) {
  10792. root = root || document;
  10793. /*
  10794. * Safari 3.x can't handle uppercase or unicode characters when in quirks mode.
  10795. */
  10796. if (!Ext.DomQuery.isXml(root) && !(Ext.isSafari3 && !Ext.isStrict)) {
  10797. try {
  10798. /*
  10799. * This checking here is to "fix" the behaviour of querySelectorAll
  10800. * for non root document queries. The way qsa works is intentional,
  10801. * however it's definitely not the expected way it should work.
  10802. * More info: http://ejohn.org/blog/thoughts-on-queryselectorall/
  10803. *
  10804. * We only modify the path for single selectors (ie, no multiples),
  10805. * without a full parser it makes it difficult to do this correctly.
  10806. */
  10807. var isDocumentRoot = root.nodeType === 9,
  10808. _path = path,
  10809. _root = root;
  10810. if (!isDocumentRoot && path.indexOf(',') === -1 && !startIdRe.test(path)) {
  10811. _path = '#' + Ext.id(root) + ' ' + path;
  10812. _root = root.parentNode;
  10813. }
  10814. return Ext.Array.toArray(_root.querySelectorAll(_path));
  10815. }
  10816. catch (e) {
  10817. }
  10818. }
  10819. return Ext.DomQuery.jsSelect.call(this, path, root, type);
  10820. } : function(path, root, type) {
  10821. return Ext.DomQuery.jsSelect.call(this, path, root, type);
  10822. },
  10823. /**
  10824. * Selects a single element.
  10825. * @param {String} selector The selector/xpath query
  10826. * @param {HTMLElement} root (optional) The start of the query (defaults to document).
  10827. * @return {HTMLElement} The DOM element which matched the selector.
  10828. */
  10829. selectNode : function(path, root){
  10830. return Ext.DomQuery.select(path, root)[0];
  10831. },
  10832. /**
  10833. * Selects the value of a node, optionally replacing null with the defaultValue.
  10834. * @param {String} selector The selector/xpath query
  10835. * @param {HTMLElement} root (optional) The start of the query (defaults to document).
  10836. * @param {String} defaultValue (optional) When specified, this is return as empty value.
  10837. * @return {String}
  10838. */
  10839. selectValue : function(path, root, defaultValue){
  10840. path = path.replace(trimRe, "");
  10841. if(!valueCache[path]){
  10842. valueCache[path] = Ext.DomQuery.compile(path, "select");
  10843. }
  10844. var n = valueCache[path](root), v;
  10845. n = n[0] ? n[0] : n;
  10846. // overcome a limitation of maximum textnode size
  10847. // Rumored to potentially crash IE6 but has not been confirmed.
  10848. // http://reference.sitepoint.com/javascript/Node/normalize
  10849. // https://developer.mozilla.org/En/DOM/Node.normalize
  10850. if (typeof n.normalize == 'function') n.normalize();
  10851. v = (n && n.firstChild ? n.firstChild.nodeValue : null);
  10852. return ((v === null||v === undefined||v==='') ? defaultValue : v);
  10853. },
  10854. /**
  10855. * Selects the value of a node, parsing integers and floats. Returns the defaultValue, or 0 if none is specified.
  10856. * @param {String} selector The selector/xpath query
  10857. * @param {HTMLElement} root (optional) The start of the query (defaults to document).
  10858. * @param {Number} defaultValue (optional) When specified, this is return as empty value.
  10859. * @return {Number}
  10860. */
  10861. selectNumber : function(path, root, defaultValue){
  10862. var v = Ext.DomQuery.selectValue(path, root, defaultValue || 0);
  10863. return parseFloat(v);
  10864. },
  10865. /**
  10866. * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
  10867. * @param {String/HTMLElement/HTMLElement[]} el An element id, element or array of elements
  10868. * @param {String} selector The simple selector to test
  10869. * @return {Boolean}
  10870. */
  10871. is : function(el, ss){
  10872. if(typeof el == "string"){
  10873. el = document.getElementById(el);
  10874. }
  10875. var isArray = Ext.isArray(el),
  10876. result = Ext.DomQuery.filter(isArray ? el : [el], ss);
  10877. return isArray ? (result.length == el.length) : (result.length > 0);
  10878. },
  10879. /**
  10880. * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
  10881. * @param {HTMLElement[]} el An array of elements to filter
  10882. * @param {String} selector The simple selector to test
  10883. * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
  10884. * the selector instead of the ones that match
  10885. * @return {HTMLElement[]} An Array of DOM elements which match the selector. If there are
  10886. * no matches, and empty Array is returned.
  10887. */
  10888. filter : function(els, ss, nonMatches){
  10889. ss = ss.replace(trimRe, "");
  10890. if(!simpleCache[ss]){
  10891. simpleCache[ss] = Ext.DomQuery.compile(ss, "simple");
  10892. }
  10893. var result = simpleCache[ss](els);
  10894. return nonMatches ? quickDiff(result, els) : result;
  10895. },
  10896. /**
  10897. * Collection of matching regular expressions and code snippets.
  10898. * Each capture group within () will be replace the {} in the select
  10899. * statement as specified by their index.
  10900. */
  10901. matchers : [{
  10902. re: /^\.([\w-]+)/,
  10903. select: 'n = byClassName(n, " {1} ");'
  10904. }, {
  10905. re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
  10906. select: 'n = byPseudo(n, "{1}", "{2}");'
  10907. },{
  10908. re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
  10909. select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
  10910. }, {
  10911. re: /^#([\w-]+)/,
  10912. select: 'n = byId(n, "{1}");'
  10913. },{
  10914. re: /^@([\w-]+)/,
  10915. select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
  10916. }
  10917. ],
  10918. /**
  10919. * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
  10920. * New operators can be added as long as the match the format <i>c</i>= where <i>c</i> is any character other than space, &gt; &lt;.
  10921. */
  10922. operators : {
  10923. "=" : function(a, v){
  10924. return a == v;
  10925. },
  10926. "!=" : function(a, v){
  10927. return a != v;
  10928. },
  10929. "^=" : function(a, v){
  10930. return a && a.substr(0, v.length) == v;
  10931. },
  10932. "$=" : function(a, v){
  10933. return a && a.substr(a.length-v.length) == v;
  10934. },
  10935. "*=" : function(a, v){
  10936. return a && a.indexOf(v) !== -1;
  10937. },
  10938. "%=" : function(a, v){
  10939. return (a % v) == 0;
  10940. },
  10941. "|=" : function(a, v){
  10942. return a && (a == v || a.substr(0, v.length+1) == v+'-');
  10943. },
  10944. "~=" : function(a, v){
  10945. return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
  10946. }
  10947. },
  10948. /**
  10949. Object hash of "pseudo class" filter functions which are used when filtering selections.
  10950. Each function is passed two parameters:
  10951. - **c** : Array
  10952. An Array of DOM elements to filter.
  10953. - **v** : String
  10954. The argument (if any) supplied in the selector.
  10955. A filter function returns an Array of DOM elements which conform to the pseudo class.
  10956. In addition to the provided pseudo classes listed above such as `first-child` and `nth-child`,
  10957. developers may add additional, custom psuedo class filters to select elements according to application-specific requirements.
  10958. For example, to filter `a` elements to only return links to __external__ resources:
  10959. Ext.DomQuery.pseudos.external = function(c, v){
  10960. var r = [], ri = -1;
  10961. for(var i = 0, ci; ci = c[i]; i++){
  10962. // Include in result set only if it's a link to an external resource
  10963. if(ci.hostname != location.hostname){
  10964. r[++ri] = ci;
  10965. }
  10966. }
  10967. return r;
  10968. };
  10969. Then external links could be gathered with the following statement:
  10970. var externalLinks = Ext.select("a:external");
  10971. * @markdown
  10972. */
  10973. pseudos : {
  10974. "first-child" : function(c){
  10975. var r = [], ri = -1, n;
  10976. for(var i = 0, ci; ci = n = c[i]; i++){
  10977. while((n = n.previousSibling) && n.nodeType != 1);
  10978. if(!n){
  10979. r[++ri] = ci;
  10980. }
  10981. }
  10982. return r;
  10983. },
  10984. "last-child" : function(c){
  10985. var r = [], ri = -1, n;
  10986. for(var i = 0, ci; ci = n = c[i]; i++){
  10987. while((n = n.nextSibling) && n.nodeType != 1);
  10988. if(!n){
  10989. r[++ri] = ci;
  10990. }
  10991. }
  10992. return r;
  10993. },
  10994. "nth-child" : function(c, a) {
  10995. var r = [], ri = -1,
  10996. m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a),
  10997. f = (m[1] || 1) - 0, l = m[2] - 0;
  10998. for(var i = 0, n; n = c[i]; i++){
  10999. var pn = n.parentNode;
  11000. if (batch != pn._batch) {
  11001. var j = 0;
  11002. for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
  11003. if(cn.nodeType == 1){
  11004. cn.nodeIndex = ++j;
  11005. }
  11006. }
  11007. pn._batch = batch;
  11008. }
  11009. if (f == 1) {
  11010. if (l == 0 || n.nodeIndex == l){
  11011. r[++ri] = n;
  11012. }
  11013. } else if ((n.nodeIndex + l) % f == 0){
  11014. r[++ri] = n;
  11015. }
  11016. }
  11017. return r;
  11018. },
  11019. "only-child" : function(c){
  11020. var r = [], ri = -1;;
  11021. for(var i = 0, ci; ci = c[i]; i++){
  11022. if(!prev(ci) && !next(ci)){
  11023. r[++ri] = ci;
  11024. }
  11025. }
  11026. return r;
  11027. },
  11028. "empty" : function(c){
  11029. var r = [], ri = -1;
  11030. for(var i = 0, ci; ci = c[i]; i++){
  11031. var cns = ci.childNodes, j = 0, cn, empty = true;
  11032. while(cn = cns[j]){
  11033. ++j;
  11034. if(cn.nodeType == 1 || cn.nodeType == 3){
  11035. empty = false;
  11036. break;
  11037. }
  11038. }
  11039. if(empty){
  11040. r[++ri] = ci;
  11041. }
  11042. }
  11043. return r;
  11044. },
  11045. "contains" : function(c, v){
  11046. var r = [], ri = -1;
  11047. for(var i = 0, ci; ci = c[i]; i++){
  11048. if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
  11049. r[++ri] = ci;
  11050. }
  11051. }
  11052. return r;
  11053. },
  11054. "nodeValue" : function(c, v){
  11055. var r = [], ri = -1;
  11056. for(var i = 0, ci; ci = c[i]; i++){
  11057. if(ci.firstChild && ci.firstChild.nodeValue == v){
  11058. r[++ri] = ci;
  11059. }
  11060. }
  11061. return r;
  11062. },
  11063. "checked" : function(c){
  11064. var r = [], ri = -1;
  11065. for(var i = 0, ci; ci = c[i]; i++){
  11066. if(ci.checked == true){
  11067. r[++ri] = ci;
  11068. }
  11069. }
  11070. return r;
  11071. },
  11072. "not" : function(c, ss){
  11073. return Ext.DomQuery.filter(c, ss, true);
  11074. },
  11075. "any" : function(c, selectors){
  11076. var ss = selectors.split('|'),
  11077. r = [], ri = -1, s;
  11078. for(var i = 0, ci; ci = c[i]; i++){
  11079. for(var j = 0; s = ss[j]; j++){
  11080. if(Ext.DomQuery.is(ci, s)){
  11081. r[++ri] = ci;
  11082. break;
  11083. }
  11084. }
  11085. }
  11086. return r;
  11087. },
  11088. "odd" : function(c){
  11089. return this["nth-child"](c, "odd");
  11090. },
  11091. "even" : function(c){
  11092. return this["nth-child"](c, "even");
  11093. },
  11094. "nth" : function(c, a){
  11095. return c[a-1] || [];
  11096. },
  11097. "first" : function(c){
  11098. return c[0] || [];
  11099. },
  11100. "last" : function(c){
  11101. return c[c.length-1] || [];
  11102. },
  11103. "has" : function(c, ss){
  11104. var s = Ext.DomQuery.select,
  11105. r = [], ri = -1;
  11106. for(var i = 0, ci; ci = c[i]; i++){
  11107. if(s(ss, ci).length > 0){
  11108. r[++ri] = ci;
  11109. }
  11110. }
  11111. return r;
  11112. },
  11113. "next" : function(c, ss){
  11114. var is = Ext.DomQuery.is,
  11115. r = [], ri = -1;
  11116. for(var i = 0, ci; ci = c[i]; i++){
  11117. var n = next(ci);
  11118. if(n && is(n, ss)){
  11119. r[++ri] = ci;
  11120. }
  11121. }
  11122. return r;
  11123. },
  11124. "prev" : function(c, ss){
  11125. var is = Ext.DomQuery.is,
  11126. r = [], ri = -1;
  11127. for(var i = 0, ci; ci = c[i]; i++){
  11128. var n = prev(ci);
  11129. if(n && is(n, ss)){
  11130. r[++ri] = ci;
  11131. }
  11132. }
  11133. return r;
  11134. }
  11135. }
  11136. };
  11137. }();
  11138. /**
  11139. * Shorthand of {@link Ext.DomQuery#select}
  11140. * @member Ext
  11141. * @method query
  11142. * @alias Ext.DomQuery#select
  11143. */
  11144. Ext.query = Ext.DomQuery.select;
  11145. /**
  11146. * @class Ext.Element
  11147. * @alternateClassName Ext.core.Element
  11148. *
  11149. * Encapsulates a DOM element, adding simple DOM manipulation facilities, normalizing for browser differences.
  11150. *
  11151. * All instances of this class inherit the methods of {@link Ext.fx.Anim} making visual effects easily available to all
  11152. * DOM elements.
  11153. *
  11154. * Note that the events documented in this class are not Ext events, they encapsulate browser events. Some older browsers
  11155. * may not support the full range of events. Which events are supported is beyond the control of Ext JS.
  11156. *
  11157. * Usage:
  11158. *
  11159. * // by id
  11160. * var el = Ext.get("my-div");
  11161. *
  11162. * // by DOM element reference
  11163. * var el = Ext.get(myDivElement);
  11164. *
  11165. * # Animations
  11166. *
  11167. * When an element is manipulated, by default there is no animation.
  11168. *
  11169. * var el = Ext.get("my-div");
  11170. *
  11171. * // no animation
  11172. * el.setWidth(100);
  11173. *
  11174. * Many of the functions for manipulating an element have an optional "animate" parameter. This parameter can be
  11175. * specified as boolean (true) for default animation effects.
  11176. *
  11177. * // default animation
  11178. * el.setWidth(100, true);
  11179. *
  11180. * To configure the effects, an object literal with animation options to use as the Element animation configuration
  11181. * object can also be specified. Note that the supported Element animation configuration options are a subset of the
  11182. * {@link Ext.fx.Anim} animation options specific to Fx effects. The supported Element animation configuration options
  11183. * are:
  11184. *
  11185. * Option Default Description
  11186. * --------- -------- ---------------------------------------------
  11187. * {@link Ext.fx.Anim#duration duration} .35 The duration of the animation in seconds
  11188. * {@link Ext.fx.Anim#easing easing} easeOut The easing method
  11189. * {@link Ext.fx.Anim#callback callback} none A function to execute when the anim completes
  11190. * {@link Ext.fx.Anim#scope scope} this The scope (this) of the callback function
  11191. *
  11192. * Usage:
  11193. *
  11194. * // Element animation options object
  11195. * var opt = {
  11196. * {@link Ext.fx.Anim#duration duration}: 1,
  11197. * {@link Ext.fx.Anim#easing easing}: 'elasticIn',
  11198. * {@link Ext.fx.Anim#callback callback}: this.foo,
  11199. * {@link Ext.fx.Anim#scope scope}: this
  11200. * };
  11201. * // animation with some options set
  11202. * el.setWidth(100, opt);
  11203. *
  11204. * The Element animation object being used for the animation will be set on the options object as "anim", which allows
  11205. * you to stop or manipulate the animation. Here is an example:
  11206. *
  11207. * // using the "anim" property to get the Anim object
  11208. * if(opt.anim.isAnimated()){
  11209. * opt.anim.stop();
  11210. * }
  11211. *
  11212. * # Composite (Collections of) Elements
  11213. *
  11214. * For working with collections of Elements, see {@link Ext.CompositeElement}
  11215. *
  11216. * @constructor
  11217. * Creates new Element directly.
  11218. * @param {String/HTMLElement} element
  11219. * @param {Boolean} forceNew (optional) By default the constructor checks to see if there is already an instance of this
  11220. * element in the cache and if there is it returns the same instance. This will skip that check (useful for extending
  11221. * this class).
  11222. * @return {Object}
  11223. */
  11224. (function() {
  11225. var DOC = document,
  11226. EC = Ext.cache;
  11227. Ext.Element = Ext.core.Element = function(element, forceNew) {
  11228. var dom = typeof element == "string" ? DOC.getElementById(element) : element,
  11229. id;
  11230. if (!dom) {
  11231. return null;
  11232. }
  11233. id = dom.id;
  11234. if (!forceNew && id && EC[id]) {
  11235. // element object already exists
  11236. return EC[id].el;
  11237. }
  11238. /**
  11239. * @property {HTMLElement} dom
  11240. * The DOM element
  11241. */
  11242. this.dom = dom;
  11243. /**
  11244. * @property {String} id
  11245. * The DOM element ID
  11246. */
  11247. this.id = id || Ext.id(dom);
  11248. };
  11249. var DH = Ext.DomHelper,
  11250. El = Ext.Element;
  11251. El.prototype = {
  11252. /**
  11253. * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
  11254. * @param {Object} o The object with the attributes
  11255. * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos.
  11256. * @return {Ext.Element} this
  11257. */
  11258. set: function(o, useSet) {
  11259. var el = this.dom,
  11260. attr,
  11261. val;
  11262. useSet = (useSet !== false) && !!el.setAttribute;
  11263. for (attr in o) {
  11264. if (o.hasOwnProperty(attr)) {
  11265. val = o[attr];
  11266. if (attr == 'style') {
  11267. DH.applyStyles(el, val);
  11268. } else if (attr == 'cls') {
  11269. el.className = val;
  11270. } else if (useSet) {
  11271. el.setAttribute(attr, val);
  11272. } else {
  11273. el[attr] = val;
  11274. }
  11275. }
  11276. }
  11277. return this;
  11278. },
  11279. // Mouse events
  11280. /**
  11281. * @event click
  11282. * Fires when a mouse click is detected within the element.
  11283. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11284. * @param {HTMLElement} t The target of the event.
  11285. */
  11286. /**
  11287. * @event contextmenu
  11288. * Fires when a right click is detected within the element.
  11289. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11290. * @param {HTMLElement} t The target of the event.
  11291. */
  11292. /**
  11293. * @event dblclick
  11294. * Fires when a mouse double click is detected within the element.
  11295. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11296. * @param {HTMLElement} t The target of the event.
  11297. */
  11298. /**
  11299. * @event mousedown
  11300. * Fires when a mousedown is detected within the element.
  11301. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11302. * @param {HTMLElement} t The target of the event.
  11303. */
  11304. /**
  11305. * @event mouseup
  11306. * Fires when a mouseup is detected within the element.
  11307. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11308. * @param {HTMLElement} t The target of the event.
  11309. */
  11310. /**
  11311. * @event mouseover
  11312. * Fires when a mouseover is detected within the element.
  11313. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11314. * @param {HTMLElement} t The target of the event.
  11315. */
  11316. /**
  11317. * @event mousemove
  11318. * Fires when a mousemove is detected with the element.
  11319. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11320. * @param {HTMLElement} t The target of the event.
  11321. */
  11322. /**
  11323. * @event mouseout
  11324. * Fires when a mouseout is detected with the element.
  11325. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11326. * @param {HTMLElement} t The target of the event.
  11327. */
  11328. /**
  11329. * @event mouseenter
  11330. * Fires when the mouse enters the element.
  11331. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11332. * @param {HTMLElement} t The target of the event.
  11333. */
  11334. /**
  11335. * @event mouseleave
  11336. * Fires when the mouse leaves the element.
  11337. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11338. * @param {HTMLElement} t The target of the event.
  11339. */
  11340. // Keyboard events
  11341. /**
  11342. * @event keypress
  11343. * Fires when a keypress is detected within the element.
  11344. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11345. * @param {HTMLElement} t The target of the event.
  11346. */
  11347. /**
  11348. * @event keydown
  11349. * Fires when a keydown is detected within the element.
  11350. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11351. * @param {HTMLElement} t The target of the event.
  11352. */
  11353. /**
  11354. * @event keyup
  11355. * Fires when a keyup is detected within the element.
  11356. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11357. * @param {HTMLElement} t The target of the event.
  11358. */
  11359. // HTML frame/object events
  11360. /**
  11361. * @event load
  11362. * Fires when the user agent finishes loading all content within the element. Only supported by window, frames,
  11363. * objects and images.
  11364. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11365. * @param {HTMLElement} t The target of the event.
  11366. */
  11367. /**
  11368. * @event unload
  11369. * Fires when the user agent removes all content from a window or frame. For elements, it fires when the target
  11370. * element or any of its content has been removed.
  11371. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11372. * @param {HTMLElement} t The target of the event.
  11373. */
  11374. /**
  11375. * @event abort
  11376. * Fires when an object/image is stopped from loading before completely loaded.
  11377. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11378. * @param {HTMLElement} t The target of the event.
  11379. */
  11380. /**
  11381. * @event error
  11382. * Fires when an object/image/frame cannot be loaded properly.
  11383. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11384. * @param {HTMLElement} t The target of the event.
  11385. */
  11386. /**
  11387. * @event resize
  11388. * Fires when a document view is resized.
  11389. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11390. * @param {HTMLElement} t The target of the event.
  11391. */
  11392. /**
  11393. * @event scroll
  11394. * Fires when a document view is scrolled.
  11395. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11396. * @param {HTMLElement} t The target of the event.
  11397. */
  11398. // Form events
  11399. /**
  11400. * @event select
  11401. * Fires when a user selects some text in a text field, including input and textarea.
  11402. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11403. * @param {HTMLElement} t The target of the event.
  11404. */
  11405. /**
  11406. * @event change
  11407. * Fires when a control loses the input focus and its value has been modified since gaining focus.
  11408. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11409. * @param {HTMLElement} t The target of the event.
  11410. */
  11411. /**
  11412. * @event submit
  11413. * Fires when a form is submitted.
  11414. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11415. * @param {HTMLElement} t The target of the event.
  11416. */
  11417. /**
  11418. * @event reset
  11419. * Fires when a form is reset.
  11420. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11421. * @param {HTMLElement} t The target of the event.
  11422. */
  11423. /**
  11424. * @event focus
  11425. * Fires when an element receives focus either via the pointing device or by tab navigation.
  11426. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11427. * @param {HTMLElement} t The target of the event.
  11428. */
  11429. /**
  11430. * @event blur
  11431. * Fires when an element loses focus either via the pointing device or by tabbing navigation.
  11432. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11433. * @param {HTMLElement} t The target of the event.
  11434. */
  11435. // User Interface events
  11436. /**
  11437. * @event DOMFocusIn
  11438. * Where supported. Similar to HTML focus event, but can be applied to any focusable element.
  11439. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11440. * @param {HTMLElement} t The target of the event.
  11441. */
  11442. /**
  11443. * @event DOMFocusOut
  11444. * Where supported. Similar to HTML blur event, but can be applied to any focusable element.
  11445. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11446. * @param {HTMLElement} t The target of the event.
  11447. */
  11448. /**
  11449. * @event DOMActivate
  11450. * Where supported. Fires when an element is activated, for instance, through a mouse click or a keypress.
  11451. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11452. * @param {HTMLElement} t The target of the event.
  11453. */
  11454. // DOM Mutation events
  11455. /**
  11456. * @event DOMSubtreeModified
  11457. * Where supported. Fires when the subtree is modified.
  11458. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11459. * @param {HTMLElement} t The target of the event.
  11460. */
  11461. /**
  11462. * @event DOMNodeInserted
  11463. * Where supported. Fires when a node has been added as a child of another node.
  11464. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11465. * @param {HTMLElement} t The target of the event.
  11466. */
  11467. /**
  11468. * @event DOMNodeRemoved
  11469. * Where supported. Fires when a descendant node of the element is removed.
  11470. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11471. * @param {HTMLElement} t The target of the event.
  11472. */
  11473. /**
  11474. * @event DOMNodeRemovedFromDocument
  11475. * Where supported. Fires when a node is being removed from a document.
  11476. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11477. * @param {HTMLElement} t The target of the event.
  11478. */
  11479. /**
  11480. * @event DOMNodeInsertedIntoDocument
  11481. * Where supported. Fires when a node is being inserted into a document.
  11482. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11483. * @param {HTMLElement} t The target of the event.
  11484. */
  11485. /**
  11486. * @event DOMAttrModified
  11487. * Where supported. Fires when an attribute has been modified.
  11488. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11489. * @param {HTMLElement} t The target of the event.
  11490. */
  11491. /**
  11492. * @event DOMCharacterDataModified
  11493. * Where supported. Fires when the character data has been modified.
  11494. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  11495. * @param {HTMLElement} t The target of the event.
  11496. */
  11497. /**
  11498. * @property {String} defaultUnit
  11499. * The default unit to append to CSS values where a unit isn't provided.
  11500. */
  11501. defaultUnit: "px",
  11502. /**
  11503. * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
  11504. * @param {String} selector The simple selector to test
  11505. * @return {Boolean} True if this element matches the selector, else false
  11506. */
  11507. is: function(simpleSelector) {
  11508. return Ext.DomQuery.is(this.dom, simpleSelector);
  11509. },
  11510. /**
  11511. * Tries to focus the element. Any exceptions are caught and ignored.
  11512. * @param {Number} defer (optional) Milliseconds to defer the focus
  11513. * @return {Ext.Element} this
  11514. */
  11515. focus: function(defer,
  11516. /* private */
  11517. dom) {
  11518. var me = this;
  11519. dom = dom || me.dom;
  11520. try {
  11521. if (Number(defer)) {
  11522. Ext.defer(me.focus, defer, null, [null, dom]);
  11523. } else {
  11524. dom.focus();
  11525. }
  11526. } catch(e) {}
  11527. return me;
  11528. },
  11529. /**
  11530. * Tries to blur the element. Any exceptions are caught and ignored.
  11531. * @return {Ext.Element} this
  11532. */
  11533. blur: function() {
  11534. try {
  11535. this.dom.blur();
  11536. } catch(e) {}
  11537. return this;
  11538. },
  11539. /**
  11540. * Returns the value of the "value" attribute
  11541. * @param {Boolean} asNumber true to parse the value as a number
  11542. * @return {String/Number}
  11543. */
  11544. getValue: function(asNumber) {
  11545. var val = this.dom.value;
  11546. return asNumber ? parseInt(val, 10) : val;
  11547. },
  11548. /**
  11549. * Appends an event handler to this element.
  11550. *
  11551. * @param {String} eventName The name of event to handle.
  11552. *
  11553. * @param {Function} fn The handler function the event invokes. This function is passed the following parameters:
  11554. *
  11555. * - **evt** : EventObject
  11556. *
  11557. * The {@link Ext.EventObject EventObject} describing the event.
  11558. *
  11559. * - **el** : HtmlElement
  11560. *
  11561. * The DOM element which was the target of the event. Note that this may be filtered by using the delegate option.
  11562. *
  11563. * - **o** : Object
  11564. *
  11565. * The options object from the addListener call.
  11566. *
  11567. * @param {Object} scope (optional) The scope (**this** reference) in which the handler function is executed. **If
  11568. * omitted, defaults to this Element.**
  11569. *
  11570. * @param {Object} options (optional) An object containing handler configuration properties. This may contain any of
  11571. * the following properties:
  11572. *
  11573. * - **scope** Object :
  11574. *
  11575. * The scope (**this** reference) in which the handler function is executed. **If omitted, defaults to this
  11576. * Element.**
  11577. *
  11578. * - **delegate** String:
  11579. *
  11580. * A simple selector to filter the target or look for a descendant of the target. See below for additional details.
  11581. *
  11582. * - **stopEvent** Boolean:
  11583. *
  11584. * True to stop the event. That is stop propagation, and prevent the default action.
  11585. *
  11586. * - **preventDefault** Boolean:
  11587. *
  11588. * True to prevent the default action
  11589. *
  11590. * - **stopPropagation** Boolean:
  11591. *
  11592. * True to prevent event propagation
  11593. *
  11594. * - **normalized** Boolean:
  11595. *
  11596. * False to pass a browser event to the handler function instead of an Ext.EventObject
  11597. *
  11598. * - **target** Ext.Element:
  11599. *
  11600. * Only call the handler if the event was fired on the target Element, _not_ if the event was bubbled up from a
  11601. * child node.
  11602. *
  11603. * - **delay** Number:
  11604. *
  11605. * The number of milliseconds to delay the invocation of the handler after the event fires.
  11606. *
  11607. * - **single** Boolean:
  11608. *
  11609. * True to add a handler to handle just the next firing of the event, and then remove itself.
  11610. *
  11611. * - **buffer** Number:
  11612. *
  11613. * Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed by the specified number of
  11614. * milliseconds. If the event fires again within that time, the original handler is _not_ invoked, but the new
  11615. * handler is scheduled in its place.
  11616. *
  11617. * **Combining Options**
  11618. *
  11619. * In the following examples, the shorthand form {@link #on} is used rather than the more verbose addListener. The
  11620. * two are equivalent. Using the options argument, it is possible to combine different types of listeners:
  11621. *
  11622. * A delayed, one-time listener that auto stops the event and adds a custom argument (forumId) to the options
  11623. * object. The options object is available as the third parameter in the handler function.
  11624. *
  11625. * Code:
  11626. *
  11627. * el.on('click', this.onClick, this, {
  11628. * single: true,
  11629. * delay: 100,
  11630. * stopEvent : true,
  11631. * forumId: 4
  11632. * });
  11633. *
  11634. * **Attaching multiple handlers in 1 call**
  11635. *
  11636. * The method also allows for a single argument to be passed which is a config object containing properties which
  11637. * specify multiple handlers.
  11638. *
  11639. * Code:
  11640. *
  11641. * el.on({
  11642. * 'click' : {
  11643. * fn: this.onClick,
  11644. * scope: this,
  11645. * delay: 100
  11646. * },
  11647. * 'mouseover' : {
  11648. * fn: this.onMouseOver,
  11649. * scope: this
  11650. * },
  11651. * 'mouseout' : {
  11652. * fn: this.onMouseOut,
  11653. * scope: this
  11654. * }
  11655. * });
  11656. *
  11657. * Or a shorthand syntax:
  11658. *
  11659. * Code:
  11660. *
  11661. * el.on({
  11662. * 'click' : this.onClick,
  11663. * 'mouseover' : this.onMouseOver,
  11664. * 'mouseout' : this.onMouseOut,
  11665. * scope: this
  11666. * });
  11667. *
  11668. * **delegate**
  11669. *
  11670. * This is a configuration option that you can pass along when registering a handler for an event to assist with
  11671. * event delegation. Event delegation is a technique that is used to reduce memory consumption and prevent exposure
  11672. * to memory-leaks. By registering an event for a container element as opposed to each element within a container.
  11673. * By setting this configuration option to a simple selector, the target element will be filtered to look for a
  11674. * descendant of the target. For example:
  11675. *
  11676. * // using this markup:
  11677. * <div id='elId'>
  11678. * <p id='p1'>paragraph one</p>
  11679. * <p id='p2' class='clickable'>paragraph two</p>
  11680. * <p id='p3'>paragraph three</p>
  11681. * </div>
  11682. *
  11683. * // utilize event delegation to registering just one handler on the container element:
  11684. * el = Ext.get('elId');
  11685. * el.on(
  11686. * 'click',
  11687. * function(e,t) {
  11688. * // handle click
  11689. * console.info(t.id); // 'p2'
  11690. * },
  11691. * this,
  11692. * {
  11693. * // filter the target element to be a descendant with the class 'clickable'
  11694. * delegate: '.clickable'
  11695. * }
  11696. * );
  11697. *
  11698. * @return {Ext.Element} this
  11699. */
  11700. addListener: function(eventName, fn, scope, options) {
  11701. Ext.EventManager.on(this.dom, eventName, fn, scope || this, options);
  11702. return this;
  11703. },
  11704. /**
  11705. * Removes an event handler from this element.
  11706. *
  11707. * **Note**: if a *scope* was explicitly specified when {@link #addListener adding} the listener,
  11708. * the same scope must be specified here.
  11709. *
  11710. * Example:
  11711. *
  11712. * el.removeListener('click', this.handlerFn);
  11713. * // or
  11714. * el.un('click', this.handlerFn);
  11715. *
  11716. * @param {String} eventName The name of the event from which to remove the handler.
  11717. * @param {Function} fn The handler function to remove. **This must be a reference to the function passed into the
  11718. * {@link #addListener} call.**
  11719. * @param {Object} scope If a scope (**this** reference) was specified when the listener was added, then this must
  11720. * refer to the same object.
  11721. * @return {Ext.Element} this
  11722. */
  11723. removeListener: function(eventName, fn, scope) {
  11724. Ext.EventManager.un(this.dom, eventName, fn, scope || this);
  11725. return this;
  11726. },
  11727. /**
  11728. * Removes all previous added listeners from this element
  11729. * @return {Ext.Element} this
  11730. */
  11731. removeAllListeners: function() {
  11732. Ext.EventManager.removeAll(this.dom);
  11733. return this;
  11734. },
  11735. /**
  11736. * Recursively removes all previous added listeners from this element and its children
  11737. * @return {Ext.Element} this
  11738. */
  11739. purgeAllListeners: function() {
  11740. Ext.EventManager.purgeElement(this);
  11741. return this;
  11742. },
  11743. /**
  11744. * Test if size has a unit, otherwise appends the passed unit string, or the default for this Element.
  11745. * @param size {Mixed} The size to set
  11746. * @param units {String} The units to append to a numeric size value
  11747. * @private
  11748. */
  11749. addUnits: function(size, units) {
  11750. // Most common case first: Size is set to a number
  11751. if (Ext.isNumber(size)) {
  11752. return size + (units || this.defaultUnit || 'px');
  11753. }
  11754. // Size set to a value which means "auto"
  11755. if (size === "" || size == "auto" || size == null) {
  11756. return size || '';
  11757. }
  11758. // Otherwise, warn if it's not a valid CSS measurement
  11759. if (!unitPattern.test(size)) {
  11760. return size || '';
  11761. }
  11762. return size;
  11763. },
  11764. /**
  11765. * Tests various css rules/browsers to determine if this element uses a border box
  11766. * @return {Boolean}
  11767. */
  11768. isBorderBox: function() {
  11769. return Ext.isBorderBox || noBoxAdjust[(this.dom.tagName || "").toLowerCase()];
  11770. },
  11771. /**
  11772. * Removes this element's dom reference. Note that event and cache removal is handled at {@link Ext#removeNode
  11773. * Ext.removeNode}
  11774. */
  11775. remove: function() {
  11776. var me = this,
  11777. dom = me.dom;
  11778. if (dom) {
  11779. delete me.dom;
  11780. Ext.removeNode(dom);
  11781. }
  11782. },
  11783. /**
  11784. * Sets up event handlers to call the passed functions when the mouse is moved into and out of the Element.
  11785. * @param {Function} overFn The function to call when the mouse enters the Element.
  11786. * @param {Function} outFn The function to call when the mouse leaves the Element.
  11787. * @param {Object} scope (optional) The scope (`this` reference) in which the functions are executed. Defaults
  11788. * to the Element's DOM element.
  11789. * @param {Object} options (optional) Options for the listener. See {@link Ext.util.Observable#addListener the
  11790. * options parameter}.
  11791. * @return {Ext.Element} this
  11792. */
  11793. hover: function(overFn, outFn, scope, options) {
  11794. var me = this;
  11795. me.on('mouseenter', overFn, scope || me.dom, options);
  11796. me.on('mouseleave', outFn, scope || me.dom, options);
  11797. return me;
  11798. },
  11799. /**
  11800. * Returns true if this element is an ancestor of the passed element
  11801. * @param {HTMLElement/String} el The element to check
  11802. * @return {Boolean} True if this element is an ancestor of el, else false
  11803. */
  11804. contains: function(el) {
  11805. return ! el ? false: Ext.Element.isAncestor(this.dom, el.dom ? el.dom: el);
  11806. },
  11807. /**
  11808. * Returns the value of a namespaced attribute from the element's underlying DOM node.
  11809. * @param {String} namespace The namespace in which to look for the attribute
  11810. * @param {String} name The attribute name
  11811. * @return {String} The attribute value
  11812. */
  11813. getAttributeNS: function(ns, name) {
  11814. return this.getAttribute(name, ns);
  11815. },
  11816. /**
  11817. * Returns the value of an attribute from the element's underlying DOM node.
  11818. * @param {String} name The attribute name
  11819. * @param {String} namespace (optional) The namespace in which to look for the attribute
  11820. * @return {String} The attribute value
  11821. * @method
  11822. */
  11823. getAttribute: (Ext.isIE && !(Ext.isIE9 && document.documentMode === 9)) ?
  11824. function(name, ns) {
  11825. var d = this.dom,
  11826. type;
  11827. if(ns) {
  11828. type = typeof d[ns + ":" + name];
  11829. if (type != 'undefined' && type != 'unknown') {
  11830. return d[ns + ":" + name] || null;
  11831. }
  11832. return null;
  11833. }
  11834. if (name === "for") {
  11835. name = "htmlFor";
  11836. }
  11837. return d[name] || null;
  11838. }: function(name, ns) {
  11839. var d = this.dom;
  11840. if (ns) {
  11841. return d.getAttributeNS(ns, name) || d.getAttribute(ns + ":" + name);
  11842. }
  11843. return d.getAttribute(name) || d[name] || null;
  11844. },
  11845. /**
  11846. * Update the innerHTML of this element
  11847. * @param {String} html The new HTML
  11848. * @return {Ext.Element} this
  11849. */
  11850. update: function(html) {
  11851. if (this.dom) {
  11852. this.dom.innerHTML = html;
  11853. }
  11854. return this;
  11855. }
  11856. };
  11857. var ep = El.prototype;
  11858. El.addMethods = function(o) {
  11859. Ext.apply(ep, o);
  11860. };
  11861. /**
  11862. * @method
  11863. * @alias Ext.Element#addListener
  11864. * Shorthand for {@link #addListener}.
  11865. */
  11866. ep.on = ep.addListener;
  11867. /**
  11868. * @method
  11869. * @alias Ext.Element#removeListener
  11870. * Shorthand for {@link #removeListener}.
  11871. */
  11872. ep.un = ep.removeListener;
  11873. /**
  11874. * @method
  11875. * @alias Ext.Element#removeAllListeners
  11876. * Alias for {@link #removeAllListeners}.
  11877. */
  11878. ep.clearListeners = ep.removeAllListeners;
  11879. /**
  11880. * @method destroy
  11881. * @member Ext.Element
  11882. * Removes this element's dom reference. Note that event and cache removal is handled at {@link Ext#removeNode
  11883. * Ext.removeNode}. Alias to {@link #remove}.
  11884. */
  11885. ep.destroy = ep.remove;
  11886. /**
  11887. * @property {Boolean} autoBoxAdjust
  11888. * true to automatically adjust width and height settings for box-model issues (default to true)
  11889. */
  11890. ep.autoBoxAdjust = true;
  11891. // private
  11892. var unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i,
  11893. docEl;
  11894. /**
  11895. * Retrieves Ext.Element objects. {@link Ext#get} is an alias for {@link Ext.Element#get}.
  11896. *
  11897. * **This method does not retrieve {@link Ext.Component Component}s.** This method retrieves Ext.Element
  11898. * objects which encapsulate DOM elements. To retrieve a Component by its ID, use {@link Ext.ComponentManager#get}.
  11899. *
  11900. * Uses simple caching to consistently return the same object. Automatically fixes if an object was recreated with
  11901. * the same id via AJAX or DOM.
  11902. *
  11903. * @param {String/HTMLElement/Ext.Element} el The id of the node, a DOM Node or an existing Element.
  11904. * @return {Ext.Element} The Element object (or null if no matching element was found)
  11905. * @static
  11906. */
  11907. El.get = function(el) {
  11908. var ex,
  11909. elm,
  11910. id;
  11911. if (!el) {
  11912. return null;
  11913. }
  11914. if (typeof el == "string") {
  11915. // element id
  11916. if (! (elm = DOC.getElementById(el))) {
  11917. return null;
  11918. }
  11919. if (EC[el] && EC[el].el) {
  11920. ex = EC[el].el;
  11921. ex.dom = elm;
  11922. } else {
  11923. ex = El.addToCache(new El(elm));
  11924. }
  11925. return ex;
  11926. } else if (el.tagName) {
  11927. // dom element
  11928. if (! (id = el.id)) {
  11929. id = Ext.id(el);
  11930. }
  11931. if (EC[id] && EC[id].el) {
  11932. ex = EC[id].el;
  11933. ex.dom = el;
  11934. } else {
  11935. ex = El.addToCache(new El(el));
  11936. }
  11937. return ex;
  11938. } else if (el instanceof El) {
  11939. if (el != docEl) {
  11940. // refresh dom element in case no longer valid,
  11941. // catch case where it hasn't been appended
  11942. // If an el instance is passed, don't pass to getElementById without some kind of id
  11943. if (Ext.isIE && (el.id == undefined || el.id == '')) {
  11944. el.dom = el.dom;
  11945. } else {
  11946. el.dom = DOC.getElementById(el.id) || el.dom;
  11947. }
  11948. }
  11949. return el;
  11950. } else if (el.isComposite) {
  11951. return el;
  11952. } else if (Ext.isArray(el)) {
  11953. return El.select(el);
  11954. } else if (el == DOC) {
  11955. // create a bogus element object representing the document object
  11956. if (!docEl) {
  11957. var f = function() {};
  11958. f.prototype = El.prototype;
  11959. docEl = new f();
  11960. docEl.dom = DOC;
  11961. }
  11962. return docEl;
  11963. }
  11964. return null;
  11965. };
  11966. /**
  11967. * Retrieves Ext.Element objects like {@link Ext#get} but is optimized for sub-elements.
  11968. * This is helpful for performance, because in IE (prior to IE 9), `getElementById` uses
  11969. * an non-optimized search. In those browsers, starting the search for an element with a
  11970. * matching ID at a parent of that element will greatly speed up the process.
  11971. *
  11972. * Unlike {@link Ext#get}, this method only accepts ID's. If the ID is not a child of
  11973. * this element, it will still be found if it exists in the document, but will be slower
  11974. * than calling {@link Ext#get} directly.
  11975. *
  11976. * @param {String} id The id of the element to get.
  11977. * @return {Ext.Element} The Element object (or null if no matching element was found)
  11978. * @member Ext.Element
  11979. * @method getById
  11980. * @markdown
  11981. */
  11982. ep.getById = (!Ext.isIE6 && !Ext.isIE7 && !Ext.isIE8) ? El.get :
  11983. function (id) {
  11984. var dom = this.dom,
  11985. cached, el, ret;
  11986. if (dom) {
  11987. el = dom.all[id];
  11988. if (el) {
  11989. // calling El.get here is a real hit (2x slower) because it has to
  11990. // redetermine that we are giving it a dom el.
  11991. cached = EC[id];
  11992. if (cached && cached.el) {
  11993. ret = cached.el;
  11994. ret.dom = el;
  11995. } else {
  11996. ret = El.addToCache(new El(el));
  11997. }
  11998. return ret;
  11999. }
  12000. }
  12001. return El.get(id);
  12002. };
  12003. El.addToCache = function(el, id) {
  12004. if (el) {
  12005. id = id || el.id;
  12006. EC[id] = {
  12007. el: el,
  12008. data: {},
  12009. events: {}
  12010. };
  12011. }
  12012. return el;
  12013. };
  12014. // private method for getting and setting element data
  12015. El.data = function(el, key, value) {
  12016. el = El.get(el);
  12017. if (!el) {
  12018. return null;
  12019. }
  12020. var c = EC[el.id].data;
  12021. if (arguments.length == 2) {
  12022. return c[key];
  12023. } else {
  12024. return (c[key] = value);
  12025. }
  12026. };
  12027. // private
  12028. // Garbage collection - uncache elements/purge listeners on orphaned elements
  12029. // so we don't hold a reference and cause the browser to retain them
  12030. function garbageCollect() {
  12031. if (!Ext.enableGarbageCollector) {
  12032. clearInterval(El.collectorThreadId);
  12033. } else {
  12034. var eid,
  12035. el,
  12036. d,
  12037. o;
  12038. for (eid in EC) {
  12039. if (!EC.hasOwnProperty(eid)) {
  12040. continue;
  12041. }
  12042. o = EC[eid];
  12043. if (o.skipGarbageCollection) {
  12044. continue;
  12045. }
  12046. el = o.el;
  12047. d = el.dom;
  12048. // -------------------------------------------------------
  12049. // Determining what is garbage:
  12050. // -------------------------------------------------------
  12051. // !d
  12052. // dom node is null, definitely garbage
  12053. // -------------------------------------------------------
  12054. // !d.parentNode
  12055. // no parentNode == direct orphan, definitely garbage
  12056. // -------------------------------------------------------
  12057. // !d.offsetParent && !document.getElementById(eid)
  12058. // display none elements have no offsetParent so we will
  12059. // also try to look it up by it's id. However, check
  12060. // offsetParent first so we don't do unneeded lookups.
  12061. // This enables collection of elements that are not orphans
  12062. // directly, but somewhere up the line they have an orphan
  12063. // parent.
  12064. // -------------------------------------------------------
  12065. if (!d || !d.parentNode || (!d.offsetParent && !DOC.getElementById(eid))) {
  12066. if (d && Ext.enableListenerCollection) {
  12067. Ext.EventManager.removeAll(d);
  12068. }
  12069. delete EC[eid];
  12070. }
  12071. }
  12072. // Cleanup IE Object leaks
  12073. if (Ext.isIE) {
  12074. var t = {};
  12075. for (eid in EC) {
  12076. if (!EC.hasOwnProperty(eid)) {
  12077. continue;
  12078. }
  12079. t[eid] = EC[eid];
  12080. }
  12081. EC = Ext.cache = t;
  12082. }
  12083. }
  12084. }
  12085. El.collectorThreadId = setInterval(garbageCollect, 30000);
  12086. var flyFn = function() {};
  12087. flyFn.prototype = El.prototype;
  12088. // dom is optional
  12089. El.Flyweight = function(dom) {
  12090. this.dom = dom;
  12091. };
  12092. El.Flyweight.prototype = new flyFn();
  12093. El.Flyweight.prototype.isFlyweight = true;
  12094. El._flyweights = {};
  12095. /**
  12096. * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference
  12097. * to this element - the dom node can be overwritten by other code. {@link Ext#fly} is alias for
  12098. * {@link Ext.Element#fly}.
  12099. *
  12100. * Use this to make one-time references to DOM elements which are not going to be accessed again either by
  12101. * application code, or by Ext's classes. If accessing an element which will be processed regularly, then {@link
  12102. * Ext#get Ext.get} will be more appropriate to take advantage of the caching provided by the Ext.Element
  12103. * class.
  12104. *
  12105. * @param {String/HTMLElement} el The dom node or id
  12106. * @param {String} named (optional) Allows for creation of named reusable flyweights to prevent conflicts (e.g.
  12107. * internally Ext uses "_global")
  12108. * @return {Ext.Element} The shared Element object (or null if no matching element was found)
  12109. * @static
  12110. */
  12111. El.fly = function(el, named) {
  12112. var ret = null;
  12113. named = named || '_global';
  12114. el = Ext.getDom(el);
  12115. if (el) {
  12116. (El._flyweights[named] = El._flyweights[named] || new El.Flyweight()).dom = el;
  12117. ret = El._flyweights[named];
  12118. }
  12119. return ret;
  12120. };
  12121. /**
  12122. * @member Ext
  12123. * @method get
  12124. * @alias Ext.Element#get
  12125. */
  12126. Ext.get = El.get;
  12127. /**
  12128. * @member Ext
  12129. * @method fly
  12130. * @alias Ext.Element#fly
  12131. */
  12132. Ext.fly = El.fly;
  12133. // speedy lookup for elements never to box adjust
  12134. var noBoxAdjust = Ext.isStrict ? {
  12135. select: 1
  12136. }: {
  12137. input: 1,
  12138. select: 1,
  12139. textarea: 1
  12140. };
  12141. if (Ext.isIE || Ext.isGecko) {
  12142. noBoxAdjust['button'] = 1;
  12143. }
  12144. })();
  12145. /**
  12146. * @class Ext.Element
  12147. */
  12148. Ext.Element.addMethods({
  12149. /**
  12150. * Looks at this node and then at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
  12151. * @param {String} selector The simple selector to test
  12152. * @param {Number/String/HTMLElement/Ext.Element} maxDepth (optional)
  12153. * The max depth to search as a number or element (defaults to 50 || document.body)
  12154. * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
  12155. * @return {HTMLElement} The matching DOM node (or null if no match was found)
  12156. */
  12157. findParent : function(simpleSelector, maxDepth, returnEl) {
  12158. var p = this.dom,
  12159. b = document.body,
  12160. depth = 0,
  12161. stopEl;
  12162. maxDepth = maxDepth || 50;
  12163. if (isNaN(maxDepth)) {
  12164. stopEl = Ext.getDom(maxDepth);
  12165. maxDepth = Number.MAX_VALUE;
  12166. }
  12167. while (p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl) {
  12168. if (Ext.DomQuery.is(p, simpleSelector)) {
  12169. return returnEl ? Ext.get(p) : p;
  12170. }
  12171. depth++;
  12172. p = p.parentNode;
  12173. }
  12174. return null;
  12175. },
  12176. /**
  12177. * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
  12178. * @param {String} selector The simple selector to test
  12179. * @param {Number/String/HTMLElement/Ext.Element} maxDepth (optional)
  12180. * The max depth to search as a number or element (defaults to 10 || document.body)
  12181. * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
  12182. * @return {HTMLElement} The matching DOM node (or null if no match was found)
  12183. */
  12184. findParentNode : function(simpleSelector, maxDepth, returnEl) {
  12185. var p = Ext.fly(this.dom.parentNode, '_internal');
  12186. return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null;
  12187. },
  12188. /**
  12189. * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
  12190. * This is a shortcut for findParentNode() that always returns an Ext.Element.
  12191. * @param {String} selector The simple selector to test
  12192. * @param {Number/String/HTMLElement/Ext.Element} maxDepth (optional)
  12193. * The max depth to search as a number or element (defaults to 10 || document.body)
  12194. * @return {Ext.Element} The matching DOM node (or null if no match was found)
  12195. */
  12196. up : function(simpleSelector, maxDepth) {
  12197. return this.findParentNode(simpleSelector, maxDepth, true);
  12198. },
  12199. /**
  12200. * Creates a {@link Ext.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
  12201. * @param {String} selector The CSS selector
  12202. * @return {Ext.CompositeElement/Ext.CompositeElement} The composite element
  12203. */
  12204. select : function(selector) {
  12205. return Ext.Element.select(selector, false, this.dom);
  12206. },
  12207. /**
  12208. * Selects child nodes based on the passed CSS selector (the selector should not contain an id).
  12209. * @param {String} selector The CSS selector
  12210. * @return {HTMLElement[]} An array of the matched nodes
  12211. */
  12212. query : function(selector) {
  12213. return Ext.DomQuery.select(selector, this.dom);
  12214. },
  12215. /**
  12216. * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
  12217. * @param {String} selector The CSS selector
  12218. * @param {Boolean} returnDom (optional) True to return the DOM node instead of Ext.Element (defaults to false)
  12219. * @return {HTMLElement/Ext.Element} The child Ext.Element (or DOM node if returnDom = true)
  12220. */
  12221. down : function(selector, returnDom) {
  12222. var n = Ext.DomQuery.selectNode(selector, this.dom);
  12223. return returnDom ? n : Ext.get(n);
  12224. },
  12225. /**
  12226. * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
  12227. * @param {String} selector The CSS selector
  12228. * @param {Boolean} returnDom (optional) True to return the DOM node instead of Ext.Element (defaults to false)
  12229. * @return {HTMLElement/Ext.Element} The child Ext.Element (or DOM node if returnDom = true)
  12230. */
  12231. child : function(selector, returnDom) {
  12232. var node,
  12233. me = this,
  12234. id;
  12235. id = Ext.get(me).id;
  12236. // Escape . or :
  12237. id = id.replace(/[\.:]/g, "\\$0");
  12238. node = Ext.DomQuery.selectNode('#' + id + " > " + selector, me.dom);
  12239. return returnDom ? node : Ext.get(node);
  12240. },
  12241. /**
  12242. * Gets the parent node for this element, optionally chaining up trying to match a selector
  12243. * @param {String} selector (optional) Find a parent node that matches the passed simple selector
  12244. * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element
  12245. * @return {Ext.Element/HTMLElement} The parent node or null
  12246. */
  12247. parent : function(selector, returnDom) {
  12248. return this.matchNode('parentNode', 'parentNode', selector, returnDom);
  12249. },
  12250. /**
  12251. * Gets the next sibling, skipping text nodes
  12252. * @param {String} selector (optional) Find the next sibling that matches the passed simple selector
  12253. * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element
  12254. * @return {Ext.Element/HTMLElement} The next sibling or null
  12255. */
  12256. next : function(selector, returnDom) {
  12257. return this.matchNode('nextSibling', 'nextSibling', selector, returnDom);
  12258. },
  12259. /**
  12260. * Gets the previous sibling, skipping text nodes
  12261. * @param {String} selector (optional) Find the previous sibling that matches the passed simple selector
  12262. * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element
  12263. * @return {Ext.Element/HTMLElement} The previous sibling or null
  12264. */
  12265. prev : function(selector, returnDom) {
  12266. return this.matchNode('previousSibling', 'previousSibling', selector, returnDom);
  12267. },
  12268. /**
  12269. * Gets the first child, skipping text nodes
  12270. * @param {String} selector (optional) Find the next sibling that matches the passed simple selector
  12271. * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element
  12272. * @return {Ext.Element/HTMLElement} The first child or null
  12273. */
  12274. first : function(selector, returnDom) {
  12275. return this.matchNode('nextSibling', 'firstChild', selector, returnDom);
  12276. },
  12277. /**
  12278. * Gets the last child, skipping text nodes
  12279. * @param {String} selector (optional) Find the previous sibling that matches the passed simple selector
  12280. * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element
  12281. * @return {Ext.Element/HTMLElement} The last child or null
  12282. */
  12283. last : function(selector, returnDom) {
  12284. return this.matchNode('previousSibling', 'lastChild', selector, returnDom);
  12285. },
  12286. matchNode : function(dir, start, selector, returnDom) {
  12287. if (!this.dom) {
  12288. return null;
  12289. }
  12290. var n = this.dom[start];
  12291. while (n) {
  12292. if (n.nodeType == 1 && (!selector || Ext.DomQuery.is(n, selector))) {
  12293. return !returnDom ? Ext.get(n) : n;
  12294. }
  12295. n = n[dir];
  12296. }
  12297. return null;
  12298. }
  12299. });
  12300. /**
  12301. * @class Ext.Element
  12302. */
  12303. Ext.Element.addMethods({
  12304. /**
  12305. * Appends the passed element(s) to this element
  12306. * @param {String/HTMLElement/Ext.Element} el
  12307. * The id of the node, a DOM Node or an existing Element.
  12308. * @return {Ext.Element} this
  12309. */
  12310. appendChild : function(el) {
  12311. return Ext.get(el).appendTo(this);
  12312. },
  12313. /**
  12314. * Appends this element to the passed element
  12315. * @param {String/HTMLElement/Ext.Element} el The new parent element.
  12316. * The id of the node, a DOM Node or an existing Element.
  12317. * @return {Ext.Element} this
  12318. */
  12319. appendTo : function(el) {
  12320. Ext.getDom(el).appendChild(this.dom);
  12321. return this;
  12322. },
  12323. /**
  12324. * Inserts this element before the passed element in the DOM
  12325. * @param {String/HTMLElement/Ext.Element} el The element before which this element will be inserted.
  12326. * The id of the node, a DOM Node or an existing Element.
  12327. * @return {Ext.Element} this
  12328. */
  12329. insertBefore : function(el) {
  12330. el = Ext.getDom(el);
  12331. el.parentNode.insertBefore(this.dom, el);
  12332. return this;
  12333. },
  12334. /**
  12335. * Inserts this element after the passed element in the DOM
  12336. * @param {String/HTMLElement/Ext.Element} el The element to insert after.
  12337. * The id of the node, a DOM Node or an existing Element.
  12338. * @return {Ext.Element} this
  12339. */
  12340. insertAfter : function(el) {
  12341. el = Ext.getDom(el);
  12342. el.parentNode.insertBefore(this.dom, el.nextSibling);
  12343. return this;
  12344. },
  12345. /**
  12346. * Inserts (or creates) an element (or DomHelper config) as the first child of this element
  12347. * @param {String/HTMLElement/Ext.Element/Object} el The id or element to insert or a DomHelper config
  12348. * to create and insert
  12349. * @return {Ext.Element} The new child
  12350. */
  12351. insertFirst : function(el, returnDom) {
  12352. el = el || {};
  12353. if (el.nodeType || el.dom || typeof el == 'string') { // element
  12354. el = Ext.getDom(el);
  12355. this.dom.insertBefore(el, this.dom.firstChild);
  12356. return !returnDom ? Ext.get(el) : el;
  12357. }
  12358. else { // dh config
  12359. return this.createChild(el, this.dom.firstChild, returnDom);
  12360. }
  12361. },
  12362. /**
  12363. * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
  12364. * @param {String/HTMLElement/Ext.Element/Object/Array} el The id, element to insert or a DomHelper config
  12365. * to create and insert *or* an array of any of those.
  12366. * @param {String} where (optional) 'before' or 'after' defaults to before
  12367. * @param {Boolean} returnDom (optional) True to return the .;ll;l,raw DOM element instead of Ext.Element
  12368. * @return {Ext.Element} The inserted Element. If an array is passed, the last inserted element is returned.
  12369. */
  12370. insertSibling: function(el, where, returnDom){
  12371. var me = this, rt,
  12372. isAfter = (where || 'before').toLowerCase() == 'after',
  12373. insertEl;
  12374. if(Ext.isArray(el)){
  12375. insertEl = me;
  12376. Ext.each(el, function(e) {
  12377. rt = Ext.fly(insertEl, '_internal').insertSibling(e, where, returnDom);
  12378. if(isAfter){
  12379. insertEl = rt;
  12380. }
  12381. });
  12382. return rt;
  12383. }
  12384. el = el || {};
  12385. if(el.nodeType || el.dom){
  12386. rt = me.dom.parentNode.insertBefore(Ext.getDom(el), isAfter ? me.dom.nextSibling : me.dom);
  12387. if (!returnDom) {
  12388. rt = Ext.get(rt);
  12389. }
  12390. }else{
  12391. if (isAfter && !me.dom.nextSibling) {
  12392. rt = Ext.DomHelper.append(me.dom.parentNode, el, !returnDom);
  12393. } else {
  12394. rt = Ext.DomHelper[isAfter ? 'insertAfter' : 'insertBefore'](me.dom, el, !returnDom);
  12395. }
  12396. }
  12397. return rt;
  12398. },
  12399. /**
  12400. * Replaces the passed element with this element
  12401. * @param {String/HTMLElement/Ext.Element} el The element to replace.
  12402. * The id of the node, a DOM Node or an existing Element.
  12403. * @return {Ext.Element} this
  12404. */
  12405. replace : function(el) {
  12406. el = Ext.get(el);
  12407. this.insertBefore(el);
  12408. el.remove();
  12409. return this;
  12410. },
  12411. /**
  12412. * Replaces this element with the passed element
  12413. * @param {String/HTMLElement/Ext.Element/Object} el The new element (id of the node, a DOM Node
  12414. * or an existing Element) or a DomHelper config of an element to create
  12415. * @return {Ext.Element} this
  12416. */
  12417. replaceWith: function(el){
  12418. var me = this;
  12419. if(el.nodeType || el.dom || typeof el == 'string'){
  12420. el = Ext.get(el);
  12421. me.dom.parentNode.insertBefore(el, me.dom);
  12422. }else{
  12423. el = Ext.DomHelper.insertBefore(me.dom, el);
  12424. }
  12425. delete Ext.cache[me.id];
  12426. Ext.removeNode(me.dom);
  12427. me.id = Ext.id(me.dom = el);
  12428. Ext.Element.addToCache(me.isFlyweight ? new Ext.Element(me.dom) : me);
  12429. return me;
  12430. },
  12431. /**
  12432. * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
  12433. * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be
  12434. * automatically generated with the specified attributes.
  12435. * @param {HTMLElement} insertBefore (optional) a child element of this element
  12436. * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element
  12437. * @return {Ext.Element} The new child element
  12438. */
  12439. createChild : function(config, insertBefore, returnDom) {
  12440. config = config || {tag:'div'};
  12441. if (insertBefore) {
  12442. return Ext.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
  12443. }
  12444. else {
  12445. return Ext.DomHelper[!this.dom.firstChild ? 'insertFirst' : 'append'](this.dom, config, returnDom !== true);
  12446. }
  12447. },
  12448. /**
  12449. * Creates and wraps this element with another element
  12450. * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div
  12451. * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Ext.Element
  12452. * @return {HTMLElement/Ext.Element} The newly created wrapper element
  12453. */
  12454. wrap : function(config, returnDom) {
  12455. var newEl = Ext.DomHelper.insertBefore(this.dom, config || {tag: "div"}, !returnDom),
  12456. d = newEl.dom || newEl;
  12457. d.appendChild(this.dom);
  12458. return newEl;
  12459. },
  12460. /**
  12461. * Inserts an html fragment into this element
  12462. * @param {String} where Where to insert the html in relation to this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
  12463. * See {@link Ext.DomHelper#insertHtml} for details.
  12464. * @param {String} html The HTML fragment
  12465. * @param {Boolean} returnEl (optional) True to return an Ext.Element (defaults to false)
  12466. * @return {HTMLElement/Ext.Element} The inserted node (or nearest related if more than 1 inserted)
  12467. */
  12468. insertHtml : function(where, html, returnEl) {
  12469. var el = Ext.DomHelper.insertHtml(where, this.dom, html);
  12470. return returnEl ? Ext.get(el) : el;
  12471. }
  12472. });
  12473. /**
  12474. * @class Ext.Element
  12475. */
  12476. (function(){
  12477. // local style camelizing for speed
  12478. var ELEMENT = Ext.Element,
  12479. supports = Ext.supports,
  12480. view = document.defaultView,
  12481. opacityRe = /alpha\(opacity=(.*)\)/i,
  12482. trimRe = /^\s+|\s+$/g,
  12483. spacesRe = /\s+/,
  12484. wordsRe = /\w/g,
  12485. adjustDirect2DTableRe = /table-row|table-.*-group/,
  12486. INTERNAL = '_internal',
  12487. PADDING = 'padding',
  12488. MARGIN = 'margin',
  12489. BORDER = 'border',
  12490. LEFT = '-left',
  12491. RIGHT = '-right',
  12492. TOP = '-top',
  12493. BOTTOM = '-bottom',
  12494. WIDTH = '-width',
  12495. MATH = Math,
  12496. HIDDEN = 'hidden',
  12497. ISCLIPPED = 'isClipped',
  12498. OVERFLOW = 'overflow',
  12499. OVERFLOWX = 'overflow-x',
  12500. OVERFLOWY = 'overflow-y',
  12501. ORIGINALCLIP = 'originalClip',
  12502. // special markup used throughout Ext when box wrapping elements
  12503. borders = {l: BORDER + LEFT + WIDTH, r: BORDER + RIGHT + WIDTH, t: BORDER + TOP + WIDTH, b: BORDER + BOTTOM + WIDTH},
  12504. paddings = {l: PADDING + LEFT, r: PADDING + RIGHT, t: PADDING + TOP, b: PADDING + BOTTOM},
  12505. margins = {l: MARGIN + LEFT, r: MARGIN + RIGHT, t: MARGIN + TOP, b: MARGIN + BOTTOM},
  12506. data = ELEMENT.data;
  12507. ELEMENT.boxMarkup = '<div class="{0}-tl"><div class="{0}-tr"><div class="{0}-tc"></div></div></div><div class="{0}-ml"><div class="{0}-mr"><div class="{0}-mc"></div></div></div><div class="{0}-bl"><div class="{0}-br"><div class="{0}-bc"></div></div></div>';
  12508. // These property values are read from the parentNode if they cannot be read
  12509. // from the child:
  12510. ELEMENT.inheritedProps = {
  12511. fontSize: 1,
  12512. fontStyle: 1,
  12513. opacity: 1
  12514. };
  12515. Ext.override(ELEMENT, {
  12516. /**
  12517. * TODO: Look at this
  12518. */
  12519. // private ==> used by Fx
  12520. adjustWidth : function(width) {
  12521. var me = this,
  12522. isNum = (typeof width == 'number');
  12523. if(isNum && me.autoBoxAdjust && !me.isBorderBox()){
  12524. width -= (me.getBorderWidth("lr") + me.getPadding("lr"));
  12525. }
  12526. return (isNum && width < 0) ? 0 : width;
  12527. },
  12528. // private ==> used by Fx
  12529. adjustHeight : function(height) {
  12530. var me = this,
  12531. isNum = (typeof height == "number");
  12532. if(isNum && me.autoBoxAdjust && !me.isBorderBox()){
  12533. height -= (me.getBorderWidth("tb") + me.getPadding("tb"));
  12534. }
  12535. return (isNum && height < 0) ? 0 : height;
  12536. },
  12537. /**
  12538. * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
  12539. * @param {String/String[]} className The CSS classes to add separated by space, or an array of classes
  12540. * @return {Ext.Element} this
  12541. */
  12542. addCls : function(className){
  12543. var me = this,
  12544. cls = [],
  12545. space = ((me.dom.className.replace(trimRe, '') == '') ? "" : " "),
  12546. i, len, v;
  12547. if (className === undefined) {
  12548. return me;
  12549. }
  12550. // Separate case is for speed
  12551. if (Object.prototype.toString.call(cl