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

https://bitbucket.org/srogerf/javascript · JavaScript · 24770 lines · 12390 code · 2615 blank · 9765 comment · 2993 complexity · 52b43a9b21ab8a7a7a4aca5537b04488 MD5 · raw file

  1. /*
  2. This file is part of Ext JS 4.1
  3. Copyright (c) 2011-2012 Sencha Inc
  4. Contact: http://www.sencha.com/contact
  5. Pre-release code in the Ext repository is intended for development purposes only and will
  6. not always be stable.
  7. Use of pre-release code is permitted with your application at your own risk under standard
  8. Ext license terms. Public redistribution is prohibited.
  9. For early licensing, please contact us at licensing@sencha.com
  10. Build date: 2012-02-21 23:18:31 (3a639ae9dd5443bffbde7bec9922e6fb07a923a8)
  11. */
  12. /**
  13. * @class Ext
  14. * @singleton
  15. */
  16. var Ext = Ext || {};
  17. Ext._startTime = new Date().getTime();
  18. (function() {
  19. var global = this,
  20. objectPrototype = Object.prototype,
  21. toString = objectPrototype.toString,
  22. enumerables = true,
  23. enumerablesTest = { toString: 1 },
  24. emptyFn = function(){},
  25. i;
  26. Ext.global = global;
  27. for (i in enumerablesTest) {
  28. enumerables = null;
  29. }
  30. if (enumerables) {
  31. enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable',
  32. 'toLocaleString', 'toString', 'constructor'];
  33. }
  34. /**
  35. * An array containing extra enumerables for old browsers
  36. * @property {String[]}
  37. */
  38. Ext.enumerables = enumerables;
  39. /**
  40. * Copies all the properties of config to the specified object.
  41. * Note that if recursive merging and cloning without referencing the original objects / arrays is needed, use
  42. * {@link Ext.Object#merge} instead.
  43. * @param {Object} object The receiver of the properties
  44. * @param {Object} config The source of the properties
  45. * @param {Object} defaults A different object that will also be applied for default values
  46. * @return {Object} returns obj
  47. */
  48. Ext.apply = function(object, config, defaults) {
  49. if (defaults) {
  50. Ext.apply(object, defaults);
  51. }
  52. if (object && config && typeof config === 'object') {
  53. var i, j, k;
  54. for (i in config) {
  55. object[i] = config[i];
  56. }
  57. if (enumerables) {
  58. for (j = enumerables.length; j--;) {
  59. k = enumerables[j];
  60. if (config.hasOwnProperty(k)) {
  61. object[k] = config[k];
  62. }
  63. }
  64. }
  65. }
  66. return object;
  67. };
  68. Ext.buildSettings = Ext.apply({
  69. baseCSSPrefix: 'x-',
  70. scopeResetCSS: false
  71. }, Ext.buildSettings || {});
  72. Ext.apply(Ext, {
  73. /**
  74. * @property {String} [name='Ext']
  75. * <p>The name of the property in the global namespace (The <code>window</code> in browser environments) which refers to the current instance of Ext.</p>
  76. * <p>This is usually <code>"Ext"</code>, but if a sandboxed build of ExtJS is being used, this will be an alternative name.</p>
  77. * <p>If code is being generated for use by <code>eval</code> or to create a <code>new Function</code>, and the global instance
  78. * of Ext must be referenced, this is the name that should be built into the code.</p>
  79. */
  80. name: Ext.sandboxName || 'Ext',
  81. /**
  82. * A reusable empty function
  83. */
  84. emptyFn: emptyFn,
  85. /**
  86. * A zero length string which will pass a truth test. Useful for passing to methods
  87. * which use a truth test to reject <i>falsy</i> values where a string value must be cleared.
  88. */
  89. emptyString: new String(),
  90. baseCSSPrefix: Ext.buildSettings.baseCSSPrefix,
  91. /**
  92. * Copies all the properties of config to object if they don't already exist.
  93. * @param {Object} object The receiver of the properties
  94. * @param {Object} config The source of the properties
  95. * @return {Object} returns obj
  96. */
  97. applyIf: function(object, config) {
  98. var property;
  99. if (object) {
  100. for (property in config) {
  101. if (object[property] === undefined) {
  102. object[property] = config[property];
  103. }
  104. }
  105. }
  106. return object;
  107. },
  108. /**
  109. * Iterates either an array or an object. This method delegates to
  110. * {@link Ext.Array#each Ext.Array.each} if the given value is iterable, and {@link Ext.Object#each Ext.Object.each} otherwise.
  111. *
  112. * @param {Object/Array} object The object or array to be iterated.
  113. * @param {Function} fn The function to be called for each iteration. See and {@link Ext.Array#each Ext.Array.each} and
  114. * {@link Ext.Object#each Ext.Object.each} for detailed lists of arguments passed to this function depending on the given object
  115. * type that is being iterated.
  116. * @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed.
  117. * Defaults to the object being iterated itself.
  118. * @markdown
  119. */
  120. iterate: function(object, fn, scope) {
  121. if (Ext.isEmpty(object)) {
  122. return;
  123. }
  124. if (scope === undefined) {
  125. scope = object;
  126. }
  127. if (Ext.isIterable(object)) {
  128. Ext.Array.each.call(Ext.Array, object, fn, scope);
  129. }
  130. else {
  131. Ext.Object.each.call(Ext.Object, object, fn, scope);
  132. }
  133. }
  134. });
  135. Ext.apply(Ext, {
  136. /**
  137. * This method deprecated. Use {@link Ext#define Ext.define} instead.
  138. * @method
  139. * @param {Function} superclass
  140. * @param {Object} overrides
  141. * @return {Function} The subclass constructor from the <tt>overrides</tt> parameter, or a generated one if not provided.
  142. * @deprecated 4.0.0 Use {@link Ext#define Ext.define} instead
  143. */
  144. extend: function() {
  145. // inline overrides
  146. var objectConstructor = objectPrototype.constructor,
  147. inlineOverrides = function(o) {
  148. for (var m in o) {
  149. if (!o.hasOwnProperty(m)) {
  150. continue;
  151. }
  152. this[m] = o[m];
  153. }
  154. };
  155. return function(subclass, superclass, overrides) {
  156. // First we check if the user passed in just the superClass with overrides
  157. if (Ext.isObject(superclass)) {
  158. overrides = superclass;
  159. superclass = subclass;
  160. subclass = overrides.constructor !== objectConstructor ? overrides.constructor : function() {
  161. superclass.apply(this, arguments);
  162. };
  163. }
  164. // We create a new temporary class
  165. var F = function() {},
  166. subclassProto, superclassProto = superclass.prototype;
  167. F.prototype = superclassProto;
  168. subclassProto = subclass.prototype = new F();
  169. subclassProto.constructor = subclass;
  170. subclass.superclass = superclassProto;
  171. if (superclassProto.constructor === objectConstructor) {
  172. superclassProto.constructor = superclass;
  173. }
  174. subclass.override = function(overrides) {
  175. Ext.override(subclass, overrides);
  176. };
  177. subclassProto.override = inlineOverrides;
  178. subclassProto.proto = subclassProto;
  179. subclass.override(overrides);
  180. subclass.extend = function(o) {
  181. return Ext.extend(subclass, o);
  182. };
  183. return subclass;
  184. };
  185. }(),
  186. /**
  187. * Proxy to {@link Ext.Base#override}. Please refer {@link Ext.Base#override} for further details.
  188. *
  189. * @param {Object} cls The class to override
  190. * @param {Object} overrides The properties to add to origClass. This should be specified as an object literal
  191. * containing one or more properties.
  192. * @method override
  193. * @markdown
  194. * @deprecated 4.1.0 Use {@link Ext#define Ext.define} instead
  195. */
  196. override: function(cls, overrides) {
  197. if (cls.$isClass) {
  198. return cls.override(overrides);
  199. }
  200. else {
  201. Ext.apply(cls.prototype, overrides);
  202. }
  203. }
  204. });
  205. // A full set of static methods to do type checking
  206. Ext.apply(Ext, {
  207. /**
  208. * Returns the given value itself if it's not empty, as described in {@link Ext#isEmpty}; returns the default
  209. * value (second argument) otherwise.
  210. *
  211. * @param {Object} value The value to test
  212. * @param {Object} defaultValue The value to return if the original value is empty
  213. * @param {Boolean} allowBlank (optional) true to allow zero length strings to qualify as non-empty (defaults to false)
  214. * @return {Object} value, if non-empty, else defaultValue
  215. */
  216. valueFrom: function(value, defaultValue, allowBlank){
  217. return Ext.isEmpty(value, allowBlank) ? defaultValue : value;
  218. },
  219. /**
  220. * Returns the type of the given variable in string format. List of possible values are:
  221. *
  222. * - `undefined`: If the given value is `undefined`
  223. * - `null`: If the given value is `null`
  224. * - `string`: If the given value is a string
  225. * - `number`: If the given value is a number
  226. * - `boolean`: If the given value is a boolean value
  227. * - `date`: If the given value is a `Date` object
  228. * - `function`: If the given value is a function reference
  229. * - `object`: If the given value is an object
  230. * - `array`: If the given value is an array
  231. * - `regexp`: If the given value is a regular expression
  232. * - `element`: If the given value is a DOM Element
  233. * - `textnode`: If the given value is a DOM text node and contains something other than whitespace
  234. * - `whitespace`: If the given value is a DOM text node and contains only whitespace
  235. *
  236. * @param {Object} value
  237. * @return {String}
  238. * @markdown
  239. */
  240. typeOf: function(value) {
  241. if (value === null) {
  242. return 'null';
  243. }
  244. var type = typeof value;
  245. if (type === 'undefined' || type === 'string' || type === 'number' || type === 'boolean') {
  246. return type;
  247. }
  248. var typeToString = toString.call(value);
  249. switch(typeToString) {
  250. case '[object Array]':
  251. return 'array';
  252. case '[object Date]':
  253. return 'date';
  254. case '[object Boolean]':
  255. return 'boolean';
  256. case '[object Number]':
  257. return 'number';
  258. case '[object RegExp]':
  259. return 'regexp';
  260. }
  261. if (type === 'function') {
  262. return 'function';
  263. }
  264. if (type === 'object') {
  265. if (value.nodeType !== undefined) {
  266. if (value.nodeType === 3) {
  267. return (/\S/).test(value.nodeValue) ? 'textnode' : 'whitespace';
  268. }
  269. else {
  270. return 'element';
  271. }
  272. }
  273. return 'object';
  274. }
  275. },
  276. /**
  277. * Returns true if the passed value is empty, false otherwise. The value is deemed to be empty if it is either:
  278. *
  279. * - `null`
  280. * - `undefined`
  281. * - a zero-length array
  282. * - a zero-length string (Unless the `allowEmptyString` parameter is set to `true`)
  283. *
  284. * @param {Object} value The value to test
  285. * @param {Boolean} allowEmptyString (optional) true to allow empty strings (defaults to false)
  286. * @return {Boolean}
  287. * @markdown
  288. */
  289. isEmpty: function(value, allowEmptyString) {
  290. return (value === null) || (value === undefined) || (!allowEmptyString ? value === '' : false) || (Ext.isArray(value) && value.length === 0);
  291. },
  292. /**
  293. * Returns true if the passed value is a JavaScript Array, false otherwise.
  294. *
  295. * @param {Object} target The target to test
  296. * @return {Boolean}
  297. * @method
  298. */
  299. isArray: ('isArray' in Array) ? Array.isArray : function(value) {
  300. return toString.call(value) === '[object Array]';
  301. },
  302. /**
  303. * Returns true if the passed value is a JavaScript Date object, false otherwise.
  304. * @param {Object} object The object to test
  305. * @return {Boolean}
  306. */
  307. isDate: function(value) {
  308. return toString.call(value) === '[object Date]';
  309. },
  310. /**
  311. * Returns true if the passed value is a JavaScript Object, false otherwise.
  312. * @param {Object} value The value to test
  313. * @return {Boolean}
  314. * @method
  315. */
  316. isObject: (toString.call(null) === '[object Object]') ?
  317. function(value) {
  318. // check ownerDocument here as well to exclude DOM nodes
  319. return value !== null && value !== undefined && toString.call(value) === '[object Object]' && value.ownerDocument === undefined;
  320. } :
  321. function(value) {
  322. return toString.call(value) === '[object Object]';
  323. },
  324. /**
  325. * @private
  326. */
  327. isSimpleObject: function(value) {
  328. return value instanceof Object && value.constructor === Object;
  329. },
  330. /**
  331. * Returns true if the passed value is a JavaScript 'primitive', a string, number or boolean.
  332. * @param {Object} value The value to test
  333. * @return {Boolean}
  334. */
  335. isPrimitive: function(value) {
  336. var type = typeof value;
  337. return type === 'string' || type === 'number' || type === 'boolean';
  338. },
  339. /**
  340. * Returns true if the passed value is a JavaScript Function, false otherwise.
  341. * @param {Object} value The value to test
  342. * @return {Boolean}
  343. * @method
  344. */
  345. isFunction:
  346. // Safari 3.x and 4.x returns 'function' for typeof <NodeList>, hence we need to fall back to using
  347. // Object.prototype.toString (slower)
  348. (typeof document !== 'undefined' && typeof document.getElementsByTagName('body') === 'function') ? function(value) {
  349. return toString.call(value) === '[object Function]';
  350. } : function(value) {
  351. return typeof value === 'function';
  352. },
  353. /**
  354. * Returns true if the passed value is a number. Returns false for non-finite numbers.
  355. * @param {Object} value The value to test
  356. * @return {Boolean}
  357. */
  358. isNumber: function(value) {
  359. return typeof value === 'number' && isFinite(value);
  360. },
  361. /**
  362. * Validates that a value is numeric.
  363. * @param {Object} value Examples: 1, '1', '2.34'
  364. * @return {Boolean} True if numeric, false otherwise
  365. */
  366. isNumeric: function(value) {
  367. return !isNaN(parseFloat(value)) && isFinite(value);
  368. },
  369. /**
  370. * Returns true if the passed value is a string.
  371. * @param {Object} value The value to test
  372. * @return {Boolean}
  373. */
  374. isString: function(value) {
  375. return typeof value === 'string';
  376. },
  377. /**
  378. * Returns true if the passed value is a boolean.
  379. *
  380. * @param {Object} value The value to test
  381. * @return {Boolean}
  382. */
  383. isBoolean: function(value) {
  384. return typeof value === 'boolean';
  385. },
  386. /**
  387. * Returns true if the passed value is an HTMLElement
  388. * @param {Object} value The value to test
  389. * @return {Boolean}
  390. */
  391. isElement: function(value) {
  392. return value ? value.nodeType === 1 : false;
  393. },
  394. /**
  395. * Returns true if the passed value is a TextNode
  396. * @param {Object} value The value to test
  397. * @return {Boolean}
  398. */
  399. isTextNode: function(value) {
  400. return value ? value.nodeName === "#text" : false;
  401. },
  402. /**
  403. * Returns true if the passed value is defined.
  404. * @param {Object} value The value to test
  405. * @return {Boolean}
  406. */
  407. isDefined: function(value) {
  408. return typeof value !== 'undefined';
  409. },
  410. /**
  411. * Returns true if the passed value is iterable, false otherwise
  412. * @param {Object} value The value to test
  413. * @return {Boolean}
  414. */
  415. isIterable: function(value) {
  416. var type = typeof value,
  417. checkLength = false;
  418. if (value && type != 'string') {
  419. // Functions have a length property, so we need to filter them out
  420. if (type == 'function') {
  421. // In Safari, NodeList/HTMLCollection both return "function" when using typeof, so we need
  422. // to explicitly check them here.
  423. if (Ext.isSafari) {
  424. checkLength = value instanceof NodeList || value instanceof HTMLCollection;
  425. }
  426. } else {
  427. checkLength = true;
  428. }
  429. }
  430. return checkLength ? value.length !== undefined : false;
  431. }
  432. });
  433. Ext.apply(Ext, {
  434. /**
  435. * Clone almost any type of variable including array, object, DOM nodes and Date without keeping the old reference
  436. * @param {Object} item The variable to clone
  437. * @return {Object} clone
  438. */
  439. clone: function(item) {
  440. if (item === null || item === undefined) {
  441. return item;
  442. }
  443. // DOM nodes
  444. // TODO proxy this to Ext.Element.clone to handle automatic id attribute changing
  445. // recursively
  446. if (item.nodeType && item.cloneNode) {
  447. return item.cloneNode(true);
  448. }
  449. var type = toString.call(item);
  450. // Date
  451. if (type === '[object Date]') {
  452. return new Date(item.getTime());
  453. }
  454. var i, j, k, clone, key;
  455. // Array
  456. if (type === '[object Array]') {
  457. i = item.length;
  458. clone = [];
  459. while (i--) {
  460. clone[i] = Ext.clone(item[i]);
  461. }
  462. }
  463. // Object
  464. else if (type === '[object Object]' && item.constructor === Object) {
  465. clone = {};
  466. for (key in item) {
  467. clone[key] = Ext.clone(item[key]);
  468. }
  469. if (enumerables) {
  470. for (j = enumerables.length; j--;) {
  471. k = enumerables[j];
  472. clone[k] = item[k];
  473. }
  474. }
  475. }
  476. return clone || item;
  477. },
  478. /**
  479. * @private
  480. * Generate a unique reference of Ext in the global scope, useful for sandboxing
  481. */
  482. getUniqueGlobalNamespace: function() {
  483. var uniqueGlobalNamespace = this.uniqueGlobalNamespace;
  484. if (uniqueGlobalNamespace === undefined) {
  485. var i = 0;
  486. do {
  487. uniqueGlobalNamespace = 'ExtBox' + (++i);
  488. } while (Ext.global[uniqueGlobalNamespace] !== undefined);
  489. Ext.global[uniqueGlobalNamespace] = Ext;
  490. this.uniqueGlobalNamespace = uniqueGlobalNamespace;
  491. }
  492. return uniqueGlobalNamespace;
  493. },
  494. /**
  495. * @private
  496. */
  497. functionFactoryCache: {},
  498. cacheableFunctionFactory: function() {
  499. var me = this,
  500. args = Array.prototype.slice.call(arguments),
  501. cache = me.functionFactoryCache,
  502. idx, fn, ln;
  503. if (Ext.isSandboxed) {
  504. ln = args.length;
  505. if (ln > 0) {
  506. ln--;
  507. args[ln] = 'var Ext=window.' + Ext.name + ';' + args[ln];
  508. }
  509. }
  510. idx = args.join('');
  511. fn = cache[idx];
  512. if (!fn) {
  513. fn = Function.prototype.constructor.apply(Function.prototype, args);
  514. cache[idx] = fn;
  515. }
  516. return fn;
  517. },
  518. functionFactory: function() {
  519. var me = this,
  520. args = Array.prototype.slice.call(arguments),
  521. ln;
  522. if (Ext.isSandboxed) {
  523. ln = args.length;
  524. if (ln > 0) {
  525. ln--;
  526. args[ln] = 'var Ext=window.' + Ext.name + ';' + args[ln];
  527. }
  528. }
  529. return Function.prototype.constructor.apply(Function.prototype, args);
  530. },
  531. /**
  532. * @property
  533. * @private
  534. */
  535. globalEval: ('execScript' in global) ? function(code) {
  536. global.execScript(code)
  537. } : function(code) {
  538. (function(){
  539. eval(code);
  540. })();
  541. },
  542. /**
  543. * @private
  544. * @property
  545. */
  546. Logger: {
  547. verbose: emptyFn,
  548. log: emptyFn,
  549. info: emptyFn,
  550. warn: emptyFn,
  551. error: function(message) {
  552. throw new Error(message);
  553. },
  554. deprecate: emptyFn
  555. }
  556. });
  557. /**
  558. * Old alias to {@link Ext#typeOf}
  559. * @deprecated 4.0.0 Use {@link Ext#typeOf} instead
  560. * @method
  561. * @inheritdoc Ext#typeOf
  562. */
  563. Ext.type = Ext.typeOf;
  564. })();
  565. /**
  566. * @author Jacky Nguyen <jacky@sencha.com>
  567. * @docauthor Jacky Nguyen <jacky@sencha.com>
  568. * @class Ext.Version
  569. *
  570. * A utility class that wrap around a string version number and provide convenient
  571. * method to perform comparison. See also: {@link Ext.Version#compare compare}. Example:
  572. var version = new Ext.Version('1.0.2beta');
  573. console.log("Version is " + version); // Version is 1.0.2beta
  574. console.log(version.getMajor()); // 1
  575. console.log(version.getMinor()); // 0
  576. console.log(version.getPatch()); // 2
  577. console.log(version.getBuild()); // 0
  578. console.log(version.getRelease()); // beta
  579. console.log(version.isGreaterThan('1.0.1')); // True
  580. console.log(version.isGreaterThan('1.0.2alpha')); // True
  581. console.log(version.isGreaterThan('1.0.2RC')); // False
  582. console.log(version.isGreaterThan('1.0.2')); // False
  583. console.log(version.isLessThan('1.0.2')); // True
  584. console.log(version.match(1.0)); // True
  585. console.log(version.match('1.0.2')); // True
  586. * @markdown
  587. */
  588. (function() {
  589. // Current core version
  590. var version = '4.1.0beta', Version;
  591. Ext.Version = Version = Ext.extend(Object, {
  592. /**
  593. * @param {String/Number} version The version number in the follow standard format: major[.minor[.patch[.build[release]]]]
  594. * Examples: 1.0 or 1.2.3beta or 1.2.3.4RC
  595. * @return {Ext.Version} this
  596. */
  597. constructor: function(version) {
  598. var parts, releaseStartIndex;
  599. if (version instanceof Version) {
  600. return version;
  601. }
  602. this.version = this.shortVersion = String(version).toLowerCase().replace(/_/g, '.').replace(/[\-+]/g, '');
  603. releaseStartIndex = this.version.search(/([^\d\.])/);
  604. if (releaseStartIndex !== -1) {
  605. this.release = this.version.substr(releaseStartIndex, version.length);
  606. this.shortVersion = this.version.substr(0, releaseStartIndex);
  607. }
  608. this.shortVersion = this.shortVersion.replace(/[^\d]/g, '');
  609. parts = this.version.split('.');
  610. this.major = parseInt(parts.shift() || 0, 10);
  611. this.minor = parseInt(parts.shift() || 0, 10);
  612. this.patch = parseInt(parts.shift() || 0, 10);
  613. this.build = parseInt(parts.shift() || 0, 10);
  614. return this;
  615. },
  616. /**
  617. * Override the native toString method
  618. * @private
  619. * @return {String} version
  620. */
  621. toString: function() {
  622. return this.version;
  623. },
  624. /**
  625. * Override the native valueOf method
  626. * @private
  627. * @return {String} version
  628. */
  629. valueOf: function() {
  630. return this.version;
  631. },
  632. /**
  633. * Returns the major component value
  634. * @return {Number} major
  635. */
  636. getMajor: function() {
  637. return this.major || 0;
  638. },
  639. /**
  640. * Returns the minor component value
  641. * @return {Number} minor
  642. */
  643. getMinor: function() {
  644. return this.minor || 0;
  645. },
  646. /**
  647. * Returns the patch component value
  648. * @return {Number} patch
  649. */
  650. getPatch: function() {
  651. return this.patch || 0;
  652. },
  653. /**
  654. * Returns the build component value
  655. * @return {Number} build
  656. */
  657. getBuild: function() {
  658. return this.build || 0;
  659. },
  660. /**
  661. * Returns the release component value
  662. * @return {Number} release
  663. */
  664. getRelease: function() {
  665. return this.release || '';
  666. },
  667. /**
  668. * Returns whether this version if greater than the supplied argument
  669. * @param {String/Number} target The version to compare with
  670. * @return {Boolean} True if this version if greater than the target, false otherwise
  671. */
  672. isGreaterThan: function(target) {
  673. return Version.compare(this.version, target) === 1;
  674. },
  675. /**
  676. * Returns whether this version if greater than or equal to the supplied argument
  677. * @param {String/Number} target The version to compare with
  678. * @return {Boolean} True if this version if greater than or equal to the target, false otherwise
  679. */
  680. isGreaterThanOrEqual: function(target) {
  681. return Version.compare(this.version, target) >= 0;
  682. },
  683. /**
  684. * Returns whether this version if smaller than the supplied argument
  685. * @param {String/Number} target The version to compare with
  686. * @return {Boolean} True if this version if smaller than the target, false otherwise
  687. */
  688. isLessThan: function(target) {
  689. return Version.compare(this.version, target) === -1;
  690. },
  691. /**
  692. * Returns whether this version if less than or equal to the supplied argument
  693. * @param {String/Number} target The version to compare with
  694. * @return {Boolean} True if this version if less than or equal to the target, false otherwise
  695. */
  696. isLessThanOrEqual: function(target) {
  697. return Version.compare(this.version, target) <= 0;
  698. },
  699. /**
  700. * Returns whether this version equals to the supplied argument
  701. * @param {String/Number} target The version to compare with
  702. * @return {Boolean} True if this version equals to the target, false otherwise
  703. */
  704. equals: function(target) {
  705. return Version.compare(this.version, target) === 0;
  706. },
  707. /**
  708. * Returns whether this version matches the supplied argument. Example:
  709. * <pre><code>
  710. * var version = new Ext.Version('1.0.2beta');
  711. * console.log(version.match(1)); // True
  712. * console.log(version.match(1.0)); // True
  713. * console.log(version.match('1.0.2')); // True
  714. * console.log(version.match('1.0.2RC')); // False
  715. * </code></pre>
  716. * @param {String/Number} target The version to compare with
  717. * @return {Boolean} True if this version matches the target, false otherwise
  718. */
  719. match: function(target) {
  720. target = String(target);
  721. return this.version.substr(0, target.length) === target;
  722. },
  723. /**
  724. * Returns this format: [major, minor, patch, build, release]. Useful for comparison
  725. * @return {Number[]}
  726. */
  727. toArray: function() {
  728. return [this.getMajor(), this.getMinor(), this.getPatch(), this.getBuild(), this.getRelease()];
  729. },
  730. /**
  731. * Returns shortVersion version without dots and release
  732. * @return {String}
  733. */
  734. getShortVersion: function() {
  735. return this.shortVersion;
  736. },
  737. /**
  738. * Convenient alias to {@link Ext.Version#isGreaterThan isGreaterThan}
  739. * @param {String/Number} target
  740. * @return {Boolean}
  741. */
  742. gt: function() {
  743. return this.isGreaterThan.apply(this, arguments);
  744. },
  745. /**
  746. * Convenient alias to {@link Ext.Version#isLessThan isLessThan}
  747. * @param {String/Number} target
  748. * @return {Boolean}
  749. */
  750. lt: function() {
  751. return this.isLessThan.apply(this, arguments);
  752. },
  753. /**
  754. * Convenient alias to {@link Ext.Version#isGreaterThanOrEqual isGreaterThanOrEqual}
  755. * @param {String/Number} target
  756. * @return {Boolean}
  757. */
  758. gtEq: function() {
  759. return this.isGreaterThanOrEqual.apply(this, arguments);
  760. },
  761. /**
  762. * Convenient alias to {@link Ext.Version#isLessThanOrEqual isLessThanOrEqual}
  763. * @param {String/Number} target
  764. * @return {Boolean}
  765. */
  766. ltEq: function() {
  767. return this.isLessThanOrEqual.apply(this, arguments);
  768. }
  769. });
  770. Ext.apply(Version, {
  771. // @private
  772. releaseValueMap: {
  773. 'dev': -6,
  774. 'alpha': -5,
  775. 'a': -5,
  776. 'beta': -4,
  777. 'b': -4,
  778. 'rc': -3,
  779. '#': -2,
  780. 'p': -1,
  781. 'pl': -1
  782. },
  783. /**
  784. * Converts a version component to a comparable value
  785. *
  786. * @static
  787. * @param {Object} value The value to convert
  788. * @return {Object}
  789. */
  790. getComponentValue: function(value) {
  791. return !value ? 0 : (isNaN(value) ? this.releaseValueMap[value] || value : parseInt(value, 10));
  792. },
  793. /**
  794. * Compare 2 specified versions, starting from left to right. If a part contains special version strings,
  795. * they are handled in the following order:
  796. * 'dev' < 'alpha' = 'a' < 'beta' = 'b' < 'RC' = 'rc' < '#' < 'pl' = 'p' < 'anything else'
  797. *
  798. * @static
  799. * @param {String} current The current version to compare to
  800. * @param {String} target The target version to compare to
  801. * @return {Number} Returns -1 if the current version is smaller than the target version, 1 if greater, and 0 if they're equivalent
  802. */
  803. compare: function(current, target) {
  804. var currentValue, targetValue, i;
  805. current = new Version(current).toArray();
  806. target = new Version(target).toArray();
  807. for (i = 0; i < Math.max(current.length, target.length); i++) {
  808. currentValue = this.getComponentValue(current[i]);
  809. targetValue = this.getComponentValue(target[i]);
  810. if (currentValue < targetValue) {
  811. return -1;
  812. } else if (currentValue > targetValue) {
  813. return 1;
  814. }
  815. }
  816. return 0;
  817. }
  818. });
  819. Ext.apply(Ext, {
  820. /**
  821. * @private
  822. */
  823. versions: {},
  824. /**
  825. * @private
  826. */
  827. lastRegisteredVersion: null,
  828. /**
  829. * Set version number for the given package name.
  830. *
  831. * @param {String} packageName The package name, for example: 'core', 'touch', 'extjs'
  832. * @param {String/Ext.Version} version The version, for example: '1.2.3alpha', '2.4.0-dev'
  833. * @return {Ext}
  834. */
  835. setVersion: function(packageName, version) {
  836. Ext.versions[packageName] = new Version(version);
  837. Ext.lastRegisteredVersion = Ext.versions[packageName];
  838. return this;
  839. },
  840. /**
  841. * Get the version number of the supplied package name; will return the last registered version
  842. * (last Ext.setVersion call) if there's no package name given.
  843. *
  844. * @param {String} packageName (Optional) The package name, for example: 'core', 'touch', 'extjs'
  845. * @return {Ext.Version} The version
  846. */
  847. getVersion: function(packageName) {
  848. if (packageName === undefined) {
  849. return Ext.lastRegisteredVersion;
  850. }
  851. return Ext.versions[packageName];
  852. },
  853. /**
  854. * Create a closure for deprecated code.
  855. *
  856. // This means Ext.oldMethod is only supported in 4.0.0beta and older.
  857. // If Ext.getVersion('extjs') returns a version that is later than '4.0.0beta', for example '4.0.0RC',
  858. // the closure will not be invoked
  859. Ext.deprecate('extjs', '4.0.0beta', function() {
  860. Ext.oldMethod = Ext.newMethod;
  861. ...
  862. });
  863. * @param {String} packageName The package name
  864. * @param {String} since The last version before it's deprecated
  865. * @param {Function} closure The callback function to be executed with the specified version is less than the current version
  866. * @param {Object} scope The execution scope (<tt>this</tt>) if the closure
  867. * @markdown
  868. */
  869. deprecate: function(packageName, since, closure, scope) {
  870. if (Version.compare(Ext.getVersion(packageName), since) < 1) {
  871. closure.call(scope);
  872. }
  873. }
  874. }); // End Versioning
  875. Ext.setVersion('core', version);
  876. })();
  877. /**
  878. * @class Ext.String
  879. *
  880. * A collection of useful static methods to deal with strings
  881. * @singleton
  882. */
  883. Ext.String = (function() {
  884. var trimRegex = /^[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+|[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+$/g,
  885. escapeRe = /('|\\)/g,
  886. formatRe = /\{(\d+)\}/g,
  887. escapeRegexRe = /([-.*+?^${}()|[\]\/\\])/g,
  888. basicTrimRe = /^\s+|\s+$/g,
  889. whitespaceRe = /\s+/,
  890. varReplace = /(^[^a-z]*|[^\w])/gi,
  891. charToEntity = {
  892. '&': '&amp;',
  893. '>': '&gt;',
  894. '<': '&lt;',
  895. '"': '&quot;'
  896. },
  897. entityToChar = {
  898. '&amp;': '&',
  899. '&gt;': '>',
  900. '&lt;': '<',
  901. '&quot;': '"'
  902. },
  903. keys = [],
  904. key,
  905. charToEntityRegex,
  906. entityToCharRegex,
  907. htmlEncodeReplaceFn = function(match, capture) {
  908. return charToEntity[capture];
  909. },
  910. htmlEncode = function(value) {
  911. return (!value) ? value : String(value).replace(charToEntityRegex, htmlEncodeReplaceFn);
  912. },
  913. htmlDecodeReplaceFn = function(match, capture) {
  914. return (capture in entityToChar) ? entityToChar[capture] : String.fromCharCode(parseInt(capture.substr(2), 10));
  915. },
  916. htmlDecode = function(value) {
  917. return (!value) ? value : String(value).replace(entityToCharRegex, htmlDecodeReplaceFn);
  918. };
  919. // Compile RexExps for HTML encode and decode functions
  920. for (key in charToEntity) {
  921. keys.push(key);
  922. }
  923. charToEntityRegex = new RegExp('(' + keys.join('|') + ')', 'g');
  924. keys = [];
  925. for (key in entityToChar) {
  926. keys.push(key);
  927. }
  928. entityToCharRegex = new RegExp('(' + keys.join('|') + '|&#[0-9]{1,5};' + ')', 'g');
  929. return {
  930. /**
  931. * Converts a string of characters into a legal, parseable Javascript `var` name as long as the passed
  932. * string contains at least one alphabetic character. Non alphanumeric characters, and *leading* non alphabetic
  933. * characters will be removed.
  934. * @param {String} s A string to be converted into a `var` name.
  935. * @return {String} A legal Javascript `var` name.
  936. */
  937. createVarName: function(s) {
  938. return s.replace(varReplace, '');
  939. },
  940. /**
  941. * Convert certain characters (&, <, >, and ") to their HTML character equivalents for literal display in web pages.
  942. * @param {String} value The string to encode
  943. * @return {String} The encoded text
  944. * @method
  945. */
  946. htmlEncode: htmlEncode,
  947. /**
  948. * Convert certain characters (&, <, >, and ") from their HTML character equivalents.
  949. * @param {String} value The string to decode
  950. * @return {String} The decoded text
  951. * @method
  952. */
  953. htmlDecode: htmlDecode,
  954. /**
  955. * Appends content to the query string of a URL, handling logic for whether to place
  956. * a question mark or ampersand.
  957. * @param {String} url The URL to append to.
  958. * @param {String} string The content to append to the URL.
  959. * @return {String} The resulting URL
  960. */
  961. urlAppend : function(url, string) {
  962. if (!Ext.isEmpty(string)) {
  963. return url + (url.indexOf('?') === -1 ? '?' : '&') + string;
  964. }
  965. return url;
  966. },
  967. /**
  968. * Trims whitespace from either end of a string, leaving spaces within the string intact. Example:
  969. * @example
  970. var s = ' foo bar ';
  971. alert('-' + s + '-'); //alerts "- foo bar -"
  972. alert('-' + Ext.String.trim(s) + '-'); //alerts "-foo bar-"
  973. * @param {String} string The string to escape
  974. * @return {String} The trimmed string
  975. */
  976. trim: function(string) {
  977. return string.replace(trimRegex, "");
  978. },
  979. /**
  980. * Capitalize the given string
  981. * @param {String} string
  982. * @return {String}
  983. */
  984. capitalize: function(string) {
  985. return string.charAt(0).toUpperCase() + string.substr(1);
  986. },
  987. /**
  988. * Uncapitalize the given string
  989. * @param {String} string
  990. * @return {String}
  991. */
  992. uncapitalize: function(string) {
  993. return string.charAt(0).toLowerCase() + string.substr(1);
  994. },
  995. /**
  996. * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
  997. * @param {String} value The string to truncate
  998. * @param {Number} length The maximum length to allow before truncating
  999. * @param {Boolean} word True to try to find a common word break
  1000. * @return {String} The converted text
  1001. */
  1002. ellipsis: function(value, len, word) {
  1003. if (value && value.length > len) {
  1004. if (word) {
  1005. var vs = value.substr(0, len - 2),
  1006. index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?'));
  1007. if (index !== -1 && index >= (len - 15)) {
  1008. return vs.substr(0, index) + "...";
  1009. }
  1010. }
  1011. return value.substr(0, len - 3) + "...";
  1012. }
  1013. return value;
  1014. },
  1015. /**
  1016. * Escapes the passed string for use in a regular expression
  1017. * @param {String} string
  1018. * @return {String}
  1019. */
  1020. escapeRegex: function(string) {
  1021. return string.replace(escapeRegexRe, "\\$1");
  1022. },
  1023. /**
  1024. * Escapes the passed string for ' and \
  1025. * @param {String} string The string to escape
  1026. * @return {String} The escaped string
  1027. */
  1028. escape: function(string) {
  1029. return string.replace(escapeRe, "\\$1");
  1030. },
  1031. /**
  1032. * Utility function that allows you to easily switch a string between two alternating values. The passed value
  1033. * is compared to the current string, and if they are equal, the other value that was passed in is returned. If
  1034. * they are already different, the first value passed in is returned. Note that this method returns the new value
  1035. * but does not change the current string.
  1036. * <pre><code>
  1037. // alternate sort directions
  1038. sort = Ext.String.toggle(sort, 'ASC', 'DESC');
  1039. // instead of conditional logic:
  1040. sort = (sort == 'ASC' ? 'DESC' : 'ASC');
  1041. </code></pre>
  1042. * @param {String} string The current string
  1043. * @param {String} value The value to compare to the current string
  1044. * @param {String} other The new value to use if the string already equals the first value passed in
  1045. * @return {String} The new value
  1046. */
  1047. toggle: function(string, value, other) {
  1048. return string === value ? other : value;
  1049. },
  1050. /**
  1051. * Pads the left side of a string with a specified character. This is especially useful
  1052. * for normalizing number and date strings. Example usage:
  1053. *
  1054. * <pre><code>
  1055. var s = Ext.String.leftPad('123', 5, '0');
  1056. // s now contains the string: '00123'
  1057. </code></pre>
  1058. * @param {String} string The original string
  1059. * @param {Number} size The total length of the output string
  1060. * @param {String} character (optional) The character with which to pad the original string (defaults to empty string " ")
  1061. * @return {String} The padded string
  1062. */
  1063. leftPad: function(string, size, character) {
  1064. var result = String(string);
  1065. character = character || " ";
  1066. while (result.length < size) {
  1067. result = character + result;
  1068. }
  1069. return result;
  1070. },
  1071. /**
  1072. * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
  1073. * token must be unique, and must increment in the format {0}, {1}, etc. Example usage:
  1074. * <pre><code>
  1075. var cls = 'my-class', text = 'Some text';
  1076. var s = Ext.String.format('&lt;div class="{0}">{1}&lt;/div>', cls, text);
  1077. // s now contains the string: '&lt;div class="my-class">Some text&lt;/div>'
  1078. </code></pre>
  1079. * @param {String} string The tokenized string to be formatted
  1080. * @param {String} value1 The value to replace token {0}
  1081. * @param {String} value2 Etc...
  1082. * @return {String} The formatted string
  1083. */
  1084. format: function(format) {
  1085. var args = Ext.Array.toArray(arguments, 1);
  1086. return format.replace(formatRe, function(m, i) {
  1087. return args[i];
  1088. });
  1089. },
  1090. /**
  1091. * Returns a string with a specified number of repititions a given string pattern.
  1092. * The pattern be separated by a different string.
  1093. *
  1094. * var s = Ext.String.repeat('---', 4); // = '------------'
  1095. * var t = Ext.String.repeat('--', 3, '/'); // = '--/--/--'
  1096. *
  1097. * @param {String} pattern The pattern to repeat.
  1098. * @param {Number} count The number of times to repeat the pattern (may be 0).
  1099. * @param {String} sep An option string to separate each pattern.
  1100. */
  1101. repeat: function(pattern, count, sep) {
  1102. for (var buf = [], i = count; i--; ) {
  1103. buf.push(pattern);
  1104. }
  1105. return buf.join(sep || '');
  1106. },
  1107. /**
  1108. * Splits a string of space separated words into an array, trimming as needed. If the
  1109. * words are already an array, it is returned.
  1110. *
  1111. * @param {String/Array} words
  1112. */
  1113. splitWords: function (words) {
  1114. if (words && typeof words == 'string') {
  1115. return words.replace(basicTrimRe, '').split(whitespaceRe);
  1116. }
  1117. return words || [];
  1118. }
  1119. };
  1120. })();
  1121. /**
  1122. * Old alias to {@link Ext.String#htmlEncode}
  1123. * @deprecated Use {@link Ext.String#htmlEncode} instead
  1124. * @method
  1125. * @member Ext
  1126. * @inheritdoc Ext.String#htmlEncode
  1127. */
  1128. Ext.htmlEncode = Ext.String.htmlEncode;
  1129. /**
  1130. * Old alias to {@link Ext.String#htmlDecode}
  1131. * @deprecated Use {@link Ext.String#htmlDecode} instead
  1132. * @method
  1133. * @member Ext
  1134. * @inheritdoc Ext.String#htmlDecode
  1135. */
  1136. Ext.htmlDecode = Ext.String.htmlDecode;
  1137. /**
  1138. * Old alias to {@link Ext.String#urlAppend}
  1139. * @deprecated Use {@link Ext.String#urlAppend} instead
  1140. * @method
  1141. * @member Ext
  1142. * @inheritdoc Ext.String#urlAppend
  1143. */
  1144. Ext.urlAppend = Ext.String.urlAppend;
  1145. /**
  1146. * @class Ext.Number
  1147. *
  1148. * A collection of useful static methods to deal with numbers
  1149. * @singleton
  1150. */
  1151. Ext.Number = new function() {
  1152. var me = this,
  1153. isToFixedBroken = (0.9).toFixed() !== '1',
  1154. math = Math;
  1155. Ext.apply(this, {
  1156. /**
  1157. * Checks whether or not the passed number is within a desired range. If the number is already within the
  1158. * range it is returned, otherwise the min or max value is returned depending on which side of the range is
  1159. * exceeded. Note that this method returns the constrained value but does not change the current number.
  1160. * @param {Number} number The number to check
  1161. * @param {Number} min The minimum number in the range
  1162. * @param {Number} max The maximum number in the range
  1163. * @return {Number} The constrained value if outside the range, otherwise the current value
  1164. */
  1165. constrain: function(number, min, max) {
  1166. number = parseFloat(number);
  1167. if (!isNaN(min)) {
  1168. number = math.max(number, min);
  1169. }
  1170. if (!isNaN(max)) {
  1171. number = math.min(number, max);
  1172. }
  1173. return number;
  1174. },
  1175. /**
  1176. * Snaps the passed number between stopping points based upon a passed increment value.
  1177. *
  1178. * The difference between this and {@link #snapInRange} is that {@link #snapInRange} uses the minValue
  1179. * when calculating snap points:
  1180. *
  1181. * r = Ext.Number.snap(56, 2, 55, 65); // Returns 56 - snap points are zero based
  1182. *
  1183. * r = Ext.Number.snapInRange(56, 2, 55, 65); // Returns 57 - snap points are based from minValue
  1184. *
  1185. * @param {Number} value The unsnapped value.
  1186. * @param {Number} increment The increment by which the value must move.
  1187. * @param {Number} minValue The minimum value to which the returned value must be constrained. Overrides the increment.
  1188. * @param {Number} maxValue The maximum value to which the returned value must be constrained. Overrides the increment.
  1189. * @return {Number} The value of the nearest snap target.
  1190. */
  1191. snap : function(value, increment, minValue, maxValue) {
  1192. var m;
  1193. // If no value passed, or minValue was passed and value is less than minValue (anything < undefined is false)
  1194. // Then use the minValue (or zero if the value was undefined)
  1195. if (value === undefined || value < minValue) {
  1196. return minValue || 0;
  1197. }
  1198. if (increment) {
  1199. m = value % increment;
  1200. if (m !== 0) {
  1201. value -= m;
  1202. if (m * 2 >= increment) {
  1203. value += increment;
  1204. } else if (m * 2 < -increment) {
  1205. value -= increment;
  1206. }
  1207. }
  1208. }
  1209. return me.constrain(value, minValue, maxValue);
  1210. },
  1211. /**
  1212. * Snaps the passed number between stopping points based upon a passed increment value.
  1213. *
  1214. * The difference between this and {@link #snap} is that {@link #snap} does not use the minValue
  1215. * when calculating snap points:
  1216. *
  1217. * r = Ext.Number.snap(56, 2, 55, 65); // Returns 56 - snap points are zero based
  1218. *
  1219. * r = Ext.Number.snapInRange(56, 2, 55, 65); // Returns 57 - snap points are based from minValue
  1220. *
  1221. * @param {Number} value The unsnapped value.
  1222. * @param {Number} increment The increment by which the value must move.
  1223. * @param {Number} [minValue=0] The minimum value to which the returned value must be constrained.
  1224. * @param {Number} [maxValue=Infinity] The maximum value to which the returned value must be constrained.
  1225. * @return {Number} The value of the nearest snap target.
  1226. */
  1227. snapInRange : function(value, increment, minValue, maxValue) {
  1228. var tween;
  1229. // default minValue to zero
  1230. minValue = (minValue || 0);
  1231. // If value is undefined, or less than minValue, use minValue
  1232. if (value === undefined || value < minValue) {
  1233. return minValue;
  1234. }
  1235. // Calculate how many snap points from the minValue the passed value is.
  1236. if (increment && (tween = ((value - minValue) % increment))) {
  1237. value -= tween;
  1238. tween *= 2;
  1239. if (tween >= increment) {
  1240. value += increment;
  1241. }
  1242. }
  1243. // If constraining within a maximum, ensure the maximum is on a snap point
  1244. if (maxValue !== undefined) {
  1245. if (value > (maxValue = me.snapInRange(maxValue, increment, minValue))) {
  1246. value = maxValue;
  1247. }
  1248. }
  1249. return value;
  1250. },
  1251. /**
  1252. * Formats a number using fixed-point notation
  1253. * @param {Number} value The number to format
  1254. * @param {Number} precision The number of digits to show after the decimal point
  1255. */
  1256. toFixed: isToFixedBroken ? function(value, precision) {
  1257. precision = precision || 0;
  1258. var pow = math.pow(10, precision);
  1259. return (math.round(value * pow) / pow).toFixed(precision);
  1260. } : function(value, precision) {
  1261. return value.toFixed(precision);
  1262. },
  1263. /**
  1264. * Validate that a value is numeric and convert it to a number if necessary. Returns the specified default value if
  1265. * it is not.
  1266. Ext.Number.from('1.23', 1); // returns 1.23
  1267. Ext.Number.from('abc', 1); // returns 1
  1268. * @param {Object} value
  1269. * @param {Number} defaultValue The value to return if the original value is non-numeric
  1270. * @return {Number} value, if numeric, defaultValue otherwise
  1271. */
  1272. from: function(value, defaultValue) {
  1273. if (isFinite(value)) {
  1274. value = parseFloat(value);
  1275. }
  1276. return !isNaN(value) ? value : defaultValue;
  1277. },
  1278. /**
  1279. * Returns a random integer between the specified range (inclusive)
  1280. * @param {Number} from Lowest value to return.
  1281. * @param {Number} to Highst value to return.
  1282. * @return {Number} A random integer within the specified range.
  1283. */
  1284. randomInt: function (from, to) {
  1285. return math.floor(math.random() * (to - from + 1) + from);
  1286. }
  1287. });
  1288. /**
  1289. * @deprecated 4.0.0 Please use {@link Ext.Number#from} instead.
  1290. * @member Ext
  1291. * @method num
  1292. * @inheritdoc Ext.Number#from
  1293. */
  1294. Ext.num = function() {
  1295. return me.from.apply(this, arguments);
  1296. };
  1297. };
  1298. /**
  1299. * @class Ext.Array
  1300. * @singleton
  1301. * @author Jacky Nguyen <jacky@sencha.com>
  1302. * @docauthor Jacky Nguyen <jacky@sencha.com>
  1303. *
  1304. * A set of useful static methods to deal with arrays; provide missing methods for older browsers.
  1305. */
  1306. (function() {
  1307. var arrayPrototype = Array.prototype,
  1308. slice = arrayPrototype.slice,
  1309. supportsSplice = function () {
  1310. var array = [],
  1311. lengthBefore,
  1312. j = 20;
  1313. if (!array.splice) {
  1314. return false;
  1315. }
  1316. // This detects a bug in IE8 splice method:
  1317. // see http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/6e946d03-e09f-4b22-a4dd-cd5e276bf05a/
  1318. while (j--) {
  1319. array.push("A");
  1320. }
  1321. array.splice(15, 0, "F", "F", "F", "F", "F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F");
  1322. lengthBefore = array.length; //41
  1323. array.splice(13, 0, "XXX"); // add one element
  1324. if (lengthBefore+1 != array.length) {
  1325. return false;
  1326. }
  1327. // end IE8 bug
  1328. return true;
  1329. }(),
  1330. supportsForEach = 'forEach' in arrayPrototype,
  1331. supportsMap = 'map' in arrayPrototype,
  1332. supportsIndexOf = 'indexOf' in arrayPrototype,
  1333. supportsEvery = 'every' in arrayPrototype,
  1334. supportsSome = 'some' in arrayPrototype,
  1335. supportsFilter = 'filter' in arrayPrototype,
  1336. supportsSort = function() {
  1337. var a = [1,2,3,4,5].sort(function(){ return 0; });
  1338. return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5;
  1339. }(),
  1340. supportsSliceOnNodeList = true,
  1341. ExtArray;
  1342. try {
  1343. // IE 6 - 8 will throw an error when using Array.prototype.slice on NodeList
  1344. if (typeof document !== 'undefined') {
  1345. slice.call(document.getElementsByTagName('body'));
  1346. }
  1347. } catch (e) {
  1348. supportsSliceOnNodeList = false;
  1349. }
  1350. function fixArrayIndex (array, index) {
  1351. return (index < 0) ? Math.max(0, array.length + index)
  1352. : Math.min(array.length, index);
  1353. }
  1354. /*
  1355. Does the same work as splice, but with a slightly more convenient signature. The splice
  1356. method has bugs in IE8, so this is the implementation we use on that platform.
  1357. The rippling of items in the array can be tricky. Consider two use cases:
  1358. index=2
  1359. removeCount=2
  1360. /=====\
  1361. +---+---+---+---+---+---+---+---+
  1362. | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
  1363. +---+---+---+---+---+---+---+---+
  1364. / \/ \/ \/ \
  1365. / /\ /\ /\ \
  1366. / / \/ \/ \ +--------------------------+
  1367. / / /\ /\ +--------------------------+ \
  1368. / / / \/ +--------------------------+ \ \
  1369. / / / /+--------------------------+ \ \ \
  1370. / / / / \ \ \ \
  1371. v v v v v v v v
  1372. +---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+---+
  1373. | 0 | 1 | 4 | 5 | 6 | 7 | | 0 | 1 | a | b | c | 4 | 5 | 6 | 7 |
  1374. +---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+---+
  1375. A B \=========/
  1376. insert=[a,b,c]
  1377. In case A, it is obvious that copying of [4,5,6,7] must be left-to-right so
  1378. that we don't end up with [0,1,6,7,6,7]. In case B, we have the opposite; we
  1379. must go right-to-left or else we would end up with [0,1,a,b,c,4,4,4,4].
  1380. */
  1381. function replaceSim (array, index, removeCount, insert) {
  1382. var add = insert ? insert.length : 0,
  1383. length = array.length,
  1384. pos = fixArrayIndex(array, index);
  1385. // we try to use Array.push when we can for efficiency...
  1386. if (pos === length) {
  1387. if (add) {
  1388. array.push.apply(array, insert);
  1389. }
  1390. } else {
  1391. var remove = Math.min(removeCount, length - pos),
  1392. tailOldPos = pos + remove,
  1393. tailNewPos = tailOldPos + add - remove,
  1394. tailCount = length - tailOldPos,
  1395. lengthAfterRemove = length - remove,
  1396. i;
  1397. if (tailNewPos < tailOldPos) { // case A
  1398. for (i = 0; i < tailCount; ++i) {
  1399. array[tailNewPos+i] = array[tailOldPos+i];
  1400. }
  1401. } else if (tailNewPos > tailOldPos) { // case B
  1402. for (i = tailCount; i--; ) {
  1403. array[tailNewPos+i] = array[tailOldPos+i];
  1404. }
  1405. } // else, add == remove (nothing to do)
  1406. if (add && pos === lengthAfterRemove) {
  1407. array.length = lengthAfterRemove; // truncate array
  1408. array.push.apply(array, insert);
  1409. } else {
  1410. array.length = lengthAfterRemove + add; // reserves space
  1411. for (i = 0; i < add; ++i) {
  1412. array[pos+i] = insert[i];
  1413. }
  1414. }
  1415. }
  1416. return array;
  1417. }
  1418. function replaceNative (array, index, removeCount, insert) {
  1419. if (insert && insert.length) {
  1420. if (index < array.length) {
  1421. array.splice.apply(array, [index, removeCount].concat(insert));
  1422. } else {
  1423. array.push.apply(array, insert);
  1424. }
  1425. } else {
  1426. array.splice(index, removeCount);
  1427. }
  1428. return array;
  1429. }
  1430. function eraseSim (array, index, removeCount) {
  1431. return replaceSim(array, index, removeCount);
  1432. }
  1433. function eraseNative (array, index, removeCount) {
  1434. array.splice(index, removeCount);
  1435. return array;
  1436. }
  1437. function spliceSim (array, index, removeCount) {
  1438. var pos = fixArrayIndex(array, index),
  1439. removed = array.slice(index, fixArrayIndex(array, pos+removeCount));
  1440. if (arguments.length < 4) {
  1441. replaceSim(array, pos, removeCount);
  1442. } else {
  1443. replaceSim(array, pos, removeCount, slice.call(arguments, 3));
  1444. }
  1445. return removed;
  1446. }
  1447. function spliceNative (array) {
  1448. return array.splice.apply(array, slice.call(arguments, 1));
  1449. }
  1450. var erase = supportsSplice ? eraseNative : eraseSim,
  1451. replace = supportsSplice ? replaceNative : replaceSim,
  1452. splice = supportsSplice ? spliceNative : spliceSim;
  1453. // NOTE: from here on, use erase, replace or splice (not native methods)...
  1454. ExtArray = Ext.Array = {
  1455. /**
  1456. * Iterates an array or an iterable value and invoke the given callback function for each item.
  1457. *
  1458. * var countries = ['Vietnam', 'Singapore', 'United States', 'Russia'];
  1459. *
  1460. * Ext.Array.each(countries, function(name, index, countriesItSelf) {
  1461. * console.log(name);
  1462. * });
  1463. *
  1464. * var sum = function() {
  1465. * var sum = 0;
  1466. *
  1467. * Ext.Array.each(arguments, function(value) {
  1468. * sum += value;
  1469. * });
  1470. *
  1471. * return sum;
  1472. * };
  1473. *
  1474. * sum(1, 2, 3); // returns 6
  1475. *
  1476. * The iteration can be stopped by returning false in the function callback.
  1477. *
  1478. * Ext.Array.each(countries, function(name, index, countriesItSelf) {
  1479. * if (name === 'Singapore') {
  1480. * return false; // break here
  1481. * }
  1482. * });
  1483. *
  1484. * {@link Ext#each Ext.each} is alias for {@link Ext.Array#each Ext.Array.each}
  1485. *
  1486. * @param {Array/NodeList/Object} iterable The value to be iterated. If this
  1487. * argument is not iterable, the callback function is called once.
  1488. * @param {Function} fn The callback function. If it returns false, the iteration stops and this method returns
  1489. * the current `index`.
  1490. * @param {Object} fn.item The item at the current `index` in the passed `array`
  1491. * @param {Number} fn.index The current `index` within the `array`
  1492. * @param {Array} fn.allItems The `array` itself which was passed as the first argument
  1493. * @param {Boolean} fn.return Return false to stop iteration.
  1494. * @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed.
  1495. * @param {Boolean} reverse (Optional) Reverse the iteration order (loop from the end to the beginning)
  1496. * Defaults false
  1497. * @return {Boolean} See description for the `fn` parameter.
  1498. */
  1499. each: function(array, fn, scope, reverse) {
  1500. array = ExtArray.from(array);
  1501. var i,
  1502. ln = array.length;
  1503. if (reverse !== true) {
  1504. for (i = 0; i < ln; i++) {
  1505. if (fn.call(scope || array[i], array[i], i, array) === false) {
  1506. return i;
  1507. }
  1508. }
  1509. }
  1510. else {
  1511. for (i = ln - 1; i > -1; i--) {
  1512. if (fn.call(scope || array[i], array[i], i, array) === false) {
  1513. return i;
  1514. }
  1515. }
  1516. }
  1517. return true;
  1518. },
  1519. /**
  1520. * Iterates an array and invoke the given callback function for each item. Note that this will simply
  1521. * delegate to the native Array.prototype.forEach method if supported. It doesn't support stopping the
  1522. * iteration by returning false in the callback function like {@link Ext.Array#each}. However, performance
  1523. * could be much better in modern browsers comparing with {@link Ext.Array#each}
  1524. *
  1525. * @param {Array} array The array to iterate
  1526. * @param {Function} fn The callback function.
  1527. * @param {Object} fn.item The item at the current `index` in the passed `array`
  1528. * @param {Number} fn.index The current `index` within the `array`
  1529. * @param {Array} fn.allItems The `array` itself which was passed as the first argument
  1530. * @param {Object} scope (Optional) The execution scope (`this`) in which the specified function is executed.
  1531. */
  1532. forEach: supportsForEach ? function(array, fn, scope) {
  1533. return array.forEach(fn, scope);
  1534. } : function(array, fn, scope) {
  1535. var i = 0,
  1536. ln = array.length;
  1537. for (; i < ln; i++) {
  1538. fn.call(scope, array[i], i, array);
  1539. }
  1540. },
  1541. /**
  1542. * Get the index of the provided `item` in the given `array`, a supplement for the
  1543. * missing arrayPrototype.indexOf in Internet Explorer.
  1544. *
  1545. * @param {Array} array The array to check
  1546. * @param {Object} item The item to look for
  1547. * @param {Number} from (Optional) The index at which to begin the search
  1548. * @return {Number} The index of item in the array (or -1 if it is not found)
  1549. */
  1550. indexOf: supportsIndexOf ? function(array, item, from) {
  1551. return array.indexOf(item, from);
  1552. } : function(array, item, from) {
  1553. var i, length = array.length;
  1554. for (i = (from < 0) ? Math.max(0, length + from) : from || 0; i < length; i++) {
  1555. if (array[i] === item) {
  1556. return i;
  1557. }
  1558. }
  1559. return -1;
  1560. },
  1561. /**
  1562. * Checks whether or not the given `array` contains the specified `item`
  1563. *
  1564. * @param {Array} array The array to check
  1565. * @param {Object} item The item to look for
  1566. * @return {Boolean} True if the array contains the item, false otherwise
  1567. */
  1568. contains: supportsIndexOf ? function(array, item) {
  1569. return array.indexOf(item) !== -1;
  1570. } : function(array, item) {
  1571. var i, ln;
  1572. for (i = 0, ln = array.length; i < ln; i++) {
  1573. if (array[i] === item) {
  1574. return true;
  1575. }
  1576. }
  1577. return false;
  1578. },
  1579. /**
  1580. * Converts any iterable (numeric indices and a length property) into a true array.
  1581. *
  1582. * function test() {
  1583. * var args = Ext.Array.toArray(arguments),
  1584. * fromSecondToLastArgs = Ext.Array.toArray(arguments, 1);
  1585. *
  1586. * alert(args.join(' '));
  1587. * alert(fromSecondToLastArgs.join(' '));
  1588. * }
  1589. *
  1590. * test('just', 'testing', 'here'); // alerts 'just testing here';
  1591. * // alerts 'testing here';
  1592. *
  1593. * Ext.Array.toArray(document.getElementsByTagName('div')); // will convert the NodeList into an array
  1594. * Ext.Array.toArray('splitted'); // returns ['s', 'p', 'l', 'i', 't', 't', 'e', 'd']
  1595. * Ext.Array.toArray('splitted', 0, 3); // returns ['s', 'p', 'l', 'i']
  1596. *
  1597. * {@link Ext#toArray Ext.toArray} is alias for {@link Ext.Array#toArray Ext.Array.toArray}
  1598. *
  1599. * @param {Object} iterable the iterable object to be turned into a true Array.
  1600. * @param {Number} start (Optional) a zero-based index that specifies the start of extraction. Defaults to 0
  1601. * @param {Number} end (Optional) a zero-based index that specifies the end of extraction. Defaults to the last
  1602. * index of the iterable value
  1603. * @return {Array} array
  1604. */
  1605. toArray: function(iterable, start, end){
  1606. if (!iterable || !iterable.length) {
  1607. return [];
  1608. }
  1609. if (typeof iterable === 'string') {
  1610. iterable = iterable.split('');
  1611. }
  1612. if (supportsSliceOnNodeList) {
  1613. return slice.call(iterable, start || 0, end || iterable.length);
  1614. }
  1615. var array = [],
  1616. i;
  1617. start = start || 0;
  1618. end = end ? ((end < 0) ? iterable.length + end : end) : iterable.length;
  1619. for (i = start; i < end; i++) {
  1620. array.push(iterable[i]);
  1621. }
  1622. return array;
  1623. },
  1624. /**
  1625. * Plucks the value of a property from each item in the Array. Example:
  1626. *
  1627. * Ext.Array.pluck(Ext.query("p"), "className"); // [el1.className, el2.className, ..., elN.className]
  1628. *
  1629. * @param {Array/NodeList} array The Array of items to pluck the value from.
  1630. * @param {String} propertyName The property name to pluck from each element.
  1631. * @return {Array} The value from each item in the Array.
  1632. */
  1633. pluck: function(array, propertyName) {
  1634. var ret = [],
  1635. i, ln, item;
  1636. for (i = 0, ln = array.length; i < ln; i++) {
  1637. item = array[i];
  1638. ret.push(item[propertyName]);
  1639. }
  1640. return ret;
  1641. },
  1642. /**
  1643. * Creates a new array with the results of calling a provided function on every element in this array.
  1644. *
  1645. * @param {Array} array
  1646. * @param {Function} fn Callback function for each item
  1647. * @param {Object} scope Callback function scope
  1648. * @return {Array} results
  1649. */
  1650. map: supportsMap ? function(array, fn, scope) {
  1651. return array.map(fn, scope);
  1652. } : function(array, fn, scope) {
  1653. var results = [],
  1654. i = 0,
  1655. len = array.length;
  1656. for (; i < len; i++) {
  1657. results[i] = fn.call(scope, array[i], i, array);
  1658. }
  1659. return results;
  1660. },
  1661. /**
  1662. * Executes the specified function for each array element until the function returns a falsy value.
  1663. * If such an item is found, the function will return false immediately.
  1664. * Otherwise, it will return true.
  1665. *
  1666. * @param {Array} array
  1667. * @param {Function} fn Callback function for each item
  1668. * @param {Object} scope Callback function scope
  1669. * @return {Boolean} True if no false value is returned by the callback function.
  1670. */
  1671. every: supportsEvery ? function(array, fn, scope) {
  1672. return array.every(fn, scope);
  1673. } : function(array, fn, scope) {
  1674. var i = 0,
  1675. ln = array.length;
  1676. for (; i < ln; ++i) {
  1677. if (!fn.call(scope, array[i], i, array)) {
  1678. return false;
  1679. }
  1680. }
  1681. return true;
  1682. },
  1683. /**
  1684. * Executes the specified function for each array element until the function returns a truthy value.
  1685. * If such an item is found, the function will return true immediately. Otherwise, it will return false.
  1686. *
  1687. * @param {Array} array
  1688. * @param {Function} fn Callback function for each item
  1689. * @param {Object} scope Callback function scope
  1690. * @return {Boolean} True if the callback function returns a truthy value.
  1691. */
  1692. some: supportsSome ? function(array, fn, scope) {
  1693. return array.some(fn, scope);
  1694. } : function(array, fn, scope) {
  1695. var i = 0,
  1696. ln = array.length;
  1697. for (; i < ln; ++i) {
  1698. if (fn.call(scope, array[i], i, array)) {
  1699. return true;
  1700. }
  1701. }
  1702. return false;
  1703. },
  1704. /**
  1705. * Filter through an array and remove empty item as defined in {@link Ext#isEmpty Ext.isEmpty}
  1706. *
  1707. * See {@link Ext.Array#filter}
  1708. *
  1709. * @param {Array} array
  1710. * @return {Array} results
  1711. */
  1712. clean: function(array) {
  1713. var results = [],
  1714. i = 0,
  1715. ln = array.length,
  1716. item;
  1717. for (; i < ln; i++) {
  1718. item = array[i];
  1719. if (!Ext.isEmpty(item)) {
  1720. results.push(item);
  1721. }
  1722. }
  1723. return results;
  1724. },
  1725. /**
  1726. * Returns a new array with unique items
  1727. *
  1728. * @param {Array} array
  1729. * @return {Array} results
  1730. */
  1731. unique: function(array) {
  1732. var clone = [],
  1733. i = 0,
  1734. ln = array.length,
  1735. item;
  1736. for (; i < ln; i++) {
  1737. item = array[i];
  1738. if (ExtArray.indexOf(clone, item) === -1) {
  1739. clone.push(item);
  1740. }
  1741. }
  1742. return clone;
  1743. },
  1744. /**
  1745. * Creates a new array with all of the elements of this array for which
  1746. * the provided filtering function returns true.
  1747. *
  1748. * @param {Array} array
  1749. * @param {Function} fn Callback function for each item
  1750. * @param {Object} scope Callback function scope
  1751. * @return {Array} results
  1752. */
  1753. filter: supportsFilter ? function(array, fn, scope) {
  1754. return array.filter(fn, scope);
  1755. } : function(array, fn, scope) {
  1756. var results = [],
  1757. i = 0,
  1758. ln = array.length;
  1759. for (; i < ln; i++) {
  1760. if (fn.call(scope, array[i], i, array)) {
  1761. results.push(array[i]);
  1762. }
  1763. }
  1764. return results;
  1765. },
  1766. /**
  1767. * Converts a value to an array if it's not already an array; returns:
  1768. *
  1769. * - An empty array if given value is `undefined` or `null`
  1770. * - Itself if given value is already an array
  1771. * - An array copy if given value is {@link Ext#isIterable iterable} (arguments, NodeList and alike)
  1772. * - An array with one item which is the given value, otherwise
  1773. *
  1774. * @param {Object} value The value to convert to an array if it's not already is an array
  1775. * @param {Boolean} newReference (Optional) True to clone the given array and return a new reference if necessary,
  1776. * defaults to false
  1777. * @return {Array} array
  1778. */
  1779. from: function(value, newReference) {
  1780. if (value === undefined || value === null) {
  1781. return [];
  1782. }
  1783. if (Ext.isArray(value)) {
  1784. return (newReference) ? slice.call(value) : value;
  1785. }
  1786. if (value && value.length !== undefined && typeof value !== 'string') {
  1787. return ExtArray.toArray(value);
  1788. }
  1789. return [value];
  1790. },
  1791. /**
  1792. * Removes the specified item from the array if it exists
  1793. *
  1794. * @param {Array} array The array
  1795. * @param {Object} item The item to remove
  1796. * @return {Array} The passed array itself
  1797. */
  1798. remove: function(array, item) {
  1799. var index = ExtArray.indexOf(array, item);
  1800. if (index !== -1) {
  1801. erase(array, index, 1);
  1802. }
  1803. return array;
  1804. },
  1805. /**
  1806. * Push an item into the array only if the array doesn't contain it yet
  1807. *
  1808. * @param {Array} array The array
  1809. * @param {Object} item The item to include
  1810. */
  1811. include: function(array, item) {
  1812. if (!ExtArray.contains(array, item)) {
  1813. array.push(item);
  1814. }
  1815. },
  1816. /**
  1817. * Clone a flat array without referencing the previous one. Note that this is different
  1818. * from Ext.clone since it doesn't handle recursive cloning. It's simply a convenient, easy-to-remember method
  1819. * for Array.prototype.slice.call(array)
  1820. *
  1821. * @param {Array} array The array
  1822. * @return {Array} The clone array
  1823. */
  1824. clone: function(array) {
  1825. return slice.call(array);
  1826. },
  1827. /**
  1828. * Merge multiple arrays into one with unique items.
  1829. *
  1830. * {@link Ext.Array#union} is alias for {@link Ext.Array#merge}
  1831. *
  1832. * @param {Array} array1
  1833. * @param {Array} array2
  1834. * @param {Array} etc
  1835. * @return {Array} merged
  1836. */
  1837. merge: function() {
  1838. var args = slice.call(arguments),
  1839. array = [],
  1840. i, ln;
  1841. for (i = 0, ln = args.length; i < ln; i++) {
  1842. array = array.concat(args[i]);
  1843. }
  1844. return ExtArray.unique(array);
  1845. },
  1846. /**
  1847. * Merge multiple arrays into one with unique items that exist in all of the arrays.
  1848. *
  1849. * @param {Array} array1
  1850. * @param {Array} array2
  1851. * @param {Array} etc
  1852. * @return {Array} intersect
  1853. */
  1854. intersect: function() {
  1855. var intersect = [],
  1856. arrays = slice.call(arguments),
  1857. i, j, k, minArray, array, x, y, ln, arraysLn, arrayLn;
  1858. if (!arrays.length) {
  1859. return intersect;
  1860. }
  1861. // Find the smallest array
  1862. for (i = x = 0,ln = arrays.length; i < ln,array = arrays[i]; i++) {
  1863. if (!minArray || array.length < minArray.length) {
  1864. minArray = array;
  1865. x = i;
  1866. }
  1867. }
  1868. minArray = ExtArray.unique(minArray);
  1869. erase(arrays, x, 1);
  1870. // Use the smallest unique'd array as the anchor loop. If the other array(s) do contain
  1871. // an item in the small array, we're likely to find it before reaching the end
  1872. // of the inner loop and can terminate the search early.
  1873. for (i = 0,ln = minArray.length; i < ln,x = minArray[i]; i++) {
  1874. var count = 0;
  1875. for (j = 0,arraysLn = arrays.length; j < arraysLn,array = arrays[j]; j++) {
  1876. for (k = 0,arrayLn = array.length; k < arrayLn,y = array[k]; k++) {
  1877. if (x === y) {
  1878. count++;
  1879. break;
  1880. }
  1881. }
  1882. }
  1883. if (count === arraysLn) {
  1884. intersect.push(x);
  1885. }
  1886. }
  1887. return intersect;
  1888. },
  1889. /**
  1890. * Perform a set difference A-B by subtracting all items in array B from array A.
  1891. *
  1892. * @param {Array} arrayA
  1893. * @param {Array} arrayB
  1894. * @return {Array} difference
  1895. */
  1896. difference: function(arrayA, arrayB) {
  1897. var clone = slice.call(arrayA),
  1898. ln = clone.length,
  1899. i, j, lnB;
  1900. for (i = 0,lnB = arrayB.length; i < lnB; i++) {
  1901. for (j = 0; j < ln; j++) {
  1902. if (clone[j] === arrayB[i]) {
  1903. erase(clone, j, 1);
  1904. j--;
  1905. ln--;
  1906. }
  1907. }
  1908. }
  1909. return clone;
  1910. },
  1911. /**
  1912. * Returns a shallow copy of a part of an array. This is equivalent to the native
  1913. * call "Array.prototype.slice.call(array, begin, end)". This is often used when "array"
  1914. * is "arguments" since the arguments object does not supply a slice method but can
  1915. * be the context object to Array.prototype.slice.
  1916. *
  1917. * @param {Array} array The array (or arguments object).
  1918. * @param {Number} begin The index at which to begin. Negative values are offsets from
  1919. * the end of the array.
  1920. * @param {Number} end The index at which to end. The copied items do not include
  1921. * end. Negative values are offsets from the end of the array. If end is omitted,
  1922. * all items up to the end of the array are copied.
  1923. * @return {Array} The copied piece of the array.
  1924. * @method
  1925. */
  1926. // Note: IE6 will return [] on slice.call(x, undefined).
  1927. slice: ([1,2].slice(1, undefined).length ?
  1928. function (array, begin, end) {
  1929. return slice.call(array, begin, end);
  1930. } :
  1931. // at least IE6 uses arguments.length for variadic signature
  1932. function (array, begin, end) {
  1933. // After tested for IE 6, the one below is of the best performance
  1934. // see http://jsperf.com/slice-fix
  1935. if (typeof begin === 'undefined') {
  1936. return slice.call(array);
  1937. }
  1938. if (typeof end === 'undefined') {
  1939. return slice.call(array, begin);
  1940. }
  1941. return slice.call(array, begin, end);
  1942. }
  1943. ),
  1944. /**
  1945. * Sorts the elements of an Array.
  1946. * By default, this method sorts the elements alphabetically and ascending.
  1947. *
  1948. * @param {Array} array The array to sort.
  1949. * @param {Function} sortFn (optional) The comparison function.
  1950. * @return {Array} The sorted array.
  1951. */
  1952. sort: supportsSort ? function(array, sortFn) {
  1953. if (sortFn) {
  1954. return array.sort(sortFn);
  1955. } else {
  1956. return array.sort();
  1957. }
  1958. } : function(array, sortFn) {
  1959. var length = array.length,
  1960. i = 0,
  1961. comparison,
  1962. j, min, tmp;
  1963. for (; i < length; i++) {
  1964. min = i;
  1965. for (j = i + 1; j < length; j++) {
  1966. if (sortFn) {
  1967. comparison = sortFn(array[j], array[min]);
  1968. if (comparison < 0) {
  1969. min = j;
  1970. }
  1971. } else if (array[j] < array[min]) {
  1972. min = j;
  1973. }
  1974. }
  1975. if (min !== i) {
  1976. tmp = array[i];
  1977. array[i] = array[min];
  1978. array[min] = tmp;
  1979. }
  1980. }
  1981. return array;
  1982. },
  1983. /**
  1984. * Recursively flattens into 1-d Array. Injects Arrays inline.
  1985. *
  1986. * @param {Array} array The array to flatten
  1987. * @return {Array} The 1-d array.
  1988. */
  1989. flatten: function(array) {
  1990. var worker = [];
  1991. function rFlatten(a) {
  1992. var i, ln, v;
  1993. for (i = 0, ln = a.length; i < ln; i++) {
  1994. v = a[i];
  1995. if (Ext.isArray(v)) {
  1996. rFlatten(v);
  1997. } else {
  1998. worker.push(v);
  1999. }
  2000. }
  2001. return worker;
  2002. }
  2003. return rFlatten(array);
  2004. },
  2005. /**
  2006. * Returns the minimum value in the Array.
  2007. *
  2008. * @param {Array/NodeList} array The Array from which to select the minimum value.
  2009. * @param {Function} comparisonFn (optional) a function to perform the comparision which determines minimization.
  2010. * If omitted the "<" operator will be used. Note: gt = 1; eq = 0; lt = -1
  2011. * @return {Object} minValue The minimum value
  2012. */
  2013. min: function(array, comparisonFn) {
  2014. var min = array[0],
  2015. i, ln, item;
  2016. for (i = 0, ln = array.length; i < ln; i++) {
  2017. item = array[i];
  2018. if (comparisonFn) {
  2019. if (comparisonFn(min, item) === 1) {
  2020. min = item;
  2021. }
  2022. }
  2023. else {
  2024. if (item < min) {
  2025. min = item;
  2026. }
  2027. }
  2028. }
  2029. return min;
  2030. },
  2031. /**
  2032. * Returns the maximum value in the Array.
  2033. *
  2034. * @param {Array/NodeList} array The Array from which to select the maximum value.
  2035. * @param {Function} comparisonFn (optional) a function to perform the comparision which determines maximization.
  2036. * If omitted the ">" operator will be used. Note: gt = 1; eq = 0; lt = -1
  2037. * @return {Object} maxValue The maximum value
  2038. */
  2039. max: function(array, comparisonFn) {
  2040. var max = array[0],
  2041. i, ln, item;
  2042. for (i = 0, ln = array.length; i < ln; i++) {
  2043. item = array[i];
  2044. if (comparisonFn) {
  2045. if (comparisonFn(max, item) === -1) {
  2046. max = item;
  2047. }
  2048. }
  2049. else {
  2050. if (item > max) {
  2051. max = item;
  2052. }
  2053. }
  2054. }
  2055. return max;
  2056. },
  2057. /**
  2058. * Calculates the mean of all items in the array.
  2059. *
  2060. * @param {Array} array The Array to calculate the mean value of.
  2061. * @return {Number} The mean.
  2062. */
  2063. mean: function(array) {
  2064. return array.length > 0 ? ExtArray.sum(array) / array.length : undefined;
  2065. },
  2066. /**
  2067. * Calculates the sum of all items in the given array.
  2068. *
  2069. * @param {Array} array The Array to calculate the sum value of.
  2070. * @return {Number} The sum.
  2071. */
  2072. sum: function(array) {
  2073. var sum = 0,
  2074. i, ln, item;
  2075. for (i = 0,ln = array.length; i < ln; i++) {
  2076. item = array[i];
  2077. sum += item;
  2078. }
  2079. return sum;
  2080. },
  2081. /**
  2082. * Creates a map (object) keyed by the elements of the given array. The values in
  2083. * the map are the index+1 of the array element. For example:
  2084. *
  2085. * var map = Ext.Array.toMap(['a','b','c']);
  2086. *
  2087. * // map = { a: 1, b: 2, c: 3 };
  2088. *
  2089. * Or a key property can be specified:
  2090. *
  2091. * var map = Ext.Array.toMap([
  2092. * { name: 'a' },
  2093. * { name: 'b' },
  2094. * { name: 'c' }
  2095. * ], 'name');
  2096. *
  2097. * // map = { a: 1, b: 2, c: 3 };
  2098. *
  2099. * Lastly, a key extractor can be provided:
  2100. *
  2101. * var map = Ext.Array.toMap([
  2102. * { name: 'a' },
  2103. * { name: 'b' },
  2104. * { name: 'c' }
  2105. * ], function (obj) { return obj.name.toUpperCase(); });
  2106. *
  2107. * // map = { A: 1, B: 2, C: 3 };
  2108. */
  2109. toMap: function(array, getKey, scope) {
  2110. var map = {},
  2111. i = array.length;
  2112. if (!getKey) {
  2113. while (i--) {
  2114. map[array[i]] = i+1;
  2115. }
  2116. } else if (typeof getKey == 'string') {
  2117. while (i--) {
  2118. map[array[i][getKey]] = i+1;
  2119. }
  2120. } else {
  2121. while (i--) {
  2122. map[getKey.call(scope, array[i])] = i+1;
  2123. }
  2124. }
  2125. return map;
  2126. },
  2127. /**
  2128. * Removes items from an array. This is functionally equivalent to the splice method
  2129. * of Array, but works around bugs in IE8's splice method and does not copy the
  2130. * removed elements in order to return them (because very often they are ignored).
  2131. *
  2132. * @param {Array} array The Array on which to replace.
  2133. * @param {Number} index The index in the array at which to operate.
  2134. * @param {Number} removeCount The number of items to remove at index.
  2135. * @return {Array} The array passed.
  2136. * @method
  2137. */
  2138. erase: erase,
  2139. /**
  2140. * Inserts items in to an array.
  2141. *
  2142. * @param {Array} array The Array in which to insert.
  2143. * @param {Number} index The index in the array at which to operate.
  2144. * @param {Array} items The array of items to insert at index.
  2145. * @return {Array} The array passed.
  2146. */
  2147. insert: function (array, index, items) {
  2148. return replace(array, index, 0, items);
  2149. },
  2150. /**
  2151. * Replaces items in an array. This is functionally equivalent to the splice method
  2152. * of Array, but works around bugs in IE8's splice method and is often more convenient
  2153. * to call because it accepts an array of items to insert rather than use a variadic
  2154. * argument list.
  2155. *
  2156. * @param {Array} array The Array on which to replace.
  2157. * @param {Number} index The index in the array at which to operate.
  2158. * @param {Number} removeCount The number of items to remove at index (can be 0).
  2159. * @param {Array} insert (optional) An array of items to insert at index.
  2160. * @return {Array} The array passed.
  2161. * @method
  2162. */
  2163. replace: replace,
  2164. /**
  2165. * Replaces items in an array. This is equivalent to the splice method of Array, but
  2166. * works around bugs in IE8's splice method. The signature is exactly the same as the
  2167. * splice method except that the array is the first argument. All arguments following
  2168. * removeCount are inserted in the array at index.
  2169. *
  2170. * @param {Array} array The Array on which to replace.
  2171. * @param {Number} index The index in the array at which to operate.
  2172. * @param {Number} removeCount The number of items to remove at index (can be 0).
  2173. * @param {Object...} elements The elements to add to the array. If you don't specify
  2174. * any elements, splice simply removes elements from the array.
  2175. * @return {Array} An array containing the removed items.
  2176. * @method
  2177. */
  2178. splice: splice,
  2179. /**
  2180. * Pushes new items onto the end of an Array.
  2181. *
  2182. * Passed parameters may be single items, or arrays of items. If an Array is found in the argument list, all its
  2183. * elements are pushed into the end of the target Array.
  2184. *
  2185. * @param {Array} target The Array onto which to push new items
  2186. * @param {Object...} elements The elements to add to the array. Each parameter may
  2187. * be an Array, in which case all the elements of that Array will be pushed into the end of the
  2188. * destination Array.
  2189. * @return {Array} An array containing all the new items push onto the end.
  2190. *
  2191. */
  2192. push: function(array) {
  2193. var len = arguments.length,
  2194. i = 1,
  2195. newItem;
  2196. if (array === undefined) {
  2197. array = [];
  2198. } else if (!Ext.isArray(array)) {
  2199. array = [array];
  2200. }
  2201. for (; i < len; i++) {
  2202. newItem = arguments[i];
  2203. Array.prototype.push[Ext.isArray(newItem) ? 'apply' : 'call'](array, newItem);
  2204. }
  2205. return array;
  2206. }
  2207. };
  2208. /**
  2209. * @method
  2210. * @member Ext
  2211. * @inheritdoc Ext.Array#each
  2212. */
  2213. Ext.each = ExtArray.each;
  2214. /**
  2215. * @method
  2216. * @member Ext.Array
  2217. * @inheritdoc Ext.Array#merge
  2218. */
  2219. ExtArray.union = ExtArray.merge;
  2220. /**
  2221. * Old alias to {@link Ext.Array#min}
  2222. * @deprecated 4.0.0 Use {@link Ext.Array#min} instead
  2223. * @method
  2224. * @member Ext
  2225. * @inheritdoc Ext.Array#min
  2226. */
  2227. Ext.min = ExtArray.min;
  2228. /**
  2229. * Old alias to {@link Ext.Array#max}
  2230. * @deprecated 4.0.0 Use {@link Ext.Array#max} instead
  2231. * @method
  2232. * @member Ext
  2233. * @inheritdoc Ext.Array#max
  2234. */
  2235. Ext.max = ExtArray.max;
  2236. /**
  2237. * Old alias to {@link Ext.Array#sum}
  2238. * @deprecated 4.0.0 Use {@link Ext.Array#sum} instead
  2239. * @method
  2240. * @member Ext
  2241. * @inheritdoc Ext.Array#sum
  2242. */
  2243. Ext.sum = ExtArray.sum;
  2244. /**
  2245. * Old alias to {@link Ext.Array#mean}
  2246. * @deprecated 4.0.0 Use {@link Ext.Array#mean} instead
  2247. * @method
  2248. * @member Ext
  2249. * @inheritdoc Ext.Array#mean
  2250. */
  2251. Ext.mean = ExtArray.mean;
  2252. /**
  2253. * Old alias to {@link Ext.Array#flatten}
  2254. * @deprecated 4.0.0 Use {@link Ext.Array#flatten} instead
  2255. * @method
  2256. * @member Ext
  2257. * @inheritdoc Ext.Array#flatten
  2258. */
  2259. Ext.flatten = ExtArray.flatten;
  2260. /**
  2261. * Old alias to {@link Ext.Array#clean}
  2262. * @deprecated 4.0.0 Use {@link Ext.Array#clean} instead
  2263. * @method
  2264. * @member Ext
  2265. * @inheritdoc Ext.Array#clean
  2266. */
  2267. Ext.clean = ExtArray.clean;
  2268. /**
  2269. * Old alias to {@link Ext.Array#unique}
  2270. * @deprecated 4.0.0 Use {@link Ext.Array#unique} instead
  2271. * @method
  2272. * @member Ext
  2273. * @inheritdoc Ext.Array#unique
  2274. */
  2275. Ext.unique = ExtArray.unique;
  2276. /**
  2277. * Old alias to {@link Ext.Array#pluck Ext.Array.pluck}
  2278. * @deprecated 4.0.0 Use {@link Ext.Array#pluck Ext.Array.pluck} instead
  2279. * @method
  2280. * @member Ext
  2281. * @inheritdoc Ext.Array#pluck
  2282. */
  2283. Ext.pluck = ExtArray.pluck;
  2284. /**
  2285. * @method
  2286. * @member Ext
  2287. * @inheritdoc Ext.Array#toArray
  2288. */
  2289. Ext.toArray = function() {
  2290. return ExtArray.toArray.apply(ExtArray, arguments);
  2291. };
  2292. })();
  2293. /**
  2294. * @class Ext.Function
  2295. *
  2296. * A collection of useful static methods to deal with function callbacks
  2297. * @singleton
  2298. * @alternateClassName Ext.util.Functions
  2299. */
  2300. Ext.Function = {
  2301. /**
  2302. * A very commonly used method throughout the framework. It acts as a wrapper around another method
  2303. * which originally accepts 2 arguments for `name` and `value`.
  2304. * The wrapped function then allows "flexible" value setting of either:
  2305. *
  2306. * - `name` and `value` as 2 arguments
  2307. * - one single object argument with multiple key - value pairs
  2308. *
  2309. * For example:
  2310. *
  2311. * var setValue = Ext.Function.flexSetter(function(name, value) {
  2312. * this[name] = value;
  2313. * });
  2314. *
  2315. * // Afterwards
  2316. * // Setting a single name - value
  2317. * setValue('name1', 'value1');
  2318. *
  2319. * // Settings multiple name - value pairs
  2320. * setValue({
  2321. * name1: 'value1',
  2322. * name2: 'value2',
  2323. * name3: 'value3'
  2324. * });
  2325. *
  2326. * @param {Function} setter
  2327. * @returns {Function} flexSetter
  2328. */
  2329. flexSetter: function(fn) {
  2330. return function(a, b) {
  2331. var k, i;
  2332. if (a === null) {
  2333. return this;
  2334. }
  2335. if (typeof a !== 'string') {
  2336. for (k in a) {
  2337. if (a.hasOwnProperty(k)) {
  2338. fn.call(this, k, a[k]);
  2339. }
  2340. }
  2341. if (Ext.enumerables) {
  2342. for (i = Ext.enumerables.length; i--;) {
  2343. k = Ext.enumerables[i];
  2344. if (a.hasOwnProperty(k)) {
  2345. fn.call(this, k, a[k]);
  2346. }
  2347. }
  2348. }
  2349. } else {
  2350. fn.call(this, a, b);
  2351. }
  2352. return this;
  2353. };
  2354. },
  2355. /**
  2356. * Create a new function from the provided `fn`, change `this` to the provided scope, optionally
  2357. * overrides arguments for the call. (Defaults to the arguments passed by the caller)
  2358. *
  2359. * {@link Ext#bind Ext.bind} is alias for {@link Ext.Function#bind Ext.Function.bind}
  2360. *
  2361. * @param {Function} fn The function to delegate.
  2362. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
  2363. * **If omitted, defaults to the default global environment object (usually the browser window).**
  2364. * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
  2365. * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
  2366. * if a number the args are inserted at the specified position
  2367. * @return {Function} The new function
  2368. */
  2369. bind: function(fn, scope, args, appendArgs) {
  2370. if (arguments.length === 2) {
  2371. return function() {
  2372. return fn.apply(scope, arguments);
  2373. };
  2374. }
  2375. var method = fn,
  2376. slice = Array.prototype.slice;
  2377. return function() {
  2378. var callArgs = args || arguments;
  2379. if (appendArgs === true) {
  2380. callArgs = slice.call(arguments, 0);
  2381. callArgs = callArgs.concat(args);
  2382. }
  2383. else if (typeof appendArgs == 'number') {
  2384. callArgs = slice.call(arguments, 0); // copy arguments first
  2385. Ext.Array.insert(callArgs, appendArgs, args);
  2386. }
  2387. return method.apply(scope || Ext.global, callArgs);
  2388. };
  2389. },
  2390. /**
  2391. * Create a new function from the provided `fn`, the arguments of which are pre-set to `args`.
  2392. * New arguments passed to the newly created callback when it's invoked are appended after the pre-set ones.
  2393. * This is especially useful when creating callbacks.
  2394. *
  2395. * For example:
  2396. *
  2397. * var originalFunction = function(){
  2398. * alert(Ext.Array.from(arguments).join(' '));
  2399. * };
  2400. *
  2401. * var callback = Ext.Function.pass(originalFunction, ['Hello', 'World']);
  2402. *
  2403. * callback(); // alerts 'Hello World'
  2404. * callback('by Me'); // alerts 'Hello World by Me'
  2405. *
  2406. * {@link Ext#pass Ext.pass} is alias for {@link Ext.Function#pass Ext.Function.pass}
  2407. *
  2408. * @param {Function} fn The original function
  2409. * @param {Array} args The arguments to pass to new callback
  2410. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
  2411. * @return {Function} The new callback function
  2412. */
  2413. pass: function(fn, args, scope) {
  2414. if (!Ext.isArray(args)) {
  2415. if (Ext.isIterable(args)) {
  2416. args = Ext.Array.clone(args);
  2417. } else {
  2418. args = args !== undefined ? [args] : [];
  2419. }
  2420. };
  2421. return function() {
  2422. var fnArgs = [].concat(args);
  2423. fnArgs.push.apply(fnArgs, arguments);
  2424. return fn.apply(scope || this, fnArgs);
  2425. };
  2426. },
  2427. /**
  2428. * Create an alias to the provided method property with name `methodName` of `object`.
  2429. * Note that the execution scope will still be bound to the provided `object` itself.
  2430. *
  2431. * @param {Object/Function} object
  2432. * @param {String} methodName
  2433. * @return {Function} aliasFn
  2434. */
  2435. alias: function(object, methodName) {
  2436. return function() {
  2437. return object[methodName].apply(object, arguments);
  2438. };
  2439. },
  2440. /**
  2441. * Create a "clone" of the provided method. The returned method will call the given
  2442. * method passing along all arguments and the "this" pointer and return its result.
  2443. *
  2444. * @param {Function} method
  2445. * @return {Function} cloneFn
  2446. */
  2447. clone: function(method) {
  2448. return function() {
  2449. return method.apply(this, arguments);
  2450. };
  2451. },
  2452. /**
  2453. * Creates an interceptor function. The passed function is called before the original one. If it returns false,
  2454. * the original one is not called. The resulting function returns the results of the original function.
  2455. * The passed function is called with the parameters of the original function. Example usage:
  2456. *
  2457. * var sayHi = function(name){
  2458. * alert('Hi, ' + name);
  2459. * }
  2460. *
  2461. * sayHi('Fred'); // alerts "Hi, Fred"
  2462. *
  2463. * // create a new function that validates input without
  2464. * // directly modifying the original function:
  2465. * var sayHiToFriend = Ext.Function.createInterceptor(sayHi, function(name){
  2466. * return name == 'Brian';
  2467. * });
  2468. *
  2469. * sayHiToFriend('Fred'); // no alert
  2470. * sayHiToFriend('Brian'); // alerts "Hi, Brian"
  2471. *
  2472. * @param {Function} origFn The original function.
  2473. * @param {Function} newFn The function to call before the original
  2474. * @param {Object} scope (optional) The scope (`this` reference) in which the passed function is executed.
  2475. * **If omitted, defaults to the scope in which the original function is called or the browser window.**
  2476. * @param {Object} returnValue (optional) The value to return if the passed function return false (defaults to null).
  2477. * @return {Function} The new function
  2478. */
  2479. createInterceptor: function(origFn, newFn, scope, returnValue) {
  2480. var method = origFn;
  2481. if (!Ext.isFunction(newFn)) {
  2482. return origFn;
  2483. }
  2484. else {
  2485. return function() {
  2486. var me = this,
  2487. args = arguments;
  2488. newFn.target = me;
  2489. newFn.method = origFn;
  2490. return (newFn.apply(scope || me || Ext.global, args) !== false) ? origFn.apply(me || Ext.global, args) : returnValue || null;
  2491. };
  2492. }
  2493. },
  2494. /**
  2495. * Creates a delegate (callback) which, when called, executes after a specific delay.
  2496. *
  2497. * @param {Function} fn The function which will be called on a delay when the returned function is called.
  2498. * Optionally, a replacement (or additional) argument list may be specified.
  2499. * @param {Number} delay The number of milliseconds to defer execution by whenever called.
  2500. * @param {Object} scope (optional) The scope (`this` reference) used by the function at execution time.
  2501. * @param {Array} args (optional) Override arguments for the call. (Defaults to the arguments passed by the caller)
  2502. * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
  2503. * if a number the args are inserted at the specified position.
  2504. * @return {Function} A function which, when called, executes the original function after the specified delay.
  2505. */
  2506. createDelayed: function(fn, delay, scope, args, appendArgs) {
  2507. if (scope || args) {
  2508. fn = Ext.Function.bind(fn, scope, args, appendArgs);
  2509. }
  2510. return function() {
  2511. var me = this,
  2512. args = Array.prototype.slice.call(arguments);
  2513. setTimeout(function() {
  2514. fn.apply(me, args);
  2515. }, delay);
  2516. };
  2517. },
  2518. /**
  2519. * Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage:
  2520. *
  2521. * var sayHi = function(name){
  2522. * alert('Hi, ' + name);
  2523. * }
  2524. *
  2525. * // executes immediately:
  2526. * sayHi('Fred');
  2527. *
  2528. * // executes after 2 seconds:
  2529. * Ext.Function.defer(sayHi, 2000, this, ['Fred']);
  2530. *
  2531. * // this syntax is sometimes useful for deferring
  2532. * // execution of an anonymous function:
  2533. * Ext.Function.defer(function(){
  2534. * alert('Anonymous');
  2535. * }, 100);
  2536. *
  2537. * {@link Ext#defer Ext.defer} is alias for {@link Ext.Function#defer Ext.Function.defer}
  2538. *
  2539. * @param {Function} fn The function to defer.
  2540. * @param {Number} millis The number of milliseconds for the setTimeout call
  2541. * (if less than or equal to 0 the function is executed immediately)
  2542. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
  2543. * **If omitted, defaults to the browser window.**
  2544. * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
  2545. * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
  2546. * if a number the args are inserted at the specified position
  2547. * @return {Number} The timeout id that can be used with clearTimeout
  2548. */
  2549. defer: function(fn, millis, scope, args, appendArgs) {
  2550. fn = Ext.Function.bind(fn, scope, args, appendArgs);
  2551. if (millis > 0) {
  2552. return setTimeout(fn, millis);
  2553. }
  2554. fn();
  2555. return 0;
  2556. },
  2557. /**
  2558. * Create a combined function call sequence of the original function + the passed function.
  2559. * The resulting function returns the results of the original function.
  2560. * The passed function is called with the parameters of the original function. Example usage:
  2561. *
  2562. * var sayHi = function(name){
  2563. * alert('Hi, ' + name);
  2564. * }
  2565. *
  2566. * sayHi('Fred'); // alerts "Hi, Fred"
  2567. *
  2568. * var sayGoodbye = Ext.Function.createSequence(sayHi, function(name){
  2569. * alert('Bye, ' + name);
  2570. * });
  2571. *
  2572. * sayGoodbye('Fred'); // both alerts show
  2573. *
  2574. * @param {Function} originalFn The original function.
  2575. * @param {Function} newFn The function to sequence
  2576. * @param {Object} scope (optional) The scope (`this` reference) in which the passed function is executed.
  2577. * If omitted, defaults to the scope in which the original function is called or the default global environment object (usually the browser window).
  2578. * @return {Function} The new function
  2579. */
  2580. createSequence: function(originalFn, newFn, scope) {
  2581. if (!newFn) {
  2582. return originalFn;
  2583. }
  2584. else {
  2585. return function() {
  2586. var result = originalFn.apply(this, arguments);
  2587. newFn.apply(scope || this, arguments);
  2588. return result;
  2589. };
  2590. }
  2591. },
  2592. /**
  2593. * Creates a delegate function, optionally with a bound scope which, when called, buffers
  2594. * the execution of the passed function for the configured number of milliseconds.
  2595. * If called again within that period, the impending invocation will be canceled, and the
  2596. * timeout period will begin again.
  2597. *
  2598. * @param {Function} fn The function to invoke on a buffered timer.
  2599. * @param {Number} buffer The number of milliseconds by which to buffer the invocation of the
  2600. * function.
  2601. * @param {Object} scope (optional) The scope (`this` reference) in which
  2602. * the passed function is executed. If omitted, defaults to the scope specified by the caller.
  2603. * @param {Array} args (optional) Override arguments for the call. Defaults to the arguments
  2604. * passed by the caller.
  2605. * @return {Function} A function which invokes the passed function after buffering for the specified time.
  2606. */
  2607. createBuffered: function(fn, buffer, scope, args) {
  2608. var timerId;
  2609. return function() {
  2610. var callArgs = args || Array.prototype.slice.call(arguments, 0),
  2611. me = scope || this;
  2612. if (timerId) {
  2613. clearTimeout(timerId);
  2614. }
  2615. timerId = setTimeout(function(){
  2616. fn.apply(me, callArgs);
  2617. }, buffer);
  2618. };
  2619. },
  2620. /**
  2621. * Creates a throttled version of the passed function which, when called repeatedly and
  2622. * rapidly, invokes the passed function only after a certain interval has elapsed since the
  2623. * previous invocation.
  2624. *
  2625. * This is useful for wrapping functions which may be called repeatedly, such as
  2626. * a handler of a mouse move event when the processing is expensive.
  2627. *
  2628. * @param {Function} fn The function to execute at a regular time interval.
  2629. * @param {Number} interval The interval **in milliseconds** on which the passed function is executed.
  2630. * @param {Object} scope (optional) The scope (`this` reference) in which
  2631. * the passed function is executed. If omitted, defaults to the scope specified by the caller.
  2632. * @returns {Function} A function which invokes the passed function at the specified interval.
  2633. */
  2634. createThrottled: function(fn, interval, scope) {
  2635. var lastCallTime, elapsed, lastArgs, timer, execute = function() {
  2636. fn.apply(scope || this, lastArgs);
  2637. lastCallTime = new Date().getTime();
  2638. };
  2639. return function() {
  2640. elapsed = new Date().getTime() - lastCallTime;
  2641. lastArgs = arguments;
  2642. clearTimeout(timer);
  2643. if (!lastCallTime || (elapsed >= interval)) {
  2644. execute();
  2645. } else {
  2646. timer = setTimeout(execute, interval - elapsed);
  2647. }
  2648. };
  2649. },
  2650. /**
  2651. * Adds behavior to an existing method that is executed before the
  2652. * original behavior of the function. For example:
  2653. *
  2654. * var soup = {
  2655. * contents: [],
  2656. * add: function(ingredient) {
  2657. * this.contents.push(ingredient);
  2658. * }
  2659. * };
  2660. * Ext.Function.interceptBefore(soup, "add", function(ingredient){
  2661. * if (!this.contents.length && ingredient !== "water") {
  2662. * // Always add water to start with
  2663. * this.contents.push("water");
  2664. * }
  2665. * });
  2666. * soup.add("onions");
  2667. * soup.add("salt");
  2668. * soup.contents; // will contain: water, onions, salt
  2669. *
  2670. * @param {Object} object The target object
  2671. * @param {String} methodName Name of the method to override
  2672. * @param {Function} fn Function with the new behavior. It will
  2673. * be called with the same arguments as the original method. The
  2674. * return value of this function will be the return value of the
  2675. * new method.
  2676. * @param {Object} [scope] The scope to execute the interceptor function. Defaults to the object.
  2677. * @return {Function} The new function just created.
  2678. */
  2679. interceptBefore: function(object, methodName, fn, scope) {
  2680. var method = object[methodName] || Ext.emptyFn;
  2681. return (object[methodName] = function() {
  2682. var ret = fn.apply(scope || this, arguments);
  2683. method.apply(this, arguments);
  2684. return ret;
  2685. });
  2686. },
  2687. /**
  2688. * Adds behavior to an existing method that is executed after the
  2689. * original behavior of the function. For example:
  2690. *
  2691. * var soup = {
  2692. * contents: [],
  2693. * add: function(ingredient) {
  2694. * this.contents.push(ingredient);
  2695. * }
  2696. * };
  2697. * Ext.Function.interceptAfter(soup, "add", function(ingredient){
  2698. * // Always add a bit of extra salt
  2699. * this.contents.push("salt");
  2700. * });
  2701. * soup.add("water");
  2702. * soup.add("onions");
  2703. * soup.contents; // will contain: water, salt, onions, salt
  2704. *
  2705. * @param {Object} object The target object
  2706. * @param {String} methodName Name of the method to override
  2707. * @param {Function} fn Function with the new behavior. It will
  2708. * be called with the same arguments as the original method. The
  2709. * return value of this function will be the return value of the
  2710. * new method.
  2711. * @param {Object} [scope] The scope to execute the interceptor function. Defaults to the object.
  2712. * @return {Function} The new function just created.
  2713. */
  2714. interceptAfter: function(object, methodName, fn, scope) {
  2715. var method = object[methodName] || Ext.emptyFn;
  2716. return (object[methodName] = function() {
  2717. method.apply(this, arguments);
  2718. return fn.apply(scope || this, arguments);
  2719. });
  2720. }
  2721. };
  2722. /**
  2723. * @method
  2724. * @member Ext
  2725. * @inheritdoc Ext.Function#defer
  2726. */
  2727. Ext.defer = Ext.Function.alias(Ext.Function, 'defer');
  2728. /**
  2729. * @method
  2730. * @member Ext
  2731. * @inheritdoc Ext.Function#pass
  2732. */
  2733. Ext.pass = Ext.Function.alias(Ext.Function, 'pass');
  2734. /**
  2735. * @method
  2736. * @member Ext
  2737. * @inheritdoc Ext.Function#bind
  2738. */
  2739. Ext.bind = Ext.Function.alias(Ext.Function, 'bind');
  2740. /**
  2741. * @author Jacky Nguyen <jacky@sencha.com>
  2742. * @docauthor Jacky Nguyen <jacky@sencha.com>
  2743. * @class Ext.Object
  2744. *
  2745. * A collection of useful static methods to deal with objects.
  2746. *
  2747. * @singleton
  2748. */
  2749. (function() {
  2750. // The "constructor" for chain:
  2751. var TemplateClass = function(){};
  2752. var ExtObject = Ext.Object = {
  2753. /**
  2754. * Returns a new object with the given object as the prototype chain.
  2755. * @param {Object} object The prototype chain for the new object.
  2756. */
  2757. chain: function (object) {
  2758. TemplateClass.prototype = object;
  2759. var result = new TemplateClass();
  2760. TemplateClass.prototype = null;
  2761. return result;
  2762. },
  2763. /**
  2764. * Converts a `name` - `value` pair to an array of objects with support for nested structures. Useful to construct
  2765. * query strings. For example:
  2766. *
  2767. * var objects = Ext.Object.toQueryObjects('hobbies', ['reading', 'cooking', 'swimming']);
  2768. *
  2769. * // objects then equals:
  2770. * [
  2771. * { name: 'hobbies', value: 'reading' },
  2772. * { name: 'hobbies', value: 'cooking' },
  2773. * { name: 'hobbies', value: 'swimming' },
  2774. * ];
  2775. *
  2776. * var objects = Ext.Object.toQueryObjects('dateOfBirth', {
  2777. * day: 3,
  2778. * month: 8,
  2779. * year: 1987,
  2780. * extra: {
  2781. * hour: 4
  2782. * minute: 30
  2783. * }
  2784. * }, true); // Recursive
  2785. *
  2786. * // objects then equals:
  2787. * [
  2788. * { name: 'dateOfBirth[day]', value: 3 },
  2789. * { name: 'dateOfBirth[month]', value: 8 },
  2790. * { name: 'dateOfBirth[year]', value: 1987 },
  2791. * { name: 'dateOfBirth[extra][hour]', value: 4 },
  2792. * { name: 'dateOfBirth[extra][minute]', value: 30 },
  2793. * ];
  2794. *
  2795. * @param {String} name
  2796. * @param {Object/Array} value
  2797. * @param {Boolean} [recursive=false] True to traverse object recursively
  2798. * @return {Array}
  2799. */
  2800. toQueryObjects: function(name, value, recursive) {
  2801. var self = ExtObject.toQueryObjects,
  2802. objects = [],
  2803. i, ln;
  2804. if (Ext.isArray(value)) {
  2805. for (i = 0, ln = value.length; i < ln; i++) {
  2806. if (recursive) {
  2807. objects = objects.concat(self(name + '[' + i + ']', value[i], true));
  2808. }
  2809. else {
  2810. objects.push({
  2811. name: name,
  2812. value: value[i]
  2813. });
  2814. }
  2815. }
  2816. }
  2817. else if (Ext.isObject(value)) {
  2818. for (i in value) {
  2819. if (value.hasOwnProperty(i)) {
  2820. if (recursive) {
  2821. objects = objects.concat(self(name + '[' + i + ']', value[i], true));
  2822. }
  2823. else {
  2824. objects.push({
  2825. name: name,
  2826. value: value[i]
  2827. });
  2828. }
  2829. }
  2830. }
  2831. }
  2832. else {
  2833. objects.push({
  2834. name: name,
  2835. value: value
  2836. });
  2837. }
  2838. return objects;
  2839. },
  2840. /**
  2841. * Takes an object and converts it to an encoded query string.
  2842. *
  2843. * Non-recursive:
  2844. *
  2845. * Ext.Object.toQueryString({foo: 1, bar: 2}); // returns "foo=1&bar=2"
  2846. * Ext.Object.toQueryString({foo: null, bar: 2}); // returns "foo=&bar=2"
  2847. * Ext.Object.toQueryString({'some price': '$300'}); // returns "some%20price=%24300"
  2848. * Ext.Object.toQueryString({date: new Date(2011, 0, 1)}); // returns "date=%222011-01-01T00%3A00%3A00%22"
  2849. * Ext.Object.toQueryString({colors: ['red', 'green', 'blue']}); // returns "colors=red&colors=green&colors=blue"
  2850. *
  2851. * Recursive:
  2852. *
  2853. * Ext.Object.toQueryString({
  2854. * username: 'Jacky',
  2855. * dateOfBirth: {
  2856. * day: 1,
  2857. * month: 2,
  2858. * year: 1911
  2859. * },
  2860. * hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']]
  2861. * }, true); // returns the following string (broken down and url-decoded for ease of reading purpose):
  2862. * // username=Jacky
  2863. * // &dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911
  2864. * // &hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&hobbies[3][0]=nested&hobbies[3][1]=stuff
  2865. *
  2866. * @param {Object} object The object to encode
  2867. * @param {Boolean} [recursive=false] Whether or not to interpret the object in recursive format.
  2868. * (PHP / Ruby on Rails servers and similar).
  2869. * @return {String} queryString
  2870. */
  2871. toQueryString: function(object, recursive) {
  2872. var paramObjects = [],
  2873. params = [],
  2874. i, j, ln, paramObject, value;
  2875. for (i in object) {
  2876. if (object.hasOwnProperty(i)) {
  2877. paramObjects = paramObjects.concat(ExtObject.toQueryObjects(i, object[i], recursive));
  2878. }
  2879. }
  2880. for (j = 0, ln = paramObjects.length; j < ln; j++) {
  2881. paramObject = paramObjects[j];
  2882. value = paramObject.value;
  2883. if (Ext.isEmpty(value)) {
  2884. value = '';
  2885. }
  2886. else if (Ext.isDate(value)) {
  2887. value = Ext.Date.toString(value);
  2888. }
  2889. params.push(encodeURIComponent(paramObject.name) + '=' + encodeURIComponent(String(value)));
  2890. }
  2891. return params.join('&');
  2892. },
  2893. /**
  2894. * Converts a query string back into an object.
  2895. *
  2896. * Non-recursive:
  2897. *
  2898. * Ext.Object.fromQueryString("foo=1&bar=2"); // returns {foo: 1, bar: 2}
  2899. * Ext.Object.fromQueryString("foo=&bar=2"); // returns {foo: null, bar: 2}
  2900. * Ext.Object.fromQueryString("some%20price=%24300"); // returns {'some price': '$300'}
  2901. * Ext.Object.fromQueryString("colors=red&colors=green&colors=blue"); // returns {colors: ['red', 'green', 'blue']}
  2902. *
  2903. * Recursive:
  2904. *
  2905. * Ext.Object.fromQueryString(
  2906. * "username=Jacky&"+
  2907. * "dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911&"+
  2908. * "hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&"+
  2909. * "hobbies[3][0]=nested&hobbies[3][1]=stuff", true);
  2910. *
  2911. * // returns
  2912. * {
  2913. * username: 'Jacky',
  2914. * dateOfBirth: {
  2915. * day: '1',
  2916. * month: '2',
  2917. * year: '1911'
  2918. * },
  2919. * hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']]
  2920. * }
  2921. *
  2922. * @param {String} queryString The query string to decode
  2923. * @param {Boolean} [recursive=false] Whether or not to recursively decode the string. This format is supported by
  2924. * PHP / Ruby on Rails servers and similar.
  2925. * @return {Object}
  2926. */
  2927. fromQueryString: function(queryString, recursive) {
  2928. var parts = queryString.replace(/^\?/, '').split('&'),
  2929. object = {},
  2930. temp, components, name, value, i, ln,
  2931. part, j, subLn, matchedKeys, matchedName,
  2932. keys, key, nextKey;
  2933. for (i = 0, ln = parts.length; i < ln; i++) {
  2934. part = parts[i];
  2935. if (part.length > 0) {
  2936. components = part.split('=');
  2937. name = decodeURIComponent(components[0]);
  2938. value = (components[1] !== undefined) ? decodeURIComponent(components[1]) : '';
  2939. if (!recursive) {
  2940. if (object.hasOwnProperty(name)) {
  2941. if (!Ext.isArray(object[name])) {
  2942. object[name] = [object[name]];
  2943. }
  2944. object[name].push(value);
  2945. }
  2946. else {
  2947. object[name] = value;
  2948. }
  2949. }
  2950. else {
  2951. matchedKeys = name.match(/(\[):?([^\]]*)\]/g);
  2952. matchedName = name.match(/^([^\[]+)/);
  2953. name = matchedName[0];
  2954. keys = [];
  2955. if (matchedKeys === null) {
  2956. object[name] = value;
  2957. continue;
  2958. }
  2959. for (j = 0, subLn = matchedKeys.length; j < subLn; j++) {
  2960. key = matchedKeys[j];
  2961. key = (key.length === 2) ? '' : key.substring(1, key.length - 1);
  2962. keys.push(key);
  2963. }
  2964. keys.unshift(name);
  2965. temp = object;
  2966. for (j = 0, subLn = keys.length; j < subLn; j++) {
  2967. key = keys[j];
  2968. if (j === subLn - 1) {
  2969. if (Ext.isArray(temp) && key === '') {
  2970. temp.push(value);
  2971. }
  2972. else {
  2973. temp[key] = value;
  2974. }
  2975. }
  2976. else {
  2977. if (temp[key] === undefined || typeof temp[key] === 'string') {
  2978. nextKey = keys[j+1];
  2979. temp[key] = (Ext.isNumeric(nextKey) || nextKey === '') ? [] : {};
  2980. }
  2981. temp = temp[key];
  2982. }
  2983. }
  2984. }
  2985. }
  2986. }
  2987. return object;
  2988. },
  2989. /**
  2990. * Iterates through an object and invokes the given callback function for each iteration.
  2991. * The iteration can be stopped by returning `false` in the callback function. For example:
  2992. *
  2993. * var person = {
  2994. * name: 'Jacky'
  2995. * hairColor: 'black'
  2996. * loves: ['food', 'sleeping', 'wife']
  2997. * };
  2998. *
  2999. * Ext.Object.each(person, function(key, value, myself) {
  3000. * console.log(key + ":" + value);
  3001. *
  3002. * if (key === 'hairColor') {
  3003. * return false; // stop the iteration
  3004. * }
  3005. * });
  3006. *
  3007. * @param {Object} object The object to iterate
  3008. * @param {Function} fn The callback function.
  3009. * @param {String} fn.key
  3010. * @param {Object} fn.value
  3011. * @param {Object} fn.object The object itself
  3012. * @param {Object} [scope] The execution scope (`this`) of the callback function
  3013. */
  3014. each: function(object, fn, scope) {
  3015. for (var property in object) {
  3016. if (object.hasOwnProperty(property)) {
  3017. if (fn.call(scope || object, property, object[property], object) === false) {
  3018. return;
  3019. }
  3020. }
  3021. }
  3022. },
  3023. /**
  3024. * Merges any number of objects recursively without referencing them or their children.
  3025. *
  3026. * var extjs = {
  3027. * companyName: 'Ext JS',
  3028. * products: ['Ext JS', 'Ext GWT', 'Ext Designer'],
  3029. * isSuperCool: true,
  3030. * office: {
  3031. * size: 2000,
  3032. * location: 'Palo Alto',
  3033. * isFun: true
  3034. * }
  3035. * };
  3036. *
  3037. * var newStuff = {
  3038. * companyName: 'Sencha Inc.',
  3039. * products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'],
  3040. * office: {
  3041. * size: 40000,
  3042. * location: 'Redwood City'
  3043. * }
  3044. * };
  3045. *
  3046. * var sencha = Ext.Object.merge(extjs, newStuff);
  3047. *
  3048. * // extjs and sencha then equals to
  3049. * {
  3050. * companyName: 'Sencha Inc.',
  3051. * products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'],
  3052. * isSuperCool: true,
  3053. * office: {
  3054. * size: 40000,
  3055. * location: 'Redwood City'
  3056. * isFun: true
  3057. * }
  3058. * }
  3059. *
  3060. * @param {Object...} object Any number of objects to merge.
  3061. * @return {Object} merged The object that is created as a result of merging all the objects passed in.
  3062. */
  3063. merge: function(source) {
  3064. var i = 1,
  3065. ln = arguments.length,
  3066. mergeFn = ExtObject.merge,
  3067. cloneFn = Ext.clone,
  3068. object, key, value, sourceKey;
  3069. for (; i < ln; i++) {
  3070. object = arguments[i];
  3071. for (key in object) {
  3072. value = object[key];
  3073. if (value && value.constructor === Object) {
  3074. sourceKey = source[key];
  3075. if (sourceKey && sourceKey.constructor === Object) {
  3076. mergeFn(sourceKey, value);
  3077. }
  3078. else {
  3079. source[key] = cloneFn(value);
  3080. }
  3081. }
  3082. else {
  3083. source[key] = value;
  3084. }
  3085. }
  3086. }
  3087. return source;
  3088. },
  3089. /**
  3090. * @private
  3091. * @param source
  3092. */
  3093. mergeIf: function(source) {
  3094. var i = 1,
  3095. ln = arguments.length,
  3096. cloneFn = Ext.clone,
  3097. object, key, value;
  3098. for (; i < ln; i++) {
  3099. object = arguments[i];
  3100. for (key in object) {
  3101. if (!(key in source)) {
  3102. value = object[key];
  3103. if (value && value.constructor === Object) {
  3104. source[key] = cloneFn(value);
  3105. }
  3106. else {
  3107. source[key] = value;
  3108. }
  3109. }
  3110. }
  3111. }
  3112. return source;
  3113. },
  3114. /**
  3115. * Returns the first matching key corresponding to the given value.
  3116. * If no matching value is found, null is returned.
  3117. *
  3118. * var person = {
  3119. * name: 'Jacky',
  3120. * loves: 'food'
  3121. * };
  3122. *
  3123. * alert(Ext.Object.getKey(person, 'food')); // alerts 'loves'
  3124. *
  3125. * @param {Object} object
  3126. * @param {Object} value The value to find
  3127. */
  3128. getKey: function(object, value) {
  3129. for (var property in object) {
  3130. if (object.hasOwnProperty(property) && object[property] === value) {
  3131. return property;
  3132. }
  3133. }
  3134. return null;
  3135. },
  3136. /**
  3137. * Gets all values of the given object as an array.
  3138. *
  3139. * var values = Ext.Object.getValues({
  3140. * name: 'Jacky',
  3141. * loves: 'food'
  3142. * }); // ['Jacky', 'food']
  3143. *
  3144. * @param {Object} object
  3145. * @return {Array} An array of values from the object
  3146. */
  3147. getValues: function(object) {
  3148. var values = [],
  3149. property;
  3150. for (property in object) {
  3151. if (object.hasOwnProperty(property)) {
  3152. values.push(object[property]);
  3153. }
  3154. }
  3155. return values;
  3156. },
  3157. /**
  3158. * Gets all keys of the given object as an array.
  3159. *
  3160. * var values = Ext.Object.getKeys({
  3161. * name: 'Jacky',
  3162. * loves: 'food'
  3163. * }); // ['name', 'loves']
  3164. *
  3165. * @param {Object} object
  3166. * @return {String[]} An array of keys from the object
  3167. * @method
  3168. */
  3169. getKeys: (typeof Object.keys == 'function')
  3170. ? function(object){
  3171. if (!object) {
  3172. return [];
  3173. }
  3174. return Object.keys(object);
  3175. }
  3176. : function(object) {
  3177. var keys = [],
  3178. property;
  3179. for (property in object) {
  3180. if (object.hasOwnProperty(property)) {
  3181. keys.push(property);
  3182. }
  3183. }
  3184. return keys;
  3185. },
  3186. /**
  3187. * Gets the total number of this object's own properties
  3188. *
  3189. * var size = Ext.Object.getSize({
  3190. * name: 'Jacky',
  3191. * loves: 'food'
  3192. * }); // size equals 2
  3193. *
  3194. * @param {Object} object
  3195. * @return {Number} size
  3196. */
  3197. getSize: function(object) {
  3198. var size = 0,
  3199. property;
  3200. for (property in object) {
  3201. if (object.hasOwnProperty(property)) {
  3202. size++;
  3203. }
  3204. }
  3205. return size;
  3206. },
  3207. /**
  3208. * @private
  3209. */
  3210. classify: function(object) {
  3211. var prototype = object,
  3212. objectProperties = [],
  3213. propertyClassesMap = {},
  3214. objectClass = function() {
  3215. var i = 0,
  3216. ln = objectProperties.length,
  3217. property;
  3218. for (; i < ln; i++) {
  3219. property = objectProperties[i];
  3220. this[property] = new propertyClassesMap[property];
  3221. }
  3222. },
  3223. key, value;
  3224. for (key in object) {
  3225. if (object.hasOwnProperty(key)) {
  3226. value = object[key];
  3227. if (value && value.constructor === Object) {
  3228. objectProperties.push(key);
  3229. propertyClassesMap[key] = ExtObject.classify(value);
  3230. }
  3231. }
  3232. }
  3233. objectClass.prototype = prototype;
  3234. return objectClass;
  3235. }
  3236. };
  3237. /**
  3238. * A convenient alias method for {@link Ext.Object#merge}.
  3239. *
  3240. * @member Ext
  3241. * @method merge
  3242. * @inheritdoc Ext.Object#merge
  3243. */
  3244. Ext.merge = Ext.Object.merge;
  3245. /**
  3246. * @private
  3247. */
  3248. Ext.mergeIf = Ext.Object.mergeIf;
  3249. /**
  3250. *
  3251. * @member Ext
  3252. * @method urlEncode
  3253. * @inheritdoc Ext.Object#toQueryString
  3254. * @deprecated 4.0.0 Use {@link Ext.Object#toQueryString} instead
  3255. */
  3256. Ext.urlEncode = function() {
  3257. var args = Ext.Array.from(arguments),
  3258. prefix = '';
  3259. // Support for the old `pre` argument
  3260. if ((typeof args[1] === 'string')) {
  3261. prefix = args[1] + '&';
  3262. args[1] = false;
  3263. }
  3264. return prefix + ExtObject.toQueryString.apply(ExtObject, args);
  3265. };
  3266. /**
  3267. * Alias for {@link Ext.Object#fromQueryString}.
  3268. *
  3269. * @member Ext
  3270. * @method urlDecode
  3271. * @inheritdoc Ext.Object#fromQueryString
  3272. * @deprecated 4.0.0 Use {@link Ext.Object#fromQueryString} instead
  3273. */
  3274. Ext.urlDecode = function() {
  3275. return ExtObject.fromQueryString.apply(ExtObject, arguments);
  3276. };
  3277. })();
  3278. //<localeInfo useApply="true" />
  3279. /**
  3280. * @class Ext.Date
  3281. * A set of useful static methods to deal with date
  3282. * Note that if Ext.Date is required and loaded, it will copy all methods / properties to
  3283. * this object for convenience
  3284. *
  3285. * The date parsing and formatting syntax contains a subset of
  3286. * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
  3287. * supported will provide results equivalent to their PHP versions.
  3288. *
  3289. * The following is a list of all currently supported formats:
  3290. * <pre class="">
  3291. Format Description Example returned values
  3292. ------ ----------------------------------------------------------------------- -----------------------
  3293. d Day of the month, 2 digits with leading zeros 01 to 31
  3294. D A short textual representation of the day of the week Mon to Sun
  3295. j Day of the month without leading zeros 1 to 31
  3296. l A full textual representation of the day of the week Sunday to Saturday
  3297. N ISO-8601 numeric representation of the day of the week 1 (for Monday) through 7 (for Sunday)
  3298. S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
  3299. w Numeric representation of the day of the week 0 (for Sunday) to 6 (for Saturday)
  3300. z The day of the year (starting from 0) 0 to 364 (365 in leap years)
  3301. W ISO-8601 week number of year, weeks starting on Monday 01 to 53
  3302. F A full textual representation of a month, such as January or March January to December
  3303. m Numeric representation of a month, with leading zeros 01 to 12
  3304. M A short textual representation of a month Jan to Dec
  3305. n Numeric representation of a month, without leading zeros 1 to 12
  3306. t Number of days in the given month 28 to 31
  3307. L Whether it&#39;s a leap year 1 if it is a leap year, 0 otherwise.
  3308. o ISO-8601 year number (identical to (Y), but if the ISO week number (W) Examples: 1998 or 2004
  3309. belongs to the previous or next year, that year is used instead)
  3310. Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
  3311. y A two digit representation of a year Examples: 99 or 03
  3312. a Lowercase Ante meridiem and Post meridiem am or pm
  3313. A Uppercase Ante meridiem and Post meridiem AM or PM
  3314. g 12-hour format of an hour without leading zeros 1 to 12
  3315. G 24-hour format of an hour without leading zeros 0 to 23
  3316. h 12-hour format of an hour with leading zeros 01 to 12
  3317. H 24-hour format of an hour with leading zeros 00 to 23
  3318. i Minutes, with leading zeros 00 to 59
  3319. s Seconds, with leading zeros 00 to 59
  3320. u Decimal fraction of a second Examples:
  3321. (minimum 1 digit, arbitrary number of digits allowed) 001 (i.e. 0.001s) or
  3322. 100 (i.e. 0.100s) or
  3323. 999 (i.e. 0.999s) or
  3324. 999876543210 (i.e. 0.999876543210s)
  3325. O Difference to Greenwich time (GMT) in hours and minutes Example: +1030
  3326. P Difference to Greenwich time (GMT) with colon between hours and minutes Example: -08:00
  3327. T Timezone abbreviation of the machine running the code Examples: EST, MDT, PDT ...
  3328. Z Timezone offset in seconds (negative if west of UTC, positive if east) -43200 to 50400
  3329. c ISO 8601 date
  3330. Notes: Examples:
  3331. 1) If unspecified, the month / day defaults to the current month / day, 1991 or
  3332. the time defaults to midnight, while the timezone defaults to the 1992-10 or
  3333. browser's timezone. If a time is specified, it must include both hours 1993-09-20 or
  3334. and minutes. The "T" delimiter, seconds, milliseconds and timezone 1994-08-19T16:20+01:00 or
  3335. are optional. 1995-07-18T17:21:28-02:00 or
  3336. 2) The decimal fraction of a second, if specified, must contain at 1996-06-17T18:22:29.98765+03:00 or
  3337. least 1 digit (there is no limit to the maximum number 1997-05-16T19:23:30,12345-0400 or
  3338. of digits allowed), and may be delimited by either a '.' or a ',' 1998-04-15T20:24:31.2468Z or
  3339. Refer to the examples on the right for the various levels of 1999-03-14T20:24:32Z or
  3340. date-time granularity which are supported, or see 2000-02-13T21:25:33
  3341. http://www.w3.org/TR/NOTE-datetime for more info. 2001-01-12 22:26:34
  3342. U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) 1193432466 or -2138434463
  3343. MS Microsoft AJAX serialized dates \/Date(1238606590509)\/ (i.e. UTC milliseconds since epoch) or
  3344. \/Date(1238606590509+0800)\/
  3345. </pre>
  3346. *
  3347. * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
  3348. * <pre><code>
  3349. // Sample date:
  3350. // 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
  3351. var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
  3352. console.log(Ext.Date.format(dt, 'Y-m-d')); // 2007-01-10
  3353. console.log(Ext.Date.format(dt, 'F j, Y, g:i a')); // January 10, 2007, 3:05 pm
  3354. console.log(Ext.Date.format(dt, 'l, \\t\\he jS \\of F Y h:i:s A')); // Wednesday, the 10th of January 2007 03:05:01 PM
  3355. </code></pre>
  3356. *
  3357. * Here are some standard date/time patterns that you might find helpful. They
  3358. * are not part of the source of Ext.Date, but to use them you can simply copy this
  3359. * block of code into any script that is included after Ext.Date and they will also become
  3360. * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
  3361. * <pre><code>
  3362. Ext.Date.patterns = {
  3363. ISO8601Long:"Y-m-d H:i:s",
  3364. ISO8601Short:"Y-m-d",
  3365. ShortDate: "n/j/Y",
  3366. LongDate: "l, F d, Y",
  3367. FullDateTime: "l, F d, Y g:i:s A",
  3368. MonthDay: "F d",
  3369. ShortTime: "g:i A",
  3370. LongTime: "g:i:s A",
  3371. SortableDateTime: "Y-m-d\\TH:i:s",
  3372. UniversalSortableDateTime: "Y-m-d H:i:sO",
  3373. YearMonth: "F, Y"
  3374. };
  3375. </code></pre>
  3376. *
  3377. * Example usage:
  3378. * <pre><code>
  3379. var dt = new Date();
  3380. console.log(Ext.Date.format(dt, Ext.Date.patterns.ShortDate));
  3381. </code></pre>
  3382. * <p>Developer-written, custom formats may be used by supplying both a formatting and a parsing function
  3383. * which perform to specialized requirements. The functions are stored in {@link #parseFunctions} and {@link #formatFunctions}.</p>
  3384. * @singleton
  3385. */
  3386. /*
  3387. * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
  3388. * (see http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/)
  3389. * They generate precompiled functions from format patterns instead of parsing and
  3390. * processing each pattern every time a date is formatted. These functions are available
  3391. * on every Date object.
  3392. */
  3393. (function() {
  3394. // create private copy of Ext's Ext.util.Format.format() method
  3395. // - to remove unnecessary dependency
  3396. // - to resolve namespace conflict with MS-Ajax's implementation
  3397. function xf(format) {
  3398. var args = Array.prototype.slice.call(arguments, 1);
  3399. return format.replace(/\{(\d+)\}/g, function(m, i) {
  3400. return args[i];
  3401. });
  3402. }
  3403. Ext.Date = {
  3404. /**
  3405. * Returns the current timestamp
  3406. * @return {Number} The current timestamp
  3407. * @method
  3408. */
  3409. now: Date.now || function() {
  3410. return +new Date();
  3411. },
  3412. /**
  3413. * @private
  3414. * Private for now
  3415. */
  3416. toString: function(date) {
  3417. var pad = Ext.String.leftPad;
  3418. return date.getFullYear() + "-"
  3419. + pad(date.getMonth() + 1, 2, '0') + "-"
  3420. + pad(date.getDate(), 2, '0') + "T"
  3421. + pad(date.getHours(), 2, '0') + ":"
  3422. + pad(date.getMinutes(), 2, '0') + ":"
  3423. + pad(date.getSeconds(), 2, '0');
  3424. },
  3425. /**
  3426. * Returns the number of milliseconds between two dates
  3427. * @param {Date} dateA The first date
  3428. * @param {Date} dateB (optional) The second date, defaults to now
  3429. * @return {Number} The difference in milliseconds
  3430. */
  3431. getElapsed: function(dateA, dateB) {
  3432. return Math.abs(dateA - (dateB || new Date()));
  3433. },
  3434. /**
  3435. * Global flag which determines if strict date parsing should be used.
  3436. * Strict date parsing will not roll-over invalid dates, which is the
  3437. * default behaviour of javascript Date objects.
  3438. * (see {@link #parse} for more information)
  3439. * Defaults to <tt>false</tt>.
  3440. * @type Boolean
  3441. */
  3442. useStrict: false,
  3443. // private
  3444. formatCodeToRegex: function(character, currentGroup) {
  3445. // Note: currentGroup - position in regex result array (see notes for Ext.Date.parseCodes below)
  3446. var p = utilDate.parseCodes[character];
  3447. if (p) {
  3448. p = typeof p == 'function'? p() : p;
  3449. utilDate.parseCodes[character] = p; // reassign function result to prevent repeated execution
  3450. }
  3451. return p ? Ext.applyIf({
  3452. c: p.c ? xf(p.c, currentGroup || "{0}") : p.c
  3453. }, p) : {
  3454. g: 0,
  3455. c: null,
  3456. s: Ext.String.escapeRegex(character) // treat unrecognised characters as literals
  3457. };
  3458. },
  3459. /**
  3460. * <p>An object hash in which each property is a date parsing function. The property name is the
  3461. * format string which that function parses.</p>
  3462. * <p>This object is automatically populated with date parsing functions as
  3463. * date formats are requested for Ext standard formatting strings.</p>
  3464. * <p>Custom parsing functions may be inserted into this object, keyed by a name which from then on
  3465. * may be used as a format string to {@link #parse}.<p>
  3466. * <p>Example:</p><pre><code>
  3467. Ext.Date.parseFunctions['x-date-format'] = myDateParser;
  3468. </code></pre>
  3469. * <p>A parsing function should return a Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
  3470. * <li><code>date</code> : String<div class="sub-desc">The date string to parse.</div></li>
  3471. * <li><code>strict</code> : Boolean<div class="sub-desc">True to validate date strings while parsing
  3472. * (i.e. prevent javascript Date "rollover") (The default must be false).
  3473. * Invalid date strings should return null when parsed.</div></li>
  3474. * </ul></div></p>
  3475. * <p>To enable Dates to also be <i>formatted</i> according to that format, a corresponding
  3476. * formatting function must be placed into the {@link #formatFunctions} property.
  3477. * @property parseFunctions
  3478. * @type Object
  3479. */
  3480. parseFunctions: {
  3481. "MS": function(input, strict) {
  3482. // note: the timezone offset is ignored since the MS Ajax server sends
  3483. // a UTC milliseconds-since-Unix-epoch value (negative values are allowed)
  3484. var re = new RegExp('\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/');
  3485. var r = (input || '').match(re);
  3486. return r? new Date(((r[1] || '') + r[2]) * 1) : null;
  3487. }
  3488. },
  3489. parseRegexes: [],
  3490. /**
  3491. * <p>An object hash in which each property is a date formatting function. The property name is the
  3492. * format string which corresponds to the produced formatted date string.</p>
  3493. * <p>This object is automatically populated with date formatting functions as
  3494. * date formats are requested for Ext standard formatting strings.</p>
  3495. * <p>Custom formatting functions may be inserted into this object, keyed by a name which from then on
  3496. * may be used as a format string to {@link #format}. Example:</p><pre><code>
  3497. Ext.Date.formatFunctions['x-date-format'] = myDateFormatter;
  3498. </code></pre>
  3499. * <p>A formatting function should return a string representation of the passed Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
  3500. * <li><code>date</code> : Date<div class="sub-desc">The Date to format.</div></li>
  3501. * </ul></div></p>
  3502. * <p>To enable date strings to also be <i>parsed</i> according to that format, a corresponding
  3503. * parsing function must be placed into the {@link #parseFunctions} property.
  3504. * @property formatFunctions
  3505. * @type Object
  3506. */
  3507. formatFunctions: {
  3508. "MS": function() {
  3509. // UTC milliseconds since Unix epoch (MS-AJAX serialized date format (MRSF))
  3510. return '\\/Date(' + this.getTime() + ')\\/';
  3511. }
  3512. },
  3513. y2kYear : 50,
  3514. /**
  3515. * Date interval constant
  3516. * @type String
  3517. */
  3518. MILLI : "ms",
  3519. /**
  3520. * Date interval constant
  3521. * @type String
  3522. */
  3523. SECOND : "s",
  3524. /**
  3525. * Date interval constant
  3526. * @type String
  3527. */
  3528. MINUTE : "mi",
  3529. /** Date interval constant
  3530. * @type String
  3531. */
  3532. HOUR : "h",
  3533. /**
  3534. * Date interval constant
  3535. * @type String
  3536. */
  3537. DAY : "d",
  3538. /**
  3539. * Date interval constant
  3540. * @type String
  3541. */
  3542. MONTH : "mo",
  3543. /**
  3544. * Date interval constant
  3545. * @type String
  3546. */
  3547. YEAR : "y",
  3548. /**
  3549. * <p>An object hash containing default date values used during date parsing.</p>
  3550. * <p>The following properties are available:<div class="mdetail-params"><ul>
  3551. * <li><code>y</code> : Number<div class="sub-desc">The default year value. (defaults to undefined)</div></li>
  3552. * <li><code>m</code> : Number<div class="sub-desc">The default 1-based month value. (defaults to undefined)</div></li>
  3553. * <li><code>d</code> : Number<div class="sub-desc">The default day value. (defaults to undefined)</div></li>
  3554. * <li><code>h</code> : Number<div class="sub-desc">The default hour value. (defaults to undefined)</div></li>
  3555. * <li><code>i</code> : Number<div class="sub-desc">The default minute value. (defaults to undefined)</div></li>
  3556. * <li><code>s</code> : Number<div class="sub-desc">The default second value. (defaults to undefined)</div></li>
  3557. * <li><code>ms</code> : Number<div class="sub-desc">The default millisecond value. (defaults to undefined)</div></li>
  3558. * </ul></div></p>
  3559. * <p>Override these properties to customize the default date values used by the {@link #parse} method.</p>
  3560. * <p><b>Note: In countries which experience Daylight Saving Time (i.e. DST), the <tt>h</tt>, <tt>i</tt>, <tt>s</tt>
  3561. * and <tt>ms</tt> properties may coincide with the exact time in which DST takes effect.
  3562. * It is the responsiblity of the developer to account for this.</b></p>
  3563. * Example Usage:
  3564. * <pre><code>
  3565. // set default day value to the first day of the month
  3566. Ext.Date.defaults.d = 1;
  3567. // parse a February date string containing only year and month values.
  3568. // setting the default day value to 1 prevents weird date rollover issues
  3569. // when attempting to parse the following date string on, for example, March 31st 2009.
  3570. Ext.Date.parse('2009-02', 'Y-m'); // returns a Date object representing February 1st 2009
  3571. </code></pre>
  3572. * @property defaults
  3573. * @type Object
  3574. */
  3575. defaults: {},
  3576. /**
  3577. * @property {String[]} dayNames
  3578. * An array of textual day names.
  3579. * Override these values for international dates.
  3580. * Example:
  3581. * <pre><code>
  3582. Ext.Date.dayNames = [
  3583. 'SundayInYourLang',
  3584. 'MondayInYourLang',
  3585. ...
  3586. ];
  3587. </code></pre>
  3588. */
  3589. //<locale type="array">
  3590. dayNames : [
  3591. "Sunday",
  3592. "Monday",
  3593. "Tuesday",
  3594. "Wednesday",
  3595. "Thursday",
  3596. "Friday",
  3597. "Saturday"
  3598. ],
  3599. //</locale>
  3600. /**
  3601. * @property {String[]} monthNames
  3602. * An array of textual month names.
  3603. * Override these values for international dates.
  3604. * Example:
  3605. * <pre><code>
  3606. Ext.Date.monthNames = [
  3607. 'JanInYourLang',
  3608. 'FebInYourLang',
  3609. ...
  3610. ];
  3611. </code></pre>
  3612. */
  3613. //<locale type="array">
  3614. monthNames : [
  3615. "January",
  3616. "February",
  3617. "March",
  3618. "April",
  3619. "May",
  3620. "June",
  3621. "July",
  3622. "August",
  3623. "September",
  3624. "October",
  3625. "November",
  3626. "December"
  3627. ],
  3628. //</locale>
  3629. /**
  3630. * @property {Object} monthNumbers
  3631. * An object hash of zero-based javascript month numbers (with short month names as keys. note: keys are case-sensitive).
  3632. * Override these values for international dates.
  3633. * Example:
  3634. * <pre><code>
  3635. Ext.Date.monthNumbers = {
  3636. 'ShortJanNameInYourLang':0,
  3637. 'ShortFebNameInYourLang':1,
  3638. ...
  3639. };
  3640. </code></pre>
  3641. */
  3642. //<locale type="object">
  3643. monthNumbers : {
  3644. Jan:0,
  3645. Feb:1,
  3646. Mar:2,
  3647. Apr:3,
  3648. May:4,
  3649. Jun:5,
  3650. Jul:6,
  3651. Aug:7,
  3652. Sep:8,
  3653. Oct:9,
  3654. Nov:10,
  3655. Dec:11
  3656. },
  3657. //</locale>
  3658. /**
  3659. * @property {String} defaultFormat
  3660. * <p>The date format string that the {@link Ext.util.Format#dateRenderer}
  3661. * and {@link Ext.util.Format#date} functions use. See {@link Ext.Date} for details.</p>
  3662. * <p>This may be overridden in a locale file.</p>
  3663. */
  3664. //<locale>
  3665. defaultFormat : "m/d/Y",
  3666. //</locale>
  3667. /**
  3668. * Get the short month name for the given month number.
  3669. * Override this function for international dates.
  3670. * @param {Number} month A zero-based javascript month number.
  3671. * @return {String} The short month name.
  3672. */
  3673. //<locale type="function">
  3674. getShortMonthName : function(month) {
  3675. return Ext.Date.monthNames[month].substring(0, 3);
  3676. },
  3677. //</locale>
  3678. /**
  3679. * Get the short day name for the given day number.
  3680. * Override this function for international dates.
  3681. * @param {Number} day A zero-based javascript day number.
  3682. * @return {String} The short day name.
  3683. */
  3684. //<locale type="function">
  3685. getShortDayName : function(day) {
  3686. return Ext.Date.dayNames[day].substring(0, 3);
  3687. },
  3688. //</locale>
  3689. /**
  3690. * Get the zero-based javascript month number for the given short/full month name.
  3691. * Override this function for international dates.
  3692. * @param {String} name The short/full month name.
  3693. * @return {Number} The zero-based javascript month number.
  3694. */
  3695. //<locale type="function">
  3696. getMonthNumber : function(name) {
  3697. // handle camel casing for english month names (since the keys for the Ext.Date.monthNumbers hash are case sensitive)
  3698. return Ext.Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()];
  3699. },
  3700. //</locale>
  3701. /**
  3702. * Checks if the specified format contains hour information
  3703. * @param {String} format The format to check
  3704. * @return {Boolean} True if the format contains hour information
  3705. * @method
  3706. */
  3707. formatContainsHourInfo : (function(){
  3708. var stripEscapeRe = /(\\.)/g,
  3709. hourInfoRe = /([gGhHisucUOPZ]|MS)/;
  3710. return function(format){
  3711. return hourInfoRe.test(format.replace(stripEscapeRe, ''));
  3712. };
  3713. })(),
  3714. /**
  3715. * Checks if the specified format contains information about
  3716. * anything other than the time.
  3717. * @param {String} format The format to check
  3718. * @return {Boolean} True if the format contains information about
  3719. * date/day information.
  3720. * @method
  3721. */
  3722. formatContainsDateInfo : (function(){
  3723. var stripEscapeRe = /(\\.)/g,
  3724. dateInfoRe = /([djzmnYycU]|MS)/;
  3725. return function(format){
  3726. return dateInfoRe.test(format.replace(stripEscapeRe, ''));
  3727. };
  3728. })(),
  3729. /**
  3730. * The base format-code to formatting-function hashmap used by the {@link #format} method.
  3731. * Formatting functions are strings (or functions which return strings) which
  3732. * will return the appropriate value when evaluated in the context of the Date object
  3733. * from which the {@link #format} method is called.
  3734. * Add to / override these mappings for custom date formatting.
  3735. * Note: Ext.Date.format() treats characters as literals if an appropriate mapping cannot be found.
  3736. * Example:
  3737. * <pre><code>
  3738. Ext.Date.formatCodes.x = "Ext.util.Format.leftPad(this.getDate(), 2, '0')";
  3739. console.log(Ext.Date.format(new Date(), 'X'); // returns the current day of the month
  3740. </code></pre>
  3741. * @type Object
  3742. */
  3743. formatCodes : {
  3744. d: "Ext.String.leftPad(this.getDate(), 2, '0')",
  3745. D: "Ext.Date.getShortDayName(this.getDay())", // get localised short day name
  3746. j: "this.getDate()",
  3747. l: "Ext.Date.dayNames[this.getDay()]",
  3748. N: "(this.getDay() ? this.getDay() : 7)",
  3749. S: "Ext.Date.getSuffix(this)",
  3750. w: "this.getDay()",
  3751. z: "Ext.Date.getDayOfYear(this)",
  3752. W: "Ext.String.leftPad(Ext.Date.getWeekOfYear(this), 2, '0')",
  3753. F: "Ext.Date.monthNames[this.getMonth()]",
  3754. m: "Ext.String.leftPad(this.getMonth() + 1, 2, '0')",
  3755. M: "Ext.Date.getShortMonthName(this.getMonth())", // get localised short month name
  3756. n: "(this.getMonth() + 1)",
  3757. t: "Ext.Date.getDaysInMonth(this)",
  3758. L: "(Ext.Date.isLeapYear(this) ? 1 : 0)",
  3759. o: "(this.getFullYear() + (Ext.Date.getWeekOfYear(this) == 1 && this.getMonth() > 0 ? +1 : (Ext.Date.getWeekOfYear(this) >= 52 && this.getMonth() < 11 ? -1 : 0)))",
  3760. Y: "Ext.String.leftPad(this.getFullYear(), 4, '0')",
  3761. y: "('' + this.getFullYear()).substring(2, 4)",
  3762. a: "(this.getHours() < 12 ? 'am' : 'pm')",
  3763. A: "(this.getHours() < 12 ? 'AM' : 'PM')",
  3764. g: "((this.getHours() % 12) ? this.getHours() % 12 : 12)",
  3765. G: "this.getHours()",
  3766. h: "Ext.String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')",
  3767. H: "Ext.String.leftPad(this.getHours(), 2, '0')",
  3768. i: "Ext.String.leftPad(this.getMinutes(), 2, '0')",
  3769. s: "Ext.String.leftPad(this.getSeconds(), 2, '0')",
  3770. u: "Ext.String.leftPad(this.getMilliseconds(), 3, '0')",
  3771. O: "Ext.Date.getGMTOffset(this)",
  3772. P: "Ext.Date.getGMTOffset(this, true)",
  3773. T: "Ext.Date.getTimezone(this)",
  3774. Z: "(this.getTimezoneOffset() * -60)",
  3775. c: function() { // ISO-8601 -- GMT format
  3776. for (var c = "Y-m-dTH:i:sP", code = [], i = 0, l = c.length; i < l; ++i) {
  3777. var e = c.charAt(i);
  3778. code.push(e == "T" ? "'T'" : utilDate.getFormatCode(e)); // treat T as a character literal
  3779. }
  3780. return code.join(" + ");
  3781. },
  3782. /*
  3783. c: function() { // ISO-8601 -- UTC format
  3784. return [
  3785. "this.getUTCFullYear()", "'-'",
  3786. "Ext.util.Format.leftPad(this.getUTCMonth() + 1, 2, '0')", "'-'",
  3787. "Ext.util.Format.leftPad(this.getUTCDate(), 2, '0')",
  3788. "'T'",
  3789. "Ext.util.Format.leftPad(this.getUTCHours(), 2, '0')", "':'",
  3790. "Ext.util.Format.leftPad(this.getUTCMinutes(), 2, '0')", "':'",
  3791. "Ext.util.Format.leftPad(this.getUTCSeconds(), 2, '0')",
  3792. "'Z'"
  3793. ].join(" + ");
  3794. },
  3795. */
  3796. U: "Math.round(this.getTime() / 1000)"
  3797. },
  3798. /**
  3799. * Checks if the passed Date parameters will cause a javascript Date "rollover".
  3800. * @param {Number} year 4-digit year
  3801. * @param {Number} month 1-based month-of-year
  3802. * @param {Number} day Day of month
  3803. * @param {Number} hour (optional) Hour
  3804. * @param {Number} minute (optional) Minute
  3805. * @param {Number} second (optional) Second
  3806. * @param {Number} millisecond (optional) Millisecond
  3807. * @return {Boolean} true if the passed parameters do not cause a Date "rollover", false otherwise.
  3808. */
  3809. isValid : function(y, m, d, h, i, s, ms) {
  3810. // setup defaults
  3811. h = h || 0;
  3812. i = i || 0;
  3813. s = s || 0;
  3814. ms = ms || 0;
  3815. // Special handling for year < 100
  3816. var dt = utilDate.add(new Date(y < 100 ? 100 : y, m - 1, d, h, i, s, ms), utilDate.YEAR, y < 100 ? y - 100 : 0);
  3817. return y == dt.getFullYear() &&
  3818. m == dt.getMonth() + 1 &&
  3819. d == dt.getDate() &&
  3820. h == dt.getHours() &&
  3821. i == dt.getMinutes() &&
  3822. s == dt.getSeconds() &&
  3823. ms == dt.getMilliseconds();
  3824. },
  3825. /**
  3826. * Parses the passed string using the specified date format.
  3827. * Note that this function expects normal calendar dates, meaning that months are 1-based (i.e. 1 = January).
  3828. * The {@link #defaults} hash will be used for any date value (i.e. year, month, day, hour, minute, second or millisecond)
  3829. * which cannot be found in the passed string. If a corresponding default date value has not been specified in the {@link #defaults} hash,
  3830. * the current date's year, month, day or DST-adjusted zero-hour time value will be used instead.
  3831. * Keep in mind that the input date string must precisely match the specified format string
  3832. * in order for the parse operation to be successful (failed parse operations return a null value).
  3833. * <p>Example:</p><pre><code>
  3834. //dt = Fri May 25 2007 (current date)
  3835. var dt = new Date();
  3836. //dt = Thu May 25 2006 (today&#39;s month/day in 2006)
  3837. dt = Ext.Date.parse("2006", "Y");
  3838. //dt = Sun Jan 15 2006 (all date parts specified)
  3839. dt = Ext.Date.parse("2006-01-15", "Y-m-d");
  3840. //dt = Sun Jan 15 2006 15:20:01
  3841. dt = Ext.Date.parse("2006-01-15 3:20:01 PM", "Y-m-d g:i:s A");
  3842. // attempt to parse Sun Feb 29 2006 03:20:01 in strict mode
  3843. dt = Ext.Date.parse("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
  3844. </code></pre>
  3845. * @param {String} input The raw date string.
  3846. * @param {String} format The expected date string format.
  3847. * @param {Boolean} strict (optional) True to validate date strings while parsing (i.e. prevents javascript Date "rollover")
  3848. (defaults to false). Invalid date strings will return null when parsed.
  3849. * @return {Date} The parsed Date.
  3850. */
  3851. parse : function(input, format, strict) {
  3852. var p = utilDate.parseFunctions;
  3853. if (p[format] == null) {
  3854. utilDate.createParser(format);
  3855. }
  3856. return p[format](input, Ext.isDefined(strict) ? strict : utilDate.useStrict);
  3857. },
  3858. // Backwards compat
  3859. parseDate: function(input, format, strict){
  3860. return utilDate.parse(input, format, strict);
  3861. },
  3862. // private
  3863. getFormatCode : function(character) {
  3864. var f = utilDate.formatCodes[character];
  3865. if (f) {
  3866. f = typeof f == 'function'? f() : f;
  3867. utilDate.formatCodes[character] = f; // reassign function result to prevent repeated execution
  3868. }
  3869. // note: unknown characters are treated as literals
  3870. return f || ("'" + Ext.String.escape(character) + "'");
  3871. },
  3872. // private
  3873. createFormat : function(format) {
  3874. var code = [],
  3875. special = false,
  3876. ch = '';
  3877. for (var i = 0; i < format.length; ++i) {
  3878. ch = format.charAt(i);
  3879. if (!special && ch == "\\") {
  3880. special = true;
  3881. } else if (special) {
  3882. special = false;
  3883. code.push("'" + Ext.String.escape(ch) + "'");
  3884. } else {
  3885. code.push(utilDate.getFormatCode(ch));
  3886. }
  3887. }
  3888. utilDate.formatFunctions[format] = Ext.functionFactory("return " + code.join('+'));
  3889. },
  3890. // private
  3891. createParser : (function() {
  3892. var code = [
  3893. "var dt, y, m, d, h, i, s, ms, o, z, zz, u, v,",
  3894. "def = Ext.Date.defaults,",
  3895. "results = String(input).match(Ext.Date.parseRegexes[{0}]);", // either null, or an array of matched strings
  3896. "if(results){",
  3897. "{1}",
  3898. "if(u != null){", // i.e. unix time is defined
  3899. "v = new Date(u * 1000);", // give top priority to UNIX time
  3900. "}else{",
  3901. // create Date object representing midnight of the current day;
  3902. // this will provide us with our date defaults
  3903. // (note: clearTime() handles Daylight Saving Time automatically)
  3904. "dt = Ext.Date.clearTime(new Date);",
  3905. // date calculations (note: these calculations create a dependency on Ext.Number.from())
  3906. "y = Ext.Number.from(y, Ext.Number.from(def.y, dt.getFullYear()));",
  3907. "m = Ext.Number.from(m, Ext.Number.from(def.m - 1, dt.getMonth()));",
  3908. "d = Ext.Number.from(d, Ext.Number.from(def.d, dt.getDate()));",
  3909. // time calculations (note: these calculations create a dependency on Ext.Number.from())
  3910. "h = Ext.Number.from(h, Ext.Number.from(def.h, dt.getHours()));",
  3911. "i = Ext.Number.from(i, Ext.Number.from(def.i, dt.getMinutes()));",
  3912. "s = Ext.Number.from(s, Ext.Number.from(def.s, dt.getSeconds()));",
  3913. "ms = Ext.Number.from(ms, Ext.Number.from(def.ms, dt.getMilliseconds()));",
  3914. "if(z >= 0 && y >= 0){",
  3915. // both the year and zero-based day of year are defined and >= 0.
  3916. // these 2 values alone provide sufficient info to create a full date object
  3917. // create Date object representing January 1st for the given year
  3918. // handle years < 100 appropriately
  3919. "v = Ext.Date.add(new Date(y < 100 ? 100 : y, 0, 1, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
  3920. // then add day of year, checking for Date "rollover" if necessary
  3921. "v = !strict? v : (strict === true && (z <= 364 || (Ext.Date.isLeapYear(v) && z <= 365))? Ext.Date.add(v, Ext.Date.DAY, z) : null);",
  3922. "}else if(strict === true && !Ext.Date.isValid(y, m + 1, d, h, i, s, ms)){", // check for Date "rollover"
  3923. "v = null;", // invalid date, so return null
  3924. "}else{",
  3925. // plain old Date object
  3926. // handle years < 100 properly
  3927. "v = Ext.Date.add(new Date(y < 100 ? 100 : y, m, d, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
  3928. "}",
  3929. "}",
  3930. "}",
  3931. "if(v){",
  3932. // favour UTC offset over GMT offset
  3933. "if(zz != null){",
  3934. // reset to UTC, then add offset
  3935. "v = Ext.Date.add(v, Ext.Date.SECOND, -v.getTimezoneOffset() * 60 - zz);",
  3936. "}else if(o){",
  3937. // reset to GMT, then add offset
  3938. "v = Ext.Date.add(v, Ext.Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));",
  3939. "}",
  3940. "}",
  3941. "return v;"
  3942. ].join('\n');
  3943. return function(format) {
  3944. var regexNum = utilDate.parseRegexes.length,
  3945. currentGroup = 1,
  3946. calc = [],
  3947. regex = [],
  3948. special = false,
  3949. ch = "",
  3950. i = 0,
  3951. len = format.length,
  3952. atEnd = [],
  3953. obj;
  3954. for (; i < len; ++i) {
  3955. ch = format.charAt(i);
  3956. if (!special && ch == "\\") {
  3957. special = true;
  3958. } else if (special) {
  3959. special = false;
  3960. regex.push(Ext.String.escape(ch));
  3961. } else {
  3962. obj = utilDate.formatCodeToRegex(ch, currentGroup);
  3963. currentGroup += obj.g;
  3964. regex.push(obj.s);
  3965. if (obj.g && obj.c) {
  3966. if (obj.calcAtEnd) {
  3967. atEnd.push(obj.c);
  3968. } else {
  3969. calc.push(obj.c);
  3970. }
  3971. }
  3972. }
  3973. }
  3974. calc = calc.concat(atEnd);
  3975. utilDate.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$", 'i');
  3976. utilDate.parseFunctions[format] = Ext.functionFactory("input", "strict", xf(code, regexNum, calc.join('')));
  3977. };
  3978. })(),
  3979. // private
  3980. parseCodes : {
  3981. /*
  3982. * Notes:
  3983. * g = {Number} calculation group (0 or 1. only group 1 contributes to date calculations.)
  3984. * c = {String} calculation method (required for group 1. null for group 0. {0} = currentGroup - position in regex result array)
  3985. * s = {String} regex pattern. all matches are stored in results[], and are accessible by the calculation mapped to 'c'
  3986. */
  3987. d: {
  3988. g:1,
  3989. c:"d = parseInt(results[{0}], 10);\n",
  3990. s:"(3[0-1]|[1-2][0-9]|0[1-9])" // day of month with leading zeroes (01 - 31)
  3991. },
  3992. j: {
  3993. g:1,
  3994. c:"d = parseInt(results[{0}], 10);\n",
  3995. s:"(3[0-1]|[1-2][0-9]|[1-9])" // day of month without leading zeroes (1 - 31)
  3996. },
  3997. D: function() {
  3998. for (var a = [], i = 0; i < 7; a.push(utilDate.getShortDayName(i)), ++i); // get localised short day names
  3999. return {
  4000. g:0,
  4001. c:null,
  4002. s:"(?:" + a.join("|") +")"
  4003. };
  4004. },
  4005. l: function() {
  4006. return {
  4007. g:0,
  4008. c:null,
  4009. s:"(?:" + utilDate.dayNames.join("|") + ")"
  4010. };
  4011. },
  4012. N: {
  4013. g:0,
  4014. c:null,
  4015. s:"[1-7]" // ISO-8601 day number (1 (monday) - 7 (sunday))
  4016. },
  4017. //<locale type="object" property="parseCodes">
  4018. S: {
  4019. g:0,
  4020. c:null,
  4021. s:"(?:st|nd|rd|th)"
  4022. },
  4023. //</locale>
  4024. w: {
  4025. g:0,
  4026. c:null,
  4027. s:"[0-6]" // javascript day number (0 (sunday) - 6 (saturday))
  4028. },
  4029. z: {
  4030. g:1,
  4031. c:"z = parseInt(results[{0}], 10);\n",
  4032. s:"(\\d{1,3})" // day of the year (0 - 364 (365 in leap years))
  4033. },
  4034. W: {
  4035. g:0,
  4036. c:null,
  4037. s:"(?:\\d{2})" // ISO-8601 week number (with leading zero)
  4038. },
  4039. F: function() {
  4040. return {
  4041. g:1,
  4042. c:"m = parseInt(Ext.Date.getMonthNumber(results[{0}]), 10);\n", // get localised month number
  4043. s:"(" + utilDate.monthNames.join("|") + ")"
  4044. };
  4045. },
  4046. M: function() {
  4047. for (var a = [], i = 0; i < 12; a.push(utilDate.getShortMonthName(i)), ++i); // get localised short month names
  4048. return Ext.applyIf({
  4049. s:"(" + a.join("|") + ")"
  4050. }, utilDate.formatCodeToRegex("F"));
  4051. },
  4052. m: {
  4053. g:1,
  4054. c:"m = parseInt(results[{0}], 10) - 1;\n",
  4055. s:"(1[0-2]|0[1-9])" // month number with leading zeros (01 - 12)
  4056. },
  4057. n: {
  4058. g:1,
  4059. c:"m = parseInt(results[{0}], 10) - 1;\n",
  4060. s:"(1[0-2]|[1-9])" // month number without leading zeros (1 - 12)
  4061. },
  4062. t: {
  4063. g:0,
  4064. c:null,
  4065. s:"(?:\\d{2})" // no. of days in the month (28 - 31)
  4066. },
  4067. L: {
  4068. g:0,
  4069. c:null,
  4070. s:"(?:1|0)"
  4071. },
  4072. o: function() {
  4073. return utilDate.formatCodeToRegex("Y");
  4074. },
  4075. Y: {
  4076. g:1,
  4077. c:"y = parseInt(results[{0}], 10);\n",
  4078. s:"(\\d{4})" // 4-digit year
  4079. },
  4080. y: {
  4081. g:1,
  4082. c:"var ty = parseInt(results[{0}], 10);\n"
  4083. + "y = ty > Ext.Date.y2kYear ? 1900 + ty : 2000 + ty;\n", // 2-digit year
  4084. s:"(\\d{1,2})"
  4085. },
  4086. /*
  4087. * In the am/pm parsing routines, we allow both upper and lower case
  4088. * even though it doesn't exactly match the spec. It gives much more flexibility
  4089. * in being able to specify case insensitive regexes.
  4090. */
  4091. a: {
  4092. g:1,
  4093. c:"if (/(am)/i.test(results[{0}])) {\n"
  4094. + "if (!h || h == 12) { h = 0; }\n"
  4095. + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
  4096. s:"(am|pm|AM|PM)",
  4097. calcAtEnd: true
  4098. },
  4099. A: {
  4100. g:1,
  4101. c:"if (/(am)/i.test(results[{0}])) {\n"
  4102. + "if (!h || h == 12) { h = 0; }\n"
  4103. + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
  4104. s:"(AM|PM|am|pm)",
  4105. calcAtEnd: true
  4106. },
  4107. g: {
  4108. g:1,
  4109. c:"h = parseInt(results[{0}], 10);\n",
  4110. s:"(1[0-2]|[0-9])" // 12-hr format of an hour without leading zeroes (1 - 12)
  4111. },
  4112. G: {
  4113. g:1,
  4114. c:"h = parseInt(results[{0}], 10);\n",
  4115. s:"(2[0-3]|1[0-9]|[0-9])" // 24-hr format of an hour without leading zeroes (0 - 23)
  4116. },
  4117. h: {
  4118. g:1,
  4119. c:"h = parseInt(results[{0}], 10);\n",
  4120. s:"(1[0-2]|0[1-9])" // 12-hr format of an hour with leading zeroes (01 - 12)
  4121. },
  4122. H: {
  4123. g:1,
  4124. c:"h = parseInt(results[{0}], 10);\n",
  4125. s:"(2[0-3]|[0-1][0-9])" // 24-hr format of an hour with leading zeroes (00 - 23)
  4126. },
  4127. i: {
  4128. g:1,
  4129. c:"i = parseInt(results[{0}], 10);\n",
  4130. s:"([0-5][0-9])" // minutes with leading zeros (00 - 59)
  4131. },
  4132. s: {
  4133. g:1,
  4134. c:"s = parseInt(results[{0}], 10);\n",
  4135. s:"([0-5][0-9])" // seconds with leading zeros (00 - 59)
  4136. },
  4137. u: {
  4138. g:1,
  4139. c:"ms = results[{0}]; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n",
  4140. s:"(\\d+)" // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
  4141. },
  4142. O: {
  4143. g:1,
  4144. c:[
  4145. "o = results[{0}];",
  4146. "var sn = o.substring(0,1),", // get + / - sign
  4147. "hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
  4148. "mn = o.substring(3,5) % 60;", // get minutes
  4149. "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.String.leftPad(hr, 2, '0') + Ext.String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs
  4150. ].join("\n"),
  4151. s: "([+\-]\\d{4})" // GMT offset in hrs and mins
  4152. },
  4153. P: {
  4154. g:1,
  4155. c:[
  4156. "o = results[{0}];",
  4157. "var sn = o.substring(0,1),", // get + / - sign
  4158. "hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
  4159. "mn = o.substring(4,6) % 60;", // get minutes
  4160. "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.String.leftPad(hr, 2, '0') + Ext.String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs
  4161. ].join("\n"),
  4162. s: "([+\-]\\d{2}:\\d{2})" // GMT offset in hrs and mins (with colon separator)
  4163. },
  4164. T: {
  4165. g:0,
  4166. c:null,
  4167. s:"[A-Z]{1,4}" // timezone abbrev. may be between 1 - 4 chars
  4168. },
  4169. Z: {
  4170. g:1,
  4171. c:"zz = results[{0}] * 1;\n" // -43200 <= UTC offset <= 50400
  4172. + "zz = (-43200 <= zz && zz <= 50400)? zz : null;\n",
  4173. s:"([+\-]?\\d{1,5})" // leading '+' sign is optional for UTC offset
  4174. },
  4175. c: function() {
  4176. var calc = [],
  4177. arr = [
  4178. utilDate.formatCodeToRegex("Y", 1), // year
  4179. utilDate.formatCodeToRegex("m", 2), // month
  4180. utilDate.formatCodeToRegex("d", 3), // day
  4181. utilDate.formatCodeToRegex("H", 4), // hour
  4182. utilDate.formatCodeToRegex("i", 5), // minute
  4183. utilDate.formatCodeToRegex("s", 6), // second
  4184. {c:"ms = results[7] || '0'; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n"}, // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
  4185. {c:[ // allow either "Z" (i.e. UTC) or "-0530" or "+08:00" (i.e. UTC offset) timezone delimiters. assumes local timezone if no timezone is specified
  4186. "if(results[8]) {", // timezone specified
  4187. "if(results[8] == 'Z'){",
  4188. "zz = 0;", // UTC
  4189. "}else if (results[8].indexOf(':') > -1){",
  4190. utilDate.formatCodeToRegex("P", 8).c, // timezone offset with colon separator
  4191. "}else{",
  4192. utilDate.formatCodeToRegex("O", 8).c, // timezone offset without colon separator
  4193. "}",
  4194. "}"
  4195. ].join('\n')}
  4196. ];
  4197. for (var i = 0, l = arr.length; i < l; ++i) {
  4198. calc.push(arr[i].c);
  4199. }
  4200. return {
  4201. g:1,
  4202. c:calc.join(""),
  4203. s:[
  4204. arr[0].s, // year (required)
  4205. "(?:", "-", arr[1].s, // month (optional)
  4206. "(?:", "-", arr[2].s, // day (optional)
  4207. "(?:",
  4208. "(?:T| )?", // time delimiter -- either a "T" or a single blank space
  4209. arr[3].s, ":", arr[4].s, // hour AND minute, delimited by a single colon (optional). MUST be preceded by either a "T" or a single blank space
  4210. "(?::", arr[5].s, ")?", // seconds (optional)
  4211. "(?:(?:\\.|,)(\\d+))?", // decimal fraction of a second (e.g. ",12345" or ".98765") (optional)
  4212. "(Z|(?:[-+]\\d{2}(?::)?\\d{2}))?", // "Z" (UTC) or "-0530" (UTC offset without colon delimiter) or "+08:00" (UTC offset with colon delimiter) (optional)
  4213. ")?",
  4214. ")?",
  4215. ")?"
  4216. ].join("")
  4217. };
  4218. },
  4219. U: {
  4220. g:1,
  4221. c:"u = parseInt(results[{0}], 10);\n",
  4222. s:"(-?\\d+)" // leading minus sign indicates seconds before UNIX epoch
  4223. }
  4224. },
  4225. //Old Ext.Date prototype methods.
  4226. // private
  4227. dateFormat: function(date, format) {
  4228. return utilDate.format(date, format);
  4229. },
  4230. /**
  4231. * Compares if two dates are equal by comparing their values.
  4232. * @param {Date} date1
  4233. * @param {Date} date2
  4234. * @return {Boolean} True if the date values are equal
  4235. */
  4236. isEqual: function(date1, date2) {
  4237. // check we have 2 date objects
  4238. if (date1 && date2) {
  4239. return (date1.getTime() === date2.getTime());
  4240. }
  4241. // one or both isn't a date, only equal if both are falsey
  4242. return !(date1 || date2);
  4243. },
  4244. /**
  4245. * Formats a date given the supplied format string.
  4246. * @param {Date} date The date to format
  4247. * @param {String} format The format string
  4248. * @return {String} The formatted date
  4249. */
  4250. format: function(date, format) {
  4251. if (utilDate.formatFunctions[format] == null) {
  4252. utilDate.createFormat(format);
  4253. }
  4254. var result = utilDate.formatFunctions[format].call(date);
  4255. return result + '';
  4256. },
  4257. /**
  4258. * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
  4259. *
  4260. * Note: The date string returned by the javascript Date object's toString() method varies
  4261. * between browsers (e.g. FF vs IE) and system region settings (e.g. IE in Asia vs IE in America).
  4262. * For a given date string e.g. "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)",
  4263. * getTimezone() first tries to get the timezone abbreviation from between a pair of parentheses
  4264. * (which may or may not be present), failing which it proceeds to get the timezone abbreviation
  4265. * from the GMT offset portion of the date string.
  4266. * @param {Date} date The date
  4267. * @return {String} The abbreviated timezone name (e.g. 'CST', 'PDT', 'EDT', 'MPST' ...).
  4268. */
  4269. getTimezone : function(date) {
  4270. // the following list shows the differences between date strings from different browsers on a WinXP SP2 machine from an Asian locale:
  4271. //
  4272. // Opera : "Thu, 25 Oct 2007 22:53:45 GMT+0800" -- shortest (weirdest) date string of the lot
  4273. // Safari : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone (same as FF)
  4274. // FF : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone
  4275. // IE : "Thu Oct 25 22:54:35 UTC+0800 2007" -- (Asian system setting) look for 3-4 letter timezone abbrev
  4276. // IE : "Thu Oct 25 17:06:37 PDT 2007" -- (American system setting) look for 3-4 letter timezone abbrev
  4277. //
  4278. // this crazy regex attempts to guess the correct timezone abbreviation despite these differences.
  4279. // step 1: (?:\((.*)\) -- find timezone in parentheses
  4280. // step 2: ([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?) -- if nothing was found in step 1, find timezone from timezone offset portion of date string
  4281. // step 3: remove all non uppercase characters found in step 1 and 2
  4282. return date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, "");
  4283. },
  4284. /**
  4285. * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
  4286. * @param {Date} date The date
  4287. * @param {Boolean} colon (optional) true to separate the hours and minutes with a colon (defaults to false).
  4288. * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600').
  4289. */
  4290. getGMTOffset : function(date, colon) {
  4291. var offset = date.getTimezoneOffset();
  4292. return (offset > 0 ? "-" : "+")
  4293. + Ext.String.leftPad(Math.floor(Math.abs(offset) / 60), 2, "0")
  4294. + (colon ? ":" : "")
  4295. + Ext.String.leftPad(Math.abs(offset % 60), 2, "0");
  4296. },
  4297. /**
  4298. * Get the numeric day number of the year, adjusted for leap year.
  4299. * @param {Date} date The date
  4300. * @return {Number} 0 to 364 (365 in leap years).
  4301. */
  4302. getDayOfYear: function(date) {
  4303. var num = 0,
  4304. d = Ext.Date.clone(date),
  4305. m = date.getMonth(),
  4306. i;
  4307. for (i = 0, d.setDate(1), d.setMonth(0); i < m; d.setMonth(++i)) {
  4308. num += utilDate.getDaysInMonth(d);
  4309. }
  4310. return num + date.getDate() - 1;
  4311. },
  4312. /**
  4313. * Get the numeric ISO-8601 week number of the year.
  4314. * (equivalent to the format specifier 'W', but without a leading zero).
  4315. * @param {Date} date The date
  4316. * @return {Number} 1 to 53
  4317. * @method
  4318. */
  4319. getWeekOfYear : (function() {
  4320. // adapted from http://www.merlyn.demon.co.uk/weekcalc.htm
  4321. var ms1d = 864e5, // milliseconds in a day
  4322. ms7d = 7 * ms1d; // milliseconds in a week
  4323. return function(date) { // return a closure so constants get calculated only once
  4324. var DC3 = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate() + 3) / ms1d, // an Absolute Day Number
  4325. AWN = Math.floor(DC3 / 7), // an Absolute Week Number
  4326. Wyr = new Date(AWN * ms7d).getUTCFullYear();
  4327. return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1;
  4328. };
  4329. })(),
  4330. /**
  4331. * Checks if the current date falls within a leap year.
  4332. * @param {Date} date The date
  4333. * @return {Boolean} True if the current date falls within a leap year, false otherwise.
  4334. */
  4335. isLeapYear : function(date) {
  4336. var year = date.getFullYear();
  4337. return !!((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
  4338. },
  4339. /**
  4340. * Get the first day of the current month, adjusted for leap year. The returned value
  4341. * is the numeric day index within the week (0-6) which can be used in conjunction with
  4342. * the {@link #monthNames} array to retrieve the textual day name.
  4343. * Example:
  4344. * <pre><code>
  4345. var dt = new Date('1/10/2007'),
  4346. firstDay = Ext.Date.getFirstDayOfMonth(dt);
  4347. console.log(Ext.Date.dayNames[firstDay]); //output: 'Monday'
  4348. * </code></pre>
  4349. * @param {Date} date The date
  4350. * @return {Number} The day number (0-6).
  4351. */
  4352. getFirstDayOfMonth : function(date) {
  4353. var day = (date.getDay() - (date.getDate() - 1)) % 7;
  4354. return (day < 0) ? (day + 7) : day;
  4355. },
  4356. /**
  4357. * Get the last day of the current month, adjusted for leap year. The returned value
  4358. * is the numeric day index within the week (0-6) which can be used in conjunction with
  4359. * the {@link #monthNames} array to retrieve the textual day name.
  4360. * Example:
  4361. * <pre><code>
  4362. var dt = new Date('1/10/2007'),
  4363. lastDay = Ext.Date.getLastDayOfMonth(dt);
  4364. console.log(Ext.Date.dayNames[lastDay]); //output: 'Wednesday'
  4365. * </code></pre>
  4366. * @param {Date} date The date
  4367. * @return {Number} The day number (0-6).
  4368. */
  4369. getLastDayOfMonth : function(date) {
  4370. return utilDate.getLastDateOfMonth(date).getDay();
  4371. },
  4372. /**
  4373. * Get the date of the first day of the month in which this date resides.
  4374. * @param {Date} date The date
  4375. * @return {Date}
  4376. */
  4377. getFirstDateOfMonth : function(date) {
  4378. return new Date(date.getFullYear(), date.getMonth(), 1);
  4379. },
  4380. /**
  4381. * Get the date of the last day of the month in which this date resides.
  4382. * @param {Date} date The date
  4383. * @return {Date}
  4384. */
  4385. getLastDateOfMonth : function(date) {
  4386. return new Date(date.getFullYear(), date.getMonth(), utilDate.getDaysInMonth(date));
  4387. },
  4388. /**
  4389. * Get the number of days in the current month, adjusted for leap year.
  4390. * @param {Date} date The date
  4391. * @return {Number} The number of days in the month.
  4392. * @method
  4393. */
  4394. getDaysInMonth: (function() {
  4395. var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  4396. return function(date) { // return a closure for efficiency
  4397. var m = date.getMonth();
  4398. return m == 1 && utilDate.isLeapYear(date) ? 29 : daysInMonth[m];
  4399. };
  4400. })(),
  4401. /**
  4402. * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
  4403. * @param {Date} date The date
  4404. * @return {String} 'st, 'nd', 'rd' or 'th'.
  4405. */
  4406. //<locale type="function">
  4407. getSuffix : function(date) {
  4408. switch (date.getDate()) {
  4409. case 1:
  4410. case 21:
  4411. case 31:
  4412. return "st";
  4413. case 2:
  4414. case 22:
  4415. return "nd";
  4416. case 3:
  4417. case 23:
  4418. return "rd";
  4419. default:
  4420. return "th";
  4421. }
  4422. },
  4423. //</locale>
  4424. /**
  4425. * Creates and returns a new Date instance with the exact same date value as the called instance.
  4426. * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
  4427. * variable will also be changed. When the intention is to create a new variable that will not
  4428. * modify the original instance, you should create a clone.
  4429. *
  4430. * Example of correctly cloning a date:
  4431. * <pre><code>
  4432. //wrong way:
  4433. var orig = new Date('10/1/2006');
  4434. var copy = orig;
  4435. copy.setDate(5);
  4436. console.log(orig); //returns 'Thu Oct 05 2006'!
  4437. //correct way:
  4438. var orig = new Date('10/1/2006'),
  4439. copy = Ext.Date.clone(orig);
  4440. copy.setDate(5);
  4441. console.log(orig); //returns 'Thu Oct 01 2006'
  4442. * </code></pre>
  4443. * @param {Date} date The date
  4444. * @return {Date} The new Date instance.
  4445. */
  4446. clone : function(date) {
  4447. return new Date(date.getTime());
  4448. },
  4449. /**
  4450. * Checks if the current date is affected by Daylight Saving Time (DST).
  4451. * @param {Date} date The date
  4452. * @return {Boolean} True if the current date is affected by DST.
  4453. */
  4454. isDST : function(date) {
  4455. // adapted from http://sencha.com/forum/showthread.php?p=247172#post247172
  4456. // courtesy of @geoffrey.mcgill
  4457. return new Date(date.getFullYear(), 0, 1).getTimezoneOffset() != date.getTimezoneOffset();
  4458. },
  4459. /**
  4460. * Attempts to clear all time information from this Date by setting the time to midnight of the same day,
  4461. * automatically adjusting for Daylight Saving Time (DST) where applicable.
  4462. * (note: DST timezone information for the browser's host operating system is assumed to be up-to-date)
  4463. * @param {Date} date The date
  4464. * @param {Boolean} clone true to create a clone of this date, clear the time and return it (defaults to false).
  4465. * @return {Date} this or the clone.
  4466. */
  4467. clearTime : function(date, clone) {
  4468. if (clone) {
  4469. return Ext.Date.clearTime(Ext.Date.clone(date));
  4470. }
  4471. // get current date before clearing time
  4472. var d = date.getDate();
  4473. // clear time
  4474. date.setHours(0);
  4475. date.setMinutes(0);
  4476. date.setSeconds(0);
  4477. date.setMilliseconds(0);
  4478. if (date.getDate() != d) { // account for DST (i.e. day of month changed when setting hour = 0)
  4479. // note: DST adjustments are assumed to occur in multiples of 1 hour (this is almost always the case)
  4480. // refer to http://www.timeanddate.com/time/aboutdst.html for the (rare) exceptions to this rule
  4481. // increment hour until cloned date == current date
  4482. for (var hr = 1, c = utilDate.add(date, Ext.Date.HOUR, hr); c.getDate() != d; hr++, c = utilDate.add(date, Ext.Date.HOUR, hr));
  4483. date.setDate(d);
  4484. date.setHours(c.getHours());
  4485. };
  4486. return date;
  4487. },
  4488. /**
  4489. * Provides a convenient method for performing basic date arithmetic. This method
  4490. * does not modify the Date instance being called - it creates and returns
  4491. * a new Date instance containing the resulting date value.
  4492. *
  4493. * Examples:
  4494. * <pre><code>
  4495. // Basic usage:
  4496. var dt = Ext.Date.add(new Date('10/29/2006'), Ext.Date.DAY, 5);
  4497. console.log(dt); //returns 'Fri Nov 03 2006 00:00:00'
  4498. // Negative values will be subtracted:
  4499. var dt2 = Ext.Date.add(new Date('10/1/2006'), Ext.Date.DAY, -5);
  4500. console.log(dt2); //returns 'Tue Sep 26 2006 00:00:00'
  4501. * </code></pre>
  4502. *
  4503. * @param {Date} date The date to modify
  4504. * @param {String} interval A valid date interval enum value.
  4505. * @param {Number} value The amount to add to the current date.
  4506. * @return {Date} The new Date instance.
  4507. */
  4508. add : function(date, interval, value) {
  4509. var d = Ext.Date.clone(date),
  4510. Date = Ext.Date;
  4511. if (!interval || value === 0) return d;
  4512. switch(interval.toLowerCase()) {
  4513. case Ext.Date.MILLI:
  4514. d.setMilliseconds(d.getMilliseconds() + value);
  4515. break;
  4516. case Ext.Date.SECOND:
  4517. d.setSeconds(d.getSeconds() + value);
  4518. break;
  4519. case Ext.Date.MINUTE:
  4520. d.setMinutes(d.getMinutes() + value);
  4521. break;
  4522. case Ext.Date.HOUR:
  4523. d.setHours(d.getHours() + value);
  4524. break;
  4525. case Ext.Date.DAY:
  4526. d.setDate(d.getDate() + value);
  4527. break;
  4528. case Ext.Date.MONTH:
  4529. var day = date.getDate();
  4530. if (day > 28) {
  4531. day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), Ext.Date.MONTH, value)).getDate());
  4532. }
  4533. d.setDate(day);
  4534. d.setMonth(date.getMonth() + value);
  4535. break;
  4536. case Ext.Date.YEAR:
  4537. var day = date.getDate();
  4538. if (day > 28) {
  4539. day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), Ext.Date.YEAR, value)).getDate());
  4540. }
  4541. d.setDate(day);
  4542. d.setFullYear(date.getFullYear() + value);
  4543. break;
  4544. }
  4545. return d;
  4546. },
  4547. /**
  4548. * Checks if a date falls on or between the given start and end dates.
  4549. * @param {Date} date The date to check
  4550. * @param {Date} start Start date
  4551. * @param {Date} end End date
  4552. * @return {Boolean} true if this date falls on or between the given start and end dates.
  4553. */
  4554. between : function(date, start, end) {
  4555. var t = date.getTime();
  4556. return start.getTime() <= t && t <= end.getTime();
  4557. },
  4558. //Maintains compatibility with old static and prototype window.Date methods.
  4559. compat: function() {
  4560. var nativeDate = window.Date,
  4561. p, u,
  4562. statics = ['useStrict', 'formatCodeToRegex', 'parseFunctions', 'parseRegexes', 'formatFunctions', 'y2kYear', 'MILLI', 'SECOND', 'MINUTE', 'HOUR', 'DAY', 'MONTH', 'YEAR', 'defaults', 'dayNames', 'monthNames', 'monthNumbers', 'getShortMonthName', 'getShortDayName', 'getMonthNumber', 'formatCodes', 'isValid', 'parseDate', 'getFormatCode', 'createFormat', 'createParser', 'parseCodes'],
  4563. proto = ['dateFormat', 'format', 'getTimezone', 'getGMTOffset', 'getDayOfYear', 'getWeekOfYear', 'isLeapYear', 'getFirstDayOfMonth', 'getLastDayOfMonth', 'getDaysInMonth', 'getSuffix', 'clone', 'isDST', 'clearTime', 'add', 'between'];
  4564. sLen = statics.length,
  4565. pLen = proto.length,
  4566. stat, prot, s;
  4567. //Append statics
  4568. for (s = 0; s < sLen; s++) {
  4569. stat = statics[s];
  4570. nativeDate[stat] = utilDate[stat];
  4571. }
  4572. //Append to prototype
  4573. for (p = 0; p < pLen; p++) {
  4574. prot = proto[p];
  4575. nativeDate.prototype[prot] = function() {
  4576. var args = Array.prototype.slice.call(arguments);
  4577. args.unshift(this);
  4578. return utilDate[prot].apply(utilDate, args);
  4579. };
  4580. }
  4581. }
  4582. };
  4583. var utilDate = Ext.Date;
  4584. })();
  4585. /**
  4586. * @author Jacky Nguyen <jacky@sencha.com>
  4587. * @docauthor Jacky Nguyen <jacky@sencha.com>
  4588. * @class Ext.Base
  4589. *
  4590. * The root of all classes created with {@link Ext#define}.
  4591. *
  4592. * Ext.Base is the building block of all Ext classes. All classes in Ext inherit from Ext.Base.
  4593. * All prototype and static members of this class are inherited by all other classes.
  4594. */
  4595. (function(flexSetter) {
  4596. var noArgs = [],
  4597. Base = function(){};
  4598. // This is the "$previous" method of a hook function on an instance. When called, it
  4599. // calls through the class prototype by the name of the called method.
  4600. function callHookParent () {
  4601. var method = callHookParent.caller.caller; // skip callParent (our caller)
  4602. return method.$owner.prototype[method.$name].apply(this, arguments);
  4603. }
  4604. // These static properties will be copied to every newly created class with {@link Ext#define}
  4605. Ext.apply(Base, {
  4606. $className: 'Ext.Base',
  4607. $isClass: true,
  4608. /**
  4609. * Create a new instance of this Class.
  4610. *
  4611. * Ext.define('My.cool.Class', {
  4612. * ...
  4613. * });
  4614. *
  4615. * My.cool.Class.create({
  4616. * someConfig: true
  4617. * });
  4618. *
  4619. * All parameters are passed to the constructor of the class.
  4620. *
  4621. * @return {Object} the created instance.
  4622. * @static
  4623. * @inheritable
  4624. */
  4625. create: function() {
  4626. return Ext.create.apply(Ext, [this].concat(Array.prototype.slice.call(arguments, 0)));
  4627. },
  4628. /**
  4629. * @private
  4630. * @param config
  4631. */
  4632. extend: function(parent) {
  4633. var parentPrototype = parent.prototype,
  4634. basePrototype, prototype, i, ln, name, statics;
  4635. prototype = this.prototype = Ext.Object.chain(parentPrototype);
  4636. prototype.self = this;
  4637. this.superclass = prototype.superclass = parentPrototype;
  4638. if (!parent.$isClass) {
  4639. basePrototype = Ext.Base.prototype;
  4640. for (i in basePrototype) {
  4641. if (i in prototype) {
  4642. prototype[i] = basePrototype[i];
  4643. }
  4644. }
  4645. }
  4646. // Statics inheritance
  4647. statics = parentPrototype.$inheritableStatics;
  4648. if (statics) {
  4649. for (i = 0,ln = statics.length; i < ln; i++) {
  4650. name = statics[i];
  4651. if (!this.hasOwnProperty(name)) {
  4652. this[name] = parent[name];
  4653. }
  4654. }
  4655. }
  4656. if (parent.$onExtended) {
  4657. this.$onExtended = parent.$onExtended.slice();
  4658. }
  4659. prototype.config = new prototype.configClass;
  4660. prototype.initConfigList = prototype.initConfigList.slice();
  4661. prototype.initConfigMap = Ext.clone(prototype.initConfigMap);
  4662. prototype.configMap = Ext.Object.chain(prototype.configMap);
  4663. },
  4664. /**
  4665. * @private
  4666. * @param config
  4667. */
  4668. '$onExtended': [],
  4669. /**
  4670. * @private
  4671. * @param config
  4672. */
  4673. triggerExtended: function() {
  4674. var callbacks = this.$onExtended,
  4675. ln = callbacks.length,
  4676. i, callback;
  4677. if (ln > 0) {
  4678. for (i = 0; i < ln; i++) {
  4679. callback = callbacks[i];
  4680. callback.fn.apply(callback.scope || this, arguments);
  4681. }
  4682. }
  4683. },
  4684. /**
  4685. * @private
  4686. * @param config
  4687. */
  4688. onExtended: function(fn, scope) {
  4689. this.$onExtended.push({
  4690. fn: fn,
  4691. scope: scope
  4692. });
  4693. return this;
  4694. },
  4695. /**
  4696. * @private
  4697. * @param config
  4698. */
  4699. addConfig: function(config, fullMerge) {
  4700. var prototype = this.prototype,
  4701. configNameCache = Ext.Class.configNameCache,
  4702. hasConfig = prototype.configMap,
  4703. initConfigList = prototype.initConfigList,
  4704. initConfigMap = prototype.initConfigMap,
  4705. defaultConfig = prototype.config,
  4706. initializedName, name, value;
  4707. for (name in config) {
  4708. if (config.hasOwnProperty(name)) {
  4709. if (!hasConfig[name]) {
  4710. hasConfig[name] = true;
  4711. }
  4712. value = config[name];
  4713. initializedName = configNameCache[name].initialized;
  4714. if (!initConfigMap[name] && value !== null && !prototype[initializedName]) {
  4715. initConfigMap[name] = true;
  4716. initConfigList.push(name);
  4717. }
  4718. }
  4719. }
  4720. if (fullMerge) {
  4721. Ext.merge(defaultConfig, config);
  4722. }
  4723. else {
  4724. Ext.mergeIf(defaultConfig, config);
  4725. }
  4726. prototype.configClass = Ext.Object.classify(defaultConfig);
  4727. },
  4728. /**
  4729. * Add / override static properties of this class.
  4730. *
  4731. * Ext.define('My.cool.Class', {
  4732. * ...
  4733. * });
  4734. *
  4735. * My.cool.Class.addStatics({
  4736. * someProperty: 'someValue', // My.cool.Class.someProperty = 'someValue'
  4737. * method1: function() { ... }, // My.cool.Class.method1 = function() { ... };
  4738. * method2: function() { ... } // My.cool.Class.method2 = function() { ... };
  4739. * });
  4740. *
  4741. * @param {Object} members
  4742. * @return {Ext.Base} this
  4743. * @static
  4744. * @inheritable
  4745. */
  4746. addStatics: function(members) {
  4747. var member, name;
  4748. for (name in members) {
  4749. if (members.hasOwnProperty(name)) {
  4750. member = members[name];
  4751. this[name] = member;
  4752. }
  4753. }
  4754. return this;
  4755. },
  4756. /**
  4757. * @private
  4758. * @param {Object} members
  4759. */
  4760. addInheritableStatics: function(members) {
  4761. var inheritableStatics,
  4762. hasInheritableStatics,
  4763. prototype = this.prototype,
  4764. name, member;
  4765. inheritableStatics = prototype.$inheritableStatics;
  4766. hasInheritableStatics = prototype.$hasInheritableStatics;
  4767. if (!inheritableStatics) {
  4768. inheritableStatics = prototype.$inheritableStatics = [];
  4769. hasInheritableStatics = prototype.$hasInheritableStatics = {};
  4770. }
  4771. for (name in members) {
  4772. if (members.hasOwnProperty(name)) {
  4773. member = members[name];
  4774. this[name] = member;
  4775. if (!hasInheritableStatics[name]) {
  4776. hasInheritableStatics[name] = true;
  4777. inheritableStatics.push(name);
  4778. }
  4779. }
  4780. }
  4781. return this;
  4782. },
  4783. /**
  4784. * Add methods / properties to the prototype of this class.
  4785. *
  4786. * Ext.define('My.awesome.Cat', {
  4787. * constructor: function() {
  4788. * ...
  4789. * }
  4790. * });
  4791. *
  4792. * My.awesome.Cat.implement({
  4793. * meow: function() {
  4794. * alert('Meowww...');
  4795. * }
  4796. * });
  4797. *
  4798. * var kitty = new My.awesome.Cat;
  4799. * kitty.meow();
  4800. *
  4801. * @param {Object} members
  4802. * @static
  4803. * @inheritable
  4804. */
  4805. addMembers: function(members) {
  4806. var prototype = this.prototype,
  4807. enumerables = Ext.enumerables,
  4808. names = [],
  4809. i, ln, name, member;
  4810. for (name in members) {
  4811. names.push(name);
  4812. }
  4813. if (enumerables) {
  4814. names.push.apply(names, enumerables);
  4815. }
  4816. for (i = 0,ln = names.length; i < ln; i++) {
  4817. name = names[i];
  4818. if (members.hasOwnProperty(name)) {
  4819. member = members[name];
  4820. if (typeof member == 'function' && !member.$isClass && member !== Ext.emptyFn) {
  4821. member.$owner = this;
  4822. member.$name = name;
  4823. }
  4824. prototype[name] = member;
  4825. }
  4826. }
  4827. return this;
  4828. },
  4829. /**
  4830. * @private
  4831. * @param name
  4832. * @param member
  4833. */
  4834. addMember: function(name, member) {
  4835. if (typeof member == 'function' && !member.$isClass && member !== Ext.emptyFn) {
  4836. member.$owner = this;
  4837. member.$name = name;
  4838. }
  4839. this.prototype[name] = member;
  4840. return this;
  4841. },
  4842. /**
  4843. * @private
  4844. */
  4845. implement: function() {
  4846. this.addMembers.apply(this, arguments);
  4847. },
  4848. /**
  4849. * Borrow another class' members to the prototype of this class.
  4850. *
  4851. * Ext.define('Bank', {
  4852. * money: '$$$',
  4853. * printMoney: function() {
  4854. * alert('$$$$$$$');
  4855. * }
  4856. * });
  4857. *
  4858. * Ext.define('Thief', {
  4859. * ...
  4860. * });
  4861. *
  4862. * Thief.borrow(Bank, ['money', 'printMoney']);
  4863. *
  4864. * var steve = new Thief();
  4865. *
  4866. * alert(steve.money); // alerts '$$$'
  4867. * steve.printMoney(); // alerts '$$$$$$$'
  4868. *
  4869. * @param {Ext.Base} fromClass The class to borrow members from
  4870. * @param {Array/String} members The names of the members to borrow
  4871. * @return {Ext.Base} this
  4872. * @static
  4873. * @inheritable
  4874. * @private
  4875. */
  4876. borrow: function(fromClass, members) {
  4877. var prototype = this.prototype,
  4878. fromPrototype = fromClass.prototype,
  4879. i, ln, name, fn, toBorrow;
  4880. members = Ext.Array.from(members);
  4881. for (i = 0,ln = members.length; i < ln; i++) {
  4882. name = members[i];
  4883. toBorrow = fromPrototype[name];
  4884. if (typeof toBorrow == 'function') {
  4885. fn = function() {
  4886. return toBorrow.apply(this, arguments);
  4887. };
  4888. fn.$owner = this;
  4889. fn.$name = name;
  4890. prototype[name] = fn;
  4891. }
  4892. else {
  4893. prototype[name] = toBorrow;
  4894. }
  4895. }
  4896. return this;
  4897. },
  4898. /**
  4899. * Override members of this class. Overridden methods can be invoked via
  4900. * {@link Ext.Base#callParent}.
  4901. *
  4902. * Ext.define('My.Cat', {
  4903. * constructor: function() {
  4904. * alert("I'm a cat!");
  4905. * }
  4906. * });
  4907. *
  4908. * My.Cat.override({
  4909. * constructor: function() {
  4910. * alert("I'm going to be a cat!");
  4911. *
  4912. * var instance = this.callParent(arguments);
  4913. *
  4914. * alert("Meeeeoooowwww");
  4915. *
  4916. * return instance;
  4917. * }
  4918. * });
  4919. *
  4920. * var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
  4921. * // alerts "I'm a cat!"
  4922. * // alerts "Meeeeoooowwww"
  4923. *
  4924. * As of 4.1, direct use of this method is deprecated. Use {@link Ext#define Ext.define}
  4925. * instead:
  4926. *
  4927. * Ext.define('My.CatOverride', {
  4928. * override: 'My.Cat',
  4929. * constructor: function() {
  4930. * alert("I'm going to be a cat!");
  4931. *
  4932. * var instance = this.callParent(arguments);
  4933. *
  4934. * alert("Meeeeoooowwww");
  4935. *
  4936. * return instance;
  4937. * }
  4938. * });
  4939. *
  4940. * The above accomplishes the same result but can be managed by the {@link Ext.Loader}
  4941. * which can properly order the override and its target class and the build process
  4942. * can determine whether the override is needed based on the required state of the
  4943. * target class (My.Cat).
  4944. *
  4945. * @param {Object} members The properties to add to this class. This should be
  4946. * specified as an object literal containing one or more properties.
  4947. * @return {Ext.Base} this class
  4948. * @static
  4949. * @inheritable
  4950. * @markdown
  4951. * @deprecated 4.1.0 Use {@link Ext#define Ext.define} instead
  4952. */
  4953. override: function(members) {
  4954. var me = this,
  4955. enumerables = Ext.enumerables,
  4956. target = me.prototype,
  4957. cloneFunction = Ext.Function.clone,
  4958. name, index, member, statics, names, previous;
  4959. if (arguments.length === 2) {
  4960. name = members;
  4961. members = {};
  4962. members[name] = arguments[1];
  4963. enumerables = null;
  4964. }
  4965. do {
  4966. names = []; // clean slate for prototype (1st pass) and static (2nd pass)
  4967. statics = null; // not needed 1st pass, but needs to be cleared for 2nd pass
  4968. for (name in members) { // hasOwnProperty is checked in the next loop...
  4969. if (name == 'statics') {
  4970. statics = members[name];
  4971. } else {
  4972. names.push(name);
  4973. }
  4974. }
  4975. if (enumerables) {
  4976. names.push.apply(names, enumerables);
  4977. }
  4978. for (index = names.length; index--; ) {
  4979. name = names[index];
  4980. if (members.hasOwnProperty(name)) {
  4981. member = members[name];
  4982. if (typeof member == 'function' && !member.$className && member !== Ext.emptyFn) {
  4983. if (typeof member.$owner != 'undefined') {
  4984. member = cloneFunction(member);
  4985. }
  4986. member.$owner = me;
  4987. member.$name = name;
  4988. previous = target[name];
  4989. if (previous) {
  4990. member.$previous = previous;
  4991. }
  4992. }
  4993. target[name] = member;
  4994. }
  4995. }
  4996. target = me; // 2nd pass is for statics
  4997. members = statics; // statics will be null on 2nd pass
  4998. } while (members);
  4999. return this;
  5000. },
  5001. // Documented downwards
  5002. callParent: function(args) {
  5003. var method;
  5004. // This code is intentionally inlined for the least number of debugger stepping
  5005. return (method = this.callParent.caller) && (method.$previous ||
  5006. ((method = method.$owner ? method : method.caller) &&
  5007. method.$owner.superclass.$class[method.$name])).apply(this, args || noArgs);
  5008. },
  5009. /**
  5010. * Used internally by the mixins pre-processor
  5011. * @private
  5012. * @inheritable
  5013. */
  5014. mixin: function(name, mixinClass) {
  5015. var mixin = mixinClass.prototype,
  5016. prototype = this.prototype,
  5017. key;
  5018. if (typeof mixin.onClassMixedIn != 'undefined') {
  5019. mixin.onClassMixedIn.call(mixinClass, this);
  5020. }
  5021. if (!prototype.hasOwnProperty('mixins')) {
  5022. if ('mixins' in prototype) {
  5023. prototype.mixins = Ext.Object.chain(prototype.mixins);
  5024. }
  5025. else {
  5026. prototype.mixins = {};
  5027. }
  5028. }
  5029. for (key in mixin) {
  5030. if (key === 'mixins') {
  5031. Ext.merge(prototype.mixins, mixin[key]);
  5032. }
  5033. else if (typeof prototype[key] == 'undefined' && key != 'mixinId' && key != 'config') {
  5034. prototype[key] = mixin[key];
  5035. }
  5036. }
  5037. if ('config' in mixin) {
  5038. this.addConfig(mixin.config, false);
  5039. }
  5040. prototype.mixins[name] = mixin;
  5041. },
  5042. /**
  5043. * Get the current class' name in string format.
  5044. *
  5045. * Ext.define('My.cool.Class', {
  5046. * constructor: function() {
  5047. * alert(this.self.getName()); // alerts 'My.cool.Class'
  5048. * }
  5049. * });
  5050. *
  5051. * My.cool.Class.getName(); // 'My.cool.Class'
  5052. *
  5053. * @return {String} className
  5054. * @static
  5055. * @inheritable
  5056. */
  5057. getName: function() {
  5058. return Ext.getClassName(this);
  5059. },
  5060. /**
  5061. * Create aliases for existing prototype methods. Example:
  5062. *
  5063. * Ext.define('My.cool.Class', {
  5064. * method1: function() { ... },
  5065. * method2: function() { ... }
  5066. * });
  5067. *
  5068. * var test = new My.cool.Class();
  5069. *
  5070. * My.cool.Class.createAlias({
  5071. * method3: 'method1',
  5072. * method4: 'method2'
  5073. * });
  5074. *
  5075. * test.method3(); // test.method1()
  5076. *
  5077. * My.cool.Class.createAlias('method5', 'method3');
  5078. *
  5079. * test.method5(); // test.method3() -> test.method1()
  5080. *
  5081. * @param {String/Object} alias The new method name, or an object to set multiple aliases. See
  5082. * {@link Ext.Function#flexSetter flexSetter}
  5083. * @param {String/Object} origin The original method name
  5084. * @static
  5085. * @inheritable
  5086. * @method
  5087. */
  5088. createAlias: flexSetter(function(alias, origin) {
  5089. this.override(alias, function() {
  5090. return this[origin].apply(this, arguments);
  5091. });
  5092. }),
  5093. /**
  5094. * @private
  5095. */
  5096. addXtype: function(xtype) {
  5097. var prototype = this.prototype,
  5098. xtypesMap = prototype.xtypesMap,
  5099. xtypes = prototype.xtypes,
  5100. xtypesChain = prototype.xtypesChain;
  5101. if (!prototype.hasOwnProperty('xtypesMap')) {
  5102. xtypesMap = prototype.xtypesMap = Ext.merge({}, prototype.xtypesMap || {});
  5103. xtypes = prototype.xtypes = prototype.xtypes ? [].concat(prototype.xtypes) : [];
  5104. xtypesChain = prototype.xtypesChain = prototype.xtypesChain ? [].concat(prototype.xtypesChain) : [];
  5105. prototype.xtype = xtype;
  5106. }
  5107. if (!xtypesMap[xtype]) {
  5108. xtypesMap[xtype] = true;
  5109. xtypes.push(xtype);
  5110. xtypesChain.push(xtype);
  5111. Ext.ClassManager.setAlias(this, 'widget.' + xtype);
  5112. }
  5113. return this;
  5114. }
  5115. });
  5116. Base.implement({
  5117. isInstance: true,
  5118. $className: 'Ext.Base',
  5119. configClass: Ext.emptyFn,
  5120. initConfigList: [],
  5121. configMap: {},
  5122. initConfigMap: {},
  5123. /**
  5124. * Get the reference to the class from which this object was instantiated. Note that unlike {@link Ext.Base#self},
  5125. * `this.statics()` is scope-independent and it always returns the class from which it was called, regardless of what
  5126. * `this` points to during run-time
  5127. *
  5128. * Ext.define('My.Cat', {
  5129. * statics: {
  5130. * totalCreated: 0,
  5131. * speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
  5132. * },
  5133. *
  5134. * constructor: function() {
  5135. * var statics = this.statics();
  5136. *
  5137. * alert(statics.speciesName); // always equals to 'Cat' no matter what 'this' refers to
  5138. * // equivalent to: My.Cat.speciesName
  5139. *
  5140. * alert(this.self.speciesName); // dependent on 'this'
  5141. *
  5142. * statics.totalCreated++;
  5143. * },
  5144. *
  5145. * clone: function() {
  5146. * var cloned = new this.self; // dependent on 'this'
  5147. *
  5148. * cloned.groupName = this.statics().speciesName; // equivalent to: My.Cat.speciesName
  5149. *
  5150. * return cloned;
  5151. * }
  5152. * });
  5153. *
  5154. *
  5155. * Ext.define('My.SnowLeopard', {
  5156. * extend: 'My.Cat',
  5157. *
  5158. * statics: {
  5159. * speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
  5160. * },
  5161. *
  5162. * constructor: function() {
  5163. * this.callParent();
  5164. * }
  5165. * });
  5166. *
  5167. * var cat = new My.Cat(); // alerts 'Cat', then alerts 'Cat'
  5168. *
  5169. * var snowLeopard = new My.SnowLeopard(); // alerts 'Cat', then alerts 'Snow Leopard'
  5170. *
  5171. * var clone = snowLeopard.clone();
  5172. * alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard'
  5173. * alert(clone.groupName); // alerts 'Cat'
  5174. *
  5175. * alert(My.Cat.totalCreated); // alerts 3
  5176. *
  5177. * @protected
  5178. * @return {Ext.Class}
  5179. */
  5180. statics: function() {
  5181. var method = this.statics.caller,
  5182. self = this.self;
  5183. if (!method) {
  5184. return self;
  5185. }
  5186. return method.$owner;
  5187. },
  5188. /**
  5189. * Call the "parent" method of the current method. That is the method previously
  5190. * overridden by derivation or by an override (see {@link Ext#define}).
  5191. *
  5192. * Ext.define('My.Base', {
  5193. * constructor: function (x) {
  5194. * this.x = x;
  5195. * },
  5196. *
  5197. * statics: {
  5198. * method: function (x) {
  5199. * return x;
  5200. * }
  5201. * }
  5202. * });
  5203. *
  5204. * Ext.define('My.Derived', {
  5205. * extend: 'My.Base',
  5206. *
  5207. * constructor: function () {
  5208. * this.callParent([21]);
  5209. * }
  5210. * });
  5211. *
  5212. * var obj = new My.Derived();
  5213. *
  5214. * alert(obj.x); // alerts 21
  5215. *
  5216. * This can be used with an override as follows:
  5217. *
  5218. * Ext.define('My.DerivedOverride', {
  5219. * override: 'My.Derived',
  5220. *
  5221. * constructor: function (x) {
  5222. * this.callParent([x*2]); // calls original My.Derived constructor
  5223. * }
  5224. * });
  5225. *
  5226. * var obj = new My.Derived();
  5227. *
  5228. * alert(obj.x); // now alerts 42
  5229. *
  5230. * This also works with static methods.
  5231. *
  5232. * Ext.define('My.Derived2', {
  5233. * extend: 'My.Base',
  5234. *
  5235. * statics: {
  5236. * method: function (x) {
  5237. * return this.callParent([x*2]); // calls My.Base.method
  5238. * }
  5239. * }
  5240. * });
  5241. *
  5242. * alert(My.Base.method(10); // alerts 10
  5243. * alert(My.Derived2.method(10); // alerts 20
  5244. *
  5245. * Lastly, it also works with overridden static methods.
  5246. *
  5247. * Ext.define('My.Derived2Override', {
  5248. * override: 'My.Derived2',
  5249. *
  5250. * statics: {
  5251. * method: function (x) {
  5252. * return this.callParent([x*2]); // calls My.Derived2.method
  5253. * }
  5254. * }
  5255. * });
  5256. *
  5257. * alert(My.Derived2.method(10); // now alerts 40
  5258. *
  5259. * @protected
  5260. * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
  5261. * from the current method, for example: `this.callParent(arguments)`
  5262. * @return {Object} Returns the result of calling the parent method
  5263. */
  5264. callParent: function(args) {
  5265. // NOTE: this code is deliberately as few expressions (and no function calls)
  5266. // as possible so that a debugger can skip over this noise with the minimum number
  5267. // of steps. Basically, just hit Step Into until you are where you really wanted
  5268. // to be.
  5269. var method,
  5270. superMethod = (method = this.callParent.caller) && (method.$previous ||
  5271. ((method = method.$owner ? method : method.caller) &&
  5272. method.$owner.superclass[method.$name]));
  5273. return superMethod.apply(this, args || noArgs);
  5274. },
  5275. /**
  5276. * @property {Ext.Class} self
  5277. *
  5278. * Get the reference to the current class from which this object was instantiated. Unlike {@link Ext.Base#statics},
  5279. * `this.self` is scope-dependent and it's meant to be used for dynamic inheritance. See {@link Ext.Base#statics}
  5280. * for a detailed comparison
  5281. *
  5282. * Ext.define('My.Cat', {
  5283. * statics: {
  5284. * speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
  5285. * },
  5286. *
  5287. * constructor: function() {
  5288. * alert(this.self.speciesName); / dependentOL on 'this'
  5289. * },
  5290. *
  5291. * clone: function() {
  5292. * return new this.self();
  5293. * }
  5294. * });
  5295. *
  5296. *
  5297. * Ext.define('My.SnowLeopard', {
  5298. * extend: 'My.Cat',
  5299. * statics: {
  5300. * speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
  5301. * }
  5302. * });
  5303. *
  5304. * var cat = new My.Cat(); // alerts 'Cat'
  5305. * var snowLeopard = new My.SnowLeopard(); // alerts 'Snow Leopard'
  5306. *
  5307. * var clone = snowLeopard.clone();
  5308. * alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard'
  5309. *
  5310. * @protected
  5311. */
  5312. self: Base,
  5313. // Default constructor, simply returns `this`
  5314. constructor: function() {
  5315. return this;
  5316. },
  5317. hookMethod: function (name, hookFn) {
  5318. var me = this,
  5319. owner = me.self;
  5320. hookFn.$owner = owner;
  5321. hookFn.$name = name;
  5322. if (me.hasOwnProperty(name)) {
  5323. hookFn.$previous = me[name]; // already hooked, so call previous hook
  5324. } else {
  5325. hookFn.$previous = callHookParent; // special "previous" to call on prototype
  5326. }
  5327. me[name] = hookFn;
  5328. },
  5329. hookMethods: function (hooks) {
  5330. Ext.Object.each(hooks, this.hookMethod, this);
  5331. },
  5332. /**
  5333. * Initialize configuration for this class. a typical example:
  5334. *
  5335. * Ext.define('My.awesome.Class', {
  5336. * // The default config
  5337. * config: {
  5338. * name: 'Awesome',
  5339. * isAwesome: true
  5340. * },
  5341. *
  5342. * constructor: function(config) {
  5343. * this.initConfig(config);
  5344. * }
  5345. * });
  5346. *
  5347. * var awesome = new My.awesome.Class({
  5348. * name: 'Super Awesome'
  5349. * });
  5350. *
  5351. * alert(awesome.getName()); // 'Super Awesome'
  5352. *
  5353. * @protected
  5354. * @param {Object} config
  5355. * @return {Object} mixins The mixin prototypes as key - value pairs
  5356. */
  5357. initConfig: function(config) {
  5358. var instanceConfig = config,
  5359. configNameCache = Ext.Class.configNameCache,
  5360. defaultConfig = new this.configClass,
  5361. defaultConfigList = this.initConfigList,
  5362. hasConfig = this.configMap,
  5363. nameMap, i, ln, name, initializedName;
  5364. this.initConfig = Ext.emptyFn;
  5365. this.initialConfig = instanceConfig || {};
  5366. this.config = config = (instanceConfig) ? Ext.merge(defaultConfig, config) : defaultConfig;
  5367. if (instanceConfig) {
  5368. defaultConfigList = defaultConfigList.slice();
  5369. for (name in instanceConfig) {
  5370. if (hasConfig[name]) {
  5371. if (instanceConfig[name] !== null) {
  5372. defaultConfigList.push(name);
  5373. this[configNameCache[name].initialized] = false;
  5374. }
  5375. }
  5376. }
  5377. }
  5378. for (i = 0,ln = defaultConfigList.length; i < ln; i++) {
  5379. name = defaultConfigList[i];
  5380. nameMap = configNameCache[name];
  5381. initializedName = nameMap.initialized;
  5382. if (!this[initializedName]) {
  5383. this[initializedName] = true;
  5384. this[nameMap.set].call(this, config[name]);
  5385. }
  5386. }
  5387. return this;
  5388. },
  5389. /**
  5390. * @private
  5391. * @param config
  5392. */
  5393. hasConfig: function(name) {
  5394. return Boolean(this.configMap[name]);
  5395. },
  5396. /**
  5397. * @private
  5398. */
  5399. setConfig: function(config, applyIfNotSet) {
  5400. if (!config) {
  5401. return this;
  5402. }
  5403. var configNameCache = Ext.Class.configNameCache,
  5404. currentConfig = this.config,
  5405. hasConfig = this.configMap,
  5406. initialConfig = this.initialConfig,
  5407. name, value;
  5408. applyIfNotSet = Boolean(applyIfNotSet);
  5409. for (name in config) {
  5410. if (applyIfNotSet && initialConfig.hasOwnProperty(name)) {
  5411. continue;
  5412. }
  5413. value = config[name];
  5414. currentConfig[name] = value;
  5415. if (hasConfig[name]) {
  5416. this[configNameCache[name].set](value);
  5417. }
  5418. }
  5419. return this;
  5420. },
  5421. /**
  5422. * @private
  5423. * @param name
  5424. */
  5425. getConfig: function(name) {
  5426. var configNameCache = Ext.Class.configNameCache;
  5427. return this[configNameCache[name].get]();
  5428. },
  5429. /**
  5430. *
  5431. * @param name
  5432. */
  5433. getInitialConfig: function(name) {
  5434. var config = this.config;
  5435. if (!name) {
  5436. return config;
  5437. }
  5438. else {
  5439. return config[name];
  5440. }
  5441. },
  5442. /**
  5443. * @private
  5444. * @param names
  5445. * @param callback
  5446. * @param scope
  5447. */
  5448. onConfigUpdate: function(names, callback, scope) {
  5449. var self = this.self,
  5450. i, ln, name,
  5451. updaterName, updater, newUpdater;
  5452. names = Ext.Array.from(names);
  5453. scope = scope || this;
  5454. for (i = 0,ln = names.length; i < ln; i++) {
  5455. name = names[i];
  5456. updaterName = 'update' + Ext.String.capitalize(name);
  5457. updater = this[updaterName] || Ext.emptyFn;
  5458. newUpdater = function() {
  5459. updater.apply(this, arguments);
  5460. scope[callback].apply(scope, arguments);
  5461. };
  5462. newUpdater.$name = updaterName;
  5463. newUpdater.$owner = self;
  5464. this[updaterName] = newUpdater;
  5465. }
  5466. },
  5467. destroy: function() {
  5468. this.destroy = Ext.emptyFn;
  5469. }
  5470. });
  5471. /**
  5472. * Call the original method that was previously overridden with {@link Ext.Base#override}
  5473. *
  5474. * Ext.define('My.Cat', {
  5475. * constructor: function() {
  5476. * alert("I'm a cat!");
  5477. * }
  5478. * });
  5479. *
  5480. * My.Cat.override({
  5481. * constructor: function() {
  5482. * alert("I'm going to be a cat!");
  5483. *
  5484. * var instance = this.callOverridden();
  5485. *
  5486. * alert("Meeeeoooowwww");
  5487. *
  5488. * return instance;
  5489. * }
  5490. * });
  5491. *
  5492. * var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
  5493. * // alerts "I'm a cat!"
  5494. * // alerts "Meeeeoooowwww"
  5495. *
  5496. * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
  5497. * from the current method, for example: `this.callOverridden(arguments)`
  5498. * @return {Object} Returns the result of calling the overridden method
  5499. * @protected
  5500. * @deprecated as of 4.1. Use {@link #callParent} instead.
  5501. */
  5502. Base.prototype.callOverridden = Base.prototype.callParent;
  5503. Ext.Base = Base;
  5504. })(Ext.Function.flexSetter);
  5505. /**
  5506. * @author Jacky Nguyen <jacky@sencha.com>
  5507. * @docauthor Jacky Nguyen <jacky@sencha.com>
  5508. * @class Ext.Class
  5509. *
  5510. * Handles class creation throughout the framework. This is a low level factory that is used by Ext.ClassManager and generally
  5511. * should not be used directly. If you choose to use Ext.Class you will lose out on the namespace, aliasing and depency loading
  5512. * features made available by Ext.ClassManager. The only time you would use Ext.Class directly is to create an anonymous class.
  5513. *
  5514. * If you wish to create a class you should use {@link Ext#define Ext.define} which aliases
  5515. * {@link Ext.ClassManager#create Ext.ClassManager.create} to enable namespacing and dynamic dependency resolution.
  5516. *
  5517. * Ext.Class is the factory and **not** the superclass of everything. For the base class that **all** Ext classes inherit
  5518. * from, see {@link Ext.Base}.
  5519. */
  5520. (function() {
  5521. var ExtClass,
  5522. Base = Ext.Base,
  5523. baseStaticMembers = [],
  5524. baseStaticMember, baseStaticMemberLength;
  5525. for (baseStaticMember in Base) {
  5526. if (Base.hasOwnProperty(baseStaticMember)) {
  5527. baseStaticMembers.push(baseStaticMember);
  5528. }
  5529. }
  5530. baseStaticMemberLength = baseStaticMembers.length;
  5531. // Creates a constructor that has nothing extra in its scope chain.
  5532. function makeCtor (className) {
  5533. function constructor () {
  5534. return this.constructor.apply(this, arguments);
  5535. };
  5536. return constructor;
  5537. }
  5538. /**
  5539. * @method constructor
  5540. * Create a new anonymous class.
  5541. *
  5542. * @param {Object} data An object represent the properties of this class
  5543. * @param {Function} onCreated Optional, the callback function to be executed when this class is fully created.
  5544. * Note that the creation process can be asynchronous depending on the pre-processors used.
  5545. *
  5546. * @return {Ext.Base} The newly created class
  5547. */
  5548. Ext.Class = ExtClass = function(Class, data, onCreated) {
  5549. if (typeof Class != 'function') {
  5550. onCreated = data;
  5551. data = Class;
  5552. Class = null;
  5553. }
  5554. if (!data) {
  5555. data = {};
  5556. }
  5557. Class = ExtClass.create(Class, data);
  5558. ExtClass.process(Class, data, onCreated);
  5559. return Class;
  5560. };
  5561. Ext.apply(ExtClass, {
  5562. /**
  5563. * @private
  5564. * @param Class
  5565. * @param data
  5566. * @param hooks
  5567. */
  5568. onBeforeCreated: function(Class, data, hooks) {
  5569. Class.addMembers(data);
  5570. hooks.onCreated.call(Class, Class);
  5571. },
  5572. /**
  5573. * @private
  5574. * @param Class
  5575. * @param classData
  5576. * @param onClassCreated
  5577. */
  5578. create: function(Class, data) {
  5579. var name, i;
  5580. if (!Class) {
  5581. // This "helped" a bit in IE8 when we create 450k instances (3400ms->2700ms),
  5582. // but removes some flexibility as a result because overrides cannot override
  5583. // the constructor method... kept in case we want to reconsider because it is
  5584. // more involved than just use the pass 'constructor'
  5585. //
  5586. //if (data.hasOwnProperty('constructor')) {
  5587. // Class = data.constructor;
  5588. // delete data.constructor;
  5589. // Class.$owner = Class;
  5590. // Class.$name = 'constructor';
  5591. //} else {
  5592. Class = makeCtor(
  5593. );
  5594. //}
  5595. }
  5596. for (i = 0; i < baseStaticMemberLength; i++) {
  5597. name = baseStaticMembers[i];
  5598. Class[name] = Base[name];
  5599. }
  5600. return Class;
  5601. },
  5602. /**
  5603. * @private
  5604. * @param Class
  5605. * @param data
  5606. * @param onCreated
  5607. */
  5608. process: function(Class, data, onCreated) {
  5609. var preprocessorStack = data.preprocessors || ExtClass.defaultPreprocessors,
  5610. registeredPreprocessors = this.preprocessors,
  5611. hooks = {
  5612. onBeforeCreated: this.onBeforeCreated
  5613. },
  5614. preprocessors = [],
  5615. preprocessor, preprocessorsProperties,
  5616. i, ln, j, subLn, preprocessorProperty, process;
  5617. delete data.preprocessors;
  5618. for (i = 0,ln = preprocessorStack.length; i < ln; i++) {
  5619. preprocessor = preprocessorStack[i];
  5620. if (typeof preprocessor == 'string') {
  5621. preprocessor = registeredPreprocessors[preprocessor];
  5622. preprocessorsProperties = preprocessor.properties;
  5623. if (preprocessorsProperties === true) {
  5624. preprocessors.push(preprocessor.fn);
  5625. }
  5626. else if (preprocessorsProperties) {
  5627. for (j = 0,subLn = preprocessorsProperties.length; j < subLn; j++) {
  5628. preprocessorProperty = preprocessorsProperties[j];
  5629. if (data.hasOwnProperty(preprocessorProperty)) {
  5630. preprocessors.push(preprocessor.fn);
  5631. break;
  5632. }
  5633. }
  5634. }
  5635. }
  5636. else {
  5637. preprocessors.push(preprocessor);
  5638. }
  5639. }
  5640. hooks.onCreated = onCreated ? onCreated : Ext.emptyFn;
  5641. hooks.preprocessors = preprocessors;
  5642. this.doProcess(Class, data, hooks);
  5643. },
  5644. doProcess: function(Class, data, hooks){
  5645. var me = this,
  5646. preprocessor = hooks.preprocessors.shift();
  5647. if (!preprocessor) {
  5648. hooks.onBeforeCreated.apply(me, arguments);
  5649. return;
  5650. }
  5651. if (preprocessor.call(me, Class, data, hooks, me.doProcess) !== false) {
  5652. me.doProcess(Class, data, hooks);
  5653. }
  5654. },
  5655. /** @private */
  5656. preprocessors: {},
  5657. /**
  5658. * Register a new pre-processor to be used during the class creation process
  5659. *
  5660. * @param {String} name The pre-processor's name
  5661. * @param {Function} fn The callback function to be executed. Typical format:
  5662. *
  5663. * function(cls, data, fn) {
  5664. * // Your code here
  5665. *
  5666. * // Execute this when the processing is finished.
  5667. * // Asynchronous processing is perfectly ok
  5668. * if (fn) {
  5669. * fn.call(this, cls, data);
  5670. * }
  5671. * });
  5672. *
  5673. * @param {Function} fn.cls The created class
  5674. * @param {Object} fn.data The set of properties passed in {@link Ext.Class} constructor
  5675. * @param {Function} fn.fn The callback function that **must** to be executed when this
  5676. * pre-processor finishes, regardless of whether the processing is synchronous or aynchronous.
  5677. * @return {Ext.Class} this
  5678. * @private
  5679. * @static
  5680. */
  5681. registerPreprocessor: function(name, fn, properties, position, relativeTo) {
  5682. if (!position) {
  5683. position = 'last';
  5684. }
  5685. if (!properties) {
  5686. properties = [name];
  5687. }
  5688. this.preprocessors[name] = {
  5689. name: name,
  5690. properties: properties || false,
  5691. fn: fn
  5692. };
  5693. this.setDefaultPreprocessorPosition(name, position, relativeTo);
  5694. return this;
  5695. },
  5696. /**
  5697. * Retrieve a pre-processor callback function by its name, which has been registered before
  5698. *
  5699. * @param {String} name
  5700. * @return {Function} preprocessor
  5701. * @private
  5702. * @static
  5703. */
  5704. getPreprocessor: function(name) {
  5705. return this.preprocessors[name];
  5706. },
  5707. /**
  5708. * @private
  5709. */
  5710. getPreprocessors: function() {
  5711. return this.preprocessors;
  5712. },
  5713. /**
  5714. * @private
  5715. */
  5716. defaultPreprocessors: [],
  5717. /**
  5718. * Retrieve the array stack of default pre-processors
  5719. * @return {Function[]} defaultPreprocessors
  5720. * @private
  5721. * @static
  5722. */
  5723. getDefaultPreprocessors: function() {
  5724. return this.defaultPreprocessors;
  5725. },
  5726. /**
  5727. * Set the default array stack of default pre-processors
  5728. *
  5729. * @private
  5730. * @param {Array} preprocessors
  5731. * @return {Ext.Class} this
  5732. * @static
  5733. */
  5734. setDefaultPreprocessors: function(preprocessors) {
  5735. this.defaultPreprocessors = Ext.Array.from(preprocessors);
  5736. return this;
  5737. },
  5738. /**
  5739. * Insert this pre-processor at a specific position in the stack, optionally relative to
  5740. * any existing pre-processor. For example:
  5741. *
  5742. * Ext.Class.registerPreprocessor('debug', function(cls, data, fn) {
  5743. * // Your code here
  5744. *
  5745. * if (fn) {
  5746. * fn.call(this, cls, data);
  5747. * }
  5748. * }).setDefaultPreprocessorPosition('debug', 'last');
  5749. *
  5750. * @private
  5751. * @param {String} name The pre-processor name. Note that it needs to be registered with
  5752. * {@link Ext#registerPreprocessor registerPreprocessor} before this
  5753. * @param {String} offset The insertion position. Four possible values are:
  5754. * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument)
  5755. * @param {String} relativeName
  5756. * @return {Ext.Class} this
  5757. * @static
  5758. */
  5759. setDefaultPreprocessorPosition: function(name, offset, relativeName) {
  5760. var defaultPreprocessors = this.defaultPreprocessors,
  5761. index;
  5762. if (typeof offset == 'string') {
  5763. if (offset === 'first') {
  5764. defaultPreprocessors.unshift(name);
  5765. return this;
  5766. }
  5767. else if (offset === 'last') {
  5768. defaultPreprocessors.push(name);
  5769. return this;
  5770. }
  5771. offset = (offset === 'after') ? 1 : -1;
  5772. }
  5773. index = Ext.Array.indexOf(defaultPreprocessors, relativeName);
  5774. if (index !== -1) {
  5775. Ext.Array.splice(defaultPreprocessors, Math.max(0, index + offset), 0, name);
  5776. }
  5777. return this;
  5778. },
  5779. configNameCache: {},
  5780. getConfigNameMap: function(name) {
  5781. var cache = this.configNameCache,
  5782. map = cache[name],
  5783. capitalizedName;
  5784. if (!map) {
  5785. capitalizedName = name.charAt(0).toUpperCase() + name.substr(1);
  5786. map = cache[name] = {
  5787. internal: name,
  5788. initialized: '_is' + capitalizedName + 'Initialized',
  5789. apply: 'apply' + capitalizedName,
  5790. update: 'update' + capitalizedName,
  5791. 'set': 'set' + capitalizedName,
  5792. 'get': 'get' + capitalizedName,
  5793. doSet : 'doSet' + capitalizedName,
  5794. changeEvent: name.toLowerCase() + 'change'
  5795. }
  5796. }
  5797. return map;
  5798. }
  5799. });
  5800. /**
  5801. * @cfg {String} extend
  5802. * The parent class that this class extends. For example:
  5803. *
  5804. * Ext.define('Person', {
  5805. * say: function(text) { alert(text); }
  5806. * });
  5807. *
  5808. * Ext.define('Developer', {
  5809. * extend: 'Person',
  5810. * say: function(text) { this.callParent(["print "+text]); }
  5811. * });
  5812. */
  5813. ExtClass.registerPreprocessor('extend', function(Class, data) {
  5814. var Base = Ext.Base,
  5815. basePrototype = Base.prototype,
  5816. extend = data.extend,
  5817. Parent, parentPrototype, i;
  5818. delete data.extend;
  5819. if (extend && extend !== Object) {
  5820. Parent = extend;
  5821. }
  5822. else {
  5823. Parent = Base;
  5824. }
  5825. parentPrototype = Parent.prototype;
  5826. if (!Parent.$isClass) {
  5827. for (i in basePrototype) {
  5828. if (!parentPrototype[i]) {
  5829. parentPrototype[i] = basePrototype[i];
  5830. }
  5831. }
  5832. }
  5833. Class.extend(Parent);
  5834. Class.triggerExtended.apply(Class, arguments);
  5835. if (data.onClassExtended) {
  5836. Class.onExtended(data.onClassExtended);
  5837. delete data.onClassExtended;
  5838. }
  5839. }, true);
  5840. /**
  5841. * @cfg {Object} statics
  5842. * List of static methods for this class. For example:
  5843. *
  5844. * Ext.define('Computer', {
  5845. * statics: {
  5846. * factory: function(brand) {
  5847. * // 'this' in static methods refer to the class itself
  5848. * return new this(brand);
  5849. * }
  5850. * },
  5851. *
  5852. * constructor: function() { ... }
  5853. * });
  5854. *
  5855. * var dellComputer = Computer.factory('Dell');
  5856. */
  5857. ExtClass.registerPreprocessor('statics', function(Class, data) {
  5858. Class.addStatics(data.statics);
  5859. delete data.statics;
  5860. });
  5861. /**
  5862. * @cfg {Object} inheritableStatics
  5863. * List of inheritable static methods for this class.
  5864. * Otherwise just like {@link #statics} but subclasses inherit these methods.
  5865. */
  5866. ExtClass.registerPreprocessor('inheritableStatics', function(Class, data) {
  5867. Class.addInheritableStatics(data.inheritableStatics);
  5868. delete data.inheritableStatics;
  5869. });
  5870. /**
  5871. * @cfg {Object} config
  5872. * List of configuration options with their default values, for which automatically
  5873. * accessor methods are generated. For example:
  5874. *
  5875. * Ext.define('SmartPhone', {
  5876. * config: {
  5877. * hasTouchScreen: false,
  5878. * operatingSystem: 'Other',
  5879. * price: 500
  5880. * },
  5881. * constructor: function(cfg) {
  5882. * this.initConfig(cfg);
  5883. * }
  5884. * });
  5885. *
  5886. * var iPhone = new SmartPhone({
  5887. * hasTouchScreen: true,
  5888. * operatingSystem: 'iOS'
  5889. * });
  5890. *
  5891. * iPhone.getPrice(); // 500;
  5892. * iPhone.getOperatingSystem(); // 'iOS'
  5893. * iPhone.getHasTouchScreen(); // true;
  5894. */
  5895. ExtClass.registerPreprocessor('config', function(Class, data) {
  5896. var config = data.config,
  5897. prototype = Class.prototype;
  5898. delete data.config;
  5899. Ext.Object.each(config, function(name, value) {
  5900. var nameMap = ExtClass.getConfigNameMap(name),
  5901. internalName = nameMap.internal,
  5902. initializedName = nameMap.initialized,
  5903. applyName = nameMap.apply,
  5904. updateName = nameMap.update,
  5905. setName = nameMap.set,
  5906. getName = nameMap.get,
  5907. hasOwnSetter = (setName in prototype) || data.hasOwnProperty(setName),
  5908. hasOwnApplier = (applyName in prototype) || data.hasOwnProperty(applyName),
  5909. hasOwnUpdater = (updateName in prototype) || data.hasOwnProperty(updateName),
  5910. optimizedGetter, customGetter;
  5911. if (value === null || (!hasOwnSetter && !hasOwnApplier && !hasOwnUpdater)) {
  5912. prototype[internalName] = value;
  5913. prototype[initializedName] = true;
  5914. }
  5915. else {
  5916. prototype[initializedName] = false;
  5917. }
  5918. if (!hasOwnSetter) {
  5919. data[setName] = function(value) {
  5920. var oldValue = this[internalName],
  5921. applier = this[applyName],
  5922. updater = this[updateName];
  5923. if (!this[initializedName]) {
  5924. this[initializedName] = true;
  5925. }
  5926. if (applier) {
  5927. value = applier.call(this, value, oldValue);
  5928. }
  5929. if (typeof value != 'undefined') {
  5930. this[internalName] = value;
  5931. if (updater && value !== oldValue) {
  5932. updater.call(this, value, oldValue);
  5933. }
  5934. }
  5935. return this;
  5936. }
  5937. }
  5938. if (!(getName in prototype) || data.hasOwnProperty(getName)) {
  5939. customGetter = data[getName] || false;
  5940. if (customGetter) {
  5941. optimizedGetter = function() {
  5942. return customGetter.apply(this, arguments);
  5943. };
  5944. }
  5945. else {
  5946. optimizedGetter = function() {
  5947. return this[internalName];
  5948. };
  5949. }
  5950. data[getName] = function() {
  5951. var currentGetter;
  5952. if (!this[initializedName]) {
  5953. this[initializedName] = true;
  5954. this[setName](this.config[name]);
  5955. }
  5956. currentGetter = this[getName];
  5957. if ('$previous' in currentGetter) {
  5958. currentGetter.$previous = optimizedGetter;
  5959. }
  5960. else {
  5961. this[getName] = optimizedGetter;
  5962. }
  5963. return optimizedGetter.apply(this, arguments);
  5964. };
  5965. }
  5966. });
  5967. Class.addConfig(config, true);
  5968. });
  5969. /**
  5970. * @cfg {String[]/Object} mixins
  5971. * List of classes to mix into this class. For example:
  5972. *
  5973. * Ext.define('CanSing', {
  5974. * sing: function() {
  5975. * alert("I'm on the highway to hell...")
  5976. * }
  5977. * });
  5978. *
  5979. * Ext.define('Musician', {
  5980. * mixins: ['CanSing']
  5981. * })
  5982. *
  5983. * In this case the Musician class will get a `sing` method from CanSing mixin.
  5984. *
  5985. * But what if the Musician already has a `sing` method? Or you want to mix
  5986. * in two classes, both of which define `sing`? In such a cases it's good
  5987. * to define mixins as an object, where you assign a name to each mixin:
  5988. *
  5989. * Ext.define('Musician', {
  5990. * mixins: {
  5991. * canSing: 'CanSing'
  5992. * },
  5993. *
  5994. * sing: function() {
  5995. * // delegate singing operation to mixin
  5996. * this.mixins.canSing.sing.call(this);
  5997. * }
  5998. * })
  5999. *
  6000. * In this case the `sing` method of Musician will overwrite the
  6001. * mixed in `sing` method. But you can access the original mixed in method
  6002. * through special `mixins` property.
  6003. */
  6004. ExtClass.registerPreprocessor('mixins', function(Class, data, hooks) {
  6005. var mixins = data.mixins,
  6006. name, mixin, i, ln;
  6007. delete data.mixins;
  6008. Ext.Function.interceptBefore(hooks, 'onCreated', function() {
  6009. if (mixins instanceof Array) {
  6010. for (i = 0,ln = mixins.length; i < ln; i++) {
  6011. mixin = mixins[i];
  6012. name = mixin.prototype.mixinId || mixin.$className;
  6013. Class.mixin(name, mixin);
  6014. }
  6015. }
  6016. else {
  6017. for (name in mixins) {
  6018. if (mixins.hasOwnProperty(name)) {
  6019. Class.mixin(name, mixins[name]);
  6020. }
  6021. }
  6022. }
  6023. });
  6024. });
  6025. // Backwards compatible
  6026. Ext.extend = function(Class, Parent, members) {
  6027. if (arguments.length === 2 && Ext.isObject(Parent)) {
  6028. members = Parent;
  6029. Parent = Class;
  6030. Class = null;
  6031. }
  6032. var cls;
  6033. if (!Parent) {
  6034. throw new Error("[Ext.extend] Attempting to extend from a class which has not been loaded on the page.");
  6035. }
  6036. members.extend = Parent;
  6037. members.preprocessors = [
  6038. 'extend'
  6039. ,'statics'
  6040. ,'inheritableStatics'
  6041. ,'mixins'
  6042. ,'config'
  6043. ];
  6044. if (Class) {
  6045. cls = new ExtClass(Class, members);
  6046. }
  6047. else {
  6048. cls = new ExtClass(members);
  6049. }
  6050. cls.prototype.override = function(o) {
  6051. for (var m in o) {
  6052. if (o.hasOwnProperty(m)) {
  6053. this[m] = o[m];
  6054. }
  6055. }
  6056. };
  6057. return cls;
  6058. };
  6059. })();
  6060. /**
  6061. * @author Jacky Nguyen <jacky@sencha.com>
  6062. * @docauthor Jacky Nguyen <jacky@sencha.com>
  6063. * @class Ext.ClassManager
  6064. *
  6065. * Ext.ClassManager manages all classes and handles mapping from string class name to
  6066. * actual class objects throughout the whole framework. It is not generally accessed directly, rather through
  6067. * these convenient shorthands:
  6068. *
  6069. * - {@link Ext#define Ext.define}
  6070. * - {@link Ext#create Ext.create}
  6071. * - {@link Ext#widget Ext.widget}
  6072. * - {@link Ext#getClass Ext.getClass}
  6073. * - {@link Ext#getClassName Ext.getClassName}
  6074. *
  6075. * # Basic syntax:
  6076. *
  6077. * Ext.define(className, properties);
  6078. *
  6079. * in which `properties` is an object represent a collection of properties that apply to the class. See
  6080. * {@link Ext.ClassManager#create} for more detailed instructions.
  6081. *
  6082. * Ext.define('Person', {
  6083. * name: 'Unknown',
  6084. *
  6085. * constructor: function(name) {
  6086. * if (name) {
  6087. * this.name = name;
  6088. * }
  6089. *
  6090. * return this;
  6091. * },
  6092. *
  6093. * eat: function(foodType) {
  6094. * alert("I'm eating: " + foodType);
  6095. *
  6096. * return this;
  6097. * }
  6098. * });
  6099. *
  6100. * var aaron = new Person("Aaron");
  6101. * aaron.eat("Sandwich"); // alert("I'm eating: Sandwich");
  6102. *
  6103. * Ext.Class has a powerful set of extensible {@link Ext.Class#registerPreprocessor pre-processors} which takes care of
  6104. * everything related to class creation, including but not limited to inheritance, mixins, configuration, statics, etc.
  6105. *
  6106. * # Inheritance:
  6107. *
  6108. * Ext.define('Developer', {
  6109. * extend: 'Person',
  6110. *
  6111. * constructor: function(name, isGeek) {
  6112. * this.isGeek = isGeek;
  6113. *
  6114. * // Apply a method from the parent class' prototype
  6115. * this.callParent([name]);
  6116. *
  6117. * return this;
  6118. *
  6119. * },
  6120. *
  6121. * code: function(language) {
  6122. * alert("I'm coding in: " + language);
  6123. *
  6124. * this.eat("Bugs");
  6125. *
  6126. * return this;
  6127. * }
  6128. * });
  6129. *
  6130. * var jacky = new Developer("Jacky", true);
  6131. * jacky.code("JavaScript"); // alert("I'm coding in: JavaScript");
  6132. * // alert("I'm eating: Bugs");
  6133. *
  6134. * See {@link Ext.Base#callParent} for more details on calling superclass' methods
  6135. *
  6136. * # Mixins:
  6137. *
  6138. * Ext.define('CanPlayGuitar', {
  6139. * playGuitar: function() {
  6140. * alert("F#...G...D...A");
  6141. * }
  6142. * });
  6143. *
  6144. * Ext.define('CanComposeSongs', {
  6145. * composeSongs: function() { ... }
  6146. * });
  6147. *
  6148. * Ext.define('CanSing', {
  6149. * sing: function() {
  6150. * alert("I'm on the highway to hell...")
  6151. * }
  6152. * });
  6153. *
  6154. * Ext.define('Musician', {
  6155. * extend: 'Person',
  6156. *
  6157. * mixins: {
  6158. * canPlayGuitar: 'CanPlayGuitar',
  6159. * canComposeSongs: 'CanComposeSongs',
  6160. * canSing: 'CanSing'
  6161. * }
  6162. * })
  6163. *
  6164. * Ext.define('CoolPerson', {
  6165. * extend: 'Person',
  6166. *
  6167. * mixins: {
  6168. * canPlayGuitar: 'CanPlayGuitar',
  6169. * canSing: 'CanSing'
  6170. * },
  6171. *
  6172. * sing: function() {
  6173. * alert("Ahem....");
  6174. *
  6175. * this.mixins.canSing.sing.call(this);
  6176. *
  6177. * alert("[Playing guitar at the same time...]");
  6178. *
  6179. * this.playGuitar();
  6180. * }
  6181. * });
  6182. *
  6183. * var me = new CoolPerson("Jacky");
  6184. *
  6185. * me.sing(); // alert("Ahem...");
  6186. * // alert("I'm on the highway to hell...");
  6187. * // alert("[Playing guitar at the same time...]");
  6188. * // alert("F#...G...D...A");
  6189. *
  6190. * # Config:
  6191. *
  6192. * Ext.define('SmartPhone', {
  6193. * config: {
  6194. * hasTouchScreen: false,
  6195. * operatingSystem: 'Other',
  6196. * price: 500
  6197. * },
  6198. *
  6199. * isExpensive: false,
  6200. *
  6201. * constructor: function(config) {
  6202. * this.initConfig(config);
  6203. *
  6204. * return this;
  6205. * },
  6206. *
  6207. * applyPrice: function(price) {
  6208. * this.isExpensive = (price > 500);
  6209. *
  6210. * return price;
  6211. * },
  6212. *
  6213. * applyOperatingSystem: function(operatingSystem) {
  6214. * if (!(/^(iOS|Android|BlackBerry)$/i).test(operatingSystem)) {
  6215. * return 'Other';
  6216. * }
  6217. *
  6218. * return operatingSystem;
  6219. * }
  6220. * });
  6221. *
  6222. * var iPhone = new SmartPhone({
  6223. * hasTouchScreen: true,
  6224. * operatingSystem: 'iOS'
  6225. * });
  6226. *
  6227. * iPhone.getPrice(); // 500;
  6228. * iPhone.getOperatingSystem(); // 'iOS'
  6229. * iPhone.getHasTouchScreen(); // true;
  6230. * iPhone.hasTouchScreen(); // true
  6231. *
  6232. * iPhone.isExpensive; // false;
  6233. * iPhone.setPrice(600);
  6234. * iPhone.getPrice(); // 600
  6235. * iPhone.isExpensive; // true;
  6236. *
  6237. * iPhone.setOperatingSystem('AlienOS');
  6238. * iPhone.getOperatingSystem(); // 'Other'
  6239. *
  6240. * # Statics:
  6241. *
  6242. * Ext.define('Computer', {
  6243. * statics: {
  6244. * factory: function(brand) {
  6245. * // 'this' in static methods refer to the class itself
  6246. * return new this(brand);
  6247. * }
  6248. * },
  6249. *
  6250. * constructor: function() { ... }
  6251. * });
  6252. *
  6253. * var dellComputer = Computer.factory('Dell');
  6254. *
  6255. * Also see {@link Ext.Base#statics} and {@link Ext.Base#self} for more details on accessing
  6256. * static properties within class methods
  6257. *
  6258. * @singleton
  6259. */
  6260. (function(Class, alias, arraySlice, arrayFrom, global) {
  6261. var Manager = Ext.ClassManager = {
  6262. /**
  6263. * @property {Object} classes
  6264. * All classes which were defined through the ClassManager. Keys are the
  6265. * name of the classes and the values are references to the classes.
  6266. * @private
  6267. */
  6268. classes: {},
  6269. /**
  6270. * @private
  6271. */
  6272. existCache: {},
  6273. /**
  6274. * @private
  6275. */
  6276. namespaceRewrites: [{
  6277. from: 'Ext.',
  6278. to: Ext
  6279. }],
  6280. /**
  6281. * @private
  6282. */
  6283. maps: {
  6284. alternateToName: {},
  6285. aliasToName: {},
  6286. nameToAliases: {},
  6287. nameToAlternates: {},
  6288. overridesByName: {}
  6289. },
  6290. /** @private */
  6291. enableNamespaceParseCache: true,
  6292. /** @private */
  6293. namespaceParseCache: {},
  6294. /** @private */
  6295. instantiators: [],
  6296. /**
  6297. * Checks if a class has already been created.
  6298. *
  6299. * @param {String} className
  6300. * @return {Boolean} exist
  6301. */
  6302. isCreated: function(className) {
  6303. var existCache = this.existCache,
  6304. i, ln, part, root, parts;
  6305. if (this.classes[className] || existCache[className]) {
  6306. return true;
  6307. }
  6308. root = global;
  6309. parts = this.parseNamespace(className);
  6310. for (i = 0, ln = parts.length; i < ln; i++) {
  6311. part = parts[i];
  6312. if (typeof part != 'string') {
  6313. root = part;
  6314. } else {
  6315. if (!root || !root[part]) {
  6316. return false;
  6317. }
  6318. root = root[part];
  6319. }
  6320. }
  6321. existCache[className] = true;
  6322. this.triggerCreated(className);
  6323. return true;
  6324. },
  6325. /**
  6326. * @private
  6327. */
  6328. createdListeners: [],
  6329. /**
  6330. * @private
  6331. */
  6332. nameCreatedListeners: {},
  6333. /**
  6334. * @private
  6335. */
  6336. triggerCreated: function(className) {
  6337. var listeners = this.createdListeners,
  6338. nameListeners = this.nameCreatedListeners,
  6339. i, ln, listener;
  6340. for (i = 0,ln = listeners.length; i < ln; i++) {
  6341. listener = listeners[i];
  6342. listener.fn.call(listener.scope, className);
  6343. }
  6344. listeners = nameListeners[className];
  6345. if (listeners) {
  6346. for (i = 0,ln = listeners.length; i < ln; i++) {
  6347. listener = listeners[i];
  6348. listener.fn.call(listener.scope, className);
  6349. }
  6350. delete nameListeners[className];
  6351. }
  6352. },
  6353. /**
  6354. * @private
  6355. */
  6356. onCreated: function(fn, scope, className) {
  6357. var listeners = this.createdListeners,
  6358. nameListeners = this.nameCreatedListeners,
  6359. listener = {
  6360. fn: fn,
  6361. scope: scope
  6362. };
  6363. if (className) {
  6364. if (this.isCreated(className)) {
  6365. fn.call(scope, className);
  6366. return;
  6367. }
  6368. if (!nameListeners[className]) {
  6369. nameListeners[className] = [];
  6370. }
  6371. nameListeners[className].push(listener);
  6372. }
  6373. else {
  6374. listeners.push(listener);
  6375. }
  6376. },
  6377. /**
  6378. * Supports namespace rewriting
  6379. * @private
  6380. */
  6381. parseNamespace: function(namespace) {
  6382. var cache = this.namespaceParseCache;
  6383. if (this.enableNamespaceParseCache) {
  6384. if (cache.hasOwnProperty(namespace)) {
  6385. return cache[namespace];
  6386. }
  6387. }
  6388. var parts = [],
  6389. rewrites = this.namespaceRewrites,
  6390. root = global,
  6391. name = namespace,
  6392. rewrite, from, to, i, ln;
  6393. for (i = 0, ln = rewrites.length; i < ln; i++) {
  6394. rewrite = rewrites[i];
  6395. from = rewrite.from;
  6396. to = rewrite.to;
  6397. if (name === from || name.substring(0, from.length) === from) {
  6398. name = name.substring(from.length);
  6399. if (typeof to != 'string') {
  6400. root = to;
  6401. } else {
  6402. parts = parts.concat(to.split('.'));
  6403. }
  6404. break;
  6405. }
  6406. }
  6407. parts.push(root);
  6408. parts = parts.concat(name.split('.'));
  6409. if (this.enableNamespaceParseCache) {
  6410. cache[namespace] = parts;
  6411. }
  6412. return parts;
  6413. },
  6414. /**
  6415. * Creates a namespace and assign the `value` to the created object
  6416. *
  6417. * Ext.ClassManager.setNamespace('MyCompany.pkg.Example', someObject);
  6418. *
  6419. * alert(MyCompany.pkg.Example === someObject); // alerts true
  6420. *
  6421. * @param {String} name
  6422. * @param {Object} value
  6423. */
  6424. setNamespace: function(name, value) {
  6425. var root = global,
  6426. parts = this.parseNamespace(name),
  6427. ln = parts.length - 1,
  6428. leaf = parts[ln],
  6429. i, part;
  6430. for (i = 0; i < ln; i++) {
  6431. part = parts[i];
  6432. if (typeof part != 'string') {
  6433. root = part;
  6434. } else {
  6435. if (!root[part]) {
  6436. root[part] = {};
  6437. }
  6438. root = root[part];
  6439. }
  6440. }
  6441. root[leaf] = value;
  6442. return root[leaf];
  6443. },
  6444. /**
  6445. * The new Ext.ns, supports namespace rewriting
  6446. * @private
  6447. */
  6448. createNamespaces: function() {
  6449. var root = global,
  6450. parts, part, i, j, ln, subLn;
  6451. for (i = 0, ln = arguments.length; i < ln; i++) {
  6452. parts = this.parseNamespace(arguments[i]);
  6453. for (j = 0, subLn = parts.length; j < subLn; j++) {
  6454. part = parts[j];
  6455. if (typeof part != 'string') {
  6456. root = part;
  6457. } else {
  6458. if (!root[part]) {
  6459. root[part] = {};
  6460. }
  6461. root = root[part];
  6462. }
  6463. }
  6464. }
  6465. return root;
  6466. },
  6467. /**
  6468. * Sets a name reference to a class.
  6469. *
  6470. * @param {String} name
  6471. * @param {Object} value
  6472. * @return {Ext.ClassManager} this
  6473. */
  6474. set: function(name, value) {
  6475. var me = this,
  6476. maps = me.maps,
  6477. nameToAlternates = maps.nameToAlternates,
  6478. targetName = me.getName(value),
  6479. alternates;
  6480. me.classes[name] = me.setNamespace(name, value);
  6481. if (targetName && targetName !== name) {
  6482. maps.alternateToName[name] = targetName;
  6483. alternates = nameToAlternates[targetName] || (nameToAlternates[targetName] = []);
  6484. alternates.push(name);
  6485. }
  6486. return this;
  6487. },
  6488. /**
  6489. * Retrieve a class by its name.
  6490. *
  6491. * @param {String} name
  6492. * @return {Ext.Class} class
  6493. */
  6494. get: function(name) {
  6495. var classes = this.classes;
  6496. if (classes[name]) {
  6497. return classes[name];
  6498. }
  6499. var root = global,
  6500. parts = this.parseNamespace(name),
  6501. part, i, ln;
  6502. for (i = 0, ln = parts.length; i < ln; i++) {
  6503. part = parts[i];
  6504. if (typeof part != 'string') {
  6505. root = part;
  6506. } else {
  6507. if (!root || !root[part]) {
  6508. return null;
  6509. }
  6510. root = root[part];
  6511. }
  6512. }
  6513. return root;
  6514. },
  6515. /**
  6516. * Register the alias for a class.
  6517. *
  6518. * @param {Ext.Class/String} cls a reference to a class or a className
  6519. * @param {String} alias Alias to use when referring to this class
  6520. */
  6521. setAlias: function(cls, alias) {
  6522. var aliasToNameMap = this.maps.aliasToName,
  6523. nameToAliasesMap = this.maps.nameToAliases,
  6524. className;
  6525. if (typeof cls == 'string') {
  6526. className = cls;
  6527. } else {
  6528. className = this.getName(cls);
  6529. }
  6530. if (alias && aliasToNameMap[alias] !== className) {
  6531. aliasToNameMap[alias] = className;
  6532. }
  6533. if (!nameToAliasesMap[className]) {
  6534. nameToAliasesMap[className] = [];
  6535. }
  6536. if (alias) {
  6537. Ext.Array.include(nameToAliasesMap[className], alias);
  6538. }
  6539. return this;
  6540. },
  6541. /**
  6542. * Get a reference to the class by its alias.
  6543. *
  6544. * @param {String} alias
  6545. * @return {Ext.Class} class
  6546. */
  6547. getByAlias: function(alias) {
  6548. return this.get(this.getNameByAlias(alias));
  6549. },
  6550. /**
  6551. * Get the name of a class by its alias.
  6552. *
  6553. * @param {String} alias
  6554. * @return {String} className
  6555. */
  6556. getNameByAlias: function(alias) {
  6557. return this.maps.aliasToName[alias] || '';
  6558. },
  6559. /**
  6560. * Get the name of a class by its alternate name.
  6561. *
  6562. * @param {String} alternate
  6563. * @return {String} className
  6564. */
  6565. getNameByAlternate: function(alternate) {
  6566. return this.maps.alternateToName[alternate] || '';
  6567. },
  6568. /**
  6569. * Get the aliases of a class by the class name
  6570. *
  6571. * @param {String} name
  6572. * @return {Array} aliases
  6573. */
  6574. getAliasesByName: function(name) {
  6575. return this.maps.nameToAliases[name] || [];
  6576. },
  6577. /**
  6578. * Get the name of the class by its reference or its instance;
  6579. * usually invoked by the shorthand {@link Ext#getClassName Ext.getClassName}
  6580. *
  6581. * Ext.ClassManager.getName(Ext.Action); // returns "Ext.Action"
  6582. *
  6583. * @param {Ext.Class/Object} object
  6584. * @return {String} className
  6585. */
  6586. getName: function(object) {
  6587. return object && object.$className || '';
  6588. },
  6589. /**
  6590. * Get the class of the provided object; returns null if it's not an instance
  6591. * of any class created with Ext.define. This is usually invoked by the shorthand {@link Ext#getClass Ext.getClass}
  6592. *
  6593. * var component = new Ext.Component();
  6594. *
  6595. * Ext.ClassManager.getClass(component); // returns Ext.Component
  6596. *
  6597. * @param {Object} object
  6598. * @return {Ext.Class} class
  6599. */
  6600. getClass: function(object) {
  6601. return object && object.self || null;
  6602. },
  6603. /**
  6604. * @private
  6605. */
  6606. applyOverrides: function (name) {
  6607. var me = this,
  6608. overridesByName = me.maps.overridesByName,
  6609. overrides = overridesByName[name],
  6610. length = overrides && overrides.length || 0,
  6611. createOverride = me.createOverride,
  6612. i;
  6613. delete overridesByName[name];
  6614. for (i = 0; i < length; ++i) {
  6615. createOverride.apply(me, overrides[i]);
  6616. }
  6617. },
  6618. /**
  6619. * Defines a class.
  6620. * @deprecated 4.1.0 Use {@link Ext#define} instead, as that also supports creating overrides.
  6621. */
  6622. create: function(className, data, createdFn) {
  6623. data.$className = className;
  6624. return new Class(data, function() {
  6625. var postprocessorStack = data.postprocessors || Manager.defaultPostprocessors,
  6626. registeredPostprocessors = Manager.postprocessors,
  6627. postprocessors = [],
  6628. postprocessor, i, ln, j, subLn, postprocessorProperties, postprocessorProperty,
  6629. alternateNames;
  6630. delete data.postprocessors;
  6631. for (i = 0,ln = postprocessorStack.length; i < ln; i++) {
  6632. postprocessor = postprocessorStack[i];
  6633. if (typeof postprocessor == 'string') {
  6634. postprocessor = registeredPostprocessors[postprocessor];
  6635. postprocessorProperties = postprocessor.properties;
  6636. if (postprocessorProperties === true) {
  6637. postprocessors.push(postprocessor.fn);
  6638. }
  6639. else if (postprocessorProperties) {
  6640. for (j = 0,subLn = postprocessorProperties.length; j < subLn; j++) {
  6641. postprocessorProperty = postprocessorProperties[j];
  6642. if (data.hasOwnProperty(postprocessorProperty)) {
  6643. postprocessors.push(postprocessor.fn);
  6644. break;
  6645. }
  6646. }
  6647. }
  6648. }
  6649. else {
  6650. postprocessors.push(postprocessor);
  6651. }
  6652. }
  6653. data.postprocessors = postprocessors;
  6654. data.createdFn = createdFn;
  6655. Manager.processCreate(className, this, data);
  6656. //TODO: Take this out, hook into classCreated instead
  6657. Manager.applyOverrides(className);
  6658. alternateNames = Manager.maps.nameToAlternates[className];
  6659. for (i = 0, ln = alternateNames && alternateNames.length || 0; i < ln; ++i) {
  6660. Manager.applyOverrides(alternateNames[i]);
  6661. }
  6662. });
  6663. },
  6664. processCreate: function(className, cls, clsData){
  6665. var me = this,
  6666. postprocessor = clsData.postprocessors.shift(),
  6667. createdFn = clsData.createdFn;
  6668. if (!postprocessor) {
  6669. me.set(className, cls);
  6670. if (createdFn) {
  6671. createdFn.call(cls, cls);
  6672. }
  6673. me.triggerCreated(className);
  6674. return;
  6675. }
  6676. if (postprocessor.call(me, className, cls, clsData, me.processCreate) !== false) {
  6677. me.processCreate(className, cls, clsData);
  6678. }
  6679. },
  6680. createOverride: function (overrideName, data, createdFn) {
  6681. var me = this,
  6682. className = data.override,
  6683. cls = me.get(className),
  6684. overrideBody, overridesByName, overrides;
  6685. if (cls) {
  6686. // We use a "faux class" here because it has all the mechanics we need to
  6687. // work with the loader via uses/requires and loader history (for build).
  6688. // This way we don't have to refactor any of the class-loader relationship.
  6689. // hoist any 'requires' or 'uses' from the body onto the faux class:
  6690. overrideBody = Ext.apply({}, data);
  6691. delete overrideBody.requires;
  6692. delete overrideBody.uses;
  6693. delete overrideBody.override;
  6694. me.create(overrideName, {
  6695. requires: data.requires,
  6696. uses: data.uses,
  6697. override: className
  6698. }, function () {
  6699. this.active = true;
  6700. if (cls.override) { // if (normal class)
  6701. cls.override(overrideBody);
  6702. } else { // else (singleton)
  6703. cls.self.override(overrideBody);
  6704. }
  6705. if (createdFn) {
  6706. // called once the override is applied and with the context of the
  6707. // overridden class (the override itself is a meaningless, name-only
  6708. // thing).
  6709. createdFn.call(cls);
  6710. }
  6711. });
  6712. } else {
  6713. // The class is not loaded and may never load, but in case it does we add
  6714. // the override arguments to an internal map keyed by the className. When
  6715. // (or if) the class loads, we will call this method again with those same
  6716. // arguments to complete the override.
  6717. overridesByName = me.maps.overridesByName;
  6718. overrides = overridesByName[className] || (overridesByName[className] = []);
  6719. overrides.push(Array.prototype.slice.call(arguments, 0));
  6720. // place an inactive stub in the namespace (appeases the Loader and could
  6721. // be useful diagnostically)
  6722. me.setNamespace(overrideName, {
  6723. override: className
  6724. });
  6725. }
  6726. },
  6727. /**
  6728. * Instantiate a class by its alias; usually invoked by the convenient shorthand {@link Ext#createByAlias Ext.createByAlias}
  6729. * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has not been defined yet, it will
  6730. * attempt to load the class via synchronous loading.
  6731. *
  6732. * var window = Ext.ClassManager.instantiateByAlias('widget.window', { width: 600, height: 800, ... });
  6733. *
  6734. * @param {String} alias
  6735. * @param {Object...} args Additional arguments after the alias will be passed to the
  6736. * class constructor.
  6737. * @return {Object} instance
  6738. */
  6739. instantiateByAlias: function() {
  6740. var alias = arguments[0],
  6741. args = arraySlice.call(arguments),
  6742. className = this.getNameByAlias(alias);
  6743. if (!className) {
  6744. className = this.maps.aliasToName[alias];
  6745. Ext.syncRequire(className);
  6746. }
  6747. args[0] = className;
  6748. return this.instantiate.apply(this, args);
  6749. },
  6750. /**
  6751. * @private
  6752. */
  6753. instantiate: function() {
  6754. var name = arguments[0],
  6755. nameType = typeof name,
  6756. args = arraySlice.call(arguments, 1),
  6757. alias = name,
  6758. possibleName, cls;
  6759. if (nameType != 'function') {
  6760. if (nameType != 'string' && args.length === 0) {
  6761. args = [name];
  6762. name = name.xclass;
  6763. }
  6764. cls = this.get(name);
  6765. }
  6766. else {
  6767. cls = name;
  6768. }
  6769. // No record of this class name, it's possibly an alias, so look it up
  6770. if (!cls) {
  6771. possibleName = this.getNameByAlias(name);
  6772. if (possibleName) {
  6773. name = possibleName;
  6774. cls = this.get(name);
  6775. }
  6776. }
  6777. // Still no record of this class name, it's possibly an alternate name, so look it up
  6778. if (!cls) {
  6779. possibleName = this.getNameByAlternate(name);
  6780. if (possibleName) {
  6781. name = possibleName;
  6782. cls = this.get(name);
  6783. }
  6784. }
  6785. // Still not existing at this point, try to load it via synchronous mode as the last resort
  6786. if (!cls) {
  6787. Ext.syncRequire(name);
  6788. cls = this.get(name);
  6789. }
  6790. return this.getInstantiator(args.length)(cls, args);
  6791. },
  6792. /**
  6793. * @private
  6794. * @param name
  6795. * @param args
  6796. */
  6797. dynInstantiate: function(name, args) {
  6798. args = arrayFrom(args, true);
  6799. args.unshift(name);
  6800. return this.instantiate.apply(this, args);
  6801. },
  6802. /**
  6803. * @private
  6804. * @param length
  6805. */
  6806. getInstantiator: function(length) {
  6807. var instantiators = this.instantiators,
  6808. instantiator;
  6809. instantiator = instantiators[length];
  6810. if (!instantiator) {
  6811. var i = length,
  6812. args = [];
  6813. for (i = 0; i < length; i++) {
  6814. args.push('a[' + i + ']');
  6815. }
  6816. instantiator = instantiators[length] = new Function('c', 'a', 'return new c(' + args.join(',') + ')');
  6817. }
  6818. return instantiator;
  6819. },
  6820. /**
  6821. * @private
  6822. */
  6823. postprocessors: {},
  6824. /**
  6825. * @private
  6826. */
  6827. defaultPostprocessors: [],
  6828. /**
  6829. * Register a post-processor function.
  6830. *
  6831. * @private
  6832. * @param {String} name
  6833. * @param {Function} postprocessor
  6834. */
  6835. registerPostprocessor: function(name, fn, properties, position, relativeTo) {
  6836. if (!position) {
  6837. position = 'last';
  6838. }
  6839. if (!properties) {
  6840. properties = [name];
  6841. }
  6842. this.postprocessors[name] = {
  6843. name: name,
  6844. properties: properties || false,
  6845. fn: fn
  6846. };
  6847. this.setDefaultPostprocessorPosition(name, position, relativeTo);
  6848. return this;
  6849. },
  6850. /**
  6851. * Set the default post processors array stack which are applied to every class.
  6852. *
  6853. * @private
  6854. * @param {String/Array} The name of a registered post processor or an array of registered names.
  6855. * @return {Ext.ClassManager} this
  6856. */
  6857. setDefaultPostprocessors: function(postprocessors) {
  6858. this.defaultPostprocessors = arrayFrom(postprocessors);
  6859. return this;
  6860. },
  6861. /**
  6862. * Insert this post-processor at a specific position in the stack, optionally relative to
  6863. * any existing post-processor
  6864. *
  6865. * @private
  6866. * @param {String} name The post-processor name. Note that it needs to be registered with
  6867. * {@link Ext.ClassManager#registerPostprocessor} before this
  6868. * @param {String} offset The insertion position. Four possible values are:
  6869. * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument)
  6870. * @param {String} relativeName
  6871. * @return {Ext.ClassManager} this
  6872. */
  6873. setDefaultPostprocessorPosition: function(name, offset, relativeName) {
  6874. var defaultPostprocessors = this.defaultPostprocessors,
  6875. index;
  6876. if (typeof offset == 'string') {
  6877. if (offset === 'first') {
  6878. defaultPostprocessors.unshift(name);
  6879. return this;
  6880. }
  6881. else if (offset === 'last') {
  6882. defaultPostprocessors.push(name);
  6883. return this;
  6884. }
  6885. offset = (offset === 'after') ? 1 : -1;
  6886. }
  6887. index = Ext.Array.indexOf(defaultPostprocessors, relativeName);
  6888. if (index !== -1) {
  6889. Ext.Array.splice(defaultPostprocessors, Math.max(0, index + offset), 0, name);
  6890. }
  6891. return this;
  6892. },
  6893. /**
  6894. * Converts a string expression to an array of matching class names. An expression can either refers to class aliases
  6895. * or class names. Expressions support wildcards:
  6896. *
  6897. * // returns ['Ext.window.Window']
  6898. * var window = Ext.ClassManager.getNamesByExpression('widget.window');
  6899. *
  6900. * // returns ['widget.panel', 'widget.window', ...]
  6901. * var allWidgets = Ext.ClassManager.getNamesByExpression('widget.*');
  6902. *
  6903. * // returns ['Ext.data.Store', 'Ext.data.ArrayProxy', ...]
  6904. * var allData = Ext.ClassManager.getNamesByExpression('Ext.data.*');
  6905. *
  6906. * @param {String} expression
  6907. * @return {String[]} classNames
  6908. */
  6909. getNamesByExpression: function(expression) {
  6910. var nameToAliasesMap = this.maps.nameToAliases,
  6911. names = [],
  6912. name, alias, aliases, possibleName, regex, i, ln;
  6913. if (expression.indexOf('*') !== -1) {
  6914. expression = expression.replace(/\*/g, '(.*?)');
  6915. regex = new RegExp('^' + expression + '$');
  6916. for (name in nameToAliasesMap) {
  6917. if (nameToAliasesMap.hasOwnProperty(name)) {
  6918. aliases = nameToAliasesMap[name];
  6919. if (name.search(regex) !== -1) {
  6920. names.push(name);
  6921. }
  6922. else {
  6923. for (i = 0, ln = aliases.length; i < ln; i++) {
  6924. alias = aliases[i];
  6925. if (alias.search(regex) !== -1) {
  6926. names.push(name);
  6927. break;
  6928. }
  6929. }
  6930. }
  6931. }
  6932. }
  6933. } else {
  6934. possibleName = this.getNameByAlias(expression);
  6935. if (possibleName) {
  6936. names.push(possibleName);
  6937. } else {
  6938. possibleName = this.getNameByAlternate(expression);
  6939. if (possibleName) {
  6940. names.push(possibleName);
  6941. } else {
  6942. names.push(expression);
  6943. }
  6944. }
  6945. }
  6946. return names;
  6947. }
  6948. };
  6949. /**
  6950. * @cfg {String[]} alias
  6951. * @member Ext.Class
  6952. * List of short aliases for class names. Most useful for defining xtypes for widgets:
  6953. *
  6954. * Ext.define('MyApp.CoolPanel', {
  6955. * extend: 'Ext.panel.Panel',
  6956. * alias: ['widget.coolpanel'],
  6957. * title: 'Yeah!'
  6958. * });
  6959. *
  6960. * // Using Ext.create
  6961. * Ext.create('widget.coolpanel');
  6962. *
  6963. * // Using the shorthand for defining widgets by xtype
  6964. * Ext.widget('panel', {
  6965. * items: [
  6966. * {xtype: 'coolpanel', html: 'Foo'},
  6967. * {xtype: 'coolpanel', html: 'Bar'}
  6968. * ]
  6969. * });
  6970. *
  6971. * Besides "widget" for xtype there are alias namespaces like "feature" for ftype and "plugin" for ptype.
  6972. */
  6973. Manager.registerPostprocessor('alias', function(name, cls, data) {
  6974. var aliases = data.alias,
  6975. i, ln;
  6976. for (i = 0,ln = aliases.length; i < ln; i++) {
  6977. alias = aliases[i];
  6978. this.setAlias(cls, alias);
  6979. }
  6980. }, ['xtype', 'alias']);
  6981. /**
  6982. * @cfg {Boolean} singleton
  6983. * @member Ext.Class
  6984. * When set to true, the class will be instantiated as singleton. For example:
  6985. *
  6986. * Ext.define('Logger', {
  6987. * singleton: true,
  6988. * log: function(msg) {
  6989. * console.log(msg);
  6990. * }
  6991. * });
  6992. *
  6993. * Logger.log('Hello');
  6994. */
  6995. Manager.registerPostprocessor('singleton', function(name, cls, data, fn) {
  6996. fn.call(this, name, new cls(), data);
  6997. return false;
  6998. });
  6999. /**
  7000. * @cfg {String/String[]} alternateClassName
  7001. * @member Ext.Class
  7002. * Defines alternate names for this class. For example:
  7003. *
  7004. * Ext.define('Developer', {
  7005. * alternateClassName: ['Coder', 'Hacker'],
  7006. * code: function(msg) {
  7007. * alert('Typing... ' + msg);
  7008. * }
  7009. * });
  7010. *
  7011. * var joe = Ext.create('Developer');
  7012. * joe.code('stackoverflow');
  7013. *
  7014. * var rms = Ext.create('Hacker');
  7015. * rms.code('hack hack');
  7016. */
  7017. Manager.registerPostprocessor('alternateClassName', function(name, cls, data) {
  7018. var alternates = data.alternateClassName,
  7019. i, ln, alternate;
  7020. if (!(alternates instanceof Array)) {
  7021. alternates = [alternates];
  7022. }
  7023. for (i = 0, ln = alternates.length; i < ln; i++) {
  7024. alternate = alternates[i];
  7025. this.set(alternate, cls);
  7026. }
  7027. });
  7028. Ext.apply(Ext, {
  7029. /**
  7030. * Instantiate a class by either full name, alias or alternate name.
  7031. *
  7032. * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has
  7033. * not been defined yet, it will attempt to load the class via synchronous loading.
  7034. *
  7035. * For example, all these three lines return the same result:
  7036. *
  7037. * // alias
  7038. * var window = Ext.create('widget.window', {
  7039. * width: 600,
  7040. * height: 800,
  7041. * ...
  7042. * });
  7043. *
  7044. * // alternate name
  7045. * var window = Ext.create('Ext.Window', {
  7046. * width: 600,
  7047. * height: 800,
  7048. * ...
  7049. * });
  7050. *
  7051. * // full class name
  7052. * var window = Ext.create('Ext.window.Window', {
  7053. * width: 600,
  7054. * height: 800,
  7055. * ...
  7056. * });
  7057. *
  7058. * // single object with xclass property:
  7059. * var window = Ext.create({
  7060. * xclass: 'Ext.window.Window', // any valid value for 'name' (above)
  7061. * width: 600,
  7062. * height: 800,
  7063. * ...
  7064. * });
  7065. *
  7066. * @param {String} [name] The class name or alias. Can be specified as `xclass`
  7067. * property if only one object parameter is specified.
  7068. * @param {Object...} [args] Additional arguments after the name will be passed to
  7069. * the class' constructor.
  7070. * @return {Object} instance
  7071. * @member Ext
  7072. * @method create
  7073. */
  7074. create: alias(Manager, 'instantiate'),
  7075. /**
  7076. * Convenient shorthand to create a widget by its xtype or a config object.
  7077. * See also {@link Ext.ClassManager#instantiateByAlias}.
  7078. *
  7079. * var button = Ext.widget('button'); // Equivalent to Ext.create('widget.button');
  7080. *
  7081. * var panel = Ext.widget('panel', { // Equivalent to Ext.create('widget.panel')
  7082. * title: 'Panel'
  7083. * });
  7084. *
  7085. * var grid = Ext.widget({
  7086. * xtype: 'grid',
  7087. * ...
  7088. * });
  7089. *
  7090. * If a {@link Ext.Component component} instance is passed, it is simply returned.
  7091. *
  7092. * @member Ext
  7093. * @param {String} [name] The xtype of the widget to create.
  7094. * @param {Object} [config] The configuration object for the widget constructor.
  7095. * @return {Object} The widget instance
  7096. */
  7097. widget: function(name, config) {
  7098. // forms:
  7099. // 1: (xtype)
  7100. // 2: (xtype, config)
  7101. // 3: (config)
  7102. // 4: (xtype, component)
  7103. // 5: (component)
  7104. //
  7105. var xtype = name,
  7106. alias, className, T, load;
  7107. if (typeof xtype != 'string') { // if (form 3 or 5)
  7108. // first arg is config or component
  7109. config = name; // arguments[0]
  7110. if (config.isComponent) {
  7111. return config;
  7112. }
  7113. xtype = config.xtype;
  7114. }
  7115. alias = 'widget.' + xtype;
  7116. className = Manager.getNameByAlias(alias);
  7117. // this is needed to support demand loading of the class
  7118. if (!className) {
  7119. load = true;
  7120. }
  7121. T = Manager.get(className);
  7122. if (load || !T) {
  7123. return Manager.instantiateByAlias(alias, config || {});
  7124. }
  7125. return new T(config);
  7126. },
  7127. /**
  7128. * Convenient shorthand, see {@link Ext.ClassManager#instantiateByAlias}
  7129. * @member Ext
  7130. * @method createByAlias
  7131. */
  7132. createByAlias: alias(Manager, 'instantiateByAlias'),
  7133. /**
  7134. * @method
  7135. * Defines a class or override. A basic class is defined like this:
  7136. *
  7137. * Ext.define('My.awesome.Class', {
  7138. * someProperty: 'something',
  7139. *
  7140. * someMethod: function() {
  7141. * alert(s + this.someProperty);
  7142. * }
  7143. *
  7144. * ...
  7145. * });
  7146. *
  7147. * var obj = new My.awesome.Class();
  7148. *
  7149. * obj.someMethod('Say '); // alerts 'Say something'
  7150. *
  7151. * To defines an override, include the `override` property. The content of an
  7152. * override is aggregated with the specified class in order to extend or modify
  7153. * that class. This can be as simple as setting default property values or it can
  7154. * extend and/or replace methods. This can also extend the statics of the class.
  7155. *
  7156. * One use for an override is to break a large class into manageable pieces.
  7157. *
  7158. * // File: /src/app/Panel.js
  7159. *
  7160. * Ext.define('My.app.Panel', {
  7161. * extend: 'Ext.panel.Panel',
  7162. * requires: [
  7163. * 'My.app.PanelPart2',
  7164. * 'My.app.PanelPart3'
  7165. * ]
  7166. *
  7167. * constructor: function (config) {
  7168. * this.callParent(arguments); // calls Ext.panel.Panel's constructor
  7169. * //...
  7170. * },
  7171. *
  7172. * statics: {
  7173. * method: function () {
  7174. * return 'abc';
  7175. * }
  7176. * }
  7177. * });
  7178. *
  7179. * // File: /src/app/PanelPart2.js
  7180. * Ext.define('My.app.PanelPart2', {
  7181. * override: 'My.app.Panel',
  7182. *
  7183. * constructor: function (config) {
  7184. * this.callParent(arguments); // calls My.app.Panel's constructor
  7185. * //...
  7186. * }
  7187. * });
  7188. *
  7189. * Another use of overrides is to provide optional parts of classes that can be
  7190. * independently required. In this case, the class may even be unaware of the
  7191. * override altogether.
  7192. *
  7193. * Ext.define('My.ux.CoolTip', {
  7194. * override: 'Ext.tip.ToolTip',
  7195. *
  7196. * constructor: function (config) {
  7197. * this.callParent(arguments); // calls Ext.tip.ToolTip's constructor
  7198. * //...
  7199. * }
  7200. * });
  7201. *
  7202. * The above override can now be required as normal.
  7203. *
  7204. * Ext.define('My.app.App', {
  7205. * requires: [
  7206. * 'My.ux.CoolTip'
  7207. * ]
  7208. * });
  7209. *
  7210. * Overrides can also contain statics:
  7211. *
  7212. * Ext.define('My.app.BarMod', {
  7213. * override: 'Ext.foo.Bar',
  7214. *
  7215. * statics: {
  7216. * method: function (x) {
  7217. * return this.callParent([x * 2]); // call Ext.foo.Bar.method
  7218. * }
  7219. * }
  7220. * });
  7221. *
  7222. * IMPORTANT: An override is only included in a build if the class it overrides is
  7223. * required. Otherwise, the override, like the target class, is not included.
  7224. *
  7225. * @param {String} className The class name to create in string dot-namespaced format, for example:
  7226. * 'My.very.awesome.Class', 'FeedViewer.plugin.CoolPager'
  7227. * It is highly recommended to follow this simple convention:
  7228. * - The root and the class name are 'CamelCased'
  7229. * - Everything else is lower-cased
  7230. * @param {Object} data The key - value pairs of properties to apply to this class. Property names can be of any valid
  7231. * strings, except those in the reserved listed below:
  7232. * - `mixins`
  7233. * - `statics`
  7234. * - `config`
  7235. * - `alias`
  7236. * - `self`
  7237. * - `singleton`
  7238. * - `alternateClassName`
  7239. * - `override`
  7240. *
  7241. * @param {Function} createdFn Optional callback to execute after the class is created, the execution scope of which
  7242. * (`this`) will be the newly created class itself.
  7243. * @return {Ext.Base}
  7244. * @markdown
  7245. * @member Ext
  7246. * @method define
  7247. */
  7248. define: function (className, data, createdFn) {
  7249. if (data.override) {
  7250. return Manager.createOverride.apply(Manager, arguments);
  7251. }
  7252. return Manager.create.apply(Manager, arguments);
  7253. },
  7254. /**
  7255. * Convenient shorthand, see {@link Ext.ClassManager#getName}
  7256. * @member Ext
  7257. * @method getClassName
  7258. */
  7259. getClassName: alias(Manager, 'getName'),
  7260. /**
  7261. * Returns the displayName property or className or object. When all else fails, returns "Anonymous".
  7262. * @param {Object} object
  7263. * @return {String}
  7264. */
  7265. getDisplayName: function(object) {
  7266. if (object) {
  7267. if (object.displayName) {
  7268. return object.displayName;
  7269. }
  7270. if (object.$name && object.$class) {
  7271. return Ext.getClassName(object.$class) + '#' + object.$name;
  7272. }
  7273. if (object.$className) {
  7274. return object.$className;
  7275. }
  7276. }
  7277. return 'Anonymous';
  7278. },
  7279. /**
  7280. * Convenient shorthand, see {@link Ext.ClassManager#getClass}
  7281. * @member Ext
  7282. * @method getClass
  7283. */
  7284. getClass: alias(Manager, 'getClass'),
  7285. /**
  7286. * Creates namespaces to be used for scoping variables and classes so that they are not global.
  7287. * Specifying the last node of a namespace implicitly creates all other nodes. Usage:
  7288. *
  7289. * Ext.namespace('Company', 'Company.data');
  7290. *
  7291. * // equivalent and preferable to the above syntax
  7292. * Ext.ns('Company.data');
  7293. *
  7294. * Company.Widget = function() { ... };
  7295. *
  7296. * Company.data.CustomStore = function(config) { ... };
  7297. *
  7298. * @param {String...} namespaces
  7299. * @return {Object} The namespace object.
  7300. * (If multiple arguments are passed, this will be the last namespace created)
  7301. * @member Ext
  7302. * @method namespace
  7303. */
  7304. namespace: alias(Manager, 'createNamespaces')
  7305. });
  7306. /**
  7307. * Old name for {@link Ext#widget}.
  7308. * @deprecated 4.0.0 Use {@link Ext#widget} instead.
  7309. * @method createWidget
  7310. * @member Ext
  7311. */
  7312. Ext.createWidget = Ext.widget;
  7313. /**
  7314. * Convenient alias for {@link Ext#namespace Ext.namespace}.
  7315. * @inheritdoc Ext#namespace
  7316. * @member Ext
  7317. * @method ns
  7318. */
  7319. Ext.ns = Ext.namespace;
  7320. Class.registerPreprocessor('className', function(cls, data) {
  7321. if (data.$className) {
  7322. cls.$className = data.$className;
  7323. }
  7324. }, true, 'first');
  7325. Class.registerPreprocessor('alias', function(cls, data) {
  7326. var prototype = cls.prototype,
  7327. xtypes = arrayFrom(data.xtype),
  7328. aliases = arrayFrom(data.alias),
  7329. widgetPrefix = 'widget.',
  7330. widgetPrefixLength = widgetPrefix.length,
  7331. xtypesChain = Array.prototype.slice.call(prototype.xtypesChain || []),
  7332. xtypesMap = Ext.merge({}, prototype.xtypesMap || {}),
  7333. i, ln, alias, xtype;
  7334. for (i = 0,ln = aliases.length; i < ln; i++) {
  7335. alias = aliases[i];
  7336. if (alias.substring(0, widgetPrefixLength) === widgetPrefix) {
  7337. xtype = alias.substring(widgetPrefixLength);
  7338. Ext.Array.include(xtypes, xtype);
  7339. }
  7340. }
  7341. cls.xtype = data.xtype = xtypes[0];
  7342. data.xtypes = xtypes;
  7343. for (i = 0,ln = xtypes.length; i < ln; i++) {
  7344. xtype = xtypes[i];
  7345. if (!xtypesMap[xtype]) {
  7346. xtypesMap[xtype] = true;
  7347. xtypesChain.push(xtype);
  7348. }
  7349. }
  7350. data.xtypesChain = xtypesChain;
  7351. data.xtypesMap = xtypesMap;
  7352. Ext.Function.interceptAfter(data, 'onClassCreated', function() {
  7353. var mixins = prototype.mixins,
  7354. key, mixin;
  7355. for (key in mixins) {
  7356. if (mixins.hasOwnProperty(key)) {
  7357. mixin = mixins[key];
  7358. xtypes = mixin.xtypes;
  7359. if (xtypes) {
  7360. for (i = 0,ln = xtypes.length; i < ln; i++) {
  7361. xtype = xtypes[i];
  7362. if (!xtypesMap[xtype]) {
  7363. xtypesMap[xtype] = true;
  7364. xtypesChain.push(xtype);
  7365. }
  7366. }
  7367. }
  7368. }
  7369. }
  7370. });
  7371. for (i = 0,ln = xtypes.length; i < ln; i++) {
  7372. xtype = xtypes[i];
  7373. Ext.Array.include(aliases, widgetPrefix + xtype);
  7374. }
  7375. data.alias = aliases;
  7376. }, ['xtype', 'alias']);
  7377. })(Ext.Class, Ext.Function.alias, Array.prototype.slice, Ext.Array.from, Ext.global);
  7378. /**
  7379. * @author Jacky Nguyen <jacky@sencha.com>
  7380. * @docauthor Jacky Nguyen <jacky@sencha.com>
  7381. * @class Ext.Loader
  7382. *
  7383. * Ext.Loader is the heart of the new dynamic dependency loading capability in Ext JS 4+. It is most commonly used
  7384. * via the {@link Ext#require} shorthand. Ext.Loader supports both asynchronous and synchronous loading
  7385. * approaches, and leverage their advantages for the best development flow. We'll discuss about the pros and cons of each approach:
  7386. *
  7387. * # Asynchronous Loading #
  7388. *
  7389. * - Advantages:
  7390. * + Cross-domain
  7391. * + No web server needed: you can run the application via the file system protocol (i.e: `file://path/to/your/index
  7392. * .html`)
  7393. * + Best possible debugging experience: error messages come with the exact file name and line number
  7394. *
  7395. * - Disadvantages:
  7396. * + Dependencies need to be specified before-hand
  7397. *
  7398. * ### Method 1: Explicitly include what you need: ###
  7399. *
  7400. * // Syntax
  7401. * Ext.require({String/Array} expressions);
  7402. *
  7403. * // Example: Single alias
  7404. * Ext.require('widget.window');
  7405. *
  7406. * // Example: Single class name
  7407. * Ext.require('Ext.window.Window');
  7408. *
  7409. * // Example: Multiple aliases / class names mix
  7410. * Ext.require(['widget.window', 'layout.border', 'Ext.data.Connection']);
  7411. *
  7412. * // Wildcards
  7413. * Ext.require(['widget.*', 'layout.*', 'Ext.data.*']);
  7414. *
  7415. * ### Method 2: Explicitly exclude what you don't need: ###
  7416. *
  7417. * // Syntax: Note that it must be in this chaining format.
  7418. * Ext.exclude({String/Array} expressions)
  7419. * .require({String/Array} expressions);
  7420. *
  7421. * // Include everything except Ext.data.*
  7422. * Ext.exclude('Ext.data.*').require('*');
  7423. *
  7424. * // Include all widgets except widget.checkbox*,
  7425. * // which will match widget.checkbox, widget.checkboxfield, widget.checkboxgroup, etc.
  7426. * Ext.exclude('widget.checkbox*').require('widget.*');
  7427. *
  7428. * # Synchronous Loading on Demand #
  7429. *
  7430. * - Advantages:
  7431. * + There's no need to specify dependencies before-hand, which is always the convenience of including ext-all.js
  7432. * before
  7433. *
  7434. * - Disadvantages:
  7435. * + Not as good debugging experience since file name won't be shown (except in Firebug at the moment)
  7436. * + Must be from the same domain due to XHR restriction
  7437. * + Need a web server, same reason as above
  7438. *
  7439. * There's one simple rule to follow: Instantiate everything with Ext.create instead of the `new` keyword
  7440. *
  7441. * Ext.create('widget.window', { ... }); // Instead of new Ext.window.Window({...});
  7442. *
  7443. * Ext.create('Ext.window.Window', {}); // Same as above, using full class name instead of alias
  7444. *
  7445. * Ext.widget('window', {}); // Same as above, all you need is the traditional `xtype`
  7446. *
  7447. * Behind the scene, {@link Ext.ClassManager} will automatically check whether the given class name / alias has already
  7448. * existed on the page. If it's not, Ext.Loader will immediately switch itself to synchronous mode and automatic load the given
  7449. * class and all its dependencies.
  7450. *
  7451. * # Hybrid Loading - The Best of Both Worlds #
  7452. *
  7453. * It has all the advantages combined from asynchronous and synchronous loading. The development flow is simple:
  7454. *
  7455. * ### Step 1: Start writing your application using synchronous approach.
  7456. *
  7457. * Ext.Loader will automatically fetch all dependencies on demand as they're needed during run-time. For example:
  7458. *
  7459. * Ext.onReady(function(){
  7460. * var window = Ext.createWidget('window', {
  7461. * width: 500,
  7462. * height: 300,
  7463. * layout: {
  7464. * type: 'border',
  7465. * padding: 5
  7466. * },
  7467. * title: 'Hello Dialog',
  7468. * items: [{
  7469. * title: 'Navigation',
  7470. * collapsible: true,
  7471. * region: 'west',
  7472. * width: 200,
  7473. * html: 'Hello',
  7474. * split: true
  7475. * }, {
  7476. * title: 'TabPanel',
  7477. * region: 'center'
  7478. * }]
  7479. * });
  7480. *
  7481. * window.show();
  7482. * })
  7483. *
  7484. * ### Step 2: Along the way, when you need better debugging ability, watch the console for warnings like these: ###
  7485. *
  7486. * [Ext.Loader] Synchronously loading 'Ext.window.Window'; consider adding Ext.require('Ext.window.Window') before your application's code
  7487. * ClassManager.js:432
  7488. * [Ext.Loader] Synchronously loading 'Ext.layout.container.Border'; consider adding Ext.require('Ext.layout.container.Border') before your application's code
  7489. *
  7490. * Simply copy and paste the suggested code above `Ext.onReady`, i.e:
  7491. *
  7492. * Ext.require('Ext.window.Window');
  7493. * Ext.require('Ext.layout.container.Border');
  7494. *
  7495. * Ext.onReady(...);
  7496. *
  7497. * Everything should now load via asynchronous mode.
  7498. *
  7499. * # Deployment #
  7500. *
  7501. * It's important to note that dynamic loading should only be used during development on your local machines.
  7502. * During production, all dependencies should be combined into one single JavaScript file. Ext.Loader makes
  7503. * the whole process of transitioning from / to between development / maintenance and production as easy as
  7504. * possible. Internally {@link Ext.Loader#history Ext.Loader.history} maintains the list of all dependencies your application
  7505. * needs in the exact loading sequence. It's as simple as concatenating all files in this array into one,
  7506. * then include it on top of your application.
  7507. *
  7508. * This process will be automated with Sencha Command, to be released and documented towards Ext JS 4 Final.
  7509. *
  7510. * @singleton
  7511. */
  7512. (function(Manager, Class, flexSetter, alias, pass, arrayFrom, arrayErase, arrayInclude) {
  7513. var
  7514. dependencyProperties = ['extend', 'mixins', 'requires'],
  7515. Loader;
  7516. Loader = Ext.Loader = {
  7517. /**
  7518. * @private
  7519. */
  7520. isInHistory: {},
  7521. /**
  7522. * An array of class names to keep track of the dependency loading order.
  7523. * This is not guaranteed to be the same everytime due to the asynchronous
  7524. * nature of the Loader.
  7525. *
  7526. * @property {Array} history
  7527. */
  7528. history: [],
  7529. /**
  7530. * Configuration
  7531. * @private
  7532. */
  7533. config: {
  7534. /**
  7535. * @cfg {Boolean} enabled
  7536. * Whether or not to enable the dynamic dependency loading feature.
  7537. */
  7538. enabled: false,
  7539. /**
  7540. * @cfg {Boolean} disableCaching
  7541. * Appends current timestamp to script files to prevent caching.
  7542. */
  7543. disableCaching: true,
  7544. /**
  7545. * @cfg {String} disableCachingParam
  7546. * The get parameter name for the cache buster's timestamp.
  7547. */
  7548. disableCachingParam: '_dc',
  7549. /**
  7550. * @cfg {Object} paths
  7551. * The mapping from namespaces to file paths
  7552. *
  7553. * {
  7554. * 'Ext': '.', // This is set by default, Ext.layout.container.Container will be
  7555. * // loaded from ./layout/Container.js
  7556. *
  7557. * 'My': './src/my_own_folder' // My.layout.Container will be loaded from
  7558. * // ./src/my_own_folder/layout/Container.js
  7559. * }
  7560. *
  7561. * Note that all relative paths are relative to the current HTML document.
  7562. * If not being specified, for example, <code>Other.awesome.Class</code>
  7563. * will simply be loaded from <code>./Other/awesome/Class.js</code>
  7564. */
  7565. paths: {
  7566. 'Ext': '.'
  7567. }
  7568. },
  7569. /**
  7570. * Set the configuration for the loader. This should be called right after ext-(debug).js
  7571. * is included in the page, and before Ext.onReady. i.e:
  7572. *
  7573. * <script type="text/javascript" src="ext-core-debug.js"></script>
  7574. * <script type="text/javascript">
  7575. * Ext.Loader.setConfig({
  7576. * enabled: true,
  7577. * paths: {
  7578. * 'My': 'my_own_path'
  7579. * }
  7580. * });
  7581. * </script>
  7582. * <script type="text/javascript">
  7583. * Ext.require(...);
  7584. *
  7585. * Ext.onReady(function() {
  7586. * // application code here
  7587. * });
  7588. * </script>
  7589. *
  7590. * Refer to config options of {@link Ext.Loader} for the list of possible properties
  7591. *
  7592. * @param {Object} config The config object to override the default values
  7593. * @return {Ext.Loader} this
  7594. */
  7595. setConfig: function(name, value) {
  7596. if (Ext.isObject(name) && arguments.length === 1) {
  7597. Ext.merge(this.config, name);
  7598. }
  7599. else {
  7600. this.config[name] = (Ext.isObject(value)) ? Ext.merge(this.config[name], value) : value;
  7601. }
  7602. return this;
  7603. },
  7604. /**
  7605. * Get the config value corresponding to the specified name. If no name is given, will return the config object
  7606. * @param {String} name The config property name
  7607. * @return {Object}
  7608. */
  7609. getConfig: function(name) {
  7610. if (name) {
  7611. return this.config[name];
  7612. }
  7613. return this.config;
  7614. },
  7615. /**
  7616. * Sets the path of a namespace.
  7617. * For Example:
  7618. *
  7619. * Ext.Loader.setPath('Ext', '.');
  7620. *
  7621. * @param {String/Object} name See {@link Ext.Function#flexSetter flexSetter}
  7622. * @param {String} path See {@link Ext.Function#flexSetter flexSetter}
  7623. * @return {Ext.Loader} this
  7624. * @method
  7625. */
  7626. setPath: flexSetter(function(name, path) {
  7627. this.config.paths[name] = path;
  7628. return this;
  7629. }),
  7630. /**
  7631. * Translates a className to a file path by adding the
  7632. * the proper prefix and converting the .'s to /'s. For example:
  7633. *
  7634. * Ext.Loader.setPath('My', '/path/to/My');
  7635. *
  7636. * alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/path/to/My/awesome/Class.js'
  7637. *
  7638. * Note that the deeper namespace levels, if explicitly set, are always resolved first. For example:
  7639. *
  7640. * Ext.Loader.setPath({
  7641. * 'My': '/path/to/lib',
  7642. * 'My.awesome': '/other/path/for/awesome/stuff',
  7643. * 'My.awesome.more': '/more/awesome/path'
  7644. * });
  7645. *
  7646. * alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/other/path/for/awesome/stuff/Class.js'
  7647. *
  7648. * alert(Ext.Loader.getPath('My.awesome.more.Class')); // alerts '/more/awesome/path/Class.js'
  7649. *
  7650. * alert(Ext.Loader.getPath('My.cool.Class')); // alerts '/path/to/lib/cool/Class.js'
  7651. *
  7652. * alert(Ext.Loader.getPath('Unknown.strange.Stuff')); // alerts 'Unknown/strange/Stuff.js'
  7653. *
  7654. * @param {String} className
  7655. * @return {String} path
  7656. */
  7657. getPath: function(className) {
  7658. var path = '',
  7659. paths = this.config.paths,
  7660. prefix = this.getPrefix(className);
  7661. if (prefix.length > 0) {
  7662. if (prefix === className) {
  7663. return paths[prefix];
  7664. }
  7665. path = paths[prefix];
  7666. className = className.substring(prefix.length + 1);
  7667. }
  7668. if (path.length > 0) {
  7669. path += '/';
  7670. }
  7671. return path.replace(/\/\.\//g, '/') + className.replace(/\./g, "/") + '.js';
  7672. },
  7673. /**
  7674. * @private
  7675. * @param {String} className
  7676. */
  7677. getPrefix: function(className) {
  7678. var paths = this.config.paths,
  7679. prefix, deepestPrefix = '';
  7680. if (paths.hasOwnProperty(className)) {
  7681. return className;
  7682. }
  7683. for (prefix in paths) {
  7684. if (paths.hasOwnProperty(prefix) && prefix + '.' === className.substring(0, prefix.length + 1)) {
  7685. if (prefix.length > deepestPrefix.length) {
  7686. deepestPrefix = prefix;
  7687. }
  7688. }
  7689. }
  7690. return deepestPrefix;
  7691. },
  7692. /**
  7693. * Loads all classes by the given names and all their direct dependencies; optionally executes the given callback function when
  7694. * finishes, within the optional scope. This method is aliased by {@link Ext#require Ext.require} for convenience
  7695. * @param {String/Array} expressions Can either be a string or an array of string
  7696. * @param {Function} fn (Optional) The callback function
  7697. * @param {Object} scope (Optional) The execution scope (`this`) of the callback function
  7698. * @param {String/Array} excludes (Optional) Classes to be excluded, useful when being used with expressions
  7699. */
  7700. require: function(expressions, fn, scope, excludes) {
  7701. if (fn) {
  7702. fn.call(scope);
  7703. }
  7704. },
  7705. /**
  7706. * Synchronously loads all classes by the given names and all their direct dependencies; optionally executes the given callback function when finishes, within the optional scope. This method is aliased by {@link Ext#syncRequire} for convenience
  7707. * @param {String/Array} expressions Can either be a string or an array of string
  7708. * @param {Function} fn (Optional) The callback function
  7709. * @param {Object} scope (Optional) The execution scope (`this`) of the callback function
  7710. * @param {String/Array} excludes (Optional) Classes to be excluded, useful when being used with expressions
  7711. */
  7712. syncRequire: function() {},
  7713. /**
  7714. * Explicitly exclude files from being loaded. Useful when used in conjunction with a broad include expression.
  7715. * Can be chained with more `require` and `exclude` methods, eg:
  7716. *
  7717. * Ext.exclude('Ext.data.*').require('*');
  7718. *
  7719. * Ext.exclude('widget.button*').require('widget.*');
  7720. *
  7721. * @param {Array} excludes
  7722. * @return {Object} object contains `require` method for chaining
  7723. */
  7724. exclude: function(excludes) {
  7725. var me = this;
  7726. return {
  7727. require: function(expressions, fn, scope) {
  7728. return me.require(expressions, fn, scope, excludes);
  7729. },
  7730. syncRequire: function(expressions, fn, scope) {
  7731. return me.syncRequire(expressions, fn, scope, excludes);
  7732. }
  7733. };
  7734. },
  7735. /**
  7736. * Add a new listener to be executed when all required scripts are fully loaded
  7737. *
  7738. * @param {Function} fn The function callback to be executed
  7739. * @param {Object} scope The execution scope (<code>this</code>) of the callback function
  7740. * @param {Boolean} withDomReady Whether or not to wait for document dom ready as well
  7741. */
  7742. onReady: function(fn, scope, withDomReady, options) {
  7743. var oldFn;
  7744. if (withDomReady !== false && Ext.onDocumentReady) {
  7745. oldFn = fn;
  7746. fn = function() {
  7747. Ext.onDocumentReady(oldFn, scope, options);
  7748. };
  7749. }
  7750. fn.call(scope);
  7751. }
  7752. };
  7753. Ext.apply(Loader, {
  7754. /**
  7755. * @private
  7756. */
  7757. documentHead: typeof document != 'undefined' && (document.head || document.getElementsByTagName('head')[0]),
  7758. /**
  7759. * Flag indicating whether there are still files being loaded
  7760. * @private
  7761. */
  7762. isLoading: false,
  7763. /**
  7764. * Maintain the queue for all dependencies. Each item in the array is an object of the format:
  7765. *
  7766. * {
  7767. * requires: [...], // The required classes for this queue item
  7768. * callback: function() { ... } // The function to execute when all classes specified in requires exist
  7769. * }
  7770. *
  7771. * @private
  7772. */
  7773. queue: [],
  7774. /**
  7775. * Maintain the list of files that have already been handled so that they never get double-loaded
  7776. * @private
  7777. */
  7778. isClassFileLoaded: {},
  7779. /**
  7780. * @private
  7781. */
  7782. isFileLoaded: {},
  7783. /**
  7784. * Maintain the list of listeners to execute when all required scripts are fully loaded
  7785. * @private
  7786. */
  7787. readyListeners: [],
  7788. /**
  7789. * Contains optional dependencies to be loaded last
  7790. * @private
  7791. */
  7792. optionalRequires: [],
  7793. /**
  7794. * Map of fully qualified class names to an array of dependent classes.
  7795. * @private
  7796. */
  7797. requiresMap: {},
  7798. /**
  7799. * @private
  7800. */
  7801. numPendingFiles: 0,
  7802. /**
  7803. * @private
  7804. */
  7805. numLoadedFiles: 0,
  7806. /** @private */
  7807. hasFileLoadError: false,
  7808. /**
  7809. * @private
  7810. */
  7811. classNameToFilePathMap: {},
  7812. /**
  7813. * @private
  7814. */
  7815. syncModeEnabled: false,
  7816. scriptElements: {},
  7817. /**
  7818. * Refresh all items in the queue. If all dependencies for an item exist during looping,
  7819. * it will execute the callback and call refreshQueue again. Triggers onReady when the queue is
  7820. * empty
  7821. * @private
  7822. */
  7823. refreshQueue: function() {
  7824. var queue = this.queue,
  7825. ln = queue.length,
  7826. i, item, j, requires, references;
  7827. if (ln === 0) {
  7828. this.triggerReady();
  7829. return;
  7830. }
  7831. for (i = 0; i < ln; i++) {
  7832. item = queue[i];
  7833. if (item) {
  7834. requires = item.requires;
  7835. references = item.references;
  7836. // Don't bother checking when the number of files loaded
  7837. // is still less than the array length
  7838. if (requires.length > this.numLoadedFiles) {
  7839. continue;
  7840. }
  7841. j = 0;
  7842. do {
  7843. if (Manager.isCreated(requires[j])) {
  7844. // Take out from the queue
  7845. arrayErase(requires, j, 1);
  7846. }
  7847. else {
  7848. j++;
  7849. }
  7850. } while (j < requires.length);
  7851. if (item.requires.length === 0) {
  7852. arrayErase(queue, i, 1);
  7853. item.callback.call(item.scope);
  7854. this.refreshQueue();
  7855. break;
  7856. }
  7857. }
  7858. }
  7859. return this;
  7860. },
  7861. /**
  7862. * Inject a script element to document's head, call onLoad and onError accordingly
  7863. * @private
  7864. */
  7865. injectScriptElement: function(url, onLoad, onError, scope) {
  7866. var script = document.createElement('script'),
  7867. me = this,
  7868. onLoadFn = function() {
  7869. me.cleanupScriptElement(script);
  7870. onLoad.call(scope);
  7871. },
  7872. onErrorFn = function() {
  7873. me.cleanupScriptElement(script);
  7874. onError.call(scope);
  7875. };
  7876. script.type = 'text/javascript';
  7877. script.src = url;
  7878. script.onload = onLoadFn;
  7879. script.onerror = onErrorFn;
  7880. script.onreadystatechange = function() {
  7881. if (this.readyState === 'loaded' || this.readyState === 'complete') {
  7882. onLoadFn();
  7883. }
  7884. };
  7885. this.documentHead.appendChild(script);
  7886. return script;
  7887. },
  7888. removeScriptElement: function(url) {
  7889. var scriptElements = this.scriptElements;
  7890. if (scriptElements[url]) {
  7891. this.cleanupScriptElement(scriptElements[url], true);
  7892. delete scriptElements[url];
  7893. }
  7894. return this;
  7895. },
  7896. /**
  7897. * @private
  7898. */
  7899. cleanupScriptElement: function(script, remove) {
  7900. script.onload = null;
  7901. script.onreadystatechange = null;
  7902. script.onerror = null;
  7903. if (remove) {
  7904. this.documentHead.removeChild(script);
  7905. }
  7906. return this;
  7907. },
  7908. /**
  7909. * Load a script file, supports both asynchronous and synchronous approaches
  7910. * @private
  7911. */
  7912. loadScriptFile: function(url, onLoad, onError, scope, synchronous) {
  7913. var me = this,
  7914. isFileLoaded = this.isFileLoaded,
  7915. scriptElements = this.scriptElements,
  7916. noCacheUrl = url + (this.getConfig('disableCaching') ? ('?' + this.getConfig('disableCachingParam') + '=' + Ext.Date.now()) : ''),
  7917. isCrossOriginRestricted = false,
  7918. xhr, status, onScriptError;
  7919. if (isFileLoaded[url]) {
  7920. return this;
  7921. }
  7922. scope = scope || this;
  7923. this.isLoading = true;
  7924. if (!synchronous) {
  7925. onScriptError = function() {
  7926. };
  7927. if (!Ext.isReady && Ext.onDocumentReady) {
  7928. Ext.onDocumentReady(function() {
  7929. if (!isFileLoaded[url]) {
  7930. scriptElements[url] = me.injectScriptElement(noCacheUrl, onLoad, onScriptError, scope);
  7931. }
  7932. });
  7933. }
  7934. else {
  7935. scriptElements[url] = this.injectScriptElement(noCacheUrl, onLoad, onScriptError, scope);
  7936. }
  7937. }
  7938. else {
  7939. if (typeof XMLHttpRequest != 'undefined') {
  7940. xhr = new XMLHttpRequest();
  7941. } else {
  7942. xhr = new ActiveXObject('Microsoft.XMLHTTP');
  7943. }
  7944. try {
  7945. xhr.open('GET', noCacheUrl, false);
  7946. xhr.send(null);
  7947. } catch (e) {
  7948. isCrossOriginRestricted = true;
  7949. }
  7950. status = (xhr.status === 1223) ? 204 : xhr.status;
  7951. if (!isCrossOriginRestricted) {
  7952. isCrossOriginRestricted = (status === 0);
  7953. }
  7954. if (isCrossOriginRestricted
  7955. ) {
  7956. }
  7957. else if (status >= 200 && status < 300
  7958. ) {
  7959. // Debugger friendly, file names are still shown even though they're eval'ed code
  7960. // Breakpoints work on both Firebug and Chrome's Web Inspector
  7961. Ext.globalEval(xhr.responseText + "\n//@ sourceURL=" + url);
  7962. onLoad.call(scope);
  7963. }
  7964. else {
  7965. }
  7966. // Prevent potential IE memory leak
  7967. xhr = null;
  7968. }
  7969. },
  7970. // documented above
  7971. syncRequire: function() {
  7972. var syncModeEnabled = this.syncModeEnabled;
  7973. if (!syncModeEnabled) {
  7974. this.syncModeEnabled = true;
  7975. }
  7976. this.require.apply(this, arguments);
  7977. if (!syncModeEnabled) {
  7978. this.syncModeEnabled = false;
  7979. }
  7980. this.refreshQueue();
  7981. },
  7982. // documented above
  7983. require: function(expressions, fn, scope, excludes) {
  7984. var excluded = {},
  7985. included = {},
  7986. queue = this.queue,
  7987. classNameToFilePathMap = this.classNameToFilePathMap,
  7988. isClassFileLoaded = this.isClassFileLoaded,
  7989. excludedClassNames = [],
  7990. possibleClassNames = [],
  7991. classNames = [],
  7992. references = [],
  7993. callback,
  7994. syncModeEnabled,
  7995. filePath, expression, exclude, className,
  7996. possibleClassName, i, j, ln, subLn;
  7997. if (excludes) {
  7998. excludes = arrayFrom(excludes);
  7999. for (i = 0,ln = excludes.length; i < ln; i++) {
  8000. exclude = excludes[i];
  8001. if (typeof exclude == 'string' && exclude.length > 0) {
  8002. excludedClassNames = Manager.getNamesByExpression(exclude);
  8003. for (j = 0,subLn = excludedClassNames.length; j < subLn; j++) {
  8004. excluded[excludedClassNames[j]] = true;
  8005. }
  8006. }
  8007. }
  8008. }
  8009. expressions = arrayFrom(expressions);
  8010. if (fn) {
  8011. if (fn.length > 0) {
  8012. callback = function() {
  8013. var classes = [],
  8014. i, ln, name;
  8015. for (i = 0,ln = references.length; i < ln; i++) {
  8016. name = references[i];
  8017. classes.push(Manager.get(name));
  8018. }
  8019. return fn.apply(this, classes);
  8020. };
  8021. }
  8022. else {
  8023. callback = fn;
  8024. }
  8025. }
  8026. else {
  8027. callback = Ext.emptyFn;
  8028. }
  8029. scope = scope || Ext.global;
  8030. for (i = 0,ln = expressions.length; i < ln; i++) {
  8031. expression = expressions[i];
  8032. if (typeof expression == 'string' && expression.length > 0) {
  8033. possibleClassNames = Manager.getNamesByExpression(expression);
  8034. subLn = possibleClassNames.length;
  8035. for (j = 0; j < subLn; j++) {
  8036. possibleClassName = possibleClassNames[j];
  8037. if (excluded[possibleClassName] !== true) {
  8038. references.push(possibleClassName);
  8039. if (!Manager.isCreated(possibleClassName) && !included[possibleClassName]) {
  8040. included[possibleClassName] = true;
  8041. classNames.push(possibleClassName);
  8042. }
  8043. }
  8044. }
  8045. }
  8046. }
  8047. // If the dynamic dependency feature is not being used, throw an error
  8048. // if the dependencies are not defined
  8049. if (classNames.length > 0) {
  8050. if (!this.config.enabled) {
  8051. throw new Error("Ext.Loader is not enabled, so dependencies cannot be resolved dynamically. " +
  8052. "Missing required class" + ((classNames.length > 1) ? "es" : "") + ": " + classNames.join(', '));
  8053. }
  8054. }
  8055. else {
  8056. callback.call(scope);
  8057. return this;
  8058. }
  8059. syncModeEnabled = this.syncModeEnabled;
  8060. if (!syncModeEnabled) {
  8061. queue.push({
  8062. requires: classNames.slice(), // this array will be modified as the queue is processed,
  8063. // so we need a copy of it
  8064. callback: callback,
  8065. scope: scope
  8066. });
  8067. }
  8068. ln = classNames.length;
  8069. for (i = 0; i < ln; i++) {
  8070. className = classNames[i];
  8071. filePath = this.getPath(className);
  8072. // If we are synchronously loading a file that has already been asychronously loaded before
  8073. // we need to destroy the script tag and revert the count
  8074. // This file will then be forced loaded in synchronous
  8075. if (syncModeEnabled && isClassFileLoaded.hasOwnProperty(className)) {
  8076. this.numPendingFiles--;
  8077. this.removeScriptElement(filePath);
  8078. delete isClassFileLoaded[className];
  8079. }
  8080. if (!isClassFileLoaded.hasOwnProperty(className)) {
  8081. isClassFileLoaded[className] = false;
  8082. classNameToFilePathMap[className] = filePath;
  8083. this.numPendingFiles++;
  8084. this.loadScriptFile(
  8085. filePath,
  8086. pass(this.onFileLoaded, [className, filePath], this),
  8087. pass(this.onFileLoadError, [className, filePath], this),
  8088. this,
  8089. syncModeEnabled
  8090. );
  8091. }
  8092. }
  8093. if (syncModeEnabled) {
  8094. callback.call(scope);
  8095. if (ln === 1) {
  8096. return Manager.get(className);
  8097. }
  8098. }
  8099. return this;
  8100. },
  8101. /**
  8102. * @private
  8103. * @param {String} className
  8104. * @param {String} filePath
  8105. */
  8106. onFileLoaded: function(className, filePath) {
  8107. this.numLoadedFiles++;
  8108. this.isClassFileLoaded[className] = true;
  8109. this.isFileLoaded[filePath] = true;
  8110. this.numPendingFiles--;
  8111. if (this.numPendingFiles === 0) {
  8112. this.refreshQueue();
  8113. }
  8114. },
  8115. /**
  8116. * @private
  8117. */
  8118. onFileLoadError: function(className, filePath, errorMessage, isSynchronous) {
  8119. this.numPendingFiles--;
  8120. this.hasFileLoadError = true;
  8121. },
  8122. /**
  8123. * @private
  8124. */
  8125. addOptionalRequires: function(requires) {
  8126. var optionalRequires = this.optionalRequires,
  8127. i, ln, require;
  8128. requires = arrayFrom(requires);
  8129. for (i = 0, ln = requires.length; i < ln; i++) {
  8130. require = requires[i];
  8131. arrayInclude(optionalRequires, require);
  8132. }
  8133. return this;
  8134. },
  8135. /**
  8136. * @private
  8137. */
  8138. triggerReady: function(force) {
  8139. var readyListeners = this.readyListeners,
  8140. optionalRequires = this.optionalRequires,
  8141. listener;
  8142. if (this.isLoading || force) {
  8143. this.isLoading = false;
  8144. if (optionalRequires.length !== 0) {
  8145. // Clone then empty the array to eliminate potential recursive loop issue
  8146. optionalRequires = optionalRequires.slice();
  8147. // Empty the original array
  8148. this.optionalRequires.length = 0;
  8149. this.require(optionalRequires, pass(this.triggerReady, [true], this), this);
  8150. return this;
  8151. }
  8152. while (readyListeners.length) {
  8153. listener = readyListeners.shift();
  8154. listener.fn.call(listener.scope);
  8155. if (this.isLoading) {
  8156. return this;
  8157. }
  8158. }
  8159. }
  8160. return this;
  8161. },
  8162. // Documented above already
  8163. onReady: function(fn, scope, withDomReady, options) {
  8164. var oldFn;
  8165. if (withDomReady !== false && Ext.onDocumentReady) {
  8166. oldFn = fn;
  8167. fn = function() {
  8168. Ext.onDocumentReady(oldFn, scope, options);
  8169. };
  8170. }
  8171. if (!this.isLoading) {
  8172. fn.call(scope);
  8173. }
  8174. else {
  8175. this.readyListeners.push({
  8176. fn: fn,
  8177. scope: scope
  8178. });
  8179. }
  8180. },
  8181. /**
  8182. * @private
  8183. * @param {String} className
  8184. */
  8185. historyPush: function(className) {
  8186. var isInHistory = this.isInHistory;
  8187. if (className && this.isClassFileLoaded.hasOwnProperty(className) && !isInHistory[className]) {
  8188. isInHistory[className] = true;
  8189. this.history.push(className);
  8190. }
  8191. return this;
  8192. }
  8193. });
  8194. /**
  8195. * Turns on or off the "cache buster" applied to dynamically loaded scripts. Normally
  8196. * dynamically loaded scripts have an extra query parameter appended to avoid stale
  8197. * cached scripts. This method can be used to disable this mechanism, and is primarily
  8198. * useful for testing. This is done using a cookie.
  8199. * @param {Boolean} disable True to disable the cache buster.
  8200. * @param {String} [path="/"] An optional path to scope the cookie.
  8201. * @private
  8202. */
  8203. Ext.disableCacheBuster = function (disable, path) {
  8204. var date = new Date();
  8205. date.setTime(date.getTime() + (disable ? 10*365 : -1) * 24*60*60*1000);
  8206. date = date.toGMTString();
  8207. document.cookie = 'ext-cache=1; expires=' + date + '; path='+(path || '/');
  8208. };
  8209. /**
  8210. * Convenient alias of {@link Ext.Loader#require}. Please see the introduction documentation of
  8211. * {@link Ext.Loader} for examples.
  8212. * @member Ext
  8213. * @method require
  8214. */
  8215. Ext.require = alias(Loader, 'require');
  8216. /**
  8217. * Synchronous version of {@link Ext#require}, convenient alias of {@link Ext.Loader#syncRequire}.
  8218. *
  8219. * @member Ext
  8220. * @method syncRequire
  8221. */
  8222. Ext.syncRequire = alias(Loader, 'syncRequire');
  8223. /**
  8224. * Convenient shortcut to {@link Ext.Loader#exclude}
  8225. * @member Ext
  8226. * @method exclude
  8227. */
  8228. Ext.exclude = alias(Loader, 'exclude');
  8229. /**
  8230. * @member Ext
  8231. * @method onReady
  8232. */
  8233. Ext.onReady = function(fn, scope, options) {
  8234. Loader.onReady(fn, scope, true, options);
  8235. };
  8236. /**
  8237. * @cfg {String[]} requires
  8238. * @member Ext.Class
  8239. * List of classes that have to be loaded before instantiating this class.
  8240. * For example:
  8241. *
  8242. * Ext.define('Mother', {
  8243. * requires: ['Child'],
  8244. * giveBirth: function() {
  8245. * // we can be sure that child class is available.
  8246. * return new Child();
  8247. * }
  8248. * });
  8249. */
  8250. Class.registerPreprocessor('loader', function(cls, data, hooks, continueFn) {
  8251. var me = this,
  8252. dependencies = [],
  8253. className = Manager.getName(cls),
  8254. i, j, ln, subLn, value, propertyName, propertyValue;
  8255. /*
  8256. Loop through the dependencyProperties, look for string class names and push
  8257. them into a stack, regardless of whether the property's value is a string, array or object. For example:
  8258. {
  8259. extend: 'Ext.MyClass',
  8260. requires: ['Ext.some.OtherClass'],
  8261. mixins: {
  8262. observable: 'Ext.util.Observable';
  8263. }
  8264. }
  8265. which will later be transformed into:
  8266. {
  8267. extend: Ext.MyClass,
  8268. requires: [Ext.some.OtherClass],
  8269. mixins: {
  8270. observable: Ext.util.Observable;
  8271. }
  8272. }
  8273. */
  8274. for (i = 0,ln = dependencyProperties.length; i < ln; i++) {
  8275. propertyName = dependencyProperties[i];
  8276. if (data.hasOwnProperty(propertyName)) {
  8277. propertyValue = data[propertyName];
  8278. if (typeof propertyValue == 'string') {
  8279. dependencies.push(propertyValue);
  8280. }
  8281. else if (propertyValue instanceof Array) {
  8282. for (j = 0, subLn = propertyValue.length; j < subLn; j++) {
  8283. value = propertyValue[j];
  8284. if (typeof value == 'string') {
  8285. dependencies.push(value);
  8286. }
  8287. }
  8288. }
  8289. else if (typeof propertyValue != 'function') {
  8290. for (j in propertyValue) {
  8291. if (propertyValue.hasOwnProperty(j)) {
  8292. value = propertyValue[j];
  8293. if (typeof value == 'string') {
  8294. dependencies.push(value);
  8295. }
  8296. }
  8297. }
  8298. }
  8299. }
  8300. }
  8301. if (dependencies.length === 0) {
  8302. return;
  8303. }
  8304. Loader.require(dependencies, function() {
  8305. for (i = 0,ln = dependencyProperties.length; i < ln; i++) {
  8306. propertyName = dependencyProperties[i];
  8307. if (data.hasOwnProperty(propertyName)) {
  8308. propertyValue = data[propertyName];
  8309. if (typeof propertyValue == 'string') {
  8310. data[propertyName] = Manager.get(propertyValue);
  8311. }
  8312. else if (propertyValue instanceof Array) {
  8313. for (j = 0, subLn = propertyValue.length; j < subLn; j++) {
  8314. value = propertyValue[j];
  8315. if (typeof value == 'string') {
  8316. data[propertyName][j] = Manager.get(value);
  8317. }
  8318. }
  8319. }
  8320. else if (typeof propertyValue != 'function') {
  8321. for (var k in propertyValue) {
  8322. if (propertyValue.hasOwnProperty(k)) {
  8323. value = propertyValue[k];
  8324. if (typeof value == 'string') {
  8325. data[propertyName][k] = Manager.get(value);
  8326. }
  8327. }
  8328. }
  8329. }
  8330. }
  8331. }
  8332. continueFn.call(me, cls, data, hooks);
  8333. });
  8334. return false;
  8335. }, true, 'after', 'className');
  8336. /**
  8337. * @cfg {String[]} uses
  8338. * @member Ext.Class
  8339. * List of optional classes to load together with this class. These aren't neccessarily loaded before
  8340. * this class is created, but are guaranteed to be available before Ext.onReady listeners are
  8341. * invoked. For example:
  8342. *
  8343. * Ext.define('Mother', {
  8344. * uses: ['Child'],
  8345. * giveBirth: function() {
  8346. * // This code might, or might not work:
  8347. * // return new Child();
  8348. *
  8349. * // Instead use Ext.create() to load the class at the spot if not loaded already:
  8350. * return Ext.create('Child');
  8351. * }
  8352. * });
  8353. */
  8354. Manager.registerPostprocessor('uses', function(name, cls, data) {
  8355. var uses = arrayFrom(data.uses),
  8356. items = [],
  8357. i, ln, item;
  8358. for (i = 0,ln = uses.length; i < ln; i++) {
  8359. item = uses[i];
  8360. if (typeof item == 'string') {
  8361. items.push(item);
  8362. }
  8363. }
  8364. Loader.addOptionalRequires(items);
  8365. });
  8366. Manager.onCreated(function(className) {
  8367. this.historyPush(className);
  8368. }, Loader);
  8369. })(Ext.ClassManager, Ext.Class, Ext.Function.flexSetter, Ext.Function.alias,
  8370. Ext.Function.pass, Ext.Array.from, Ext.Array.erase, Ext.Array.include);
  8371. /**
  8372. * @author Brian Moeskau <brian@sencha.com>
  8373. * @docauthor Brian Moeskau <brian@sencha.com>
  8374. *
  8375. * A wrapper class for the native JavaScript Error object that adds a few useful capabilities for handling
  8376. * errors in an Ext application. When you use Ext.Error to {@link #raise} an error from within any class that
  8377. * uses the Ext 4 class system, the Error class can automatically add the source class and method from which
  8378. * the error was raised. It also includes logic to automatically log the eroor to the console, if available,
  8379. * with additional metadata about the error. In all cases, the error will always be thrown at the end so that
  8380. * execution will halt.
  8381. *
  8382. * Ext.Error also offers a global error {@link #handle handling} method that can be overridden in order to
  8383. * handle application-wide errors in a single spot. You can optionally {@link #ignore} errors altogether,
  8384. * although in a real application it's usually a better idea to override the handling function and perform
  8385. * logging or some other method of reporting the errors in a way that is meaningful to the application.
  8386. *
  8387. * At its simplest you can simply raise an error as a simple string from within any code:
  8388. *
  8389. * Example usage:
  8390. *
  8391. * Ext.Error.raise('Something bad happened!');
  8392. *
  8393. * If raised from plain JavaScript code, the error will be logged to the console (if available) and the message
  8394. * displayed. In most cases however you'll be raising errors from within a class, and it may often be useful to add
  8395. * additional metadata about the error being raised. The {@link #raise} method can also take a config object.
  8396. * In this form the `msg` attribute becomes the error description, and any other data added to the config gets
  8397. * added to the error object and, if the console is available, logged to the console for inspection.
  8398. *
  8399. * Example usage:
  8400. *
  8401. * Ext.define('Ext.Foo', {
  8402. * doSomething: function(option){
  8403. * if (someCondition === false) {
  8404. * Ext.Error.raise({
  8405. * msg: 'You cannot do that!',
  8406. * option: option, // whatever was passed into the method
  8407. * 'error code': 100 // other arbitrary info
  8408. * });
  8409. * }
  8410. * }
  8411. * });
  8412. *
  8413. * If a console is available (that supports the `console.dir` function) you'll see console output like:
  8414. *
  8415. * An error was raised with the following data:
  8416. * option: Object { foo: "bar"}
  8417. * foo: "bar"
  8418. * error code: 100
  8419. * msg: "You cannot do that!"
  8420. * sourceClass: "Ext.Foo"
  8421. * sourceMethod: "doSomething"
  8422. *
  8423. * uncaught exception: You cannot do that!
  8424. *
  8425. * As you can see, the error will report exactly where it was raised and will include as much information as the
  8426. * raising code can usefully provide.
  8427. *
  8428. * If you want to handle all application errors globally you can simply override the static {@link #handle} method
  8429. * and provide whatever handling logic you need. If the method returns true then the error is considered handled
  8430. * and will not be thrown to the browser. If anything but true is returned then the error will be thrown normally.
  8431. *
  8432. * Example usage:
  8433. *
  8434. * Ext.Error.handle = function(err) {
  8435. * if (err.someProperty == 'NotReallyAnError') {
  8436. * // maybe log something to the application here if applicable
  8437. * return true;
  8438. * }
  8439. * // any non-true return value (including none) will cause the error to be thrown
  8440. * }
  8441. *
  8442. */
  8443. Ext.Error = Ext.extend(Error, {
  8444. statics: {
  8445. /**
  8446. * @property {Boolean} ignore
  8447. * Static flag that can be used to globally disable error reporting to the browser if set to true
  8448. * (defaults to false). Note that if you ignore Ext errors it's likely that some other code may fail
  8449. * and throw a native JavaScript error thereafter, so use with caution. In most cases it will probably
  8450. * be preferable to supply a custom error {@link #handle handling} function instead.
  8451. *
  8452. * Example usage:
  8453. *
  8454. * Ext.Error.ignore = true;
  8455. *
  8456. * @static
  8457. */
  8458. ignore: false,
  8459. /**
  8460. * @property {Boolean} notify
  8461. * Static flag that can be used to globally control error notification to the user. Unlike
  8462. * Ex.Error.ignore, this does not effect exceptions. They are still thrown. This value can be
  8463. * set to false to disable the alert notification (default is true for IE6 and IE7).
  8464. *
  8465. * Only the first error will generate an alert. Internally this flag is set to false when the
  8466. * first error occurs prior to displaying the alert.
  8467. *
  8468. * This flag is not used in a release build.
  8469. *
  8470. * Example usage:
  8471. *
  8472. * Ext.Error.notify = false;
  8473. *
  8474. * @static
  8475. */
  8476. //notify: Ext.isIE6 || Ext.isIE7,
  8477. /**
  8478. * Raise an error that can include additional data and supports automatic console logging if available.
  8479. * You can pass a string error message or an object with the `msg` attribute which will be used as the
  8480. * error message. The object can contain any other name-value attributes (or objects) to be logged
  8481. * along with the error.
  8482. *
  8483. * Note that after displaying the error message a JavaScript error will ultimately be thrown so that
  8484. * execution will halt.
  8485. *
  8486. * Example usage:
  8487. *
  8488. * Ext.Error.raise('A simple string error message');
  8489. *
  8490. * // or...
  8491. *
  8492. * Ext.define('Ext.Foo', {
  8493. * doSomething: function(option){
  8494. * if (someCondition === false) {
  8495. * Ext.Error.raise({
  8496. * msg: 'You cannot do that!',
  8497. * option: option, // whatever was passed into the method
  8498. * 'error code': 100 // other arbitrary info
  8499. * });
  8500. * }
  8501. * }
  8502. * });
  8503. *
  8504. * @param {String/Object} err The error message string, or an object containing the attribute "msg" that will be
  8505. * used as the error message. Any other data included in the object will also be logged to the browser console,
  8506. * if available.
  8507. * @static
  8508. */
  8509. raise: function(err){
  8510. err = err || {};
  8511. if (Ext.isString(err)) {
  8512. err = { msg: err };
  8513. }
  8514. var method = this.raise.caller;
  8515. if (method) {
  8516. if (method.$name) {
  8517. err.sourceMethod = method.$name;
  8518. }
  8519. if (method.$owner) {
  8520. err.sourceClass = method.$owner.$className;
  8521. }
  8522. }
  8523. if (Ext.Error.handle(err) !== true) {
  8524. var msg = Ext.Error.prototype.toString.call(err);
  8525. Ext.log({
  8526. msg: msg,
  8527. level: 'error',
  8528. dump: err,
  8529. stack: true
  8530. });
  8531. throw new Ext.Error(err);
  8532. }
  8533. },
  8534. /**
  8535. * Globally handle any Ext errors that may be raised, optionally providing custom logic to
  8536. * handle different errors individually. Return true from the function to bypass throwing the
  8537. * error to the browser, otherwise the error will be thrown and execution will halt.
  8538. *
  8539. * Example usage:
  8540. *
  8541. * Ext.Error.handle = function(err) {
  8542. * if (err.someProperty == 'NotReallyAnError') {
  8543. * // maybe log something to the application here if applicable
  8544. * return true;
  8545. * }
  8546. * // any non-true return value (including none) will cause the error to be thrown
  8547. * }
  8548. *
  8549. * @param {Ext.Error} err The Ext.Error object being raised. It will contain any attributes that were originally
  8550. * raised with it, plus properties about the method and class from which the error originated (if raised from a
  8551. * class that uses the Ext 4 class system).
  8552. * @static
  8553. */
  8554. handle: function(){
  8555. return Ext.Error.ignore;
  8556. }
  8557. },
  8558. // This is the standard property that is the name of the constructor.
  8559. name: 'Ext.Error',
  8560. /**
  8561. * Creates new Error object.
  8562. * @param {String/Object} config The error message string, or an object containing the
  8563. * attribute "msg" that will be used as the error message. Any other data included in
  8564. * the object will be applied to the error instance and logged to the browser console, if available.
  8565. */
  8566. constructor: function(config){
  8567. if (Ext.isString(config)) {
  8568. config = { msg: config };
  8569. }
  8570. var me = this;
  8571. Ext.apply(me, config);
  8572. me.message = me.message || me.msg; // 'message' is standard ('msg' is non-standard)
  8573. // note: the above does not work in old WebKit (me.message is readonly) (Safari 4)
  8574. },
  8575. /**
  8576. * Provides a custom string representation of the error object. This is an override of the base JavaScript
  8577. * `Object.toString` method, which is useful so that when logged to the browser console, an error object will
  8578. * be displayed with a useful message instead of `[object Object]`, the default `toString` result.
  8579. *
  8580. * The default implementation will include the error message along with the raising class and method, if available,
  8581. * but this can be overridden with a custom implementation either at the prototype level (for all errors) or on
  8582. * a particular error instance, if you want to provide a custom description that will show up in the console.
  8583. * @return {String} The error message. If raised from within the Ext 4 class system, the error message will also
  8584. * include the raising class and method names, if available.
  8585. */
  8586. toString: function(){
  8587. var me = this,
  8588. className = me.className ? me.className : '',
  8589. methodName = me.methodName ? '.' + me.methodName + '(): ' : '',
  8590. msg = me.msg || '(No description provided)';
  8591. return className + methodName + msg;
  8592. }
  8593. });
  8594. /*
  8595. * Create a function that will throw an error if called (in debug mode) with a message that
  8596. * indicates the method has been removed.
  8597. * @param {String} suggestion Optional text to include in the message (a workaround perhaps).
  8598. * @return {Function} The generated function.
  8599. * @private
  8600. */
  8601. Ext.deprecated = function (suggestion) {
  8602. return Ext.emptyFn;
  8603. };
  8604. /*
  8605. * This mechanism is used to notify the user of the first error encountered on the page. This
  8606. * was previously internal to Ext.Error.raise and is a desirable feature since errors often
  8607. * slip silently under the radar. It cannot live in Ext.Error.raise since there are times
  8608. * where exceptions are handled in a try/catch.
  8609. */
  8610. /**
  8611. * @class Ext.JSON
  8612. * Modified version of Douglas Crockford's JSON.js that doesn't
  8613. * mess with the Object prototype
  8614. * http://www.json.org/js.html
  8615. * @singleton
  8616. */
  8617. Ext.JSON = new(function() {
  8618. var me = this,
  8619. encodingFunction,
  8620. decodingFunction,
  8621. useNative = null,
  8622. useHasOwn = !! {}.hasOwnProperty,
  8623. isNative = function() {
  8624. if (useNative === null) {
  8625. useNative = Ext.USE_NATIVE_JSON && window.JSON && JSON.toString() == '[object JSON]';
  8626. }
  8627. return useNative;
  8628. },
  8629. pad = function(n) {
  8630. return n < 10 ? "0" + n : n;
  8631. },
  8632. doDecode = function(json) {
  8633. return eval("(" + json + ')');
  8634. },
  8635. doEncode = function(o, newline) {
  8636. // http://jsperf.com/is-undefined
  8637. if (o === null || o === undefined) {
  8638. return "null";
  8639. } else if (Ext.isDate(o)) {
  8640. return Ext.JSON.encodeDate(o);
  8641. } else if (Ext.isString(o)) {
  8642. return encodeString(o);
  8643. }
  8644. // Allow custom zerialization by adding a toJSON method to any object type.
  8645. // Date/String have a toJSON in some environments, so check these first.
  8646. else if (o.toJSON) {
  8647. return o.toJSON();
  8648. } else if (Ext.isArray(o)) {
  8649. return encodeArray(o, newline);
  8650. } else if (typeof o == "number") {
  8651. //don't use isNumber here, since finite checks happen inside isNumber
  8652. return isFinite(o) ? String(o) : "null";
  8653. } else if (Ext.isBoolean(o)) {
  8654. return String(o);
  8655. } else if (Ext.isObject(o)) {
  8656. return encodeObject(o, newline);
  8657. } else if (typeof o === "function") {
  8658. return "null";
  8659. }
  8660. return 'undefined';
  8661. },
  8662. m = {
  8663. "\b": '\\b',
  8664. "\t": '\\t',
  8665. "\n": '\\n',
  8666. "\f": '\\f',
  8667. "\r": '\\r',
  8668. '"': '\\"',
  8669. "\\": '\\\\',
  8670. '\x0b': '\\u000b' //ie doesn't handle \v
  8671. },
  8672. charToReplace = /[\\\"\x00-\x1f\x7f-\uffff]/g,
  8673. encodeString = function(s) {
  8674. return '"' + s.replace(charToReplace, function(a) {
  8675. var c = m[a];
  8676. return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  8677. }) + '"';
  8678. },
  8679. encodeArray = function(o, newline) {
  8680. var a = ["[", ""], // Note empty string in case there are no serializable members.
  8681. len = o.length,
  8682. i;
  8683. for (i = 0; i < len; i += 1) {
  8684. a.push(doEncode(o[i]), ',');
  8685. }
  8686. // Overwrite trailing comma (or empty string)
  8687. a[a.length - 1] = ']';
  8688. return a.join("");
  8689. },
  8690. encodeObject = function(o, newline) {
  8691. var a = ["{", ""], // Note empty string in case there are no serializable members.
  8692. i;
  8693. for (i in o) {
  8694. if (!useHasOwn || o.hasOwnProperty(i)) {
  8695. a.push(doEncode(i), ":", doEncode(o[i]), ',');
  8696. }
  8697. }
  8698. // Overwrite trailing comma (or empty string)
  8699. a[a.length - 1] = '}';
  8700. return a.join("");
  8701. };
  8702. /**
  8703. * The function which {@link #encode} uses to encode all javascript values to their JSON representations
  8704. * when {@link Ext#USE_NATIVE_JSON} is `false`.
  8705. *
  8706. * This is made public so that it can be replaced with a custom implementation.
  8707. *
  8708. * @param {Object} o Any javascript value to be converted to its JSON representation
  8709. * @return {String} The JSON representation of the passed value.
  8710. * @method
  8711. */
  8712. me.encodeValue = doEncode;
  8713. /**
  8714. * Encodes a Date. This returns the actual string which is inserted into the JSON string as the literal expression.
  8715. * **The returned value includes enclosing double quotation marks.**
  8716. *
  8717. * The default return format is "yyyy-mm-ddThh:mm:ss".
  8718. *
  8719. * To override this:
  8720. * Ext.JSON.encodeDate = function(d) {
  8721. * return Ext.Date.format(d, '"Y-m-d"');
  8722. * };
  8723. *
  8724. * @param {Date} d The Date to encode
  8725. * @return {String} The string literal to use in a JSON string.
  8726. */
  8727. me.encodeDate = function(o) {
  8728. return '"' + o.getFullYear() + "-"
  8729. + pad(o.getMonth() + 1) + "-"
  8730. + pad(o.getDate()) + "T"
  8731. + pad(o.getHours()) + ":"
  8732. + pad(o.getMinutes()) + ":"
  8733. + pad(o.getSeconds()) + '"';
  8734. };
  8735. /**
  8736. * Encodes an Object, Array or other value.
  8737. *
  8738. * If the environment's native JSON encoding is not being used ({@link Ext#USE_NATIVE_JSON} is not set, or the environment does not support it), then
  8739. * ExtJS's encoding will be used. This allows the developer to add a `toJSON` method to their classes which need serializing to return a valid
  8740. * JSON representation of the object.
  8741. *
  8742. * @param {Object} o The variable to encode
  8743. * @return {String} The JSON string
  8744. */
  8745. me.encode = function(o) {
  8746. if (!encodingFunction) {
  8747. // setup encoding function on first access
  8748. encodingFunction = isNative() ? JSON.stringify : me.encodeValue;
  8749. }
  8750. return encodingFunction(o);
  8751. };
  8752. /**
  8753. * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError unless the safe option is set.
  8754. * @param {String} json The JSON string
  8755. * @param {Boolean} safe (optional) Whether to return null or throw an exception if the JSON is invalid.
  8756. * @return {Object} The resulting object
  8757. */
  8758. me.decode = function(json, safe) {
  8759. if (!decodingFunction) {
  8760. // setup decoding function on first access
  8761. decodingFunction = isNative() ? JSON.parse : doDecode;
  8762. }
  8763. try {
  8764. return decodingFunction(json);
  8765. } catch (e) {
  8766. if (safe === true) {
  8767. return null;
  8768. }
  8769. Ext.Error.raise({
  8770. sourceClass: "Ext.JSON",
  8771. sourceMethod: "decode",
  8772. msg: "You're trying to decode an invalid JSON String: " + json
  8773. });
  8774. }
  8775. };
  8776. })();
  8777. /**
  8778. * Shorthand for {@link Ext.JSON#encode}
  8779. * @member Ext
  8780. * @method encode
  8781. * @inheritdoc Ext.JSON#encode
  8782. */
  8783. Ext.encode = Ext.JSON.encode;
  8784. /**
  8785. * Shorthand for {@link Ext.JSON#decode}
  8786. * @member Ext
  8787. * @method decode
  8788. * @inheritdoc Ext.JSON#decode
  8789. */
  8790. Ext.decode = Ext.JSON.decode;
  8791. /**
  8792. * @class Ext
  8793. *
  8794. * The Ext namespace (global object) encapsulates all classes, singletons, and
  8795. * utility methods provided by Sencha's libraries.
  8796. *
  8797. * Most user interface Components are at a lower level of nesting in the namespace,
  8798. * but many common utility functions are provided as direct properties of the Ext namespace.
  8799. *
  8800. * Also many frequently used methods from other classes are provided as shortcuts
  8801. * within the Ext namespace. For example {@link Ext#getCmp Ext.getCmp} aliases
  8802. * {@link Ext.ComponentManager#get Ext.ComponentManager.get}.
  8803. *
  8804. * Many applications are initiated with {@link Ext#onReady Ext.onReady} which is
  8805. * called once the DOM is ready. This ensures all scripts have been loaded,
  8806. * preventing dependency issues. For example:
  8807. *
  8808. * Ext.onReady(function(){
  8809. * new Ext.Component({
  8810. * renderTo: document.body,
  8811. * html: 'DOM ready!'
  8812. * });
  8813. * });
  8814. *
  8815. * For more information about how to use the Ext classes, see:
  8816. *
  8817. * - <a href="http://www.sencha.com/learn/">The Learning Center</a>
  8818. * - <a href="http://www.sencha.com/learn/Ext_FAQ">The FAQ</a>
  8819. * - <a href="http://www.sencha.com/forum/">The forums</a>
  8820. *
  8821. * @singleton
  8822. */
  8823. Ext.apply(Ext, {
  8824. userAgent: navigator.userAgent.toLowerCase(),
  8825. cache: {},
  8826. idSeed: 1000,
  8827. windowId: 'ext-window',
  8828. documentId: 'ext-document',
  8829. /**
  8830. * True when the document is fully initialized and ready for action
  8831. */
  8832. isReady: false,
  8833. /**
  8834. * True to automatically uncache orphaned Ext.Elements periodically
  8835. */
  8836. enableGarbageCollector: true,
  8837. /**
  8838. * True to automatically purge event listeners during garbageCollection.
  8839. */
  8840. enableListenerCollection: true,
  8841. /**
  8842. * Generates unique ids. If the element already has an id, it is unchanged
  8843. * @param {HTMLElement/Ext.Element} [el] The element to generate an id for
  8844. * @param {String} prefix (optional) Id prefix (defaults "ext-gen")
  8845. * @return {String} The generated Id.
  8846. */
  8847. id: function(el, prefix) {
  8848. var me = this,
  8849. sandboxPrefix = '';
  8850. el = Ext.getDom(el, true) || {};
  8851. if (el === document) {
  8852. el.id = me.documentId;
  8853. }
  8854. else if (el === window) {
  8855. el.id = me.windowId;
  8856. }
  8857. if (!el.id) {
  8858. if (me.isSandboxed) {
  8859. sandboxPrefix = Ext.sandboxName.toLowerCase() + '-';
  8860. }
  8861. el.id = sandboxPrefix + (prefix || "ext-gen") + (++Ext.idSeed);
  8862. }
  8863. return el.id;
  8864. },
  8865. /**
  8866. * Returns the current document body as an {@link Ext.Element}.
  8867. * @return Ext.Element The document body
  8868. */
  8869. getBody: function() {
  8870. var body;
  8871. return function() {
  8872. return body || (body = Ext.get(document.body));
  8873. };
  8874. }(),
  8875. /**
  8876. * Returns the current document head as an {@link Ext.Element}.
  8877. * @return Ext.Element The document head
  8878. * @method
  8879. */
  8880. getHead: function() {
  8881. var head;
  8882. return function() {
  8883. return head || (head = Ext.get(document.getElementsByTagName("head")[0]));
  8884. };
  8885. }(),
  8886. /**
  8887. * Returns the current HTML document object as an {@link Ext.Element}.
  8888. * @return Ext.Element The document
  8889. */
  8890. getDoc: function() {
  8891. var doc;
  8892. return function() {
  8893. return doc || (doc = Ext.get(document));
  8894. };
  8895. }(),
  8896. /**
  8897. * This is shorthand reference to {@link Ext.ComponentManager#get}.
  8898. * Looks up an existing {@link Ext.Component Component} by {@link Ext.Component#id id}
  8899. *
  8900. * @param {String} id The component {@link Ext.Component#id id}
  8901. * @return Ext.Component The Component, `undefined` if not found, or `null` if a
  8902. * Class was found.
  8903. */
  8904. getCmp: function(id) {
  8905. return Ext.ComponentManager.get(id);
  8906. },
  8907. /**
  8908. * Returns the current orientation of the mobile device
  8909. * @return {String} Either 'portrait' or 'landscape'
  8910. */
  8911. getOrientation: function() {
  8912. return window.innerHeight > window.innerWidth ? 'portrait' : 'landscape';
  8913. },
  8914. /**
  8915. * Attempts to destroy any objects passed to it by removing all event listeners, removing them from the
  8916. * DOM (if applicable) and calling their destroy functions (if available). This method is primarily
  8917. * intended for arguments of type {@link Ext.Element} and {@link Ext.Component}, but any subclass of
  8918. * {@link Ext.util.Observable} can be passed in. Any number of elements and/or components can be
  8919. * passed into this function in a single call as separate arguments.
  8920. *
  8921. * @param {Ext.Element/Ext.Component/Ext.Element[]/Ext.Component[]...} args
  8922. * An {@link Ext.Element}, {@link Ext.Component}, or an Array of either of these to destroy
  8923. */
  8924. destroy: function() {
  8925. var ln = arguments.length,
  8926. i, arg;
  8927. for (i = 0; i < ln; i++) {
  8928. arg = arguments[i];
  8929. if (arg) {
  8930. if (Ext.isArray(arg)) {
  8931. this.destroy.apply(this, arg);
  8932. }
  8933. else if (Ext.isFunction(arg.destroy)) {
  8934. arg.destroy();
  8935. }
  8936. else if (arg.dom) {
  8937. arg.remove();
  8938. }
  8939. }
  8940. }
  8941. },
  8942. /**
  8943. * Execute a callback function in a particular scope. If no function is passed the call is ignored.
  8944. *
  8945. * For example, these lines are equivalent:
  8946. *
  8947. * Ext.callback(myFunc, this, [arg1, arg2]);
  8948. * Ext.isFunction(myFunc) && myFunc.apply(this, [arg1, arg2]);
  8949. *
  8950. * @param {Function} callback The callback to execute
  8951. * @param {Object} [scope] The scope to execute in
  8952. * @param {Array} [args] The arguments to pass to the function
  8953. * @param {Number} [delay] Pass a number to delay the call by a number of milliseconds.
  8954. */
  8955. callback: function(callback, scope, args, delay){
  8956. if(Ext.isFunction(callback)){
  8957. args = args || [];
  8958. scope = scope || window;
  8959. if (delay) {
  8960. Ext.defer(callback, delay, scope, args);
  8961. } else {
  8962. callback.apply(scope, args);
  8963. }
  8964. }
  8965. },
  8966. /**
  8967. * Alias for {@link Ext.String#htmlEncode}.
  8968. * @inheritdoc Ext.String#htmlEncode
  8969. */
  8970. htmlEncode : function(value) {
  8971. return Ext.String.htmlEncode(value);
  8972. },
  8973. /**
  8974. * Alias for {@link Ext.String#htmlDecode}.
  8975. * @inheritdoc Ext.String#htmlDecode
  8976. */
  8977. htmlDecode : function(value) {
  8978. return Ext.String.htmlDecode(value);
  8979. },
  8980. /**
  8981. * Alias for {@link Ext.String#urlAppend}.
  8982. * @inheritdoc Ext.String#urlAppend
  8983. */
  8984. urlAppend : function(url, s) {
  8985. return Ext.String.urlAppend(url, s);
  8986. }
  8987. });
  8988. Ext.ns = Ext.namespace;
  8989. // for old browsers
  8990. window.undefined = window.undefined;
  8991. /**
  8992. * @class Ext
  8993. */
  8994. (function(){
  8995. /*
  8996. FF 3.6 - Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.17) Gecko/20110420 Firefox/3.6.17
  8997. FF 4.0.1 - Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1
  8998. FF 5.0 - Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0
  8999. IE6 - Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1;)
  9000. IE7 - Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1;)
  9001. IE8 - Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)
  9002. IE9 - Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
  9003. Chrome 11 - Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.60 Safari/534.24
  9004. Safari 5 - Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1
  9005. Opera 11.11 - Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11
  9006. */
  9007. var check = function(regex){
  9008. return regex.test(Ext.userAgent);
  9009. },
  9010. isStrict = document.compatMode == "CSS1Compat",
  9011. version = function (is, regex) {
  9012. var m;
  9013. return (is && (m = regex.exec(Ext.userAgent))) ? parseFloat(m[1]) : 0;
  9014. },
  9015. docMode = document.documentMode,
  9016. isOpera = check(/opera/),
  9017. isOpera10_5 = isOpera && check(/version\/10\.5/),
  9018. isChrome = check(/\bchrome\b/),
  9019. isWebKit = check(/webkit/),
  9020. isSafari = !isChrome && check(/safari/),
  9021. isSafari2 = isSafari && check(/applewebkit\/4/), // unique to Safari 2
  9022. isSafari3 = isSafari && check(/version\/3/),
  9023. isSafari4 = isSafari && check(/version\/4/),
  9024. isSafari5 = isSafari && check(/version\/5/),
  9025. isIE = !isOpera && check(/msie/),
  9026. isIE7 = isIE && ((check(/msie 7/) && docMode != 8 && docMode != 9) || docMode == 7),
  9027. isIE8 = isIE && ((check(/msie 8/) && docMode != 7 && docMode != 9) || docMode == 8),
  9028. isIE9 = isIE && ((check(/msie 9/) && docMode != 7 && docMode != 8) || docMode == 9),
  9029. isIE6 = isIE && check(/msie 6/),
  9030. isGecko = !isWebKit && check(/gecko/),
  9031. isGecko3 = isGecko && check(/rv:1\.9/),
  9032. isGecko4 = isGecko && check(/rv:2\.0/),
  9033. isGecko5 = isGecko && check(/rv:5\./),
  9034. isGecko10 = isGecko && check(/rv:10\./),
  9035. isFF3_0 = isGecko3 && check(/rv:1\.9\.0/),
  9036. isFF3_5 = isGecko3 && check(/rv:1\.9\.1/),
  9037. isFF3_6 = isGecko3 && check(/rv:1\.9\.2/),
  9038. isWindows = check(/windows|win32/),
  9039. isMac = check(/macintosh|mac os x/),
  9040. isLinux = check(/linux/),
  9041. scrollbarSize = null,
  9042. chromeVersion = version(true, /\bchrome\/(\d+\.\d+)/),
  9043. firefoxVersion = version(true, /\bfirefox\/(\d+\.\d+)/),
  9044. ieVersion = version(isIE, /msie (\d+\.\d+)/),
  9045. operaVersion = version(isOpera, /version\/(\d+\.\d+)/),
  9046. safariVersion = version(isSafari, /version\/(\d+\.\d+)/),
  9047. webKitVersion = version(isWebKit, /webkit\/(\d+\.\d+)/),
  9048. isSecure = /^https/i.test(window.location.protocol);
  9049. // remove css image flicker
  9050. try {
  9051. document.execCommand("BackgroundImageCache", false, true);
  9052. } catch(e) {}
  9053. var nullLog = function () {};
  9054. nullLog.info = nullLog.warn = nullLog.error = Ext.emptyFn;
  9055. Ext.setVersion('extjs', '4.1.0');
  9056. Ext.apply(Ext, {
  9057. /**
  9058. * @property {String} SSL_SECURE_URL
  9059. * URL to a blank file used by Ext when in secure mode for iframe src and onReady src
  9060. * to prevent the IE insecure content warning (`'about:blank'`, except for IE
  9061. * in secure mode, which is `'javascript:""'`).
  9062. */
  9063. SSL_SECURE_URL : isSecure && isIE ? 'javascript:\'\'' : 'about:blank',
  9064. /**
  9065. * @property {Boolean} enableFx
  9066. * True if the {@link Ext.fx.Anim} Class is available.
  9067. */
  9068. /**
  9069. * @property {Boolean} scopeResetCSS
  9070. * True to scope the reset CSS to be just applied to Ext components. Note that this
  9071. * wraps root containers with an additional element. Also remember that when you turn
  9072. * on this option, you have to use ext-all-scoped (unless you use the bootstrap.js to
  9073. * load your javascript, in which case it will be handled for you).
  9074. */
  9075. scopeResetCSS : Ext.buildSettings.scopeResetCSS,
  9076. /**
  9077. * @property {String} resetCls
  9078. * The css class used to wrap Ext components when the {@link #scopeResetCSS} option
  9079. * is used.
  9080. */
  9081. resetCls: Ext.buildSettings.baseCSSPrefix + 'reset',
  9082. /**
  9083. * @property {Boolean} enableNestedListenerRemoval
  9084. * **Experimental.** True to cascade listener removal to child elements when an element
  9085. * is removed. Currently not optimized for performance.
  9086. */
  9087. enableNestedListenerRemoval : false,
  9088. /**
  9089. * @property {Boolean} USE_NATIVE_JSON
  9090. * Indicates whether to use native browser parsing for JSON methods.
  9091. * This option is ignored if the browser does not support native JSON methods.
  9092. *
  9093. * **Note:** Native JSON methods will not work with objects that have functions.
  9094. * Also, property names must be quoted, otherwise the data will not parse.
  9095. */
  9096. USE_NATIVE_JSON : false,
  9097. /**
  9098. * Returns the dom node for the passed String (id), dom node, or Ext.Element.
  9099. * Optional 'strict' flag is needed for IE since it can return 'name' and
  9100. * 'id' elements by using getElementById.
  9101. *
  9102. * Here are some examples:
  9103. *
  9104. * // gets dom node based on id
  9105. * var elDom = Ext.getDom('elId');
  9106. * // gets dom node based on the dom node
  9107. * var elDom1 = Ext.getDom(elDom);
  9108. *
  9109. * // If we don&#39;t know if we are working with an
  9110. * // Ext.Element or a dom node use Ext.getDom
  9111. * function(el){
  9112. * var dom = Ext.getDom(el);
  9113. * // do something with the dom node
  9114. * }
  9115. *
  9116. * **Note:** the dom node to be found actually needs to exist (be rendered, etc)
  9117. * when this method is called to be successful.
  9118. *
  9119. * @param {String/HTMLElement/Ext.Element} el
  9120. * @return HTMLElement
  9121. */
  9122. getDom : function(el, strict) {
  9123. if (!el || !document) {
  9124. return null;
  9125. }
  9126. if (el.dom) {
  9127. return el.dom;
  9128. } else {
  9129. if (typeof el == 'string') {
  9130. var e = Ext.getElementById(el);
  9131. // IE returns elements with the 'name' and 'id' attribute.
  9132. // we do a strict check to return the element with only the id attribute
  9133. if (e && isIE && strict) {
  9134. if (el == e.getAttribute('id')) {
  9135. return e;
  9136. } else {
  9137. return null;
  9138. }
  9139. }
  9140. return e;
  9141. } else {
  9142. return el;
  9143. }
  9144. }
  9145. },
  9146. /**
  9147. * Removes a DOM node from the document.
  9148. *
  9149. * Removes this element from the document, removes all DOM event listeners, and
  9150. * deletes the cache reference. All DOM event listeners are removed from this element.
  9151. * If {@link Ext#enableNestedListenerRemoval Ext.enableNestedListenerRemoval} is
  9152. * `true`, then DOM event listeners are also removed from all child nodes.
  9153. * The body node will be ignored if passed in.
  9154. *
  9155. * @param {HTMLElement} node The node to remove
  9156. * @method
  9157. */
  9158. removeNode : isIE6 || isIE7 ? function() {
  9159. var d;
  9160. return function(n){
  9161. if(n && n.tagName != 'BODY'){
  9162. (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n) : Ext.EventManager.removeAll(n);
  9163. d = d || document.createElement('div');
  9164. d.appendChild(n);
  9165. d.innerHTML = '';
  9166. delete Ext.cache[n.id];
  9167. }
  9168. };
  9169. }() : function(n) {
  9170. if (n && n.parentNode && n.tagName != 'BODY') {
  9171. (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n) : Ext.EventManager.removeAll(n);
  9172. n.parentNode.removeChild(n);
  9173. delete Ext.cache[n.id];
  9174. }
  9175. },
  9176. isStrict: isStrict,
  9177. isIEQuirks: isIE && !isStrict,
  9178. /**
  9179. * True if the detected browser is Opera.
  9180. * @type Boolean
  9181. */
  9182. isOpera : isOpera,
  9183. /**
  9184. * True if the detected browser is Opera 10.5x.
  9185. * @type Boolean
  9186. */
  9187. isOpera10_5 : isOpera10_5,
  9188. /**
  9189. * True if the detected browser uses WebKit.
  9190. * @type Boolean
  9191. */
  9192. isWebKit : isWebKit,
  9193. /**
  9194. * True if the detected browser is Chrome.
  9195. * @type Boolean
  9196. */
  9197. isChrome : isChrome,
  9198. /**
  9199. * True if the detected browser is Safari.
  9200. * @type Boolean
  9201. */
  9202. isSafari : isSafari,
  9203. /**
  9204. * True if the detected browser is Safari 3.x.
  9205. * @type Boolean
  9206. */
  9207. isSafari3 : isSafari3,
  9208. /**
  9209. * True if the detected browser is Safari 4.x.
  9210. * @type Boolean
  9211. */
  9212. isSafari4 : isSafari4,
  9213. /**
  9214. * True if the detected browser is Safari 5.x.
  9215. * @type Boolean
  9216. */
  9217. isSafari5 : isSafari5,
  9218. /**
  9219. * True if the detected browser is Safari 2.x.
  9220. * @type Boolean
  9221. */
  9222. isSafari2 : isSafari2,
  9223. /**
  9224. * True if the detected browser is Internet Explorer.
  9225. * @type Boolean
  9226. */
  9227. isIE : isIE,
  9228. /**
  9229. * True if the detected browser is Internet Explorer 6.x.
  9230. * @type Boolean
  9231. */
  9232. isIE6 : isIE6,
  9233. /**
  9234. * True if the detected browser is Internet Explorer 7.x.
  9235. * @type Boolean
  9236. */
  9237. isIE7 : isIE7,
  9238. /**
  9239. * True if the detected browser is Internet Explorer 8.x.
  9240. * @type Boolean
  9241. */
  9242. isIE8 : isIE8,
  9243. /**
  9244. * True if the detected browser is Internet Explorer 9.x.
  9245. * @type Boolean
  9246. */
  9247. isIE9 : isIE9,
  9248. /**
  9249. * True if the detected browser uses the Gecko layout engine (e.g. Mozilla, Firefox).
  9250. * @type Boolean
  9251. */
  9252. isGecko : isGecko,
  9253. /**
  9254. * True if the detected browser uses a Gecko 1.9+ layout engine (e.g. Firefox 3.x).
  9255. * @type Boolean
  9256. */
  9257. isGecko3 : isGecko3,
  9258. /**
  9259. * True if the detected browser uses a Gecko 2.0+ layout engine (e.g. Firefox 4.x).
  9260. * @type Boolean
  9261. */
  9262. isGecko4 : isGecko4,
  9263. /**
  9264. * True if the detected browser uses a Gecko 5.0+ layout engine (e.g. Firefox 5.x).
  9265. * @type Boolean
  9266. */
  9267. isGecko5 : isGecko5,
  9268. /**
  9269. * True if the detected browser uses a Gecko 5.0+ layout engine (e.g. Firefox 5.x).
  9270. * @type Boolean
  9271. */
  9272. isGecko10 : isGecko10,
  9273. /**
  9274. * True if the detected browser uses FireFox 3.0
  9275. * @type Boolean
  9276. */
  9277. isFF3_0 : isFF3_0,
  9278. /**
  9279. * True if the detected browser uses FireFox 3.5
  9280. * @type Boolean
  9281. */
  9282. isFF3_5 : isFF3_5,
  9283. /**
  9284. * True if the detected browser uses FireFox 3.6
  9285. * @type Boolean
  9286. */
  9287. isFF3_6 : isFF3_6,
  9288. /**
  9289. * True if the detected browser uses FireFox 4
  9290. * @type Boolean
  9291. */
  9292. isFF4 : 4 <= firefoxVersion && firefoxVersion < 5,
  9293. /**
  9294. * True if the detected browser uses FireFox 5
  9295. * @type Boolean
  9296. */
  9297. isFF5 : 5 <= firefoxVersion && firefoxVersion < 6,
  9298. /**
  9299. * True if the detected browser uses FireFox 10
  9300. * @type Boolean
  9301. */
  9302. isFF10 : 10 <= firefoxVersion && firefoxVersion < 11,
  9303. /**
  9304. * True if the detected platform is Linux.
  9305. * @type Boolean
  9306. */
  9307. isLinux : isLinux,
  9308. /**
  9309. * True if the detected platform is Windows.
  9310. * @type Boolean
  9311. */
  9312. isWindows : isWindows,
  9313. /**
  9314. * True if the detected platform is Mac OS.
  9315. * @type Boolean
  9316. */
  9317. isMac : isMac,
  9318. /**
  9319. * The current version of Chrome (0 if the browser is not Chrome).
  9320. * @type Number
  9321. */
  9322. chromeVersion: chromeVersion,
  9323. /**
  9324. * The current version of Firefox (0 if the browser is not Firefox).
  9325. * @type Number
  9326. */
  9327. firefoxVersion: firefoxVersion,
  9328. /**
  9329. * The current version of IE (0 if the browser is not IE). This does not account
  9330. * for the documentMode of the current page, which is factored into {@link #isIE7},
  9331. * {@link #isIE8} and {@link #isIE9}. Thus this is not always true:
  9332. *
  9333. * Ext.isIE8 == (Ext.ieVersion == 8)
  9334. *
  9335. * @type Number
  9336. */
  9337. ieVersion: ieVersion,
  9338. /**
  9339. * The current version of Opera (0 if the browser is not Opera).
  9340. * @type Number
  9341. */
  9342. operaVersion: operaVersion,
  9343. /**
  9344. * The current version of Safari (0 if the browser is not Safari).
  9345. * @type Number
  9346. */
  9347. safariVersion: safariVersion,
  9348. /**
  9349. * The current version of WebKit (0 if the browser does not use WebKit).
  9350. * @type Number
  9351. */
  9352. webKitVersion: webKitVersion,
  9353. /**
  9354. * True if the page is running over SSL
  9355. * @type Boolean
  9356. */
  9357. isSecure: isSecure,
  9358. /**
  9359. * URL to a 1x1 transparent gif image used by Ext to create inline icons with
  9360. * CSS background images. In older versions of IE, this defaults to
  9361. * "http://sencha.com/s.gif" and you should change this to a URL on your server.
  9362. * For other browsers it uses an inline data URL.
  9363. * @type String
  9364. */
  9365. BLANK_IMAGE_URL : (isIE6 || isIE7) ? '/' + '/www.sencha.com/s.gif' : 'data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==',
  9366. /**
  9367. * Utility method for returning a default value if the passed value is empty.
  9368. *
  9369. * The value is deemed to be empty if it is:
  9370. *
  9371. * - null
  9372. * - undefined
  9373. * - an empty array
  9374. * - a zero length string (Unless the `allowBlank` parameter is `true`)
  9375. *
  9376. * @param {Object} value The value to test
  9377. * @param {Object} defaultValue The value to return if the original value is empty
  9378. * @param {Boolean} [allowBlank=false] true to allow zero length strings to qualify as non-empty.
  9379. * @return {Object} value, if non-empty, else defaultValue
  9380. * @deprecated 4.0.0 Use {@link Ext#valueFrom} instead
  9381. */
  9382. value : function(v, defaultValue, allowBlank){
  9383. return Ext.isEmpty(v, allowBlank) ? defaultValue : v;
  9384. },
  9385. /**
  9386. * Escapes the passed string for use in a regular expression.
  9387. * @param {String} str
  9388. * @return {String}
  9389. * @deprecated 4.0.0 Use {@link Ext.String#escapeRegex} instead
  9390. */
  9391. escapeRe : function(s) {
  9392. return s.replace(/([-.*+?^${}()|[\]\/\\])/g, "\\$1");
  9393. },
  9394. /**
  9395. * Applies event listeners to elements by selectors when the document is ready.
  9396. * The event name is specified with an `@` suffix.
  9397. *
  9398. * Ext.addBehaviors({
  9399. * // add a listener for click on all anchors in element with id foo
  9400. * '#foo a@click' : function(e, t){
  9401. * // do something
  9402. * },
  9403. *
  9404. * // add the same listener to multiple selectors (separated by comma BEFORE the @)
  9405. * '#foo a, #bar span.some-class@mouseover' : function(){
  9406. * // do something
  9407. * }
  9408. * });
  9409. *
  9410. * @param {Object} obj The list of behaviors to apply
  9411. */
  9412. addBehaviors : function(o){
  9413. if(!Ext.isReady){
  9414. Ext.onReady(function(){
  9415. Ext.addBehaviors(o);
  9416. });
  9417. } else {
  9418. var cache = {}, // simple cache for applying multiple behaviors to same selector does query multiple times
  9419. parts,
  9420. b,
  9421. s;
  9422. for (b in o) {
  9423. if ((parts = b.split('@'))[1]) { // for Object prototype breakers
  9424. s = parts[0];
  9425. if(!cache[s]){
  9426. cache[s] = Ext.select(s);
  9427. }
  9428. cache[s].on(parts[1], o[b]);
  9429. }
  9430. }
  9431. cache = null;
  9432. }
  9433. },
  9434. /**
  9435. * Returns the size of the browser scrollbars. This can differ depending on
  9436. * operating system settings, such as the theme or font size.
  9437. * @param {Boolean} [force] true to force a recalculation of the value.
  9438. * @return {Object} An object containing scrollbar sizes.
  9439. * @return.width {Number} The width of the vertical scrollbar.
  9440. * @return.height {Number} The height of the horizontal scrollbar.
  9441. */
  9442. getScrollbarSize: function (force) {
  9443. if (!Ext.isReady) {
  9444. return {};
  9445. }
  9446. if (force || !scrollbarSize) {
  9447. var db = document.body,
  9448. div = document.createElement('div');
  9449. div.style.width = div.style.height = '100px';
  9450. div.style.overflow = 'scroll';
  9451. div.style.position = 'absolute';
  9452. db.appendChild(div); // now we can measure the div...
  9453. // at least in iE9 the div is not 100px - the scrollbar size is removed!
  9454. scrollbarSize = {
  9455. width: div.offsetWidth - div.clientWidth,
  9456. height: div.offsetHeight - div.clientHeight
  9457. };
  9458. db.removeChild(div);
  9459. }
  9460. return scrollbarSize;
  9461. },
  9462. /**
  9463. * Utility method for getting the width of the browser's vertical scrollbar. This
  9464. * can differ depending on operating system settings, such as the theme or font size.
  9465. *
  9466. * This method is deprected in favor of {@link #getScrollbarSize}.
  9467. *
  9468. * @param {Boolean} [force] true to force a recalculation of the value.
  9469. * @return {Number} The width of a vertical scrollbar.
  9470. * @deprecated
  9471. */
  9472. getScrollBarWidth: function(force){
  9473. var size = Ext.getScrollbarSize(force);
  9474. return size.width + 2; // legacy fudge factor
  9475. },
  9476. /**
  9477. * Copies a set of named properties fom the source object to the destination object.
  9478. *
  9479. * Example:
  9480. *
  9481. * ImageComponent = Ext.extend(Ext.Component, {
  9482. * initComponent: function() {
  9483. * this.autoEl = { tag: 'img' };
  9484. * MyComponent.superclass.initComponent.apply(this, arguments);
  9485. * this.initialBox = Ext.copyTo({}, this.initialConfig, 'x,y,width,height');
  9486. * }
  9487. * });
  9488. *
  9489. * Important note: To borrow class prototype methods, use {@link Ext.Base#borrow} instead.
  9490. *
  9491. * @param {Object} dest The destination object.
  9492. * @param {Object} source The source object.
  9493. * @param {String/String[]} names Either an Array of property names, or a comma-delimited list
  9494. * of property names to copy.
  9495. * @param {Boolean} [usePrototypeKeys] Defaults to false. Pass true to copy keys off of the
  9496. * prototype as well as the instance.
  9497. * @return {Object} The modified object.
  9498. */
  9499. copyTo : function(dest, source, names, usePrototypeKeys){
  9500. if(typeof names == 'string'){
  9501. names = names.split(/[,;\s]/);
  9502. }
  9503. var n,
  9504. nLen = names.length,
  9505. name;
  9506. for(n = 0; n < nLen; n++) {
  9507. name = names[n];
  9508. if(usePrototypeKeys || source.hasOwnProperty(name)){
  9509. dest[name] = source[name];
  9510. }
  9511. }
  9512. return dest;
  9513. },
  9514. /**
  9515. * Attempts to destroy and then remove a set of named properties of the passed object.
  9516. * @param {Object} o The object (most likely a Component) who's properties you wish to destroy.
  9517. * @param {String...} args One or more names of the properties to destroy and remove from the object.
  9518. */
  9519. destroyMembers : function(o){
  9520. for (var i = 1, a = arguments, len = a.length; i < len; i++) {
  9521. Ext.destroy(o[a[i]]);
  9522. delete o[a[i]];
  9523. }
  9524. },
  9525. /**
  9526. * Logs a message. If a console is present it will be used. On Opera, the method
  9527. * "opera.postError" is called. In other cases, the message is logged to an array
  9528. * "Ext.log.out". An attached debugger can watch this array and view the log. The
  9529. * log buffer is limited to a maximum of "Ext.log.max" entries (defaults to 250).
  9530. * The `Ext.log.out` array can also be written to a popup window by entering the
  9531. * following in the URL bar (a "bookmarklet"):
  9532. *
  9533. * javascript:void(Ext.log.show());
  9534. *
  9535. * If additional parameters are passed, they are joined and appended to the message.
  9536. * A technique for tracing entry and exit of a function is this:
  9537. *
  9538. * function foo () {
  9539. * Ext.log({ indent: 1 }, '>> foo');
  9540. *
  9541. * // log statements in here or methods called from here will be indented
  9542. * // by one step
  9543. *
  9544. * Ext.log({ outdent: 1 }, '<< foo');
  9545. * }
  9546. *
  9547. * This method does nothing in a release build.
  9548. *
  9549. * @param {String/Object} message The message to log or an options object with any
  9550. * of the following properties:
  9551. *
  9552. * - `msg`: The message to log (required).
  9553. * - `level`: One of: "error", "warn", "info" or "log" (the default is "log").
  9554. * - `dump`: An object to dump to the log as part of the message.
  9555. * - `stack`: True to include a stack trace in the log.
  9556. * - `indent`: Cause subsequent log statements to be indented one step.
  9557. * - `outdent`: Cause this and following statements to be one step less indented.
  9558. *
  9559. * @method
  9560. */
  9561. log :
  9562. nullLog,
  9563. /**
  9564. * Partitions the set into two sets: a true set and a false set.
  9565. *
  9566. * Example 1:
  9567. *
  9568. * Ext.partition([true, false, true, true, false]);
  9569. * // returns [[true, true, true], [false, false]]
  9570. *
  9571. * Example 2:
  9572. *
  9573. * Ext.partition(
  9574. * Ext.query("p"),
  9575. * function(val){
  9576. * return val.className == "class1"
  9577. * }
  9578. * );
  9579. * // true are those paragraph elements with a className of "class1",
  9580. * // false set are those that do not have that className.
  9581. *
  9582. * @param {Array/NodeList} arr The array to partition
  9583. * @param {Function} truth (optional) a function to determine truth.
  9584. * If this is omitted the element itself must be able to be evaluated for its truthfulness.
  9585. * @return {Array} [array of truish values, array of falsy values]
  9586. * @deprecated 4.0.0 Will be removed in the next major version
  9587. */
  9588. partition : function(arr, truth){
  9589. var ret = [[],[]],
  9590. a, v,
  9591. aLen = arr.length;
  9592. for (a = 0; a < aLen; a++) {
  9593. v = arr[a];
  9594. ret[ (truth && truth(v, a, arr)) || (!truth && v) ? 0 : 1].push(v);
  9595. }
  9596. return ret;
  9597. },
  9598. /**
  9599. * Invokes a method on each item in an Array.
  9600. *
  9601. * Example:
  9602. *
  9603. * Ext.invoke(Ext.query("p"), "getAttribute", "id");
  9604. * // [el1.getAttribute("id"), el2.getAttribute("id"), ..., elN.getAttribute("id")]
  9605. *
  9606. * @param {Array/NodeList} arr The Array of items to invoke the method on.
  9607. * @param {String} methodName The method name to invoke.
  9608. * @param {Object...} args Arguments to send into the method invocation.
  9609. * @return {Array} The results of invoking the method on each item in the array.
  9610. * @deprecated 4.0.0 Will be removed in the next major version
  9611. */
  9612. invoke : function(arr, methodName){
  9613. var ret = [],
  9614. args = Array.prototype.slice.call(arguments, 2),
  9615. a, v,
  9616. aLen = arr.length;
  9617. for (a = 0; a < aLen; a++) {
  9618. v = arr[a];
  9619. if (v && typeof v[methodName] == 'function') {
  9620. ret.push(v[methodName].apply(v, args));
  9621. } else {
  9622. ret.push(undefined);
  9623. }
  9624. }
  9625. return ret;
  9626. },
  9627. /**
  9628. * Zips N sets together.
  9629. *
  9630. * Example 1:
  9631. *
  9632. * Ext.zip([1,2,3],[4,5,6]); // [[1,4],[2,5],[3,6]]
  9633. *
  9634. * Example 2:
  9635. *
  9636. * Ext.zip(
  9637. * [ "+", "-", "+"],
  9638. * [ 12, 10, 22],
  9639. * [ 43, 15, 96],
  9640. * function(a, b, c){
  9641. * return "$" + a + "" + b + "." + c
  9642. * }
  9643. * ); // ["$+12.43", "$-10.15", "$+22.96"]
  9644. *
  9645. * @param {Array/NodeList...} arr This argument may be repeated. Array(s)
  9646. * to contribute values.
  9647. * @param {Function} zipper (optional) The last item in the argument list.
  9648. * This will drive how the items are zipped together.
  9649. * @return {Array} The zipped set.
  9650. * @deprecated 4.0.0 Will be removed in the next major version
  9651. */
  9652. zip : function(){
  9653. var parts = Ext.partition(arguments, function( val ){ return typeof val != 'function'; }),
  9654. arrs = parts[0],
  9655. fn = parts[1][0],
  9656. len = Ext.max(Ext.pluck(arrs, "length")),
  9657. ret = [];
  9658. for (var i = 0; i < len; i++) {
  9659. ret[i] = [];
  9660. if(fn){
  9661. ret[i] = fn.apply(fn, Ext.pluck(arrs, i));
  9662. }else{
  9663. for (var j = 0, aLen = arrs.length; j < aLen; j++){
  9664. ret[i].push( arrs[j][i] );
  9665. }
  9666. }
  9667. }
  9668. return ret;
  9669. },
  9670. /**
  9671. * Turns an array into a sentence, joined by a specified connector - e.g.:
  9672. *
  9673. * Ext.toSentence(['Adama', 'Tigh', 'Roslin']); //'Adama, Tigh and Roslin'
  9674. * Ext.toSentence(['Adama', 'Tigh', 'Roslin'], 'or'); //'Adama, Tigh or Roslin'
  9675. *
  9676. * @param {String[]} items The array to create a sentence from
  9677. * @param {String} connector The string to use to connect the last two words.
  9678. * Usually 'and' or 'or' - defaults to 'and'.
  9679. * @return {String} The sentence string
  9680. * @deprecated 4.0.0 Will be removed in the next major version
  9681. */
  9682. toSentence: function(items, connector) {
  9683. var length = items.length;
  9684. if (length <= 1) {
  9685. return items[0];
  9686. } else {
  9687. var head = items.slice(0, length - 1),
  9688. tail = items[length - 1];
  9689. return Ext.util.Format.format("{0} {1} {2}", head.join(", "), connector || 'and', tail);
  9690. }
  9691. },
  9692. /**
  9693. * @property {Boolean} useShims
  9694. * By default, Ext intelligently decides whether floating elements should be shimmed.
  9695. * If you are using flash, you may want to set this to true.
  9696. */
  9697. useShims: isIE6
  9698. });
  9699. })();
  9700. /**
  9701. * Loads Ext.app.Application class and starts it up with given configuration after the page is ready.
  9702. *
  9703. * See Ext.app.Application for details.
  9704. *
  9705. * @param {Object} config
  9706. */
  9707. Ext.application = function(config) {
  9708. Ext.require('Ext.app.Application');
  9709. Ext.onReady(function() {
  9710. new Ext.app.Application(config);
  9711. });
  9712. };
  9713. //<localeInfo useApply="true" />
  9714. /**
  9715. * @class Ext.util.Format
  9716. This class is a centralized place for formatting functions. It includes
  9717. functions to format various different types of data, such as text, dates and numeric values.
  9718. __Localization__
  9719. This class contains several options for localization. These can be set once the library has loaded,
  9720. all calls to the functions from that point will use the locale settings that were specified.
  9721. Options include:
  9722. - thousandSeparator
  9723. - decimalSeparator
  9724. - currenyPrecision
  9725. - currencySign
  9726. - currencyAtEnd
  9727. This class also uses the default date format defined here: {@link Ext.Date#defaultFormat}.
  9728. __Using with renderers__
  9729. There are two helper functions that return a new function that can be used in conjunction with
  9730. grid renderers:
  9731. columns: [{
  9732. dataIndex: 'date',
  9733. renderer: Ext.util.Format.dateRenderer('Y-m-d')
  9734. }, {
  9735. dataIndex: 'time',
  9736. renderer: Ext.util.Format.numberRenderer('0.000')
  9737. }]
  9738. Functions that only take a single argument can also be passed directly:
  9739. columns: [{
  9740. dataIndex: 'cost',
  9741. renderer: Ext.util.Format.usMoney
  9742. }, {
  9743. dataIndex: 'productCode',
  9744. renderer: Ext.util.Format.uppercase
  9745. }]
  9746. __Using with XTemplates__
  9747. XTemplates can also directly use Ext.util.Format functions:
  9748. new Ext.XTemplate([
  9749. 'Date: {startDate:date("Y-m-d")}',
  9750. 'Cost: {cost:usMoney}'
  9751. ]);
  9752. * @markdown
  9753. * @singleton
  9754. */
  9755. (function() {
  9756. Ext.ns('Ext.util');
  9757. Ext.util.Format = {};
  9758. var UtilFormat = Ext.util.Format,
  9759. stripTagsRE = /<\/?[^>]+>/gi,
  9760. stripScriptsRe = /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,
  9761. nl2brRe = /\r?\n/g,
  9762. // A RegExp to remove from a number format string, all characters except digits and '.'
  9763. formatCleanRe = /[^\d\.]/g,
  9764. // A RegExp to remove from a number format string, all characters except digits and the local decimal separator.
  9765. // Created on first use. The local decimal separator character must be initialized for this to be created.
  9766. I18NFormatCleanRe;
  9767. Ext.apply(UtilFormat, {
  9768. /**
  9769. * @property {String} thousandSeparator
  9770. * <p>The character that the {@link #number} function uses as a thousand separator.</p>
  9771. * <p>This may be overridden in a locale file.</p>
  9772. */
  9773. //<locale>
  9774. thousandSeparator: ',',
  9775. //</locale>
  9776. /**
  9777. * @property {String} decimalSeparator
  9778. * <p>The character that the {@link #number} function uses as a decimal point.</p>
  9779. * <p>This may be overridden in a locale file.</p>
  9780. */
  9781. //<locale>
  9782. decimalSeparator: '.',
  9783. //</locale>
  9784. /**
  9785. * @property {Number} currencyPrecision
  9786. * <p>The number of decimal places that the {@link #currency} function displays.</p>
  9787. * <p>This may be overridden in a locale file.</p>
  9788. */
  9789. //<locale>
  9790. currencyPrecision: 2,
  9791. //</locale>
  9792. /**
  9793. * @property {String} currencySign
  9794. * <p>The currency sign that the {@link #currency} function displays.</p>
  9795. * <p>This may be overridden in a locale file.</p>
  9796. */
  9797. //<locale>
  9798. currencySign: '$',
  9799. //</locale>
  9800. /**
  9801. * @property {Boolean} currencyAtEnd
  9802. * <p>This may be set to <code>true</code> to make the {@link #currency} function
  9803. * append the currency sign to the formatted value.</p>
  9804. * <p>This may be overridden in a locale file.</p>
  9805. */
  9806. //<locale>
  9807. currencyAtEnd: false,
  9808. //</locale>
  9809. /**
  9810. * Checks a reference and converts it to empty string if it is undefined
  9811. * @param {Object} value Reference to check
  9812. * @return {Object} Empty string if converted, otherwise the original value
  9813. */
  9814. undef : function(value) {
  9815. return value !== undefined ? value : "";
  9816. },
  9817. /**
  9818. * Checks a reference and converts it to the default value if it's empty
  9819. * @param {Object} value Reference to check
  9820. * @param {String} defaultValue The value to insert of it's undefined (defaults to "")
  9821. * @return {String}
  9822. */
  9823. defaultValue : function(value, defaultValue) {
  9824. return value !== undefined && value !== '' ? value : defaultValue;
  9825. },
  9826. /**
  9827. * Returns a substring from within an original string
  9828. * @param {String} value The original text
  9829. * @param {Number} start The start index of the substring
  9830. * @param {Number} length The length of the substring
  9831. * @return {String} The substring
  9832. */
  9833. substr : function(value, start, length) {
  9834. return String(value).substr(start, length);
  9835. },
  9836. /**
  9837. * Converts a string to all lower case letters
  9838. * @param {String} value The text to convert
  9839. * @return {String} The converted text
  9840. */
  9841. lowercase : function(value) {
  9842. return String(value).toLowerCase();
  9843. },
  9844. /**
  9845. * Converts a string to all upper case letters
  9846. * @param {String} value The text to convert
  9847. * @return {String} The converted text
  9848. */
  9849. uppercase : function(value) {
  9850. return String(value).toUpperCase();
  9851. },
  9852. /**
  9853. * Format a number as US currency
  9854. * @param {Number/String} value The numeric value to format
  9855. * @return {String} The formatted currency string
  9856. */
  9857. usMoney : function(v) {
  9858. return UtilFormat.currency(v, '$', 2);
  9859. },
  9860. /**
  9861. * Format a number as a currency
  9862. * @param {Number/String} value The numeric value to format
  9863. * @param {String} sign The currency sign to use (defaults to {@link #currencySign})
  9864. * @param {Number} decimals The number of decimals to use for the currency (defaults to {@link #currencyPrecision})
  9865. * @param {Boolean} end True if the currency sign should be at the end of the string (defaults to {@link #currencyAtEnd})
  9866. * @return {String} The formatted currency string
  9867. */
  9868. currency: function(v, currencySign, decimals, end) {
  9869. var negativeSign = '',
  9870. format = ",0",
  9871. i = 0;
  9872. v = v - 0;
  9873. if (v < 0) {
  9874. v = -v;
  9875. negativeSign = '-';
  9876. }
  9877. decimals = Ext.isDefined(decimals) ? decimals : UtilFormat.currencyPrecision;
  9878. format += format + (decimals > 0 ? '.' : '');
  9879. for (; i < decimals; i++) {
  9880. format += '0';
  9881. }
  9882. v = UtilFormat.number(v, format);
  9883. if ((end || UtilFormat.currencyAtEnd) === true) {
  9884. return Ext.String.format("{0}{1}{2}", negativeSign, v, currencySign || UtilFormat.currencySign);
  9885. } else {
  9886. return Ext.String.format("{0}{1}{2}", negativeSign, currencySign || UtilFormat.currencySign, v);
  9887. }
  9888. },
  9889. /**
  9890. * Formats the passed date using the specified format pattern.
  9891. * @param {String/Date} value The value to format. If a string is passed, it is converted to a Date by the Javascript
  9892. * Date object's <a href="http://www.w3schools.com/jsref/jsref_parse.asp">parse()</a> method.
  9893. * @param {String} format (Optional) Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
  9894. * @return {String} The formatted date string.
  9895. */
  9896. date: function(v, format) {
  9897. if (!v) {
  9898. return "";
  9899. }
  9900. if (!Ext.isDate(v)) {
  9901. v = new Date(Date.parse(v));
  9902. }
  9903. return Ext.Date.dateFormat(v, format || Ext.Date.defaultFormat);
  9904. },
  9905. /**
  9906. * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
  9907. * @param {String} format Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
  9908. * @return {Function} The date formatting function
  9909. */
  9910. dateRenderer : function(format) {
  9911. return function(v) {
  9912. return UtilFormat.date(v, format);
  9913. };
  9914. },
  9915. /**
  9916. * Strips all HTML tags
  9917. * @param {Object} value The text from which to strip tags
  9918. * @return {String} The stripped text
  9919. */
  9920. stripTags : function(v) {
  9921. return !v ? v : String(v).replace(stripTagsRE, "");
  9922. },
  9923. /**
  9924. * Strips all script tags
  9925. * @param {Object} value The text from which to strip script tags
  9926. * @return {String} The stripped text
  9927. */
  9928. stripScripts : function(v) {
  9929. return !v ? v : String(v).replace(stripScriptsRe, "");
  9930. },
  9931. /**
  9932. * Simple format for a file size (xxx bytes, xxx KB, xxx MB)
  9933. * @param {Number/String} size The numeric value to format
  9934. * @return {String} The formatted file size
  9935. */
  9936. fileSize : function(size) {
  9937. if (size < 1024) {
  9938. return size + " bytes";
  9939. } else if (size < 1048576) {
  9940. return (Math.round(((size*10) / 1024))/10) + " KB";
  9941. } else {
  9942. return (Math.round(((size*10) / 1048576))/10) + " MB";
  9943. }
  9944. },
  9945. /**
  9946. * It does simple math for use in a template, for example:<pre><code>
  9947. * var tpl = new Ext.Template('{value} * 10 = {value:math("* 10")}');
  9948. * </code></pre>
  9949. * @return {Function} A function that operates on the passed value.
  9950. * @method
  9951. */
  9952. math : function(){
  9953. var fns = {};
  9954. return function(v, a){
  9955. if (!fns[a]) {
  9956. fns[a] = Ext.functionFactory('v', 'return v ' + a + ';');
  9957. }
  9958. return fns[a](v);
  9959. };
  9960. }(),
  9961. /**
  9962. * Rounds the passed number to the required decimal precision.
  9963. * @param {Number/String} value The numeric value to round.
  9964. * @param {Number} precision The number of decimal places to which to round the first parameter's value.
  9965. * @return {Number} The rounded value.
  9966. */
  9967. round : function(value, precision) {
  9968. var result = Number(value);
  9969. if (typeof precision == 'number') {
  9970. precision = Math.pow(10, precision);
  9971. result = Math.round(value * precision) / precision;
  9972. }
  9973. return result;
  9974. },
  9975. /**
  9976. * <p>Formats the passed number according to the passed format string.</p>
  9977. * <p>The number of digits after the decimal separator character specifies the number of
  9978. * decimal places in the resulting string. The <u>local-specific</u> decimal character is used in the result.</p>
  9979. * <p>The <i>presence</i> of a thousand separator character in the format string specifies that
  9980. * the <u>locale-specific</u> thousand separator (if any) is inserted separating thousand groups.</p>
  9981. * <p>By default, "," is expected as the thousand separator, and "." is expected as the decimal separator.</p>
  9982. * <p><b>New to Ext JS 4</b></p>
  9983. * <p>Locale-specific characters are always used in the formatted output when inserting
  9984. * thousand and decimal separators.</p>
  9985. * <p>The format string must specify separator characters according to US/UK conventions ("," as the
  9986. * thousand separator, and "." as the decimal separator)</p>
  9987. * <p>To allow specification of format strings according to local conventions for separator characters, add
  9988. * the string <code>/i</code> to the end of the format string.</p>
  9989. * <div style="margin-left:40px">examples (123456.789):
  9990. * <div style="margin-left:10px">
  9991. * 0 - (123456) show only digits, no precision<br>
  9992. * 0.00 - (123456.78) show only digits, 2 precision<br>
  9993. * 0.0000 - (123456.7890) show only digits, 4 precision<br>
  9994. * 0,000 - (123,456) show comma and digits, no precision<br>
  9995. * 0,000.00 - (123,456.78) show comma and digits, 2 precision<br>
  9996. * 0,0.00 - (123,456.78) shortcut method, show comma and digits, 2 precision<br>
  9997. * To allow specification of the formatting string using UK/US grouping characters (,) and decimal (.) for international numbers, add /i to the end.
  9998. * For example: 0.000,00/i
  9999. * </div></div>
  10000. * @param {Number} v The number to format.
  10001. * @param {String} format The way you would like to format this text.
  10002. * @return {String} The formatted number.
  10003. */
  10004. number : function(v, formatString) {
  10005. if (!formatString) {
  10006. return v;
  10007. }
  10008. v = Ext.Number.from(v, NaN);
  10009. if (isNaN(v)) {
  10010. return '';
  10011. }
  10012. var comma = UtilFormat.thousandSeparator,
  10013. dec = UtilFormat.decimalSeparator,
  10014. i18n = false,
  10015. neg = v < 0,
  10016. hasComma,
  10017. psplit;
  10018. v = Math.abs(v);
  10019. // The "/i" suffix allows caller to use a locale-specific formatting string.
  10020. // Clean the format string by removing all but numerals and the decimal separator.
  10021. // Then split the format string into pre and post decimal segments according to *what* the
  10022. // decimal separator is. If they are specifying "/i", they are using the local convention in the format string.
  10023. if (formatString.substr(formatString.length - 2) == '/i') {
  10024. if (!I18NFormatCleanRe) {
  10025. I18NFormatCleanRe = new RegExp('[^\\d\\' + UtilFormat.decimalSeparator + ']','g');
  10026. }
  10027. formatString = formatString.substr(0, formatString.length - 2);
  10028. i18n = true;
  10029. hasComma = formatString.indexOf(comma) != -1;
  10030. psplit = formatString.replace(I18NFormatCleanRe, '').split(dec);
  10031. } else {
  10032. hasComma = formatString.indexOf(',') != -1;
  10033. psplit = formatString.replace(formatCleanRe, '').split('.');
  10034. }
  10035. if (psplit.length > 2) {
  10036. } else if (psplit.length > 1) {
  10037. v = Ext.Number.toFixed(v, psplit[1].length);
  10038. } else {
  10039. v = Ext.Number.toFixed(v, 0);
  10040. }
  10041. var fnum = v.toString();
  10042. psplit = fnum.split('.');
  10043. if (hasComma) {
  10044. var cnum = psplit[0],
  10045. parr = [],
  10046. j = cnum.length,
  10047. m = Math.floor(j / 3),
  10048. n = cnum.length % 3 || 3,
  10049. i;
  10050. for (i = 0; i < j; i += n) {
  10051. if (i !== 0) {
  10052. n = 3;
  10053. }
  10054. parr[parr.length] = cnum.substr(i, n);
  10055. m -= 1;
  10056. }
  10057. fnum = parr.join(comma);
  10058. if (psplit[1]) {
  10059. fnum += dec + psplit[1];
  10060. }
  10061. } else {
  10062. if (psplit[1]) {
  10063. fnum = psplit[0] + dec + psplit[1];
  10064. }
  10065. }
  10066. if (neg) {
  10067. /*
  10068. * Edge case. If we have a very small negative number it will get rounded to 0,
  10069. * however the initial check at the top will still report as negative. Replace
  10070. * everything but 1-9 and check if the string is empty to determine a 0 value.
  10071. */
  10072. neg = fnum.replace(/[^1-9]/g, '') !== '';
  10073. }
  10074. return (neg ? '-' : '') + formatString.replace(/[\d,?\.?]+/, fnum);
  10075. },
  10076. /**
  10077. * Returns a number rendering function that can be reused to apply a number format multiple times efficiently
  10078. * @param {String} format Any valid number format string for {@link #number}
  10079. * @return {Function} The number formatting function
  10080. */
  10081. numberRenderer : function(format) {
  10082. return function(v) {
  10083. return UtilFormat.number(v, format);
  10084. };
  10085. },
  10086. /**
  10087. * Selectively do a plural form of a word based on a numeric value. For example, in a template,
  10088. * {commentCount:plural("Comment")} would result in "1 Comment" if commentCount was 1 or would be "x Comments"
  10089. * if the value is 0 or greater than 1.
  10090. * @param {Number} value The value to compare against
  10091. * @param {String} singular The singular form of the word
  10092. * @param {String} plural (optional) The plural form of the word (defaults to the singular with an "s")
  10093. */
  10094. plural : function(v, s, p) {
  10095. return v +' ' + (v == 1 ? s : (p ? p : s+'s'));
  10096. },
  10097. /**
  10098. * Converts newline characters to the HTML tag &lt;br/>
  10099. * @param {String} The string value to format.
  10100. * @return {String} The string with embedded &lt;br/> tags in place of newlines.
  10101. */
  10102. nl2br : function(v) {
  10103. return Ext.isEmpty(v) ? '' : v.replace(nl2brRe, '<br/>');
  10104. },
  10105. /**
  10106. * Alias for {@link Ext.String#capitalize}.
  10107. * @method
  10108. * @inheritdoc Ext.String#capitalize
  10109. */
  10110. capitalize: Ext.String.capitalize,
  10111. /**
  10112. * Alias for {@link Ext.String#ellipsis}.
  10113. * @method
  10114. * @inheritdoc Ext.String#ellipsis
  10115. */
  10116. ellipsis: Ext.String.ellipsis,
  10117. /**
  10118. * Alias for {@link Ext.String#format}.
  10119. * @method
  10120. * @inheritdoc Ext.String#format
  10121. */
  10122. format: Ext.String.format,
  10123. /**
  10124. * Alias for {@link Ext.String#htmlDecode}.
  10125. * @method
  10126. * @inheritdoc Ext.String#htmlDecode
  10127. */
  10128. htmlDecode: Ext.String.htmlDecode,
  10129. /**
  10130. * Alias for {@link Ext.String#htmlEncode}.
  10131. * @method
  10132. * @inheritdoc Ext.String#htmlEncode
  10133. */
  10134. htmlEncode: Ext.String.htmlEncode,
  10135. /**
  10136. * Alias for {@link Ext.String#leftPad}.
  10137. * @method
  10138. * @inheritdoc Ext.String#leftPad
  10139. */
  10140. leftPad: Ext.String.leftPad,
  10141. /**
  10142. * Alias for {@link Ext.String#trim}.
  10143. * @method
  10144. * @inheritdoc Ext.String#trim
  10145. */
  10146. trim : Ext.String.trim,
  10147. /**
  10148. * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations
  10149. * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result)
  10150. * @param {Number/String} v The encoded margins
  10151. * @return {Object} An object with margin sizes for top, right, bottom and left
  10152. */
  10153. parseBox : function(box) {
  10154. box = Ext.isEmpty(box) ? '' : box;
  10155. if (Ext.isNumber(box)) {
  10156. box = box.toString();
  10157. }
  10158. var parts = box.split(' '),
  10159. ln = parts.length;
  10160. if (ln == 1) {
  10161. parts[1] = parts[2] = parts[3] = parts[0];
  10162. }
  10163. else if (ln == 2) {
  10164. parts[2] = parts[0];
  10165. parts[3] = parts[1];
  10166. }
  10167. else if (ln == 3) {
  10168. parts[3] = parts[1];
  10169. }
  10170. return {
  10171. top :parseInt(parts[0], 10) || 0,
  10172. right :parseInt(parts[1], 10) || 0,
  10173. bottom:parseInt(parts[2], 10) || 0,
  10174. left :parseInt(parts[3], 10) || 0
  10175. };
  10176. },
  10177. /**
  10178. * Escapes the passed string for use in a regular expression
  10179. * @param {String} str
  10180. * @return {String}
  10181. */
  10182. escapeRegex : function(s) {
  10183. return s.replace(/([\-.*+?\^${}()|\[\]\/\\])/g, "\\$1");
  10184. }
  10185. });
  10186. })();
  10187. /**
  10188. * Provides the ability to execute one or more arbitrary tasks in a asynchronous manner.
  10189. * Generally, you can use the singleton {@link Ext.TaskManager} instead, but if needed,
  10190. * you can create separate instances of TaskRunner. Any number of separate tasks can be
  10191. * started at any time and will run independently of each other.
  10192. *
  10193. * Example usage:
  10194. *
  10195. * // Start a simple clock task that updates a div once per second
  10196. * var updateClock = function () {
  10197. * Ext.fly('clock').update(new Date().format('g:i:s A'));
  10198. * }
  10199. *
  10200. * var runner = new Ext.util.TaskRunner();
  10201. * var task = runner.start({
  10202. * run: updateClock,
  10203. * interval: 1000
  10204. * }
  10205. *
  10206. * The equivalent using TaskManager:
  10207. *
  10208. * var task = Ext.TaskManager.start({
  10209. * run: updateClock,
  10210. * interval: 1000
  10211. * });
  10212. *
  10213. * To end a running task:
  10214. *
  10215. * task.destroy();
  10216. *
  10217. * If a task needs to be started and stopped repeated over time, you can create a
  10218. * {@link Ext.util.TaskRunner.Task Task} instance.
  10219. *
  10220. * var task = runner.newTask({
  10221. * run: function () {
  10222. * // useful code
  10223. * },
  10224. * interval: 1000
  10225. * });
  10226. *
  10227. * task.start();
  10228. *
  10229. * // ...
  10230. *
  10231. * task.stop();
  10232. *
  10233. * // ...
  10234. *
  10235. * task.start();
  10236. *
  10237. * A re-usable, one-shot task can be managed similar to the above:
  10238. *
  10239. * var task = runner.newTask({
  10240. * run: function () {
  10241. * // useful code to run once
  10242. * },
  10243. * repeat: 1
  10244. * });
  10245. *
  10246. * task.start();
  10247. *
  10248. * // ...
  10249. *
  10250. * task.start();
  10251. *
  10252. * See the {@link #start} method for details about how to configure a task object.
  10253. *
  10254. * Also see {@link Ext.util.DelayedTask}.
  10255. *
  10256. * @constructor
  10257. * @param {Number/Object} [interval=10] The minimum precision in milliseconds supported by this
  10258. * TaskRunner instance. Alternatively, a config object to apply to the new instance.
  10259. */
  10260. Ext.define('Ext.util.TaskRunner', {
  10261. /**
  10262. * @cfg interval
  10263. * The timer resolution.
  10264. */
  10265. interval: 10,
  10266. /**
  10267. * @property timerId
  10268. * The id of the current timer.
  10269. * @private
  10270. */
  10271. timerId: null,
  10272. constructor: function (interval) {
  10273. var me = this;
  10274. if (typeof interval == 'number') {
  10275. me.interval = interval;
  10276. } else if (interval) {
  10277. Ext.apply(me, interval);
  10278. }
  10279. me.tasks = [];
  10280. me.timerFn = Ext.Function.bind(me.onTick, me);
  10281. },
  10282. /**
  10283. * Creates a new {@link Ext.util.TaskRunner.Task Task} instance. These instances can
  10284. * be easily started and stopped.
  10285. * @param {Object} config The config object. For details on the supported properties,
  10286. * see {@link #start}.
  10287. */
  10288. newTask: function (config) {
  10289. var task = new Ext.util.TaskRunner.Task(config);
  10290. task.manager = this;
  10291. return task;
  10292. },
  10293. /**
  10294. * Starts a new task.
  10295. *
  10296. * Before each invocation, Ext injects the property `taskRunCount` into the task object
  10297. * so that calculations based on the repeat count can be performed.
  10298. *
  10299. * The returned task will contain a `destroy` method that can be used to destroy the
  10300. * task and cancel further calls. This is equivalent to the {@link #stop} method.
  10301. *
  10302. * @param {Object} task A config object that supports the following properties:
  10303. * @param {Function} task.run The function to execute each time the task is invoked. The
  10304. * function will be called at each interval and passed the `args` argument if specified,
  10305. * and the current invocation count if not.
  10306. *
  10307. * If a particular scope (`this` reference) is required, be sure to specify it using
  10308. * the `scope` argument.
  10309. *
  10310. * @param {Boolean} task.run.return `false` from this function to terminate the task.
  10311. *
  10312. * @param {Number} task.interval The frequency in milliseconds with which the task
  10313. * should be invoked.
  10314. *
  10315. * @param {Object[]} task.args An array of arguments to be passed to the function
  10316. * specified by `run`. If not specified, the current invocation count is passed.
  10317. *
  10318. * @param {Object} task.scope The scope (`this` reference) in which to execute the
  10319. * `run` function. Defaults to the task config object.
  10320. *
  10321. * @param {Number} task.duration The length of time in milliseconds to invoke the task
  10322. * before stopping automatically (defaults to indefinite).
  10323. *
  10324. * @param {Number} task.repeat The number of times to invoke the task before stopping
  10325. * automatically (defaults to indefinite).
  10326. * @return {Object} The task
  10327. */
  10328. start: function(task) {
  10329. var me = this,
  10330. now = new Date().getTime();
  10331. if (!task.pending) {
  10332. me.tasks.push(task);
  10333. task.pending = true; // don't allow the task to be added to me.tasks again
  10334. }
  10335. task.stopped = false; // might have been previously stopped...
  10336. task.taskRunTime = task.taskStartTime = now;
  10337. task.taskRunCount = 0;
  10338. if (!me.firing) {
  10339. me.startTimer(task.interval, now);
  10340. }
  10341. return task;
  10342. },
  10343. /**
  10344. * Stops an existing running task.
  10345. * @param {Object} task The task to stop
  10346. * @return {Object} The task
  10347. */
  10348. stop: function(task) {
  10349. // NOTE: we don't attempt to remove the task from me.tasks at this point because
  10350. // this could be called from inside a task which would then corrupt the state of
  10351. // the loop in onTick
  10352. if (!task.stopped) {
  10353. task.stopped = true;
  10354. if (task.onStop) {
  10355. task.onStop.call(task.scope || task);
  10356. }
  10357. }
  10358. return task;
  10359. },
  10360. /**
  10361. * Stops all tasks that are currently running.
  10362. */
  10363. stopAll: function() {
  10364. // onTick will take care of cleaning up the mess after this point...
  10365. Ext.each(this.tasks, this.stop, this);
  10366. },
  10367. //-------------------------------------------------------------------------
  10368. firing: false,
  10369. nextExpires: 1e99,
  10370. // private
  10371. onTick: function () {
  10372. var me = this,
  10373. tasks = me.tasks,
  10374. now = new Date().getTime(),
  10375. nextExpires = 1e99,
  10376. len = tasks.length,
  10377. expires, newTasks, i, task, rt, remove;
  10378. me.timerId = null;
  10379. me.firing = true; // ensure we don't startTimer during this loop...
  10380. // tasks.length can be > len if start is called during a task.run call... so we
  10381. // first check len to avoid tasks.length reference but eventually we need to also
  10382. // check tasks.length. we avoid repeating use of tasks.length by setting len at
  10383. // that time (to help the next loop)
  10384. for (i = 0; i < len || i < (len = tasks.length); ++i) {
  10385. task = tasks[i];
  10386. if (!(remove = task.stopped)) {
  10387. expires = task.taskRunTime + task.interval;
  10388. if (expires <= now) {
  10389. rt = task.run.apply(task.scope || task, task.args || [++task.taskRunCount]);
  10390. task.taskRunTime = now;
  10391. if (rt === false || task.taskRunCount === task.repeat) {
  10392. me.stop(task);
  10393. remove = true;
  10394. } else {
  10395. remove = task.stopped; // in case stop was called by run
  10396. expires = now + task.interval;
  10397. }
  10398. }
  10399. if (!remove && task.duration && task.duration <= (now - task.taskStartTime)) {
  10400. me.stop(task);
  10401. remove = true;
  10402. }
  10403. }
  10404. if (remove) {
  10405. task.pending = false; // allow the task to be added to me.tasks again
  10406. // once we detect that a task needs to be removed, we copy the tasks that
  10407. // will carry forward into newTasks... this way we avoid O(N*N) to remove
  10408. // each task from the tasks array (and ripple the array down) and also the
  10409. // potentially wasted effort of making a new tasks[] even if all tasks are
  10410. // going into the next wave.
  10411. if (!newTasks) {
  10412. newTasks = tasks.slice(0, i);
  10413. // we don't set me.tasks here because callbacks can also start tasks,
  10414. // which get added to me.tasks... so we will visit them in this loop
  10415. // and account for their expirations in nextExpires...
  10416. }
  10417. } else {
  10418. if (newTasks) {
  10419. newTasks.push(task); // we've cloned the tasks[], so keep this one...
  10420. }
  10421. if (nextExpires > expires) {
  10422. nextExpires = expires; // track the nearest expiration time
  10423. }
  10424. }
  10425. }
  10426. if (newTasks) {
  10427. // only now can we copy the newTasks to me.tasks since no user callbacks can
  10428. // take place
  10429. me.tasks = newTasks;
  10430. }
  10431. me.firing = false; // we're done, so allow startTimer afterwards
  10432. if (me.tasks.length) {
  10433. // we create a new Date here because all the callbacks could have taken a long
  10434. // time... we want to base the next timeout on the current time (after the
  10435. // callback storm):
  10436. me.startTimer(nextExpires - now, new Date().getTime());
  10437. }
  10438. },
  10439. // private
  10440. startTimer: function (timeout, now) {
  10441. var me = this,
  10442. expires = now + timeout,
  10443. timerId = me.timerId;
  10444. // Check to see if this request is enough in advance of the current timer. If so,
  10445. // we reschedule the timer based on this new expiration.
  10446. if (timerId && me.nextExpires - expires > me.interval) {
  10447. clearTimeout(timerId);
  10448. timerId = null;
  10449. }
  10450. if (!timerId) {
  10451. if (timeout < me.interval) {
  10452. timeout = me.interval;
  10453. }
  10454. me.timerId = setTimeout(me.timerFn, timeout);
  10455. me.nextExpires = expires;
  10456. }
  10457. }
  10458. },
  10459. function () {
  10460. var me = this,
  10461. proto = me.prototype;
  10462. /**
  10463. * Destroys this instance, stopping all tasks that are currently running.
  10464. * @method destroy
  10465. */
  10466. proto.destroy = proto.stopAll;
  10467. /**
  10468. * @class Ext.TaskManager
  10469. * @extends Ext.util.TaskRunner
  10470. * @singleton
  10471. *
  10472. * A static {@link Ext.util.TaskRunner} instance that can be used to start and stop
  10473. * arbitrary tasks. See {@link Ext.util.TaskRunner} for supported methods and task
  10474. * config properties.
  10475. *
  10476. * // Start a simple clock task that updates a div once per second
  10477. * var task = {
  10478. * run: function(){
  10479. * Ext.fly('clock').update(new Date().format('g:i:s A'));
  10480. * },
  10481. * interval: 1000 //1 second
  10482. * }
  10483. *
  10484. * Ext.TaskManager.start(task);
  10485. *
  10486. * See the {@link #start} method for details about how to configure a task object.
  10487. */
  10488. Ext.util.TaskManager = Ext.TaskManager = new me();
  10489. /**
  10490. * Instances of this class are created by {@link Ext.util.TaskRunner#newTask} method.
  10491. *
  10492. * For details on config properties, see {@link Ext.util.TaskRunner#start}.
  10493. * @class Ext.util.TaskRunner.Task
  10494. */
  10495. me.Task = new Ext.Class({
  10496. isTask: true,
  10497. /**
  10498. * This flag is set to `true` by {@link #stop}.
  10499. * @private
  10500. */
  10501. stopped: true, // this avoids the odd combination of !stopped && !pending
  10502. constructor: function (config) {
  10503. Ext.apply(this, config);
  10504. },
  10505. /**
  10506. * Restarts this task, clearing it duration, expiration and run count.
  10507. * @param {Number} [interval] Optionally reset this task's interval.
  10508. */
  10509. restart: function (interval) {
  10510. if (interval !== undefined) {
  10511. this.interval = interval;
  10512. }
  10513. this.manager.start(this);
  10514. },
  10515. /**
  10516. * Starts this task if it is not already started.
  10517. * @param {Number} [interval] Optionally reset this task's interval.
  10518. */
  10519. start: function (interval) {
  10520. if (this.stopped) {
  10521. this.restart(interval);
  10522. }
  10523. },
  10524. /**
  10525. * Stops this task.
  10526. */
  10527. stop: function () {
  10528. this.manager.stop(this);
  10529. }
  10530. });
  10531. proto = me.Task.prototype;
  10532. /**
  10533. * Destroys this instance, stopping this task's execution.
  10534. * @method destroy
  10535. */
  10536. proto.destroy = proto.stop;
  10537. });
  10538. /**
  10539. * @class Ext.perf.Accumulator
  10540. * @private
  10541. */
  10542. Ext.define('Ext.perf.Accumulator', function () {
  10543. var currentFrame = null,
  10544. khrome = Ext.global['chrome'],
  10545. formatTpl,
  10546. // lazy init on first request for timestamp (avoids infobar in IE until needed)
  10547. // Also avoids kicking off Chrome's microsecond timer until first needed
  10548. getTimestamp = function () {
  10549. getTimestamp = function () {
  10550. return new Date().getTime();
  10551. }
  10552. // If Chrome is started with the --enable-benchmarking switch
  10553. if (Ext.isChrome && khrome && khrome.Interval) {
  10554. var interval = new khrome.Interval();
  10555. interval.start();
  10556. getTimestamp = function () {
  10557. return interval.microseconds() / 1000;
  10558. }
  10559. }
  10560. else if (window.ActiveXObject) {
  10561. try {
  10562. // the above technique is not very accurate for small intervals...
  10563. var toolbox = new ActiveXObject('SenchaToolbox.Toolbox');
  10564. getTimestamp = function () {
  10565. return toolbox.milliseconds;
  10566. };
  10567. } catch (e) {
  10568. // ignore
  10569. }
  10570. } else if (Date.now) {
  10571. getTimestamp = Date.now;
  10572. }
  10573. Ext.perf.getTimestamp = Ext.perf.Accumulator.getTimestamp = getTimestamp;
  10574. return getTimestamp();
  10575. };
  10576. function adjustSet (set, time) {
  10577. set.sum += time;
  10578. set.min = Math.min(set.min, time);
  10579. set.max = Math.max(set.max, time);
  10580. }
  10581. function leaveFrame (time) {
  10582. var totalTime = time ? time : (getTimestamp() - this.time), // do this first
  10583. me = this, // me = frame
  10584. accum = me.accum;
  10585. ++accum.count;
  10586. if (! --accum.depth) {
  10587. adjustSet(accum.total, totalTime);
  10588. }
  10589. adjustSet(accum.pure, totalTime - me.childTime);
  10590. currentFrame = me.parent;
  10591. if (currentFrame) {
  10592. ++currentFrame.accum.childCount;
  10593. currentFrame.childTime += totalTime;
  10594. }
  10595. }
  10596. function makeSet () {
  10597. return {
  10598. min: Number.MAX_VALUE,
  10599. max: 0,
  10600. sum: 0
  10601. }
  10602. }
  10603. function makeTap (me, fn) {
  10604. return function () {
  10605. var frame = me.enter(),
  10606. ret = fn.apply(this, arguments);
  10607. frame.leave();
  10608. return ret;
  10609. };
  10610. }
  10611. function round (x) {
  10612. return Math.round(x * 100) / 100;
  10613. }
  10614. function setToJSON (count, childCount, calibration, set) {
  10615. var data = {
  10616. avg: 0,
  10617. min: set.min,
  10618. max: set.max,
  10619. sum: 0
  10620. };
  10621. if (count) {
  10622. calibration = calibration || 0;
  10623. data.sum = set.sum - childCount * calibration;
  10624. data.avg = data.sum / count;
  10625. // min and max cannot be easily corrected since we don't know the number of
  10626. // child calls for them.
  10627. }
  10628. return data;
  10629. }
  10630. return {
  10631. constructor: function (name) {
  10632. var me = this;
  10633. me.count = me.childCount = me.depth = me.maxDepth = 0;
  10634. me.pure = makeSet();
  10635. me.total = makeSet();
  10636. me.name = name;
  10637. },
  10638. statics: {
  10639. getTimestamp: getTimestamp
  10640. },
  10641. format: function (calibration) {
  10642. if (!formatTpl) {
  10643. formatTpl = new Ext.XTemplate([
  10644. '{name} - {count} call(s)',
  10645. '<tpl if="count">',
  10646. '<tpl if="childCount">',
  10647. ' ({childCount} children)',
  10648. '</tpl>',
  10649. '<tpl if="depth - 1">',
  10650. ' ({depth} deep)',
  10651. '</tpl>',
  10652. '<tpl for="times">',
  10653. ', {type}: {[this.time(values.sum)]} msec (',
  10654. //'min={[this.time(values.min)]}, ',
  10655. 'avg={[this.time(values.sum / parent.count)]}',
  10656. //', max={[this.time(values.max)]}',
  10657. ')',
  10658. '</tpl>',
  10659. '</tpl>'
  10660. ].join(''), {
  10661. time: function (t) {
  10662. return Math.round(t * 100) / 100;
  10663. }
  10664. });
  10665. }
  10666. var data = this.getData(calibration);
  10667. data.name = this.name;
  10668. data.pure.type = 'Pure';
  10669. data.total.type = 'Total';
  10670. data.times = [data.pure, data.total];
  10671. return formatTpl.apply(data);
  10672. },
  10673. getData: function (calibration) {
  10674. var me = this;
  10675. return {
  10676. count: me.count,
  10677. childCount: me.childCount,
  10678. depth: me.maxDepth,
  10679. pure: setToJSON(me.count, me.childCount, calibration, me.pure),
  10680. total: setToJSON(me.count, me.childCount, calibration, me.total)
  10681. };
  10682. },
  10683. enter: function () {
  10684. var me = this,
  10685. frame = {
  10686. accum: me,
  10687. leave: leaveFrame,
  10688. childTime: 0,
  10689. parent: currentFrame
  10690. };
  10691. ++me.depth;
  10692. if (me.maxDepth < me.depth) {
  10693. me.maxDepth = me.depth;
  10694. }
  10695. currentFrame = frame;
  10696. frame.time = getTimestamp(); // do this last
  10697. return frame;
  10698. },
  10699. monitor: function (fn, scope, args) {
  10700. var frame = this.enter();
  10701. if (args) {
  10702. fn.apply(scope, args);
  10703. } else {
  10704. fn.call(scope);
  10705. }
  10706. frame.leave();
  10707. },
  10708. report: function () {
  10709. Ext.log(this.format());
  10710. },
  10711. tap: function (className, methodName) {
  10712. var me = this,
  10713. methods = typeof methodName == 'string' ? [methodName] : methodName,
  10714. klass, statik, i, parts, length, name, src;
  10715. var tapFunc = function(){
  10716. if (typeof className == 'string') {
  10717. klass = Ext.global;
  10718. parts = className.split('.');
  10719. for (i = 0, length = parts.length; i < length; ++i) {
  10720. klass = klass[parts[i]];
  10721. }
  10722. } else {
  10723. klass = className;
  10724. }
  10725. for (i = 0, length = methods.length; i < length; ++i) {
  10726. name = methods[i];
  10727. statik = name.charAt(0) == '!';
  10728. if (statik) {
  10729. name = name.substring(1);
  10730. } else {
  10731. statik = !(name in klass.prototype);
  10732. }
  10733. src = statik ? klass : klass.prototype;
  10734. src[name] = makeTap(me, src[name]);
  10735. }
  10736. };
  10737. Ext.ClassManager.onCreated(tapFunc, me, className);
  10738. return me;
  10739. }
  10740. };
  10741. }(),
  10742. function () {
  10743. Ext.perf.getTimestamp = this.getTimestamp;
  10744. });
  10745. /**
  10746. * @class Ext.perf.Monitor
  10747. * @singleton
  10748. * @private
  10749. */
  10750. Ext.define('Ext.perf.Monitor', {
  10751. singleton: true,
  10752. alternateClassName: 'Ext.Perf',
  10753. requires: [
  10754. 'Ext.perf.Accumulator'
  10755. ],
  10756. constructor: function () {
  10757. this.accumulators = [];
  10758. this.accumulatorsByName = {};
  10759. },
  10760. calibrate: function () {
  10761. var accum = new Ext.perf.Accumulator('$'),
  10762. total = accum.total,
  10763. getTimestamp = Ext.perf.Accumulator.getTimestamp,
  10764. count = 0,
  10765. frame,
  10766. endTime,
  10767. startTime;
  10768. startTime = getTimestamp();
  10769. do {
  10770. frame = accum.enter();
  10771. frame.leave();
  10772. ++count;
  10773. } while (total.sum < 100);
  10774. endTime = getTimestamp();
  10775. return (endTime - startTime) / count;
  10776. },
  10777. get: function (name) {
  10778. var me = this,
  10779. accum = me.accumulatorsByName[name];
  10780. if (!accum) {
  10781. me.accumulatorsByName[name] = accum = new Ext.perf.Accumulator(name);
  10782. me.accumulators.push(accum);
  10783. }
  10784. return accum;
  10785. },
  10786. enter: function (name) {
  10787. return this.get(name).enter();
  10788. },
  10789. monitor: function (name, fn, scope) {
  10790. this.get(name).monitor(fn, scope);
  10791. },
  10792. report: function () {
  10793. var me = this,
  10794. accumulators = me.accumulators,
  10795. calibration = me.calibrate(),
  10796. report = ['Calibration: ' + Math.round(calibration * 100) / 100 + ' msec/sample'];
  10797. accumulators.sort(function (a, b) {
  10798. return (a.name < b.name) ? -1 : ((b.name < a.name) ? 1 : 0);
  10799. });
  10800. Ext.each(accumulators, function (accum) {
  10801. report.push(accum.format(calibration));
  10802. });
  10803. Ext.log(report.join('\n'));
  10804. },
  10805. getData: function (all) {
  10806. var ret = {},
  10807. accumulators = this.accumulators;
  10808. Ext.each(accumulators, function (accum) {
  10809. if (all || accum.count) {
  10810. ret[accum.name] = accum.getData();
  10811. }
  10812. });
  10813. return ret;
  10814. },
  10815. setup: function (config) {
  10816. if (!config) {
  10817. config = {
  10818. /*insertHtml: {
  10819. 'Ext.dom.Helper': 'insertHtml'
  10820. },*/
  10821. /*xtplCompile: {
  10822. 'Ext.XTemplateCompiler': 'compile'
  10823. },*/
  10824. // doInsert: {
  10825. // 'Ext.Template': 'doInsert'
  10826. // },
  10827. // applyOut: {
  10828. // 'Ext.XTemplate': 'applyOut'
  10829. // },
  10830. render: {
  10831. 'Ext.AbstractComponent': 'render'
  10832. },
  10833. // fnishRender: {
  10834. // 'Ext.AbstractComponent': 'finishRender'
  10835. // },
  10836. // renderSelectors: {
  10837. // 'Ext.AbstractComponent': 'applyRenderSelectors'
  10838. // },
  10839. // compAddCls: {
  10840. // 'Ext.AbstractComponent': 'addCls'
  10841. // },
  10842. // compRemoveCls: {
  10843. // 'Ext.AbstractComponent': 'removeCls'
  10844. // },
  10845. // getStyle: {
  10846. // 'Ext.core.Element': 'getStyle'
  10847. // },
  10848. // setStyle: {
  10849. // 'Ext.core.Element': 'setStyle'
  10850. // },
  10851. // addCls: {
  10852. // 'Ext.core.Element': 'addCls'
  10853. // },
  10854. // removeCls: {
  10855. // 'Ext.core.Element': 'removeCls'
  10856. // },
  10857. // measure: {
  10858. // 'Ext.layout.component.Component': 'measureAutoDimensions'
  10859. // },
  10860. // moveItem: {
  10861. // 'Ext.layout.Layout': 'moveItem'
  10862. // },
  10863. // layoutFlush: {
  10864. // 'Ext.layout.Context': 'flush'
  10865. // },
  10866. layout: {
  10867. 'Ext.layout.Context': 'run'
  10868. }
  10869. };
  10870. }
  10871. this.currentConfig = config;
  10872. var key, prop;
  10873. for (key in config) {
  10874. if (config.hasOwnProperty(key)) {
  10875. prop = config[key];
  10876. var accum = Ext.Perf.get(key),
  10877. className, methods;
  10878. for (className in prop) {
  10879. if (prop.hasOwnProperty(className)) {
  10880. methods = prop[className];
  10881. accum.tap(className, methods);
  10882. }
  10883. }
  10884. }
  10885. }
  10886. }
  10887. });
  10888. /**
  10889. * @class Ext.is
  10890. *
  10891. * Determines information about the current platform the application is running on.
  10892. *
  10893. * @singleton
  10894. */
  10895. Ext.is = {
  10896. init : function(navigator) {
  10897. var platforms = this.platforms,
  10898. ln = platforms.length,
  10899. i, platform;
  10900. navigator = navigator || window.navigator;
  10901. for (i = 0; i < ln; i++) {
  10902. platform = platforms[i];
  10903. this[platform.identity] = platform.regex.test(navigator[platform.property]);
  10904. }
  10905. /**
  10906. * @property Desktop True if the browser is running on a desktop machine
  10907. * @type {Boolean}
  10908. */
  10909. this.Desktop = this.Mac || this.Windows || (this.Linux && !this.Android);
  10910. /**
  10911. * @property Tablet True if the browser is running on a tablet (iPad)
  10912. */
  10913. this.Tablet = this.iPad;
  10914. /**
  10915. * @property Phone True if the browser is running on a phone.
  10916. * @type {Boolean}
  10917. */
  10918. this.Phone = !this.Desktop && !this.Tablet;
  10919. /**
  10920. * @property iOS True if the browser is running on iOS
  10921. * @type {Boolean}
  10922. */
  10923. this.iOS = this.iPhone || this.iPad || this.iPod;
  10924. /**
  10925. * @property Standalone Detects when application has been saved to homescreen.
  10926. * @type {Boolean}
  10927. */
  10928. this.Standalone = !!window.navigator.standalone;
  10929. },
  10930. /**
  10931. * @property iPhone True when the browser is running on a iPhone
  10932. * @type {Boolean}
  10933. */
  10934. platforms: [{
  10935. property: 'platform',
  10936. regex: /iPhone/i,
  10937. identity: 'iPhone'
  10938. },
  10939. /**
  10940. * @property iPod True when the browser is running on a iPod
  10941. * @type {Boolean}
  10942. */
  10943. {
  10944. property: 'platform',
  10945. regex: /iPod/i,
  10946. identity: 'iPod'
  10947. },
  10948. /**
  10949. * @property iPad True when the browser is running on a iPad
  10950. * @type {Boolean}
  10951. */
  10952. {
  10953. property: 'userAgent',
  10954. regex: /iPad/i,
  10955. identity: 'iPad'
  10956. },
  10957. /**
  10958. * @property Blackberry True when the browser is running on a Blackberry
  10959. * @type {Boolean}
  10960. */
  10961. {
  10962. property: 'userAgent',
  10963. regex: /Blackberry/i,
  10964. identity: 'Blackberry'
  10965. },
  10966. /**
  10967. * @property Android True when the browser is running on an Android device
  10968. * @type {Boolean}
  10969. */
  10970. {
  10971. property: 'userAgent',
  10972. regex: /Android/i,
  10973. identity: 'Android'
  10974. },
  10975. /**
  10976. * @property Mac True when the browser is running on a Mac
  10977. * @type {Boolean}
  10978. */
  10979. {
  10980. property: 'platform',
  10981. regex: /Mac/i,
  10982. identity: 'Mac'
  10983. },
  10984. /**
  10985. * @property Windows True when the browser is running on Windows
  10986. * @type {Boolean}
  10987. */
  10988. {
  10989. property: 'platform',
  10990. regex: /Win/i,
  10991. identity: 'Windows'
  10992. },
  10993. /**
  10994. * @property Linux True when the browser is running on Linux
  10995. * @type {Boolean}
  10996. */
  10997. {
  10998. property: 'platform',
  10999. regex: /Linux/i,
  11000. identity: 'Linux'
  11001. }]
  11002. };
  11003. Ext.is.init();
  11004. /**
  11005. * @class Ext.supports
  11006. *
  11007. * Determines information about features are supported in the current environment
  11008. *
  11009. * @singleton
  11010. */
  11011. Ext.supports = {
  11012. /**
  11013. * Runs feature detection routines and sets the various flags. This is called when
  11014. * the scripts loads (very early) and again at {@link Ext#onReady}. Some detections
  11015. * are flagged as `early` and run immediately. Others that require the document body
  11016. * will not run until ready.
  11017. *
  11018. * Each test is run only once, so calling this method from an onReady function is safe
  11019. * and ensures that all flags have been set.
  11020. * @markdown
  11021. * @private
  11022. */
  11023. init : function() {
  11024. var me = this,
  11025. doc = document,
  11026. tests = me.tests,
  11027. n = tests.length,
  11028. div = n && Ext.isReady && doc.createElement('div'),
  11029. test, notRun = [];
  11030. if (div) {
  11031. div.innerHTML = [
  11032. '<div style="height:30px;width:50px;">',
  11033. '<div style="height:20px;width:20px;"></div>',
  11034. '</div>',
  11035. '<div style="width: 200px; height: 200px; position: relative; padding: 5px;">',
  11036. '<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></div>',
  11037. '</div>',
  11038. '<div style="position: absolute; left: 10%; top: 10%;"></div>',
  11039. '<div style="float:left; background-color:transparent;"></div>'
  11040. ].join('');
  11041. doc.body.appendChild(div);
  11042. }
  11043. while (n--) {
  11044. test = tests[n];
  11045. if (div || test.early) {
  11046. me[test.identity] = test.fn.call(me, doc, div);
  11047. } else {
  11048. notRun.push(test);
  11049. }
  11050. }
  11051. if (div) {
  11052. doc.body.removeChild(div);
  11053. }
  11054. me.tests = notRun;
  11055. },
  11056. /**
  11057. * @property PointerEvents True if document environment supports the CSS3 pointer-events style.
  11058. * @type {Boolean}
  11059. */
  11060. PointerEvents: 'pointerEvents' in document.documentElement.style,
  11061. /**
  11062. * @property CSS3BoxShadow True if document environment supports the CSS3 box-shadow style.
  11063. * @type {Boolean}
  11064. */
  11065. CSS3BoxShadow: 'boxShadow' in document.documentElement.style,
  11066. /**
  11067. * @property ClassList True if document environment supports the HTML5 classList API.
  11068. * @type {Boolean}
  11069. */
  11070. ClassList: !!document.documentElement.classList,
  11071. /**
  11072. * @property OrientationChange True if the device supports orientation change
  11073. * @type {Boolean}
  11074. */
  11075. OrientationChange: ((typeof window.orientation != 'undefined') && ('onorientationchange' in window)),
  11076. /**
  11077. * @property DeviceMotion True if the device supports device motion (acceleration and rotation rate)
  11078. * @type {Boolean}
  11079. */
  11080. DeviceMotion: ('ondevicemotion' in window),
  11081. /**
  11082. * @property Touch True if the device supports touch
  11083. * @type {Boolean}
  11084. */
  11085. // is.Desktop is needed due to the bug in Chrome 5.0.375, Safari 3.1.2
  11086. // and Safari 4.0 (they all have 'ontouchstart' in the window object).
  11087. Touch: ('ontouchstart' in window) && (!Ext.is.Desktop),
  11088. tests: [
  11089. /**
  11090. * @property Transitions True if the device supports CSS3 Transitions
  11091. * @type {Boolean}
  11092. */
  11093. {
  11094. identity: 'Transitions',
  11095. fn: function(doc, div) {
  11096. var prefix = [
  11097. 'webkit',
  11098. 'Moz',
  11099. 'o',
  11100. 'ms',
  11101. 'khtml'
  11102. ],
  11103. TE = 'TransitionEnd',
  11104. transitionEndName = [
  11105. prefix[0] + TE,
  11106. 'transitionend', //Moz bucks the prefixing convention
  11107. prefix[2] + TE,
  11108. prefix[3] + TE,
  11109. prefix[4] + TE
  11110. ],
  11111. ln = prefix.length,
  11112. i = 0,
  11113. out = false;
  11114. div = Ext.get(div);
  11115. for (; i < ln; i++) {
  11116. if (div.getStyle(prefix[i] + "TransitionProperty")) {
  11117. Ext.supports.CSS3Prefix = prefix[i];
  11118. Ext.supports.CSS3TransitionEnd = transitionEndName[i];
  11119. out = true;
  11120. break;
  11121. }
  11122. }
  11123. return out;
  11124. }
  11125. },
  11126. /**
  11127. * @property RightMargin True if the device supports right margin.
  11128. * See https://bugs.webkit.org/show_bug.cgi?id=13343 for why this is needed.
  11129. * @type {Boolean}
  11130. */
  11131. {
  11132. identity: 'RightMargin',
  11133. fn: function(doc, div) {
  11134. var view = doc.defaultView;
  11135. return !(view && view.getComputedStyle(div.firstChild.firstChild, null).marginRight != '0px');
  11136. }
  11137. },
  11138. /**
  11139. * @property DisplayChangeInputSelectionBug True if INPUT elements lose their
  11140. * selection when their display style is changed. Essentially, if a text input
  11141. * has focus and its display style is changed, the I-beam disappears.
  11142. *
  11143. * This bug is encountered due to the work around in place for the {@link #RightMargin}
  11144. * bug. This has been observed in Safari 4.0.4 and older, and appears to be fixed
  11145. * in Safari 5. It's not clear if Safari 4.1 has the bug, but it has the same WebKit
  11146. * version number as Safari 5 (according to http://unixpapa.com/js/gecko.html).
  11147. */
  11148. {
  11149. identity: 'DisplayChangeInputSelectionBug',
  11150. early: true,
  11151. fn: function() {
  11152. var webKitVersion = Ext.webKitVersion;
  11153. // WebKit but older than Safari 5 or Chrome 6:
  11154. return 0 < webKitVersion && webKitVersion < 533;
  11155. }
  11156. },
  11157. /**
  11158. * @property DisplayChangeTextAreaSelectionBug True if TEXTAREA elements lose their
  11159. * selection when their display style is changed. Essentially, if a text area has
  11160. * focus and its display style is changed, the I-beam disappears.
  11161. *
  11162. * This bug is encountered due to the work around in place for the {@link #RightMargin}
  11163. * bug. This has been observed in Chrome 10 and Safari 5 and older, and appears to
  11164. * be fixed in Chrome 11.
  11165. */
  11166. {
  11167. identity: 'DisplayChangeTextAreaSelectionBug',
  11168. early: true,
  11169. fn: function() {
  11170. var webKitVersion = Ext.webKitVersion;
  11171. /*
  11172. Has bug w/textarea:
  11173. (Chrome) Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-US)
  11174. AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.127
  11175. Safari/534.16
  11176. (Safari) Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-us)
  11177. AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5
  11178. Safari/533.21.1
  11179. No bug:
  11180. (Chrome) Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_7)
  11181. AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.57
  11182. Safari/534.24
  11183. */
  11184. return 0 < webKitVersion && webKitVersion < 534.24;
  11185. }
  11186. },
  11187. /**
  11188. * @property TransparentColor True if the device supports transparent color
  11189. * @type {Boolean}
  11190. */
  11191. {
  11192. identity: 'TransparentColor',
  11193. fn: function(doc, div, view) {
  11194. view = doc.defaultView;
  11195. return !(view && view.getComputedStyle(div.lastChild, null).backgroundColor != 'transparent');
  11196. }
  11197. },
  11198. /**
  11199. * @property ComputedStyle True if the browser supports document.defaultView.getComputedStyle()
  11200. * @type {Boolean}
  11201. */
  11202. {
  11203. identity: 'ComputedStyle',
  11204. fn: function(doc, div, view) {
  11205. view = doc.defaultView;
  11206. return view && view.getComputedStyle;
  11207. }
  11208. },
  11209. /**
  11210. * @property SVG True if the device supports SVG
  11211. * @type {Boolean}
  11212. */
  11213. {
  11214. identity: 'Svg',
  11215. fn: function(doc) {
  11216. return !!doc.createElementNS && !!doc.createElementNS( "http:/" + "/www.w3.org/2000/svg", "svg").createSVGRect;
  11217. }
  11218. },
  11219. /**
  11220. * @property Canvas True if the device supports Canvas
  11221. * @type {Boolean}
  11222. */
  11223. {
  11224. identity: 'Canvas',
  11225. fn: function(doc) {
  11226. return !!doc.createElement('canvas').getContext;
  11227. }
  11228. },
  11229. /**
  11230. * @property VML True if the device supports VML
  11231. * @type {Boolean}
  11232. */
  11233. {
  11234. identity: 'Vml',
  11235. fn: function(doc) {
  11236. var d = doc.createElement("div");
  11237. d.innerHTML = "<!--[if vml]><br><br><![endif]-->";
  11238. return (d.childNodes.length == 2);
  11239. }
  11240. },
  11241. /**
  11242. * @property Float True if the device supports CSS float
  11243. * @type {Boolean}
  11244. */
  11245. {
  11246. identity: 'Float',
  11247. fn: function(doc, div) {
  11248. return !!div.lastChild.style.cssFloat;
  11249. }
  11250. },
  11251. /**
  11252. * @property AudioTag True if the device supports the HTML5 audio tag
  11253. * @type {Boolean}
  11254. */
  11255. {
  11256. identity: 'AudioTag',
  11257. fn: function(doc) {
  11258. return !!doc.createElement('audio').canPlayType;
  11259. }
  11260. },
  11261. /**
  11262. * @property History True if the device supports HTML5 history
  11263. * @type {Boolean}
  11264. */
  11265. {
  11266. identity: 'History',
  11267. fn: function() {
  11268. var history = window.history;
  11269. return !!(history && history.pushState);
  11270. }
  11271. },
  11272. /**
  11273. * @property CSS3DTransform True if the device supports CSS3DTransform
  11274. * @type {Boolean}
  11275. */
  11276. {
  11277. identity: 'CSS3DTransform',
  11278. fn: function() {
  11279. return (typeof WebKitCSSMatrix != 'undefined' && new WebKitCSSMatrix().hasOwnProperty('m41'));
  11280. }
  11281. },
  11282. /**
  11283. * @property CSS3LinearGradient True if the device supports CSS3 linear gradients
  11284. * @type {Boolean}
  11285. */
  11286. {
  11287. identity: 'CSS3LinearGradient',
  11288. fn: function(doc, div) {
  11289. var property = 'background-image:',
  11290. webkit = '-webkit-gradient(linear, left top, right bottom, from(black), to(white))',
  11291. w3c = 'linear-gradient(left top, black, white)',
  11292. moz = '-moz-' + w3c,
  11293. opera = '-o-' + w3c,
  11294. options = [property + webkit, property + w3c, property + moz, property + opera];
  11295. div.style.cssText = options.join(';');
  11296. return ("" + div.style.backgroundImage).indexOf('gradient') !== -1;
  11297. }
  11298. },
  11299. /**
  11300. * @property CSS3BorderRadius True if the device supports CSS3 border radius
  11301. * @type {Boolean}
  11302. */
  11303. {
  11304. identity: 'CSS3BorderRadius',
  11305. fn: function(doc, div) {
  11306. var domPrefixes = ['borderRadius', 'BorderRadius', 'MozBorderRadius', 'WebkitBorderRadius', 'OBorderRadius', 'KhtmlBorderRadius'],
  11307. pass = false,
  11308. i;
  11309. for (i = 0; i < domPrefixes.length; i++) {
  11310. if (document.body.style[domPrefixes[i]] !== undefined) {
  11311. return true;
  11312. }
  11313. }
  11314. return pass;
  11315. }
  11316. },
  11317. /**
  11318. * @property GeoLocation True if the device supports GeoLocation
  11319. * @type {Boolean}
  11320. */
  11321. {
  11322. identity: 'GeoLocation',
  11323. fn: function() {
  11324. return (typeof navigator != 'undefined' && typeof navigator.geolocation != 'undefined') || (typeof google != 'undefined' && typeof google.gears != 'undefined');
  11325. }
  11326. },
  11327. /**
  11328. * @property MouseEnterLeave True if the browser supports mouseenter and mouseleave events
  11329. * @type {Boolean}
  11330. */
  11331. {
  11332. identity: 'MouseEnterLeave',
  11333. fn: function(doc, div){
  11334. return ('onmouseenter' in div && 'onmouseleave' in div);
  11335. }
  11336. },
  11337. /**
  11338. * @property MouseWheel True if the browser supports the mousewheel event
  11339. * @type {Boolean}
  11340. */
  11341. {
  11342. identity: 'MouseWheel',
  11343. fn: function(doc, div) {
  11344. return ('onmousewheel' in div);
  11345. }
  11346. },
  11347. /**
  11348. * @property Opacity True if the browser supports normal css opacity
  11349. * @type {Boolean}
  11350. */
  11351. {
  11352. identity: 'Opacity',
  11353. fn: function(doc, div){
  11354. // Not a strict equal comparison in case opacity can be converted to a number.
  11355. if (Ext.isIE6 || Ext.isIE7 || Ext.isIE8) {
  11356. return false;
  11357. }
  11358. div.firstChild.style.cssText = 'opacity:0.73';
  11359. return div.firstChild.style.opacity == '0.73';
  11360. }
  11361. },
  11362. /**
  11363. * @property Placeholder True if the browser supports the HTML5 placeholder attribute on inputs
  11364. * @type {Boolean}
  11365. */
  11366. {
  11367. identity: 'Placeholder',
  11368. fn: function(doc) {
  11369. return 'placeholder' in doc.createElement('input');
  11370. }
  11371. },
  11372. /**
  11373. * @property Direct2DBug True if when asking for an element's dimension via offsetWidth or offsetHeight,
  11374. * getBoundingClientRect, etc. the browser returns the subpixel width rounded to the nearest pixel.
  11375. * @type {Boolean}
  11376. */
  11377. {
  11378. identity: 'Direct2DBug',
  11379. fn: function() {
  11380. return Ext.isString(document.body.style.msTransformOrigin);
  11381. }
  11382. },
  11383. /**
  11384. * @property BoundingClientRect True if the browser supports the getBoundingClientRect method on elements
  11385. * @type {Boolean}
  11386. */
  11387. {
  11388. identity: 'BoundingClientRect',
  11389. fn: function(doc, div) {
  11390. return Ext.isFunction(div.getBoundingClientRect);
  11391. }
  11392. },
  11393. {
  11394. identity: 'IncludePaddingInWidthCalculation',
  11395. fn: function(doc, div){
  11396. var el = Ext.get(div.childNodes[1].firstChild);
  11397. return el.getWidth() == 210;
  11398. }
  11399. },
  11400. {
  11401. identity: 'IncludePaddingInHeightCalculation',
  11402. fn: function(doc, div){
  11403. var el = Ext.get(div.childNodes[1].firstChild);
  11404. return el.getHeight() == 210;
  11405. }
  11406. },
  11407. /**
  11408. * @property ArraySort True if the Array sort native method isn't bugged.
  11409. * @type {Boolean}
  11410. */
  11411. {
  11412. identity: 'ArraySort',
  11413. fn: function() {
  11414. var a = [1,2,3,4,5].sort(function(){ return 0; });
  11415. return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5;
  11416. }
  11417. },
  11418. /**
  11419. * @property Range True if browser support document.createRange native method.
  11420. * @type {Boolean}
  11421. */
  11422. {
  11423. identity: 'Range',
  11424. fn: function() {
  11425. return !!document.createRange;
  11426. }
  11427. },
  11428. /**
  11429. * @property CreateContextualFragment True if browser support CreateContextualFragment range native methods.
  11430. * @type {Boolean}
  11431. */
  11432. {
  11433. identity: 'CreateContextualFragment',
  11434. fn: function() {
  11435. var range = Ext.supports.Range ? document.createRange() : false;
  11436. return range && !!range.createContextualFragment;
  11437. }
  11438. },
  11439. /**
  11440. * @property WindowOnError True if browser supports window.onerror.
  11441. * @type {Boolean}
  11442. */
  11443. {
  11444. identity: 'WindowOnError',
  11445. fn: function () {
  11446. // sadly, we cannot feature detect this...
  11447. return Ext.isIE || Ext.isGecko || Ext.webKitVersion >= 534.16; // Chrome 10+
  11448. }
  11449. },
  11450. /**
  11451. * @property TextAreaMaxLength True if the browser supports maxlength on textareas.
  11452. * @type {Boolean}
  11453. */
  11454. {
  11455. identity: 'TextAreaMaxLength',
  11456. fn: function(){
  11457. var el = document.createElement('textarea');
  11458. return ('maxlength' in el);
  11459. }
  11460. },
  11461. /**
  11462. * @property GetPositionPercentage True if the browser will return the left/top/right/bottom
  11463. * position as a percentage when explicitly set as a percentage value.
  11464. * @type {Boolean}
  11465. */
  11466. // Related bug: https://bugzilla.mozilla.org/show_bug.cgi?id=707691#c7
  11467. {
  11468. identity: 'GetPositionPercentage',
  11469. fn: function(doc, div){
  11470. return Ext.get(div.childNodes[2]).getStyle('left') == '10%';
  11471. }
  11472. }
  11473. ]
  11474. };
  11475. Ext.supports.init(); // run the "early" detections now
  11476. /**
  11477. * @class Ext.util.DelayedTask
  11478. *
  11479. * The DelayedTask class provides a convenient way to "buffer" the execution of a method,
  11480. * performing setTimeout where a new timeout cancels the old timeout. When called, the
  11481. * task will wait the specified time period before executing. If durng that time period,
  11482. * the task is called again, the original call will be cancelled. This continues so that
  11483. * the function is only called a single time for each iteration.
  11484. *
  11485. * This method is especially useful for things like detecting whether a user has finished
  11486. * typing in a text field. An example would be performing validation on a keypress. You can
  11487. * use this class to buffer the keypress events for a certain number of milliseconds, and
  11488. * perform only if they stop for that amount of time.
  11489. *
  11490. * ## Usage
  11491. *
  11492. * var task = new Ext.util.DelayedTask(function(){
  11493. * alert(Ext.getDom('myInputField').value.length);
  11494. * });
  11495. *
  11496. * // Wait 500ms before calling our function. If the user presses another key
  11497. * // during that 500ms, it will be cancelled and we'll wait another 500ms.
  11498. * Ext.get('myInputField').on('keypress', function(){
  11499. * task.{@link #delay}(500);
  11500. * });
  11501. *
  11502. * Note that we are using a DelayedTask here to illustrate a point. The configuration
  11503. * option `buffer` for {@link Ext.util.Observable#addListener addListener/on} will
  11504. * also setup a delayed task for you to buffer events.
  11505. *
  11506. * @constructor The parameters to this constructor serve as defaults and are not required.
  11507. * @param {Function} fn (optional) The default function to call. If not specified here, it must be specified during the {@link #delay} call.
  11508. * @param {Object} scope (optional) The default scope (The <code><b>this</b></code> reference) in which the
  11509. * function is called. If not specified, <code>this</code> will refer to the browser window.
  11510. * @param {Array} args (optional) The default Array of arguments.
  11511. */
  11512. Ext.util.DelayedTask = function(fn, scope, args) {
  11513. var me = this,
  11514. id,
  11515. call = function() {
  11516. clearInterval(id);
  11517. id = null;
  11518. fn.apply(scope, args || []);
  11519. };
  11520. /**
  11521. * Cancels any pending timeout and queues a new one
  11522. * @param {Number} delay The milliseconds to delay
  11523. * @param {Function} newFn (optional) Overrides function passed to constructor
  11524. * @param {Object} newScope (optional) Overrides scope passed to constructor. Remember that if no scope
  11525. * is specified, <code>this</code> will refer to the browser window.
  11526. * @param {Array} newArgs (optional) Overrides args passed to constructor
  11527. */
  11528. this.delay = function(delay, newFn, newScope, newArgs) {
  11529. me.cancel();
  11530. fn = newFn || fn;
  11531. scope = newScope || scope;
  11532. args = newArgs || args;
  11533. id = setInterval(call, delay);
  11534. };
  11535. /**
  11536. * Cancel the last queued timeout
  11537. */
  11538. this.cancel = function(){
  11539. if (id) {
  11540. clearInterval(id);
  11541. id = null;
  11542. }
  11543. };
  11544. };
  11545. Ext.require('Ext.util.DelayedTask', function() {
  11546. /**
  11547. * Represents single event type that an Observable object listens to.
  11548. * All actual listeners are tracked inside here. When the event fires,
  11549. * it calls all the registered listener functions.
  11550. *
  11551. * @private
  11552. */
  11553. Ext.util.Event = Ext.extend(Object, (function() {
  11554. function createBuffered(handler, listener, o, scope) {
  11555. listener.task = new Ext.util.DelayedTask();
  11556. return function() {
  11557. listener.task.delay(o.buffer, handler, scope, Ext.Array.toArray(arguments));
  11558. };
  11559. }
  11560. function createDelayed(handler, listener, o, scope) {
  11561. return function() {
  11562. var task = new Ext.util.DelayedTask();
  11563. if (!listener.tasks) {
  11564. listener.tasks = [];
  11565. }
  11566. listener.tasks.push(task);
  11567. task.delay(o.delay || 10, handler, scope, Ext.Array.toArray(arguments));
  11568. };
  11569. }
  11570. function createSingle(handler, listener, o, scope) {
  11571. return function() {
  11572. var event = listener.ev;
  11573. if (event.removeListener(listener.fn, scope) && event.observable) {
  11574. // Removing from a regular Observable-owned, named event (not an anonymous
  11575. // event such as Ext's readyEvent): Decrement the listeners count
  11576. event.observable.hasListeners[event.name]--;
  11577. }
  11578. return handler.apply(scope, arguments);
  11579. };
  11580. }
  11581. return {
  11582. /**
  11583. * @property {Boolean} isEvent
  11584. * `true` in this class to identify an objact as an instantiated Event, or subclass thereof.
  11585. */
  11586. isEvent: true,
  11587. constructor: function(observable, name) {
  11588. this.name = name;
  11589. this.observable = observable;
  11590. this.listeners = [];
  11591. },
  11592. addListener: function(fn, scope, options) {
  11593. var me = this,
  11594. listener;
  11595. scope = scope || me.observable;
  11596. if (!me.isListening(fn, scope)) {
  11597. listener = me.createListener(fn, scope, options);
  11598. if (me.firing) {
  11599. // if we are currently firing this event, don't disturb the listener loop
  11600. me.listeners = me.listeners.slice(0);
  11601. }
  11602. me.listeners.push(listener);
  11603. }
  11604. },
  11605. createListener: function(fn, scope, o) {
  11606. o = o || {};
  11607. scope = scope || this.observable;
  11608. var listener = {
  11609. fn: fn,
  11610. scope: scope,
  11611. o: o,
  11612. ev: this
  11613. },
  11614. handler = fn;
  11615. // The order is important. The 'single' wrapper must be wrapped by the 'buffer' and 'delayed' wrapper
  11616. // because the event removal that the single listener does destroys the listener's DelayedTask(s)
  11617. if (o.single) {
  11618. handler = createSingle(handler, listener, o, scope);
  11619. }
  11620. if (o.delay) {
  11621. handler = createDelayed(handler, listener, o, scope);
  11622. }
  11623. if (o.buffer) {
  11624. handler = createBuffered(handler, listener, o, scope);
  11625. }
  11626. listener.fireFn = handler;
  11627. return listener;
  11628. },
  11629. findListener: function(fn, scope) {
  11630. var listeners = this.listeners,
  11631. i = listeners.length,
  11632. listener,
  11633. s;
  11634. while (i--) {
  11635. listener = listeners[i];
  11636. if (listener) {
  11637. s = listener.scope;
  11638. if (listener.fn == fn && (s == scope || s == this.observable)) {
  11639. return i;
  11640. }
  11641. }
  11642. }
  11643. return - 1;
  11644. },
  11645. isListening: function(fn, scope) {
  11646. return this.findListener(fn, scope) !== -1;
  11647. },
  11648. removeListener: function(fn, scope) {
  11649. var me = this,
  11650. index,
  11651. listener,
  11652. k;
  11653. index = me.findListener(fn, scope);
  11654. if (index != -1) {
  11655. listener = me.listeners[index];
  11656. if (me.firing) {
  11657. me.listeners = me.listeners.slice(0);
  11658. }
  11659. // cancel and remove a buffered handler that hasn't fired yet
  11660. if (listener.task) {
  11661. listener.task.cancel();
  11662. delete listener.task;
  11663. }
  11664. // cancel and remove all delayed handlers that haven't fired yet
  11665. k = listener.tasks && listener.tasks.length;
  11666. if (k) {
  11667. while (k--) {
  11668. listener.tasks[k].cancel();
  11669. }
  11670. delete listener.tasks;
  11671. }
  11672. // remove this listener from the listeners array
  11673. Ext.Array.erase(me.listeners, index, 1);
  11674. return true;
  11675. }
  11676. return false;
  11677. },
  11678. // Iterate to stop any buffered/delayed events
  11679. clearListeners: function() {
  11680. var listeners = this.listeners,
  11681. i = listeners.length;
  11682. while (i--) {
  11683. this.removeListener(listeners[i].fn, listeners[i].scope);
  11684. }
  11685. },
  11686. fire: function() {
  11687. var me = this,
  11688. listeners = me.listeners,
  11689. count = listeners.length,
  11690. i,
  11691. args,
  11692. listener;
  11693. if (count > 0) {
  11694. me.firing = true;
  11695. for (i = 0; i < count; i++) {
  11696. listener = listeners[i];
  11697. args = arguments.length ? Array.prototype.slice.call(arguments, 0) : [];
  11698. if (listener.o) {
  11699. args.push(listener.o);
  11700. }
  11701. if (listener && listener.fireFn.apply(listener.scope || me.observable, args) === false) {
  11702. return (me.firing = false);
  11703. }
  11704. }
  11705. }
  11706. me.firing = false;
  11707. return true;
  11708. }
  11709. };
  11710. })());
  11711. });
  11712. /**
  11713. * @class Ext.EventManager
  11714. * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
  11715. * several useful events directly.
  11716. * See {@link Ext.EventObject} for more details on normalized event objects.
  11717. * @singleton
  11718. */
  11719. Ext.EventManager = new function() {
  11720. var EventManager = this,
  11721. doc = document,
  11722. win = window,
  11723. initExtCss = function() {
  11724. // find the body element
  11725. var bd = doc.body || doc.getElementsByTagName('body')[0],
  11726. baseCSSPrefix = Ext.baseCSSPrefix,
  11727. cls = [baseCSSPrefix + 'body'],
  11728. htmlCls = [],
  11729. html;
  11730. if (!bd) {
  11731. return false;
  11732. }
  11733. html = bd.parentNode;
  11734. function add (c) {
  11735. cls.push(baseCSSPrefix + c);
  11736. }
  11737. //Let's keep this human readable!
  11738. if (Ext.isIE) {
  11739. add('ie');
  11740. // very often CSS needs to do checks like "IE7+" or "IE6 or 7". To help
  11741. // reduce the clutter (since CSS/SCSS cannot do these tests), we add some
  11742. // additional classes:
  11743. //
  11744. // x-ie7p : IE7+ : 7 <= ieVer
  11745. // x-ie7m : IE7- : ieVer <= 7
  11746. // x-ie8p : IE8+ : 8 <= ieVer
  11747. // x-ie8m : IE8- : ieVer <= 8
  11748. // x-ie9p : IE9+ : 9 <= ieVer
  11749. // x-ie78 : IE7 or 8 : 7 <= ieVer <= 8
  11750. //
  11751. if (Ext.isIE6) {
  11752. add('ie6');
  11753. } else { // ignore pre-IE6 :)
  11754. add('ie7p');
  11755. if (Ext.isIE7) {
  11756. add('ie7');
  11757. } else {
  11758. add('ie8p');
  11759. if (Ext.isIE8) {
  11760. add('ie8');
  11761. } else {
  11762. add('ie9p');
  11763. if (Ext.isIE9) {
  11764. add('ie9');
  11765. }
  11766. }
  11767. }
  11768. }
  11769. if (Ext.isIE6 || Ext.isIE7) {
  11770. add('ie7m');
  11771. }
  11772. if (Ext.isIE6 || Ext.isIE7 || Ext.isIE8) {
  11773. add('ie8m');
  11774. }
  11775. if (Ext.isIE7 || Ext.isIE8) {
  11776. add('ie78');
  11777. }
  11778. }
  11779. if (Ext.isGecko) {
  11780. add('gecko');
  11781. if (Ext.isGecko3) {
  11782. add('gecko3');
  11783. }
  11784. if (Ext.isGecko4) {
  11785. add('gecko4');
  11786. }
  11787. if (Ext.isGecko5) {
  11788. add('gecko5');
  11789. }
  11790. }
  11791. if (Ext.isOpera) {
  11792. add('opera');
  11793. }
  11794. if (Ext.isWebKit) {
  11795. add('webkit');
  11796. }
  11797. if (Ext.isSafari) {
  11798. add('safari');
  11799. if (Ext.isSafari2) {
  11800. add('safari2');
  11801. }
  11802. if (Ext.isSafari3) {
  11803. add('safari3');
  11804. }
  11805. if (Ext.isSafari4) {
  11806. add('safari4');
  11807. }
  11808. if (Ext.isSafari5) {
  11809. add('safari5');
  11810. }
  11811. }
  11812. if (Ext.isChrome) {
  11813. add('chrome');
  11814. }
  11815. if (Ext.isMac) {
  11816. add('mac');
  11817. }
  11818. if (Ext.isLinux) {
  11819. add('linux');
  11820. }
  11821. if (!Ext.supports.CSS3BorderRadius) {
  11822. add('nbr');
  11823. }
  11824. if (!Ext.supports.CSS3LinearGradient) {
  11825. add('nlg');
  11826. }
  11827. if (!Ext.scopeResetCSS) {
  11828. add('reset');
  11829. }
  11830. // add to the parent to allow for selectors x-strict x-border-box, also set the isBorderBox property correctly
  11831. if (html) {
  11832. if (Ext.isStrict && (Ext.isIE6 || Ext.isIE7)) {
  11833. Ext.isBorderBox = false;
  11834. }
  11835. else {
  11836. Ext.isBorderBox = true;
  11837. }
  11838. if(Ext.isBorderBox) {
  11839. htmlCls.push(baseCSSPrefix + 'border-box');
  11840. }
  11841. if (Ext.isStrict) {
  11842. htmlCls.push(baseCSSPrefix + 'strict');
  11843. } else {
  11844. htmlCls.push(baseCSSPrefix + 'quirks');
  11845. }
  11846. Ext.fly(html, '_internal').addCls(htmlCls);
  11847. }
  11848. Ext.fly(bd, '_internal').addCls(cls);
  11849. return true;
  11850. };
  11851. Ext.apply(EventManager, {
  11852. /**
  11853. * Check if we have bound our global onReady listener
  11854. * @private
  11855. */
  11856. hasBoundOnReady: false,
  11857. /**
  11858. * Check if fireDocReady has been called
  11859. * @private
  11860. */
  11861. hasFiredReady: false,
  11862. /**
  11863. * Additionally, allow the 'DOM' listener thread to complete (usually desirable with mobWebkit, Gecko)
  11864. * before firing the entire onReady chain (high stack load on Loader) by specifying a delay value
  11865. * @default 1ms
  11866. * @private
  11867. */
  11868. deferReadyEvent : 1,
  11869. /*
  11870. * diags: a list of event names passed to onReadyEvent (in chron order)
  11871. * @private
  11872. */
  11873. onReadyChain : [],
  11874. /**
  11875. * Holds references to any onReady functions
  11876. * @private
  11877. */
  11878. readyEvent:
  11879. (function () {
  11880. var event = new Ext.util.Event();
  11881. event.fire = function () {
  11882. if (!/[?&]ext-pauseReadyFire\b/i.test(location.search) || Ext._continueFireReady) {
  11883. Ext._beforeReadyTime = new Date().getTime();
  11884. event.self.prototype.fire.apply(event, arguments);
  11885. Ext._afterReadytime = new Date().getTime();
  11886. }
  11887. }
  11888. return event;
  11889. })(),
  11890. /**
  11891. * Fires when a DOM event handler finishes its run, just before returning to browser control.
  11892. * This can be useful for performing cleanup, or upfdate tasks which need to happen only
  11893. * after all code in an event handler has been run, but which should not be executed in a timer
  11894. * due to the intervening browser reflow/repaint which would take place.
  11895. *
  11896. */
  11897. idleEvent: new Ext.util.Event(),
  11898. /**
  11899. * Binds the appropriate browser event for checking if the DOM has loaded.
  11900. * @private
  11901. */
  11902. bindReadyEvent: function() {
  11903. if (EventManager.hasBoundOnReady) {
  11904. return;
  11905. }
  11906. // Test scenario where Core is dynamically loaded AFTER window.load
  11907. if ( doc.readyState == 'complete' ) { // Firefox4+ got support for this state, others already do.
  11908. EventManager.onReadyEvent({
  11909. type: doc.readyState || 'body'
  11910. });
  11911. } else {
  11912. document.addEventListener('DOMContentLoaded', EventManager.onReadyEvent, false);
  11913. window.addEventListener('load', EventManager.onReadyEvent, false);
  11914. EventManager.hasBoundOnReady = true;
  11915. }
  11916. },
  11917. onReadyEvent : function(e) {
  11918. if (e && e.type) {
  11919. EventManager.onReadyChain.push(e.type);
  11920. }
  11921. if (EventManager.hasBoundOnReady) {
  11922. document.removeEventListener('DOMContentLoaded', EventManager.onReadyEvent, false);
  11923. window.removeEventListener('load', EventManager.onReadyEvent, false);
  11924. }
  11925. if (!Ext.isReady) {
  11926. EventManager.fireDocReady();
  11927. }
  11928. },
  11929. /**
  11930. * We know the document is loaded, so trigger any onReady events.
  11931. * @private
  11932. */
  11933. fireDocReady: function() {
  11934. if (!Ext.isReady) {
  11935. Ext._readyTime = new Date().getTime();
  11936. Ext.isReady = true;
  11937. Ext.supports.init();
  11938. EventManager.onWindowUnload();
  11939. EventManager.readyEvent.onReadyChain = EventManager.onReadyChain; //diags report
  11940. if (Ext.isNumber(EventManager.deferReadyEvent)) {
  11941. Ext.Function.defer(EventManager.readyEvent.fire, EventManager.deferReadyEvent, EventManager.readyEvent);
  11942. } else {
  11943. EventManager.readyEvent.fire();
  11944. }
  11945. EventManager.hasFiredReady = true;
  11946. }
  11947. },
  11948. /**
  11949. * Adds a listener to be notified when the document is ready (before onload and before images are loaded). Can be
  11950. * accessed shorthanded as Ext.onReady().
  11951. * @param {Function} fn The method the event invokes.
  11952. * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
  11953. * @param {Boolean} options (optional) Options object as passed to {@link Ext.Element#addListener}.
  11954. */
  11955. onDocumentReady: function(fn, scope, options) {
  11956. options = options || {};
  11957. var readyEvent = EventManager.readyEvent;
  11958. // force single to be true so our event is only ever fired once.
  11959. options.single = true;
  11960. readyEvent.addListener(fn, scope, options);
  11961. // Document already loaded, let's just fire it
  11962. if (Ext.isReady) {
  11963. readyEvent.fire();
  11964. } else {
  11965. EventManager.bindReadyEvent();
  11966. }
  11967. },
  11968. // --------------------- event binding ---------------------
  11969. /**
  11970. * Contains a list of all document mouse downs, so we can ensure they fire even when stopEvent is called.
  11971. * @private
  11972. */
  11973. stoppedMouseDownEvent: new Ext.util.Event(),
  11974. /**
  11975. * Options to parse for the 4th argument to addListener.
  11976. * @private
  11977. */
  11978. propRe: /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate|freezeEvent)$/,
  11979. /**
  11980. * Get the id of the element. If one has not been assigned, automatically assign it.
  11981. * @param {HTMLElement/Ext.Element} element The element to get the id for.
  11982. * @return {String} id
  11983. */
  11984. getId : function(element) {
  11985. var skipGarbageCollection = false,
  11986. id;
  11987. element = Ext.getDom(element);
  11988. if (element === doc || element === win) {
  11989. id = element === doc ? Ext.documentId : Ext.windowId;
  11990. }
  11991. else {
  11992. id = Ext.id(element);
  11993. }
  11994. // skip garbage collection for special elements (window, document, iframes)
  11995. if (element && (element.getElementById || element.navigator)) {
  11996. skipGarbageCollection = true;
  11997. }
  11998. if (!Ext.cache[id]) {
  11999. Ext.Element.addToCache(new Ext.Element(element), id);
  12000. if (skipGarbageCollection) {
  12001. Ext.cache[id].skipGarbageCollection = true;
  12002. }
  12003. }
  12004. return id;
  12005. },
  12006. /**
  12007. * Convert a "config style" listener into a set of flat arguments so they can be passed to addListener
  12008. * @private
  12009. * @param {Object} element The element the event is for
  12010. * @param {Object} event The event configuration
  12011. * @param {Object} isRemove True if a removal should be performed, otherwise an add will be done.
  12012. */
  12013. prepareListenerConfig: function(element, config, isRemove) {
  12014. var propRe = EventManager.propRe,
  12015. key, value, args;
  12016. // loop over all the keys in the object
  12017. for (key in config) {
  12018. if (config.hasOwnProperty(key)) {
  12019. // if the key is something else then an event option
  12020. if (!propRe.test(key)) {
  12021. value = config[key];
  12022. // if the value is a function it must be something like click: function() {}, scope: this
  12023. // which means that there might be multiple event listeners with shared options
  12024. if (typeof value == 'function') {
  12025. // shared options
  12026. args = [element, key, value, config.scope, config];
  12027. } else {
  12028. // if its not a function, it must be an object like click: {fn: function() {}, scope: this}
  12029. args = [element, key, value.fn, value.scope, value];
  12030. }
  12031. if (isRemove) {
  12032. EventManager.removeListener.apply(EventManager, args);
  12033. } else {
  12034. EventManager.addListener.apply(EventManager, args);
  12035. }
  12036. }
  12037. }
  12038. }
  12039. },
  12040. mouseEnterLeaveRe: /mouseenter|mouseleave/,
  12041. /**
  12042. * Normalize cross browser event differences
  12043. * @private
  12044. * @param {Object} eventName The event name
  12045. * @param {Object} fn The function to execute
  12046. * @return {Object} The new event name/function
  12047. */
  12048. normalizeEvent: function(eventName, fn) {
  12049. if (EventManager.mouseEnterLeaveRe.test(eventName) && !Ext.supports.MouseEnterLeave) {
  12050. if (fn) {
  12051. fn = Ext.Function.createInterceptor(fn, EventManager.contains);
  12052. }
  12053. eventName = eventName == 'mouseenter' ? 'mouseover' : 'mouseout';
  12054. } else if (eventName == 'mousewheel' && !Ext.supports.MouseWheel && !Ext.isOpera) {
  12055. eventName = 'DOMMouseScroll';
  12056. }
  12057. return {
  12058. eventName: eventName,
  12059. fn: fn
  12060. };
  12061. },
  12062. /**
  12063. * Checks whether the event's relatedTarget is contained inside (or <b>is</b>) the element.
  12064. * @private
  12065. * @param {Object} event
  12066. */
  12067. contains: function(event) {
  12068. var parent = event.browserEvent.currentTarget,
  12069. child = EventManager.getRelatedTarget(event);
  12070. if (parent && parent.firstChild) {
  12071. while (child) {
  12072. if (child === parent) {
  12073. return false;
  12074. }
  12075. child = child.parentNode;
  12076. if (child && (child.nodeType != 1)) {
  12077. child = null;
  12078. }
  12079. }
  12080. }
  12081. return true;
  12082. },
  12083. /**
  12084. * Appends an event handler to an element. The shorthand version {@link #on} is equivalent. Typically you will
  12085. * use {@link Ext.Element#addListener} directly on an Element in favor of calling this version.
  12086. * @param {String/HTMLElement} el The html element or id to assign the event handler to.
  12087. * @param {String} eventName The name of the event to listen for.
  12088. * @param {Function} handler The handler function the event invokes. This function is passed
  12089. * the following parameters:<ul>
  12090. * <li>evt : EventObject<div class="sub-desc">The {@link Ext.EventObject EventObject} describing the event.</div></li>
  12091. * <li>t : Element<div class="sub-desc">The {@link Ext.Element Element} which was the target of the event.
  12092. * Note that this may be filtered by using the <tt>delegate</tt> option.</div></li>
  12093. * <li>o : Object<div class="sub-desc">The options object from the addListener call.</div></li>
  12094. * </ul>
  12095. * @param {Object} scope (optional) The scope (<b><code>this</code></b> reference) in which the handler function is executed. <b>Defaults to the Element</b>.
  12096. * @param {Object} options (optional) An object containing handler configuration properties.
  12097. * This may contain any of the following properties:<ul>
  12098. * <li>scope : Object<div class="sub-desc">The scope (<b><code>this</code></b> reference) in which the handler function is executed. <b>Defaults to the Element</b>.</div></li>
  12099. * <li>delegate : String<div class="sub-desc">A simple selector to filter the target or look for a descendant of the target</div></li>
  12100. * <li>stopEvent : Boolean<div class="sub-desc">True to stop the event. That is stop propagation, and prevent the default action.</div></li>
  12101. * <li>preventDefault : Boolean<div class="sub-desc">True to prevent the default action</div></li>
  12102. * <li>stopPropagation : Boolean<div class="sub-desc">True to prevent event propagation</div></li>
  12103. * <li>normalized : Boolean<div class="sub-desc">False to pass a browser event to the handler function instead of an Ext.EventObject</div></li>
  12104. * <li>delay : Number<div class="sub-desc">The number of milliseconds to delay the invocation of the handler after te event fires.</div></li>
  12105. * <li>single : Boolean<div class="sub-desc">True to add a handler to handle just the next firing of the event, and then remove itself.</div></li>
  12106. * <li>buffer : Number<div class="sub-desc">Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed
  12107. * by the specified number of milliseconds. If the event fires again within that time, the original
  12108. * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</div></li>
  12109. * <li>target : Element<div class="sub-desc">Only call the handler if the event was fired on the target Element, <i>not</i> if the event was bubbled up from a child node.</div></li>
  12110. * </ul><br>
  12111. * <p>See {@link Ext.Element#addListener} for examples of how to use these options.</p>
  12112. */
  12113. addListener: function(element, eventName, fn, scope, options) {
  12114. // Check if we've been passed a "config style" event.
  12115. if (typeof eventName !== 'string') {
  12116. EventManager.prepareListenerConfig(element, eventName);
  12117. return;
  12118. }
  12119. var dom = element.dom || Ext.getDom(element),
  12120. bind, wrap;
  12121. // create the wrapper function
  12122. options = options || {};
  12123. bind = EventManager.normalizeEvent(eventName, fn);
  12124. wrap = EventManager.createListenerWrap(dom, eventName, bind.fn, scope, options);
  12125. if (dom.attachEvent) {
  12126. dom.attachEvent('on' + bind.eventName, wrap);
  12127. } else {
  12128. dom.addEventListener(bind.eventName, wrap, options.capture || false);
  12129. }
  12130. if (dom == doc && eventName == 'mousedown') {
  12131. EventManager.stoppedMouseDownEvent.addListener(wrap);
  12132. }
  12133. // add all required data into the event cache
  12134. EventManager.getEventListenerCache(element.dom ? element : dom, eventName).push({
  12135. fn: fn,
  12136. wrap: wrap,
  12137. scope: scope
  12138. });
  12139. },
  12140. /**
  12141. * Removes an event handler from an element. The shorthand version {@link #un} is equivalent. Typically
  12142. * you will use {@link Ext.Element#removeListener} directly on an Element in favor of calling this version.
  12143. * @param {String/HTMLElement} el The id or html element from which to remove the listener.
  12144. * @param {String} eventName The name of the event.
  12145. * @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
  12146. * @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
  12147. * then this must refer to the same object.
  12148. */
  12149. removeListener : function(element, eventName, fn, scope) {
  12150. // handle our listener config object syntax
  12151. if (typeof eventName !== 'string') {
  12152. EventManager.prepareListenerConfig(element, eventName, true);
  12153. return;
  12154. }
  12155. var dom = Ext.getDom(element),
  12156. el = element.dom ? element : Ext.get(dom),
  12157. cache = EventManager.getEventListenerCache(el, eventName),
  12158. bindName = EventManager.normalizeEvent(eventName).eventName,
  12159. i = cache.length, j,
  12160. listener, wrap, tasks;
  12161. while (i--) {
  12162. listener = cache[i];
  12163. if (listener && (!fn || listener.fn == fn) && (!scope || listener.scope === scope)) {
  12164. wrap = listener.wrap;
  12165. // clear buffered calls
  12166. if (wrap.task) {
  12167. clearTimeout(wrap.task);
  12168. delete wrap.task;
  12169. }
  12170. // clear delayed calls
  12171. j = wrap.tasks && wrap.tasks.length;
  12172. if (j) {
  12173. while (j--) {
  12174. clearTimeout(wrap.tasks[j]);
  12175. }
  12176. delete wrap.tasks;
  12177. }
  12178. if (dom.detachEvent) {
  12179. dom.detachEvent('on' + bindName, wrap);
  12180. } else {
  12181. dom.removeEventListener(bindName, wrap, false);
  12182. }
  12183. if (wrap && dom == doc && eventName == 'mousedown') {
  12184. EventManager.stoppedMouseDownEvent.removeListener(wrap);
  12185. }
  12186. // remove listener from cache
  12187. Ext.Array.erase(cache, i, 1);
  12188. }
  12189. }
  12190. },
  12191. /**
  12192. * Removes all event handers from an element. Typically you will use {@link Ext.Element#removeAllListeners}
  12193. * directly on an Element in favor of calling this version.
  12194. * @param {String/HTMLElement} el The id or html element from which to remove all event handlers.
  12195. */
  12196. removeAll : function(element) {
  12197. var el = element.dom ? element : Ext.get(element),
  12198. cache, events, eventName;
  12199. if (!el) {
  12200. return;
  12201. }
  12202. cache = (el.$cache || el.getCache());
  12203. events = cache.events;
  12204. for (eventName in events) {
  12205. if (events.hasOwnProperty(eventName)) {
  12206. EventManager.removeListener(el, eventName);
  12207. }
  12208. }
  12209. cache.events = {};
  12210. },
  12211. /**
  12212. * Recursively removes all previous added listeners from an element and its children. Typically you will use {@link Ext.Element#purgeAllListeners}
  12213. * directly on an Element in favor of calling this version.
  12214. * @param {String/HTMLElement} el The id or html element from which to remove all event handlers.
  12215. * @param {String} eventName (optional) The name of the event.
  12216. */
  12217. purgeElement : function(element, eventName) {
  12218. var dom = Ext.getDom(element),
  12219. i = 0, len;
  12220. if (eventName) {
  12221. EventManager.removeListener(element, eventName);
  12222. }
  12223. else {
  12224. EventManager.removeAll(element);
  12225. }
  12226. if (dom && dom.childNodes) {
  12227. for (len = element.childNodes.length; i < len; i++) {
  12228. EventManager.purgeElement(element.childNodes[i], eventName);
  12229. }
  12230. }
  12231. },
  12232. /**
  12233. * Create the wrapper function for the event
  12234. * @private
  12235. * @param {HTMLElement} dom The dom element
  12236. * @param {String} ename The event name
  12237. * @param {Function} fn The function to execute
  12238. * @param {Object} scope The scope to execute callback in
  12239. * @param {Object} options The options
  12240. * @return {Function} the wrapper function
  12241. */
  12242. createListenerWrap : function(dom, ename, fn, scope, options) {
  12243. options = options || {};
  12244. var f, gen, wrap = function(e, args) {
  12245. // Compile the implementation upon first firing
  12246. if (!gen) {
  12247. f = ['if(!' + Ext.name + ') {return;}'];
  12248. if(options.buffer || options.delay || options.freezeEvent) {
  12249. f.push('e = new X.EventObjectImpl(e, ' + (options.freezeEvent ? 'true' : 'false' ) + ');');
  12250. } else {
  12251. f.push('e = X.EventObject.setEvent(e);');
  12252. }
  12253. if (options.delegate) {
  12254. f.push('var t = e.getTarget("' + options.delegate + '", this);');
  12255. f.push('if(!t) {return;}');
  12256. } else {
  12257. f.push('var t = e.target;');
  12258. }
  12259. if (options.target) {
  12260. f.push('if(e.target !== options.target) {return;}');
  12261. }
  12262. if(options.stopEvent) {
  12263. f.push('e.stopEvent();');
  12264. } else {
  12265. if(options.preventDefault) {
  12266. f.push('e.preventDefault();');
  12267. }
  12268. if(options.stopPropagation) {
  12269. f.push('e.stopPropagation();');
  12270. }
  12271. }
  12272. if(options.normalized === false) {
  12273. f.push('e = e.browserEvent;');
  12274. }
  12275. if(options.buffer) {
  12276. f.push('(wrap.task && clearTimeout(wrap.task));');
  12277. f.push('wrap.task = setTimeout(function() {');
  12278. }
  12279. if(options.delay) {
  12280. f.push('wrap.tasks = wrap.tasks || [];');
  12281. f.push('wrap.tasks.push(setTimeout(function() {');
  12282. }
  12283. // finally call the actual handler fn
  12284. f.push('fn.call(scope || dom, e, t, options);');
  12285. if(options.single) {
  12286. f.push('evtMgr.removeListener(dom, ename, fn, scope);');
  12287. }
  12288. // Fire the global idle event for all events except mousemove which is too common, and
  12289. // fires too frequently and fast to be use in tiggering onIdle processing.
  12290. if (ename !== 'mousemove') {
  12291. f.push('if (evtMgr.idleEvent.listeners.length) {');
  12292. f.push('evtMgr.idleEvent.fire();');
  12293. f.push('}');
  12294. }
  12295. if(options.delay) {
  12296. f.push('}, ' + options.delay + '));');
  12297. }
  12298. if(options.buffer) {
  12299. f.push('}, ' + options.buffer + ');');
  12300. }
  12301. gen = Ext.cacheableFunctionFactory('e', 'options', 'fn', 'scope', 'ename', 'dom', 'wrap', 'args', 'X', 'evtMgr', f.join('\n'));
  12302. }
  12303. gen.call(dom, e, options, fn, scope, ename, dom, wrap, args, Ext, EventManager);
  12304. };
  12305. return wrap;
  12306. },
  12307. /**
  12308. * Get the event cache for a particular element for a particular event
  12309. * @private
  12310. * @param {HTMLElement} element The element
  12311. * @param {Object} eventName The event name
  12312. * @return {Array} The events for the element
  12313. */
  12314. getEventListenerCache : function(element, eventName) {
  12315. var elementCache, eventCache, id;
  12316. if (!element) {
  12317. return [];
  12318. }
  12319. if (element.$cache) {
  12320. elementCache = element.$cache;
  12321. } else {
  12322. elementCache = Ext.cache[id = EventManager.getId(element)] || (Ext.cache[id] = {});
  12323. }
  12324. eventCache = elementCache.events || (elementCache.events = {});
  12325. return eventCache[eventName] || (eventCache[eventName] = []);
  12326. },
  12327. // --------------------- utility methods ---------------------
  12328. mouseLeaveRe: /(mouseout|mouseleave)/,
  12329. mouseEnterRe: /(mouseover|mouseenter)/,
  12330. /**
  12331. * Stop the event (preventDefault and stopPropagation)
  12332. * @param {Event} The event to stop
  12333. */
  12334. stopEvent: function(event) {
  12335. EventManager.stopPropagation(event);
  12336. EventManager.preventDefault(event);
  12337. },
  12338. /**
  12339. * Cancels bubbling of the event.
  12340. * @param {Event} The event to stop bubbling.
  12341. */
  12342. stopPropagation: function(event) {
  12343. event = event.browserEvent || event;
  12344. if (event.stopPropagation) {
  12345. event.stopPropagation();
  12346. } else {
  12347. event.cancelBubble = true;
  12348. }
  12349. },
  12350. /**
  12351. * Prevents the browsers default handling of the event.
  12352. * @param {Event} The event to prevent the default
  12353. */
  12354. preventDefault: function(event) {
  12355. event = event.browserEvent || event;
  12356. if (event.preventDefault) {
  12357. event.preventDefault();
  12358. } else {
  12359. event.returnValue = false;
  12360. // Some keys events require setting the keyCode to -1 to be prevented
  12361. try {
  12362. // all ctrl + X and F1 -> F12
  12363. if (event.ctrlKey || event.keyCode > 111 && event.keyCode < 124) {
  12364. event.keyCode = -1;
  12365. }
  12366. } catch (e) {
  12367. // see this outdated document http://support.microsoft.com/kb/934364/en-us for more info
  12368. }
  12369. }
  12370. },
  12371. /**
  12372. * Gets the related target from the event.
  12373. * @param {Object} event The event
  12374. * @return {HTMLElement} The related target.
  12375. */
  12376. getRelatedTarget: function(event) {
  12377. event = event.browserEvent || event;
  12378. var target = event.relatedTarget;
  12379. if (!target) {
  12380. if (EventManager.mouseLeaveRe.test(event.type)) {
  12381. target = event.toElement;
  12382. } else if (EventManager.mouseEnterRe.test(event.type)) {
  12383. target = event.fromElement;
  12384. }
  12385. }
  12386. return EventManager.resolveTextNode(target);
  12387. },
  12388. /**
  12389. * Gets the x coordinate from the event
  12390. * @param {Object} event The event
  12391. * @return {Number} The x coordinate
  12392. */
  12393. getPageX: function(event) {
  12394. return EventManager.getPageXY(event)[0];
  12395. },
  12396. /**
  12397. * Gets the y coordinate from the event
  12398. * @param {Object} event The event
  12399. * @return {Number} The y coordinate
  12400. */
  12401. getPageY: function(event) {
  12402. return EventManager.getPageXY(event)[1];
  12403. },
  12404. /**
  12405. * Gets the x & y coordinate from the event
  12406. * @param {Object} event The event
  12407. * @return {Number[]} The x/y coordinate
  12408. */
  12409. getPageXY: function(event) {
  12410. event = event.browserEvent || event;
  12411. var x = event.pageX,
  12412. y = event.pageY,
  12413. docEl = doc.documentElement,
  12414. body = doc.body;
  12415. // pageX/pageY not available (undefined, not null), use clientX/clientY instead
  12416. if (!x && x !== 0) {
  12417. x = event.clientX + (docEl && docEl.scrollLeft || body && body.scrollLeft || 0) - (docEl && docEl.clientLeft || body && body.clientLeft || 0);
  12418. y = event.clientY + (docEl && docEl.scrollTop || body && body.scrollTop || 0) - (docEl && docEl.clientTop || body && body.clientTop || 0);
  12419. }
  12420. return [x, y];
  12421. },
  12422. /**
  12423. * Gets the target of the event.
  12424. * @param {Object} event The event
  12425. * @return {HTMLElement} target
  12426. */
  12427. getTarget: function(event) {
  12428. event = event.browserEvent || event;
  12429. return EventManager.resolveTextNode(event.target || event.srcElement);
  12430. },
  12431. /**
  12432. * Resolve any text nodes accounting for browser differences.
  12433. * @private
  12434. * @param {HTMLElement} node The node
  12435. * @return {HTMLElement} The resolved node
  12436. */
  12437. // technically no need to browser sniff this, however it makes no sense to check this every time, for every event, whether the string is equal.
  12438. resolveTextNode: Ext.isGecko ?
  12439. function(node) {
  12440. if (!node) {
  12441. return;
  12442. }
  12443. // work around firefox bug, https://bugzilla.mozilla.org/show_bug.cgi?id=101197
  12444. var s = HTMLElement.prototype.toString.call(node);
  12445. if (s == '[xpconnect wrapped native prototype]' || s == '[object XULElement]') {
  12446. return;
  12447. }
  12448. return node.nodeType == 3 ? node.parentNode: node;
  12449. }: function(node) {
  12450. return node && node.nodeType == 3 ? node.parentNode: node;
  12451. },
  12452. // --------------------- custom event binding ---------------------
  12453. // Keep track of the current width/height
  12454. curWidth: 0,
  12455. curHeight: 0,
  12456. /**
  12457. * Adds a listener to be notified when the browser window is resized and provides resize event buffering (100 milliseconds),
  12458. * passes new viewport width and height to handlers.
  12459. * @param {Function} fn The handler function the window resize event invokes.
  12460. * @param {Object} scope The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
  12461. * @param {Boolean} options Options object as passed to {@link Ext.Element#addListener}
  12462. */
  12463. onWindowResize: function(fn, scope, options) {
  12464. var resize = EventManager.resizeEvent;
  12465. if (!resize) {
  12466. EventManager.resizeEvent = resize = new Ext.util.Event();
  12467. EventManager.on(win, 'resize', EventManager.fireResize, null, {buffer: 100});
  12468. }
  12469. resize.addListener(fn, scope, options);
  12470. },
  12471. /**
  12472. * Fire the resize event.
  12473. * @private
  12474. */
  12475. fireResize: function() {
  12476. var w = Ext.Element.getViewWidth(),
  12477. h = Ext.Element.getViewHeight();
  12478. //whacky problem in IE where the resize event will sometimes fire even though the w/h are the same.
  12479. if (EventManager.curHeight != h || EventManager.curWidth != w) {
  12480. EventManager.curHeight = h;
  12481. EventManager.curWidth = w;
  12482. EventManager.resizeEvent.fire(w, h);
  12483. }
  12484. },
  12485. /**
  12486. * Removes the passed window resize listener.
  12487. * @param {Function} fn The method the event invokes
  12488. * @param {Object} scope The scope of handler
  12489. */
  12490. removeResizeListener: function(fn, scope) {
  12491. var resize = EventManager.resizeEvent;
  12492. if (resize) {
  12493. resize.removeListener(fn, scope);
  12494. }
  12495. },
  12496. /**
  12497. * Adds a listener to be notified when the browser window is unloaded.
  12498. * @param {Function} fn The handler function the window unload event invokes.
  12499. * @param {Object} scope The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
  12500. * @param {Boolean} options Options object as passed to {@link Ext.Element#addListener}
  12501. */
  12502. onWindowUnload: function(fn, scope, options) {
  12503. var unload = EventManager.unloadEvent;
  12504. if (!unload) {
  12505. EventManager.unloadEvent = unload = new Ext.util.Event();
  12506. EventManager.addListener(win, 'unload', EventManager.fireUnload);
  12507. }
  12508. if (fn) {
  12509. unload.addListener(fn, scope, options);
  12510. }
  12511. },
  12512. /**
  12513. * Fires the unload event for items bound with onWindowUnload
  12514. * @private
  12515. */
  12516. fireUnload: function() {
  12517. // wrap in a try catch, could have some problems during unload
  12518. try {
  12519. // relinquish references.
  12520. doc = win = undefined;
  12521. EventManager.unloadEvent.fire();
  12522. // Work around FF3 remembering the last scroll position when refreshing the grid and then losing grid view
  12523. if (Ext.isGecko3) {
  12524. var gridviews = Ext.ComponentQuery.query('gridview'),
  12525. i = 0,
  12526. ln = gridviews.length;
  12527. for (; i < ln; i++) {
  12528. gridviews[i].scrollToTop();
  12529. }
  12530. }
  12531. // Purge all elements in the cache
  12532. var el,
  12533. cache = Ext.cache;
  12534. for (el in cache) {
  12535. if (cache.hasOwnProperty(el)) {
  12536. EventManager.removeAll(el);
  12537. }
  12538. }
  12539. } catch(e) {
  12540. }
  12541. },
  12542. /**
  12543. * Removes the passed window unload listener.
  12544. * @param {Function} fn The method the event invokes
  12545. * @param {Object} scope The scope of handler
  12546. */
  12547. removeUnloadListener: function(fn, scope) {
  12548. var unload = EventManager.unloadEvent;
  12549. if (unload) {
  12550. unload.removeListener(fn, scope);
  12551. }
  12552. },
  12553. /**
  12554. * note 1: IE fires ONLY the keydown event on specialkey autorepeat
  12555. * note 2: Safari < 3.1, Gecko (Mac/Linux) & Opera fire only the keypress event on specialkey autorepeat
  12556. * (research done by Jan Wolter at http://unixpapa.com/js/key.html)
  12557. * @private
  12558. */
  12559. useKeyDown: Ext.isWebKit ?
  12560. parseInt(navigator.userAgent.match(/AppleWebKit\/(\d+)/)[1], 10) >= 525 :
  12561. !((Ext.isGecko && !Ext.isWindows) || Ext.isOpera),
  12562. /**
  12563. * Indicates which event to use for getting key presses.
  12564. * @return {String} The appropriate event name.
  12565. */
  12566. getKeyEvent: function() {
  12567. return EventManager.useKeyDown ? 'keydown' : 'keypress';
  12568. }
  12569. });
  12570. // route "< ie9-Standards" to a legacy IE onReady implementation
  12571. if(!('addEventListener' in document) && document.attachEvent) {
  12572. Ext.apply( EventManager, {
  12573. /* Customized implementation for Legacy IE. The default implementation is configured for use
  12574. * with all other 'standards compliant' agents.
  12575. * References: http://javascript.nwbox.com/IEContentLoaded/
  12576. * licensed courtesy of http://developer.yahoo.com/yui/license.html
  12577. */
  12578. /**
  12579. * This strategy has minimal benefits for Sencha solutions that build themselves (ie. minimal initial page markup).
  12580. * However, progressively-enhanced pages (with image content and/or embedded frames) will benefit the most from it.
  12581. * Browser timer resolution is too poor to ensure a doScroll check more than once on a page loaded with minimal
  12582. * assets (the readystatechange event 'complete' usually beats the doScroll timer on a 'lightly-loaded' initial document).
  12583. */
  12584. pollScroll : function() {
  12585. var scrollable = true;
  12586. try {
  12587. document.documentElement.doScroll('left');
  12588. } catch(e) {
  12589. scrollable = false;
  12590. }
  12591. if (scrollable) {
  12592. EventManager.onReadyEvent({
  12593. type:'doScroll'
  12594. });
  12595. } else {
  12596. /*
  12597. * minimize thrashing --
  12598. * adjusted for setTimeout's close-to-minimums (not too low),
  12599. * as this method SHOULD always be called once initially
  12600. */
  12601. EventManager.scrollTimeout = setTimeout(EventManager.pollScroll, 20);
  12602. }
  12603. return scrollable;
  12604. },
  12605. /**
  12606. * Timer for doScroll polling
  12607. * @private
  12608. */
  12609. scrollTimeout: null,
  12610. /* @private
  12611. */
  12612. readyStatesRe : /complete/i,
  12613. /* @private
  12614. */
  12615. checkReadyState: function() {
  12616. var state = document.readyState;
  12617. if (EventManager.readyStatesRe.test(state)) {
  12618. EventManager.onReadyEvent({
  12619. type: state
  12620. });
  12621. }
  12622. },
  12623. bindReadyEvent: function() {
  12624. var topContext = true;
  12625. if (EventManager.hasBoundOnReady) {
  12626. return;
  12627. }
  12628. //are we in an IFRAME? (doScroll ineffective here)
  12629. try {
  12630. topContext = !window.frameElement;
  12631. } catch(e) {
  12632. }
  12633. if (!topContext || !doc.documentElement.doScroll) {
  12634. EventManager.pollScroll = Ext.emptyFn; //then noop this test altogether
  12635. }
  12636. // starts doScroll polling if necessary
  12637. if (EventManager.pollScroll() === true) {
  12638. return;
  12639. }
  12640. // Core is loaded AFTER initial document write/load ?
  12641. if (doc.readyState == 'complete' ) {
  12642. EventManager.onReadyEvent({type: 'already ' + (doc.readyState || 'body') });
  12643. } else {
  12644. doc.attachEvent('onreadystatechange', EventManager.checkReadyState);
  12645. window.attachEvent('onload', EventManager.onReadyEvent);
  12646. EventManager.hasBoundOnReady = true;
  12647. }
  12648. },
  12649. onReadyEvent : function(e) {
  12650. if (e && e.type) {
  12651. EventManager.onReadyChain.push(e.type);
  12652. }
  12653. if (EventManager.hasBoundOnReady) {
  12654. document.detachEvent('onreadystatechange', EventManager.checkReadyState);
  12655. window.detachEvent('onload', EventManager.onReadyEvent);
  12656. }
  12657. if (Ext.isNumber(EventManager.scrollTimeout)) {
  12658. clearTimeout(EventManager.scrollTimeout);
  12659. delete EventManager.scrollTimeout;
  12660. }
  12661. if (!Ext.isReady) {
  12662. EventManager.fireDocReady();
  12663. }
  12664. },
  12665. //diags: a list of event types passed to onReadyEvent (in chron order)
  12666. onReadyChain : []
  12667. });
  12668. }
  12669. /**
  12670. * Alias for {@link Ext.Loader#onReady Ext.Loader.onReady} with withDomReady set to true
  12671. * @member Ext
  12672. * @method onReady
  12673. */
  12674. Ext.onReady = function(fn, scope, options) {
  12675. Ext.Loader.onReady(fn, scope, true, options);
  12676. };
  12677. /**
  12678. * Alias for {@link Ext.EventManager#onDocumentReady Ext.EventManager.onDocumentReady}
  12679. * @member Ext
  12680. * @method onDocumentReady
  12681. */
  12682. Ext.onDocumentReady = EventManager.onDocumentReady;
  12683. /**
  12684. * Alias for {@link Ext.EventManager#addListener Ext.EventManager.addListener}
  12685. * @member Ext.EventManager
  12686. * @method on
  12687. */
  12688. EventManager.on = EventManager.addListener;
  12689. /**
  12690. * Alias for {@link Ext.EventManager#removeListener Ext.EventManager.removeListener}
  12691. * @member Ext.EventManager
  12692. * @method un
  12693. */
  12694. EventManager.un = EventManager.removeListener;
  12695. Ext.onReady(initExtCss);
  12696. };
  12697. /**
  12698. * @class Ext.EventObject
  12699. Just as {@link Ext.Element} wraps around a native DOM node, Ext.EventObject
  12700. wraps the browser's native event-object normalizing cross-browser differences,
  12701. such as which mouse button is clicked, keys pressed, mechanisms to stop
  12702. event-propagation along with a method to prevent default actions from taking place.
  12703. For example:
  12704. function handleClick(e, t){ // e is not a standard event object, it is a Ext.EventObject
  12705. e.preventDefault();
  12706. var target = e.getTarget(); // same as t (the target HTMLElement)
  12707. ...
  12708. }
  12709. var myDiv = {@link Ext#get Ext.get}("myDiv"); // get reference to an {@link Ext.Element}
  12710. myDiv.on( // 'on' is shorthand for addListener
  12711. "click", // perform an action on click of myDiv
  12712. handleClick // reference to the action handler
  12713. );
  12714. // other methods to do the same:
  12715. Ext.EventManager.on("myDiv", 'click', handleClick);
  12716. Ext.EventManager.addListener("myDiv", 'click', handleClick);
  12717. * @singleton
  12718. * @markdown
  12719. */
  12720. Ext.define('Ext.EventObjectImpl', {
  12721. uses: ['Ext.util.Point'],
  12722. /** Key constant @type Number */
  12723. BACKSPACE: 8,
  12724. /** Key constant @type Number */
  12725. TAB: 9,
  12726. /** Key constant @type Number */
  12727. NUM_CENTER: 12,
  12728. /** Key constant @type Number */
  12729. ENTER: 13,
  12730. /** Key constant @type Number */
  12731. RETURN: 13,
  12732. /** Key constant @type Number */
  12733. SHIFT: 16,
  12734. /** Key constant @type Number */
  12735. CTRL: 17,
  12736. /** Key constant @type Number */
  12737. ALT: 18,
  12738. /** Key constant @type Number */
  12739. PAUSE: 19,
  12740. /** Key constant @type Number */
  12741. CAPS_LOCK: 20,
  12742. /** Key constant @type Number */
  12743. ESC: 27,
  12744. /** Key constant @type Number */
  12745. SPACE: 32,
  12746. /** Key constant @type Number */
  12747. PAGE_UP: 33,
  12748. /** Key constant @type Number */
  12749. PAGE_DOWN: 34,
  12750. /** Key constant @type Number */
  12751. END: 35,
  12752. /** Key constant @type Number */
  12753. HOME: 36,
  12754. /** Key constant @type Number */
  12755. LEFT: 37,
  12756. /** Key constant @type Number */
  12757. UP: 38,
  12758. /** Key constant @type Number */
  12759. RIGHT: 39,
  12760. /** Key constant @type Number */
  12761. DOWN: 40,
  12762. /** Key constant @type Number */
  12763. PRINT_SCREEN: 44,
  12764. /** Key constant @type Number */
  12765. INSERT: 45,
  12766. /** Key constant @type Number */
  12767. DELETE: 46,
  12768. /** Key constant @type Number */
  12769. ZERO: 48,
  12770. /** Key constant @type Number */
  12771. ONE: 49,
  12772. /** Key constant @type Number */
  12773. TWO: 50,
  12774. /** Key constant @type Number */
  12775. THREE: 51,
  12776. /** Key constant @type Number */
  12777. FOUR: 52,
  12778. /** Key constant @type Number */
  12779. FIVE: 53,
  12780. /** Key constant @type Number */
  12781. SIX: 54,
  12782. /** Key constant @type Number */
  12783. SEVEN: 55,
  12784. /** Key constant @type Number */
  12785. EIGHT: 56,
  12786. /** Key constant @type Number */
  12787. NINE: 57,
  12788. /** Key constant @type Number */
  12789. A: 65,
  12790. /** Key constant @type Number */
  12791. B: 66,
  12792. /** Key constant @type Number */
  12793. C: 67,
  12794. /** Key constant @type Number */
  12795. D: 68,
  12796. /** Key constant @type Number */
  12797. E: 69,
  12798. /** Key constant @type Number */
  12799. F: 70,
  12800. /** Key constant @type Number */
  12801. G: 71,
  12802. /** Key constant @type Number */
  12803. H: 72,
  12804. /** Key constant @type Number */
  12805. I: 73,
  12806. /** Key constant @type Number */
  12807. J: 74,
  12808. /** Key constant @type Number */
  12809. K: 75,
  12810. /** Key constant @type Number */
  12811. L: 76,
  12812. /** Key constant @type Number */
  12813. M: 77,
  12814. /** Key constant @type Number */
  12815. N: 78,
  12816. /** Key constant @type Number */
  12817. O: 79,
  12818. /** Key constant @type Number */
  12819. P: 80,
  12820. /** Key constant @type Number */
  12821. Q: 81,
  12822. /** Key constant @type Number */
  12823. R: 82,
  12824. /** Key constant @type Number */
  12825. S: 83,
  12826. /** Key constant @type Number */
  12827. T: 84,
  12828. /** Key constant @type Number */
  12829. U: 85,
  12830. /** Key constant @type Number */
  12831. V: 86,
  12832. /** Key constant @type Number */
  12833. W: 87,
  12834. /** Key constant @type Number */
  12835. X: 88,
  12836. /** Key constant @type Number */
  12837. Y: 89,
  12838. /** Key constant @type Number */
  12839. Z: 90,
  12840. /** Key constant @type Number */
  12841. CONTEXT_MENU: 93,
  12842. /** Key constant @type Number */
  12843. NUM_ZERO: 96,
  12844. /** Key constant @type Number */
  12845. NUM_ONE: 97,
  12846. /** Key constant @type Number */
  12847. NUM_TWO: 98,
  12848. /** Key constant @type Number */
  12849. NUM_THREE: 99,
  12850. /** Key constant @type Number */
  12851. NUM_FOUR: 100,
  12852. /** Key constant @type Number */
  12853. NUM_FIVE: 101,
  12854. /** Key constant @type Number */
  12855. NUM_SIX: 102,
  12856. /** Key constant @type Number */
  12857. NUM_SEVEN: 103,
  12858. /** Key constant @type Number */
  12859. NUM_EIGHT: 104,
  12860. /** Key constant @type Number */
  12861. NUM_NINE: 105,
  12862. /** Key constant @type Number */
  12863. NUM_MULTIPLY: 106,
  12864. /** Key constant @type Number */
  12865. NUM_PLUS: 107,
  12866. /** Key constant @type Number */
  12867. NUM_MINUS: 109,
  12868. /** Key constant @type Number */
  12869. NUM_PERIOD: 110,
  12870. /** Key constant @type Number */
  12871. NUM_DIVISION: 111,
  12872. /** Key constant @type Number */
  12873. F1: 112,
  12874. /** Key constant @type Number */
  12875. F2: 113,
  12876. /** Key constant @type Number */
  12877. F3: 114,
  12878. /** Key constant @type Number */
  12879. F4: 115,
  12880. /** Key constant @type Number */
  12881. F5: 116,
  12882. /** Key constant @type Number */
  12883. F6: 117,
  12884. /** Key constant @type Number */
  12885. F7: 118,
  12886. /** Key constant @type Number */
  12887. F8: 119,
  12888. /** Key constant @type Number */
  12889. F9: 120,
  12890. /** Key constant @type Number */
  12891. F10: 121,
  12892. /** Key constant @type Number */
  12893. F11: 122,
  12894. /** Key constant @type Number */
  12895. F12: 123,
  12896. /**
  12897. * The mouse wheel delta scaling factor. This value depends on browser version and OS and
  12898. * attempts to produce a similar scrolling experience across all platforms and browsers.
  12899. *
  12900. * To change this value:
  12901. *
  12902. * Ext.EventObjectImpl.prototype.WHEEL_SCALE = 72;
  12903. *
  12904. * @type Number
  12905. * @markdown
  12906. */
  12907. WHEEL_SCALE: (function () {
  12908. var scale;
  12909. if (Ext.isGecko) {
  12910. // Firefox uses 3 on all platforms
  12911. scale = 3;
  12912. } else if (Ext.isMac) {
  12913. // Continuous scrolling devices have momentum and produce much more scroll than
  12914. // discrete devices on the same OS and browser. To make things exciting, Safari
  12915. // (and not Chrome) changed from small values to 120 (like IE).
  12916. if (Ext.isSafari && Ext.webKitVersion >= 532.0) {
  12917. // Safari changed the scrolling factor to match IE (for details see
  12918. // https://bugs.webkit.org/show_bug.cgi?id=24368). The WebKit version where this
  12919. // change was introduced was 532.0
  12920. // Detailed discussion:
  12921. // https://bugs.webkit.org/show_bug.cgi?id=29601
  12922. // http://trac.webkit.org/browser/trunk/WebKit/chromium/src/mac/WebInputEventFactory.mm#L1063
  12923. scale = 120;
  12924. } else {
  12925. // MS optical wheel mouse produces multiples of 12 which is close enough
  12926. // to help tame the speed of the continuous mice...
  12927. scale = 12;
  12928. }
  12929. // Momentum scrolling produces very fast scrolling, so increase the scale factor
  12930. // to help produce similar results cross platform. This could be even larger and
  12931. // it would help those mice, but other mice would become almost unusable as a
  12932. // result (since we cannot tell which device type is in use).
  12933. scale *= 3;
  12934. } else {
  12935. // IE, Opera and other Windows browsers use 120.
  12936. scale = 120;
  12937. }
  12938. return scale;
  12939. })(),
  12940. /**
  12941. * Simple click regex
  12942. * @private
  12943. */
  12944. clickRe: /(dbl)?click/,
  12945. // safari keypress events for special keys return bad keycodes
  12946. safariKeys: {
  12947. 3: 13, // enter
  12948. 63234: 37, // left
  12949. 63235: 39, // right
  12950. 63232: 38, // up
  12951. 63233: 40, // down
  12952. 63276: 33, // page up
  12953. 63277: 34, // page down
  12954. 63272: 46, // delete
  12955. 63273: 36, // home
  12956. 63275: 35 // end
  12957. },
  12958. // normalize button clicks, don't see any way to feature detect this.
  12959. btnMap: Ext.isIE ? {
  12960. 1: 0,
  12961. 4: 1,
  12962. 2: 2
  12963. } : {
  12964. 0: 0,
  12965. 1: 1,
  12966. 2: 2
  12967. },
  12968. /**
  12969. * @property {Boolean} ctrlKey
  12970. * True if the control key was down during the event.
  12971. * In Mac this will also be true when meta key was down.
  12972. */
  12973. /**
  12974. * @property {Boolean} altKey
  12975. * True if the alt key was down during the event.
  12976. */
  12977. /**
  12978. * @property {Boolean} shiftKey
  12979. * True if the shift key was down during the event.
  12980. */
  12981. constructor: function(event, freezeEvent){
  12982. if (event) {
  12983. this.setEvent(event.browserEvent || event, freezeEvent);
  12984. }
  12985. },
  12986. setEvent: function(event, freezeEvent){
  12987. var me = this, button, options;
  12988. if (event == me || (event && event.browserEvent)) { // already wrapped
  12989. return event;
  12990. }
  12991. me.browserEvent = event;
  12992. if (event) {
  12993. // normalize buttons
  12994. button = event.button ? me.btnMap[event.button] : (event.which ? event.which - 1 : -1);
  12995. if (me.clickRe.test(event.type) && button == -1) {
  12996. button = 0;
  12997. }
  12998. options = {
  12999. type: event.type,
  13000. button: button,
  13001. shiftKey: event.shiftKey,
  13002. // mac metaKey behaves like ctrlKey
  13003. ctrlKey: event.ctrlKey || event.metaKey || false,
  13004. altKey: event.altKey,
  13005. // in getKey these will be normalized for the mac
  13006. keyCode: event.keyCode,
  13007. charCode: event.charCode,
  13008. // cache the targets for the delayed and or buffered events
  13009. target: Ext.EventManager.getTarget(event),
  13010. relatedTarget: Ext.EventManager.getRelatedTarget(event),
  13011. currentTarget: event.currentTarget,
  13012. xy: (freezeEvent ? me.getXY() : null)
  13013. };
  13014. } else {
  13015. options = {
  13016. button: -1,
  13017. shiftKey: false,
  13018. ctrlKey: false,
  13019. altKey: false,
  13020. keyCode: 0,
  13021. charCode: 0,
  13022. target: null,
  13023. xy: [0, 0]
  13024. };
  13025. }
  13026. Ext.apply(me, options);
  13027. return me;
  13028. },
  13029. /**
  13030. * Stop the event (preventDefault and stopPropagation)
  13031. */
  13032. stopEvent: function(){
  13033. this.stopPropagation();
  13034. this.preventDefault();
  13035. },
  13036. /**
  13037. * Prevents the browsers default handling of the event.
  13038. */
  13039. preventDefault: function(){
  13040. if (this.browserEvent) {
  13041. Ext.EventManager.preventDefault(this.browserEvent);
  13042. }
  13043. },
  13044. /**
  13045. * Cancels bubbling of the event.
  13046. */
  13047. stopPropagation: function(){
  13048. var browserEvent = this.browserEvent;
  13049. if (browserEvent) {
  13050. if (browserEvent.type == 'mousedown') {
  13051. Ext.EventManager.stoppedMouseDownEvent.fire(this);
  13052. }
  13053. Ext.EventManager.stopPropagation(browserEvent);
  13054. }
  13055. },
  13056. /**
  13057. * Gets the character code for the event.
  13058. * @return {Number}
  13059. */
  13060. getCharCode: function(){
  13061. return this.charCode || this.keyCode;
  13062. },
  13063. /**
  13064. * Returns a normalized keyCode for the event.
  13065. * @return {Number} The key code
  13066. */
  13067. getKey: function(){
  13068. return this.normalizeKey(this.keyCode || this.charCode);
  13069. },
  13070. /**
  13071. * Normalize key codes across browsers
  13072. * @private
  13073. * @param {Number} key The key code
  13074. * @return {Number} The normalized code
  13075. */
  13076. normalizeKey: function(key){
  13077. // can't feature detect this
  13078. return Ext.isWebKit ? (this.safariKeys[key] || key) : key;
  13079. },
  13080. /**
  13081. * Gets the x coordinate of the event.
  13082. * @return {Number}
  13083. * @deprecated 4.0 Replaced by {@link #getX}
  13084. */
  13085. getPageX: function(){
  13086. return this.getX();
  13087. },
  13088. /**
  13089. * Gets the y coordinate of the event.
  13090. * @return {Number}
  13091. * @deprecated 4.0 Replaced by {@link #getY}
  13092. */
  13093. getPageY: function(){
  13094. return this.getY();
  13095. },
  13096. /**
  13097. * Gets the x coordinate of the event.
  13098. * @return {Number}
  13099. */
  13100. getX: function() {
  13101. return this.getXY()[0];
  13102. },
  13103. /**
  13104. * Gets the y coordinate of the event.
  13105. * @return {Number}
  13106. */
  13107. getY: function() {
  13108. return this.getXY()[1];
  13109. },
  13110. /**
  13111. * Gets the page coordinates of the event.
  13112. * @return {Number[]} The xy values like [x, y]
  13113. */
  13114. getXY: function() {
  13115. if (!this.xy) {
  13116. // same for XY
  13117. this.xy = Ext.EventManager.getPageXY(this.browserEvent);
  13118. }
  13119. return this.xy;
  13120. },
  13121. /**
  13122. * Gets the target for the event.
  13123. * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
  13124. * @param {Number/HTMLElement} maxDepth (optional) The max depth to search as a number or element (defaults to 10 || document.body)
  13125. * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
  13126. * @return {HTMLElement}
  13127. */
  13128. getTarget : function(selector, maxDepth, returnEl){
  13129. if (selector) {
  13130. return Ext.fly(this.target).findParent(selector, maxDepth, returnEl);
  13131. }
  13132. return returnEl ? Ext.get(this.target) : this.target;
  13133. },
  13134. /**
  13135. * Gets the related target.
  13136. * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
  13137. * @param {Number/HTMLElement} maxDepth (optional) The max depth to search as a number or element (defaults to 10 || document.body)
  13138. * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
  13139. * @return {HTMLElement}
  13140. */
  13141. getRelatedTarget : function(selector, maxDepth, returnEl){
  13142. if (selector) {
  13143. return Ext.fly(this.relatedTarget).findParent(selector, maxDepth, returnEl);
  13144. }
  13145. return returnEl ? Ext.get(this.relatedTarget) : this.relatedTarget;
  13146. },
  13147. /**
  13148. * Correctly scales a given wheel delta.
  13149. * @param {Number} delta The delta value.
  13150. */
  13151. correctWheelDelta : function (delta) {
  13152. var scale = this.WHEEL_SCALE,
  13153. ret = Math.round(delta / scale);
  13154. if (!ret && delta) {
  13155. ret = (delta < 0) ? -1 : 1; // don't allow non-zero deltas to go to zero!
  13156. }
  13157. return ret;
  13158. },
  13159. /**
  13160. * Returns the mouse wheel deltas for this event.
  13161. * @return {Object} An object with "x" and "y" properties holding the mouse wheel deltas.
  13162. */
  13163. getWheelDeltas : function () {
  13164. var me = this,
  13165. event = me.browserEvent,
  13166. dx = 0, dy = 0; // the deltas
  13167. if (Ext.isDefined(event.wheelDeltaX)) { // WebKit has both dimensions
  13168. dx = event.wheelDeltaX;
  13169. dy = event.wheelDeltaY;
  13170. } else if (event.wheelDelta) { // old WebKit and IE
  13171. dy = event.wheelDelta;
  13172. } else if (event.detail) { // Gecko
  13173. dy = -event.detail; // gecko is backwards
  13174. // Gecko sometimes returns really big values if the user changes settings to
  13175. // scroll a whole page per scroll
  13176. if (dy > 100) {
  13177. dy = 3;
  13178. } else if (dy < -100) {
  13179. dy = -3;
  13180. }
  13181. // Firefox 3.1 adds an axis field to the event to indicate direction of
  13182. // scroll. See https://developer.mozilla.org/en/Gecko-Specific_DOM_Events
  13183. if (Ext.isDefined(event.axis) && event.axis === event.HORIZONTAL_AXIS) {
  13184. dx = dy;
  13185. dy = 0;
  13186. }
  13187. }
  13188. return {
  13189. x: me.correctWheelDelta(dx),
  13190. y: me.correctWheelDelta(dy)
  13191. };
  13192. },
  13193. /**
  13194. * Normalizes mouse wheel y-delta across browsers. To get x-delta information, use
  13195. * {@link #getWheelDeltas} instead.
  13196. * @return {Number} The mouse wheel y-delta
  13197. */
  13198. getWheelDelta : function(){
  13199. var deltas = this.getWheelDeltas();
  13200. return deltas.y;
  13201. },
  13202. /**
  13203. * Returns true if the target of this event is a child of el. Unless the allowEl parameter is set, it will return false if if the target is el.
  13204. * Example usage:<pre><code>
  13205. // Handle click on any child of an element
  13206. Ext.getBody().on('click', function(e){
  13207. if(e.within('some-el')){
  13208. alert('Clicked on a child of some-el!');
  13209. }
  13210. });
  13211. // Handle click directly on an element, ignoring clicks on child nodes
  13212. Ext.getBody().on('click', function(e,t){
  13213. if((t.id == 'some-el') && !e.within(t, true)){
  13214. alert('Clicked directly on some-el!');
  13215. }
  13216. });
  13217. </code></pre>
  13218. * @param {String/HTMLElement/Ext.Element} el The id, DOM element or Ext.Element to check
  13219. * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
  13220. * @param {Boolean} allowEl (optional) true to also check if the passed element is the target or related target
  13221. * @return {Boolean}
  13222. */
  13223. within : function(el, related, allowEl){
  13224. if(el){
  13225. var t = related ? this.getRelatedTarget() : this.getTarget(),
  13226. result;
  13227. if (t) {
  13228. result = Ext.fly(el).contains(t);
  13229. if (!result && allowEl) {
  13230. result = t == Ext.getDom(el);
  13231. }
  13232. return result;
  13233. }
  13234. }
  13235. return false;
  13236. },
  13237. /**
  13238. * Checks if the key pressed was a "navigation" key
  13239. * @return {Boolean} True if the press is a navigation keypress
  13240. */
  13241. isNavKeyPress : function(){
  13242. var me = this,
  13243. k = this.normalizeKey(me.keyCode);
  13244. return (k >= 33 && k <= 40) || // Page Up/Down, End, Home, Left, Up, Right, Down
  13245. k == me.RETURN ||
  13246. k == me.TAB ||
  13247. k == me.ESC;
  13248. },
  13249. /**
  13250. * Checks if the key pressed was a "special" key
  13251. * @return {Boolean} True if the press is a special keypress
  13252. */
  13253. isSpecialKey : function(){
  13254. var k = this.normalizeKey(this.keyCode);
  13255. return (this.type == 'keypress' && this.ctrlKey) ||
  13256. this.isNavKeyPress() ||
  13257. (k == this.BACKSPACE) || // Backspace
  13258. (k >= 16 && k <= 20) || // Shift, Ctrl, Alt, Pause, Caps Lock
  13259. (k >= 44 && k <= 46); // Print Screen, Insert, Delete
  13260. },
  13261. /**
  13262. * Returns a point object that consists of the object coordinates.
  13263. * @return {Ext.util.Point} point
  13264. */
  13265. getPoint : function(){
  13266. var xy = this.getXY();
  13267. return new Ext.util.Point(xy[0], xy[1]);
  13268. },
  13269. /**
  13270. * Returns true if the control, meta, shift or alt key was pressed during this event.
  13271. * @return {Boolean}
  13272. */
  13273. hasModifier : function(){
  13274. return this.ctrlKey || this.altKey || this.shiftKey || this.metaKey;
  13275. },
  13276. /**
  13277. * Injects a DOM event using the data in this object and (optionally) a new target.
  13278. * This is a low-level technique and not likely to be used by application code. The
  13279. * currently supported event types are:
  13280. * <p><b>HTMLEvents</b></p>
  13281. * <ul>
  13282. * <li>load</li>
  13283. * <li>unload</li>
  13284. * <li>select</li>
  13285. * <li>change</li>
  13286. * <li>submit</li>
  13287. * <li>reset</li>
  13288. * <li>resize</li>
  13289. * <li>scroll</li>
  13290. * </ul>
  13291. * <p><b>MouseEvents</b></p>
  13292. * <ul>
  13293. * <li>click</li>
  13294. * <li>dblclick</li>
  13295. * <li>mousedown</li>
  13296. * <li>mouseup</li>
  13297. * <li>mouseover</li>
  13298. * <li>mousemove</li>
  13299. * <li>mouseout</li>
  13300. * </ul>
  13301. * <p><b>UIEvents</b></p>
  13302. * <ul>
  13303. * <li>focusin</li>
  13304. * <li>focusout</li>
  13305. * <li>activate</li>
  13306. * <li>focus</li>
  13307. * <li>blur</li>
  13308. * </ul>
  13309. * @param {Ext.Element/HTMLElement} target (optional) If specified, the target for the event. This
  13310. * is likely to be used when relaying a DOM event. If not specified, {@link #getTarget}
  13311. * is used to determine the target.
  13312. */
  13313. injectEvent: function () {
  13314. var API,
  13315. dispatchers = {}; // keyed by event type (e.g., 'mousedown')
  13316. // Good reference: http://developer.yahoo.com/yui/docs/UserAction.js.html
  13317. // IE9 has createEvent, but this code causes major problems with htmleditor (it
  13318. // blocks all mouse events and maybe more). TODO
  13319. if (!Ext.isIE && document.createEvent) { // if (DOM compliant)
  13320. API = {
  13321. createHtmlEvent: function (doc, type, bubbles, cancelable) {
  13322. var event = doc.createEvent('HTMLEvents');
  13323. event.initEvent(type, bubbles, cancelable);
  13324. return event;
  13325. },
  13326. createMouseEvent: function (doc, type, bubbles, cancelable, detail,
  13327. clientX, clientY, ctrlKey, altKey, shiftKey, metaKey,
  13328. button, relatedTarget) {
  13329. var event = doc.createEvent('MouseEvents'),
  13330. view = doc.defaultView || window;
  13331. if (event.initMouseEvent) {
  13332. event.initMouseEvent(type, bubbles, cancelable, view, detail,
  13333. clientX, clientY, clientX, clientY, ctrlKey, altKey,
  13334. shiftKey, metaKey, button, relatedTarget);
  13335. } else { // old Safari
  13336. event = doc.createEvent('UIEvents');
  13337. event.initEvent(type, bubbles, cancelable);
  13338. event.view = view;
  13339. event.detail = detail;
  13340. event.screenX = clientX;
  13341. event.screenY = clientY;
  13342. event.clientX = clientX;
  13343. event.clientY = clientY;
  13344. event.ctrlKey = ctrlKey;
  13345. event.altKey = altKey;
  13346. event.metaKey = metaKey;
  13347. event.shiftKey = shiftKey;
  13348. event.button = button;
  13349. event.relatedTarget = relatedTarget;
  13350. }
  13351. return event;
  13352. },
  13353. createUIEvent: function (doc, type, bubbles, cancelable, detail) {
  13354. var event = doc.createEvent('UIEvents'),
  13355. view = doc.defaultView || window;
  13356. event.initUIEvent(type, bubbles, cancelable, view, detail);
  13357. return event;
  13358. },
  13359. fireEvent: function (target, type, event) {
  13360. target.dispatchEvent(event);
  13361. },
  13362. fixTarget: function (target) {
  13363. // Safari3 doesn't have window.dispatchEvent()
  13364. if (target == window && !target.dispatchEvent) {
  13365. return document;
  13366. }
  13367. return target;
  13368. }
  13369. };
  13370. } else if (document.createEventObject) { // else if (IE)
  13371. var crazyIEButtons = { 0: 1, 1: 4, 2: 2 };
  13372. API = {
  13373. createHtmlEvent: function (doc, type, bubbles, cancelable) {
  13374. var event = doc.createEventObject();
  13375. event.bubbles = bubbles;
  13376. event.cancelable = cancelable;
  13377. return event;
  13378. },
  13379. createMouseEvent: function (doc, type, bubbles, cancelable, detail,
  13380. clientX, clientY, ctrlKey, altKey, shiftKey, metaKey,
  13381. button, relatedTarget) {
  13382. var event = doc.createEventObject();
  13383. event.bubbles = bubbles;
  13384. event.cancelable = cancelable;
  13385. event.detail = detail;
  13386. event.screenX = clientX;
  13387. event.screenY = clientY;
  13388. event.clientX = clientX;
  13389. event.clientY = clientY;
  13390. event.ctrlKey = ctrlKey;
  13391. event.altKey = altKey;
  13392. event.shiftKey = shiftKey;
  13393. event.metaKey = metaKey;
  13394. event.button = crazyIEButtons[button] || button;
  13395. event.relatedTarget = relatedTarget; // cannot assign to/fromElement
  13396. return event;
  13397. },
  13398. createUIEvent: function (doc, type, bubbles, cancelable, detail) {
  13399. var event = doc.createEventObject();
  13400. event.bubbles = bubbles;
  13401. event.cancelable = cancelable;
  13402. return event;
  13403. },
  13404. fireEvent: function (target, type, event) {
  13405. target.fireEvent('on' + type, event);
  13406. },
  13407. fixTarget: function (target) {
  13408. if (target == document) {
  13409. // IE6,IE7 thinks window==document and doesn't have window.fireEvent()
  13410. // IE6,IE7 cannot properly call document.fireEvent()
  13411. return document.documentElement;
  13412. }
  13413. return target;
  13414. }
  13415. };
  13416. }
  13417. //----------------
  13418. // HTMLEvents
  13419. Ext.Object.each({
  13420. load: [false, false],
  13421. unload: [false, false],
  13422. select: [true, false],
  13423. change: [true, false],
  13424. submit: [true, true],
  13425. reset: [true, false],
  13426. resize: [true, false],
  13427. scroll: [true, false]
  13428. },
  13429. function (name, value) {
  13430. var bubbles = value[0], cancelable = value[1];
  13431. dispatchers[name] = function (targetEl, srcEvent) {
  13432. var e = API.createHtmlEvent(name, bubbles, cancelable);
  13433. API.fireEvent(targetEl, name, e);
  13434. };
  13435. });
  13436. //----------------
  13437. // MouseEvents
  13438. function createMouseEventDispatcher (type, detail) {
  13439. var cancelable = (type != 'mousemove');
  13440. return function (targetEl, srcEvent) {
  13441. var xy = srcEvent.getXY(),
  13442. e = API.createMouseEvent(targetEl.ownerDocument, type, true, cancelable,
  13443. detail, xy[0], xy[1], srcEvent.ctrlKey, srcEvent.altKey,
  13444. srcEvent.shiftKey, srcEvent.metaKey, srcEvent.button,
  13445. srcEvent.relatedTarget);
  13446. API.fireEvent(targetEl, type, e);
  13447. };
  13448. }
  13449. Ext.each(['click', 'dblclick', 'mousedown', 'mouseup', 'mouseover', 'mousemove', 'mouseout'],
  13450. function (eventName) {
  13451. dispatchers[eventName] = createMouseEventDispatcher(eventName, 1);
  13452. });
  13453. //----------------
  13454. // UIEvents
  13455. Ext.Object.each({
  13456. focusin: [true, false],
  13457. focusout: [true, false],
  13458. activate: [true, true],
  13459. focus: [false, false],
  13460. blur: [false, false]
  13461. },
  13462. function (name, value) {
  13463. var bubbles = value[0], cancelable = value[1];
  13464. dispatchers[name] = function (targetEl, srcEvent) {
  13465. var e = API.createUIEvent(targetEl.ownerDocument, name, bubbles, cancelable, 1);
  13466. API.fireEvent(targetEl, name, e);
  13467. };
  13468. });
  13469. //---------
  13470. if (!API) {
  13471. // not even sure what ancient browsers fall into this category...
  13472. dispatchers = {}; // never mind all those we just built :P
  13473. API = {
  13474. fixTarget: function (t) {
  13475. return t;
  13476. }
  13477. };
  13478. }
  13479. function cannotInject (target, srcEvent) {
  13480. }
  13481. return function (target) {
  13482. var me = this,
  13483. dispatcher = dispatchers[me.type] || cannotInject,
  13484. t = target ? (target.dom || target) : me.getTarget();
  13485. t = API.fixTarget(t);
  13486. dispatcher(t, me);
  13487. };
  13488. }() // call to produce method
  13489. }, function() {
  13490. Ext.EventObject = new Ext.EventObjectImpl();
  13491. });
  13492. /**
  13493. * @class Ext.dom.AbstractQuery
  13494. * @private
  13495. */
  13496. Ext.define('Ext.dom.AbstractQuery', {
  13497. /**
  13498. * Selects a group of elements.
  13499. * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
  13500. * @param {HTMLElement/String} [root] The start of the query (defaults to document).
  13501. * @return {HTMLElement[]} An Array of DOM elements which match the selector. If there are
  13502. * no matches, and empty Array is returned.
  13503. */
  13504. select: function(q, root) {
  13505. var results = [],
  13506. nodes,
  13507. i,
  13508. j,
  13509. qlen,
  13510. nlen;
  13511. root = root || document;
  13512. if (typeof root == 'string') {
  13513. root = document.getElementById(root);
  13514. }
  13515. q = q.split(",");
  13516. for (i = 0,qlen = q.length; i < qlen; i++) {
  13517. if (typeof q[i] == 'string') {
  13518. //support for node attribute selection
  13519. if (typeof q[i][0] == '@') {
  13520. nodes = root.getAttributeNode(q[i].substring(1));
  13521. results.push(nodes);
  13522. } else {
  13523. nodes = root.querySelectorAll(q[i]);
  13524. for (j = 0,nlen = nodes.length; j < nlen; j++) {
  13525. results.push(nodes[j]);
  13526. }
  13527. }
  13528. }
  13529. }
  13530. return results;
  13531. },
  13532. /**
  13533. * Selects a single element.
  13534. * @param {String} selector The selector/xpath query
  13535. * @param {HTMLElement/String} [root] The start of the query (defaults to document).
  13536. * @return {HTMLElement} The DOM element which matched the selector.
  13537. */
  13538. selectNode: function(q, root) {
  13539. return this.select(q, root)[0];
  13540. },
  13541. /**
  13542. * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
  13543. * @param {String/HTMLElement/Array} el An element id, element or array of elements
  13544. * @param {String} selector The simple selector to test
  13545. * @return {Boolean}
  13546. */
  13547. is: function(el, q) {
  13548. if (typeof el == "string") {
  13549. el = document.getElementById(el);
  13550. }
  13551. return this.select(q).indexOf(el) !== -1;
  13552. }
  13553. });
  13554. /**
  13555. * @class Ext.dom.AbstractHelper
  13556. * @private
  13557. * Abstract base class for {@link Ext.dom.Helper}.
  13558. * @private
  13559. */
  13560. Ext.define('Ext.dom.AbstractHelper', {
  13561. emptyTags : /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i,
  13562. confRe : /tag|children|cn|html|tpl|tplData$/i,
  13563. endRe : /end/i,
  13564. attribXlat: { cls : 'class', htmlFor : 'for' },
  13565. closeTags: {},
  13566. decamelizeName : function () {
  13567. var camelCaseRe = /([a-z])([A-Z])/g,
  13568. cache = {};
  13569. function decamel (match, p1, p2) {
  13570. return p1 + '-' + p2.toLowerCase();
  13571. }
  13572. return function (s) {
  13573. return cache[s] || (cache[s] = s.replace(camelCaseRe, decamel));
  13574. };
  13575. }(),
  13576. generateMarkup: function(spec, buffer) {
  13577. var me = this,
  13578. attr, val, tag, i, closeTags;
  13579. if (typeof spec == "string") {
  13580. buffer.push(spec);
  13581. } else if (Ext.isArray(spec)) {
  13582. for (i = 0; i < spec.length; i++) {
  13583. if (spec[i]) {
  13584. me.generateMarkup(spec[i], buffer);
  13585. }
  13586. }
  13587. } else {
  13588. tag = spec.tag || 'div';
  13589. buffer.push('<', tag);
  13590. for (attr in spec) {
  13591. if (spec.hasOwnProperty(attr)) {
  13592. val = spec[attr];
  13593. if (!me.confRe.test(attr)) {
  13594. if (typeof val == "object") {
  13595. buffer.push(' ', attr, '="');
  13596. me.generateStyles(val, buffer).push('"');
  13597. } else {
  13598. buffer.push(' ', me.attribXlat[attr] || attr, '="', val, '"');
  13599. }
  13600. }
  13601. }
  13602. }
  13603. // Now either just close the tag or try to add children and close the tag.
  13604. if (me.emptyTags.test(tag)) {
  13605. buffer.push('/>');
  13606. } else {
  13607. buffer.push('>');
  13608. // Apply the tpl html, and cn specifications
  13609. if ((val = spec.tpl)) {
  13610. val.applyOut(spec.tplData, buffer);
  13611. }
  13612. if ((val = spec.html)) {
  13613. buffer.push(val);
  13614. }
  13615. if ((val = spec.cn || spec.children)) {
  13616. me.generateMarkup(val, buffer);
  13617. }
  13618. // we generate a lot of close tags, so cache them rather than push 3 parts
  13619. closeTags = me.closeTags;
  13620. buffer.push(closeTags[tag] || (closeTags[tag] = '</' + tag + '>'));
  13621. }
  13622. }
  13623. return buffer;
  13624. },
  13625. /**
  13626. * Converts the styles from the given object to text. The styles are CSS style names
  13627. * with their associated value.
  13628. *
  13629. * The basic form of this method returns a string:
  13630. *
  13631. * var s = Ext.DomHelper.generateStyles({
  13632. * backgroundColor: 'red'
  13633. * });
  13634. *
  13635. * // s = 'background-color:red;'
  13636. *
  13637. * Alternatively, this method can append to an output array.
  13638. *
  13639. * var buf = [];
  13640. *
  13641. * ...
  13642. *
  13643. * Ext.DomHelper.generateStyles({
  13644. * backgroundColor: 'red'
  13645. * }, buf);
  13646. *
  13647. * In this case, the style text is pushed on to the array and the array is returned.
  13648. *
  13649. * @param {Object} styles The object describing the styles.
  13650. * @param {String[]} [buffer] The output buffer.
  13651. * @return {String/String[]} If buffer is passed, it is returned. Otherwise the style
  13652. * string is returned.
  13653. */
  13654. generateStyles: function (styles, buffer) {
  13655. var a = buffer || [],
  13656. name;
  13657. for (name in styles) {
  13658. if (styles.hasOwnProperty(name)) {
  13659. a.push(this.decamelizeName(name), ':', styles[name], ';');
  13660. }
  13661. }
  13662. return buffer || a.join('');
  13663. },
  13664. /**
  13665. * Returns the markup for the passed Element(s) config.
  13666. * @param {Object} spec The DOM object spec (and children)
  13667. * @return {String}
  13668. */
  13669. markup: function(spec) {
  13670. if (typeof spec == "string") {
  13671. return spec;
  13672. }
  13673. var buf = this.generateMarkup(spec, []);
  13674. return buf.join('');
  13675. },
  13676. /**
  13677. * Applies a style specification to an element.
  13678. * @param {String/HTMLElement} el The element to apply styles to
  13679. * @param {String/Object/Function} styles A style specification string e.g. 'width:100px', or object in the form {width:'100px'}, or
  13680. * a function which returns such a specification.
  13681. */
  13682. applyStyles: function(el, styles) {
  13683. if (styles) {
  13684. var i = 0,
  13685. len,
  13686. style;
  13687. el = Ext.fly(el);
  13688. if (typeof styles == 'function') {
  13689. styles = styles.call();
  13690. }
  13691. if (typeof styles == 'string'){
  13692. styles = Ext.util.Format.trim(styles).split(/\s*(?::|;)\s*/);
  13693. for(len = styles.length; i < len;){
  13694. el.setStyle(styles[i++], styles[i++]);
  13695. }
  13696. } else if (Ext.isObject(styles)) {
  13697. el.setStyle(styles);
  13698. }
  13699. }
  13700. },
  13701. /**
  13702. * Inserts an HTML fragment into the DOM.
  13703. * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
  13704. *
  13705. * For example take the following HTML: `<div>Contents</div>`
  13706. *
  13707. * Using different `where` values inserts element to the following places:
  13708. *
  13709. * - beforeBegin: `<HERE><div>Contents</div>`
  13710. * - afterBegin: `<div><HERE>Contents</div>`
  13711. * - beforeEnd: `<div>Contents<HERE></div>`
  13712. * - afterEnd: `<div>Contents</div><HERE>`
  13713. *
  13714. * @param {HTMLElement/TextNode} el The context element
  13715. * @param {String} html The HTML fragment
  13716. * @return {HTMLElement} The new node
  13717. */
  13718. insertHtml: function(where, el, html) {
  13719. var hash = {},
  13720. hashVal,
  13721. setStart,
  13722. range,
  13723. frag,
  13724. rangeEl,
  13725. rs;
  13726. where = where.toLowerCase();
  13727. // add these here because they are used in both branches of the condition.
  13728. hash['beforebegin'] = ['BeforeBegin', 'previousSibling'];
  13729. hash['afterend'] = ['AfterEnd', 'nextSibling'];
  13730. range = el.ownerDocument.createRange();
  13731. setStart = 'setStart' + (this.endRe.test(where) ? 'After' : 'Before');
  13732. if (hash[where]) {
  13733. range[setStart](el);
  13734. frag = range.createContextualFragment(html);
  13735. el.parentNode.insertBefore(frag, where == 'beforebegin' ? el : el.nextSibling);
  13736. return el[(where == 'beforebegin' ? 'previous' : 'next') + 'Sibling'];
  13737. }
  13738. else {
  13739. rangeEl = (where == 'afterbegin' ? 'first' : 'last') + 'Child';
  13740. if (el.firstChild) {
  13741. range[setStart](el[rangeEl]);
  13742. frag = range.createContextualFragment(html);
  13743. if (where == 'afterbegin') {
  13744. el.insertBefore(frag, el.firstChild);
  13745. }
  13746. else {
  13747. el.appendChild(frag);
  13748. }
  13749. }
  13750. else {
  13751. el.innerHTML = html;
  13752. }
  13753. return el[rangeEl];
  13754. }
  13755. throw 'Illegal insertion point -> "' + where + '"';
  13756. },
  13757. /**
  13758. * Creates new DOM element(s) and inserts them before el.
  13759. * @param {String/HTMLElement/Ext.Element} el The context element
  13760. * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
  13761. * @param {Boolean} [returnElement] true to return a Ext.Element
  13762. * @return {HTMLElement/Ext.Element} The new node
  13763. */
  13764. insertBefore: function(el, o, returnElement) {
  13765. return this.doInsert(el, o, returnElement, 'beforebegin');
  13766. },
  13767. /**
  13768. * Creates new DOM element(s) and inserts them after el.
  13769. * @param {String/HTMLElement/Ext.Element} el The context element
  13770. * @param {Object} o The DOM object spec (and children)
  13771. * @param {Boolean} [returnElement] true to return a Ext.Element
  13772. * @return {HTMLElement/Ext.Element} The new node
  13773. */
  13774. insertAfter: function(el, o, returnElement) {
  13775. return this.doInsert(el, o, returnElement, 'afterend', 'nextSibling');
  13776. },
  13777. /**
  13778. * Creates new DOM element(s) and inserts them as the first child of el.
  13779. * @param {String/HTMLElement/Ext.Element} el The context element
  13780. * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
  13781. * @param {Boolean} [returnElement] true to return a Ext.Element
  13782. * @return {HTMLElement/Ext.Element} The new node
  13783. */
  13784. insertFirst: function(el, o, returnElement) {
  13785. return this.doInsert(el, o, returnElement, 'afterbegin', 'firstChild');
  13786. },
  13787. /**
  13788. * Creates new DOM element(s) and appends them to el.
  13789. * @param {String/HTMLElement/Ext.Element} el The context element
  13790. * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
  13791. * @param {Boolean} [returnElement] true to return a Ext.Element
  13792. * @return {HTMLElement/Ext.Element} The new node
  13793. */
  13794. append: function(el, o, returnElement) {
  13795. return this.doInsert(el, o, returnElement, 'beforeend', '', true);
  13796. },
  13797. /**
  13798. * Creates new DOM element(s) and overwrites the contents of el with them.
  13799. * @param {String/HTMLElement/Ext.Element} el The context element
  13800. * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
  13801. * @param {Boolean} [returnElement] true to return a Ext.Element
  13802. * @return {HTMLElement/Ext.Element} The new node
  13803. */
  13804. overwrite: function(el, o, returnElement) {
  13805. el = Ext.getDom(el);
  13806. el.innerHTML = this.markup(o);
  13807. return returnElement ? Ext.get(el.firstChild) : el.firstChild;
  13808. },
  13809. doInsert: function(el, o, returnElement, pos, sibling, append) {
  13810. var newNode = this.insertHtml(pos, Ext.getDom(el), this.markup(o));
  13811. return returnElement ? Ext.get(newNode, true) : newNode;
  13812. }
  13813. });
  13814. /**
  13815. * @class Ext.dom.AbstractElement
  13816. * @extend Ext.Base
  13817. * @private
  13818. */
  13819. (function() {
  13820. var document = window.document,
  13821. trimRe = /^\s+|\s+$/g,
  13822. whitespaceRe = /\s/;
  13823. if (!Ext.cache){
  13824. Ext.cache = {};
  13825. }
  13826. Ext.define('Ext.dom.AbstractElement', {
  13827. inheritableStatics: {
  13828. /**
  13829. * Retrieves Ext.dom.Element objects. {@link Ext#get} is alias for {@link Ext.dom.Element#get}.
  13830. *
  13831. * **This method does not retrieve {@link Ext.Component Component}s.** This method retrieves Ext.dom.Element
  13832. * objects which encapsulate DOM elements. To retrieve a Component by its ID, use {@link Ext.ComponentManager#get}.
  13833. *
  13834. * Uses simple caching to consistently return the same object. Automatically fixes if an object was recreated with
  13835. * the same id via AJAX or DOM.
  13836. *
  13837. * @param {String/HTMLElement/Ext.Element} el The id of the node, a DOM Node or an existing Element.
  13838. * @return {Ext.dom.Element} The Element object (or null if no matching element was found)
  13839. * @static
  13840. * @inheritable
  13841. */
  13842. get: function(el) {
  13843. var me = this,
  13844. El = Ext.dom.Element,
  13845. cache,
  13846. extEl,
  13847. dom,
  13848. id;
  13849. if (!el) {
  13850. return null;
  13851. }
  13852. if (typeof el == "string") { // element id
  13853. if (el == Ext.windowId) {
  13854. return El.get(window);
  13855. } else if (el == Ext.documentId) {
  13856. return El.get(document);
  13857. }
  13858. cache = Ext.cache[el];
  13859. // This code is here to catch the case where we've got a reference to a document of an iframe
  13860. // It getElementById will fail because it's not part of the document, so if we're skipping
  13861. // GC it means it's a window/document object that isn't the default window/document, which we have
  13862. // already handled above
  13863. if (cache && cache.skipGarbageCollection) {
  13864. extEl = cache.el;
  13865. return extEl;
  13866. }
  13867. if (!(dom = document.getElementById(el))) {
  13868. return null;
  13869. }
  13870. if (cache && cache.el) {
  13871. extEl = cache.el;
  13872. extEl.dom = dom;
  13873. } else {
  13874. // Force new element if there's a cache but no el attached
  13875. extEl = new El(dom, !!cache);
  13876. }
  13877. return extEl;
  13878. } else if (el.tagName) { // dom element
  13879. if (!(id = el.id)) {
  13880. id = Ext.id(el);
  13881. }
  13882. cache = Ext.cache[id];
  13883. if (cache && cache.el) {
  13884. extEl = Ext.cache[id].el;
  13885. extEl.dom = el;
  13886. } else {
  13887. // Force new element if there's a cache but no el attached
  13888. extEl = new El(el, !!cache);
  13889. }
  13890. return extEl;
  13891. } else if (el instanceof me) {
  13892. if (el != me.docEl && el != me.winEl) {
  13893. // refresh dom element in case no longer valid,
  13894. // catch case where it hasn't been appended
  13895. el.dom = document.getElementById(el.id) || el.dom;
  13896. }
  13897. return el;
  13898. } else if (el.isComposite) {
  13899. return el;
  13900. } else if (Ext.isArray(el)) {
  13901. return me.select(el);
  13902. } else if (el === document) {
  13903. // create a bogus element object representing the document object
  13904. if (!me.docEl) {
  13905. me.docEl = Ext.Object.chain(El.prototype);
  13906. me.docEl.dom = document;
  13907. me.docEl.id = Ext.id(document);
  13908. me.addToCache(me.docEl);
  13909. }
  13910. return me.docEl;
  13911. } else if (el === window) {
  13912. if (!me.winEl) {
  13913. me.winEl = Ext.Object.chain(El.prototype);
  13914. me.winEl.dom = window;
  13915. me.winEl.id = Ext.id(window);
  13916. me.addToCache(me.winEl);
  13917. }
  13918. return me.winEl;
  13919. }
  13920. return null;
  13921. },
  13922. addToCache: function(el, id) {
  13923. if (el) {
  13924. id = id || el.id;
  13925. el.$cache = Ext.cache[id] || (Ext.cache[id] = {
  13926. data: {},
  13927. events: {}
  13928. });
  13929. // Inject the back link from the cache in case the cache entry
  13930. // had already been created by Ext.fly. Ext.fly creates a cache entry with no el link.
  13931. el.$cache.el = el;
  13932. }
  13933. return el;
  13934. },
  13935. addMethods: function() {
  13936. this.override.apply(this, arguments);
  13937. },
  13938. /**
  13939. * <p>Returns an array of unique class names based upon the input strings, or string arrays.</p>
  13940. * <p>The number of parameters is unlimited.</p>
  13941. * <p>Example</p><code><pre>
  13942. // Add x-invalid and x-mandatory classes, do not duplicate
  13943. myElement.dom.className = Ext.core.Element.mergeClsList(this.initialClasses, 'x-invalid x-mandatory');
  13944. </pre></code>
  13945. * @param {Mixed} clsList1 A string of class names, or an array of class names.
  13946. * @param {Mixed} clsList2 A string of class names, or an array of class names.
  13947. * @return {Array} An array of strings representing remaining unique, merged class names. If class names were added to the first list, the <code>changed</code> property will be <code>true</code>.
  13948. * @static
  13949. * @inheritable
  13950. */
  13951. mergeClsList: function() {
  13952. var clsList, clsHash = {},
  13953. i, length, j, listLength, clsName, result = [],
  13954. changed = false;
  13955. for (i = 0, length = arguments.length; i < length; i++) {
  13956. clsList = arguments[i];
  13957. if (Ext.isString(clsList)) {
  13958. clsList = clsList.replace(trimRe, '').split(whitespaceRe);
  13959. }
  13960. if (clsList) {
  13961. for (j = 0, listLength = clsList.length; j < listLength; j++) {
  13962. clsName = clsList[j];
  13963. if (!clsHash[clsName]) {
  13964. if (i) {
  13965. changed = true;
  13966. }
  13967. clsHash[clsName] = true;
  13968. }
  13969. }
  13970. }
  13971. }
  13972. for (clsName in clsHash) {
  13973. result.push(clsName);
  13974. }
  13975. result.changed = changed;
  13976. return result;
  13977. },
  13978. /**
  13979. * <p>Returns an array of unique class names deom the first parameter with all class names
  13980. * from the second parameter removed.</p>
  13981. * <p>Example</p><code><pre>
  13982. // Remove x-invalid and x-mandatory classes if present.
  13983. myElement.dom.className = Ext.core.Element.removeCls(this.initialClasses, 'x-invalid x-mandatory');
  13984. </pre></code>
  13985. * @param {Mixed} existingClsList A string of class names, or an array of class names.
  13986. * @param {Mixed} removeClsList A string of class names, or an array of class names to remove from <code>existingClsList</code>.
  13987. * @return {Array} An array of strings representing remaining class names. If class names were removed, the <code>changed</code> property will be <code>true</code>.
  13988. * @static
  13989. * @inheritable
  13990. */
  13991. removeCls: function(existingClsList, removeClsList) {
  13992. var clsHash = {},
  13993. i, length, clsName, result = [],
  13994. changed = false;
  13995. if (existingClsList) {
  13996. if (Ext.isString(existingClsList)) {
  13997. existingClsList = existingClsList.replace(trimRe, '').split(whitespaceRe);
  13998. }
  13999. for (i = 0, length = existingClsList.length; i < length; i++) {
  14000. clsHash[existingClsList[i]] = true;
  14001. }
  14002. }
  14003. if (removeClsList) {
  14004. if (Ext.isString(removeClsList)) {
  14005. removeClsList = removeClsList.split(whitespaceRe);
  14006. }
  14007. for (i = 0, length = removeClsList.length; i < length; i++) {
  14008. clsName = removeClsList[i];
  14009. if (clsHash[clsName]) {
  14010. changed = true;
  14011. delete clsHash[clsName];
  14012. }
  14013. }
  14014. }
  14015. for (clsName in clsHash) {
  14016. result.push(clsName);
  14017. }
  14018. result.changed = changed;
  14019. return result;
  14020. },
  14021. /**
  14022. * @property
  14023. * Visibility mode constant for use with {@link Ext.dom.Element#setVisibilityMode}. Use visibility to hide element
  14024. * @static
  14025. * @inheritable
  14026. */
  14027. VISIBILITY: 1,
  14028. /**
  14029. * @property
  14030. * Visibility mode constant for use with {@link Ext.dom.Element#setVisibilityMode}. Use display to hide element
  14031. * @static
  14032. * @inheritable
  14033. */
  14034. DISPLAY: 2,
  14035. /**
  14036. * @property
  14037. * Visibility mode constant for use with {@link Ext.dom.Element#setVisibilityMode}. Use offsets to hide element
  14038. * @static
  14039. * @inheritable
  14040. */
  14041. OFFSETS: 3
  14042. },
  14043. constructor: function(element, forceNew) {
  14044. var me = this,
  14045. dom = typeof element == 'string'
  14046. ? document.getElementById(element)
  14047. : element,
  14048. id;
  14049. if (!dom) {
  14050. return null;
  14051. }
  14052. id = dom.id;
  14053. if (!forceNew && id && Ext.cache[id]) {
  14054. // element object already exists
  14055. return Ext.cache[id].el;
  14056. }
  14057. /**
  14058. * @property {HTMLElement} dom
  14059. * The DOM element
  14060. */
  14061. me.dom = dom;
  14062. /**
  14063. * @property {String} id
  14064. * The DOM element ID
  14065. */
  14066. me.id = id || Ext.id(dom);
  14067. me.self.addToCache(me);
  14068. },
  14069. /**
  14070. * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
  14071. * @param {Object} o The object with the attributes
  14072. * @param {Boolean} [useSet=true] false to override the default setAttribute to use expandos.
  14073. * @return {Ext.dom.Element} this
  14074. */
  14075. set: function(o, useSet) {
  14076. var el = this.dom,
  14077. attr,
  14078. value;
  14079. for (attr in o) {
  14080. if (o.hasOwnProperty(attr)) {
  14081. value = o[attr];
  14082. if (attr == 'style') {
  14083. this.applyStyles(value);
  14084. }
  14085. else if (attr == 'cls') {
  14086. el.className = value;
  14087. }
  14088. else if (useSet !== false) {
  14089. if (value === undefined) {
  14090. el.removeAttribute(attr);
  14091. } else {
  14092. el.setAttribute(attr, value);
  14093. }
  14094. }
  14095. else {
  14096. el[attr] = value;
  14097. }
  14098. }
  14099. }
  14100. return this;
  14101. },
  14102. /**
  14103. * @property {String} defaultUnit
  14104. * The default unit to append to CSS values where a unit isn't provided.
  14105. */
  14106. defaultUnit: "px",
  14107. /**
  14108. * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
  14109. * @param {String} selector The simple selector to test
  14110. * @return {Boolean} True if this element matches the selector, else false
  14111. */
  14112. is: function(simpleSelector) {
  14113. return Ext.DomQuery.is(this.dom, simpleSelector);
  14114. },
  14115. /**
  14116. * Returns the value of the "value" attribute
  14117. * @param {Boolean} asNumber true to parse the value as a number
  14118. * @return {String/Number}
  14119. */
  14120. getValue: function(asNumber) {
  14121. var val = this.dom.value;
  14122. return asNumber ? parseInt(val, 10) : val;
  14123. },
  14124. /**
  14125. * Removes this element's dom reference. Note that event and cache removal is handled at {@link Ext#removeNode
  14126. * Ext.removeNode}
  14127. */
  14128. remove: function() {
  14129. var me = this,
  14130. dom = me.dom;
  14131. if (dom) {
  14132. Ext.removeNode(dom);
  14133. delete me.dom;
  14134. }
  14135. },
  14136. /**
  14137. * Returns true if this element is an ancestor of the passed element
  14138. * @param {HTMLElement/String} el The element to check
  14139. * @return {Boolean} True if this element is an ancestor of el, else false
  14140. */
  14141. contains: function(el) {
  14142. if (!el) {
  14143. return false;
  14144. }
  14145. var me = this,
  14146. dom = el.dom || el;
  14147. // we need el-contains-itself logic here because isAncestor does not do that:
  14148. return (dom === me.dom) || Ext.dom.AbstractElement.isAncestor(me.dom, dom);
  14149. },
  14150. /**
  14151. * Returns the value of an attribute from the element's underlying DOM node.
  14152. * @param {String} name The attribute name
  14153. * @param {String} [namespace] The namespace in which to look for the attribute
  14154. * @return {String} The attribute value
  14155. */
  14156. getAttribute: function(name, ns) {
  14157. var dom = this.dom;
  14158. return dom.getAttributeNS(ns, name) || dom.getAttribute(ns + ":" + name) || dom.getAttribute(name) || dom[name];
  14159. },
  14160. /**
  14161. * Update the innerHTML of this element
  14162. * @param {String} html The new HTML
  14163. * @return {Ext.dom.Element} this
  14164. */
  14165. update: function(html) {
  14166. if (this.dom) {
  14167. this.dom.innerHTML = html;
  14168. }
  14169. return this;
  14170. },
  14171. /**
  14172. * Set the innerHTML of this element
  14173. * @param {String} html The new HTML
  14174. * @return {Ext.Element} this
  14175. */
  14176. setHTML: function(html) {
  14177. if(this.dom) {
  14178. this.dom.innerHTML = html;
  14179. }
  14180. return this;
  14181. },
  14182. /**
  14183. * Returns the innerHTML of an Element or an empty string if the element's
  14184. * dom no longer exists.
  14185. */
  14186. getHTML: function() {
  14187. return this.dom ? this.dom.innerHTML : '';
  14188. },
  14189. /**
  14190. * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
  14191. * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
  14192. * @return {Ext.Element} this
  14193. */
  14194. hide: function() {
  14195. this.setVisible(false);
  14196. return this;
  14197. },
  14198. /**
  14199. * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
  14200. * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
  14201. * @return {Ext.Element} this
  14202. */
  14203. show: function() {
  14204. this.setVisible(true);
  14205. return this;
  14206. },
  14207. /**
  14208. * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
  14209. * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
  14210. * @param {Boolean} visible Whether the element is visible
  14211. * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
  14212. * @return {Ext.Element} this
  14213. */
  14214. setVisible: function(visible, animate) {
  14215. var me = this,
  14216. statics = me.self,
  14217. mode = me.getVisibilityMode(),
  14218. prefix = Ext.baseCSSPrefix;
  14219. switch (mode) {
  14220. case statics.VISIBILITY:
  14221. me.removeCls([prefix + 'hidden-display', prefix + 'hidden-offsets']);
  14222. me[visible ? 'removeCls' : 'addCls'](prefix + 'hidden-visibility');
  14223. break;
  14224. case statics.DISPLAY:
  14225. me.removeCls([prefix + 'hidden-visibility', prefix + 'hidden-offsets']);
  14226. me[visible ? 'removeCls' : 'addCls'](prefix + 'hidden-display');
  14227. break;
  14228. case statics.OFFSETS:
  14229. me.removeCls([prefix + 'hidden-visibility', prefix + 'hidden-display']);
  14230. me[visible ? 'removeCls' : 'addCls'](prefix + 'hidden-offsets');
  14231. break;
  14232. }
  14233. return me;
  14234. },
  14235. getVisibilityMode: function() {
  14236. // Only flyweights won't have a $cache object, by calling getCache the cache
  14237. // will be created for future accesses. As such, we're eliminating the method
  14238. // call since it's mostly redundant
  14239. var data = (this.$cache || this.getCache()).data,
  14240. visMode = data.visibilityMode;
  14241. if (visMode === undefined) {
  14242. data.visibilityMode = visMode = this.self.DISPLAY;
  14243. }
  14244. return visMode;
  14245. },
  14246. /**
  14247. * Use this to change the visisbiliy mode between {@link #VISIBILITY}, {@link #DISPLAY} or {@link #OFFSETS}.
  14248. */
  14249. setVisibilityMode: function(mode) {
  14250. (this.$cache || this.getCache()).data.visibilityMode = mode;
  14251. return this;
  14252. },
  14253. getCache: function() {
  14254. var me = this,
  14255. id = me.dom.id || Ext.id(me.dom);
  14256. // Note that we do not assign an ID to the calling object here.
  14257. // An Ext.dom.Element will have one assigned at construction, and an Ext.dom.AbstractElement.Fly must not have one.
  14258. // We assign an ID to the DOM element if it does not have one.
  14259. me.$cache = Ext.cache[id] || (Ext.cache[id] = {
  14260. data: {},
  14261. events: {}
  14262. });
  14263. return me.$cache;
  14264. }
  14265. }, function() {
  14266. var AbstractElement = this,
  14267. validIdRe = /^[a-z_][a-z0-9_\-]*$/i;
  14268. Ext.getDetachedBody = function () {
  14269. var detachedEl = AbstractElement.detachedBodyEl;
  14270. if (!detachedEl) {
  14271. detachedEl = document.createElement('div');
  14272. AbstractElement.detachedBodyEl = detachedEl = new AbstractElement.Fly(detachedEl);
  14273. detachedEl.isDetachedBody = true;
  14274. }
  14275. return detachedEl;
  14276. };
  14277. Ext.getElementById = function (id) {
  14278. var el = document.getElementById(id),
  14279. detachedBodyEl;
  14280. if (!el && (detachedBodyEl = AbstractElement.detachedBodyEl) && validIdRe.test(id)) {
  14281. el = detachedBodyEl.dom.querySelector('#' + id);
  14282. }
  14283. return el;
  14284. };
  14285. /**
  14286. * @member Ext
  14287. * @method get
  14288. * @inheritdoc Ext.dom.Element#get
  14289. */
  14290. Ext.get = function(el) {
  14291. return Ext.dom.Element.get(el);
  14292. };
  14293. this.addStatics({
  14294. /**
  14295. * @class Ext.dom.AbstractElement.Fly
  14296. * @extends Ext.dom.AbstractElement
  14297. *
  14298. * A non-persistent wrapper for a DOM element which may be used to execute methods of {@link Ext.dom.Element}
  14299. * upon a DOM element without creating an instance of {@link Ext.dom.Element}.
  14300. *
  14301. * A **singleton** instance of this class is returned when you use {@link Ext#fly}
  14302. *
  14303. * Because it is a singleton, this Flyweight does not have an ID, and must be used and discarded in a single line.
  14304. * You should not keep and use the reference to this singleton over multiple lines because methods that you call
  14305. * may themselves make use of {@link Ext#fly} and may change the DOM element to which the instance refers.
  14306. */
  14307. Fly: new Ext.Class({
  14308. extend: AbstractElement,
  14309. /**
  14310. * @property {Boolean} isFly
  14311. * This is `true` to identify Element flyweights
  14312. */
  14313. isFly: true,
  14314. constructor: function(dom) {
  14315. this.dom = dom;
  14316. },
  14317. /**
  14318. * @private
  14319. * Attach this fliyweight instance to the passed DOM element.
  14320. *
  14321. * Note that a flightweight does **not** have an ID, and does not acquire the ID of the DOM element.
  14322. */
  14323. attach: function (dom) {
  14324. // Attach to the passed DOM element. The same code as in Ext.Fly
  14325. this.dom = dom;
  14326. // Use cached data if there is existing cached data for the referenced DOM element,
  14327. // otherwise it will be created when needed by getCache.
  14328. this.$cache = dom.id ? Ext.cache[dom.id] : null;
  14329. return this;
  14330. }
  14331. }),
  14332. _flyweights: {},
  14333. /**
  14334. * Gets the singleton {@link Ext.dom.AbstractElement.Fly flyweight} element, with the passed node as the active element.
  14335. *
  14336. * Because it is a singleton, this Flyweight does not have an ID, and must be used and discarded in a single line.
  14337. * You may not keep and use the reference to this singleton over multiple lines because methods that you call
  14338. * may themselves make use of {@link Ext#fly} and may change the DOM element to which the instance refers.
  14339. *
  14340. * {@link Ext#fly} is alias for {@link Ext.dom.AbstractElement#fly}.
  14341. *
  14342. * Use this to make one-time references to DOM elements which are not going to be accessed again either by
  14343. * application code, or by Ext's classes. If accessing an element which will be processed regularly, then {@link
  14344. * Ext#get Ext.get} will be more appropriate to take advantage of the caching provided by the Ext.dom.Element
  14345. * class.
  14346. *
  14347. * @param {String/HTMLElement} dom The dom node or id
  14348. * @param {String} [named] Allows for creation of named reusable flyweights to prevent conflicts (e.g.
  14349. * internally Ext uses "_global")
  14350. * @return {Ext.dom.AbstractElement.Fly} The singleton flyweight object (or null if no matching element was found)
  14351. * @static
  14352. * @member Ext.dom.AbstractElement
  14353. */
  14354. fly: function(dom, named) {
  14355. var fly = null,
  14356. _flyweights = AbstractElement._flyweights;
  14357. named = named || '_global';
  14358. dom = Ext.getDom(dom);
  14359. if (dom) {
  14360. fly = _flyweights[named] || (_flyweights[named] = new AbstractElement.Fly());
  14361. // Attach to the passed DOM element.
  14362. // This code performs the same function as Fly.attach, but inline it for efficiency
  14363. fly.dom = dom;
  14364. // Use cached data if there is existing cached data for the referenced DOM element,
  14365. // otherwise it will be created when needed by getCache.
  14366. fly.$cache = dom.id ? Ext.cache[dom.id] : null;
  14367. }
  14368. return fly;
  14369. }
  14370. });
  14371. /**
  14372. * @member Ext
  14373. * @method fly
  14374. * @inheritdoc Ext.dom.AbstractElement#fly
  14375. */
  14376. Ext.fly = function() {
  14377. return AbstractElement.fly.apply(AbstractElement, arguments);
  14378. };
  14379. (function (proto) {
  14380. /**
  14381. * @method destroy
  14382. * @member Ext.dom.AbstractElement
  14383. * @inheritdoc Ext.dom.AbstractElement#remove
  14384. * Alias to {@link #remove}.
  14385. */
  14386. proto.destroy = proto.remove;
  14387. /**
  14388. * Returns a child element of this element given its `id`.
  14389. * @method getById
  14390. * @member Ext.dom.AbstractElement
  14391. * @param {String} id The id of the desired child element.
  14392. * @param {Boolean} [asDom=false] True to return the DOM element, false to return a
  14393. * wrapped Element object.
  14394. */
  14395. if (document.querySelector) {
  14396. proto.getById = function (id, asDom) {
  14397. // for normal elements getElementById is the best solution, but if the el is
  14398. // not part of the document.body, we have to resort to querySelector
  14399. var dom = document.getElementById(id) ||
  14400. (validIdRe.test(id) ? this.dom.querySelector('#'+id) : null);
  14401. return asDom ? dom : (dom ? Ext.get(dom) : null);
  14402. };
  14403. } else {
  14404. proto.getById = function (id, asDom) {
  14405. var dom = document.getElementById(id);
  14406. return asDom ? dom : (dom ? Ext.get(dom) : null);
  14407. };
  14408. }
  14409. })(this.prototype);
  14410. });
  14411. })();
  14412. /**
  14413. * @class Ext.dom.AbstractElement
  14414. */
  14415. Ext.dom.AbstractElement.addInheritableStatics({
  14416. unitRe: /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i,
  14417. camelRe: /(-[a-z])/gi,
  14418. cssRe: /([a-z0-9-]+)\s*:\s*([^;\s]+(?:\s*[^;\s]+)*);?/gi,
  14419. opacityRe: /alpha\(opacity=(.*)\)/i,
  14420. propertyCache: {},
  14421. defaultUnit : "px",
  14422. borders: {l: 'border-left-width', r: 'border-right-width', t: 'border-top-width', b: 'border-bottom-width'},
  14423. paddings: {l: 'padding-left', r: 'padding-right', t: 'padding-top', b: 'padding-bottom'},
  14424. margins: {l: 'margin-left', r: 'margin-right', t: 'margin-top', b: 'margin-bottom'},
  14425. /**
  14426. * Test if size has a unit, otherwise appends the passed unit string, or the default for this Element.
  14427. * @param size {Object} The size to set
  14428. * @param units {String} The units to append to a numeric size value
  14429. * @private
  14430. * @static
  14431. */
  14432. addUnits: function(size, units) {
  14433. // Most common case first: Size is set to a number
  14434. if (typeof size == 'number') {
  14435. return size + (units || this.defaultUnit || 'px');
  14436. }
  14437. // Size set to a value which means "auto"
  14438. if (size === "" || size == "auto" || size === undefined || size === null) {
  14439. return size || '';
  14440. }
  14441. // Otherwise, warn if it's not a valid CSS measurement
  14442. if (!this.unitRe.test(size)) {
  14443. return size || '';
  14444. }
  14445. return size;
  14446. },
  14447. /**
  14448. * @static
  14449. * @private
  14450. */
  14451. isAncestor: function(p, c) {
  14452. var ret = false;
  14453. p = Ext.getDom(p);
  14454. c = Ext.getDom(c);
  14455. if (p && c) {
  14456. if (p.contains) {
  14457. return p.contains(c);
  14458. } else if (p.compareDocumentPosition) {
  14459. return !!(p.compareDocumentPosition(c) & 16);
  14460. } else {
  14461. while ((c = c.parentNode)) {
  14462. ret = c == p || ret;
  14463. }
  14464. }
  14465. }
  14466. return ret;
  14467. },
  14468. /**
  14469. * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations
  14470. * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result)
  14471. * @static
  14472. * @param {Number/String} box The encoded margins
  14473. * @return {Object} An object with margin sizes for top, right, bottom and left
  14474. */
  14475. parseBox: function(box) {
  14476. if (typeof box != 'string') {
  14477. box = box.toString();
  14478. }
  14479. var parts = box.split(' '),
  14480. ln = parts.length;
  14481. if (ln == 1) {
  14482. parts[1] = parts[2] = parts[3] = parts[0];
  14483. }
  14484. else if (ln == 2) {
  14485. parts[2] = parts[0];
  14486. parts[3] = parts[1];
  14487. }
  14488. else if (ln == 3) {
  14489. parts[3] = parts[1];
  14490. }
  14491. return {
  14492. top :parseFloat(parts[0]) || 0,
  14493. right :parseFloat(parts[1]) || 0,
  14494. bottom:parseFloat(parts[2]) || 0,
  14495. left :parseFloat(parts[3]) || 0
  14496. };
  14497. },
  14498. /**
  14499. * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations
  14500. * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result)
  14501. * @static
  14502. * @param {Number/String} box The encoded margins
  14503. * @param {String} units The type of units to add
  14504. * @return {String} An string with unitized (px if units is not specified) metrics for top, right, bottom and left
  14505. */
  14506. unitizeBox: function(box, units) {
  14507. var A = this.addUnits,
  14508. B = this.parseBox(box);
  14509. return A(B.top, units) + ' ' +
  14510. A(B.right, units) + ' ' +
  14511. A(B.bottom, units) + ' ' +
  14512. A(B.left, units);
  14513. },
  14514. // private
  14515. camelReplaceFn: function(m, a) {
  14516. return a.charAt(1).toUpperCase();
  14517. },
  14518. /**
  14519. * Normalizes CSS property keys from dash delimited to camel case JavaScript Syntax.
  14520. * For example:
  14521. *
  14522. * - border-width -> borderWidth
  14523. * - padding-top -> paddingTop
  14524. *
  14525. * @static
  14526. * @param {String} prop The property to normalize
  14527. * @return {String} The normalized string
  14528. */
  14529. normalize: function(prop) {
  14530. // TODO: Mobile optimization?
  14531. if (prop == 'float') {
  14532. prop = Ext.supports.Float ? 'cssFloat' : 'styleFloat';
  14533. }
  14534. return this.propertyCache[prop] || (this.propertyCache[prop] = prop.replace(this.camelRe, this.camelReplaceFn));
  14535. },
  14536. /**
  14537. * Retrieves the document height
  14538. * @static
  14539. * @return {Number} documentHeight
  14540. */
  14541. getDocumentHeight: function() {
  14542. return Math.max(!Ext.isStrict ? document.body.scrollHeight : document.documentElement.scrollHeight, this.getViewportHeight());
  14543. },
  14544. /**
  14545. * Retrieves the document width
  14546. * @static
  14547. * @return {Number} documentWidth
  14548. */
  14549. getDocumentWidth: function() {
  14550. return Math.max(!Ext.isStrict ? document.body.scrollWidth : document.documentElement.scrollWidth, this.getViewportWidth());
  14551. },
  14552. /**
  14553. * Retrieves the viewport height of the window.
  14554. * @static
  14555. * @return {Number} viewportHeight
  14556. */
  14557. getViewportHeight: function(){
  14558. return window.innerHeight;
  14559. },
  14560. /**
  14561. * Retrieves the viewport width of the window.
  14562. * @static
  14563. * @return {Number} viewportWidth
  14564. */
  14565. getViewportWidth: function() {
  14566. return window.innerWidth;
  14567. },
  14568. /**
  14569. * Retrieves the viewport size of the window.
  14570. * @static
  14571. * @return {Object} object containing width and height properties
  14572. */
  14573. getViewSize: function() {
  14574. return {
  14575. width: window.innerWidth,
  14576. height: window.innerHeight
  14577. };
  14578. },
  14579. /**
  14580. * Retrieves the current orientation of the window. This is calculated by
  14581. * determing if the height is greater than the width.
  14582. * @static
  14583. * @return {String} Orientation of window: 'portrait' or 'landscape'
  14584. */
  14585. getOrientation: function() {
  14586. if (Ext.supports.OrientationChange) {
  14587. return (window.orientation == 0) ? 'portrait' : 'landscape';
  14588. }
  14589. return (window.innerHeight > window.innerWidth) ? 'portrait' : 'landscape';
  14590. },
  14591. /**
  14592. * Returns the top Element that is located at the passed coordinates
  14593. * @static
  14594. * @param {Number} x The x coordinate
  14595. * @param {Number} y The y coordinate
  14596. * @return {String} The found Element
  14597. */
  14598. fromPoint: function(x, y) {
  14599. return Ext.get(document.elementFromPoint(x, y));
  14600. },
  14601. /**
  14602. * Converts a CSS string into an object with a property for each style.
  14603. *
  14604. * The sample code below would return an object with 2 properties, one
  14605. * for background-color and one for color.
  14606. *
  14607. * var css = 'background-color: red;color: blue; ';
  14608. * console.log(Ext.dom.Element.parseStyles(css));
  14609. *
  14610. * @static
  14611. * @param {String} styles A CSS string
  14612. * @return {Object} styles
  14613. */
  14614. parseStyles: function(styles){
  14615. var out = {},
  14616. cssRe = this.cssRe,
  14617. matches;
  14618. if (styles) {
  14619. // Since we're using the g flag on the regex, we need to set the lastIndex.
  14620. // This automatically happens on some implementations, but not others, see:
  14621. // http://stackoverflow.com/questions/2645273/javascript-regular-expression-literal-persists-between-function-calls
  14622. // http://blog.stevenlevithan.com/archives/fixing-javascript-regexp
  14623. cssRe.lastIndex = 0;
  14624. while ((matches = cssRe.exec(styles))) {
  14625. out[matches[1]] = matches[2];
  14626. }
  14627. }
  14628. return out;
  14629. }
  14630. });
  14631. //TODO Need serious cleanups
  14632. (function(){
  14633. var doc = document,
  14634. AbstractElement = Ext.dom.AbstractElement,
  14635. activeElement = null,
  14636. isCSS1 = doc.compatMode == "CSS1Compat",
  14637. flyInstance,
  14638. fly = function (el) {
  14639. if (!flyInstance) {
  14640. flyInstance = new AbstractElement.Fly();
  14641. }
  14642. flyInstance.attach(el);
  14643. return flyInstance;
  14644. };
  14645. // If the browser does not support document.activeElement we need some assistance.
  14646. // This covers old Safari 3.2 (4.0 added activeElement along with just about all
  14647. // other browsers). We need this support to handle issues with old Safari.
  14648. if (!('activeElement' in doc) && doc.addEventListener) {
  14649. doc.addEventListener('focus',
  14650. function (ev) {
  14651. if (ev && ev.target) {
  14652. activeElement = (ev.target == doc) ? null : ev.target;
  14653. }
  14654. }, true);
  14655. }
  14656. /*
  14657. * Helper function to create the function that will restore the selection.
  14658. */
  14659. function makeSelectionRestoreFn (activeEl, start, end) {
  14660. return function () {
  14661. activeEl.selectionStart = start;
  14662. activeEl.selectionEnd = end;
  14663. };
  14664. }
  14665. AbstractElement.addInheritableStatics({
  14666. /**
  14667. * Returns the active element in the DOM. If the browser supports activeElement
  14668. * on the document, this is returned. If not, the focus is tracked and the active
  14669. * element is maintained internally.
  14670. * @return {HTMLElement} The active (focused) element in the document.
  14671. */
  14672. getActiveElement: function () {
  14673. return doc.activeElement || activeElement;
  14674. },
  14675. /**
  14676. * Creates a function to call to clean up problems with the work-around for the
  14677. * WebKit RightMargin bug. The work-around is to add "display: 'inline-block'" to
  14678. * the element before calling getComputedStyle and then to restore its original
  14679. * display value. The problem with this is that it corrupts the selection of an
  14680. * INPUT or TEXTAREA element (as in the "I-beam" goes away but ths focus remains).
  14681. * To cleanup after this, we need to capture the selection of any such element and
  14682. * then restore it after we have restored the display style.
  14683. *
  14684. * @param {Ext.dom.Element} target The top-most element being adjusted.
  14685. * @private
  14686. */
  14687. getRightMarginFixCleaner: function (target) {
  14688. var supports = Ext.supports,
  14689. hasInputBug = supports.DisplayChangeInputSelectionBug,
  14690. hasTextAreaBug = supports.DisplayChangeTextAreaSelectionBug;
  14691. if (hasInputBug || hasTextAreaBug) {
  14692. var activeEl = doc.activeElement || activeElement, // save a call
  14693. tag = activeEl && activeEl.tagName,
  14694. start,
  14695. end;
  14696. if ((hasTextAreaBug && tag == 'TEXTAREA') ||
  14697. (hasInputBug && tag == 'INPUT' && activeEl.type == 'text')) {
  14698. if (Ext.dom.Element.isAncestor(target, activeEl)) {
  14699. start = activeEl.selectionStart;
  14700. end = activeEl.selectionEnd;
  14701. if (Ext.isNumber(start) && Ext.isNumber(end)) { // to be safe...
  14702. // We don't create the raw closure here inline because that
  14703. // will be costly even if we don't want to return it (nested
  14704. // function decls and exprs are often instantiated on entry
  14705. // regardless of whether execution ever reaches them):
  14706. return makeSelectionRestoreFn(activeEl, start, end);
  14707. }
  14708. }
  14709. }
  14710. }
  14711. return Ext.emptyFn; // avoid special cases, just return a nop
  14712. },
  14713. getViewWidth: function(full) {
  14714. return full ? Ext.dom.Element.getDocumentWidth() : Ext.dom.Element.getViewportWidth();
  14715. },
  14716. getViewHeight: function(full) {
  14717. return full ? Ext.dom.Element.getDocumentHeight() : Ext.dom.Element.getViewportHeight();
  14718. },
  14719. getDocumentHeight: function() {
  14720. return Math.max(!isCSS1 ? doc.body.scrollHeight : doc.documentElement.scrollHeight, Ext.dom.Element.getViewportHeight());
  14721. },
  14722. getDocumentWidth: function() {
  14723. return Math.max(!isCSS1 ? doc.body.scrollWidth : doc.documentElement.scrollWidth, Ext.dom.Element.getViewportWidth());
  14724. },
  14725. getViewportHeight: function(){
  14726. return Ext.isIE ?
  14727. (Ext.isStrict ? doc.documentElement.clientHeight : doc.body.clientHeight) :
  14728. self.innerHeight;
  14729. },
  14730. getViewportWidth: function() {
  14731. return (!Ext.isStrict && !Ext.isOpera) ? doc.body.clientWidth :
  14732. Ext.isIE ? doc.documentElement.clientWidth : self.innerWidth;
  14733. },
  14734. getY: function(el) {
  14735. return Ext.dom.Element.getXY(el)[1];
  14736. },
  14737. getX: function(el) {
  14738. return Ext.dom.Element.getXY(el)[0];
  14739. },
  14740. getXY: function(el) {
  14741. var p,
  14742. pe,
  14743. b,
  14744. bt,
  14745. bl,
  14746. dbd,
  14747. x = 0,
  14748. y = 0,
  14749. scroll,
  14750. hasAbsolute,
  14751. bd = (doc.body || doc.documentElement),
  14752. ret = [0,0];
  14753. el = Ext.getDom(el);
  14754. if(el != doc && el != bd){
  14755. hasAbsolute = fly(el).isStyle("position", "absolute");
  14756. // IE has the potential to throw when getBoundingClientRect called
  14757. // on element not attached to dom
  14758. if (Ext.isIE) {
  14759. try {
  14760. b = el.getBoundingClientRect();
  14761. } catch (ex) {
  14762. b = { left: 0, top: 0 }
  14763. }
  14764. } else {
  14765. b = el.getBoundingClientRect();
  14766. }
  14767. scroll = fly(document).getScroll();
  14768. ret = [Math.round(b.left + scroll.left), Math.round(b.top + scroll.top)];
  14769. }
  14770. return ret;
  14771. },
  14772. setXY: function(el, xy) {
  14773. (el = Ext.fly(el, '_setXY')).position();
  14774. var pts = el.translatePoints(xy),
  14775. style = el.dom.style,
  14776. pos;
  14777. for (pos in pts) {
  14778. if (!isNaN(pts[pos])) {
  14779. style[pos] = pts[pos] + "px";
  14780. }
  14781. }
  14782. },
  14783. setX: function(el, x) {
  14784. Ext.dom.Element.setXY(el, [x, false]);
  14785. },
  14786. setY: function(el, y) {
  14787. Ext.dom.Element.setXY(el, [false, y]);
  14788. },
  14789. /**
  14790. * Serializes a DOM form into a url encoded string
  14791. * @param {Object} form The form
  14792. * @return {String} The url encoded form
  14793. */
  14794. serializeForm: function(form) {
  14795. var fElements = form.elements || (document.forms[form] || Ext.getDom(form)).elements,
  14796. hasSubmit = false,
  14797. encoder = encodeURIComponent,
  14798. data = '',
  14799. eLen = fElements.length,
  14800. element, name, type, options, hasValue, e,
  14801. o, oLen, opt;
  14802. for (e = 0; e < eLen; e++) {
  14803. element = fElements[e];
  14804. name = element.name;
  14805. type = element.type;
  14806. options = element.options;
  14807. if (!element.disabled && name) {
  14808. if (/select-(one|multiple)/i.test(type)) {
  14809. oLen = options.length;
  14810. for (o = 0; o < oLen; o++) {
  14811. opt = options[o];
  14812. if (opt.selected) {
  14813. hasValue = opt.hasAttribute ? opt.hasAttribute('value') : opt.getAttributeNode('value').specified;
  14814. data += Ext.String.format("{0}={1}&", encoder(name), encoder(hasValue ? opt.value : opt.text));
  14815. }
  14816. }
  14817. } else if (!(/file|undefined|reset|button/i.test(type))) {
  14818. if (!(/radio|checkbox/i.test(type) && !element.checked) && !(type == 'submit' && hasSubmit)) {
  14819. data += encoder(name) + '=' + encoder(element.value) + '&';
  14820. hasSubmit = /submit/i.test(type);
  14821. }
  14822. }
  14823. }
  14824. }
  14825. return data.substr(0, data.length - 1);
  14826. }
  14827. });
  14828. })();
  14829. /**
  14830. * @class Ext.dom.AbstractElement
  14831. */
  14832. Ext.dom.AbstractElement.override({
  14833. /**
  14834. * Gets the x,y coordinates specified by the anchor position on the element.
  14835. * @param {String} [anchor] The specified anchor position (defaults to "c"). See {@link Ext.dom.Element#alignTo}
  14836. * for details on supported anchor positions.
  14837. * @param {Boolean} [local] True to get the local (element top/left-relative) anchor position instead
  14838. * of page coordinates
  14839. * @param {Object} [size] An object containing the size to use for calculating anchor position
  14840. * {width: (target width), height: (target height)} (defaults to the element's current size)
  14841. * @return {Array} [x, y] An array containing the element's x and y coordinates
  14842. */
  14843. getAnchorXY: function(anchor, local, size) {
  14844. //Passing a different size is useful for pre-calculating anchors,
  14845. //especially for anchored animations that change the el size.
  14846. anchor = (anchor || "tl").toLowerCase();
  14847. size = size || {};
  14848. var me = this,
  14849. vp = me.dom == document.body || me.dom == document,
  14850. width = size.width || vp ? window.innerWidth: me.getWidth(),
  14851. height = size.height || vp ? window.innerHeight: me.getHeight(),
  14852. xy,
  14853. rnd = Math.round,
  14854. myXY = me.getXY(),
  14855. extraX = vp ? 0: !local ? myXY[0] : 0,
  14856. extraY = vp ? 0: !local ? myXY[1] : 0,
  14857. hash = {
  14858. c: [rnd(width * 0.5), rnd(height * 0.5)],
  14859. t: [rnd(width * 0.5), 0],
  14860. l: [0, rnd(height * 0.5)],
  14861. r: [width, rnd(height * 0.5)],
  14862. b: [rnd(width * 0.5), height],
  14863. tl: [0, 0],
  14864. bl: [0, height],
  14865. br: [width, height],
  14866. tr: [width, 0]
  14867. };
  14868. xy = hash[anchor];
  14869. return [xy[0] + extraX, xy[1] + extraY];
  14870. },
  14871. alignToRe: /^([a-z]+)-([a-z]+)(\?)?$/,
  14872. /**
  14873. * Gets the x,y coordinates to align this element with another element. See {@link Ext.dom.Element#alignTo} for more info on the
  14874. * supported position values.
  14875. * @param {Ext.Element/HTMLElement/String} element The element to align to.
  14876. * @param {String} [position="tl-bl?"] The position to align to.
  14877. * @param {Array} [offsets=[0,0]] Offset the positioning by [x, y]
  14878. * @return {Array} [x, y]
  14879. */
  14880. getAlignToXY: function(el, position, offsets, local) {
  14881. local = !!local;
  14882. el = Ext.get(el);
  14883. offsets = offsets || [0, 0];
  14884. if (!position || position == '?') {
  14885. position = 'tl-bl?';
  14886. }
  14887. else if (! (/-/).test(position) && position !== "") {
  14888. position = 'tl-' + position;
  14889. }
  14890. position = position.toLowerCase();
  14891. var me = this,
  14892. matches = position.match(this.alignToRe),
  14893. dw = window.innerWidth,
  14894. dh = window.innerHeight,
  14895. p1 = "",
  14896. p2 = "",
  14897. a1,
  14898. a2,
  14899. x,
  14900. y,
  14901. swapX,
  14902. swapY,
  14903. p1x,
  14904. p1y,
  14905. p2x,
  14906. p2y,
  14907. width,
  14908. height,
  14909. region,
  14910. constrain;
  14911. if (!matches) {
  14912. throw "Element.alignTo with an invalid alignment " + position;
  14913. }
  14914. p1 = matches[1];
  14915. p2 = matches[2];
  14916. constrain = !!matches[3];
  14917. //Subtract the aligned el's internal xy from the target's offset xy
  14918. //plus custom offset to get the aligned el's new offset xy
  14919. a1 = me.getAnchorXY(p1, true);
  14920. a2 = el.getAnchorXY(p2, local);
  14921. x = a2[0] - a1[0] + offsets[0];
  14922. y = a2[1] - a1[1] + offsets[1];
  14923. if (constrain) {
  14924. width = me.getWidth();
  14925. height = me.getHeight();
  14926. region = el.getPageBox();
  14927. //If we are at a viewport boundary and the aligned el is anchored on a target border that is
  14928. //perpendicular to the vp border, allow the aligned el to slide on that border,
  14929. //otherwise swap the aligned el to the opposite border of the target.
  14930. p1y = p1.charAt(0);
  14931. p1x = p1.charAt(p1.length - 1);
  14932. p2y = p2.charAt(0);
  14933. p2x = p2.charAt(p2.length - 1);
  14934. swapY = ((p1y == "t" && p2y == "b") || (p1y == "b" && p2y == "t"));
  14935. swapX = ((p1x == "r" && p2x == "l") || (p1x == "l" && p2x == "r"));
  14936. if (x + width > dw) {
  14937. x = swapX ? region.left - width: dw - width;
  14938. }
  14939. if (x < 0) {
  14940. x = swapX ? region.right: 0;
  14941. }
  14942. if (y + height > dh) {
  14943. y = swapY ? region.top - height: dh - height;
  14944. }
  14945. if (y < 0) {
  14946. y = swapY ? region.bottom: 0;
  14947. }
  14948. }
  14949. return [x, y];
  14950. },
  14951. // private
  14952. getAnchor: function(){
  14953. var data = (this.$cache || this.getCache()).data,
  14954. anchor;
  14955. if (!this.dom) {
  14956. return;
  14957. }
  14958. anchor = data._anchor;
  14959. if(!anchor){
  14960. anchor = data._anchor = {};
  14961. }
  14962. return anchor;
  14963. },
  14964. // private ==> used outside of core
  14965. adjustForConstraints: function(xy, parent) {
  14966. var vector = this.getConstrainVector(parent, xy);
  14967. if (vector) {
  14968. xy[0] += vector[0];
  14969. xy[1] += vector[1];
  14970. }
  14971. return xy;
  14972. }
  14973. });
  14974. /**
  14975. * @class Ext.dom.AbstractElement
  14976. */
  14977. Ext.dom.AbstractElement.addMethods({
  14978. /**
  14979. * Appends the passed element(s) to this element
  14980. * @param {String/HTMLElement/Ext.dom.AbstractElement} el
  14981. * The id of the node, a DOM Node or an existing Element.
  14982. * @return {Ext.dom.AbstractElement} This element
  14983. */
  14984. appendChild: function(el) {
  14985. return Ext.get(el).appendTo(this);
  14986. },
  14987. /**
  14988. * Appends this element to the passed element
  14989. * @param {String/HTMLElement/Ext.dom.AbstractElement} el The new parent element.
  14990. * The id of the node, a DOM Node or an existing Element.
  14991. * @return {Ext.dom.AbstractElement} This element
  14992. */
  14993. appendTo: function(el) {
  14994. Ext.getDom(el).appendChild(this.dom);
  14995. return this;
  14996. },
  14997. /**
  14998. * Inserts this element before the passed element in the DOM
  14999. * @param {String/HTMLElement/Ext.dom.AbstractElement} el The element before which this element will be inserted.
  15000. * The id of the node, a DOM Node or an existing Element.
  15001. * @return {Ext.dom.AbstractElement} This element
  15002. */
  15003. insertBefore: function(el) {
  15004. el = Ext.getDom(el);
  15005. el.parentNode.insertBefore(this.dom, el);
  15006. return this;
  15007. },
  15008. /**
  15009. * Inserts this element after the passed element in the DOM
  15010. * @param {String/HTMLElement/Ext.dom.AbstractElement} el The element to insert after.
  15011. * The id of the node, a DOM Node or an existing Element.
  15012. * @return {Ext.dom.AbstractElement} This element
  15013. */
  15014. insertAfter: function(el) {
  15015. el = Ext.getDom(el);
  15016. el.parentNode.insertBefore(this.dom, el.nextSibling);
  15017. return this;
  15018. },
  15019. /**
  15020. * Inserts (or creates) an element (or DomHelper config) as the first child of this element
  15021. * @param {String/HTMLElement/Ext.dom.AbstractElement/Object} el The id or element to insert or a DomHelper config
  15022. * to create and insert
  15023. * @return {Ext.dom.AbstractElement} The new child
  15024. */
  15025. insertFirst: function(el, returnDom) {
  15026. el = el || {};
  15027. if (el.nodeType || el.dom || typeof el == 'string') { // element
  15028. el = Ext.getDom(el);
  15029. this.dom.insertBefore(el, this.dom.firstChild);
  15030. return !returnDom ? Ext.get(el) : el;
  15031. }
  15032. else { // dh config
  15033. return this.createChild(el, this.dom.firstChild, returnDom);
  15034. }
  15035. },
  15036. /**
  15037. * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
  15038. * @param {String/HTMLElement/Ext.dom.AbstractElement/Object/Array} el The id, element to insert or a DomHelper config
  15039. * to create and insert *or* an array of any of those.
  15040. * @param {String} [where='before'] 'before' or 'after'
  15041. * @param {Boolean} [returnDom=false] True to return the .;ll;l,raw DOM element instead of Ext.dom.AbstractElement
  15042. * @return {Ext.dom.AbstractElement} The inserted Element. If an array is passed, the last inserted element is returned.
  15043. */
  15044. insertSibling: function(el, where, returnDom){
  15045. var me = this,
  15046. isAfter = (where || 'before').toLowerCase() == 'after',
  15047. rt, insertEl, eLen, e;
  15048. if (Ext.isArray(el)) {
  15049. insertEl = me;
  15050. eLen = el.length;
  15051. for (e = 0; e < eLen; e++) {
  15052. rt = Ext.fly(insertEl, '_internal').insertSibling(el[e], where, returnDom);
  15053. if (isAfter) {
  15054. insertEl = rt;
  15055. }
  15056. }
  15057. return rt;
  15058. }
  15059. el = el || {};
  15060. if(el.nodeType || el.dom){
  15061. rt = me.dom.parentNode.insertBefore(Ext.getDom(el), isAfter ? me.dom.nextSibling : me.dom);
  15062. if (!returnDom) {
  15063. rt = Ext.get(rt);
  15064. }
  15065. }else{
  15066. if (isAfter && !me.dom.nextSibling) {
  15067. rt = Ext.core.DomHelper.append(me.dom.parentNode, el, !returnDom);
  15068. } else {
  15069. rt = Ext.core.DomHelper[isAfter ? 'insertAfter' : 'insertBefore'](me.dom, el, !returnDom);
  15070. }
  15071. }
  15072. return rt;
  15073. },
  15074. /**
  15075. * Replaces the passed element with this element
  15076. * @param {String/HTMLElement/Ext.dom.AbstractElement} el The element to replace.
  15077. * The id of the node, a DOM Node or an existing Element.
  15078. * @return {Ext.dom.AbstractElement} This element
  15079. */
  15080. replace: function(el) {
  15081. el = Ext.get(el);
  15082. this.insertBefore(el);
  15083. el.remove();
  15084. return this;
  15085. },
  15086. /**
  15087. * Replaces this element with the passed element
  15088. * @param {String/HTMLElement/Ext.dom.AbstractElement/Object} el The new element (id of the node, a DOM Node
  15089. * or an existing Element) or a DomHelper config of an element to create
  15090. * @return {Ext.dom.AbstractElement} This element
  15091. */
  15092. replaceWith: function(el){
  15093. var me = this;
  15094. if(el.nodeType || el.dom || typeof el == 'string'){
  15095. el = Ext.get(el);
  15096. me.dom.parentNode.insertBefore(el, me.dom);
  15097. }else{
  15098. el = Ext.core.DomHelper.insertBefore(me.dom, el);
  15099. }
  15100. delete Ext.cache[me.id];
  15101. Ext.removeNode(me.dom);
  15102. me.id = Ext.id(me.dom = el);
  15103. Ext.dom.AbstractElement.addToCache(me.isFlyweight ? new Ext.dom.AbstractElement(me.dom) : me);
  15104. return me;
  15105. },
  15106. /**
  15107. * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
  15108. * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be
  15109. * automatically generated with the specified attributes.
  15110. * @param {HTMLElement} [insertBefore] a child element of this element
  15111. * @param {Boolean} [returnDom=false] true to return the dom node instead of creating an Element
  15112. * @return {Ext.dom.AbstractElement} The new child element
  15113. */
  15114. createChild: function(config, insertBefore, returnDom) {
  15115. config = config || {tag:'div'};
  15116. if (insertBefore) {
  15117. return Ext.core.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
  15118. }
  15119. else {
  15120. return Ext.core.DomHelper[!this.dom.firstChild ? 'insertFirst' : 'append'](this.dom, config, returnDom !== true);
  15121. }
  15122. },
  15123. /**
  15124. * Creates and wraps this element with another element
  15125. * @param {Object} [config] DomHelper element config object for the wrapper element or null for an empty div
  15126. * @param {Boolean} [returnDom=false] True to return the raw DOM element instead of Ext.dom.AbstractElement
  15127. * @return {HTMLElement/Ext.dom.AbstractElement} The newly created wrapper element
  15128. */
  15129. wrap: function(config, returnDom) {
  15130. var newEl = Ext.core.DomHelper.insertBefore(this.dom, config || {tag: "div"}, !returnDom),
  15131. d = newEl.dom || newEl;
  15132. d.appendChild(this.dom);
  15133. return newEl;
  15134. },
  15135. /**
  15136. * Inserts an html fragment into this element
  15137. * @param {String} where Where to insert the html in relation to this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
  15138. * See {@link Ext.dom.Helper#insertHtml} for details.
  15139. * @param {String} html The HTML fragment
  15140. * @param {Boolean} [returnEl=false] True to return an Ext.dom.AbstractElement
  15141. * @return {HTMLElement/Ext.dom.AbstractElement} The inserted node (or nearest related if more than 1 inserted)
  15142. */
  15143. insertHtml: function(where, html, returnEl) {
  15144. var el = Ext.core.DomHelper.insertHtml(where, this.dom, html);
  15145. return returnEl ? Ext.get(el) : el;
  15146. }
  15147. });
  15148. /**
  15149. * @class Ext.dom.AbstractElement
  15150. */
  15151. (function(){
  15152. var Element = Ext.dom.AbstractElement;
  15153. Element.override({
  15154. /**
  15155. * Gets the current X position of the element based on page coordinates. Element must be part of the DOM
  15156. * tree to have page coordinates (display:none or elements not appended return false).
  15157. * @return {Number} The X position of the element
  15158. */
  15159. getX: function(el) {
  15160. return this.getXY(el)[0];
  15161. },
  15162. /**
  15163. * Gets the current Y position of the element based on page coordinates. Element must be part of the DOM
  15164. * tree to have page coordinates (display:none or elements not appended return false).
  15165. * @return {Number} The Y position of the element
  15166. */
  15167. getY: function(el) {
  15168. return this.getXY(el)[1];
  15169. },
  15170. /**
  15171. * Gets the current position of the element based on page coordinates. Element must be part of the DOM
  15172. * tree to have page coordinates (display:none or elements not appended return false).
  15173. * @return {Array} The XY position of the element
  15174. */
  15175. getXY: function() {
  15176. // @FEATUREDETECT
  15177. var point = window.webkitConvertPointFromNodeToPage(this.dom, new WebKitPoint(0, 0));
  15178. return [point.x, point.y];
  15179. },
  15180. /**
  15181. * Returns the offsets of this element from the passed element. Both element must be part of the DOM
  15182. * tree and not have display:none to have page coordinates.
  15183. * @param {Ext.Element/HTMLElement/String} element The element to get the offsets from.
  15184. * @return {Array} The XY page offsets (e.g. [100, -200])
  15185. */
  15186. getOffsetsTo: function(el){
  15187. var o = this.getXY(),
  15188. e = Ext.fly(el, '_internal').getXY();
  15189. return [o[0]-e[0],o[1]-e[1]];
  15190. },
  15191. /**
  15192. * Sets the X position of the element based on page coordinates. Element must be part of the DOM tree
  15193. * to have page coordinates (display:none or elements not appended return false).
  15194. * @param {Number} The X position of the element
  15195. * @param {Boolean/Object} [animate] True for the default animation, or a standard Element
  15196. * animation config object
  15197. * @return {Ext.dom.AbstractElement} this
  15198. */
  15199. setX: function(x){
  15200. return this.setXY([x, this.getY()]);
  15201. },
  15202. /**
  15203. * Sets the Y position of the element based on page coordinates. Element must be part of the DOM tree
  15204. * to have page coordinates (display:none or elements not appended return false).
  15205. * @param {Number} The Y position of the element
  15206. * @param {Boolean/Object} [animate] True for the default animation, or a standard Element
  15207. * animation config object
  15208. * @return {Ext.dom.AbstractElement} this
  15209. */
  15210. setY: function(y) {
  15211. return this.setXY([this.getX(), y]);
  15212. },
  15213. /**
  15214. * Sets the element's left position directly using CSS style (instead of {@link #setX}).
  15215. * @param {String} left The left CSS property value
  15216. * @return {Ext.dom.AbstractElement} this
  15217. */
  15218. setLeft: function(left) {
  15219. this.setStyle('left', Element.addUnits(left));
  15220. return this;
  15221. },
  15222. /**
  15223. * Sets the element's top position directly using CSS style (instead of {@link #setY}).
  15224. * @param {String} top The top CSS property value
  15225. * @return {Ext.dom.AbstractElement} this
  15226. */
  15227. setTop: function(top) {
  15228. this.setStyle('top', Element.addUnits(top));
  15229. return this;
  15230. },
  15231. /**
  15232. * Sets the element's CSS right style.
  15233. * @param {String} right The right CSS property value
  15234. * @return {Ext.dom.AbstractElement} this
  15235. */
  15236. setRight: function(right) {
  15237. this.setStyle('right', Element.addUnits(right));
  15238. return this;
  15239. },
  15240. /**
  15241. * Sets the element's CSS bottom style.
  15242. * @param {String} bottom The bottom CSS property value
  15243. * @return {Ext.dom.AbstractElement} this
  15244. */
  15245. setBottom: function(bottom) {
  15246. this.setStyle('bottom', Element.addUnits(bottom));
  15247. return this;
  15248. },
  15249. /**
  15250. * Sets the position of the element in page coordinates, regardless of how the element is positioned.
  15251. * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
  15252. * @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
  15253. * @param {Boolean/Object} [animate] True for the default animation, or a standard Element animation config object
  15254. * @return {Ext.dom.AbstractElement} this
  15255. */
  15256. setXY: function(pos) {
  15257. var me = this;
  15258. if (arguments.length > 1) {
  15259. pos = [pos, arguments[1]];
  15260. }
  15261. // me.position();
  15262. var pts = me.translatePoints(pos),
  15263. style = me.dom.style;
  15264. for (pos in pts) {
  15265. if (!pts.hasOwnProperty(pos)) {
  15266. continue;
  15267. }
  15268. if (!isNaN(pts[pos])) style[pos] = pts[pos] + "px";
  15269. }
  15270. return me;
  15271. },
  15272. /**
  15273. * Gets the left X coordinate
  15274. * @param {Boolean} local True to get the local css position instead of page coordinate
  15275. * @return {Number}
  15276. */
  15277. getLeft: function(local) {
  15278. return parseInt(this.getStyle('left'), 10) || 0;
  15279. },
  15280. /**
  15281. * Gets the right X coordinate of the element (element X position + element width)
  15282. * @param {Boolean} local True to get the local css position instead of page coordinate
  15283. * @return {Number}
  15284. */
  15285. getRight: function(local) {
  15286. return parseInt(this.getStyle('right'), 10) || 0;
  15287. },
  15288. /**
  15289. * Gets the top Y coordinate
  15290. * @param {Boolean} local True to get the local css position instead of page coordinate
  15291. * @return {Number}
  15292. */
  15293. getTop: function(local) {
  15294. return parseInt(this.getStyle('top'), 10) || 0;
  15295. },
  15296. /**
  15297. * Gets the bottom Y coordinate of the element (element Y position + element height)
  15298. * @param {Boolean} local True to get the local css position instead of page coordinate
  15299. * @return {Number}
  15300. */
  15301. getBottom: function(local) {
  15302. return parseInt(this.getStyle('bottom'), 10) || 0;
  15303. },
  15304. /**
  15305. * Translates the passed page coordinates into left/top css values for this element
  15306. * @param {Number/Array} x The page x or an array containing [x, y]
  15307. * @param {Number} [y] The page y, required if x is not an array
  15308. * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)}
  15309. */
  15310. translatePoints: function(x, y) {
  15311. y = isNaN(x[1]) ? y : x[1];
  15312. x = isNaN(x[0]) ? x : x[0];
  15313. var me = this,
  15314. relative = me.isStyle('position', 'relative'),
  15315. o = me.getXY(),
  15316. l = parseInt(me.getStyle('left'), 10),
  15317. t = parseInt(me.getStyle('top'), 10);
  15318. l = !isNaN(l) ? l : (relative ? 0 : me.dom.offsetLeft);
  15319. t = !isNaN(t) ? t : (relative ? 0 : me.dom.offsetTop);
  15320. return {left: (x - o[0] + l), top: (y - o[1] + t)};
  15321. },
  15322. /**
  15323. * Sets the element's box. Use getBox() on another element to get a box obj.
  15324. * If animate is true then width, height, x and y will be animated concurrently.
  15325. * @param {Object} box The box to fill {x, y, width, height}
  15326. * @param {Boolean} [adjust] Whether to adjust for box-model issues automatically
  15327. * @param {Boolean/Object} [animate] true for the default animation or a standard
  15328. * Element animation config object
  15329. * @return {Ext.dom.AbstractElement} this
  15330. */
  15331. setBox: function(box) {
  15332. var me = this,
  15333. width = box.width,
  15334. height = box.height,
  15335. top = box.top,
  15336. left = box.left;
  15337. if (left !== undefined) {
  15338. me.setLeft(left);
  15339. }
  15340. if (top !== undefined) {
  15341. me.setTop(top);
  15342. }
  15343. if (width !== undefined) {
  15344. me.setWidth(width);
  15345. }
  15346. if (height !== undefined) {
  15347. me.setHeight(height);
  15348. }
  15349. return this;
  15350. },
  15351. /**
  15352. * Return an object defining the area of this Element which can be passed to {@link #setBox} to
  15353. * set another Element's size/location to match this element.
  15354. *
  15355. * @param {Boolean} [contentBox] If true a box for the content of the element is returned.
  15356. * @param {Boolean} [local] If true the element's left and top are returned instead of page x/y.
  15357. * @return {Object} box An object in the format:
  15358. *
  15359. * {
  15360. * x: <Element's X position>,
  15361. * y: <Element's Y position>,
  15362. * width: <Element's width>,
  15363. * height: <Element's height>,
  15364. * bottom: <Element's lower bound>,
  15365. * right: <Element's rightmost bound>
  15366. * }
  15367. *
  15368. * The returned object may also be addressed as an Array where index 0 contains the X position
  15369. * and index 1 contains the Y position. So the result may also be used for {@link #setXY}
  15370. */
  15371. getBox: function(contentBox, local) {
  15372. var me = this,
  15373. dom = me.dom,
  15374. width = dom.offsetWidth,
  15375. height = dom.offsetHeight,
  15376. xy, box, l, r, t, b;
  15377. if (!local) {
  15378. xy = me.getXY();
  15379. }
  15380. else if (contentBox) {
  15381. xy = [0,0];
  15382. }
  15383. else {
  15384. xy = [parseInt(me.getStyle("left"), 10) || 0, parseInt(me.getStyle("top"), 10) || 0];
  15385. }
  15386. if (!contentBox) {
  15387. box = {
  15388. x: xy[0],
  15389. y: xy[1],
  15390. 0: xy[0],
  15391. 1: xy[1],
  15392. width: width,
  15393. height: height
  15394. };
  15395. }
  15396. else {
  15397. l = me.getBorderWidth.call(me, "l") + me.getPadding.call(me, "l");
  15398. r = me.getBorderWidth.call(me, "r") + me.getPadding.call(me, "r");
  15399. t = me.getBorderWidth.call(me, "t") + me.getPadding.call(me, "t");
  15400. b = me.getBorderWidth.call(me, "b") + me.getPadding.call(me, "b");
  15401. box = {
  15402. x: xy[0] + l,
  15403. y: xy[1] + t,
  15404. 0: xy[0] + l,
  15405. 1: xy[1] + t,
  15406. width: width - (l + r),
  15407. height: height - (t + b)
  15408. };
  15409. }
  15410. box.left = box.x;
  15411. box.top = box.y;
  15412. box.right = box.x + box.width;
  15413. box.bottom = box.y + box.height;
  15414. return box;
  15415. },
  15416. /**
  15417. * Return an object defining the area of this Element which can be passed to {@link #setBox} to
  15418. * set another Element's size/location to match this element.
  15419. *
  15420. * @param {Boolean} [asRegion] If true an Ext.util.Region will be returned
  15421. * @return {Object} box An object in the format
  15422. *
  15423. * {
  15424. * x: <Element's X position>,
  15425. * y: <Element's Y position>,
  15426. * width: <Element's width>,
  15427. * height: <Element's height>,
  15428. * bottom: <Element's lower bound>,
  15429. * right: <Element's rightmost bound>
  15430. * }
  15431. *
  15432. * The returned object may also be addressed as an Array where index 0 contains the X position
  15433. * and index 1 contains the Y position. So the result may also be used for {@link #setXY}
  15434. */
  15435. getPageBox: function(getRegion) {
  15436. var me = this,
  15437. el = me.dom,
  15438. w = el.offsetWidth,
  15439. h = el.offsetHeight,
  15440. xy = me.getXY(),
  15441. t = xy[1],
  15442. r = xy[0] + w,
  15443. b = xy[1] + h,
  15444. l = xy[0];
  15445. if (!el) {
  15446. return new Ext.util.Region();
  15447. }
  15448. if (getRegion) {
  15449. return new Ext.util.Region(t, r, b, l);
  15450. }
  15451. else {
  15452. return {
  15453. left: l,
  15454. top: t,
  15455. width: w,
  15456. height: h,
  15457. right: r,
  15458. bottom: b
  15459. };
  15460. }
  15461. }
  15462. });
  15463. })();
  15464. /**
  15465. * @class Ext.dom.AbstractElement
  15466. */
  15467. (function(){
  15468. // local style camelizing for speed
  15469. var Element = Ext.dom.AbstractElement,
  15470. view = document.defaultView,
  15471. array = Ext.Array,
  15472. trimRe = /^\s+|\s+$/g,
  15473. wordsRe = /\w/g,
  15474. spacesRe = /\s+/,
  15475. transparentRe = /^(?:transparent|(?:rgba[(](?:\s*\d+\s*[,]){3}\s*0\s*[)]))$/i,
  15476. hasClassList = Ext.supports.ClassList,
  15477. PADDING = 'padding',
  15478. MARGIN = 'margin',
  15479. BORDER = 'border',
  15480. LEFT_SUFFIX = '-left',
  15481. RIGHT_SUFFIX = '-right',
  15482. TOP_SUFFIX = '-top',
  15483. BOTTOM_SUFFIX = '-bottom',
  15484. WIDTH = '-width',
  15485. // special markup used throughout Ext when box wrapping elements
  15486. borders = {l: BORDER + LEFT_SUFFIX + WIDTH, r: BORDER + RIGHT_SUFFIX + WIDTH, t: BORDER + TOP_SUFFIX + WIDTH, b: BORDER + BOTTOM_SUFFIX + WIDTH},
  15487. paddings = {l: PADDING + LEFT_SUFFIX, r: PADDING + RIGHT_SUFFIX, t: PADDING + TOP_SUFFIX, b: PADDING + BOTTOM_SUFFIX},
  15488. margins = {l: MARGIN + LEFT_SUFFIX, r: MARGIN + RIGHT_SUFFIX, t: MARGIN + TOP_SUFFIX, b: MARGIN + BOTTOM_SUFFIX};
  15489. Element.override({
  15490. /**
  15491. * This shared object is keyed by style name (e.g., 'margin-left' or 'marginLeft'). The
  15492. * values are objects with the following properties:
  15493. *
  15494. * * `name` (String) : The actual name to be presented to the DOM. This is typically the value
  15495. * returned by {@link #normalize}.
  15496. * * `get` (Function) : A hook function that will perform the get on this style. These
  15497. * functions receive "(dom, el)" arguments. The `dom` parameter is the DOM Element
  15498. * from which to get ths tyle. The `el` argument (may be null) is the Ext.Element.
  15499. * * `set` (Function) : A hook function that will perform the set on this style. These
  15500. * functions receive "(dom, value, el)" arguments. The `dom` parameter is the DOM Element
  15501. * from which to get ths tyle. The `value` parameter is the new value for the style. The
  15502. * `el` argument (may be null) is the Ext.Element.
  15503. *
  15504. * The `this` pointer is the object that contains `get` or `set`, which means that
  15505. * `this.name` can be accessed if needed. The hook functions are both optional.
  15506. * @private
  15507. */
  15508. styleHooks: {},
  15509. // private
  15510. addStyles : function(sides, styles){
  15511. var totalSize = 0,
  15512. sidesArr = (sides || '').match(wordsRe),
  15513. i,
  15514. len = sidesArr.length,
  15515. side,
  15516. styleSides = [];
  15517. if (len == 1) {
  15518. totalSize = Math.abs(parseFloat(this.getStyle(styles[sidesArr[0]])) || 0);
  15519. } else if (len) {
  15520. for (i = 0; i < len; i++) {
  15521. side = sidesArr[i];
  15522. styleSides.push(styles[side]);
  15523. }
  15524. //Gather all at once, returning a hash
  15525. styleSides = this.getStyle(styleSides);
  15526. for (i=0; i < len; i++) {
  15527. side = sidesArr[i];
  15528. totalSize += Math.abs(parseFloat(styleSides[styles[side]]) || 0);
  15529. }
  15530. }
  15531. return totalSize;
  15532. },
  15533. /**
  15534. * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
  15535. * @param {String/String[]} className The CSS classes to add separated by space, or an array of classes
  15536. * @return {Ext.dom.Element} this
  15537. * @method
  15538. */
  15539. addCls: hasClassList ?
  15540. function (className) {
  15541. var me = this,
  15542. dom = me.dom,
  15543. classList,
  15544. newCls,
  15545. i,
  15546. len,
  15547. cls;
  15548. if (typeof(className) == 'string') {
  15549. // split string on spaces to make an array of className
  15550. className = className.replace(trimRe, '').split(spacesRe);
  15551. }
  15552. // the gain we have here is that we can skip parsing className and use the
  15553. // classList.contains method, so now O(M) not O(M+N)
  15554. if (dom && className && !!(len = className.length)) {
  15555. if (!dom.className) {
  15556. dom.className = className.join(' ');
  15557. } else {
  15558. classList = dom.classList;
  15559. for (i = 0; i < len; ++i) {
  15560. cls = className[i];
  15561. if (cls) {
  15562. if (!classList.contains(cls)) {
  15563. if (newCls) {
  15564. newCls.push(cls);
  15565. } else {
  15566. newCls = dom.className.replace(trimRe, '');
  15567. newCls = newCls ? [newCls, cls] : [cls];
  15568. }
  15569. }
  15570. }
  15571. }
  15572. if (newCls) {
  15573. dom.className = newCls.join(' '); // write to DOM once
  15574. }
  15575. }
  15576. }
  15577. return me;
  15578. } :
  15579. function(className) {
  15580. var me = this,
  15581. dom = me.dom,
  15582. changed,
  15583. elClasses;
  15584. if (dom && className && className.length) {
  15585. elClasses = Ext.Element.mergeClsList(dom.className, className);
  15586. if (elClasses.changed) {
  15587. dom.className = elClasses.join(' '); // write to DOM once
  15588. }
  15589. }
  15590. return me;
  15591. },
  15592. /**
  15593. * Removes one or more CSS classes from the element.
  15594. * @param {String/String[]} className The CSS classes to remove separated by space, or an array of classes
  15595. * @return {Ext.dom.Element} this
  15596. */
  15597. removeCls: function(className) {
  15598. var me = this,
  15599. dom = me.dom,
  15600. len,
  15601. elClasses;
  15602. if (typeof(className) == 'string') {
  15603. // split string on spaces to make an array of className
  15604. className = className.replace(trimRe, '').split(spacesRe);
  15605. }
  15606. if (dom && dom.className && className && !!(len = className.length)) {
  15607. if (len == 1 && hasClassList) {
  15608. if (className[0]) {
  15609. dom.classList.remove(className[0]); // one DOM write
  15610. }
  15611. } else {
  15612. elClasses = Ext.Element.removeCls(dom.className, className);
  15613. if (elClasses.changed) {
  15614. dom.className = elClasses.join(' ');
  15615. }
  15616. }
  15617. }
  15618. return me;
  15619. },
  15620. /**
  15621. * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
  15622. * @param {String/String[]} className The CSS class to add, or an array of classes
  15623. * @return {Ext.dom.Element} this
  15624. */
  15625. radioCls: function(className) {
  15626. var cn = this.dom.parentNode.childNodes,
  15627. v;
  15628. className = Ext.isArray(className) ? className: [className];
  15629. for (var i = 0, len = cn.length; i < len; i++) {
  15630. v = cn[i];
  15631. if (v && v.nodeType == 1) {
  15632. Ext.fly(v, '_internal').removeCls(className);
  15633. }
  15634. };
  15635. return this.addCls(className);
  15636. },
  15637. /**
  15638. * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
  15639. * @param {String} className The CSS class to toggle
  15640. * @return {Ext.dom.Element} this
  15641. * @method
  15642. */
  15643. toggleCls: hasClassList ?
  15644. function (className) {
  15645. var me = this,
  15646. dom = me.dom;
  15647. if (dom) {
  15648. className = className.replace(trimRe, '');
  15649. if (className) {
  15650. dom.classList.toggle(className);
  15651. }
  15652. }
  15653. return me;
  15654. } :
  15655. function(className) {
  15656. var me = this;
  15657. return me.hasCls(className) ? me.removeCls(className) : me.addCls(className);
  15658. },
  15659. /**
  15660. * Checks if the specified CSS class exists on this element's DOM node.
  15661. * @param {String} className The CSS class to check for
  15662. * @return {Boolean} True if the class exists, else false
  15663. * @method
  15664. */
  15665. hasCls: hasClassList ?
  15666. function (className) {
  15667. var dom = this.dom;
  15668. return (dom && className) ? dom.classList.contains(className) : false;
  15669. } :
  15670. function(className) {
  15671. var dom = this.dom;
  15672. return dom ? className && (' '+dom.className+' ').indexOf(' '+className+' ') != -1 : false;
  15673. },
  15674. /**
  15675. * Replaces a CSS class on the element with another. If the old name does not exist, the new name will simply be added.
  15676. * @param {String} oldClassName The CSS class to replace
  15677. * @param {String} newClassName The replacement CSS class
  15678. * @return {Ext.dom.Element} this
  15679. */
  15680. replaceCls: function(oldClassName, newClassName){
  15681. return this.removeCls(oldClassName).addCls(newClassName);
  15682. },
  15683. /**
  15684. * Checks if the current value of a style is equal to a given value.
  15685. * @param {String} style property whose value is returned.
  15686. * @param {String} value to check against.
  15687. * @return {Boolean} true for when the current value equals the given value.
  15688. */
  15689. isStyle: function(style, val) {
  15690. return this.getStyle(style) == val;
  15691. },
  15692. /**
  15693. * Returns a named style property based on computed/currentStyle (primary) and
  15694. * inline-style if primary is not available.
  15695. *
  15696. * @param {String/String[]} property The style property (or multiple property names
  15697. * in an array) whose value is returned.
  15698. * @param {Boolean} [inline=false] if `true` only inline styles will be returned.
  15699. * @return {String/Object} The current value of the style property for this element
  15700. * (or a hash of named style values if multiple property arguments are requested).
  15701. * @method
  15702. */
  15703. getStyle: function (property, inline) {
  15704. var me = this,
  15705. dom = me.dom,
  15706. multiple = typeof property != 'string',
  15707. hooks = me.styleHooks,
  15708. prop = property,
  15709. props = prop,
  15710. len = 1,
  15711. domStyle, camel, values, hook, out, style, i;
  15712. if (multiple) {
  15713. values = {};
  15714. prop = props[0];
  15715. i = 0;
  15716. if (!(len = props.length)) {
  15717. return values;
  15718. }
  15719. }
  15720. if (!dom || dom.documentElement) {
  15721. return values || '';
  15722. }
  15723. domStyle = dom.style;
  15724. if (inline) {
  15725. style = domStyle;
  15726. } else {
  15727. // Caution: Firefox will not render "presentation" (ie. computed styles) in
  15728. // iframes that are display:none or those inheriting display:none. Similar
  15729. // issues with legacy Safari.
  15730. //
  15731. style = dom.ownerDocument.defaultView.getComputedStyle(dom, null);
  15732. // fallback to inline style if rendering context not available
  15733. if (!style) {
  15734. inline = true;
  15735. style = domStyle;
  15736. }
  15737. }
  15738. do {
  15739. hook = hooks[prop];
  15740. if (!hook) {
  15741. hooks[prop] = hook = { name: Element.normalize(prop) };
  15742. }
  15743. if (hook.get) {
  15744. out = hook.get(dom, me, inline, style);
  15745. } else {
  15746. camel = hook.name;
  15747. out = style[camel];
  15748. }
  15749. if (!multiple) {
  15750. return out;
  15751. }
  15752. values[prop] = out;
  15753. prop = props[++i];
  15754. } while (i < len);
  15755. return values;
  15756. },
  15757. getStyles: function () {
  15758. var props = Ext.Array.slice(arguments),
  15759. len = props.length,
  15760. inline;
  15761. if (len && typeof props[len-1] == 'boolean') {
  15762. inline = props.pop();
  15763. }
  15764. return this.getStyle(props, inline);
  15765. },
  15766. /**
  15767. * Returns true if the value of the given property is visually transparent. This
  15768. * may be due to a 'transparent' style value or an rgba value with 0 in the alpha
  15769. * component.
  15770. * @param {String} prop The style property whose value is to be tested.
  15771. * @return {Boolean} True if the style property is visually transparent.
  15772. */
  15773. isTransparent: function (prop) {
  15774. var value = this.getStyle(prop);
  15775. return value ? transparentRe.test(value) : false;
  15776. },
  15777. /**
  15778. * Wrapper for setting style properties, also takes single object parameter of multiple styles.
  15779. * @param {String/Object} property The style property to be set, or an object of multiple styles.
  15780. * @param {String} [value] The value to apply to the given property, or null if an object was passed.
  15781. * @return {Ext.dom.Element} this
  15782. */
  15783. setStyle: function(prop, value) {
  15784. var me = this,
  15785. dom = me.dom,
  15786. hooks = me.styleHooks,
  15787. style = dom.style,
  15788. name = prop,
  15789. hook;
  15790. // we don't promote the 2-arg form to object-form to avoid the overhead...
  15791. if (typeof name == 'string') {
  15792. hook = hooks[name];
  15793. if (!hook) {
  15794. hooks[name] = hook = { name: Element.normalize(name) };
  15795. }
  15796. value = (value == null) ? '' : value;
  15797. if (hook.set) {
  15798. hook.set(dom, value, me);
  15799. } else {
  15800. style[hook.name] = value;
  15801. }
  15802. if (hook.afterSet) {
  15803. hook.afterSet(dom, value, me);
  15804. }
  15805. } else {
  15806. for (name in prop) {
  15807. if (prop.hasOwnProperty(name)) {
  15808. hook = hooks[name];
  15809. if (!hook) {
  15810. hooks[name] = hook = { name: Element.normalize(name) };
  15811. }
  15812. value = prop[name];
  15813. value = (value == null) ? '' : value;
  15814. if (hook.set) {
  15815. hook.set(dom, value, me);
  15816. } else {
  15817. style[hook.name] = value;
  15818. }
  15819. if (hook.afterSet) {
  15820. hook.afterSet(dom, value, me);
  15821. }
  15822. }
  15823. }
  15824. }
  15825. return me;
  15826. },
  15827. /**
  15828. * Returns the offset height of the element
  15829. * @param {Boolean} [contentHeight] true to get the height minus borders and padding
  15830. * @return {Number} The element's height
  15831. */
  15832. getHeight: function(contentHeight) {
  15833. var dom = this.dom,
  15834. height = contentHeight ? (dom.clientHeight - this.getPadding("tb")) : dom.offsetHeight;
  15835. return height > 0 ? height: 0;
  15836. },
  15837. /**
  15838. * Returns the offset width of the element
  15839. * @param {Boolean} [contentWidth] true to get the width minus borders and padding
  15840. * @return {Number} The element's width
  15841. */
  15842. getWidth: function(contentWidth) {
  15843. var dom = this.dom,
  15844. width = contentWidth ? (dom.clientWidth - this.getPadding("lr")) : dom.offsetWidth;
  15845. return width > 0 ? width: 0;
  15846. },
  15847. /**
  15848. * Set the width of this Element.
  15849. * @param {Number/String} width The new width. This may be one of:
  15850. *
  15851. * - A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels).
  15852. * - A String used to set the CSS width style. Animation may **not** be used.
  15853. *
  15854. * @param {Boolean/Object} [animate] true for the default animation or a standard Element animation config object
  15855. * @return {Ext.dom.Element} this
  15856. */
  15857. setWidth: function(width) {
  15858. var me = this;
  15859. me.dom.style.width = Element.addUnits(width);
  15860. return me;
  15861. },
  15862. /**
  15863. * Set the height of this Element.
  15864. *
  15865. * // change the height to 200px and animate with default configuration
  15866. * Ext.fly('elementId').setHeight(200, true);
  15867. *
  15868. * // change the height to 150px and animate with a custom configuration
  15869. * Ext.fly('elId').setHeight(150, {
  15870. * duration : .5, // animation will have a duration of .5 seconds
  15871. * // will change the content to "finished"
  15872. * callback: function(){ this.{@link #update}("finished"); }
  15873. * });
  15874. *
  15875. * @param {Number/String} height The new height. This may be one of:
  15876. *
  15877. * - A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels.)
  15878. * - A String used to set the CSS height style. Animation may **not** be used.
  15879. *
  15880. * @param {Boolean/Object} [animate] true for the default animation or a standard Element animation config object
  15881. * @return {Ext.dom.Element} this
  15882. */
  15883. setHeight: function(height) {
  15884. var me = this;
  15885. me.dom.style.height = Element.addUnits(height);
  15886. return me;
  15887. },
  15888. /**
  15889. * Gets the width of the border(s) for the specified side(s)
  15890. * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
  15891. * passing `'lr'` would get the border **l**eft width + the border **r**ight width.
  15892. * @return {Number} The width of the sides passed added together
  15893. */
  15894. getBorderWidth: function(side){
  15895. return this.addStyles(side, borders);
  15896. },
  15897. /**
  15898. * Gets the width of the padding(s) for the specified side(s)
  15899. * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
  15900. * passing `'lr'` would get the padding **l**eft + the padding **r**ight.
  15901. * @return {Number} The padding of the sides passed added together
  15902. */
  15903. getPadding: function(side){
  15904. return this.addStyles(side, paddings);
  15905. },
  15906. margins : margins,
  15907. /**
  15908. * More flexible version of {@link #setStyle} for setting style properties.
  15909. * @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
  15910. * a function which returns such a specification.
  15911. * @return {Ext.dom.Element} this
  15912. */
  15913. applyStyles: function(styles) {
  15914. if (styles) {
  15915. var i,
  15916. len,
  15917. dom = this.dom;
  15918. if (typeof styles == 'function') {
  15919. styles = styles.call();
  15920. }
  15921. if (typeof styles == 'string') {
  15922. styles = Ext.util.Format.trim(styles).split(/\s*(?::|;)\s*/);
  15923. for (i = 0, len = styles.length; i < len;) {
  15924. dom.style[Element.normalize(styles[i++])] = styles[i++];
  15925. }
  15926. }
  15927. else if (typeof styles == 'object') {
  15928. this.setStyle(styles);
  15929. }
  15930. }
  15931. },
  15932. /**
  15933. * Set the size of this Element. If animation is true, both width and height will be animated concurrently.
  15934. * @param {Number/String} width The new width. This may be one of:
  15935. *
  15936. * - A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels).
  15937. * - A String used to set the CSS width style. Animation may **not** be used.
  15938. * - A size object in the format `{width: widthValue, height: heightValue}`.
  15939. *
  15940. * @param {Number/String} height The new height. This may be one of:
  15941. *
  15942. * - A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels).
  15943. * - A String used to set the CSS height style. Animation may **not** be used.
  15944. *
  15945. * @param {Boolean/Object} [animate] true for the default animation or a standard Element animation config object
  15946. * @return {Ext.dom.Element} this
  15947. */
  15948. setSize: function(width, height) {
  15949. var me = this,
  15950. style = me.dom.style;
  15951. if (Ext.isObject(width)) {
  15952. // in case of object from getSize()
  15953. height = width.height;
  15954. width = width.width;
  15955. }
  15956. style.width = Element.addUnits(width);
  15957. style.height = Element.addUnits(height);
  15958. return me;
  15959. },
  15960. /**
  15961. * Returns the dimensions of the element available to lay content out in.
  15962. *
  15963. * If the element (or any ancestor element) has CSS style `display: none`, the dimensions will be zero.
  15964. *
  15965. * Example:
  15966. *
  15967. * var vpSize = Ext.getBody().getViewSize();
  15968. *
  15969. * // all Windows created afterwards will have a default value of 90% height and 95% width
  15970. * Ext.Window.override({
  15971. * width: vpSize.width * 0.9,
  15972. * height: vpSize.height * 0.95
  15973. * });
  15974. * // To handle window resizing you would have to hook onto onWindowResize.
  15975. *
  15976. * getViewSize utilizes clientHeight/clientWidth which excludes sizing of scrollbars.
  15977. * To obtain the size including scrollbars, use getStyleSize
  15978. *
  15979. * Sizing of the document body is handled at the adapter level which handles special cases for IE and strict modes, etc.
  15980. *
  15981. * @return {Object} Object describing width and height.
  15982. * @return {Number} return.width
  15983. * @return {Number} return.height
  15984. */
  15985. getViewSize: function() {
  15986. var doc = document,
  15987. dom = this.dom;
  15988. if (dom == doc || dom == doc.body) {
  15989. return {
  15990. width: Element.getViewportWidth(),
  15991. height: Element.getViewportHeight()
  15992. };
  15993. }
  15994. else {
  15995. return {
  15996. width: dom.clientWidth,
  15997. height: dom.clientHeight
  15998. };
  15999. }
  16000. },
  16001. /**
  16002. * Returns the size of the element.
  16003. * @param {Boolean} [contentSize] true to get the width/size minus borders and padding
  16004. * @return {Object} An object containing the element's size:
  16005. * @return {Number} return.width
  16006. * @return {Number} return.height
  16007. */
  16008. getSize: function(contentSize) {
  16009. var dom = this.dom;
  16010. return {
  16011. width: Math.max(0, contentSize ? (dom.clientWidth - this.getPadding("lr")) : dom.offsetWidth),
  16012. height: Math.max(0, contentSize ? (dom.clientHeight - this.getPadding("tb")) : dom.offsetHeight)
  16013. };
  16014. },
  16015. /**
  16016. * Forces the browser to repaint this element
  16017. * @return {Ext.dom.Element} this
  16018. */
  16019. repaint: function(){
  16020. var dom = this.dom;
  16021. this.addCls(Ext.baseCSSPrefix + 'repaint');
  16022. setTimeout(function(){
  16023. Ext.fly(dom).removeCls(Ext.baseCSSPrefix + 'repaint');
  16024. }, 1);
  16025. return this;
  16026. },
  16027. /**
  16028. * Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
  16029. * then it returns the calculated width of the sides (see getPadding)
  16030. * @param {String} [sides] Any combination of l, r, t, b to get the sum of those sides
  16031. * @return {Object/Number}
  16032. */
  16033. getMargin: function(side){
  16034. var me = this,
  16035. hash = {t:"top", l:"left", r:"right", b: "bottom"},
  16036. key,
  16037. o,
  16038. margins;
  16039. if (!side) {
  16040. margins = [];
  16041. for (key in me.margins) {
  16042. if(me.margins.hasOwnProperty(key)) {
  16043. margins.push(me.margins[key]);
  16044. }
  16045. }
  16046. o = me.getStyle(margins);
  16047. if(o && typeof o == 'object') {
  16048. //now mixin nomalized values (from hash table)
  16049. for (key in me.margins) {
  16050. if(me.margins.hasOwnProperty(key)) {
  16051. o[hash[key]] = parseFloat(o[me.margins[key]]) || 0;
  16052. }
  16053. }
  16054. }
  16055. return o;
  16056. } else {
  16057. return me.addStyles.call(me, side, me.margins);
  16058. }
  16059. },
  16060. /**
  16061. * Puts a mask over this element to disable user interaction. Requires core.css.
  16062. * This method can only be applied to elements which accept child nodes.
  16063. * @param {String} [msg] A message to display in the mask
  16064. * @param {String} [msgCls] A css class to apply to the msg element
  16065. */
  16066. mask: function(msg, msgCls, transparent) {
  16067. var me = this,
  16068. dom = me.dom,
  16069. data = (me.$cache || me.getCache()).data,
  16070. el = data.mask,
  16071. mask,
  16072. size,
  16073. cls = '',
  16074. prefix = Ext.baseCSSPrefix;
  16075. me.addCls(prefix + 'masked');
  16076. if (me.getStyle("position") == "static") {
  16077. me.addCls(prefix + 'masked-relative');
  16078. }
  16079. if (el) {
  16080. el.remove();
  16081. }
  16082. if (msgCls && typeof msgCls == 'string' ) {
  16083. cls = ' ' + msgCls;
  16084. }
  16085. else {
  16086. cls = ' ' + prefix + 'mask-gray';
  16087. }
  16088. mask = me.createChild({
  16089. cls: prefix + 'mask' + ((transparent !== false) ? '' : (' ' + prefix + 'mask-gray')),
  16090. html: msg ? ('<div class="' + (msgCls || (prefix + 'mask-message')) + '">' + msg + '</div>') : ''
  16091. });
  16092. size = me.getSize();
  16093. data.mask = mask;
  16094. if (dom === document.body) {
  16095. size.height = window.innerHeight;
  16096. if (me.orientationHandler) {
  16097. Ext.EventManager.unOrientationChange(me.orientationHandler, me);
  16098. }
  16099. me.orientationHandler = function() {
  16100. size = me.getSize();
  16101. size.height = window.innerHeight;
  16102. mask.setSize(size);
  16103. };
  16104. Ext.EventManager.onOrientationChange(me.orientationHandler, me);
  16105. }
  16106. mask.setSize(size);
  16107. if (Ext.is.iPad) {
  16108. Ext.repaint();
  16109. }
  16110. },
  16111. /**
  16112. * Removes a previously applied mask.
  16113. */
  16114. unmask: function() {
  16115. var me = this,
  16116. data = (me.$cache || me.getCache()).data,
  16117. mask = data.mask,
  16118. prefix = Ext.baseCSSPrefix;
  16119. if (mask) {
  16120. mask.remove();
  16121. delete data.mask;
  16122. }
  16123. me.removeCls([prefix + 'masked', prefix + 'masked-relative']);
  16124. if (me.dom === document.body) {
  16125. Ext.EventManager.unOrientationChange(me.orientationHandler, me);
  16126. delete me.orientationHandler;
  16127. }
  16128. }
  16129. });
  16130. /**
  16131. * Creates mappings for 'margin-before' to 'marginLeft' (etc.) given the output
  16132. * map and an ordering pair (e.g., ['left', 'right']). The ordering pair is in
  16133. * before/after order.
  16134. */
  16135. Element.populateStyleMap = function (map, order) {
  16136. var baseStyles = ['margin-', 'padding-', 'border-width-'],
  16137. beforeAfter = ['before', 'after'],
  16138. index, style, name, i;
  16139. for (index = baseStyles.length; index--; ) {
  16140. for (i = 2; i--; ) {
  16141. style = baseStyles[index] + beforeAfter[i]; // margin-before
  16142. // ex: maps margin-before and marginBefore to marginLeft
  16143. map[Element.normalize(style)] = map[style] = {
  16144. name: Element.normalize(baseStyles[index] + order[i])
  16145. };
  16146. }
  16147. }
  16148. };
  16149. Ext.onReady(function () {
  16150. var supports = Ext.supports;
  16151. function fixTransparent (dom, el, inline, style) {
  16152. var value = style[this.name] || '';
  16153. return transparentRe.test(value) ? 'transparent' : value;
  16154. }
  16155. function fixRightMargin (dom, el, inline, style) {
  16156. var result = style.marginRight,
  16157. domStyle, display;
  16158. // Ignore cases when the margin is correctly reported as 0, the bug only shows
  16159. // numbers larger.
  16160. if (result != '0px') {
  16161. domStyle = dom.style;
  16162. display = domStyle.display;
  16163. domStyle.display = 'inline-block';
  16164. result = (inline ? style : dom.ownerDocument.defaultView.getComputedStyle(dom, null)).marginRight;
  16165. domStyle.display = display;
  16166. }
  16167. return result;
  16168. }
  16169. function fixRightMarginAndInputFocus (dom, el, inline, style) {
  16170. var result = style.marginRight,
  16171. domStyle, cleaner, display;
  16172. if (result != '0px') {
  16173. domStyle = dom.style;
  16174. cleaner = Element.getRightMarginFixCleaner(dom);
  16175. display = domStyle.display;
  16176. domStyle.display = 'inline-block';
  16177. result = (inline ? style : dom.ownerDocument.defaultView.getComputedStyle(dom, '')).marginRight;
  16178. domStyle.display = display;
  16179. cleaner();
  16180. }
  16181. return result;
  16182. }
  16183. var styleHooks = Element.prototype.styleHooks;
  16184. // Populate the LTR flavors of margin-before et.al. (see Ext.rtl.AbstractElement):
  16185. Element.populateStyleMap(styleHooks, ['left', 'right']);
  16186. // Ext.supports needs to be initialized (we run very early in the onready sequence),
  16187. // but it is OK to call Ext.supports.init() more times than necessary...
  16188. if (supports.init) {
  16189. supports.init();
  16190. }
  16191. // Fix bug caused by this: https://bugs.webkit.org/show_bug.cgi?id=13343
  16192. if (!supports.RightMargin) {
  16193. styleHooks.marginRight = styleHooks['margin-right'] = {
  16194. name: 'marginRight',
  16195. // TODO - Touch should use conditional compilation here or ensure that the
  16196. // underlying Ext.supports flags are set correctly...
  16197. get: (supports.DisplayChangeInputSelectionBug || supports.DisplayChangeTextAreaSelectionBug) ?
  16198. fixRightMarginAndInputFocus : fixRightMargin
  16199. };
  16200. }
  16201. if (!supports.TransparentColor) {
  16202. var colorStyles = ['background-color', 'border-color', 'color', 'outline-color'];
  16203. for (var i = colorStyles.length; i--; ) {
  16204. var name = colorStyles[i],
  16205. camel = Element.normalize(name);
  16206. styleHooks[name] = styleHooks[camel] = {
  16207. name: camel,
  16208. get: fixTransparent
  16209. };
  16210. }
  16211. }
  16212. });
  16213. })();
  16214. /**
  16215. * @class Ext.dom.AbstractElement
  16216. */
  16217. Ext.dom.AbstractElement.override({
  16218. /**
  16219. * 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)
  16220. * @param {String} selector The simple selector to test
  16221. * @param {Number/String/HTMLElement/Ext.Element} [limit]
  16222. * The max depth to search as a number or an element which causes the upward traversal to stop
  16223. * and is <b>not</b> considered for inclusion as the result. (defaults to 50 || document.documentElement)
  16224. * @param {Boolean} [returnEl=false] True to return a Ext.Element object instead of DOM node
  16225. * @return {HTMLElement} The matching DOM node (or null if no match was found)
  16226. */
  16227. findParent: function(simpleSelector, limit, returnEl) {
  16228. var target = this.dom,
  16229. topmost = document.documentElement,
  16230. depth = 0,
  16231. stopEl;
  16232. limit = limit || 50;
  16233. if (isNaN(limit)) {
  16234. stopEl = Ext.getDom(limit);
  16235. limit = Number.MAX_VALUE;
  16236. }
  16237. while (target && target.nodeType == 1 && depth < limit && target != topmost && target != stopEl) {
  16238. if (Ext.DomQuery.is(target, simpleSelector)) {
  16239. return returnEl ? Ext.get(target) : target;
  16240. }
  16241. depth++;
  16242. target = target.parentNode;
  16243. }
  16244. return null;
  16245. },
  16246. /**
  16247. * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
  16248. * @param {String} selector The simple selector to test
  16249. * @param {Number/String/HTMLElement/Ext.Element} [limit]
  16250. * The max depth to search as a number or an element which causes the upward traversal to stop
  16251. * and is <b>not</b> considered for inclusion as the result. (defaults to 50 || document.documentElement)
  16252. * @param {Boolean} [returnEl=false] True to return a Ext.Element object instead of DOM node
  16253. * @return {HTMLElement} The matching DOM node (or null if no match was found)
  16254. */
  16255. findParentNode: function(simpleSelector, limit, returnEl) {
  16256. var p = Ext.fly(this.dom.parentNode, '_internal');
  16257. return p ? p.findParent(simpleSelector, limit, returnEl) : null;
  16258. },
  16259. /**
  16260. * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
  16261. * This is a shortcut for findParentNode() that always returns an Ext.dom.Element.
  16262. * @param {String} selector The simple selector to test
  16263. * @param {Number/String/HTMLElement/Ext.Element} [limit]
  16264. * The max depth to search as a number or an element which causes the upward traversal to stop
  16265. * and is <b>not</b> considered for inclusion as the result. (defaults to 50 || document.documentElement)
  16266. * @return {Ext.Element} The matching DOM node (or null if no match was found)
  16267. */
  16268. up: function(simpleSelector, limit) {
  16269. return this.findParentNode(simpleSelector, limit, true);
  16270. },
  16271. /**
  16272. * Creates a {@link Ext.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
  16273. * @param {String} selector The CSS selector
  16274. * @return {Ext.CompositeElement} The composite element
  16275. */
  16276. select: function(selector, composite) {
  16277. return Ext.dom.Element.select(selector, this.dom, composite);
  16278. },
  16279. /**
  16280. * Selects child nodes based on the passed CSS selector (the selector should not contain an id).
  16281. * @param {String} selector The CSS selector
  16282. * @return {HTMLElement[]} An array of the matched nodes
  16283. */
  16284. query: function(selector) {
  16285. return Ext.DomQuery.select(selector, this.dom);
  16286. },
  16287. /**
  16288. * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
  16289. * @param {String} selector The CSS selector
  16290. * @param {Boolean} [returnDom=false] True to return the DOM node instead of Ext.dom.Element
  16291. * @return {HTMLElement/Ext.dom.Element} The child Ext.dom.Element (or DOM node if returnDom = true)
  16292. */
  16293. down: function(selector, returnDom) {
  16294. var n = Ext.DomQuery.selectNode(selector, this.dom);
  16295. return returnDom ? n : Ext.get(n);
  16296. },
  16297. /**
  16298. * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
  16299. * @param {String} selector The CSS selector
  16300. * @param {Boolean} [returnDom=false] True to return the DOM node instead of Ext.dom.Element.
  16301. * @return {HTMLElement/Ext.dom.Element} The child Ext.dom.Element (or DOM node if returnDom = true)
  16302. */
  16303. child: function(selector, returnDom) {
  16304. var node,
  16305. me = this,
  16306. id;
  16307. id = Ext.get(me).id;
  16308. // Escape . or :
  16309. id = id.replace(/[\.:]/g, "\\$0");
  16310. node = Ext.DomQuery.selectNode('#' + id + " > " + selector, me.dom);
  16311. return returnDom ? node : Ext.get(node);
  16312. },
  16313. /**
  16314. * Gets the parent node for this element, optionally chaining up trying to match a selector
  16315. * @param {String} [selector] Find a parent node that matches the passed simple selector
  16316. * @param {Boolean} [returnDom=false] True to return a raw dom node instead of an Ext.dom.Element
  16317. * @return {Ext.dom.Element/HTMLElement} The parent node or null
  16318. */
  16319. parent: function(selector, returnDom) {
  16320. return this.matchNode('parentNode', 'parentNode', selector, returnDom);
  16321. },
  16322. /**
  16323. * Gets the next sibling, skipping text nodes
  16324. * @param {String} [selector] Find the next sibling that matches the passed simple selector
  16325. * @param {Boolean} [returnDom=false] True to return a raw dom node instead of an Ext.dom.Element
  16326. * @return {Ext.dom.Element/HTMLElement} The next sibling or null
  16327. */
  16328. next: function(selector, returnDom) {
  16329. return this.matchNode('nextSibling', 'nextSibling', selector, returnDom);
  16330. },
  16331. /**
  16332. * Gets the previous sibling, skipping text nodes
  16333. * @param {String} [selector] Find the previous sibling that matches the passed simple selector
  16334. * @param {Boolean} [returnDom=false] True to return a raw dom node instead of an Ext.dom.Element
  16335. * @return {Ext.dom.Element/HTMLElement} The previous sibling or null
  16336. */
  16337. prev: function(selector, returnDom) {
  16338. return this.matchNode('previousSibling', 'previousSibling', selector, returnDom);
  16339. },
  16340. /**
  16341. * Gets the first child, skipping text nodes
  16342. * @param {String} [selector] Find the next sibling that matches the passed simple selector
  16343. * @param {Boolean} [returnDom=false] True to return a raw dom node instead of an Ext.dom.Element
  16344. * @return {Ext.dom.Element/HTMLElement} The first child or null
  16345. */
  16346. first: function(selector, returnDom) {
  16347. return this.matchNode('nextSibling', 'firstChild', selector, returnDom);
  16348. },
  16349. /**
  16350. * Gets the last child, skipping text nodes
  16351. * @param {String} [selector] Find the previous sibling that matches the passed simple selector
  16352. * @param {Boolean} [returnDom=false] True to return a raw dom node instead of an Ext.dom.Element
  16353. * @return {Ext.dom.Element/HTMLElement} The last child or null
  16354. */
  16355. last: function(selector, returnDom) {
  16356. return this.matchNode('previousSibling', 'lastChild', selector, returnDom);
  16357. },
  16358. matchNode: function(dir, start, selector, returnDom) {
  16359. if (!this.dom) {
  16360. return null;
  16361. }
  16362. var n = this.dom[start];
  16363. while (n) {
  16364. if (n.nodeType == 1 && (!selector || Ext.DomQuery.is(n, selector))) {
  16365. return !returnDom ? Ext.get(n) : n;
  16366. }
  16367. n = n[dir];
  16368. }
  16369. return null;
  16370. },
  16371. isAncestor: function(element) {
  16372. return this.self.isAncestor.call(this.self, this.dom, element);
  16373. }
  16374. });
  16375. /**
  16376. * @class Ext.dom.Helper
  16377. * @extends Ext.dom.AbstractHelper
  16378. * @alternateClassName Ext.DomHelper
  16379. * @alternateClassName Ext.core.DomHelper
  16380. * @singleton
  16381. *
  16382. * The DomHelper class provides a layer of abstraction from DOM and transparently supports creating elements via DOM or
  16383. * using HTML fragments. It also has the ability to create HTML fragment templates from your DOM building code.
  16384. *
  16385. * # DomHelper element specification object
  16386. *
  16387. * A specification object is used when creating elements. Attributes of this object are assumed to be element
  16388. * attributes, except for 4 special attributes:
  16389. *
  16390. * - **tag** - The tag name of the element.
  16391. * - **children** or **cn** - An array of the same kind of element definition objects to be created and appended.
  16392. * These can be nested as deep as you want.
  16393. * - **cls** - The class attribute of the element. This will end up being either the "class" attribute on a HTML
  16394. * fragment or className for a DOM node, depending on whether DomHelper is using fragments or DOM.
  16395. * - **html** - The innerHTML for the element.
  16396. *
  16397. * **NOTE:** For other arbitrary attributes, the value will currently **not** be automatically HTML-escaped prior to
  16398. * building the element's HTML string. This means that if your attribute value contains special characters that would
  16399. * not normally be allowed in a double-quoted attribute value, you **must** manually HTML-encode it beforehand (see
  16400. * {@link Ext.String#htmlEncode}) or risk malformed HTML being created. This behavior may change in a future release.
  16401. *
  16402. * # Insertion methods
  16403. *
  16404. * Commonly used insertion methods:
  16405. *
  16406. * - **{@link #append}**
  16407. * - **{@link #insertBefore}**
  16408. * - **{@link #insertAfter}**
  16409. * - **{@link #overwrite}**
  16410. * - **{@link #createTemplate}**
  16411. * - **{@link #insertHtml}**
  16412. *
  16413. * # Example
  16414. *
  16415. * This is an example, where an unordered list with 3 children items is appended to an existing element with
  16416. * id 'my-div':
  16417. *
  16418. * var dh = Ext.DomHelper; // create shorthand alias
  16419. * // specification object
  16420. * var spec = {
  16421. * id: 'my-ul',
  16422. * tag: 'ul',
  16423. * cls: 'my-list',
  16424. * // append children after creating
  16425. * children: [ // may also specify 'cn' instead of 'children'
  16426. * {tag: 'li', id: 'item0', html: 'List Item 0'},
  16427. * {tag: 'li', id: 'item1', html: 'List Item 1'},
  16428. * {tag: 'li', id: 'item2', html: 'List Item 2'}
  16429. * ]
  16430. * };
  16431. * var list = dh.append(
  16432. * 'my-div', // the context element 'my-div' can either be the id or the actual node
  16433. * spec // the specification object
  16434. * );
  16435. *
  16436. * Element creation specification parameters in this class may also be passed as an Array of specification objects. This
  16437. * can be used to insert multiple sibling nodes into an existing container very efficiently. For example, to add more
  16438. * list items to the example above:
  16439. *
  16440. * dh.append('my-ul', [
  16441. * {tag: 'li', id: 'item3', html: 'List Item 3'},
  16442. * {tag: 'li', id: 'item4', html: 'List Item 4'}
  16443. * ]);
  16444. *
  16445. * # Templating
  16446. *
  16447. * The real power is in the built-in templating. Instead of creating or appending any elements, {@link #createTemplate}
  16448. * returns a Template object which can be used over and over to insert new elements. Revisiting the example above, we
  16449. * could utilize templating this time:
  16450. *
  16451. * // create the node
  16452. * var list = dh.append('my-div', {tag: 'ul', cls: 'my-list'});
  16453. * // get template
  16454. * var tpl = dh.createTemplate({tag: 'li', id: 'item{0}', html: 'List Item {0}'});
  16455. *
  16456. * for(var i = 0; i < 5, i++){
  16457. * tpl.append(list, [i]); // use template to append to the actual node
  16458. * }
  16459. *
  16460. * An example using a template:
  16461. *
  16462. * var html = '<a id="{0}" href="{1}" class="nav">{2}</a>';
  16463. *
  16464. * var tpl = new Ext.DomHelper.createTemplate(html);
  16465. * tpl.append('blog-roll', ['link1', 'http://www.edspencer.net/', "Ed's Site"]);
  16466. * tpl.append('blog-roll', ['link2', 'http://www.dustindiaz.com/', "Dustin's Site"]);
  16467. *
  16468. * The same example using named parameters:
  16469. *
  16470. * var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
  16471. *
  16472. * var tpl = new Ext.DomHelper.createTemplate(html);
  16473. * tpl.append('blog-roll', {
  16474. * id: 'link1',
  16475. * url: 'http://www.edspencer.net/',
  16476. * text: "Ed's Site"
  16477. * });
  16478. * tpl.append('blog-roll', {
  16479. * id: 'link2',
  16480. * url: 'http://www.dustindiaz.com/',
  16481. * text: "Dustin's Site"
  16482. * });
  16483. *
  16484. * # Compiling Templates
  16485. *
  16486. * Templates are applied using regular expressions. The performance is great, but if you are adding a bunch of DOM
  16487. * elements using the same template, you can increase performance even further by {@link Ext.Template#compile
  16488. * "compiling"} the template. The way "{@link Ext.Template#compile compile()}" works is the template is parsed and
  16489. * broken up at the different variable points and a dynamic function is created and eval'ed. The generated function
  16490. * performs string concatenation of these parts and the passed variables instead of using regular expressions.
  16491. *
  16492. * var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
  16493. *
  16494. * var tpl = new Ext.DomHelper.createTemplate(html);
  16495. * tpl.compile();
  16496. *
  16497. * //... use template like normal
  16498. *
  16499. * # Performance Boost
  16500. *
  16501. * DomHelper will transparently create HTML fragments when it can. Using HTML fragments instead of DOM can significantly
  16502. * boost performance.
  16503. *
  16504. * Element creation specification parameters may also be strings. If {@link #useDom} is false, then the string is used
  16505. * as innerHTML. If {@link #useDom} is true, a string specification results in the creation of a text node. Usage:
  16506. *
  16507. * Ext.DomHelper.useDom = true; // force it to use DOM; reduces performance
  16508. *
  16509. */
  16510. (function() {
  16511. // kill repeat to save bytes
  16512. var afterbegin = 'afterbegin',
  16513. afterend = 'afterend',
  16514. beforebegin = 'beforebegin',
  16515. beforeend = 'beforeend',
  16516. ts = '<table>',
  16517. te = '</table>',
  16518. tbs = ts+'<tbody>',
  16519. tbe = '</tbody>'+te,
  16520. trs = tbs + '<tr>',
  16521. tre = '</tr>'+tbe;
  16522. Ext.define('Ext.dom.Helper', {
  16523. extend: 'Ext.dom.AbstractHelper',
  16524. tempTableEl: null,
  16525. tableRe: /^table|tbody|tr|td$/i,
  16526. tableElRe: /td|tr|tbody/i,
  16527. /**
  16528. * @property {Boolean} useDom
  16529. * True to force the use of DOM instead of html fragments.
  16530. */
  16531. useDom : false,
  16532. /**
  16533. * Creates new DOM element(s) without inserting them to the document.
  16534. * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
  16535. * @return {HTMLElement} The new uninserted node
  16536. */
  16537. createDom: function(o, parentNode){
  16538. var el,
  16539. doc = document,
  16540. useSet,
  16541. attr,
  16542. val,
  16543. cn;
  16544. if (Ext.isArray(o)) { // Allow Arrays of siblings to be inserted
  16545. el = doc.createDocumentFragment(); // in one shot using a DocumentFragment
  16546. for (var i = 0, l = o.length; i < l; i++) {
  16547. this.createDom(o[i], el);
  16548. }
  16549. } else if (typeof o == 'string') { // Allow a string as a child spec.
  16550. el = doc.createTextNode(o);
  16551. } else {
  16552. el = doc.createElement(o.tag || 'div');
  16553. useSet = !!el.setAttribute; // In IE some elements don't have setAttribute
  16554. for (attr in o) {
  16555. if (!this.confRe.test(attr)) {
  16556. val = o[attr];
  16557. if (attr == 'cls') {
  16558. el.className = val;
  16559. } else {
  16560. if (useSet) {
  16561. el.setAttribute(attr, val);
  16562. } else {
  16563. el[attr] = val;
  16564. }
  16565. }
  16566. }
  16567. }
  16568. Ext.DomHelper.applyStyles(el, o.style);
  16569. if ((cn = o.children || o.cn)) {
  16570. this.createDom(cn, el);
  16571. } else if (o.html) {
  16572. el.innerHTML = o.html;
  16573. }
  16574. }
  16575. if (parentNode) {
  16576. parentNode.appendChild(el);
  16577. }
  16578. return el;
  16579. },
  16580. ieTable: function(depth, s, h, e){
  16581. this.tempTableEl.innerHTML = [s, h, e].join('');
  16582. var i = -1,
  16583. el = this.tempTableEl,
  16584. ns;
  16585. while (++i < depth) {
  16586. el = el.firstChild;
  16587. }
  16588. // If the result is multiple siblings, then encapsulate them into one fragment.
  16589. ns = el.nextSibling;
  16590. if (ns) {
  16591. var df = document.createDocumentFragment();
  16592. while (el) {
  16593. ns = el.nextSibling;
  16594. df.appendChild(el);
  16595. el = ns;
  16596. }
  16597. el = df;
  16598. }
  16599. return el;
  16600. },
  16601. /**
  16602. * @ignore
  16603. * Nasty code for IE's broken table implementation
  16604. */
  16605. insertIntoTable: function(tag, where, el, html) {
  16606. var node,
  16607. before;
  16608. this.tempTableEl = this.tempTableEl || document.createElement('div');
  16609. if (tag == 'td' && (where == afterbegin || where == beforeend) ||
  16610. !this.tableElRe.test(tag) && (where == beforebegin || where == afterend)) {
  16611. return null;
  16612. }
  16613. before = where == beforebegin ? el :
  16614. where == afterend ? el.nextSibling :
  16615. where == afterbegin ? el.firstChild : null;
  16616. if (where == beforebegin || where == afterend) {
  16617. el = el.parentNode;
  16618. }
  16619. if (tag == 'td' || (tag == 'tr' && (where == beforeend || where == afterbegin))) {
  16620. node = this.ieTable(4, trs, html, tre);
  16621. } else if ((tag == 'tbody' && (where == beforeend || where == afterbegin)) ||
  16622. (tag == 'tr' && (where == beforebegin || where == afterend))) {
  16623. node = this.ieTable(3, tbs, html, tbe);
  16624. } else {
  16625. node = this.ieTable(2, ts, html, te);
  16626. }
  16627. el.insertBefore(node, before);
  16628. return node;
  16629. },
  16630. /**
  16631. * @ignore
  16632. * Fix for IE9 createContextualFragment missing method
  16633. */
  16634. createContextualFragment: function(html){
  16635. var div = document.createElement("div"),
  16636. fragment = document.createDocumentFragment(),
  16637. i = 0,
  16638. length, childNodes;
  16639. div.innerHTML = html;
  16640. childNodes = div.childNodes;
  16641. length = childNodes.length;
  16642. for (; i < length; i++) {
  16643. fragment.appendChild(childNodes[i].cloneNode(true));
  16644. }
  16645. return fragment;
  16646. },
  16647. applyStyles: function(el, styles) {
  16648. if (styles) {
  16649. el = Ext.fly(el);
  16650. if (typeof styles == "function") {
  16651. styles = styles.call();
  16652. }
  16653. if (typeof styles == "string") {
  16654. styles = Ext.dom.Element.parseStyles(styles);
  16655. }
  16656. if (typeof styles == "object") {
  16657. el.setStyle(styles);
  16658. }
  16659. }
  16660. },
  16661. /**
  16662. * Alias for {@link #markup}.
  16663. * @inheritdoc Ext.dom.AbstractHelper#markup
  16664. */
  16665. createHtml: function(spec) {
  16666. return this.markup(spec);
  16667. },
  16668. doInsert: function(el, o, returnElement, pos, sibling, append) {
  16669. el = el.dom || Ext.getDom(el);
  16670. var newNode;
  16671. if (this.useDom) {
  16672. newNode = this.createDom(o, null);
  16673. if (append) {
  16674. el.appendChild(newNode);
  16675. }
  16676. else {
  16677. (sibling == 'firstChild' ? el : el.parentNode).insertBefore(newNode, el[sibling] || el);
  16678. }
  16679. } else {
  16680. newNode = this.insertHtml(pos, el, this.markup(o));
  16681. }
  16682. return returnElement ? Ext.get(newNode, true) : newNode;
  16683. },
  16684. insertHtml: function(where, el, html) {
  16685. var hash = {},
  16686. hashVal,
  16687. range,
  16688. rangeEl,
  16689. setStart,
  16690. frag,
  16691. rs;
  16692. where = where.toLowerCase();
  16693. // add these here because they are used in both branches of the condition.
  16694. hash[beforebegin] = ['BeforeBegin', 'previousSibling'];
  16695. hash[afterend] = ['AfterEnd', 'nextSibling'];
  16696. // if IE and context element is an HTMLElement
  16697. if (el.insertAdjacentHTML) {
  16698. if (this.tableRe.test(el.tagName) && (rs = this.insertIntoTable(el.tagName.toLowerCase(), where, el, html))) {
  16699. return rs;
  16700. }
  16701. // add these two to the hash.
  16702. hash[afterbegin] = ['AfterBegin', 'firstChild'];
  16703. hash[beforeend] = ['BeforeEnd', 'lastChild'];
  16704. if ((hashVal = hash[where])) {
  16705. el.insertAdjacentHTML(hashVal[0], html);
  16706. return el[hashVal[1]];
  16707. }
  16708. // if (not IE and context element is an HTMLElement) or TextNode
  16709. } else {
  16710. // we cannot insert anything inside a textnode so...
  16711. if (Ext.isTextNode(el)) {
  16712. where = where === 'afterbegin' ? 'beforebegin' : where;
  16713. where = where === 'beforeend' ? 'afterend' : where;
  16714. }
  16715. range = Ext.supports.CreateContextualFragment ? el.ownerDocument.createRange() : undefined;
  16716. setStart = 'setStart' + (this.endRe.test(where) ? 'After' : 'Before');
  16717. if (hash[where]) {
  16718. if (range) {
  16719. range[setStart](el);
  16720. frag = range.createContextualFragment(html);
  16721. } else {
  16722. frag = this.createContextualFragment(html);
  16723. }
  16724. el.parentNode.insertBefore(frag, where == beforebegin ? el : el.nextSibling);
  16725. return el[(where == beforebegin ? 'previous' : 'next') + 'Sibling'];
  16726. } else {
  16727. rangeEl = (where == afterbegin ? 'first' : 'last') + 'Child';
  16728. if (el.firstChild) {
  16729. if (range) {
  16730. range[setStart](el[rangeEl]);
  16731. frag = range.createContextualFragment(html);
  16732. } else {
  16733. frag = this.createContextualFragment(html);
  16734. }
  16735. if (where == afterbegin) {
  16736. el.insertBefore(frag, el.firstChild);
  16737. } else {
  16738. el.appendChild(frag);
  16739. }
  16740. } else {
  16741. el.innerHTML = html;
  16742. }
  16743. return el[rangeEl];
  16744. }
  16745. }
  16746. },
  16747. /**
  16748. * Creates a new Ext.Template from the DOM object spec.
  16749. * @param {Object} o The DOM object spec (and children)
  16750. * @return {Ext.Template} The new template
  16751. */
  16752. createTemplate: function(o) {
  16753. var html = this.markup(o);
  16754. return new Ext.Template(html);
  16755. }
  16756. }, function() {
  16757. Ext.ns('Ext.core');
  16758. Ext.DomHelper = Ext.core.DomHelper = new this;
  16759. });
  16760. })();
  16761. /*
  16762. * This is code is also distributed under MIT license for use
  16763. * with jQuery and prototype JavaScript libraries.
  16764. */
  16765. /**
  16766. * @class Ext.dom.Query
  16767. * @alternateClassName Ext.DomQuery
  16768. * @alternateClassName Ext.core.DomQuery
  16769. * @singleton
  16770. *
  16771. * Provides high performance selector/xpath processing by compiling queries into reusable functions. New pseudo classes
  16772. * and matchers can be plugged. It works on HTML and XML documents (if a content node is passed in).
  16773. *
  16774. * DomQuery supports most of the [CSS3 selectors spec][1], along with some custom selectors and basic XPath.
  16775. *
  16776. * All selectors, attribute filters and pseudos below can be combined infinitely in any order. For example
  16777. * `div.foo:nth-child(odd)[@foo=bar].bar:first` would be a perfectly valid selector. Node filters are processed
  16778. * in the order in which they appear, which allows you to optimize your queries for your document structure.
  16779. *
  16780. * ## Element Selectors:
  16781. *
  16782. * - **`*`** any element
  16783. * - **`E`** an element with the tag E
  16784. * - **`E F`** All descendent elements of E that have the tag F
  16785. * - **`E > F`** or **E/F** all direct children elements of E that have the tag F
  16786. * - **`E + F`** all elements with the tag F that are immediately preceded by an element with the tag E
  16787. * - **`E ~ F`** all elements with the tag F that are preceded by a sibling element with the tag E
  16788. *
  16789. * ## Attribute Selectors:
  16790. *
  16791. * The use of `@` and quotes are optional. For example, `div[@foo='bar']` is also a valid attribute selector.
  16792. *
  16793. * - **`E[foo]`** has an attribute "foo"
  16794. * - **`E[foo=bar]`** has an attribute "foo" that equals "bar"
  16795. * - **`E[foo^=bar]`** has an attribute "foo" that starts with "bar"
  16796. * - **`E[foo$=bar]`** has an attribute "foo" that ends with "bar"
  16797. * - **`E[foo*=bar]`** has an attribute "foo" that contains the substring "bar"
  16798. * - **`E[foo%=2]`** has an attribute "foo" that is evenly divisible by 2
  16799. * - **`E[foo!=bar]`** attribute "foo" does not equal "bar"
  16800. *
  16801. * ## Pseudo Classes:
  16802. *
  16803. * - **`E:first-child`** E is the first child of its parent
  16804. * - **`E:last-child`** E is the last child of its parent
  16805. * - **`E:nth-child(_n_)`** E is the _n_th child of its parent (1 based as per the spec)
  16806. * - **`E:nth-child(odd)`** E is an odd child of its parent
  16807. * - **`E:nth-child(even)`** E is an even child of its parent
  16808. * - **`E:only-child`** E is the only child of its parent
  16809. * - **`E:checked`** E is an element that is has a checked attribute that is true (e.g. a radio or checkbox)
  16810. * - **`E:first`** the first E in the resultset
  16811. * - **`E:last`** the last E in the resultset
  16812. * - **`E:nth(_n_)`** the _n_th E in the resultset (1 based)
  16813. * - **`E:odd`** shortcut for :nth-child(odd)
  16814. * - **`E:even`** shortcut for :nth-child(even)
  16815. * - **`E:contains(foo)`** E's innerHTML contains the substring "foo"
  16816. * - **`E:nodeValue(foo)`** E contains a textNode with a nodeValue that equals "foo"
  16817. * - **`E:not(S)`** an E element that does not match simple selector S
  16818. * - **`E:has(S)`** an E element that has a descendent that matches simple selector S
  16819. * - **`E:next(S)`** an E element whose next sibling matches simple selector S
  16820. * - **`E:prev(S)`** an E element whose previous sibling matches simple selector S
  16821. * - **`E:any(S1|S2|S2)`** an E element which matches any of the simple selectors S1, S2 or S3
  16822. *
  16823. * ## CSS Value Selectors:
  16824. *
  16825. * - **`E{display=none}`** css value "display" that equals "none"
  16826. * - **`E{display^=none}`** css value "display" that starts with "none"
  16827. * - **`E{display$=none}`** css value "display" that ends with "none"
  16828. * - **`E{display*=none}`** css value "display" that contains the substring "none"
  16829. * - **`E{display%=2}`** css value "display" that is evenly divisible by 2
  16830. * - **`E{display!=none}`** css value "display" that does not equal "none"
  16831. *
  16832. * [1]: http://www.w3.org/TR/2005/WD-css3-selectors-20051215/#selectors
  16833. */
  16834. Ext.ns('Ext.core');
  16835. Ext.dom.Query = Ext.core.DomQuery = Ext.DomQuery = function(){
  16836. var cache = {},
  16837. simpleCache = {},
  16838. valueCache = {},
  16839. nonSpace = /\S/,
  16840. trimRe = /^\s+|\s+$/g,
  16841. tplRe = /\{(\d+)\}/g,
  16842. modeRe = /^(\s?[\/>+~]\s?|\s|$)/,
  16843. tagTokenRe = /^(#)?([\w\-\*]+)/,
  16844. nthRe = /(\d*)n\+?(\d*)/,
  16845. nthRe2 = /\D/,
  16846. startIdRe = /^\s*\#/,
  16847. // This is for IE MSXML which does not support expandos.
  16848. // IE runs the same speed using setAttribute, however FF slows way down
  16849. // and Safari completely fails so they need to continue to use expandos.
  16850. isIE = window.ActiveXObject ? true : false,
  16851. key = 30803;
  16852. // this eval is stop the compressor from
  16853. // renaming the variable to something shorter
  16854. eval("var batch = 30803;");
  16855. // Retrieve the child node from a particular
  16856. // parent at the specified index.
  16857. function child(parent, index){
  16858. var i = 0,
  16859. n = parent.firstChild;
  16860. while(n){
  16861. if(n.nodeType == 1){
  16862. if(++i == index){
  16863. return n;
  16864. }
  16865. }
  16866. n = n.nextSibling;
  16867. }
  16868. return null;
  16869. }
  16870. // retrieve the next element node
  16871. function next(n){
  16872. while((n = n.nextSibling) && n.nodeType != 1);
  16873. return n;
  16874. }
  16875. // retrieve the previous element node
  16876. function prev(n){
  16877. while((n = n.previousSibling) && n.nodeType != 1);
  16878. return n;
  16879. }
  16880. // Mark each child node with a nodeIndex skipping and
  16881. // removing empty text nodes.
  16882. function children(parent){
  16883. var n = parent.firstChild,
  16884. nodeIndex = -1,
  16885. nextNode;
  16886. while(n){
  16887. nextNode = n.nextSibling;
  16888. // clean worthless empty nodes.
  16889. if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
  16890. parent.removeChild(n);
  16891. }else{
  16892. // add an expando nodeIndex
  16893. n.nodeIndex = ++nodeIndex;
  16894. }
  16895. n = nextNode;
  16896. }
  16897. return this;
  16898. }
  16899. // nodeSet - array of nodes
  16900. // cls - CSS Class
  16901. function byClassName(nodeSet, cls){
  16902. if(!cls){
  16903. return nodeSet;
  16904. }
  16905. var result = [], ri = -1;
  16906. for(var i = 0, ci; ci = nodeSet[i]; i++){
  16907. if((' '+ci.className+' ').indexOf(cls) != -1){
  16908. result[++ri] = ci;
  16909. }
  16910. }
  16911. return result;
  16912. };
  16913. function attrValue(n, attr){
  16914. // if its an array, use the first node.
  16915. if(!n.tagName && typeof n.length != "undefined"){
  16916. n = n[0];
  16917. }
  16918. if(!n){
  16919. return null;
  16920. }
  16921. if(attr == "for"){
  16922. return n.htmlFor;
  16923. }
  16924. if(attr == "class" || attr == "className"){
  16925. return n.className;
  16926. }
  16927. return n.getAttribute(attr) || n[attr];
  16928. };
  16929. // ns - nodes
  16930. // mode - false, /, >, +, ~
  16931. // tagName - defaults to "*"
  16932. function getNodes(ns, mode, tagName){
  16933. var result = [], ri = -1, cs;
  16934. if(!ns){
  16935. return result;
  16936. }
  16937. tagName = tagName || "*";
  16938. // convert to array
  16939. if(typeof ns.getElementsByTagName != "undefined"){
  16940. ns = [ns];
  16941. }
  16942. // no mode specified, grab all elements by tagName
  16943. // at any depth
  16944. if(!mode){
  16945. for(var i = 0, ni; ni = ns[i]; i++){
  16946. cs = ni.getElementsByTagName(tagName);
  16947. for(var j = 0, ci; ci = cs[j]; j++){
  16948. result[++ri] = ci;
  16949. }
  16950. }
  16951. // Direct Child mode (/ or >)
  16952. // E > F or E/F all direct children elements of E that have the tag
  16953. } else if(mode == "/" || mode == ">"){
  16954. var utag = tagName.toUpperCase();
  16955. for(var i = 0, ni, cn; ni = ns[i]; i++){
  16956. cn = ni.childNodes;
  16957. for(var j = 0, cj; cj = cn[j]; j++){
  16958. if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){
  16959. result[++ri] = cj;
  16960. }
  16961. }
  16962. }
  16963. // Immediately Preceding mode (+)
  16964. // E + F all elements with the tag F that are immediately preceded by an element with the tag E
  16965. }else if(mode == "+"){
  16966. var utag = tagName.toUpperCase();
  16967. for(var i = 0, n; n = ns[i]; i++){
  16968. while((n = n.nextSibling) && n.nodeType != 1);
  16969. if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
  16970. result[++ri] = n;
  16971. }
  16972. }
  16973. // Sibling mode (~)
  16974. // E ~ F all elements with the tag F that are preceded by a sibling element with the tag E
  16975. }else if(mode == "~"){
  16976. var utag = tagName.toUpperCase();
  16977. for(var i = 0, n; n = ns[i]; i++){
  16978. while((n = n.nextSibling)){
  16979. if (n.nodeName == utag || n.nodeName == tagName || tagName == '*'){
  16980. result[++ri] = n;
  16981. }
  16982. }
  16983. }
  16984. }
  16985. return result;
  16986. }
  16987. function concat(a, b){
  16988. if(b.slice){
  16989. return a.concat(b);
  16990. }
  16991. for(var i = 0, l = b.length; i < l; i++){
  16992. a[a.length] = b[i];
  16993. }
  16994. return a;
  16995. }
  16996. function byTag(cs, tagName){
  16997. if(cs.tagName || cs == document){
  16998. cs = [cs];
  16999. }
  17000. if(!tagName){
  17001. return cs;
  17002. }
  17003. var result = [], ri = -1;
  17004. tagName = tagName.toLowerCase();
  17005. for(var i = 0, ci; ci = cs[i]; i++){
  17006. if(ci.nodeType == 1 && ci.tagName.toLowerCase() == tagName){
  17007. result[++ri] = ci;
  17008. }
  17009. }
  17010. return result;
  17011. }
  17012. function byId(cs, id){
  17013. if(cs.tagName || cs == document){
  17014. cs = [cs];
  17015. }
  17016. if(!id){
  17017. return cs;
  17018. }
  17019. var result = [], ri = -1;
  17020. for(var i = 0, ci; ci = cs[i]; i++){
  17021. if(ci && ci.id == id){
  17022. result[++ri] = ci;
  17023. return result;
  17024. }
  17025. }
  17026. return result;
  17027. }
  17028. // operators are =, !=, ^=, $=, *=, %=, |= and ~=
  17029. // custom can be "{"
  17030. function byAttribute(cs, attr, value, op, custom){
  17031. var result = [],
  17032. ri = -1,
  17033. useGetStyle = custom == "{",
  17034. fn = Ext.DomQuery.operators[op],
  17035. a,
  17036. xml,
  17037. hasXml;
  17038. for(var i = 0, ci; ci = cs[i]; i++){
  17039. // skip non-element nodes.
  17040. if(ci.nodeType != 1){
  17041. continue;
  17042. }
  17043. // only need to do this for the first node
  17044. if(!hasXml){
  17045. xml = Ext.DomQuery.isXml(ci);
  17046. hasXml = true;
  17047. }
  17048. // we only need to change the property names if we're dealing with html nodes, not XML
  17049. if(!xml){
  17050. if(useGetStyle){
  17051. a = Ext.DomQuery.getStyle(ci, attr);
  17052. } else if (attr == "class" || attr == "className"){
  17053. a = ci.className;
  17054. } else if (attr == "for"){
  17055. a = ci.htmlFor;
  17056. } else if (attr == "href"){
  17057. // getAttribute href bug
  17058. // http://www.glennjones.net/Post/809/getAttributehrefbug.htm
  17059. a = ci.getAttribute("href", 2);
  17060. } else{
  17061. a = ci.getAttribute(attr);
  17062. }
  17063. }else{
  17064. a = ci.getAttribute(attr);
  17065. }
  17066. if((fn && fn(a, value)) || (!fn && a)){
  17067. result[++ri] = ci;
  17068. }
  17069. }
  17070. return result;
  17071. }
  17072. function byPseudo(cs, name, value){
  17073. return Ext.DomQuery.pseudos[name](cs, value);
  17074. }
  17075. function nodupIEXml(cs){
  17076. var d = ++key,
  17077. r;
  17078. cs[0].setAttribute("_nodup", d);
  17079. r = [cs[0]];
  17080. for(var i = 1, len = cs.length; i < len; i++){
  17081. var c = cs[i];
  17082. if(!c.getAttribute("_nodup") != d){
  17083. c.setAttribute("_nodup", d);
  17084. r[r.length] = c;
  17085. }
  17086. }
  17087. for(var i = 0, len = cs.length; i < len; i++){
  17088. cs[i].removeAttribute("_nodup");
  17089. }
  17090. return r;
  17091. }
  17092. function nodup(cs){
  17093. if(!cs){
  17094. return [];
  17095. }
  17096. var len = cs.length, c, i, r = cs, cj, ri = -1;
  17097. if(!len || typeof cs.nodeType != "undefined" || len == 1){
  17098. return cs;
  17099. }
  17100. if(isIE && typeof cs[0].selectSingleNode != "undefined"){
  17101. return nodupIEXml(cs);
  17102. }
  17103. var d = ++key;
  17104. cs[0]._nodup = d;
  17105. for(i = 1; c = cs[i]; i++){
  17106. if(c._nodup != d){
  17107. c._nodup = d;
  17108. }else{
  17109. r = [];
  17110. for(var j = 0; j < i; j++){
  17111. r[++ri] = cs[j];
  17112. }
  17113. for(j = i+1; cj = cs[j]; j++){
  17114. if(cj._nodup != d){
  17115. cj._nodup = d;
  17116. r[++ri] = cj;
  17117. }
  17118. }
  17119. return r;
  17120. }
  17121. }
  17122. return r;
  17123. }
  17124. function quickDiffIEXml(c1, c2){
  17125. var d = ++key,
  17126. r = [];
  17127. for(var i = 0, len = c1.length; i < len; i++){
  17128. c1[i].setAttribute("_qdiff", d);
  17129. }
  17130. for(var i = 0, len = c2.length; i < len; i++){
  17131. if(c2[i].getAttribute("_qdiff") != d){
  17132. r[r.length] = c2[i];
  17133. }
  17134. }
  17135. for(var i = 0, len = c1.length; i < len; i++){
  17136. c1[i].removeAttribute("_qdiff");
  17137. }
  17138. return r;
  17139. }
  17140. function quickDiff(c1, c2){
  17141. var len1 = c1.length,
  17142. d = ++key,
  17143. r = [];
  17144. if(!len1){
  17145. return c2;
  17146. }
  17147. if(isIE && typeof c1[0].selectSingleNode != "undefined"){
  17148. return quickDiffIEXml(c1, c2);
  17149. }
  17150. for(var i = 0; i < len1; i++){
  17151. c1[i]._qdiff = d;
  17152. }
  17153. for(var i = 0, len = c2.length; i < len; i++){
  17154. if(c2[i]._qdiff != d){
  17155. r[r.length] = c2[i];
  17156. }
  17157. }
  17158. return r;
  17159. }
  17160. function quickId(ns, mode, root, id){
  17161. if(ns == root){
  17162. var d = root.ownerDocument || root;
  17163. return d.getElementById(id);
  17164. }
  17165. ns = getNodes(ns, mode, "*");
  17166. return byId(ns, id);
  17167. }
  17168. return {
  17169. getStyle : function(el, name){
  17170. return Ext.fly(el).getStyle(name);
  17171. },
  17172. /**
  17173. * Compiles a selector/xpath query into a reusable function. The returned function
  17174. * takes one parameter "root" (optional), which is the context node from where the query should start.
  17175. * @param {String} selector The selector/xpath query
  17176. * @param {String} [type="select"] Either "select" or "simple" for a simple selector match
  17177. * @return {Function}
  17178. */
  17179. compile : function(path, type){
  17180. type = type || "select";
  17181. // setup fn preamble
  17182. var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"],
  17183. mode,
  17184. lastPath,
  17185. matchers = Ext.DomQuery.matchers,
  17186. matchersLn = matchers.length,
  17187. modeMatch,
  17188. // accept leading mode switch
  17189. lmode = path.match(modeRe);
  17190. if(lmode && lmode[1]){
  17191. fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
  17192. path = path.replace(lmode[1], "");
  17193. }
  17194. // strip leading slashes
  17195. while(path.substr(0, 1)=="/"){
  17196. path = path.substr(1);
  17197. }
  17198. while(path && lastPath != path){
  17199. lastPath = path;
  17200. var tokenMatch = path.match(tagTokenRe);
  17201. if(type == "select"){
  17202. if(tokenMatch){
  17203. // ID Selector
  17204. if(tokenMatch[1] == "#"){
  17205. fn[fn.length] = 'n = quickId(n, mode, root, "'+tokenMatch[2]+'");';
  17206. }else{
  17207. fn[fn.length] = 'n = getNodes(n, mode, "'+tokenMatch[2]+'");';
  17208. }
  17209. path = path.replace(tokenMatch[0], "");
  17210. }else if(path.substr(0, 1) != '@'){
  17211. fn[fn.length] = 'n = getNodes(n, mode, "*");';
  17212. }
  17213. // type of "simple"
  17214. }else{
  17215. if(tokenMatch){
  17216. if(tokenMatch[1] == "#"){
  17217. fn[fn.length] = 'n = byId(n, "'+tokenMatch[2]+'");';
  17218. }else{
  17219. fn[fn.length] = 'n = byTag(n, "'+tokenMatch[2]+'");';
  17220. }
  17221. path = path.replace(tokenMatch[0], "");
  17222. }
  17223. }
  17224. while(!(modeMatch = path.match(modeRe))){
  17225. var matched = false;
  17226. for(var j = 0; j < matchersLn; j++){
  17227. var t = matchers[j];
  17228. var m = path.match(t.re);
  17229. if(m){
  17230. fn[fn.length] = t.select.replace(tplRe, function(x, i){
  17231. return m[i];
  17232. });
  17233. path = path.replace(m[0], "");
  17234. matched = true;
  17235. break;
  17236. }
  17237. }
  17238. // prevent infinite loop on bad selector
  17239. if(!matched){
  17240. }
  17241. }
  17242. if(modeMatch[1]){
  17243. fn[fn.length] = 'mode="'+modeMatch[1].replace(trimRe, "")+'";';
  17244. path = path.replace(modeMatch[1], "");
  17245. }
  17246. }
  17247. // close fn out
  17248. fn[fn.length] = "return nodup(n);\n}";
  17249. // eval fn and return it
  17250. eval(fn.join(""));
  17251. return f;
  17252. },
  17253. /**
  17254. * Selects an array of DOM nodes using JavaScript-only implementation.
  17255. *
  17256. * Use {@link #select} to take advantage of browsers built-in support for CSS selectors.
  17257. * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
  17258. * @param {HTMLElement/String} [root=document] The start of the query.
  17259. * @return {HTMLElement[]} An Array of DOM elements which match the selector. If there are
  17260. * no matches, and empty Array is returned.
  17261. */
  17262. jsSelect: function(path, root, type){
  17263. // set root to doc if not specified.
  17264. root = root || document;
  17265. if(typeof root == "string"){
  17266. root = document.getElementById(root);
  17267. }
  17268. var paths = path.split(","),
  17269. results = [];
  17270. // loop over each selector
  17271. for(var i = 0, len = paths.length; i < len; i++){
  17272. var subPath = paths[i].replace(trimRe, "");
  17273. // compile and place in cache
  17274. if(!cache[subPath]){
  17275. cache[subPath] = Ext.DomQuery.compile(subPath, type);
  17276. if(!cache[subPath]){
  17277. }
  17278. }
  17279. var result = cache[subPath](root);
  17280. if(result && result != document){
  17281. results = results.concat(result);
  17282. }
  17283. }
  17284. // if there were multiple selectors, make sure dups
  17285. // are eliminated
  17286. if(paths.length > 1){
  17287. return nodup(results);
  17288. }
  17289. return results;
  17290. },
  17291. isXml: function(el) {
  17292. var docEl = (el ? el.ownerDocument || el : 0).documentElement;
  17293. return docEl ? docEl.nodeName !== "HTML" : false;
  17294. },
  17295. /**
  17296. * Selects an array of DOM nodes by CSS/XPath selector.
  17297. *
  17298. * Uses [document.querySelectorAll][0] if browser supports that, otherwise falls back to
  17299. * {@link Ext.dom.Query#jsSelect} to do the work.
  17300. *
  17301. * Aliased as {@link Ext#query}.
  17302. *
  17303. * [0]: https://developer.mozilla.org/en/DOM/document.querySelectorAll
  17304. *
  17305. * @param {String} path The selector/xpath query
  17306. * @param {HTMLElement} [root=document] The start of the query.
  17307. * @return {HTMLElement[]} An array of DOM elements (not a NodeList as returned by `querySelectorAll`).
  17308. * @param {String} [type="select"] Either "select" or "simple" for a simple selector match (only valid when
  17309. * used when the call is deferred to the jsSelect method)
  17310. * @method
  17311. */
  17312. select : document.querySelectorAll ? function(path, root, type) {
  17313. root = root || document;
  17314. if (!Ext.DomQuery.isXml(root)) {
  17315. try {
  17316. /*
  17317. * This checking here is to "fix" the behaviour of querySelectorAll
  17318. * for non root document queries. The way qsa works is intentional,
  17319. * however it's definitely not the expected way it should work.
  17320. * When descendant selectors are used, only the lowest selector must be inside the root!
  17321. * More info: http://ejohn.org/blog/thoughts-on-queryselectorall/
  17322. * So we create a descendant selector by prepending the root's ID, and query the parent node.
  17323. * UNLESS the root has no parent in which qsa will work perfectly.
  17324. *
  17325. * We only modify the path for single selectors (ie, no multiples),
  17326. * without a full parser it makes it difficult to do this correctly.
  17327. */
  17328. if (root.parentNode && (root.nodeType !== 9) && path.indexOf(',') === -1 && !startIdRe.test(path)) {
  17329. path = '#' + Ext.id(root) + ' ' + path;
  17330. root = root.parentNode;
  17331. }
  17332. return Ext.Array.toArray(root.querySelectorAll(path));
  17333. }
  17334. catch (e) {
  17335. }
  17336. }
  17337. return Ext.DomQuery.jsSelect.call(this, path, root, type);
  17338. } : function(path, root, type) {
  17339. return Ext.DomQuery.jsSelect.call(this, path, root, type);
  17340. },
  17341. /**
  17342. * Selects a single element.
  17343. * @param {String} selector The selector/xpath query
  17344. * @param {HTMLElement} [root=document] The start of the query.
  17345. * @return {HTMLElement} The DOM element which matched the selector.
  17346. */
  17347. selectNode : function(path, root){
  17348. return Ext.DomQuery.select(path, root)[0];
  17349. },
  17350. /**
  17351. * Selects the value of a node, optionally replacing null with the defaultValue.
  17352. * @param {String} selector The selector/xpath query
  17353. * @param {HTMLElement} [root=document] The start of the query.
  17354. * @param {String} [defaultValue] When specified, this is return as empty value.
  17355. * @return {String}
  17356. */
  17357. selectValue : function(path, root, defaultValue){
  17358. path = path.replace(trimRe, "");
  17359. if(!valueCache[path]){
  17360. valueCache[path] = Ext.DomQuery.compile(path, "select");
  17361. }
  17362. var n = valueCache[path](root), v;
  17363. n = n[0] ? n[0] : n;
  17364. // overcome a limitation of maximum textnode size
  17365. // Rumored to potentially crash IE6 but has not been confirmed.
  17366. // http://reference.sitepoint.com/javascript/Node/normalize
  17367. // https://developer.mozilla.org/En/DOM/Node.normalize
  17368. if (typeof n.normalize == 'function') n.normalize();
  17369. v = (n && n.firstChild ? n.firstChild.nodeValue : null);
  17370. return ((v === null||v === undefined||v==='') ? defaultValue : v);
  17371. },
  17372. /**
  17373. * Selects the value of a node, parsing integers and floats.
  17374. * Returns the defaultValue, or 0 if none is specified.
  17375. * @param {String} selector The selector/xpath query
  17376. * @param {HTMLElement} [root=document] The start of the query.
  17377. * @param {Number} [defaultValue] When specified, this is return as empty value.
  17378. * @return {Number}
  17379. */
  17380. selectNumber : function(path, root, defaultValue){
  17381. var v = Ext.DomQuery.selectValue(path, root, defaultValue || 0);
  17382. return parseFloat(v);
  17383. },
  17384. /**
  17385. * Returns true if the passed element(s) match the passed simple selector
  17386. * (e.g. `div.some-class` or `span:first-child`)
  17387. * @param {String/HTMLElement/HTMLElement[]} el An element id, element or array of elements
  17388. * @param {String} selector The simple selector to test
  17389. * @return {Boolean}
  17390. */
  17391. is : function(el, ss){
  17392. if(typeof el == "string"){
  17393. el = document.getElementById(el);
  17394. }
  17395. var isArray = Ext.isArray(el),
  17396. result = Ext.DomQuery.filter(isArray ? el : [el], ss);
  17397. return isArray ? (result.length == el.length) : (result.length > 0);
  17398. },
  17399. /**
  17400. * Filters an array of elements to only include matches of a simple selector
  17401. * (e.g. `div.some-class` or `span:first-child`)
  17402. * @param {HTMLElement[]} el An array of elements to filter
  17403. * @param {String} selector The simple selector to test
  17404. * @param {Boolean} nonMatches If true, it returns the elements that DON'T match the selector instead of the
  17405. * ones that match
  17406. * @return {HTMLElement[]} An Array of DOM elements which match the selector. If there are no matches, and empty
  17407. * Array is returned.
  17408. */
  17409. filter : function(els, ss, nonMatches){
  17410. ss = ss.replace(trimRe, "");
  17411. if(!simpleCache[ss]){
  17412. simpleCache[ss] = Ext.DomQuery.compile(ss, "simple");
  17413. }
  17414. var result = simpleCache[ss](els);
  17415. return nonMatches ? quickDiff(result, els) : result;
  17416. },
  17417. /**
  17418. * Collection of matching regular expressions and code snippets.
  17419. * Each capture group within `()` will be replace the `{}` in the select
  17420. * statement as specified by their index.
  17421. */
  17422. matchers : [{
  17423. re: /^\.([\w-]+)/,
  17424. select: 'n = byClassName(n, " {1} ");'
  17425. }, {
  17426. re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
  17427. select: 'n = byPseudo(n, "{1}", "{2}");'
  17428. },{
  17429. re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
  17430. select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
  17431. }, {
  17432. re: /^#([\w-]+)/,
  17433. select: 'n = byId(n, "{1}");'
  17434. },{
  17435. re: /^@([\w-]+)/,
  17436. select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
  17437. }
  17438. ],
  17439. /**
  17440. * Collection of operator comparison functions.
  17441. * The default operators are `=`, `!=`, `^=`, `$=`, `*=`, `%=`, `|=` and `~=`.
  17442. * New operators can be added as long as the match the format *c*`=` where *c*
  17443. * is any character other than space, `>`, or `<`.
  17444. */
  17445. operators : {
  17446. "=" : function(a, v){
  17447. return a == v;
  17448. },
  17449. "!=" : function(a, v){
  17450. return a != v;
  17451. },
  17452. "^=" : function(a, v){
  17453. return a && a.substr(0, v.length) == v;
  17454. },
  17455. "$=" : function(a, v){
  17456. return a && a.substr(a.length-v.length) == v;
  17457. },
  17458. "*=" : function(a, v){
  17459. return a && a.indexOf(v) !== -1;
  17460. },
  17461. "%=" : function(a, v){
  17462. return (a % v) == 0;
  17463. },
  17464. "|=" : function(a, v){
  17465. return a && (a == v || a.substr(0, v.length+1) == v+'-');
  17466. },
  17467. "~=" : function(a, v){
  17468. return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
  17469. }
  17470. },
  17471. /**
  17472. * Object hash of "pseudo class" filter functions which are used when filtering selections.
  17473. * Each function is passed two parameters:
  17474. *
  17475. * - **c** : Array
  17476. * An Array of DOM elements to filter.
  17477. *
  17478. * - **v** : String
  17479. * The argument (if any) supplied in the selector.
  17480. *
  17481. * A filter function returns an Array of DOM elements which conform to the pseudo class.
  17482. * In addition to the provided pseudo classes listed above such as `first-child` and `nth-child`,
  17483. * developers may add additional, custom psuedo class filters to select elements according to application-specific requirements.
  17484. *
  17485. * For example, to filter `a` elements to only return links to __external__ resources:
  17486. *
  17487. * Ext.DomQuery.pseudos.external = function(c, v){
  17488. * var r = [], ri = -1;
  17489. * for(var i = 0, ci; ci = c[i]; i++){
  17490. * // Include in result set only if it's a link to an external resource
  17491. * if(ci.hostname != location.hostname){
  17492. * r[++ri] = ci;
  17493. * }
  17494. * }
  17495. * return r;
  17496. * };
  17497. *
  17498. * Then external links could be gathered with the following statement:
  17499. *
  17500. * var externalLinks = Ext.select("a:external");
  17501. */
  17502. pseudos : {
  17503. "first-child" : function(c){
  17504. var r = [], ri = -1, n;
  17505. for(var i = 0, ci; ci = n = c[i]; i++){
  17506. while((n = n.previousSibling) && n.nodeType != 1);
  17507. if(!n){
  17508. r[++ri] = ci;
  17509. }
  17510. }
  17511. return r;
  17512. },
  17513. "last-child" : function(c){
  17514. var r = [], ri = -1, n;
  17515. for(var i = 0, ci; ci = n = c[i]; i++){
  17516. while((n = n.nextSibling) && n.nodeType != 1);
  17517. if(!n){
  17518. r[++ri] = ci;
  17519. }
  17520. }
  17521. return r;
  17522. },
  17523. "nth-child" : function(c, a) {
  17524. var r = [], ri = -1,
  17525. m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a),
  17526. f = (m[1] || 1) - 0, l = m[2] - 0;
  17527. for(var i = 0, n; n = c[i]; i++){
  17528. var pn = n.parentNode;
  17529. if (batch != pn._batch) {
  17530. var j = 0;
  17531. for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
  17532. if(cn.nodeType == 1){
  17533. cn.nodeIndex = ++j;
  17534. }
  17535. }
  17536. pn._batch = batch;
  17537. }
  17538. if (f == 1) {
  17539. if (l == 0 || n.nodeIndex == l){
  17540. r[++ri] = n;
  17541. }
  17542. } else if ((n.nodeIndex + l) % f == 0){
  17543. r[++ri] = n;
  17544. }
  17545. }
  17546. return r;
  17547. },
  17548. "only-child" : function(c){
  17549. var r = [], ri = -1;;
  17550. for(var i = 0, ci; ci = c[i]; i++){
  17551. if(!prev(ci) && !next(ci)){
  17552. r[++ri] = ci;
  17553. }
  17554. }
  17555. return r;
  17556. },
  17557. "empty" : function(c){
  17558. var r = [], ri = -1;
  17559. for(var i = 0, ci; ci = c[i]; i++){
  17560. var cns = ci.childNodes, j = 0, cn, empty = true;
  17561. while(cn = cns[j]){
  17562. ++j;
  17563. if(cn.nodeType == 1 || cn.nodeType == 3){
  17564. empty = false;
  17565. break;
  17566. }
  17567. }
  17568. if(empty){
  17569. r[++ri] = ci;
  17570. }
  17571. }
  17572. return r;
  17573. },
  17574. "contains" : function(c, v){
  17575. var r = [], ri = -1;
  17576. for(var i = 0, ci; ci = c[i]; i++){
  17577. if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
  17578. r[++ri] = ci;
  17579. }
  17580. }
  17581. return r;
  17582. },
  17583. "nodeValue" : function(c, v){
  17584. var r = [], ri = -1;
  17585. for(var i = 0, ci; ci = c[i]; i++){
  17586. if(ci.firstChild && ci.firstChild.nodeValue == v){
  17587. r[++ri] = ci;
  17588. }
  17589. }
  17590. return r;
  17591. },
  17592. "checked" : function(c){
  17593. var r = [], ri = -1;
  17594. for(var i = 0, ci; ci = c[i]; i++){
  17595. if(ci.checked == true){
  17596. r[++ri] = ci;
  17597. }
  17598. }
  17599. return r;
  17600. },
  17601. "not" : function(c, ss){
  17602. return Ext.DomQuery.filter(c, ss, true);
  17603. },
  17604. "any" : function(c, selectors){
  17605. var ss = selectors.split('|'),
  17606. r = [], ri = -1, s;
  17607. for(var i = 0, ci; ci = c[i]; i++){
  17608. for(var j = 0; s = ss[j]; j++){
  17609. if(Ext.DomQuery.is(ci, s)){
  17610. r[++ri] = ci;
  17611. break;
  17612. }
  17613. }
  17614. }
  17615. return r;
  17616. },
  17617. "odd" : function(c){
  17618. return this["nth-child"](c, "odd");
  17619. },
  17620. "even" : function(c){
  17621. return this["nth-child"](c, "even");
  17622. },
  17623. "nth" : function(c, a){
  17624. return c[a-1] || [];
  17625. },
  17626. "first" : function(c){
  17627. return c[0] || [];
  17628. },
  17629. "last" : function(c){
  17630. return c[c.length-1] || [];
  17631. },
  17632. "has" : function(c, ss){
  17633. var s = Ext.DomQuery.select,
  17634. r = [], ri = -1;
  17635. for(var i = 0, ci; ci = c[i]; i++){
  17636. if(s(ss, ci).length > 0){
  17637. r[++ri] = ci;
  17638. }
  17639. }
  17640. return r;
  17641. },
  17642. "next" : function(c, ss){
  17643. var is = Ext.DomQuery.is,
  17644. r = [], ri = -1;
  17645. for(var i = 0, ci; ci = c[i]; i++){
  17646. var n = next(ci);
  17647. if(n && is(n, ss)){
  17648. r[++ri] = ci;
  17649. }
  17650. }
  17651. return r;
  17652. },
  17653. "prev" : function(c, ss){
  17654. var is = Ext.DomQuery.is,
  17655. r = [], ri = -1;
  17656. for(var i = 0, ci; ci = c[i]; i++){
  17657. var n = prev(ci);
  17658. if(n && is(n, ss)){
  17659. r[++ri] = ci;
  17660. }
  17661. }
  17662. return r;
  17663. }
  17664. }
  17665. };
  17666. }();
  17667. /**
  17668. * Shorthand of {@link Ext.dom.Query#select}
  17669. * @member Ext
  17670. * @method query
  17671. * @inheritdoc Ext.dom.Query#select
  17672. */
  17673. Ext.query = Ext.DomQuery.select;
  17674. /**
  17675. * @class Ext.dom.Element
  17676. * @alternateClassName Ext.Element
  17677. * @alternateClassName Ext.core.Element
  17678. * @extend Ext.dom.AbstractElement
  17679. *
  17680. * Encapsulates a DOM element, adding simple DOM manipulation facilities, normalizing for browser differences.
  17681. *
  17682. * All instances of this class inherit the methods of {@link Ext.fx.Anim} making visual effects easily available to all
  17683. * DOM elements.
  17684. *
  17685. * Note that the events documented in this class are not Ext events, they encapsulate browser events. Some older browsers
  17686. * may not support the full range of events. Which events are supported is beyond the control of Ext JS.
  17687. *
  17688. * Usage:
  17689. *
  17690. * // by id
  17691. * var el = Ext.get("my-div");
  17692. *
  17693. * // by DOM element reference
  17694. * var el = Ext.get(myDivElement);
  17695. *
  17696. * # Animations
  17697. *
  17698. * When an element is manipulated, by default there is no animation.
  17699. *
  17700. * var el = Ext.get("my-div");
  17701. *
  17702. * // no animation
  17703. * el.setWidth(100);
  17704. *
  17705. * Many of the functions for manipulating an element have an optional "animate" parameter. This parameter can be
  17706. * specified as boolean (true) for default animation effects.
  17707. *
  17708. * // default animation
  17709. * el.setWidth(100, true);
  17710. *
  17711. * To configure the effects, an object literal with animation options to use as the Element animation configuration
  17712. * object can also be specified. Note that the supported Element animation configuration options are a subset of the
  17713. * {@link Ext.fx.Anim} animation options specific to Fx effects. The supported Element animation configuration options
  17714. * are:
  17715. *
  17716. * Option Default Description
  17717. * --------- -------- ---------------------------------------------
  17718. * {@link Ext.fx.Anim#duration duration} .35 The duration of the animation in seconds
  17719. * {@link Ext.fx.Anim#easing easing} easeOut The easing method
  17720. * {@link Ext.fx.Anim#callback callback} none A function to execute when the anim completes
  17721. * {@link Ext.fx.Anim#scope scope} this The scope (this) of the callback function
  17722. *
  17723. * Usage:
  17724. *
  17725. * // Element animation options object
  17726. * var opt = {
  17727. * {@link Ext.fx.Anim#duration duration}: 1,
  17728. * {@link Ext.fx.Anim#easing easing}: 'elasticIn',
  17729. * {@link Ext.fx.Anim#callback callback}: this.foo,
  17730. * {@link Ext.fx.Anim#scope scope}: this
  17731. * };
  17732. * // animation with some options set
  17733. * el.setWidth(100, opt);
  17734. *
  17735. * The Element animation object being used for the animation will be set on the options object as "anim", which allows
  17736. * you to stop or manipulate the animation. Here is an example:
  17737. *
  17738. * // using the "anim" property to get the Anim object
  17739. * if(opt.anim.isAnimated()){
  17740. * opt.anim.stop();
  17741. * }
  17742. *
  17743. * # Composite (Collections of) Elements
  17744. *
  17745. * For working with collections of Elements, see {@link Ext.CompositeElement}
  17746. *
  17747. * @constructor
  17748. * Creates new Element directly.
  17749. * @param {String/HTMLElement} element
  17750. * @param {Boolean} [forceNew] By default the constructor checks to see if there is already an instance of this
  17751. * element in the cache and if there is it returns the same instance. This will skip that check (useful for extending
  17752. * this class).
  17753. * @return {Object}
  17754. */
  17755. (function() {
  17756. var HIDDEN = 'hidden',
  17757. DOC = document,
  17758. VISIBILITY = "visibility",
  17759. DISPLAY = "display",
  17760. NONE = "none",
  17761. XMASKED = Ext.baseCSSPrefix + "masked",
  17762. XMASKEDRELATIVE = Ext.baseCSSPrefix + "masked-relative",
  17763. EXTELMASKMSG = Ext.baseCSSPrefix + "mask-msg",
  17764. bodyRe = /^body/i,
  17765. // speedy lookup for elements never to box adjust
  17766. noBoxAdjust = Ext.isStrict ? {
  17767. select: 1
  17768. }: {
  17769. input: 1,
  17770. select: 1,
  17771. textarea: 1
  17772. },
  17773. Element = Ext.define('Ext.dom.Element', {
  17774. extend: 'Ext.dom.AbstractElement',
  17775. alternateClassName: ['Ext.Element', 'Ext.core.Element'],
  17776. addUnits: function() {
  17777. return this.self.addUnits.apply(this.self, arguments);
  17778. },
  17779. /**
  17780. * Tries to focus the element. Any exceptions are caught and ignored.
  17781. * @param {Number} [defer] Milliseconds to defer the focus
  17782. * @return {Ext.dom.Element} this
  17783. */
  17784. focus: function(defer, /* private */ dom) {
  17785. var me = this,
  17786. scrollTop,
  17787. body;
  17788. dom = dom || me.dom;
  17789. body = (dom.ownerDocument || DOC).body || DOC.body;
  17790. try {
  17791. if (Number(defer)) {
  17792. Ext.defer(me.focus, defer, me, [null, dom]);
  17793. } else {
  17794. // Focusing a large element, the browser attempts to scroll as much of it into view
  17795. // as possible. We need to override this behaviour.
  17796. if (dom.offsetHeight > Element.getViewHeight()) {
  17797. scrollTop = body.scrollTop;
  17798. }
  17799. dom.focus();
  17800. if (scrollTop !== undefined) {
  17801. body.scrollTop = scrollTop;
  17802. }
  17803. }
  17804. } catch(e) {
  17805. }
  17806. return me;
  17807. },
  17808. /**
  17809. * Tries to blur the element. Any exceptions are caught and ignored.
  17810. * @return {Ext.dom.Element} this
  17811. */
  17812. blur: function() {
  17813. try {
  17814. this.dom.blur();
  17815. } catch(e) {
  17816. }
  17817. return this;
  17818. },
  17819. /**
  17820. * Tests various css rules/browsers to determine if this element uses a border box
  17821. * @return {Boolean}
  17822. */
  17823. isBorderBox: function() {
  17824. var box = Ext.isBorderBox;
  17825. if (box) {
  17826. box = !((this.dom.tagName || "").toLowerCase() in noBoxAdjust);
  17827. }
  17828. return box;
  17829. },
  17830. /**
  17831. * Sets up event handlers to call the passed functions when the mouse is moved into and out of the Element.
  17832. * @param {Function} overFn The function to call when the mouse enters the Element.
  17833. * @param {Function} outFn The function to call when the mouse leaves the Element.
  17834. * @param {Object} [scope] The scope (`this` reference) in which the functions are executed. Defaults
  17835. * to the Element's DOM element.
  17836. * @param {Object} [options] Options for the listener. See {@link Ext.util.Observable#addListener the
  17837. * options parameter}.
  17838. * @return {Ext.dom.Element} this
  17839. */
  17840. hover: function(overFn, outFn, scope, options) {
  17841. var me = this;
  17842. me.on('mouseenter', overFn, scope || me.dom, options);
  17843. me.on('mouseleave', outFn, scope || me.dom, options);
  17844. return me;
  17845. },
  17846. /**
  17847. * Returns the value of a namespaced attribute from the element's underlying DOM node.
  17848. * @param {String} namespace The namespace in which to look for the attribute
  17849. * @param {String} name The attribute name
  17850. * @return {String} The attribute value
  17851. */
  17852. getAttributeNS: function(ns, name) {
  17853. return this.getAttribute(name, ns);
  17854. },
  17855. getAttribute: (Ext.isIE && !(Ext.isIE9 && DOC.documentMode === 9)) ?
  17856. function(name, ns) {
  17857. var d = this.dom,
  17858. type;
  17859. if (ns) {
  17860. type = typeof d[ns + ":" + name];
  17861. if (type != 'undefined' && type != 'unknown') {
  17862. return d[ns + ":" + name] || null;
  17863. }
  17864. return null;
  17865. }
  17866. if (name === "for") {
  17867. name = "htmlFor";
  17868. }
  17869. return d[name] || null;
  17870. } : function(name, ns) {
  17871. var d = this.dom;
  17872. if (ns) {
  17873. return d.getAttributeNS(ns, name) || d.getAttribute(ns + ":" + name);
  17874. }
  17875. return d.getAttribute(name) || d[name] || null;
  17876. },
  17877. /**
  17878. * @property {Boolean} autoBoxAdjust
  17879. * True to automatically adjust width and height settings for box-model issues.
  17880. */
  17881. autoBoxAdjust: true,
  17882. /**
  17883. * Checks whether the element is currently visible using both visibility and display properties.
  17884. * @param {Boolean} [deep] True to walk the dom and see if parent elements are hidden (defaults to false)
  17885. * @return {Boolean} True if the element is currently visible, else false
  17886. */
  17887. isVisible : function(deep) {
  17888. var vis = !this.isStyle(VISIBILITY, HIDDEN) && !this.isStyle(DISPLAY, NONE),
  17889. p = this.dom.parentNode;
  17890. if (deep !== true || !vis) {
  17891. return vis;
  17892. }
  17893. while (p && !(bodyRe.test(p.tagName))) {
  17894. if (!Ext.fly(p, '_isVisible').isVisible()) {
  17895. return false;
  17896. }
  17897. p = p.parentNode;
  17898. }
  17899. return true;
  17900. },
  17901. /**
  17902. * Returns true if display is not "none"
  17903. * @return {Boolean}
  17904. */
  17905. isDisplayed : function() {
  17906. return !this.isStyle(DISPLAY, NONE);
  17907. },
  17908. /**
  17909. * Convenience method for setVisibilityMode(Element.DISPLAY)
  17910. * @param {String} [display] What to set display to when visible
  17911. * @return {Ext.dom.Element} this
  17912. */
  17913. enableDisplayMode : function(display) {
  17914. var me = this;
  17915. me.setVisibilityMode(Element.DISPLAY);
  17916. if (!Ext.isEmpty(display)) {
  17917. (me.$cache || me.getCache()).data.originalDisplay = display;
  17918. }
  17919. return me;
  17920. },
  17921. /**
  17922. * Puts a mask over this element to disable user interaction. Requires core.css.
  17923. * This method can only be applied to elements which accept child nodes.
  17924. * @param {String} [msg] A message to display in the mask
  17925. * @param {String} [msgCls] A css class to apply to the msg element
  17926. * @return {Ext.dom.Element} The mask element
  17927. */
  17928. mask : function(msg, msgCls /* private - passed by AbstractComponent.mask to avoid the need to interrogate the DOM to get the height*/, elHeight) {
  17929. var me = this,
  17930. dom = me.dom,
  17931. setExpression = dom.style.setExpression,
  17932. data = (me.$cache || me.getCache()).data,
  17933. maskEl = data.maskEl,
  17934. maskMsg = data.maskMsg;
  17935. if (!(bodyRe.test(dom.tagName) && me.getStyle('position') == 'static')) {
  17936. me.addCls(XMASKEDRELATIVE);
  17937. }
  17938. // We always needs to recreate the mask since the DOM element may have been re-created
  17939. if (maskEl) {
  17940. maskEl.remove();
  17941. }
  17942. if (maskMsg) {
  17943. maskMsg.remove();
  17944. }
  17945. Ext.DomHelper.append(dom, [{
  17946. cls : Ext.baseCSSPrefix + "mask"
  17947. }, {
  17948. cls : msgCls ? EXTELMASKMSG + " " + msgCls : EXTELMASKMSG,
  17949. cn : {
  17950. tag: 'div',
  17951. html: msg || ''
  17952. }
  17953. }]);
  17954. maskMsg = Ext.get(dom.lastChild);
  17955. maskEl = Ext.get(maskMsg.dom.previousSibling);
  17956. data.maskMsg = maskMsg;
  17957. data.maskEl = maskEl;
  17958. me.addCls(XMASKED);
  17959. maskEl.setDisplayed(true);
  17960. if (typeof msg == 'string') {
  17961. maskMsg.setDisplayed(true);
  17962. maskMsg.center(me);
  17963. } else {
  17964. maskMsg.setDisplayed(false);
  17965. }
  17966. // NOTE: CSS expressions are resource intensive and to be used only as a last resort
  17967. // These expressions are removed as soon as they are no longer necessary - in the unmask method.
  17968. // In normal use cases an element will be masked for a limited period of time.
  17969. // Fix for https://sencha.jira.com/browse/EXTJSIV-19.
  17970. // IE6 strict mode and IE6-9 quirks mode takes off left+right padding when calculating width!
  17971. if (!Ext.supports.IncludePaddingInWidthCalculation && setExpression) {
  17972. maskEl.dom.style.setExpression('width', 'this.parentNode.clientWidth + "px"');
  17973. }
  17974. // Some versions and modes of IE subtract top+bottom padding when calculating height.
  17975. // Different versions from those which make the same error for width!
  17976. if (!Ext.supports.IncludePaddingInHeightCalculation && setExpression) {
  17977. maskEl.dom.style.setExpression('height', 'this.parentNode.' + (dom == DOC.body ? 'scrollHeight' : 'offsetHeight') + ' + "px"');
  17978. }
  17979. // ie will not expand full height automatically
  17980. else if (Ext.isIE && !(Ext.isIE7 && Ext.isStrict) && me.getStyle('height') == 'auto') {
  17981. maskEl.setSize(undefined, elHeight || me.getHeight());
  17982. }
  17983. return maskEl;
  17984. },
  17985. /**
  17986. * Hides a previously applied mask.
  17987. */
  17988. unmask : function() {
  17989. var me = this,
  17990. data = (me.$cache || me.getCache()).data,
  17991. maskEl = data.maskEl,
  17992. maskMsg = data.maskMsg,
  17993. style;
  17994. if (maskEl) {
  17995. style = maskEl.dom.style;
  17996. // Remove resource-intensive CSS expressions as soon as they are not required.
  17997. if (style.clearExpression) {
  17998. style.clearExpression('width');
  17999. style.clearExpression('height');
  18000. }
  18001. if (maskEl) {
  18002. maskEl.remove();
  18003. delete data.maskEl;
  18004. }
  18005. if (maskMsg) {
  18006. maskMsg.remove();
  18007. delete data.maskMsg;
  18008. }
  18009. me.removeCls([XMASKED, XMASKEDRELATIVE]);
  18010. }
  18011. },
  18012. /**
  18013. * Returns true if this element is masked. Also re-centers any displayed message within the mask.
  18014. * @return {Boolean}
  18015. */
  18016. isMasked : function() {
  18017. var me = this,
  18018. data = (me.$cache || me.getCache()).data,
  18019. maskEl = data.maskEl,
  18020. maskMsg = data.maskMsg,
  18021. hasMask = false;
  18022. if (maskEl && maskEl.isVisible()) {
  18023. if (maskMsg) {
  18024. maskMsg.center(me);
  18025. }
  18026. hasMask = true;
  18027. }
  18028. return hasMask;
  18029. },
  18030. /**
  18031. * Creates an iframe shim for this element to keep selects and other windowed objects from
  18032. * showing through.
  18033. * @return {Ext.dom.Element} The new shim element
  18034. */
  18035. createShim : function() {
  18036. var el = DOC.createElement('iframe'),
  18037. shim;
  18038. el.frameBorder = '0';
  18039. el.className = Ext.baseCSSPrefix + 'shim';
  18040. el.src = Ext.SSL_SECURE_URL;
  18041. shim = Ext.get(this.dom.parentNode.insertBefore(el, this.dom));
  18042. shim.autoBoxAdjust = false;
  18043. return shim;
  18044. },
  18045. /**
  18046. * Convenience method for constructing a KeyMap
  18047. * @param {String/Number/Number[]/Object} key Either a string with the keys to listen for, the numeric key code,
  18048. * array of key codes or an object with the following options:
  18049. * @param {Number/Array} key.key
  18050. * @param {Boolean} key.shift
  18051. * @param {Boolean} key.ctrl
  18052. * @param {Boolean} key.alt
  18053. * @param {Function} fn The function to call
  18054. * @param {Object} [scope] The scope (`this` reference) in which the specified function is executed. Defaults to this Element.
  18055. * @return {Ext.util.KeyMap} The KeyMap created
  18056. */
  18057. addKeyListener : function(key, fn, scope){
  18058. var config;
  18059. if(typeof key != 'object' || Ext.isArray(key)){
  18060. config = {
  18061. target: this,
  18062. key: key,
  18063. fn: fn,
  18064. scope: scope
  18065. };
  18066. }else{
  18067. config = {
  18068. target: this,
  18069. key : key.key,
  18070. shift : key.shift,
  18071. ctrl : key.ctrl,
  18072. alt : key.alt,
  18073. fn: fn,
  18074. scope: scope
  18075. };
  18076. }
  18077. return new Ext.util.KeyMap(config);
  18078. },
  18079. /**
  18080. * Creates a KeyMap for this element
  18081. * @param {Object} config The KeyMap config. See {@link Ext.util.KeyMap} for more details
  18082. * @return {Ext.util.KeyMap} The KeyMap created
  18083. */
  18084. addKeyMap : function(config) {
  18085. return new Ext.util.KeyMap(Ext.apply({
  18086. target: this
  18087. }, config));
  18088. },
  18089. // Mouse events
  18090. /**
  18091. * @event click
  18092. * Fires when a mouse click is detected within the element.
  18093. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18094. * @param {HTMLElement} t The target of the event.
  18095. */
  18096. /**
  18097. * @event contextmenu
  18098. * Fires when a right click is detected within the element.
  18099. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18100. * @param {HTMLElement} t The target of the event.
  18101. */
  18102. /**
  18103. * @event dblclick
  18104. * Fires when a mouse double click is detected within the element.
  18105. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18106. * @param {HTMLElement} t The target of the event.
  18107. */
  18108. /**
  18109. * @event mousedown
  18110. * Fires when a mousedown is detected within the element.
  18111. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18112. * @param {HTMLElement} t The target of the event.
  18113. */
  18114. /**
  18115. * @event mouseup
  18116. * Fires when a mouseup is detected within the element.
  18117. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18118. * @param {HTMLElement} t The target of the event.
  18119. */
  18120. /**
  18121. * @event mouseover
  18122. * Fires when a mouseover is detected within the element.
  18123. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18124. * @param {HTMLElement} t The target of the event.
  18125. */
  18126. /**
  18127. * @event mousemove
  18128. * Fires when a mousemove is detected with the element.
  18129. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18130. * @param {HTMLElement} t The target of the event.
  18131. */
  18132. /**
  18133. * @event mouseout
  18134. * Fires when a mouseout is detected with the element.
  18135. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18136. * @param {HTMLElement} t The target of the event.
  18137. */
  18138. /**
  18139. * @event mouseenter
  18140. * Fires when the mouse enters the element.
  18141. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18142. * @param {HTMLElement} t The target of the event.
  18143. */
  18144. /**
  18145. * @event mouseleave
  18146. * Fires when the mouse leaves the element.
  18147. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18148. * @param {HTMLElement} t The target of the event.
  18149. */
  18150. // Keyboard events
  18151. /**
  18152. * @event keypress
  18153. * Fires when a keypress is detected within the element.
  18154. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18155. * @param {HTMLElement} t The target of the event.
  18156. */
  18157. /**
  18158. * @event keydown
  18159. * Fires when a keydown is detected within the element.
  18160. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18161. * @param {HTMLElement} t The target of the event.
  18162. */
  18163. /**
  18164. * @event keyup
  18165. * Fires when a keyup is detected within the element.
  18166. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18167. * @param {HTMLElement} t The target of the event.
  18168. */
  18169. // HTML frame/object events
  18170. /**
  18171. * @event load
  18172. * Fires when the user agent finishes loading all content within the element. Only supported by window, frames,
  18173. * objects and images.
  18174. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18175. * @param {HTMLElement} t The target of the event.
  18176. */
  18177. /**
  18178. * @event unload
  18179. * Fires when the user agent removes all content from a window or frame. For elements, it fires when the target
  18180. * element or any of its content has been removed.
  18181. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18182. * @param {HTMLElement} t The target of the event.
  18183. */
  18184. /**
  18185. * @event abort
  18186. * Fires when an object/image is stopped from loading before completely loaded.
  18187. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18188. * @param {HTMLElement} t The target of the event.
  18189. */
  18190. /**
  18191. * @event error
  18192. * Fires when an object/image/frame cannot be loaded properly.
  18193. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18194. * @param {HTMLElement} t The target of the event.
  18195. */
  18196. /**
  18197. * @event resize
  18198. * Fires when a document view is resized.
  18199. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18200. * @param {HTMLElement} t The target of the event.
  18201. */
  18202. /**
  18203. * @event scroll
  18204. * Fires when a document view is scrolled.
  18205. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18206. * @param {HTMLElement} t The target of the event.
  18207. */
  18208. // Form events
  18209. /**
  18210. * @event select
  18211. * Fires when a user selects some text in a text field, including input and textarea.
  18212. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18213. * @param {HTMLElement} t The target of the event.
  18214. */
  18215. /**
  18216. * @event change
  18217. * Fires when a control loses the input focus and its value has been modified since gaining focus.
  18218. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18219. * @param {HTMLElement} t The target of the event.
  18220. */
  18221. /**
  18222. * @event submit
  18223. * Fires when a form is submitted.
  18224. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18225. * @param {HTMLElement} t The target of the event.
  18226. */
  18227. /**
  18228. * @event reset
  18229. * Fires when a form is reset.
  18230. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18231. * @param {HTMLElement} t The target of the event.
  18232. */
  18233. /**
  18234. * @event focus
  18235. * Fires when an element receives focus either via the pointing device or by tab navigation.
  18236. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18237. * @param {HTMLElement} t The target of the event.
  18238. */
  18239. /**
  18240. * @event blur
  18241. * Fires when an element loses focus either via the pointing device or by tabbing navigation.
  18242. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18243. * @param {HTMLElement} t The target of the event.
  18244. */
  18245. // User Interface events
  18246. /**
  18247. * @event DOMFocusIn
  18248. * Where supported. Similar to HTML focus event, but can be applied to any focusable element.
  18249. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18250. * @param {HTMLElement} t The target of the event.
  18251. */
  18252. /**
  18253. * @event DOMFocusOut
  18254. * Where supported. Similar to HTML blur event, but can be applied to any focusable element.
  18255. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18256. * @param {HTMLElement} t The target of the event.
  18257. */
  18258. /**
  18259. * @event DOMActivate
  18260. * Where supported. Fires when an element is activated, for instance, through a mouse click or a keypress.
  18261. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18262. * @param {HTMLElement} t The target of the event.
  18263. */
  18264. // DOM Mutation events
  18265. /**
  18266. * @event DOMSubtreeModified
  18267. * Where supported. Fires when the subtree is modified.
  18268. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18269. * @param {HTMLElement} t The target of the event.
  18270. */
  18271. /**
  18272. * @event DOMNodeInserted
  18273. * Where supported. Fires when a node has been added as a child of another node.
  18274. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18275. * @param {HTMLElement} t The target of the event.
  18276. */
  18277. /**
  18278. * @event DOMNodeRemoved
  18279. * Where supported. Fires when a descendant node of the element is removed.
  18280. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18281. * @param {HTMLElement} t The target of the event.
  18282. */
  18283. /**
  18284. * @event DOMNodeRemovedFromDocument
  18285. * Where supported. Fires when a node is being removed from a document.
  18286. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18287. * @param {HTMLElement} t The target of the event.
  18288. */
  18289. /**
  18290. * @event DOMNodeInsertedIntoDocument
  18291. * Where supported. Fires when a node is being inserted into a document.
  18292. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18293. * @param {HTMLElement} t The target of the event.
  18294. */
  18295. /**
  18296. * @event DOMAttrModified
  18297. * Where supported. Fires when an attribute has been modified.
  18298. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18299. * @param {HTMLElement} t The target of the event.
  18300. */
  18301. /**
  18302. * @event DOMCharacterDataModified
  18303. * Where supported. Fires when the character data has been modified.
  18304. * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
  18305. * @param {HTMLElement} t The target of the event.
  18306. */
  18307. /**
  18308. * Appends an event handler to this element.
  18309. *
  18310. * @param {String} eventName The name of event to handle.
  18311. *
  18312. * @param {Function} fn The handler function the event invokes. This function is passed the following parameters:
  18313. *
  18314. * - **evt** : EventObject
  18315. *
  18316. * The {@link Ext.EventObject EventObject} describing the event.
  18317. *
  18318. * - **el** : HtmlElement
  18319. *
  18320. * The DOM element which was the target of the event. Note that this may be filtered by using the delegate option.
  18321. *
  18322. * - **o** : Object
  18323. *
  18324. * The options object from the call that setup the listener.
  18325. *
  18326. * @param {Object} scope (optional) The scope (**this** reference) in which the handler function is executed. **If
  18327. * omitted, defaults to this Element.**
  18328. *
  18329. * @param {Object} options (optional) An object containing handler configuration properties. This may contain any of
  18330. * the following properties:
  18331. *
  18332. * - **scope** Object :
  18333. *
  18334. * The scope (**this** reference) in which the handler function is executed. **If omitted, defaults to this
  18335. * Element.**
  18336. *
  18337. * - **delegate** String:
  18338. *
  18339. * A simple selector to filter the target or look for a descendant of the target. See below for additional details.
  18340. *
  18341. * - **stopEvent** Boolean:
  18342. *
  18343. * True to stop the event. That is stop propagation, and prevent the default action.
  18344. *
  18345. * - **preventDefault** Boolean:
  18346. *
  18347. * True to prevent the default action
  18348. *
  18349. * - **stopPropagation** Boolean:
  18350. *
  18351. * True to prevent event propagation
  18352. *
  18353. * - **normalized** Boolean:
  18354. *
  18355. * False to pass a browser event to the handler function instead of an Ext.EventObject
  18356. *
  18357. * - **target** Ext.dom.Element:
  18358. *
  18359. * Only call the handler if the event was fired on the target Element, _not_ if the event was bubbled up from a
  18360. * child node.
  18361. *
  18362. * - **delay** Number:
  18363. *
  18364. * The number of milliseconds to delay the invocation of the handler after the event fires.
  18365. *
  18366. * - **single** Boolean:
  18367. *
  18368. * True to add a handler to handle just the next firing of the event, and then remove itself.
  18369. *
  18370. * - **buffer** Number:
  18371. *
  18372. * Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed by the specified number of
  18373. * milliseconds. If the event fires again within that time, the original handler is _not_ invoked, but the new
  18374. * handler is scheduled in its place.
  18375. *
  18376. * **Combining Options**
  18377. *
  18378. * Using the options argument, it is possible to combine different types of listeners:
  18379. *
  18380. * A delayed, one-time listener that auto stops the event and adds a custom argument (forumId) to the options
  18381. * object. The options object is available as the third parameter in the handler function.
  18382. *
  18383. * Code:
  18384. *
  18385. * el.on('click', this.onClick, this, {
  18386. * single: true,
  18387. * delay: 100,
  18388. * stopEvent : true,
  18389. * forumId: 4
  18390. * });
  18391. *
  18392. * **Attaching multiple handlers in 1 call**
  18393. *
  18394. * The method also allows for a single argument to be passed which is a config object containing properties which
  18395. * specify multiple handlers.
  18396. *
  18397. * Code:
  18398. *
  18399. * el.on({
  18400. * 'click' : {
  18401. * fn: this.onClick,
  18402. * scope: this,
  18403. * delay: 100
  18404. * },
  18405. * 'mouseover' : {
  18406. * fn: this.onMouseOver,
  18407. * scope: this
  18408. * },
  18409. * 'mouseout' : {
  18410. * fn: this.onMouseOut,
  18411. * scope: this
  18412. * }
  18413. * });
  18414. *
  18415. * Or a shorthand syntax:
  18416. *
  18417. * Code:
  18418. *
  18419. * el.on({
  18420. * 'click' : this.onClick,
  18421. * 'mouseover' : this.onMouseOver,
  18422. * 'mouseout' : this.onMouseOut,
  18423. * scope: this
  18424. * });
  18425. *
  18426. * **delegate**
  18427. *
  18428. * This is a configuration option that you can pass along when registering a handler for an event to assist with
  18429. * event delegation. Event delegation is a technique that is used to reduce memory consumption and prevent exposure
  18430. * to memory-leaks. By registering an event for a container element as opposed to each element within a container.
  18431. * By setting this configuration option to a simple selector, the target element will be filtered to look for a
  18432. * descendant of the target. For example:
  18433. *
  18434. * // using this markup:
  18435. * <div id='elId'>
  18436. * <p id='p1'>paragraph one</p>
  18437. * <p id='p2' class='clickable'>paragraph two</p>
  18438. * <p id='p3'>paragraph three</p>
  18439. * </div>
  18440. *
  18441. * // utilize event delegation to registering just one handler on the container element:
  18442. * el = Ext.get('elId');
  18443. * el.on(
  18444. * 'click',
  18445. * function(e,t) {
  18446. * // handle click
  18447. * console.info(t.id); // 'p2'
  18448. * },
  18449. * this,
  18450. * {
  18451. * // filter the target element to be a descendant with the class 'clickable'
  18452. * delegate: '.clickable'
  18453. * }
  18454. * );
  18455. *
  18456. * @return {Ext.dom.Element} this
  18457. */
  18458. on: function(eventName, fn, scope, options) {
  18459. Ext.EventManager.on(this, eventName, fn, scope || this, options);
  18460. return this;
  18461. },
  18462. /**
  18463. * Removes an event handler from this element.
  18464. *
  18465. * **Note**: if a *scope* was explicitly specified when {@link #on adding} the listener,
  18466. * the same scope must be specified here.
  18467. *
  18468. * Example:
  18469. *
  18470. * el.un('click', this.handlerFn);
  18471. * // or
  18472. * el.removeListener('click', this.handlerFn);
  18473. *
  18474. * @param {String} eventName The name of the event from which to remove the handler.
  18475. * @param {Function} fn The handler function to remove. **This must be a reference to the function passed into the
  18476. * {@link #on} call.**
  18477. * @param {Object} scope If a scope (**this** reference) was specified when the listener was added, then this must
  18478. * refer to the same object.
  18479. * @return {Ext.dom.Element} this
  18480. */
  18481. un: function(eventName, fn, scope) {
  18482. Ext.EventManager.un(this, eventName, fn, scope || this);
  18483. return this;
  18484. },
  18485. /**
  18486. * Removes all previous added listeners from this element
  18487. * @return {Ext.dom.Element} this
  18488. */
  18489. removeAllListeners: function() {
  18490. Ext.EventManager.removeAll(this);
  18491. return this;
  18492. },
  18493. /**
  18494. * Recursively removes all previous added listeners from this element and its children
  18495. * @return {Ext.dom.Element} this
  18496. */
  18497. purgeAllListeners: function() {
  18498. Ext.EventManager.purgeElement(this);
  18499. return this;
  18500. }
  18501. }, function() {
  18502. var EC = Ext.cache,
  18503. El = this,
  18504. AbstractElement = Ext.dom.AbstractElement,
  18505. focusRe = /a|button|embed|iframe|img|input|object|select|textarea/i,
  18506. nonSpaceRe = /\S/,
  18507. scriptTagRe = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig,
  18508. replaceScriptTagRe = /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,
  18509. srcRe = /\ssrc=([\'\"])(.*?)\1/i,
  18510. typeRe = /\stype=([\'\"])(.*?)\1/i,
  18511. useDocForId = !(Ext.isIE6 || Ext.isIE7 || Ext.isIE8);
  18512. El.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>';
  18513. //</!if>
  18514. // private
  18515. // Garbage collection - uncache elements/purge listeners on orphaned elements
  18516. // so we don't hold a reference and cause the browser to retain them
  18517. function garbageCollect() {
  18518. if (!Ext.enableGarbageCollector) {
  18519. clearInterval(El.collectorThreadId);
  18520. } else {
  18521. var eid,
  18522. el,
  18523. d,
  18524. o;
  18525. for (eid in EC) {
  18526. if (!EC.hasOwnProperty(eid)) {
  18527. continue;
  18528. }
  18529. o = EC[eid];
  18530. if (o.skipGarbageCollection) {
  18531. continue;
  18532. }
  18533. el = o.el;
  18534. if (!el) {
  18535. continue;
  18536. }
  18537. d = el.dom;
  18538. // -------------------------------------------------------
  18539. // Determining what is garbage:
  18540. // -------------------------------------------------------
  18541. // !d
  18542. // dom node is null, definitely garbage
  18543. // -------------------------------------------------------
  18544. // !d.parentNode
  18545. // no parentNode == direct orphan, definitely garbage
  18546. // -------------------------------------------------------
  18547. // !d.offsetParent && !document.getElementById(eid)
  18548. // display none elements have no offsetParent so we will
  18549. // also try to look it up by it's id. However, check
  18550. // offsetParent first so we don't do unneeded lookups.
  18551. // This enables collection of elements that are not orphans
  18552. // directly, but somewhere up the line they have an orphan
  18553. // parent.
  18554. // -------------------------------------------------------
  18555. if (!d || !d.parentNode || (!d.offsetParent && !Ext.getElementById(eid))) {
  18556. if (d && Ext.enableListenerCollection) {
  18557. Ext.EventManager.removeAll(d);
  18558. }
  18559. delete EC[eid];
  18560. }
  18561. }
  18562. // Cleanup IE Object leaks
  18563. if (Ext.isIE) {
  18564. var t = {};
  18565. for (eid in EC) {
  18566. if (!EC.hasOwnProperty(eid)) {
  18567. continue;
  18568. }
  18569. t[eid] = EC[eid];
  18570. }
  18571. EC = Ext.cache = t;
  18572. }
  18573. }
  18574. }
  18575. El.collectorThreadId = setInterval(garbageCollect, 30000);
  18576. //Stuff from Element-more.js
  18577. El.addMethods({
  18578. /**
  18579. * Monitors this Element for the mouse leaving. Calls the function after the specified delay only if
  18580. * the mouse was not moved back into the Element within the delay. If the mouse *was* moved
  18581. * back in, the function is not called.
  18582. * @param {Number} delay The delay **in milliseconds** to wait for possible mouse re-entry before calling the handler function.
  18583. * @param {Function} handler The function to call if the mouse remains outside of this Element for the specified time.
  18584. * @param {Object} [scope] The scope (`this` reference) in which the handler function executes. Defaults to this Element.
  18585. * @return {Object} The listeners object which was added to this element so that monitoring can be stopped. Example usage:
  18586. *
  18587. * // Hide the menu if the mouse moves out for 250ms or more
  18588. * this.mouseLeaveMonitor = this.menuEl.monitorMouseLeave(250, this.hideMenu, this);
  18589. *
  18590. * ...
  18591. * // Remove mouseleave monitor on menu destroy
  18592. * this.menuEl.un(this.mouseLeaveMonitor);
  18593. *
  18594. */
  18595. monitorMouseLeave: function(delay, handler, scope) {
  18596. var me = this,
  18597. timer,
  18598. listeners = {
  18599. mouseleave: function(e) {
  18600. timer = setTimeout(Ext.Function.bind(handler, scope||me, [e]), delay);
  18601. },
  18602. mouseenter: function() {
  18603. clearTimeout(timer);
  18604. },
  18605. freezeEvent: true
  18606. };
  18607. me.on(listeners);
  18608. return listeners;
  18609. },
  18610. /**
  18611. * Stops the specified event(s) from bubbling and optionally prevents the default action
  18612. * @param {String/String[]} eventName an event / array of events to stop from bubbling
  18613. * @param {Boolean} [preventDefault] true to prevent the default action too
  18614. * @return {Ext.dom.Element} this
  18615. */
  18616. swallowEvent : function(eventName, preventDefault) {
  18617. var me = this;
  18618. function fn(e) {
  18619. e.stopPropagation();
  18620. if (preventDefault) {
  18621. e.preventDefault();
  18622. }
  18623. }
  18624. if (Ext.isArray(eventName)) {
  18625. var e,
  18626. eLen = eventName.length;
  18627. for (e = 0; e < eLen; e++) {
  18628. me.on(eventName[e], fn);
  18629. }
  18630. return me;
  18631. }
  18632. me.on(eventName, fn);
  18633. return me;
  18634. },
  18635. /**
  18636. * Create an event handler on this element such that when the event fires and is handled by this element,
  18637. * it will be relayed to another object (i.e., fired again as if it originated from that object instead).
  18638. * @param {String} eventName The type of event to relay
  18639. * @param {Object} observable Any object that extends {@link Ext.util.Observable} that will provide the context
  18640. * for firing the relayed event
  18641. */
  18642. relayEvent : function(eventName, observable) {
  18643. this.on(eventName, function(e) {
  18644. observable.fireEvent(eventName, e);
  18645. });
  18646. },
  18647. /**
  18648. * Removes Empty, or whitespace filled text nodes. Combines adjacent text nodes.
  18649. * @param {Boolean} [forceReclean=false] By default the element keeps track if it has been cleaned already
  18650. * so you can call this over and over. However, if you update the element and need to force a reclean, you
  18651. * can pass true.
  18652. */
  18653. clean : function(forceReclean) {
  18654. var me = this,
  18655. dom = me.dom,
  18656. data = (me.$cache || me.getCache()).data,
  18657. n = dom.firstChild,
  18658. ni = -1,
  18659. nx;
  18660. if (data.isCleaned && forceReclean !== true) {
  18661. return me;
  18662. }
  18663. while (n) {
  18664. nx = n.nextSibling;
  18665. if (n.nodeType == 3) {
  18666. // Remove empty/whitespace text nodes
  18667. if (!(nonSpaceRe.test(n.nodeValue))) {
  18668. dom.removeChild(n);
  18669. // Combine adjacent text nodes
  18670. } else if (nx && nx.nodeType == 3) {
  18671. n.appendData(Ext.String.trim(nx.data));
  18672. dom.removeChild(nx);
  18673. nx = n.nextSibling;
  18674. n.nodeIndex = ++ni;
  18675. }
  18676. } else {
  18677. // Recursively clean
  18678. Ext.fly(n).clean();
  18679. n.nodeIndex = ++ni;
  18680. }
  18681. n = nx;
  18682. }
  18683. data.isCleaned = true;
  18684. return me;
  18685. },
  18686. /**
  18687. * Direct access to the Ext.ElementLoader {@link Ext.ElementLoader#method-load} method. The method takes the same object
  18688. * parameter as {@link Ext.ElementLoader#method-load}
  18689. * @return {Ext.dom.Element} this
  18690. */
  18691. load : function(options) {
  18692. this.getLoader().load(options);
  18693. return this;
  18694. },
  18695. /**
  18696. * Gets this element's {@link Ext.ElementLoader ElementLoader}
  18697. * @return {Ext.ElementLoader} The loader
  18698. */
  18699. getLoader : function() {
  18700. var me = this,
  18701. data = (me.$cache || me.getCache()).data,
  18702. loader = data.loader;
  18703. if (!loader) {
  18704. data.loader = loader = new Ext.ElementLoader({
  18705. target: me
  18706. });
  18707. }
  18708. return loader;
  18709. },
  18710. /**
  18711. * Updates the innerHTML of this element, optionally searching for and processing scripts.
  18712. * @param {String} html The new HTML
  18713. * @param {Boolean} [loadScripts] True to look for and process scripts (defaults to false)
  18714. * @param {Function} [callback] For async script loading you can be notified when the update completes
  18715. * @return {Ext.dom.Element} this
  18716. */
  18717. update : function(html, loadScripts, callback) {
  18718. var me = this,
  18719. id,
  18720. dom,
  18721. interval;
  18722. if (!me.dom) {
  18723. return me;
  18724. }
  18725. html = html || '';
  18726. dom = me.dom;
  18727. if (loadScripts !== true) {
  18728. dom.innerHTML = html;
  18729. Ext.callback(callback, me);
  18730. return me;
  18731. }
  18732. id = Ext.id();
  18733. html += '<span id="' + id + '"></span>';
  18734. interval = setInterval(function() {
  18735. if (!(el = DOC.getElementById(id))) {
  18736. return false;
  18737. }
  18738. clearInterval(interval);
  18739. Ext.removeNode(el);
  18740. var hd = Ext.getHead().dom,
  18741. match,
  18742. attrs,
  18743. srcMatch,
  18744. typeMatch,
  18745. el,
  18746. s;
  18747. while ((match = scriptTagRe.exec(html))) {
  18748. attrs = match[1];
  18749. srcMatch = attrs ? attrs.match(srcRe) : false;
  18750. if (srcMatch && srcMatch[2]) {
  18751. s = DOC.createElement("script");
  18752. s.src = srcMatch[2];
  18753. typeMatch = attrs.match(typeRe);
  18754. if (typeMatch && typeMatch[2]) {
  18755. s.type = typeMatch[2];
  18756. }
  18757. hd.appendChild(s);
  18758. } else if (match[2] && match[2].length > 0) {
  18759. if (window.execScript) {
  18760. window.execScript(match[2]);
  18761. } else {
  18762. window.eval(match[2]);
  18763. }
  18764. }
  18765. }
  18766. Ext.callback(callback, me);
  18767. }, 20);
  18768. dom.innerHTML = html.replace(replaceScriptTagRe, '');
  18769. return me;
  18770. },
  18771. // inherit docs, overridden so we can add removeAnchor
  18772. removeAllListeners : function() {
  18773. this.removeAnchor();
  18774. Ext.EventManager.removeAll(this.dom);
  18775. return this;
  18776. },
  18777. /**
  18778. * Creates a proxy element of this element
  18779. * @param {String/Object} config The class name of the proxy element or a DomHelper config object
  18780. * @param {String/HTMLElement} [renderTo] The element or element id to render the proxy to. Defaults to: document.body.
  18781. * @param {Boolean} [matchBox=false] True to align and size the proxy to this element now.
  18782. * @return {Ext.dom.Element} The new proxy element
  18783. */
  18784. createProxy : function(config, renderTo, matchBox) {
  18785. config = (typeof config == 'object') ? config : {tag : "div", cls: config};
  18786. var me = this,
  18787. proxy = renderTo ? Ext.DomHelper.append(renderTo, config, true) :
  18788. Ext.DomHelper.insertBefore(me.dom, config, true);
  18789. proxy.setVisibilityMode(Element.DISPLAY);
  18790. proxy.hide();
  18791. if (matchBox && me.setBox && me.getBox) { // check to make sure Element.position.js is loaded
  18792. proxy.setBox(me.getBox());
  18793. }
  18794. return proxy;
  18795. },
  18796. /**
  18797. * Gets the parent node of the current element taking into account Ext.scopeResetCSS
  18798. * @protected
  18799. * @return {HTMLElement} The parent element
  18800. */
  18801. getScopeParent: function() {
  18802. var parent = this.dom.parentNode;
  18803. return Ext.scopeResetCSS ? parent.parentNode : parent;
  18804. },
  18805. /**
  18806. * Returns true if this element needs an explicit tabIndex to make it focusable. Input fields, text areas, buttons
  18807. * anchors elements **with an href** etc do not need a tabIndex, but structural elements do.
  18808. */
  18809. needsTabIndex: function() {
  18810. if (this.dom) {
  18811. if ((this.dom.nodeName === 'a') && (!this.dom.href)) {
  18812. return true;
  18813. }
  18814. return !focusRe.test(this.dom.nodeName);
  18815. }
  18816. },
  18817. /**
  18818. * Checks whether this element can be focused.
  18819. * @return {Boolean} True if the element is focusable
  18820. */
  18821. focusable: function () {
  18822. var dom = this.dom,
  18823. nodeName = dom.nodeName,
  18824. canFocus = false;
  18825. if (!dom.disabled) {
  18826. if (focusRe.test(nodeName)) {
  18827. if ((nodeName !== 'a') || dom.href) {
  18828. canFocus = true;
  18829. }
  18830. } else {
  18831. canFocus = !isNaN(dom.tabIndex);
  18832. }
  18833. }
  18834. return canFocus && this.isVisible(true);
  18835. }
  18836. });
  18837. if (Ext.isIE) {
  18838. El.prototype.getById = function (id, asDom) {
  18839. var dom = this.dom,
  18840. cached, el, ret;
  18841. if (dom) {
  18842. // for normal elements getElementById is the best solution, but if the el is
  18843. // not part of the document.body, we need to use all[]
  18844. el = (useDocForId && DOC.getElementById(id)) || dom.all[id];
  18845. if (el) {
  18846. if (asDom) {
  18847. ret = el;
  18848. } else {
  18849. // calling El.get here is a real hit (2x slower) because it has to
  18850. // redetermine that we are giving it a dom el.
  18851. cached = EC[id];
  18852. if (cached && cached.el) {
  18853. ret = cached.el;
  18854. ret.dom = el;
  18855. } else {
  18856. ret = new Element(el);
  18857. }
  18858. }
  18859. return ret;
  18860. }
  18861. }
  18862. return asDom ? Ext.getDom(id) : El.get(id);
  18863. };
  18864. }
  18865. El.createAlias({
  18866. /**
  18867. * @method
  18868. * @inheritdoc Ext.dom.Element#on
  18869. * Shorthand for {@link #on}.
  18870. */
  18871. addListener: 'on',
  18872. /**
  18873. * @method
  18874. * @inheritdoc Ext.dom.Element#un
  18875. * Shorthand for {@link #un}.
  18876. */
  18877. removeListener: 'un',
  18878. /**
  18879. * @method
  18880. * @inheritdoc Ext.dom.Element#removeAllListeners
  18881. * Alias for {@link #removeAllListeners}.
  18882. */
  18883. clearListeners: 'removeAllListeners'
  18884. });
  18885. El.Fly = AbstractElement.Fly = new Ext.Class({
  18886. extend: El,
  18887. constructor: function(dom) {
  18888. this.dom = dom;
  18889. },
  18890. attach: AbstractElement.Fly.prototype.attach
  18891. });
  18892. if (Ext.isIE) {
  18893. Ext.getElementById = function (id) {
  18894. var el = DOC.getElementById(id),
  18895. detachedBodyEl;
  18896. if (!el && (detachedBodyEl = AbstractElement.detachedBodyEl)) {
  18897. el = detachedBodyEl.dom.all[id];
  18898. }
  18899. return el;
  18900. };
  18901. } else if (!DOC.querySelector) {
  18902. Ext.getDetachedBody = Ext.getBody;
  18903. Ext.getElementById = function (id) {
  18904. return DOC.getElementById(id);
  18905. };
  18906. }
  18907. });
  18908. })();
  18909. /**
  18910. * @class Ext.dom.Element
  18911. */
  18912. Ext.dom.Element.override((function() {
  18913. var doc = document,
  18914. win = window,
  18915. alignRe = /^([a-z]+)-([a-z]+)(\?)?$/,
  18916. round = Math.round;
  18917. return {
  18918. /**
  18919. * Gets the x,y coordinates specified by the anchor position on the element.
  18920. * @param {String} [anchor='c'] The specified anchor position. See {@link #alignTo}
  18921. * for details on supported anchor positions.
  18922. * @param {Boolean} [local] True to get the local (element top/left-relative) anchor position instead
  18923. * of page coordinates
  18924. * @param {Object} [size] An object containing the size to use for calculating anchor position
  18925. * {width: (target width), height: (target height)} (defaults to the element's current size)
  18926. * @return {Number[]} [x, y] An array containing the element's x and y coordinates
  18927. */
  18928. getAnchorXY: function(anchor, local, mySize) {
  18929. //Passing a different size is useful for pre-calculating anchors,
  18930. //especially for anchored animations that change the el size.
  18931. anchor = (anchor || "tl").toLowerCase();
  18932. mySize = mySize || {};
  18933. var me = this,
  18934. isViewport = me.dom == doc.body || me.dom == doc,
  18935. myWidth = mySize.width || isViewport ? Ext.dom.Element.getViewWidth() : me.getWidth(),
  18936. myHeight = mySize.height || isViewport ? Ext.dom.Element.getViewHeight() : me.getHeight(),
  18937. xy,
  18938. myPos = me.getXY(),
  18939. scroll = me.getScroll(),
  18940. extraX = isViewport ? scroll.left : !local ? myPos[0] : 0,
  18941. extraY = isViewport ? scroll.top : !local ? myPos[1] : 0;
  18942. // Calculate anchor position.
  18943. // Test most common cases for picker alignment first.
  18944. switch (anchor) {
  18945. case 'tl' : xy = [ 0, 0];
  18946. break;
  18947. case 'bl' : xy = [ 0, myHeight];
  18948. break;
  18949. case 'tr' : xy = [ myWidth, 0];
  18950. break;
  18951. case 'c' : xy = [ round(myWidth * 0.5), round(myHeight * 0.5)];
  18952. break;
  18953. case 't' : xy = [ round(myWidth * 0.5), 0];
  18954. break;
  18955. case 'l' : xy = [ 0, round(myHeight * 0.5)];
  18956. break;
  18957. case 'r' : xy = [ myWidth, round(myHeight * 0.5)];
  18958. break;
  18959. case 'b' : xy = [ round(myWidth * 0.5), myHeight];
  18960. break;
  18961. case 'br' : xy = [ myWidth, myHeight];
  18962. }
  18963. return [xy[0] + extraX, xy[1] + extraY];
  18964. },
  18965. /**
  18966. * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
  18967. * supported position values.
  18968. * @param {String/HTMLElement/Ext.Element} element The element to align to.
  18969. * @param {String} [position="tl-bl?"] The position to align to (defaults to )
  18970. * @param {Number[]} [offsets] Offset the positioning by [x, y]
  18971. * @return {Number[]} [x, y]
  18972. */
  18973. getAlignToXY : function(alignToEl, posSpec, offset) {
  18974. alignToEl = Ext.get(alignToEl);
  18975. if (!alignToEl || !alignToEl.dom) {
  18976. }
  18977. offset = offset || [0,0];
  18978. posSpec = (!posSpec || posSpec == "?" ? "tl-bl?" : (!(/-/).test(posSpec) && posSpec !== "" ? "tl-" + posSpec : posSpec || "tl-bl")).toLowerCase();
  18979. var me = this,
  18980. myPosition,
  18981. alignToElPosition,
  18982. x,
  18983. y,
  18984. myWidth,
  18985. myHeight,
  18986. alignToElRegion,
  18987. viewportWidth = Ext.dom.Element.getViewWidth() - 10, // 10px of margin for ie
  18988. viewportHeight = Ext.dom.Element.getViewHeight() - 10, // 10px of margin for ie
  18989. p1y,
  18990. p1x,
  18991. p2y,
  18992. p2x,
  18993. swapY,
  18994. swapX,
  18995. docElement = doc.documentElement,
  18996. docBody = doc.body,
  18997. scrollX = (docElement.scrollLeft || docBody.scrollLeft || 0),// + 5, WHY was 5 ever added?
  18998. scrollY = (docElement.scrollTop || docBody.scrollTop || 0),// + 5, It means align will fail if the alignTo el was at less than 5,5
  18999. constrain, //constrain to viewport
  19000. align1,
  19001. align2,
  19002. alignMatch = posSpec.match(alignRe);
  19003. align1 = alignMatch[1];
  19004. align2 = alignMatch[2];
  19005. constrain = !!alignMatch[3];
  19006. //Subtract the aligned el's internal xy from the target's offset xy
  19007. //plus custom offset to get this Element's new offset xy
  19008. myPosition = me.getAnchorXY(align1, true);
  19009. alignToElPosition = alignToEl.getAnchorXY(align2, false);
  19010. x = alignToElPosition[0] - myPosition[0] + offset[0];
  19011. y = alignToElPosition[1] - myPosition[1] + offset[1];
  19012. // If position spec ended with a "?", then constrain to viewport is necessary
  19013. if (constrain) {
  19014. myWidth = me.getWidth();
  19015. myHeight = me.getHeight();
  19016. alignToElRegion = alignToEl.getRegion();
  19017. //If we are at a viewport boundary and the aligned el is anchored on a target border that is
  19018. //perpendicular to the vp border, allow the aligned el to slide on that border,
  19019. //otherwise swap the aligned el to the opposite border of the target.
  19020. p1y = align1.charAt(0);
  19021. p1x = align1.charAt(align1.length - 1);
  19022. p2y = align2.charAt(0);
  19023. p2x = align2.charAt(align2.length - 1);
  19024. swapY = ((p1y == "t" && p2y == "b") || (p1y == "b" && p2y == "t"));
  19025. swapX = ((p1x == "r" && p2x == "l") || (p1x == "l" && p2x == "r"));
  19026. if (x + myWidth > viewportWidth + scrollX) {
  19027. x = swapX ? alignToElRegion.left - myWidth : viewportWidth + scrollX - myWidth;
  19028. }
  19029. if (x < scrollX) {
  19030. x = swapX ? alignToElRegion.right : scrollX;
  19031. }
  19032. if (y + myHeight > viewportHeight + scrollY) {
  19033. y = swapY ? alignToElRegion.top - myHeight : viewportHeight + scrollY - myHeight;
  19034. }
  19035. if (y < scrollY) {
  19036. y = swapY ? alignToElRegion.bottom : scrollY;
  19037. }
  19038. }
  19039. return [x,y];
  19040. },
  19041. /**
  19042. * Anchors an element to another element and realigns it when the window is resized.
  19043. * @param {String/HTMLElement/Ext.Element} element The element to align to.
  19044. * @param {String} position The position to align to.
  19045. * @param {Number[]} [offsets] Offset the positioning by [x, y]
  19046. * @param {Boolean/Object} [animate] True for the default animation or a standard Element animation config object
  19047. * @param {Boolean/Number} [monitorScroll] True to monitor body scroll and reposition. If this parameter
  19048. * is a number, it is used as the buffer delay (defaults to 50ms).
  19049. * @param {Function} [callback] The function to call after the animation finishes
  19050. * @return {Ext.Element} this
  19051. */
  19052. anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback) {
  19053. var me = this,
  19054. dom = me.dom,
  19055. scroll = !Ext.isEmpty(monitorScroll),
  19056. action = function() {
  19057. Ext.fly(dom).alignTo(el, alignment, offsets, animate);
  19058. Ext.callback(callback, Ext.fly(dom));
  19059. },
  19060. anchor = this.getAnchor();
  19061. // previous listener anchor, remove it
  19062. this.removeAnchor();
  19063. Ext.apply(anchor, {
  19064. fn: action,
  19065. scroll: scroll
  19066. });
  19067. Ext.EventManager.onWindowResize(action, null);
  19068. if (scroll) {
  19069. Ext.EventManager.on(win, 'scroll', action, null,
  19070. {buffer: !isNaN(monitorScroll) ? monitorScroll : 50});
  19071. }
  19072. action.call(me); // align immediately
  19073. return me;
  19074. },
  19075. /**
  19076. * Remove any anchor to this element. See {@link #anchorTo}.
  19077. * @return {Ext.dom.Element} this
  19078. */
  19079. removeAnchor : function() {
  19080. var me = this,
  19081. anchor = this.getAnchor();
  19082. if (anchor && anchor.fn) {
  19083. Ext.EventManager.removeResizeListener(anchor.fn);
  19084. if (anchor.scroll) {
  19085. Ext.EventManager.un(win, 'scroll', anchor.fn);
  19086. }
  19087. delete anchor.fn;
  19088. }
  19089. return me;
  19090. },
  19091. getAlignVector: function(el, spec, offset) {
  19092. var me = this,
  19093. myPos = me.getXY(),
  19094. alignedPos = me.getAlignToXY(el, spec, offset);
  19095. el = Ext.get(el);
  19096. alignedPos[0] -= myPos[0];
  19097. alignedPos[1] -= myPos[1];
  19098. return alignedPos;
  19099. },
  19100. /**
  19101. * Aligns this element with another element relative to the specified anchor points. If the other element is the
  19102. * document it aligns it to the viewport. The position parameter is optional, and can be specified in any one of
  19103. * the following formats:
  19104. *
  19105. * - **Blank**: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").
  19106. * - **One anchor (deprecated)**: The passed anchor position is used as the target element's anchor point.
  19107. * The element being aligned will position its top-left corner (tl) to that point. *This method has been
  19108. * deprecated in favor of the newer two anchor syntax below*.
  19109. * - **Two anchors**: If two values from the table below are passed separated by a dash, the first value is used as the
  19110. * element's anchor point, and the second value is used as the target's anchor point.
  19111. *
  19112. * In addition to the anchor points, the position parameter also supports the "?" character. If "?" is passed at the end of
  19113. * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
  19114. * the viewport if necessary. Note that the element being aligned might be swapped to align to a different position than
  19115. * that specified in order to enforce the viewport constraints.
  19116. * Following are all of the supported anchor positions:
  19117. *
  19118. * <pre>
  19119. * Value Description
  19120. * ----- -----------------------------
  19121. * tl The top left corner (default)
  19122. * t The center of the top edge
  19123. * tr The top right corner
  19124. * l The center of the left edge
  19125. * c In the center of the element
  19126. * r The center of the right edge
  19127. * bl The bottom left corner
  19128. * b The center of the bottom edge
  19129. * br The bottom right corner
  19130. * </pre>
  19131. *
  19132. * Example Usage:
  19133. *
  19134. * // align el to other-el using the default positioning ("tl-bl", non-constrained)
  19135. * el.alignTo("other-el");
  19136. *
  19137. * // align the top left corner of el with the top right corner of other-el (constrained to viewport)
  19138. * el.alignTo("other-el", "tr?");
  19139. *
  19140. * // align the bottom right corner of el with the center left edge of other-el
  19141. * el.alignTo("other-el", "br-l?");
  19142. *
  19143. * // align the center of el with the bottom left corner of other-el and
  19144. * // adjust the x position by -6 pixels (and the y position by 0)
  19145. * el.alignTo("other-el", "c-bl", [-6, 0]);
  19146. *
  19147. * @param {String/HTMLElement/Ext.Element} element The element to align to.
  19148. * @param {String} [position="tl-bl?"] The position to align to
  19149. * @param {Number[]} [offsets] Offset the positioning by [x, y]
  19150. * @param {Boolean/Object} [animate] true for the default animation or a standard Element animation config object
  19151. * @return {Ext.Element} this
  19152. */
  19153. alignTo: function(element, position, offsets, animate) {
  19154. var me = this;
  19155. return me.setXY(me.getAlignToXY(element, position, offsets),
  19156. me.anim && !!animate ? me.anim(animate) : false);
  19157. },
  19158. /**
  19159. * Returns the `[X, Y]` vector by which this element must be translated to make a best attempt
  19160. * to constrain within the passed constraint. Returns `false` is this element does not need to be moved.
  19161. *
  19162. * Priority is given to constraining the top and left within the constraint.
  19163. *
  19164. * The constraint may either be an existing element into which this element is to be constrained, or
  19165. * an {@link Ext.util.Region Region} into which this element is to be constrained.
  19166. *
  19167. * @param {Ext.Element/Ext.util.Region} constrainTo The Element or Region into which this element is to be constrained.
  19168. * @param {Number[]} proposedPosition A proposed `[X, Y]` position to test for validity and to produce a vector for instead
  19169. * of using this Element's current position;
  19170. * @returns {Number[]/Boolean} **If** this element *needs* to be translated, an `[X, Y]`
  19171. * vector by which this element must be translated. Otherwise, `false`.
  19172. */
  19173. getConstrainVector: function(constrainTo, proposedPosition) {
  19174. if (!(constrainTo instanceof Ext.util.Region)) {
  19175. constrainTo = Ext.get(constrainTo).getViewRegion();
  19176. }
  19177. var thisRegion = this.getRegion(),
  19178. vector = [0, 0],
  19179. shadowSize = this.shadow && this.shadow.offset,
  19180. overflowed = false;
  19181. // Shift this region to occupy the proposed position
  19182. if (proposedPosition) {
  19183. thisRegion.translateBy(proposedPosition[0] - thisRegion.x, proposedPosition[1] - thisRegion.y);
  19184. }
  19185. // Reduce the constrain region to allow for shadow
  19186. // TODO: Rewrite the Shadow class. When that's done, get the extra for each side from the Shadow.
  19187. if (shadowSize) {
  19188. constrainTo.adjust(0, -shadowSize, -shadowSize, shadowSize);
  19189. }
  19190. // Constrain the X coordinate by however much this Element overflows
  19191. if (thisRegion.right > constrainTo.right) {
  19192. overflowed = true;
  19193. vector[0] = (constrainTo.right - thisRegion.right); // overflowed the right
  19194. }
  19195. if (thisRegion.left + vector[0] < constrainTo.left) {
  19196. overflowed = true;
  19197. vector[0] = (constrainTo.left - thisRegion.left); // overflowed the left
  19198. }
  19199. // Constrain the Y coordinate by however much this Element overflows
  19200. if (thisRegion.bottom > constrainTo.bottom) {
  19201. overflowed = true;
  19202. vector[1] = (constrainTo.bottom - thisRegion.bottom); // overflowed the bottom
  19203. }
  19204. if (thisRegion.top + vector[1] < constrainTo.top) {
  19205. overflowed = true;
  19206. vector[1] = (constrainTo.top - thisRegion.top); // overflowed the top
  19207. }
  19208. return overflowed ? vector : false;
  19209. },
  19210. /**
  19211. * Calculates the x, y to center this element on the screen
  19212. * @return {Number[]} The x, y values [x, y]
  19213. */
  19214. getCenterXY : function(){
  19215. return this.getAlignToXY(doc, 'c-c');
  19216. },
  19217. /**
  19218. * Centers the Element in either the viewport, or another Element.
  19219. * @param {String/HTMLElement/Ext.Element} [centerIn] The element in which to center the element.
  19220. */
  19221. center : function(centerIn){
  19222. return this.alignTo(centerIn || doc, 'c-c');
  19223. }
  19224. };
  19225. })());
  19226. /**
  19227. * @class Ext.dom.Element
  19228. */
  19229. /* ================================
  19230. * A Note About Wrapped Animations
  19231. * ================================
  19232. * A few of the effects below implement two different animations per effect, one wrapping
  19233. * animation that performs the visual effect and a "no-op" animation on this Element where
  19234. * no attributes of the element itself actually change. The purpose for this is that the
  19235. * wrapper is required for the effect to work and so it does the actual animation work, but
  19236. * we always animate `this` so that the element's events and callbacks work as expected to
  19237. * the callers of this API.
  19238. *
  19239. * Because of this, we always want each wrap animation to complete first (we don't want to
  19240. * cut off the visual effect early). To ensure that, we arbitrarily increase the duration of
  19241. * the element's no-op animation, also ensuring that it has a decent minimum value -- on slow
  19242. * systems, too-low durations can cause race conditions between the wrap animation and the
  19243. * element animation being removed out of order. Note that in each wrap's `afteranimate`
  19244. * callback it will explicitly terminate the element animation as soon as the wrap is complete,
  19245. * so there's no real danger in making the duration too long.
  19246. *
  19247. * This applies to all effects that get wrapped, including slideIn, slideOut, switchOff and frame.
  19248. */
  19249. Ext.dom.Element.override({
  19250. // @private override base Ext.util.Animate mixin for animate for backwards compatibility
  19251. animate: function(config) {
  19252. var me = this,
  19253. listeners,
  19254. anim,
  19255. animId = me.dom.id || Ext.id(me.dom);
  19256. if (!Ext.fx.Manager.hasFxBlock(animId)) {
  19257. // Bit of gymnastics here to ensure our internal listeners get bound first
  19258. if (config.listeners) {
  19259. listeners = config.listeners;
  19260. delete config.listeners;
  19261. }
  19262. if (config.internalListeners) {
  19263. config.listeners = config.internalListeners;
  19264. delete config.internalListeners;
  19265. }
  19266. anim = new Ext.fx.Anim(me.anim(config));
  19267. if (listeners) {
  19268. anim.on(listeners);
  19269. }
  19270. Ext.fx.Manager.queueFx(anim);
  19271. }
  19272. return me;
  19273. },
  19274. // @private override base Ext.util.Animate mixin for animate for backwards compatibility
  19275. anim: function(config) {
  19276. if (!Ext.isObject(config)) {
  19277. return (config) ? {} : false;
  19278. }
  19279. var me = this,
  19280. duration = config.duration || Ext.fx.Anim.prototype.duration,
  19281. easing = config.easing || 'ease',
  19282. animConfig;
  19283. if (config.stopAnimation) {
  19284. me.stopAnimation();
  19285. }
  19286. Ext.applyIf(config, Ext.fx.Manager.getFxDefaults(me.id));
  19287. // Clear any 'paused' defaults.
  19288. Ext.fx.Manager.setFxDefaults(me.id, {
  19289. delay: 0
  19290. });
  19291. animConfig = {
  19292. // Pass the DOM reference. That's tested first so will be converted to an Ext.fx.Target fastest.
  19293. target: me.dom,
  19294. remove: config.remove,
  19295. alternate: config.alternate || false,
  19296. duration: duration,
  19297. easing: easing,
  19298. callback: config.callback,
  19299. listeners: config.listeners,
  19300. iterations: config.iterations || 1,
  19301. scope: config.scope,
  19302. block: config.block,
  19303. concurrent: config.concurrent,
  19304. delay: config.delay || 0,
  19305. paused: true,
  19306. keyframes: config.keyframes,
  19307. from: config.from || {},
  19308. to: Ext.apply({}, config)
  19309. };
  19310. Ext.apply(animConfig.to, config.to);
  19311. // Anim API properties - backward compat
  19312. delete animConfig.to.to;
  19313. delete animConfig.to.from;
  19314. delete animConfig.to.remove;
  19315. delete animConfig.to.alternate;
  19316. delete animConfig.to.keyframes;
  19317. delete animConfig.to.iterations;
  19318. delete animConfig.to.listeners;
  19319. delete animConfig.to.target;
  19320. delete animConfig.to.paused;
  19321. delete animConfig.to.callback;
  19322. delete animConfig.to.scope;
  19323. delete animConfig.to.duration;
  19324. delete animConfig.to.easing;
  19325. delete animConfig.to.concurrent;
  19326. delete animConfig.to.block;
  19327. delete animConfig.to.stopAnimation;
  19328. delete animConfig.to.delay;
  19329. return animConfig;
  19330. },
  19331. /**
  19332. * Slides the element into view. An anchor point can be optionally passed to set the point of origin for the slide
  19333. * effect. This function automatically handles wrapping the element with a fixed-size container if needed. See the
  19334. * Fx class overview for valid anchor point options. Usage:
  19335. *
  19336. * // default: slide the element in from the top
  19337. * el.slideIn();
  19338. *
  19339. * // custom: slide the element in from the right with a 2-second duration
  19340. * el.slideIn('r', { duration: 2000 });
  19341. *
  19342. * // common config options shown with default values
  19343. * el.slideIn('t', {
  19344. * easing: 'easeOut',
  19345. * duration: 500
  19346. * });
  19347. *
  19348. * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
  19349. * @param {Object} options (optional) Object literal with any of the Fx config options
  19350. * @return {Ext.dom.Element} The Element
  19351. */
  19352. slideIn: function(anchor, obj, slideOut) {
  19353. var me = this,
  19354. elStyle = me.dom.style,
  19355. beforeAnim, wrapAnim;
  19356. anchor = anchor || "t";
  19357. obj = obj || {};
  19358. beforeAnim = function() {
  19359. var animScope = this,
  19360. listeners = obj.listeners,
  19361. box, originalStyles, anim, wrap;
  19362. if (!slideOut) {
  19363. me.fixDisplay();
  19364. }
  19365. box = me.getBox();
  19366. if ((anchor == 't' || anchor == 'b') && box.height === 0) {
  19367. box.height = me.dom.scrollHeight;
  19368. }
  19369. else if ((anchor == 'l' || anchor == 'r') && box.width === 0) {
  19370. box.width = me.dom.scrollWidth;
  19371. }
  19372. originalStyles = me.getStyles('width', 'height', 'left', 'right', 'top', 'bottom', 'position', 'z-index', true);
  19373. me.setSize(box.width, box.height);
  19374. wrap = me.wrap({
  19375. id: Ext.id() + '-anim-wrap-for-' + me.id,
  19376. style: {
  19377. visibility: slideOut ? 'visible' : 'hidden'
  19378. }
  19379. });
  19380. wrap.setPositioning(me.getPositioning());
  19381. if (wrap.isStyle('position', 'static')) {
  19382. wrap.position('relative');
  19383. }
  19384. me.clearPositioning('auto');
  19385. wrap.clip();
  19386. // This element is temporarily positioned absolute within its wrapper.
  19387. // Restore to its default, CSS-inherited visibility setting.
  19388. // We cannot explicitly poke visibility:visible into its style because that overrides the visibility of the wrap.
  19389. me.setStyle({
  19390. visibility: '',
  19391. position: 'absolute'
  19392. });
  19393. if (slideOut) {
  19394. wrap.setSize(box.width, box.height);
  19395. }
  19396. switch (anchor) {
  19397. case 't':
  19398. anim = {
  19399. from: {
  19400. width: box.width + 'px',
  19401. height: '0px'
  19402. },
  19403. to: {
  19404. width: box.width + 'px',
  19405. height: box.height + 'px'
  19406. }
  19407. };
  19408. elStyle.bottom = '0px';
  19409. break;
  19410. case 'l':
  19411. anim = {
  19412. from: {
  19413. width: '0px',
  19414. height: box.height + 'px'
  19415. },
  19416. to: {
  19417. width: box.width + 'px',
  19418. height: box.height + 'px'
  19419. }
  19420. };
  19421. elStyle.right = '0px';
  19422. break;
  19423. case 'r':
  19424. anim = {
  19425. from: {
  19426. x: box.x + box.width,
  19427. width: '0px',
  19428. height: box.height + 'px'
  19429. },
  19430. to: {
  19431. x: box.x,
  19432. width: box.width + 'px',
  19433. height: box.height + 'px'
  19434. }
  19435. };
  19436. break;
  19437. case 'b':
  19438. anim = {
  19439. from: {
  19440. y: box.y + box.height,
  19441. width: box.width + 'px',
  19442. height: '0px'
  19443. },
  19444. to: {
  19445. y: box.y,
  19446. width: box.width + 'px',
  19447. height: box.height + 'px'
  19448. }
  19449. };
  19450. break;
  19451. case 'tl':
  19452. anim = {
  19453. from: {
  19454. x: box.x,
  19455. y: box.y,
  19456. width: '0px',
  19457. height: '0px'
  19458. },
  19459. to: {
  19460. width: box.width + 'px',
  19461. height: box.height + 'px'
  19462. }
  19463. };
  19464. elStyle.bottom = '0px';
  19465. elStyle.right = '0px';
  19466. break;
  19467. case 'bl':
  19468. anim = {
  19469. from: {
  19470. x: box.x + box.width,
  19471. width: '0px',
  19472. height: '0px'
  19473. },
  19474. to: {
  19475. x: box.x,
  19476. width: box.width + 'px',
  19477. height: box.height + 'px'
  19478. }
  19479. };
  19480. elStyle.right = '0px';
  19481. break;
  19482. case 'br':
  19483. anim = {
  19484. from: {
  19485. x: box.x + box.width,
  19486. y: box.y + box.height,
  19487. width: '0px',
  19488. height: '0px'
  19489. },
  19490. to: {
  19491. x: box.x,
  19492. y: box.y,
  19493. width: box.width + 'px',
  19494. height: box.height + 'px'
  19495. }
  19496. };
  19497. break;
  19498. case 'tr':
  19499. anim = {
  19500. from: {
  19501. y: box.y + box.height,
  19502. width: '0px',
  19503. height: '0px'
  19504. },
  19505. to: {
  19506. y: box.y,
  19507. width: box.width + 'px',
  19508. height: box.height + 'px'
  19509. }
  19510. };
  19511. elStyle.bottom = '0px';
  19512. break;
  19513. }
  19514. wrap.show();
  19515. wrapAnim = Ext.apply({}, obj);
  19516. delete wrapAnim.listeners;
  19517. wrapAnim = new Ext.fx.Anim(Ext.applyIf(wrapAnim, {
  19518. target: wrap,
  19519. duration: 500,
  19520. easing: 'ease-out',
  19521. from: slideOut ? anim.to : anim.from,
  19522. to: slideOut ? anim.from : anim.to
  19523. }));
  19524. // In the absence of a callback, this listener MUST be added first
  19525. wrapAnim.on('afteranimate', function() {
  19526. me.setStyle(originalStyles);
  19527. if (slideOut) {
  19528. if (obj.useDisplay) {
  19529. me.setDisplayed(false);
  19530. } else {
  19531. me.hide();
  19532. }
  19533. }
  19534. if (wrap.dom) {
  19535. wrap.dom.parentNode.insertBefore(me.dom, wrap.dom);
  19536. wrap.remove();
  19537. }
  19538. // kill the no-op element animation created below
  19539. animScope.end();
  19540. });
  19541. // Add configured listeners after
  19542. if (listeners) {
  19543. wrapAnim.on(listeners);
  19544. }
  19545. };
  19546. me.animate({
  19547. // See "A Note About Wrapped Animations" at the top of this class:
  19548. duration: obj.duration ? Math.max(obj.duration, 500) * 2 : 1000,
  19549. listeners: {
  19550. beforeanimate: beforeAnim, // kick off the wrap animation
  19551. afteranimate: function() {
  19552. if (wrapAnim && wrapAnim.running) {
  19553. // should never get here, but just to be safe
  19554. wrapAnim.end();
  19555. }
  19556. }
  19557. }
  19558. });
  19559. return me;
  19560. },
  19561. /**
  19562. * Slides the element out of view. An anchor point can be optionally passed to set the end point for the slide
  19563. * effect. When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will
  19564. * still take up space in the document. The element must be removed from the DOM using the 'remove' config option if
  19565. * desired. This function automatically handles wrapping the element with a fixed-size container if needed. See the
  19566. * Fx class overview for valid anchor point options. Usage:
  19567. *
  19568. * // default: slide the element out to the top
  19569. * el.slideOut();
  19570. *
  19571. * // custom: slide the element out to the right with a 2-second duration
  19572. * el.slideOut('r', { duration: 2000 });
  19573. *
  19574. * // common config options shown with default values
  19575. * el.slideOut('t', {
  19576. * easing: 'easeOut',
  19577. * duration: 500,
  19578. * remove: false,
  19579. * useDisplay: false
  19580. * });
  19581. *
  19582. * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
  19583. * @param {Object} options (optional) Object literal with any of the Fx config options
  19584. * @return {Ext.dom.Element} The Element
  19585. */
  19586. slideOut: function(anchor, o) {
  19587. return this.slideIn(anchor, o, true);
  19588. },
  19589. /**
  19590. * Fades the element out while slowly expanding it in all directions. When the effect is completed, the element will
  19591. * be hidden (visibility = 'hidden') but block elements will still take up space in the document. Usage:
  19592. *
  19593. * // default
  19594. * el.puff();
  19595. *
  19596. * // common config options shown with default values
  19597. * el.puff({
  19598. * easing: 'easeOut',
  19599. * duration: 500,
  19600. * useDisplay: false
  19601. * });
  19602. *
  19603. * @param {Object} options (optional) Object literal with any of the Fx config options
  19604. * @return {Ext.dom.Element} The Element
  19605. */
  19606. puff: function(obj) {
  19607. var me = this,
  19608. beforeAnim;
  19609. obj = Ext.applyIf(obj || {}, {
  19610. easing: 'ease-out',
  19611. duration: 500,
  19612. useDisplay: false
  19613. });
  19614. beforeAnim = function() {
  19615. me.clearOpacity();
  19616. me.show();
  19617. var box = me.getBox(),
  19618. fontSize = me.getStyle('fontSize'),
  19619. position = me.getPositioning();
  19620. this.to = {
  19621. width: box.width * 2,
  19622. height: box.height * 2,
  19623. x: box.x - (box.width / 2),
  19624. y: box.y - (box.height /2),
  19625. opacity: 0,
  19626. fontSize: '200%'
  19627. };
  19628. this.on('afteranimate',function() {
  19629. if (me.dom) {
  19630. if (obj.useDisplay) {
  19631. me.setDisplayed(false);
  19632. } else {
  19633. me.hide();
  19634. }
  19635. me.clearOpacity();
  19636. me.setPositioning(position);
  19637. me.setStyle({fontSize: fontSize});
  19638. }
  19639. });
  19640. };
  19641. me.animate({
  19642. duration: obj.duration,
  19643. easing: obj.easing,
  19644. listeners: {
  19645. beforeanimate: {
  19646. fn: beforeAnim
  19647. }
  19648. }
  19649. });
  19650. return me;
  19651. },
  19652. /**
  19653. * Blinks the element as if it was clicked and then collapses on its center (similar to switching off a television).
  19654. * When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will still
  19655. * take up space in the document. The element must be removed from the DOM using the 'remove' config option if
  19656. * desired. Usage:
  19657. *
  19658. * // default
  19659. * el.switchOff();
  19660. *
  19661. * // all config options shown with default values
  19662. * el.switchOff({
  19663. * easing: 'easeIn',
  19664. * duration: .3,
  19665. * remove: false,
  19666. * useDisplay: false
  19667. * });
  19668. *
  19669. * @param {Object} options (optional) Object literal with any of the Fx config options
  19670. * @return {Ext.dom.Element} The Element
  19671. */
  19672. switchOff: function(obj) {
  19673. var me = this,
  19674. beforeAnim;
  19675. obj = Ext.applyIf(obj || {}, {
  19676. easing: 'ease-in',
  19677. duration: 500,
  19678. remove: false,
  19679. useDisplay: false
  19680. });
  19681. beforeAnim = function() {
  19682. var animScope = this,
  19683. size = me.getSize(),
  19684. xy = me.getXY(),
  19685. keyframe, position;
  19686. me.clearOpacity();
  19687. me.clip();
  19688. position = me.getPositioning();
  19689. keyframe = new Ext.fx.Animator({
  19690. target: me,
  19691. duration: obj.duration,
  19692. easing: obj.easing,
  19693. keyframes: {
  19694. 33: {
  19695. opacity: 0.3
  19696. },
  19697. 66: {
  19698. height: 1,
  19699. y: xy[1] + size.height / 2
  19700. },
  19701. 100: {
  19702. width: 1,
  19703. x: xy[0] + size.width / 2
  19704. }
  19705. }
  19706. });
  19707. keyframe.on('afteranimate', function() {
  19708. if (obj.useDisplay) {
  19709. me.setDisplayed(false);
  19710. } else {
  19711. me.hide();
  19712. }
  19713. me.clearOpacity();
  19714. me.setPositioning(position);
  19715. me.setSize(size);
  19716. // kill the no-op element animation created below
  19717. animScope.end();
  19718. });
  19719. };
  19720. me.animate({
  19721. // See "A Note About Wrapped Animations" at the top of this class:
  19722. duration: (Math.max(obj.duration, 500) * 2),
  19723. listeners: {
  19724. beforeanimate: {
  19725. fn: beforeAnim
  19726. }
  19727. }
  19728. });
  19729. return me;
  19730. },
  19731. /**
  19732. * Shows a ripple of exploding, attenuating borders to draw attention to an Element. Usage:
  19733. *
  19734. * // default: a single light blue ripple
  19735. * el.frame();
  19736. *
  19737. * // custom: 3 red ripples lasting 3 seconds total
  19738. * el.frame("#ff0000", 3, { duration: 3 });
  19739. *
  19740. * // common config options shown with default values
  19741. * el.frame("#C3DAF9", 1, {
  19742. * duration: 1 //duration of each individual ripple.
  19743. * // Note: Easing is not configurable and will be ignored if included
  19744. * });
  19745. *
  19746. * @param {String} color (optional) The color of the border. Should be a 6 char hex color without the leading #
  19747. * (defaults to light blue: 'C3DAF9').
  19748. * @param {Number} count (optional) The number of ripples to display (defaults to 1)
  19749. * @param {Object} options (optional) Object literal with any of the Fx config options
  19750. * @return {Ext.dom.Element} The Element
  19751. */
  19752. frame : function(color, count, obj){
  19753. var me = this,
  19754. beforeAnim;
  19755. color = color || '#C3DAF9';
  19756. count = count || 1;
  19757. obj = obj || {};
  19758. beforeAnim = function() {
  19759. me.show();
  19760. var animScope = this,
  19761. box = me.getBox(),
  19762. proxy = Ext.getBody().createChild({
  19763. id: me.id + '-anim-proxy',
  19764. style: {
  19765. position : 'absolute',
  19766. 'pointer-events': 'none',
  19767. 'z-index': 35000,
  19768. border : '0px solid ' + color
  19769. }
  19770. }),
  19771. proxyAnim;
  19772. proxyAnim = new Ext.fx.Anim({
  19773. target: proxy,
  19774. duration: obj.duration || 1000,
  19775. iterations: count,
  19776. from: {
  19777. top: box.y,
  19778. left: box.x,
  19779. borderWidth: 0,
  19780. opacity: 1,
  19781. height: box.height,
  19782. width: box.width
  19783. },
  19784. to: {
  19785. top: box.y - 20,
  19786. left: box.x - 20,
  19787. borderWidth: 10,
  19788. opacity: 0,
  19789. height: box.height + 40,
  19790. width: box.width + 40
  19791. }
  19792. });
  19793. proxyAnim.on('afteranimate', function() {
  19794. proxy.remove();
  19795. // kill the no-op element animation created below
  19796. animScope.end();
  19797. });
  19798. };
  19799. me.animate({
  19800. // See "A Note About Wrapped Animations" at the top of this class:
  19801. duration: (Math.max(obj.duration, 500) * 2) || 2000,
  19802. listeners: {
  19803. beforeanimate: {
  19804. fn: beforeAnim
  19805. }
  19806. }
  19807. });
  19808. return me;
  19809. },
  19810. /**
  19811. * Slides the element while fading it out of view. An anchor point can be optionally passed to set the ending point
  19812. * of the effect. Usage:
  19813. *
  19814. * // default: slide the element downward while fading out
  19815. * el.ghost();
  19816. *
  19817. * // custom: slide the element out to the right with a 2-second duration
  19818. * el.ghost('r', { duration: 2000 });
  19819. *
  19820. * // common config options shown with default values
  19821. * el.ghost('b', {
  19822. * easing: 'easeOut',
  19823. * duration: 500
  19824. * });
  19825. *
  19826. * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to bottom: 'b')
  19827. * @param {Object} options (optional) Object literal with any of the Fx config options
  19828. * @return {Ext.dom.Element} The Element
  19829. */
  19830. ghost: function(anchor, obj) {
  19831. var me = this,
  19832. beforeAnim;
  19833. anchor = anchor || "b";
  19834. beforeAnim = function() {
  19835. var width = me.getWidth(),
  19836. height = me.getHeight(),
  19837. xy = me.getXY(),
  19838. position = me.getPositioning(),
  19839. to = {
  19840. opacity: 0
  19841. };
  19842. switch (anchor) {
  19843. case 't':
  19844. to.y = xy[1] - height;
  19845. break;
  19846. case 'l':
  19847. to.x = xy[0] - width;
  19848. break;
  19849. case 'r':
  19850. to.x = xy[0] + width;
  19851. break;
  19852. case 'b':
  19853. to.y = xy[1] + height;
  19854. break;
  19855. case 'tl':
  19856. to.x = xy[0] - width;
  19857. to.y = xy[1] - height;
  19858. break;
  19859. case 'bl':
  19860. to.x = xy[0] - width;
  19861. to.y = xy[1] + height;
  19862. break;
  19863. case 'br':
  19864. to.x = xy[0] + width;
  19865. to.y = xy[1] + height;
  19866. break;
  19867. case 'tr':
  19868. to.x = xy[0] + width;
  19869. to.y = xy[1] - height;
  19870. break;
  19871. }
  19872. this.to = to;
  19873. this.on('afteranimate', function () {
  19874. if (me.dom) {
  19875. me.hide();
  19876. me.clearOpacity();
  19877. me.setPositioning(position);
  19878. }
  19879. });
  19880. };
  19881. me.animate(Ext.applyIf(obj || {}, {
  19882. duration: 500,
  19883. easing: 'ease-out',
  19884. listeners: {
  19885. beforeanimate: {
  19886. fn: beforeAnim
  19887. }
  19888. }
  19889. }));
  19890. return me;
  19891. },
  19892. /**
  19893. * Highlights the Element by setting a color (applies to the background-color by default, but can be changed using
  19894. * the "attr" config option) and then fading back to the original color. If no original color is available, you
  19895. * should provide the "endColor" config option which will be cleared after the animation. Usage:
  19896. *
  19897. * // default: highlight background to yellow
  19898. * el.highlight();
  19899. *
  19900. * // custom: highlight foreground text to blue for 2 seconds
  19901. * el.highlight("0000ff", { attr: 'color', duration: 2000 });
  19902. *
  19903. * // common config options shown with default values
  19904. * el.highlight("ffff9c", {
  19905. * attr: "backgroundColor", //can be any valid CSS property (attribute) that supports a color value
  19906. * endColor: (current color) or "ffffff",
  19907. * easing: 'easeIn',
  19908. * duration: 1000
  19909. * });
  19910. *
  19911. * @param {String} color (optional) The highlight color. Should be a 6 char hex color without the leading #
  19912. * (defaults to yellow: 'ffff9c')
  19913. * @param {Object} options (optional) Object literal with any of the Fx config options
  19914. * @return {Ext.dom.Element} The Element
  19915. */
  19916. highlight: function(color, o) {
  19917. var me = this,
  19918. dom = me.dom,
  19919. from = {},
  19920. restore, to, attr, lns, event, fn;
  19921. o = o || {};
  19922. lns = o.listeners || {};
  19923. attr = o.attr || 'backgroundColor';
  19924. from[attr] = color || 'ffff9c';
  19925. if (!o.to) {
  19926. to = {};
  19927. to[attr] = o.endColor || me.getColor(attr, 'ffffff', '');
  19928. }
  19929. else {
  19930. to = o.to;
  19931. }
  19932. // Don't apply directly on lns, since we reference it in our own callbacks below
  19933. o.listeners = Ext.apply(Ext.apply({}, lns), {
  19934. beforeanimate: function() {
  19935. restore = dom.style[attr];
  19936. me.clearOpacity();
  19937. me.show();
  19938. event = lns.beforeanimate;
  19939. if (event) {
  19940. fn = event.fn || event;
  19941. return fn.apply(event.scope || lns.scope || window, arguments);
  19942. }
  19943. },
  19944. afteranimate: function() {
  19945. if (dom) {
  19946. dom.style[attr] = restore;
  19947. }
  19948. event = lns.afteranimate;
  19949. if (event) {
  19950. fn = event.fn || event;
  19951. fn.apply(event.scope || lns.scope || window, arguments);
  19952. }
  19953. }
  19954. });
  19955. me.animate(Ext.apply({}, o, {
  19956. duration: 1000,
  19957. easing: 'ease-in',
  19958. from: from,
  19959. to: to
  19960. }));
  19961. return me;
  19962. },
  19963. /**
  19964. * @deprecated 4.0
  19965. * Creates a pause before any subsequent queued effects begin. If there are no effects queued after the pause it will
  19966. * have no effect. Usage:
  19967. *
  19968. * el.pause(1);
  19969. *
  19970. * @param {Number} seconds The length of time to pause (in seconds)
  19971. * @return {Ext.Element} The Element
  19972. */
  19973. pause: function(ms) {
  19974. var me = this;
  19975. Ext.fx.Manager.setFxDefaults(me.id, {
  19976. delay: ms
  19977. });
  19978. return me;
  19979. },
  19980. /**
  19981. * Fade an element in (from transparent to opaque). The ending opacity can be specified using the `opacity`
  19982. * config option. Usage:
  19983. *
  19984. * // default: fade in from opacity 0 to 100%
  19985. * el.fadeIn();
  19986. *
  19987. * // custom: fade in from opacity 0 to 75% over 2 seconds
  19988. * el.fadeIn({ opacity: .75, duration: 2000});
  19989. *
  19990. * // common config options shown with default values
  19991. * el.fadeIn({
  19992. * opacity: 1, //can be any value between 0 and 1 (e.g. .5)
  19993. * easing: 'easeOut',
  19994. * duration: 500
  19995. * });
  19996. *
  19997. * @param {Object} options (optional) Object literal with any of the Fx config options
  19998. * @return {Ext.Element} The Element
  19999. */
  20000. fadeIn: function(o) {
  20001. this.animate(Ext.apply({}, o, {
  20002. opacity: 1
  20003. }));
  20004. return this;
  20005. },
  20006. /**
  20007. * Fade an element out (from opaque to transparent). The ending opacity can be specified using the `opacity`
  20008. * config option. Note that IE may require `useDisplay:true` in order to redisplay correctly.
  20009. * Usage:
  20010. *
  20011. * // default: fade out from the element's current opacity to 0
  20012. * el.fadeOut();
  20013. *
  20014. * // custom: fade out from the element's current opacity to 25% over 2 seconds
  20015. * el.fadeOut({ opacity: .25, duration: 2000});
  20016. *
  20017. * // common config options shown with default values
  20018. * el.fadeOut({
  20019. * opacity: 0, //can be any value between 0 and 1 (e.g. .5)
  20020. * easing: 'easeOut',
  20021. * duration: 500,
  20022. * remove: false,
  20023. * useDisplay: false
  20024. * });
  20025. *
  20026. * @param {Object} options (optional) Object literal with any of the Fx config options
  20027. * @return {Ext.Element} The Element
  20028. */
  20029. fadeOut: function(o) {
  20030. var me = this;
  20031. me.animate(Ext.applyIf(o || {}, {
  20032. opacity: 0,
  20033. internalListeners: {
  20034. afteranimate: function(anim){
  20035. var dom = me.dom;
  20036. if (dom && anim.to.opacity === 0) {
  20037. if (o.useDisplay) {
  20038. me.setDisplayed(false);
  20039. } else {
  20040. me.hide();
  20041. }
  20042. }
  20043. }
  20044. }
  20045. }));
  20046. return me;
  20047. },
  20048. /**
  20049. * @deprecated 4.0
  20050. * Animates the transition of an element's dimensions from a starting height/width to an ending height/width. This
  20051. * method is a convenience implementation of {@link #shift}. Usage:
  20052. *
  20053. * // change height and width to 100x100 pixels
  20054. * el.scale(100, 100);
  20055. *
  20056. * // common config options shown with default values. The height and width will default to
  20057. * // the element's existing values if passed as null.
  20058. * el.scale(
  20059. * [element's width],
  20060. * [element's height], {
  20061. * easing: 'easeOut',
  20062. * duration: .35
  20063. * }
  20064. * );
  20065. *
  20066. * @param {Number} width The new width (pass undefined to keep the original width)
  20067. * @param {Number} height The new height (pass undefined to keep the original height)
  20068. * @param {Object} options (optional) Object literal with any of the Fx config options
  20069. * @return {Ext.Element} The Element
  20070. */
  20071. scale: function(w, h, o) {
  20072. this.animate(Ext.apply({}, o, {
  20073. width: w,
  20074. height: h
  20075. }));
  20076. return this;
  20077. },
  20078. /**
  20079. * @deprecated 4.0
  20080. * Animates the transition of any combination of an element's dimensions, xy position and/or opacity. Any of these
  20081. * properties not specified in the config object will not be changed. This effect requires that at least one new
  20082. * dimension, position or opacity setting must be passed in on the config object in order for the function to have
  20083. * any effect. Usage:
  20084. *
  20085. * // slide the element horizontally to x position 200 while changing the height and opacity
  20086. * el.shift({ x: 200, height: 50, opacity: .8 });
  20087. *
  20088. * // common config options shown with default values.
  20089. * el.shift({
  20090. * width: [element's width],
  20091. * height: [element's height],
  20092. * x: [element's x position],
  20093. * y: [element's y position],
  20094. * opacity: [element's opacity],
  20095. * easing: 'easeOut',
  20096. * duration: .35
  20097. * });
  20098. *
  20099. * @param {Object} options Object literal with any of the Fx config options
  20100. * @return {Ext.Element} The Element
  20101. */
  20102. shift: function(config) {
  20103. this.animate(config);
  20104. return this;
  20105. }
  20106. });
  20107. /**
  20108. * @class Ext.dom.Element
  20109. */
  20110. Ext.dom.Element.override({
  20111. /**
  20112. * Initializes a {@link Ext.dd.DD} drag drop object for this element.
  20113. * @param {String} group The group the DD object is member of
  20114. * @param {Object} config The DD config object
  20115. * @param {Object} overrides An object containing methods to override/implement on the DD object
  20116. * @return {Ext.dd.DD} The DD object
  20117. */
  20118. initDD : function(group, config, overrides){
  20119. var dd = new Ext.dd.DD(Ext.id(this.dom), group, config);
  20120. return Ext.apply(dd, overrides);
  20121. },
  20122. /**
  20123. * Initializes a {@link Ext.dd.DDProxy} object for this element.
  20124. * @param {String} group The group the DDProxy object is member of
  20125. * @param {Object} config The DDProxy config object
  20126. * @param {Object} overrides An object containing methods to override/implement on the DDProxy object
  20127. * @return {Ext.dd.DDProxy} The DDProxy object
  20128. */
  20129. initDDProxy : function(group, config, overrides){
  20130. var dd = new Ext.dd.DDProxy(Ext.id(this.dom), group, config);
  20131. return Ext.apply(dd, overrides);
  20132. },
  20133. /**
  20134. * Initializes a {@link Ext.dd.DDTarget} object for this element.
  20135. * @param {String} group The group the DDTarget object is member of
  20136. * @param {Object} config The DDTarget config object
  20137. * @param {Object} overrides An object containing methods to override/implement on the DDTarget object
  20138. * @return {Ext.dd.DDTarget} The DDTarget object
  20139. */
  20140. initDDTarget : function(group, config, overrides){
  20141. var dd = new Ext.dd.DDTarget(Ext.id(this.dom), group, config);
  20142. return Ext.apply(dd, overrides);
  20143. }
  20144. });
  20145. /**
  20146. * @class Ext.dom.Element
  20147. */
  20148. (function() {
  20149. var Element = Ext.dom.Element,
  20150. VISIBILITY = "visibility",
  20151. DISPLAY = "display",
  20152. NONE = "none",
  20153. HIDDEN = 'hidden',
  20154. OFFSETS = "offsets",
  20155. ASCLASS = "asclass",
  20156. NOSIZE = 'nosize',
  20157. ORIGINALDISPLAY = 'originalDisplay',
  20158. VISMODE = 'visibilityMode',
  20159. ISVISIBLE = 'isVisible',
  20160. getDisplay = function(el){
  20161. var data = (el.$cache || el.getCache()).data,
  20162. display = data[ORIGINALDISPLAY];
  20163. if (display === undefined) {
  20164. data[ORIGINALDISPLAY] = display = '';
  20165. }
  20166. return display;
  20167. },
  20168. getVisMode = function(el){
  20169. var data = (el.$cache || el.getCache()).data,
  20170. visMode = data[VISMODE];
  20171. if (visMode === undefined) {
  20172. data[VISMODE] = visMode = Ext.dom.Element.VISIBILITY;
  20173. }
  20174. return visMode;
  20175. };
  20176. Element.override({
  20177. /**
  20178. * The element's default display mode.
  20179. */
  20180. originalDisplay : "",
  20181. visibilityMode : 1,
  20182. /**
  20183. * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
  20184. * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
  20185. * @param {Boolean} visible Whether the element is visible
  20186. * @param {Boolean/Object} [animate] True for the default animation, or a standard Element animation config object
  20187. * @return {Ext.dom.Element} this
  20188. */
  20189. setVisible : function(visible, animate){
  20190. var me = this, isDisplay, isVisibility, isOffsets, isNosize,
  20191. dom = me.dom,
  20192. visMode = getVisMode(me);
  20193. // hideMode string override
  20194. if (typeof animate == 'string'){
  20195. switch (animate) {
  20196. case DISPLAY:
  20197. visMode = Ext.dom.Element.DISPLAY;
  20198. break;
  20199. case VISIBILITY:
  20200. visMode = Ext.dom.Element.VISIBILITY;
  20201. break;
  20202. case OFFSETS:
  20203. visMode = Ext.dom.Element.OFFSETS;
  20204. break;
  20205. case NOSIZE:
  20206. case ASCLASS:
  20207. visMode = Ext.dom.Element.ASCLASS;
  20208. break;
  20209. }
  20210. me.setVisibilityMode(visMode);
  20211. animate = false;
  20212. }
  20213. if (!animate || !me.anim) {
  20214. if(visMode == Ext.dom.Element.ASCLASS ){
  20215. me[visible?'removeCls':'addCls'](me.visibilityCls || Ext.dom.Element.visibilityCls);
  20216. } else if (visMode == Ext.dom.Element.DISPLAY){
  20217. return me.setDisplayed(visible);
  20218. } else if (visMode == Ext.dom.Element.OFFSETS){
  20219. if (!visible){
  20220. // Remember position for restoring, if we are not already hidden by offsets.
  20221. if (!me.hideModeStyles) {
  20222. me.hideModeStyles = {
  20223. position: me.getStyle('position'),
  20224. top: me.getStyle('top'),
  20225. left: me.getStyle('left')
  20226. };
  20227. }
  20228. me.applyStyles({position: 'absolute', top: '-10000px', left: '-10000px'});
  20229. }
  20230. // Only "restore" as position if we have actually been hidden using offsets.
  20231. // Calling setVisible(true) on a positioned element should not reposition it.
  20232. else if (me.hideModeStyles) {
  20233. me.applyStyles(me.hideModeStyles || {position: '', top: '', left: ''});
  20234. delete me.hideModeStyles;
  20235. }
  20236. }else{
  20237. me.fixDisplay();
  20238. // Show by clearing visibility style. Explicitly setting to "visible" overrides parent visibility setting.
  20239. dom.style.visibility = visible ? '' : HIDDEN;
  20240. }
  20241. }else{
  20242. // closure for composites
  20243. if(visible){
  20244. me.setOpacity(0.01);
  20245. me.setVisible(true);
  20246. }
  20247. if (!Ext.isObject(animate)) {
  20248. animate = {
  20249. duration: 350,
  20250. easing: 'ease-in'
  20251. };
  20252. }
  20253. me.animate(Ext.applyIf({
  20254. callback: function() {
  20255. if (!visible) {
  20256. me.setVisible(false).setOpacity(1);
  20257. }
  20258. },
  20259. to: {
  20260. opacity: (visible) ? 1 : 0
  20261. }
  20262. }, animate));
  20263. }
  20264. (me.$cache || me.getCache()).data[ISVISIBLE] = visible;
  20265. return me;
  20266. },
  20267. /**
  20268. * @private
  20269. * Determine if the Element has a relevant height and width available based
  20270. * upon current logical visibility state
  20271. */
  20272. hasMetrics : function(){
  20273. var visMode = getVisMode(this);
  20274. return this.isVisible() || (visMode == Ext.dom.Element.OFFSETS) || (visMode == Ext.dom.Element.VISIBILITY);
  20275. },
  20276. /**
  20277. * Toggles the element's visibility or display, depending on visibility mode.
  20278. * @param {Boolean/Object} [animate] True for the default animation, or a standard Element animation config object
  20279. * @return {Ext.dom.Element} this
  20280. */
  20281. toggle : function(animate){
  20282. var me = this;
  20283. me.setVisible(!me.isVisible(), me.anim(animate));
  20284. return me;
  20285. },
  20286. /**
  20287. * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
  20288. * @param {Boolean/String} value Boolean value to display the element using its default display, or a string to set the display directly.
  20289. * @return {Ext.dom.Element} this
  20290. */
  20291. setDisplayed : function(value) {
  20292. if(typeof value == "boolean"){
  20293. value = value ? getDisplay(this) : NONE;
  20294. }
  20295. this.setStyle(DISPLAY, value);
  20296. return this;
  20297. },
  20298. // private
  20299. fixDisplay : function(){
  20300. var me = this;
  20301. if (me.isStyle(DISPLAY, NONE)) {
  20302. me.setStyle(VISIBILITY, HIDDEN);
  20303. me.setStyle(DISPLAY, getDisplay(me)); // first try reverting to default
  20304. if (me.isStyle(DISPLAY, NONE)) { // if that fails, default to block
  20305. me.setStyle(DISPLAY, "block");
  20306. }
  20307. }
  20308. },
  20309. /**
  20310. * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
  20311. * @param {Boolean/Object} [animate] true for the default animation or a standard Element animation config object
  20312. * @return {Ext.dom.Element} this
  20313. */
  20314. hide : function(animate){
  20315. // hideMode override
  20316. if (typeof animate == 'string'){
  20317. this.setVisible(false, animate);
  20318. return this;
  20319. }
  20320. this.setVisible(false, this.anim(animate));
  20321. return this;
  20322. },
  20323. /**
  20324. * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
  20325. * @param {Boolean/Object} [animate] true for the default animation or a standard Element animation config object
  20326. * @return {Ext.dom.Element} this
  20327. */
  20328. show : function(animate){
  20329. // hideMode override
  20330. if (typeof animate == 'string'){
  20331. this.setVisible(true, animate);
  20332. return this;
  20333. }
  20334. this.setVisible(true, this.anim(animate));
  20335. return this;
  20336. }
  20337. });
  20338. })();
  20339. /**
  20340. * @class Ext.dom.Element
  20341. */
  20342. (function() {
  20343. var Element = Ext.dom.Element,
  20344. LEFT = "left",
  20345. RIGHT = "right",
  20346. TOP = "top",
  20347. BOTTOM = "bottom",
  20348. POSITION = "position",
  20349. STATIC = "static",
  20350. RELATIVE = "relative",
  20351. AUTO = "auto",
  20352. ZINDEX = "z-index",
  20353. BODY = 'BODY',
  20354. PADDING = 'padding',
  20355. BORDER = 'border',
  20356. SLEFT = '-left',
  20357. SRIGHT = '-right',
  20358. STOP = '-top',
  20359. SBOTTOM = '-bottom',
  20360. SWIDTH = '-width',
  20361. // special markup used throughout Ext when box wrapping elements
  20362. borders = {l: BORDER + SLEFT + SWIDTH, r: BORDER + SRIGHT + SWIDTH, t: BORDER + STOP + SWIDTH, b: BORDER + SBOTTOM + SWIDTH},
  20363. paddings = {l: PADDING + SLEFT, r: PADDING + SRIGHT, t: PADDING + STOP, b: PADDING + SBOTTOM},
  20364. paddingsTLRB = [paddings.l, paddings.r, paddings.t, paddings.b],
  20365. bordersTLRB = [borders.l, borders.r, borders.t, borders.b],
  20366. positionTopLeft = ['position', 'top', 'left'];
  20367. Element.override({
  20368. getX: function() {
  20369. return Element.getX(this.dom);
  20370. },
  20371. getY: function() {
  20372. return Element.getY(this.dom);
  20373. },
  20374. /**
  20375. * Gets the current position of the element based on page coordinates.
  20376. * Element must be part of the DOM tree to have page coordinates
  20377. * (display:none or elements not appended return false).
  20378. * @return {Number[]} The XY position of the element
  20379. */
  20380. getXY: function() {
  20381. return Element.getXY(this.dom);
  20382. },
  20383. /**
  20384. * Returns the offsets of this element from the passed element. Both element must be part
  20385. * of the DOM tree and not have display:none to have page coordinates.
  20386. * @param {String/HTMLElement/Ext.Element} element The element to get the offsets from.
  20387. * @return {Number[]} The XY page offsets (e.g. `[100, -200]`)
  20388. */
  20389. getOffsetsTo : function(el){
  20390. var o = this.getXY(),
  20391. e = Ext.fly(el, '_internal').getXY();
  20392. return [o[0] - e[0],o[1] - e[1]];
  20393. },
  20394. setX: function(x, animate) {
  20395. return this.setXY([x, this.getY()], animate);
  20396. },
  20397. setY: function(y, animate) {
  20398. return this.setXY([this.getX(), y], animate);
  20399. },
  20400. setLeft: function(left) {
  20401. this.setStyle(LEFT, this.addUnits(left));
  20402. return this;
  20403. },
  20404. setTop: function(top) {
  20405. this.setStyle(TOP, this.addUnits(top));
  20406. return this;
  20407. },
  20408. setRight: function(right) {
  20409. this.setStyle(RIGHT, this.addUnits(right));
  20410. return this;
  20411. },
  20412. setBottom: function(bottom) {
  20413. this.setStyle(BOTTOM, this.addUnits(bottom));
  20414. return this;
  20415. },
  20416. /**
  20417. * Sets the position of the element in page coordinates, regardless of how the element
  20418. * is positioned. The element must be part of the DOM tree to have page coordinates
  20419. * (`display:none` or elements not appended return false).
  20420. * @param {Number[]} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
  20421. * @param {Boolean/Object} [animate] True for the default animation, or a standard Element
  20422. * animation config object
  20423. * @return {Ext.Element} this
  20424. */
  20425. setXY: function(pos, animate) {
  20426. var me = this;
  20427. if (!animate || !me.anim) {
  20428. Element.setXY(me.dom, pos);
  20429. }
  20430. else {
  20431. if (!Ext.isObject(animate)) {
  20432. animate = {};
  20433. }
  20434. me.animate(Ext.applyIf({ to: { x: pos[0], y: pos[1] } }, animate));
  20435. }
  20436. return me;
  20437. },
  20438. getLeft: function(local) {
  20439. return !local ? this.getX() : parseFloat(this.getStyle(LEFT)) || 0;
  20440. },
  20441. getRight: function(local) {
  20442. var me = this;
  20443. return !local ? me.getX() + me.getWidth() : (me.getLeft(true) + me.getWidth()) || 0;
  20444. },
  20445. getTop: function(local) {
  20446. return !local ? this.getY() : parseFloat(this.getStyle(TOP)) || 0;
  20447. },
  20448. getBottom: function(local) {
  20449. var me = this;
  20450. return !local ? me.getY() + me.getHeight() : (me.getTop(true) + me.getHeight()) || 0;
  20451. },
  20452. translatePoints: function(x, y) {
  20453. var me = this,
  20454. styles = me.getStyle(positionTopLeft),
  20455. relative = styles.position == 'relative',
  20456. left = parseFloat(styles.left),
  20457. top = parseFloat(styles.top),
  20458. xy = me.getXY();
  20459. if (Ext.isArray(x)) {
  20460. y = x[1];
  20461. x = x[0];
  20462. }
  20463. if (isNaN(left)) {
  20464. left = relative ? 0 : me.dom.offsetLeft;
  20465. }
  20466. if (isNaN(top)) {
  20467. top = relative ? 0 : me.dom.offsetTop;
  20468. }
  20469. left = (typeof x == 'number') ? x - xy[0] + left : undefined;
  20470. top = (typeof y == 'number') ? y - xy[1] + top : undefined;
  20471. return {
  20472. left: left,
  20473. top: top
  20474. };
  20475. },
  20476. setBox: function(box, adjust, animate) {
  20477. var me = this,
  20478. w = box.width,
  20479. h = box.height;
  20480. if ((adjust && !me.autoBoxAdjust) && !me.isBorderBox()) {
  20481. w -= (me.getBorderWidth("lr") + me.getPadding("lr"));
  20482. h -= (me.getBorderWidth("tb") + me.getPadding("tb"));
  20483. }
  20484. me.setBounds(box.x, box.y, w, h, animate);
  20485. return me;
  20486. },
  20487. getBox: function(contentBox, local) {
  20488. var me = this,
  20489. xy,
  20490. left,
  20491. top,
  20492. paddingWidth,
  20493. bordersWidth,
  20494. l, r, t, b, w, h, bx;
  20495. if (!local) {
  20496. xy = me.getXY();
  20497. } else {
  20498. xy = me.getStyle([LEFT, TOP]);
  20499. xy = [ parseFloat(xy.left) || 0, parseFloat(xy.top) || 0];
  20500. }
  20501. w = me.getWidth();
  20502. h = me.getHeight();
  20503. if (!contentBox) {
  20504. bx = {
  20505. x: xy[0],
  20506. y: xy[1],
  20507. 0: xy[0],
  20508. 1: xy[1],
  20509. width: w,
  20510. height: h
  20511. };
  20512. } else {
  20513. paddingWidth = me.getStyle(paddingsTLRB);
  20514. bordersWidth = me.getStyle(bordersTLRB);
  20515. l = (parseFloat(bordersWidth[borders.l]) || 0) + (parseFloat(paddingWidth[paddings.l]) || 0);
  20516. r = (parseFloat(bordersWidth[borders.r]) || 0) + (parseFloat(paddingWidth[paddings.r]) || 0);
  20517. t = (parseFloat(bordersWidth[borders.t]) || 0) + (parseFloat(paddingWidth[paddings.t]) || 0);
  20518. b = (parseFloat(bordersWidth[borders.b]) || 0) + (parseFloat(paddingWidth[paddings.b]) || 0);
  20519. bx = {
  20520. x: xy[0] + l,
  20521. y: xy[1] + t,
  20522. 0: xy[0] + l,
  20523. 1: xy[1] + t,
  20524. width: w - (l + r),
  20525. height: h - (t + b)
  20526. };
  20527. }
  20528. bx.right = bx.x + bx.width;
  20529. bx.bottom = bx.y + bx.height;
  20530. return bx;
  20531. },
  20532. getPageBox: function(getRegion) {
  20533. var me = this,
  20534. el = me.dom,
  20535. isDoc = el.nodeName == BODY,
  20536. w = isDoc ? Ext.dom.AbstractElement.getViewWidth() : el.offsetWidth,
  20537. h = isDoc ? Ext.dom.AbstractElement.getViewHeight() : el.offsetHeight,
  20538. xy = me.getXY(),
  20539. t = xy[1],
  20540. r = xy[0] + w,
  20541. b = xy[1] + h,
  20542. l = xy[0];
  20543. if (getRegion) {
  20544. return new Ext.util.Region(t, r, b, l);
  20545. }
  20546. else {
  20547. return {
  20548. left: l,
  20549. top: t,
  20550. width: w,
  20551. height: h,
  20552. right: r,
  20553. bottom: b
  20554. };
  20555. }
  20556. },
  20557. /**
  20558. * Sets the position of the element in page coordinates, regardless of how the element
  20559. * is positioned. The element must be part of the DOM tree to have page coordinates
  20560. * (`display:none` or elements not appended return false).
  20561. * @param {Number} x X value for new position (coordinates are page-based)
  20562. * @param {Number} y Y value for new position (coordinates are page-based)
  20563. * @param {Boolean/Object} [animate] True for the default animation, or a standard Element
  20564. * animation config object
  20565. * @return {Ext.dom.AbstractElement} this
  20566. */
  20567. setLocation : function(x, y, animate) {
  20568. return this.setXY([x, y], animate);
  20569. },
  20570. /**
  20571. * Sets the position of the element in page coordinates, regardless of how the element
  20572. * is positioned. The element must be part of the DOM tree to have page coordinates
  20573. * (`display:none` or elements not appended return false).
  20574. * @param {Number} x X value for new position (coordinates are page-based)
  20575. * @param {Number} y Y value for new position (coordinates are page-based)
  20576. * @param {Boolean/Object} [animate] True for the default animation, or a standard Element
  20577. * animation config object
  20578. * @return {Ext.dom.AbstractElement} this
  20579. */
  20580. moveTo : function(x, y, animate) {
  20581. return this.setXY([x, y], animate);
  20582. },
  20583. /**
  20584. * Initializes positioning on this element. If a desired position is not passed, it will make the
  20585. * the element positioned relative IF it is not already positioned.
  20586. * @param {String} [pos] Positioning to use "relative", "absolute" or "fixed"
  20587. * @param {Number} [zIndex] The zIndex to apply
  20588. * @param {Number} [x] Set the page X position
  20589. * @param {Number} [y] Set the page Y position
  20590. */
  20591. position : function(pos, zIndex, x, y) {
  20592. var me = this;
  20593. if (!pos && me.isStyle(POSITION, STATIC)) {
  20594. me.setStyle(POSITION, RELATIVE);
  20595. } else if (pos) {
  20596. me.setStyle(POSITION, pos);
  20597. }
  20598. if (zIndex) {
  20599. me.setStyle(ZINDEX, zIndex);
  20600. }
  20601. if (x || y) {
  20602. me.setXY([x || false, y || false]);
  20603. }
  20604. },
  20605. /**
  20606. * Clears positioning back to the default when the document was loaded.
  20607. * @param {String} [value=''] The value to use for the left, right, top, bottom. You could use 'auto'.
  20608. * @return {Ext.dom.AbstractElement} this
  20609. */
  20610. clearPositioning : function(value) {
  20611. value = value || '';
  20612. this.setStyle({
  20613. left : value,
  20614. right : value,
  20615. top : value,
  20616. bottom : value,
  20617. "z-index" : "",
  20618. position : STATIC
  20619. });
  20620. return this;
  20621. },
  20622. /**
  20623. * Gets an object with all CSS positioning properties. Useful along with #setPostioning to get
  20624. * snapshot before performing an update and then restoring the element.
  20625. * @return {Object}
  20626. */
  20627. getPositioning : function(){
  20628. var styles = this.getStyle([LEFT, TOP, POSITION, RIGHT, BOTTOM, ZINDEX]);
  20629. styles[RIGHT] = styles[LEFT] ? '' : styles[RIGHT];
  20630. styles[BOTTOM] = styles[TOP] ? '' : styles[BOTTOM];
  20631. return styles;
  20632. },
  20633. /**
  20634. * Set positioning with an object returned by #getPositioning.
  20635. * @param {Object} posCfg
  20636. * @return {Ext.dom.AbstractElement} this
  20637. */
  20638. setPositioning : function(pc) {
  20639. var me = this,
  20640. style = me.dom.style;
  20641. me.setStyle(pc);
  20642. if (pc.right == AUTO) {
  20643. style.right = "";
  20644. }
  20645. if (pc.bottom == AUTO) {
  20646. style.bottom = "";
  20647. }
  20648. return me;
  20649. },
  20650. /**
  20651. * Move this element relative to its current position.
  20652. * @param {String} direction Possible values are:
  20653. *
  20654. * - `"l"` (or `"left"`)
  20655. * - `"r"` (or `"right"`)
  20656. * - `"t"` (or `"top"`, or `"up"`)
  20657. * - `"b"` (or `"bottom"`, or `"down"`)
  20658. *
  20659. * @param {Number} distance How far to move the element in pixels
  20660. * @param {Boolean/Object} [animate] true for the default animation or a standard Element
  20661. * animation config object
  20662. */
  20663. move: function(direction, distance, animate) {
  20664. var me = this,
  20665. xy = me.getXY(),
  20666. x = xy[0],
  20667. y = xy[1],
  20668. left = [x - distance, y],
  20669. right = [x + distance, y],
  20670. top = [x, y - distance],
  20671. bottom = [x, y + distance],
  20672. hash = {
  20673. l: left,
  20674. left: left,
  20675. r: right,
  20676. right: right,
  20677. t: top,
  20678. top: top,
  20679. up: top,
  20680. b: bottom,
  20681. bottom: bottom,
  20682. down: bottom
  20683. };
  20684. direction = direction.toLowerCase();
  20685. me.moveTo(hash[direction][0], hash[direction][1], animate);
  20686. },
  20687. /**
  20688. * Conveniently sets left and top adding default units.
  20689. * @param {String} left The left CSS property value
  20690. * @param {String} top The top CSS property value
  20691. * @return {Ext.dom.Element} this
  20692. */
  20693. setLeftTop: function(left, top) {
  20694. var style = this.dom.style;
  20695. style.left = Element.addUnits(left);
  20696. style.top = Element.addUnits(top);
  20697. return this;
  20698. },
  20699. /**
  20700. * Returns the region of this element.
  20701. * The element must be part of the DOM tree to have a region
  20702. * (display:none or elements not appended return false).
  20703. * @return {Ext.util.Region} A Region containing "top, left, bottom, right" member data.
  20704. */
  20705. getRegion: function() {
  20706. return this.getPageBox(true);
  20707. },
  20708. /**
  20709. * Returns the **content** region of this element. That is the region within the borders and padding.
  20710. * @return {Ext.util.Region} A Region containing "top, left, bottom, right" member data.
  20711. */
  20712. getViewRegion: function() {
  20713. var me = this,
  20714. isBody = me.dom.nodeName == BODY,
  20715. scroll, pos, top, left, width, height;
  20716. // For the body we want to do some special logic
  20717. if (isBody) {
  20718. scroll = me.getScroll();
  20719. left = scroll.left;
  20720. top = scroll.top;
  20721. width = Ext.dom.AbstractElement.getViewportWidth();
  20722. height = Ext.dom.AbstractElement.getViewportHeight();
  20723. }
  20724. else {
  20725. pos = me.getXY();
  20726. left = pos[0] + me.getBorderWidth('l') + me.getPadding('l');
  20727. top = pos[1] + me.getBorderWidth('t') + me.getPadding('t');
  20728. width = me.getWidth(true);
  20729. height = me.getHeight(true);
  20730. }
  20731. return new Ext.util.Region(top, left + width, top + height, left);
  20732. },
  20733. /**
  20734. * Sets the element's position and size in one shot. If animation is true then width, height,
  20735. * x and y will be animated concurrently.
  20736. *
  20737. * @param {Number} x X value for new position (coordinates are page-based)
  20738. * @param {Number} y Y value for new position (coordinates are page-based)
  20739. * @param {Number/String} width The new width. This may be one of:
  20740. *
  20741. * - A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels)
  20742. * - A String used to set the CSS width style. Animation may **not** be used.
  20743. *
  20744. * @param {Number/String} height The new height. This may be one of:
  20745. *
  20746. * - A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels)
  20747. * - A String used to set the CSS height style. Animation may **not** be used.
  20748. *
  20749. * @param {Boolean/Object} [animate] true for the default animation or a standard Element
  20750. * animation config object
  20751. *
  20752. * @return {Ext.dom.AbstractElement} this
  20753. */
  20754. setBounds: function(x, y, width, height, animate) {
  20755. var me = this;
  20756. if (!animate || !me.anim) {
  20757. me.setSize(width, height);
  20758. me.setLocation(x, y);
  20759. } else {
  20760. if (!Ext.isObject(animate)) {
  20761. animate = {};
  20762. }
  20763. me.animate(Ext.applyIf({
  20764. to: {
  20765. x: x,
  20766. y: y,
  20767. width: me.adjustWidth(width),
  20768. height: me.adjustHeight(height)
  20769. }
  20770. }, animate));
  20771. }
  20772. return me;
  20773. },
  20774. /**
  20775. * Sets the element's position and size the specified region. If animation is true then width, height,
  20776. * x and y will be animated concurrently.
  20777. *
  20778. * @param {Ext.util.Region} region The region to fill
  20779. * @param {Boolean/Object} [animate] true for the default animation or a standard Element
  20780. * animation config object
  20781. * @return {Ext.dom.AbstractElement} this
  20782. */
  20783. setRegion: function(region, animate) {
  20784. return this.setBounds(region.left, region.top, region.right - region.left, region.bottom - region.top, animate);
  20785. }
  20786. });
  20787. })();
  20788. /**
  20789. * @class Ext.dom.Element
  20790. */
  20791. Ext.dom.Element.override({
  20792. /**
  20793. * Returns true if this element is scrollable.
  20794. * @return {Boolean}
  20795. */
  20796. isScrollable: function() {
  20797. var dom = this.dom;
  20798. return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
  20799. },
  20800. /**
  20801. * Returns the current scroll position of the element.
  20802. * @return {Object} An object containing the scroll position in the format
  20803. * `{left: (scrollLeft), top: (scrollTop)}`
  20804. */
  20805. getScroll: function() {
  20806. var d = this.dom,
  20807. doc = document,
  20808. body = doc.body,
  20809. docElement = doc.documentElement,
  20810. l,
  20811. t,
  20812. ret;
  20813. if (d == doc || d == body) {
  20814. if (Ext.isIE && Ext.isStrict) {
  20815. l = docElement.scrollLeft;
  20816. t = docElement.scrollTop;
  20817. } else {
  20818. l = window.pageXOffset;
  20819. t = window.pageYOffset;
  20820. }
  20821. ret = {
  20822. left: l || (body ? body.scrollLeft : 0),
  20823. top : t || (body ? body.scrollTop : 0)
  20824. };
  20825. } else {
  20826. ret = {
  20827. left: d.scrollLeft,
  20828. top : d.scrollTop
  20829. };
  20830. }
  20831. return ret;
  20832. },
  20833. /**
  20834. * Scrolls this element by the passed delta values, optionally animating.
  20835. *
  20836. * All of the following are equivalent:
  20837. *
  20838. * el.scrollBy(10, 10, true);
  20839. * el.scrollBy([10, 10], true);
  20840. * el.scrollBy({ x: 10, y: 10 }, true);
  20841. *
  20842. * @param {Number/Number[]/Object} deltaX Either the x delta, an Array specifying x and y deltas or
  20843. * an object with "x" and "y" properties.
  20844. * @param {Number/Boolean/Object} deltaY Either the y delta, or an animate flag or config object.
  20845. * @param {Boolean/Object} animate Animate flag/config object if the delta values were passed separately.
  20846. * @return {Ext.Element} this
  20847. */
  20848. scrollBy: function(deltaX, deltaY, animate) {
  20849. var me = this,
  20850. dom = me.dom;
  20851. // Extract args if deltas were passed as an Array.
  20852. if (deltaX.length) {
  20853. animate = deltaY;
  20854. deltaY = deltaX[1];
  20855. deltaX = deltaX[0];
  20856. } else if (typeof deltaX != 'number') { // or an object
  20857. animate = deltaY;
  20858. deltaY = deltaX.y;
  20859. deltaX = deltaX.x;
  20860. }
  20861. if (deltaX) {
  20862. me.scrollTo('left', Math.max(Math.min(dom.scrollLeft + deltaX, dom.scrollWidth - dom.clientWidth), 0), animate);
  20863. }
  20864. if (deltaY) {
  20865. me.scrollTo('top', Math.max(Math.min(dom.scrollTop + deltaY, dom.scrollHeight - dom.clientHeight), 0), animate);
  20866. }
  20867. return me;
  20868. },
  20869. /**
  20870. * Scrolls this element the specified scroll point. It does NOT do bounds checking so
  20871. * if you scroll to a weird value it will try to do it. For auto bounds checking, use #scroll.
  20872. * @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values.
  20873. * @param {Number} value The new scroll value
  20874. * @param {Boolean/Object} [animate] true for the default animation or a standard Element
  20875. * animation config object
  20876. * @return {Ext.Element} this
  20877. */
  20878. scrollTo: function(side, value, animate) {
  20879. //check if we're scrolling top or left
  20880. var top = /top/i.test(side),
  20881. me = this,
  20882. dom = me.dom,
  20883. obj = {},
  20884. prop;
  20885. if (!animate || !me.anim) {
  20886. // just setting the value, so grab the direction
  20887. prop = 'scroll' + (top ? 'Top' : 'Left');
  20888. dom[prop] = value;
  20889. }
  20890. else {
  20891. if (!Ext.isObject(animate)) {
  20892. animate = {};
  20893. }
  20894. obj['scroll' + (top ? 'Top' : 'Left')] = value;
  20895. me.animate(Ext.applyIf({
  20896. to: obj
  20897. }, animate));
  20898. }
  20899. return me;
  20900. },
  20901. /**
  20902. * Scrolls this element into view within the passed container.
  20903. * @param {String/HTMLElement/Ext.Element} [container=document.body] The container element
  20904. * to scroll. Should be a string (id), dom node, or Ext.Element.
  20905. * @param {Boolean} [hscroll=true] False to disable horizontal scroll.
  20906. * @return {Ext.dom.Element} this
  20907. */
  20908. scrollIntoView: function(container, hscroll) {
  20909. container = Ext.getDom(container) || Ext.getBody().dom;
  20910. var el = this.dom,
  20911. offsets = this.getOffsetsTo(container),
  20912. // el's box
  20913. left = offsets[0] + container.scrollLeft,
  20914. top = offsets[1] + container.scrollTop,
  20915. bottom = top + el.offsetHeight,
  20916. right = left + el.offsetWidth,
  20917. // ct's box
  20918. ctClientHeight = container.clientHeight,
  20919. ctScrollTop = parseInt(container.scrollTop, 10),
  20920. ctScrollLeft = parseInt(container.scrollLeft, 10),
  20921. ctBottom = ctScrollTop + ctClientHeight,
  20922. ctRight = ctScrollLeft + container.clientWidth;
  20923. if (el.offsetHeight > ctClientHeight || top < ctScrollTop) {
  20924. container.scrollTop = top;
  20925. } else if (bottom > ctBottom) {
  20926. container.scrollTop = bottom - ctClientHeight;
  20927. }
  20928. // corrects IE, other browsers will ignore
  20929. container.scrollTop = container.scrollTop;
  20930. if (hscroll !== false) {
  20931. if (el.offsetWidth > container.clientWidth || left < ctScrollLeft) {
  20932. container.scrollLeft = left;
  20933. }
  20934. else if (right > ctRight) {
  20935. container.scrollLeft = right - container.clientWidth;
  20936. }
  20937. container.scrollLeft = container.scrollLeft;
  20938. }
  20939. return this;
  20940. },
  20941. // @private
  20942. scrollChildIntoView: function(child, hscroll) {
  20943. Ext.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll);
  20944. },
  20945. /**
  20946. * Scrolls this element the specified direction. Does bounds checking to make sure the scroll is
  20947. * within this element's scrollable range.
  20948. * @param {String} direction Possible values are:
  20949. *
  20950. * - `"l"` (or `"left"`)
  20951. * - `"r"` (or `"right"`)
  20952. * - `"t"` (or `"top"`, or `"up"`)
  20953. * - `"b"` (or `"bottom"`, or `"down"`)
  20954. *
  20955. * @param {Number} distance How far to scroll the element in pixels
  20956. * @param {Boolean/Object} [animate] true for the default animation or a standard Element
  20957. * animation config object
  20958. * @return {Boolean} Returns true if a scroll was triggered or false if the element
  20959. * was scrolled as far as it could go.
  20960. */
  20961. scroll: function(direction, distance, animate) {
  20962. if (!this.isScrollable()) {
  20963. return false;
  20964. }
  20965. var el = this.dom,
  20966. l = el.scrollLeft, t = el.scrollTop,
  20967. w = el.scrollWidth, h = el.scrollHeight,
  20968. cw = el.clientWidth, ch = el.clientHeight,
  20969. scrolled = false, v,
  20970. hash = {
  20971. l: Math.min(l + distance, w - cw),
  20972. r: v = Math.max(l - distance, 0),
  20973. t: Math.max(t - distance, 0),
  20974. b: Math.min(t + distance, h - ch)
  20975. };
  20976. hash.d = hash.b;
  20977. hash.u = hash.t;
  20978. direction = direction.substr(0, 1);
  20979. if ((v = hash[direction]) > -1) {
  20980. scrolled = true;
  20981. this.scrollTo(direction == 'l' || direction == 'r' ? 'left' : 'top', v, this.anim(animate));
  20982. }
  20983. return scrolled;
  20984. }
  20985. });
  20986. /**
  20987. * @class Ext.dom.Element
  20988. */
  20989. (function() {
  20990. var Element = Ext.dom.Element,
  20991. view = document.defaultView;
  20992. var adjustDirect2DTableRe = /table-row|table-.*-group/,
  20993. INTERNAL = '_internal',
  20994. HIDDEN = 'hidden',
  20995. HEIGHT = 'height',
  20996. WIDTH = 'width',
  20997. ISCLIPPED = 'isClipped',
  20998. OVERFLOW = 'overflow',
  20999. OVERFLOWX = 'overflow-x',
  21000. OVERFLOWY = 'overflow-y',
  21001. ORIGINALCLIP = 'originalClip',
  21002. DOCORBODYRE = /#document|body/i;
  21003. if (!view || !view.getComputedStyle) {
  21004. Element.prototype.getStyle = function (property, inline) {
  21005. var me = this,
  21006. dom = me.dom,
  21007. multiple = typeof property != 'string',
  21008. hooks = me.styleHooks,
  21009. prop = property,
  21010. props = prop,
  21011. len = 1,
  21012. isInline = inline,
  21013. camel, domStyle, values, hook, out, style, i;
  21014. if (multiple) {
  21015. values = {};
  21016. prop = props[0];
  21017. i = 0;
  21018. if (!(len = props.length)) {
  21019. return values;
  21020. }
  21021. }
  21022. if (!dom || dom.documentElement) {
  21023. return values || '';
  21024. }
  21025. domStyle = dom.style;
  21026. if (inline) {
  21027. style = domStyle;
  21028. } else {
  21029. style = dom.currentStyle;
  21030. // fallback to inline style if rendering context not available
  21031. if (!style) {
  21032. isInline = true;
  21033. style = domStyle;
  21034. }
  21035. }
  21036. do {
  21037. hook = hooks[prop];
  21038. if (!hook) {
  21039. hooks[prop] = hook = { name: Element.normalize(prop) };
  21040. }
  21041. if (hook.get) {
  21042. out = hook.get(dom, me, isInline, style);
  21043. } else {
  21044. camel = hook.name;
  21045. // In some cases, IE6 will throw Invalid Argument exceptions for properties
  21046. // like fontSize (/examples/tabs/tabs.html in 4.0 used to exhibit this but
  21047. // no longer does due to font style changes). There is a real cost to a try
  21048. // block, so we avoid it where possible...
  21049. if (hook.canThrow) {
  21050. try {
  21051. out = style[camel];
  21052. } catch (e) {
  21053. out = '';
  21054. }
  21055. } else {
  21056. out = style[camel];
  21057. }
  21058. }
  21059. if (!multiple) {
  21060. return out;
  21061. }
  21062. values[prop] = out;
  21063. prop = props[++i];
  21064. } while (i < len);
  21065. return values;
  21066. };
  21067. }
  21068. Element.override({
  21069. getHeight: function(contentHeight, preciseHeight) {
  21070. var me = this,
  21071. dom = me.dom,
  21072. hidden = me.isStyle('display', 'none'),
  21073. height,
  21074. floating;
  21075. if (hidden) {
  21076. return 0;
  21077. }
  21078. height = Math.max(dom.offsetHeight, dom.clientHeight) || 0;
  21079. // IE9 Direct2D dimension rounding bug
  21080. if (Ext.supports.Direct2DBug) {
  21081. floating = me.adjustDirect2DDimension(HEIGHT);
  21082. if (preciseHeight) {
  21083. height += floating;
  21084. }
  21085. else if (floating > 0 && floating < 0.5) {
  21086. height++;
  21087. }
  21088. }
  21089. if (contentHeight) {
  21090. height -= me.getBorderWidth("tb") + me.getPadding("tb");
  21091. }
  21092. return (height < 0) ? 0 : height;
  21093. },
  21094. getWidth: function(contentWidth, preciseWidth) {
  21095. var me = this,
  21096. dom = me.dom,
  21097. hidden = me.isStyle('display', 'none'),
  21098. rect, width, floating;
  21099. if (hidden) {
  21100. return 0;
  21101. }
  21102. // Gecko will in some cases report an offsetWidth that is actually less than the width of the
  21103. // text contents, because it measures fonts with sub-pixel precision but rounds the calculated
  21104. // value down. Using getBoundingClientRect instead of offsetWidth allows us to get the precise
  21105. // subpixel measurements so we can force them to always be rounded up. See
  21106. // https://bugzilla.mozilla.org/show_bug.cgi?id=458617
  21107. // Rounding up ensures that the width includes the full width of the text contents.
  21108. if (Ext.supports.BoundingClientRect) {
  21109. rect = dom.getBoundingClientRect();
  21110. width = rect.right - rect.left;
  21111. width = preciseWidth ? width : Math.ceil(width);
  21112. } else {
  21113. width = dom.offsetWidth;
  21114. }
  21115. width = Math.max(width, dom.clientWidth) || 0;
  21116. // IE9 Direct2D dimension rounding bug
  21117. if (Ext.supports.Direct2DBug) {
  21118. // get the fractional portion of the sub-pixel precision width of the element's text contents
  21119. floating = me.adjustDirect2DDimension(WIDTH);
  21120. if (preciseWidth) {
  21121. width += floating;
  21122. }
  21123. // IE9 also measures fonts with sub-pixel precision, but unlike Gecko, instead of rounding the offsetWidth down,
  21124. // it rounds to the nearest integer. This means that in order to ensure that the width includes the full
  21125. // width of the text contents we need to increment the width by 1 only if the fractional portion is less than 0.5
  21126. else if (floating > 0 && floating < 0.5) {
  21127. width++;
  21128. }
  21129. }
  21130. if (contentWidth) {
  21131. width -= me.getBorderWidth("lr") + me.getPadding("lr");
  21132. }
  21133. return (width < 0) ? 0 : width;
  21134. },
  21135. setWidth: function(width, animate) {
  21136. var me = this;
  21137. width = me.adjustWidth(width);
  21138. if (!animate || !me.anim) {
  21139. me.dom.style.width = me.addUnits(width);
  21140. }
  21141. else {
  21142. if (!Ext.isObject(animate)) {
  21143. animate = {};
  21144. }
  21145. me.animate(Ext.applyIf({
  21146. to: {
  21147. width: width
  21148. }
  21149. }, animate));
  21150. }
  21151. return me;
  21152. },
  21153. setHeight : function(height, animate) {
  21154. var me = this;
  21155. height = me.adjustHeight(height);
  21156. if (!animate || !me.anim) {
  21157. me.dom.style.height = me.addUnits(height);
  21158. }
  21159. else {
  21160. if (!Ext.isObject(animate)) {
  21161. animate = {};
  21162. }
  21163. me.animate(Ext.applyIf({
  21164. to: {
  21165. height: height
  21166. }
  21167. }, animate));
  21168. }
  21169. return me;
  21170. },
  21171. applyStyles: function(style) {
  21172. Ext.DomHelper.applyStyles(this.dom, style);
  21173. return this;
  21174. },
  21175. setSize: function(width, height, animate) {
  21176. var me = this;
  21177. if (Ext.isObject(width)) { // in case of object from getSize()
  21178. animate = height;
  21179. height = width.height;
  21180. width = width.width;
  21181. }
  21182. width = me.adjustWidth(width);
  21183. height = me.adjustHeight(height);
  21184. if (!animate || !me.anim) {
  21185. me.dom.style.width = me.addUnits(width);
  21186. me.dom.style.height = me.addUnits(height);
  21187. }
  21188. else {
  21189. if (animate === true) {
  21190. animate = {};
  21191. }
  21192. me.animate(Ext.applyIf({
  21193. to: {
  21194. width: width,
  21195. height: height
  21196. }
  21197. }, animate));
  21198. }
  21199. return me;
  21200. },
  21201. getViewSize : function() {
  21202. var me = this,
  21203. dom = me.dom,
  21204. isDoc = DOCORBODYRE.test(dom.nodeName),
  21205. ret;
  21206. // If the body, use static methods
  21207. if (isDoc) {
  21208. ret = {
  21209. width : Element.getViewWidth(),
  21210. height : Element.getViewHeight()
  21211. };
  21212. } else {
  21213. ret = {
  21214. width : dom.clientWidth,
  21215. height : dom.clientHeight
  21216. };
  21217. }
  21218. return ret;
  21219. },
  21220. getSize: function(contentSize) {
  21221. return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)};
  21222. },
  21223. // TODO: Look at this
  21224. // private ==> used by Fx
  21225. adjustWidth : function(width) {
  21226. var me = this,
  21227. isNum = (typeof width == 'number');
  21228. if (isNum && me.autoBoxAdjust && !me.isBorderBox()) {
  21229. width -= (me.getBorderWidth("lr") + me.getPadding("lr"));
  21230. }
  21231. return (isNum && width < 0) ? 0 : width;
  21232. },
  21233. // private ==> used by Fx
  21234. adjustHeight : function(height) {
  21235. var me = this,
  21236. isNum = (typeof height == "number");
  21237. if (isNum && me.autoBoxAdjust && !me.isBorderBox()) {
  21238. height -= (me.getBorderWidth("tb") + me.getPadding("tb"));
  21239. }
  21240. return (isNum && height < 0) ? 0 : height;
  21241. },
  21242. /**
  21243. * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like `#fff`) and valid values
  21244. * are convert to standard 6 digit hex color.
  21245. * @param {String} attr The css attribute
  21246. * @param {String} defaultValue The default value to use when a valid color isn't found
  21247. * @param {String} [prefix] defaults to #. Use an empty string when working with
  21248. * color anims.
  21249. */
  21250. getColor : function(attr, defaultValue, prefix) {
  21251. var v = this.getStyle(attr),
  21252. color = prefix || prefix === '' ? prefix : '#',
  21253. h, len, i=0;
  21254. if (!v || (/transparent|inherit/.test(v))) {
  21255. return defaultValue;
  21256. }
  21257. if (/^r/.test(v)) {
  21258. v = v.slice(4, v.length - 1).split(',');
  21259. len = v.length;
  21260. for (; i<len; i++) {
  21261. h = parseInt(v[i], 10);
  21262. color += (h < 16 ? '0' : '') + h.toString(16);
  21263. }
  21264. } else {
  21265. v = v.replace('#', '');
  21266. color += v.length == 3 ? v.replace(/^(\w)(\w)(\w)$/, '$1$1$2$2$3$3') : v;
  21267. }
  21268. return(color.length > 5 ? color.toLowerCase() : defaultValue);
  21269. },
  21270. /**
  21271. * Set the opacity of the element
  21272. * @param {Number} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
  21273. * @param {Boolean/Object} [animate] a standard Element animation config object or `true` for
  21274. * the default animation (`{duration: .35, easing: 'easeIn'}`)
  21275. * @return {Ext.dom.Element} this
  21276. */
  21277. setOpacity: function(opacity, animate) {
  21278. var me = this;
  21279. if (!me.dom) {
  21280. return me;
  21281. }
  21282. if (!animate || !me.anim) {
  21283. me.setStyle('opacity', opacity);
  21284. }
  21285. else {
  21286. if (!typeof (animate) == 'object') {
  21287. animate = {
  21288. duration: 350,
  21289. easing: 'ease-in'
  21290. };
  21291. }
  21292. me.animate(Ext.applyIf({
  21293. to: {
  21294. opacity: opacity
  21295. }
  21296. }, animate));
  21297. }
  21298. return me;
  21299. },
  21300. /**
  21301. * Clears any opacity settings from this element. Required in some cases for IE.
  21302. * @return {Ext.dom.Element} this
  21303. */
  21304. clearOpacity : function() {
  21305. return this.setOpacity('');
  21306. },
  21307. /**
  21308. * @private
  21309. * Returns 1 if the browser returns the subpixel dimension rounded to the lowest pixel.
  21310. * @return {Number} 0 or 1
  21311. */
  21312. adjustDirect2DDimension: function(dimension) {
  21313. var me = this,
  21314. dom = me.dom,
  21315. display = me.getStyle('display'),
  21316. inlineDisplay = dom.style.display,
  21317. inlinePosition = dom.style.position,
  21318. originIndex = dimension === WIDTH ? 0 : 1,
  21319. floating;
  21320. if (display === 'inline') {
  21321. dom.style.display = 'inline-block';
  21322. }
  21323. dom.style.position = display.match(adjustDirect2DTableRe) ? 'absolute' : 'static';
  21324. // floating will contain digits that appears after the decimal point
  21325. // if height or width are set to auto we fallback to msTransformOrigin calculation
  21326. floating = (parseFloat(me.getStyle(dimension)) || parseFloat(dom.currentStyle.msTransformOrigin.split(' ')[originIndex]) * 2) % 1;
  21327. dom.style.position = inlinePosition;
  21328. if (display === 'inline') {
  21329. dom.style.display = inlineDisplay;
  21330. }
  21331. return floating;
  21332. },
  21333. /**
  21334. * Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove
  21335. * @return {Ext.dom.Element} this
  21336. */
  21337. clip : function() {
  21338. var me = this,
  21339. data = (me.$cache || me.getCache()).data,
  21340. style;
  21341. if (!data[ISCLIPPED]) {
  21342. data[ISCLIPPED] = true;
  21343. style = me.getStyle([OVERFLOW, OVERFLOWX, OVERFLOWY]);
  21344. data[ORIGINALCLIP] = {
  21345. o: style[OVERFLOW],
  21346. x: style[OVERFLOWX],
  21347. y: style[OVERFLOWY]
  21348. };
  21349. me.setStyle(OVERFLOW, HIDDEN);
  21350. me.setStyle(OVERFLOWX, HIDDEN);
  21351. me.setStyle(OVERFLOWY, HIDDEN);
  21352. }
  21353. return me;
  21354. },
  21355. /**
  21356. * Return clipping (overflow) to original clipping before {@link #clip} was called
  21357. * @return {Ext.dom.Element} this
  21358. */
  21359. unclip : function() {
  21360. var me = this,
  21361. data = (me.$cache || me.getCache()).data,
  21362. clip;
  21363. if (data[ISCLIPPED]) {
  21364. data[ISCLIPPED] = false;
  21365. clip = data[ORIGINALCLIP];
  21366. if (clip.o) {
  21367. me.setStyle(OVERFLOW, clip.o);
  21368. }
  21369. if (clip.x) {
  21370. me.setStyle(OVERFLOWX, clip.x);
  21371. }
  21372. if (clip.y) {
  21373. me.setStyle(OVERFLOWY, clip.y);
  21374. }
  21375. }
  21376. return me;
  21377. },
  21378. /**
  21379. * Wraps the specified element with a special 9 element markup/CSS block that renders by default as
  21380. * a gray container with a gradient background, rounded corners and a 4-way shadow.
  21381. *
  21382. * This special markup is used throughout Ext when box wrapping elements ({@link Ext.button.Button},
  21383. * {@link Ext.panel.Panel} when {@link Ext.panel.Panel#frame frame=true}, {@link Ext.window.Window}).
  21384. * The markup is of this form:
  21385. *
  21386. * Ext.dom.Element.boxMarkup =
  21387. * '<div class="{0}-tl"><div class="{0}-tr"><div class="{0}-tc"></div></div></div>
  21388. * <div class="{0}-ml"><div class="{0}-mr"><div class="{0}-mc"></div></div></div>
  21389. * <div class="{0}-bl"><div class="{0}-br"><div class="{0}-bc"></div></div></div>';
  21390. *
  21391. * Example usage:
  21392. *
  21393. * // Basic box wrap
  21394. * Ext.get("foo").boxWrap();
  21395. *
  21396. * // You can also add a custom class and use CSS inheritance rules to customize the box look.
  21397. * // 'x-box-blue' is a built-in alternative -- look at the related CSS definitions as an example
  21398. * // for how to create a custom box wrap style.
  21399. * Ext.get("foo").boxWrap().addCls("x-box-blue");
  21400. *
  21401. * @param {String} [class='x-box'] A base CSS class to apply to the containing wrapper element.
  21402. * Note that there are a number of CSS rules that are dependent on this name to make the overall effect work,
  21403. * so if you supply an alternate base class, make sure you also supply all of the necessary rules.
  21404. * @return {Ext.dom.Element} The outermost wrapping element of the created box structure.
  21405. */
  21406. boxWrap : function(cls) {
  21407. cls = cls || Ext.baseCSSPrefix + 'box';
  21408. var el = Ext.get(this.insertHtml("beforeBegin", "<div class='" + cls + "'>" + Ext.String.format(Element.boxMarkup, cls) + "</div>"));
  21409. Ext.DomQuery.selectNode('.' + cls + '-mc', el.dom).appendChild(this.dom);
  21410. return el;
  21411. },
  21412. /**
  21413. * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders
  21414. * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements
  21415. * if a height has not been set using CSS.
  21416. * @return {Number}
  21417. */
  21418. getComputedHeight : function() {
  21419. var me = this,
  21420. h = Math.max(me.dom.offsetHeight, me.dom.clientHeight);
  21421. if (!h) {
  21422. h = parseFloat(me.getStyle(HEIGHT)) || 0;
  21423. if (!me.isBorderBox()) {
  21424. h += me.getFrameWidth('tb');
  21425. }
  21426. }
  21427. return h;
  21428. },
  21429. /**
  21430. * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
  21431. * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
  21432. * if a width has not been set using CSS.
  21433. * @return {Number}
  21434. */
  21435. getComputedWidth : function() {
  21436. var me = this,
  21437. w = Math.max(me.dom.offsetWidth, me.dom.clientWidth);
  21438. if (!w) {
  21439. w = parseFloat(me.getStyle(WIDTH)) || 0;
  21440. if (!me.isBorderBox()) {
  21441. w += me.getFrameWidth('lr');
  21442. }
  21443. }
  21444. return w;
  21445. },
  21446. /**
  21447. * Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth()
  21448. * for more information about the sides.
  21449. * @param {String} sides
  21450. * @return {Number}
  21451. */
  21452. getFrameWidth : function(sides, onlyContentBox) {
  21453. return (onlyContentBox && this.isBorderBox()) ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides));
  21454. },
  21455. /**
  21456. * Sets up event handlers to add and remove a css class when the mouse is over this element
  21457. * @param {String} className
  21458. * @return {Ext.dom.Element} this
  21459. */
  21460. addClsOnOver : function(className) {
  21461. var dom = this.dom;
  21462. this.hover(
  21463. function() {
  21464. Ext.fly(dom, INTERNAL).addCls(className);
  21465. },
  21466. function() {
  21467. Ext.fly(dom, INTERNAL).removeCls(className);
  21468. }
  21469. );
  21470. return this;
  21471. },
  21472. /**
  21473. * Sets up event handlers to add and remove a css class when this element has the focus
  21474. * @param {String} className
  21475. * @return {Ext.dom.Element} this
  21476. */
  21477. addClsOnFocus : function(className) {
  21478. var me = this,
  21479. dom = me.dom;
  21480. me.on("focus", function() {
  21481. Ext.fly(dom, INTERNAL).addCls(className);
  21482. });
  21483. me.on("blur", function() {
  21484. Ext.fly(dom, INTERNAL).removeCls(className);
  21485. });
  21486. return me;
  21487. },
  21488. /**
  21489. * Sets up event handlers to add and remove a css class when the mouse is down and then up on this element (a click effect)
  21490. * @param {String} className
  21491. * @return {Ext.dom.Element} this
  21492. */
  21493. addClsOnClick : function(className) {
  21494. var dom = this.dom;
  21495. this.on("mousedown", function() {
  21496. Ext.fly(dom, INTERNAL).addCls(className);
  21497. var d = Ext.getDoc(),
  21498. fn = function() {
  21499. Ext.fly(dom, INTERNAL).removeCls(className);
  21500. d.removeListener("mouseup", fn);
  21501. };
  21502. d.on("mouseup", fn);
  21503. });
  21504. return this;
  21505. },
  21506. /**
  21507. * Returns the dimensions of the element available to lay content out in.
  21508. *
  21509. * getStyleSize utilizes prefers style sizing if present, otherwise it chooses the larger of offsetHeight/clientHeight and
  21510. * offsetWidth/clientWidth. To obtain the size excluding scrollbars, use getViewSize.
  21511. *
  21512. * Sizing of the document body is handled at the adapter level which handles special cases for IE and strict modes, etc.
  21513. *
  21514. * @return {Object} Object describing width and height.
  21515. * @return {Number} return.width
  21516. * @return {Number} return.height
  21517. */
  21518. getStyleSize : function() {
  21519. var me = this,
  21520. d = this.dom,
  21521. isDoc = DOCORBODYRE.test(d.nodeName),
  21522. s ,
  21523. w, h;
  21524. // If the body, use static methods
  21525. if (isDoc) {
  21526. return {
  21527. width : Element.getViewWidth(),
  21528. height : Element.getViewHeight()
  21529. };
  21530. }
  21531. s = me.getStyle([HEIGHT, WIDTH], true); //seek inline
  21532. // Use Styles if they are set
  21533. if (s.width && s.width != 'auto') {
  21534. w = parseFloat(s.width);
  21535. if (me.isBorderBox()) {
  21536. w -= me.getFrameWidth('lr');
  21537. }
  21538. }
  21539. // Use Styles if they are set
  21540. if (s.height && s.height != 'auto') {
  21541. h = parseFloat(s.height);
  21542. if (me.isBorderBox()) {
  21543. h -= me.getFrameWidth('tb');
  21544. }
  21545. }
  21546. // Use getWidth/getHeight if style not set.
  21547. return {width: w || me.getWidth(true), height: h || me.getHeight(true)};
  21548. },
  21549. /**
  21550. * Enable text selection for this element (normalized across browsers)
  21551. * @return {Ext.Element} this
  21552. */
  21553. selectable : function() {
  21554. var me = this;
  21555. me.dom.unselectable = "off";
  21556. // Prevent it from bubles up and enables it to be selectable
  21557. me.on('selectstart', function (e) {
  21558. e.stopPropagation();
  21559. return true;
  21560. });
  21561. me.applyStyles("-moz-user-select: text; -khtml-user-select: text;");
  21562. me.removeCls(Ext.baseCSSPrefix + 'unselectable');
  21563. return me;
  21564. },
  21565. /**
  21566. * Disables text selection for this element (normalized across browsers)
  21567. * @return {Ext.dom.Element} this
  21568. */
  21569. unselectable : function() {
  21570. var me = this;
  21571. me.dom.unselectable = "on";
  21572. me.swallowEvent("selectstart", true);
  21573. me.applyStyles("-moz-user-select:-moz-none;-khtml-user-select:none;");
  21574. me.addCls(Ext.baseCSSPrefix + 'unselectable');
  21575. return me;
  21576. }
  21577. });
  21578. // This reduces the lookup of 'me.styleHooks' by one hop in the prototype chain. It is
  21579. // the same object.
  21580. var styleHooks;
  21581. Element.prototype.styleHooks = styleHooks = Ext.dom.AbstractElement.prototype.styleHooks;
  21582. if (Ext.isIE6) {
  21583. styleHooks.fontSize = styleHooks['font-size'] = {
  21584. name: 'fontSize',
  21585. canThrow: true
  21586. }
  21587. }
  21588. // override getStyle for border-*-width
  21589. if (Ext.isIEQuirks || Ext.isIE && Ext.ieVersion <= 8) {
  21590. function getBorderWidth (dom, el, inline, style) {
  21591. if (style[this.styleName] == 'none') {
  21592. return '0px';
  21593. }
  21594. return style[this.name];
  21595. }
  21596. var edges = ['Top','Right','Bottom','Left'],
  21597. k = edges.length,
  21598. edge, borderWidth;
  21599. while (k--) {
  21600. edge = edges[k];
  21601. borderWidth = 'border' + edge + 'Width';
  21602. styleHooks['border-'+edge.toLowerCase()+'-width'] = styleHooks[borderWidth] = {
  21603. name: borderWidth,
  21604. styleName: 'border' + edge + 'Style',
  21605. get: getBorderWidth
  21606. };
  21607. }
  21608. }
  21609. })();
  21610. Ext.onReady(function () {
  21611. var opacityRe = /alpha\(opacity=(.*)\)/i,
  21612. trimRe = /^\s+|\s+$/g,
  21613. hooks = Ext.dom.Element.prototype.styleHooks;
  21614. // Ext.supports flags are not populated until onReady...
  21615. hooks.opacity = {
  21616. name: 'opacity',
  21617. afterSet: function(dom, value, el) {
  21618. if (el.isLayer) {
  21619. el.onOpacitySet(value);
  21620. }
  21621. }
  21622. };
  21623. if (!Ext.supports.Opacity && Ext.isIE) {
  21624. Ext.apply(hooks.opacity, {
  21625. get: function (dom) {
  21626. var filter = dom.style.filter,
  21627. match, opacity;
  21628. if (filter.match) {
  21629. match = filter.match(opacityRe);
  21630. if (match) {
  21631. opacity = parseFloat(match[1]);
  21632. if (!isNaN(opacity)) {
  21633. return opacity ? opacity / 100 : 0;
  21634. }
  21635. }
  21636. }
  21637. return 1;
  21638. },
  21639. set: function (dom, value) {
  21640. var style = dom.style,
  21641. val = style.filter.replace(opacityRe, '').replace(trimRe, '');
  21642. style.zoom = 1; // ensure dom.hasLayout
  21643. // value can be a number or '' or null... so treat falsey as no opacity
  21644. if (typeof(value) == 'number' && value >= 0 && value < 1) {
  21645. value *= 100;
  21646. style.filter = val + (val.length ? ' ' : '') + 'alpha(opacity='+value+')';
  21647. } else {
  21648. style.filter = val;
  21649. }
  21650. }
  21651. });
  21652. }
  21653. // else there is no work around for the lack of opacity support. Should not be a
  21654. // problem given that this has been supported for a long time now...
  21655. });
  21656. /**
  21657. * @class Ext.dom.Element
  21658. */
  21659. Ext.dom.Element.override({
  21660. select: function(selector) {
  21661. return Ext.dom.Element.select(selector, false, this.dom);
  21662. }
  21663. });
  21664. /**
  21665. * This class encapsulates a *collection* of DOM elements, providing methods to filter members, or to perform collective
  21666. * actions upon the whole set.
  21667. *
  21668. * Although they are not listed, this class supports all of the methods of {@link Ext.dom.Element} and
  21669. * {@link Ext.fx.Anim}. The methods from these classes will be performed on all the elements in this collection.
  21670. *
  21671. * Example:
  21672. *
  21673. * var els = Ext.select("#some-el div.some-class");
  21674. * // or select directly from an existing element
  21675. * var el = Ext.get('some-el');
  21676. * el.select('div.some-class');
  21677. *
  21678. * els.setWidth(100); // all elements become 100 width
  21679. * els.hide(true); // all elements fade out and hide
  21680. * // or
  21681. * els.setWidth(100).hide(true);
  21682. */
  21683. Ext.define('Ext.dom.CompositeElementLite', {
  21684. alternateClassName: 'Ext.CompositeElementLite',
  21685. requires: ['Ext.dom.Element'],
  21686. statics: {
  21687. /**
  21688. * @private
  21689. * Copies all of the functions from Ext.dom.Element's prototype onto CompositeElementLite's prototype.
  21690. * This is called twice - once immediately below, and once again after additional Ext.dom.Element
  21691. * are added in Ext JS
  21692. */
  21693. importElementMethods: function() {
  21694. var name,
  21695. elementPrototype = Ext.dom.Element.prototype,
  21696. prototype = this.prototype;
  21697. for (name in elementPrototype) {
  21698. if (typeof elementPrototype[name] == 'function'){
  21699. (function(key) {
  21700. prototype[key] = prototype[key] || function() {
  21701. return this.invoke(key, arguments);
  21702. };
  21703. }).call(prototype, name);
  21704. }
  21705. }
  21706. }
  21707. },
  21708. constructor: function(elements, root) {
  21709. /**
  21710. * @property {HTMLElement[]} elements
  21711. * The Array of DOM elements which this CompositeElement encapsulates.
  21712. *
  21713. * This will not *usually* be accessed in developers' code, but developers wishing to augment the capabilities
  21714. * of the CompositeElementLite class may use it when adding methods to the class.
  21715. *
  21716. * For example to add the `nextAll` method to the class to **add** all following siblings of selected elements,
  21717. * the code would be
  21718. *
  21719. * Ext.override(Ext.dom.CompositeElementLite, {
  21720. * nextAll: function() {
  21721. * var elements = this.elements, i, l = elements.length, n, r = [], ri = -1;
  21722. *
  21723. * // Loop through all elements in this Composite, accumulating
  21724. * // an Array of all siblings.
  21725. * for (i = 0; i < l; i++) {
  21726. * for (n = elements[i].nextSibling; n; n = n.nextSibling) {
  21727. * r[++ri] = n;
  21728. * }
  21729. * }
  21730. *
  21731. * // Add all found siblings to this Composite
  21732. * return this.add(r);
  21733. * }
  21734. * });
  21735. *
  21736. * @readonly
  21737. */
  21738. this.elements = [];
  21739. this.add(elements, root);
  21740. this.el = new Ext.dom.AbstractElement.Fly();
  21741. },
  21742. /**
  21743. * @property {Boolean} isComposite
  21744. * `true` in this class to identify an objact as an instantiated CompositeElement, or subclass thereof.
  21745. */
  21746. isComposite: true,
  21747. // private
  21748. getElement: function(el) {
  21749. // Set the shared flyweight dom property to the current element
  21750. return this.el.attach(el);
  21751. },
  21752. // private
  21753. transformElement: function(el) {
  21754. return Ext.getDom(el);
  21755. },
  21756. /**
  21757. * Returns the number of elements in this Composite.
  21758. * @return {Number}
  21759. */
  21760. getCount: function() {
  21761. return this.elements.length;
  21762. },
  21763. /**
  21764. * Adds elements to this Composite object.
  21765. * @param {HTMLElement[]/Ext.dom.CompositeElement} els Either an Array of DOM elements to add, or another Composite
  21766. * object who's elements should be added.
  21767. * @return {Ext.dom.CompositeElement} This Composite object.
  21768. */
  21769. add: function(els, root) {
  21770. var elements = this.elements,
  21771. i, ln;
  21772. if (!els) {
  21773. return this;
  21774. }
  21775. if (typeof els == "string") {
  21776. els = Ext.dom.Element.selectorFunction(els, root);
  21777. }
  21778. else if (els.isComposite) {
  21779. els = els.elements;
  21780. }
  21781. else if (!Ext.isIterable(els)) {
  21782. els = [els];
  21783. }
  21784. for (i = 0, ln = els.length; i < ln; ++i) {
  21785. elements.push(this.transformElement(els[i]));
  21786. }
  21787. return this;
  21788. },
  21789. invoke: function(fn, args) {
  21790. var elements = this.elements,
  21791. ln = elements.length,
  21792. element,
  21793. i;
  21794. fn = Ext.dom.Element.prototype[fn];
  21795. for (i = 0; i < ln; i++) {
  21796. element = elements[i];
  21797. if (element) {
  21798. fn.apply(this.getElement(element), args);
  21799. }
  21800. }
  21801. return this;
  21802. },
  21803. /**
  21804. * Returns a flyweight Element of the dom element object at the specified index
  21805. * @param {Number} index
  21806. * @return {Ext.dom.Element}
  21807. */
  21808. item: function(index) {
  21809. var el = this.elements[index],
  21810. out = null;
  21811. if (el) {
  21812. out = this.getElement(el);
  21813. }
  21814. return out;
  21815. },
  21816. // fixes scope with flyweight
  21817. addListener: function(eventName, handler, scope, opt) {
  21818. var els = this.elements,
  21819. len = els.length,
  21820. i, e;
  21821. for (i = 0; i < len; i++) {
  21822. e = els[i];
  21823. if (e) {
  21824. Ext.EventManager.on(e, eventName, handler, scope || e, opt);
  21825. }
  21826. }
  21827. return this;
  21828. },
  21829. /**
  21830. * Calls the passed function for each element in this composite.
  21831. * @param {Function} fn The function to call.
  21832. * @param {Ext.dom.Element} fn.el The current Element in the iteration. **This is the flyweight
  21833. * (shared) Ext.dom.Element instance, so if you require a a reference to the dom node, use el.dom.**
  21834. * @param {Ext.dom.CompositeElement} fn.c This Composite object.
  21835. * @param {Number} fn.index The zero-based index in the iteration.
  21836. * @param {Object} [scope] The scope (this reference) in which the function is executed.
  21837. * Defaults to the Element.
  21838. * @return {Ext.dom.CompositeElement} this
  21839. */
  21840. each: function(fn, scope) {
  21841. var me = this,
  21842. els = me.elements,
  21843. len = els.length,
  21844. i, e;
  21845. for (i = 0; i < len; i++) {
  21846. e = els[i];
  21847. if (e) {
  21848. e = this.getElement(e);
  21849. if (fn.call(scope || e, e, me, i) === false) {
  21850. break;
  21851. }
  21852. }
  21853. }
  21854. return me;
  21855. },
  21856. /**
  21857. * Clears this Composite and adds the elements passed.
  21858. * @param {HTMLElement[]/Ext.dom.CompositeElement} els Either an array of DOM elements, or another Composite from which
  21859. * to fill this Composite.
  21860. * @return {Ext.dom.CompositeElement} this
  21861. */
  21862. fill: function(els) {
  21863. var me = this;
  21864. me.elements = [];
  21865. me.add(els);
  21866. return me;
  21867. },
  21868. /**
  21869. * Filters this composite to only elements that match the passed selector.
  21870. * @param {String/Function} selector A string CSS selector or a comparison function. The comparison function will be
  21871. * called with the following arguments:
  21872. * @param {Ext.dom.Element} selector.el The current DOM element.
  21873. * @param {Number} selector.index The current index within the collection.
  21874. * @return {Ext.dom.CompositeElement} this
  21875. */
  21876. filter: function(selector) {
  21877. var me = this,
  21878. els = [],
  21879. len = els.length,
  21880. i, e;
  21881. for (i = 0; i < len; i++) {
  21882. e = els[i];
  21883. if (e) {
  21884. e = me.getElement(e);
  21885. if (typeof selector == 'function') {
  21886. if (selector.call(e, e, me, i) === false) {
  21887. break;
  21888. }
  21889. } else if (el.is(selector) === false) {
  21890. break;
  21891. }
  21892. }
  21893. }
  21894. me.elements = els;
  21895. return me;
  21896. },
  21897. /**
  21898. * Find the index of the passed element within the composite collection.
  21899. * @param {String/HTMLElement/Ext.Element/Number} el The id of an element, or an Ext.dom.Element, or an HtmlElement
  21900. * to find within the composite collection.
  21901. * @return {Number} The index of the passed Ext.dom.Element in the composite collection, or -1 if not found.
  21902. */
  21903. indexOf: function(el) {
  21904. return Ext.Array.indexOf(this.elements, this.transformElement(el));
  21905. },
  21906. /**
  21907. * Replaces the specified element with the passed element.
  21908. * @param {String/HTMLElement/Ext.Element/Number} el The id of an element, the Element itself, the index of the
  21909. * element in this composite to replace.
  21910. * @param {String/Ext.Element} replacement The id of an element or the Element itself.
  21911. * @param {Boolean} [domReplace] True to remove and replace the element in the document too.
  21912. * @return {Ext.dom.CompositeElement} this
  21913. */
  21914. replaceElement: function(el, replacement, domReplace) {
  21915. var index = !isNaN(el) ? el : this.indexOf(el),
  21916. d;
  21917. if (index > -1) {
  21918. replacement = Ext.getDom(replacement);
  21919. if (domReplace) {
  21920. d = this.elements[index];
  21921. d.parentNode.insertBefore(replacement, d);
  21922. Ext.removeNode(d);
  21923. }
  21924. Ext.Array.splice(this.elements, index, 1, replacement);
  21925. }
  21926. return this;
  21927. },
  21928. /**
  21929. * Removes all elements.
  21930. */
  21931. clear: function() {
  21932. this.elements = [];
  21933. },
  21934. addElements: function(els, root) {
  21935. if (!els) {
  21936. return this;
  21937. }
  21938. if (typeof els == "string") {
  21939. els = Ext.dom.Element.selectorFunction(els, root);
  21940. }
  21941. var yels = this.elements,
  21942. eLen = els.length,
  21943. e;
  21944. for (e = 0; e < eLen; e++) {
  21945. yels.push(Ext.get(els[e]));
  21946. }
  21947. return this;
  21948. },
  21949. /**
  21950. * Returns the first Element
  21951. * @return {Ext.dom.Element}
  21952. */
  21953. first: function() {
  21954. return this.item(0);
  21955. },
  21956. /**
  21957. * Returns the last Element
  21958. * @return {Ext.dom.Element}
  21959. */
  21960. last: function() {
  21961. return this.item(this.getCount() - 1);
  21962. },
  21963. /**
  21964. * Returns true if this composite contains the passed element
  21965. * @param {String/HTMLElement/Ext.Element/Number} el The id of an element, or an Ext.Element, or an HtmlElement to
  21966. * find within the composite collection.
  21967. * @return {Boolean}
  21968. */
  21969. contains: function(el) {
  21970. return this.indexOf(el) != -1;
  21971. },
  21972. /**
  21973. * Removes the specified element(s).
  21974. * @param {String/HTMLElement/Ext.Element/Number} el The id of an element, the Element itself, the index of the
  21975. * element in this composite or an array of any of those.
  21976. * @param {Boolean} [removeDom] True to also remove the element from the document
  21977. * @return {Ext.dom.CompositeElement} this
  21978. */
  21979. removeElement: function(keys, removeDom) {
  21980. keys = [].concat(keys);
  21981. var me = this,
  21982. elements = this.elements,
  21983. kLen = keys.length,
  21984. val, el, k;
  21985. for (k = 0; k < kLen; k++) {
  21986. val = keys[k];
  21987. if ((el = (elements[val] || elements[val = me.indexOf(val)]))) {
  21988. if (removeDom) {
  21989. if (el.dom) {
  21990. el.remove();
  21991. } else {
  21992. Ext.removeNode(el);
  21993. }
  21994. }
  21995. Ext.Array.erase(elements, val, 1);
  21996. }
  21997. }
  21998. return this;
  21999. }
  22000. }, function() {
  22001. this.importElementMethods();
  22002. this.prototype.on = this.prototype.addListener;
  22003. if (Ext.DomQuery){
  22004. Ext.dom.Element.selectorFunction = Ext.DomQuery.select;
  22005. }
  22006. /**
  22007. * Selects elements based on the passed CSS selector to enable {@link Ext.Element Element} methods
  22008. * to be applied to many related elements in one statement through the returned
  22009. * {@link Ext.dom.CompositeElement CompositeElement} or
  22010. * {@link Ext.dom.CompositeElementLite CompositeElementLite} object.
  22011. * @param {String/HTMLElement[]} selector The CSS selector or an array of elements
  22012. * @param {HTMLElement/String} [root] The root element of the query or id of the root
  22013. * @return {Ext.dom.CompositeElementLite/Ext.dom.CompositeElement}
  22014. * @member Ext.dom.Element
  22015. * @method select
  22016. * @static
  22017. */
  22018. Ext.dom.Element.select = function(selector, root) {
  22019. var elements;
  22020. if (typeof selector == "string") {
  22021. elements = Ext.dom.Element.selectorFunction(selector, root);
  22022. }
  22023. else if (selector.length !== undefined) {
  22024. elements = selector;
  22025. }
  22026. else {
  22027. }
  22028. return new Ext.CompositeElementLite(elements);
  22029. };
  22030. /**
  22031. * @member Ext
  22032. * @method select
  22033. * @inheritdoc Ext.dom.Element#select
  22034. */
  22035. Ext.select = function() {
  22036. return Ext.dom.Element.select.apply(Ext.dom.Element, arguments);
  22037. };
  22038. });
  22039. /**
  22040. * @class Ext.dom.CompositeElement
  22041. * <p>This class encapsulates a <i>collection</i> of DOM elements, providing methods to filter
  22042. * members, or to perform collective actions upon the whole set.</p>
  22043. * <p>Although they are not listed, this class supports all of the methods of {@link Ext.dom.Element} and
  22044. * {@link Ext.fx.Anim}. The methods from these classes will be performed on all the elements in this collection.</p>
  22045. * <p>All methods return <i>this</i> and can be chained.</p>
  22046. * Usage:
  22047. <pre><code>
  22048. var els = Ext.select("#some-el div.some-class", true);
  22049. // or select directly from an existing element
  22050. var el = Ext.get('some-el');
  22051. el.select('div.some-class', true);
  22052. els.setWidth(100); // all elements become 100 width
  22053. els.hide(true); // all elements fade out and hide
  22054. // or
  22055. els.setWidth(100).hide(true);
  22056. </code></pre>
  22057. */
  22058. Ext.define('Ext.dom.CompositeElement', {
  22059. alternateClassName: 'Ext.CompositeElement',
  22060. extend: 'Ext.dom.CompositeElementLite',
  22061. // private
  22062. getElement: function(el) {
  22063. // In this case just return it, since we already have a reference to it
  22064. return el;
  22065. },
  22066. // private
  22067. transformElement: function(el) {
  22068. return Ext.get(el);
  22069. }
  22070. }, function() {
  22071. /**
  22072. * Selects elements based on the passed CSS selector to enable {@link Ext.Element Element} methods
  22073. * to be applied to many related elements in one statement through the returned {@link Ext.CompositeElement CompositeElement} or
  22074. * {@link Ext.CompositeElementLite CompositeElementLite} object.
  22075. * @param {String/HTMLElement[]} selector The CSS selector or an array of elements
  22076. * @param {Boolean} [unique] true to create a unique Ext.Element for each element (defaults to a shared flyweight object)
  22077. * @param {HTMLElement/String} [root] The root element of the query or id of the root
  22078. * @return {Ext.CompositeElementLite/Ext.CompositeElement}
  22079. * @member Ext.dom.Element
  22080. * @method select
  22081. * @static
  22082. */
  22083. Ext.dom.Element.select = function(selector, unique, root) {
  22084. var elements;
  22085. if (typeof selector == "string") {
  22086. elements = Ext.dom.Element.selectorFunction(selector, root);
  22087. }
  22088. else if (selector.length !== undefined) {
  22089. elements = selector;
  22090. }
  22091. else {
  22092. }
  22093. return (unique === true) ? new Ext.CompositeElement(elements) : new Ext.CompositeElementLite(elements);
  22094. };
  22095. });
  22096. /**
  22097. * Shorthand of {@link Ext.Element#method-select}.
  22098. * @member Ext
  22099. * @method select
  22100. * @inheritdoc Ext.Element#select
  22101. */
  22102. Ext.select = Ext.Element.select;
  22103. Ext._endTime = new Date().getTime();