ux-debug.js 157 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314
  1. Ext.define(null, {
  2. override: 'Ext.ux.gauge.needle.Abstract',
  3. compatibility: Ext.isIE10p,
  4. setTransform: function(centerX, centerY, rotation) {
  5. var needleGroup = this.getNeedleGroup();
  6. this.callParent([
  7. centerX,
  8. centerY,
  9. rotation
  10. ]);
  11. needleGroup.set({
  12. transform: getComputedStyle(needleGroup.dom).getPropertyValue('transform')
  13. });
  14. },
  15. updateStyle: function(style) {
  16. var pathElement;
  17. this.callParent([
  18. style
  19. ]);
  20. if (Ext.isObject(style) && 'transform' in style) {
  21. pathElement = this.getNeedlePath();
  22. pathElement.set({
  23. transform: getComputedStyle(pathElement.dom).getPropertyValue('transform')
  24. });
  25. }
  26. }
  27. });
  28. /**
  29. * This is a base class for more advanced "simlets" (simulated servers). A simlet is asked
  30. * to provide a response given a {@link Ext.ux.ajax.SimXhr} instance.
  31. */
  32. Ext.define('Ext.ux.ajax.Simlet', function() {
  33. var urlRegex = /([^?#]*)(#.*)?$/,
  34. dateRegex = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/,
  35. intRegex = /^[+-]?\d+$/,
  36. floatRegex = /^[+-]?\d+\.\d+$/;
  37. function parseParamValue(value) {
  38. var m;
  39. if (Ext.isDefined(value)) {
  40. value = decodeURIComponent(value);
  41. if (intRegex.test(value)) {
  42. value = parseInt(value, 10);
  43. } else if (floatRegex.test(value)) {
  44. value = parseFloat(value);
  45. } else if (!!(m = dateRegex.exec(value))) {
  46. value = new Date(Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]));
  47. }
  48. }
  49. return value;
  50. }
  51. return {
  52. alias: 'simlet.basic',
  53. isSimlet: true,
  54. responseProps: [
  55. 'responseText',
  56. 'responseXML',
  57. 'status',
  58. 'statusText',
  59. 'responseHeaders'
  60. ],
  61. /**
  62. * @cfg {String/Function} responseText
  63. */
  64. /**
  65. * @cfg {String/Function} responseXML
  66. */
  67. /**
  68. * @cfg {Object/Function} responseHeaders
  69. */
  70. /**
  71. * @cfg {Number/Function} status
  72. */
  73. status: 200,
  74. /**
  75. * @cfg {String/Function} statusText
  76. */
  77. statusText: 'OK',
  78. constructor: function(config) {
  79. Ext.apply(this, config);
  80. },
  81. doGet: function(ctx) {
  82. return this.handleRequest(ctx);
  83. },
  84. doPost: function(ctx) {
  85. return this.handleRequest(ctx);
  86. },
  87. doRedirect: function(ctx) {
  88. return false;
  89. },
  90. doDelete: function(ctx) {
  91. var me = this,
  92. xhr = ctx.xhr,
  93. records = xhr.options.records;
  94. me.removeFromData(ctx, records);
  95. },
  96. /**
  97. * Performs the action requested by the given XHR and returns an object to be applied
  98. * on to the XHR (containing `status`, `responseText`, etc.). For the most part,
  99. * this is delegated to `doMethod` methods on this class, such as `doGet`.
  100. *
  101. * @param {Ext.ux.ajax.SimXhr} xhr The simulated XMLHttpRequest instance.
  102. * @return {Object} The response properties to add to the XMLHttpRequest.
  103. */
  104. exec: function(xhr) {
  105. var me = this,
  106. ret = {},
  107. method = 'do' + Ext.String.capitalize(xhr.method.toLowerCase()),
  108. // doGet
  109. fn = me[method];
  110. if (fn) {
  111. ret = fn.call(me, me.getCtx(xhr.method, xhr.url, xhr));
  112. } else {
  113. ret = {
  114. status: 405,
  115. statusText: 'Method Not Allowed'
  116. };
  117. }
  118. return ret;
  119. },
  120. getCtx: function(method, url, xhr) {
  121. return {
  122. method: method,
  123. params: this.parseQueryString(url),
  124. url: url,
  125. xhr: xhr
  126. };
  127. },
  128. handleRequest: function(ctx) {
  129. var me = this,
  130. ret = {},
  131. val;
  132. Ext.Array.forEach(me.responseProps, function(prop) {
  133. if (prop in me) {
  134. val = me[prop];
  135. if (Ext.isFunction(val)) {
  136. val = val.call(me, ctx);
  137. }
  138. ret[prop] = val;
  139. }
  140. });
  141. return ret;
  142. },
  143. openRequest: function(method, url, options, async) {
  144. var ctx = this.getCtx(method, url),
  145. redirect = this.doRedirect(ctx),
  146. xhr;
  147. if (options.action === 'destroy') {
  148. method = 'delete';
  149. }
  150. if (redirect) {
  151. xhr = redirect;
  152. } else {
  153. xhr = new Ext.ux.ajax.SimXhr({
  154. mgr: this.manager,
  155. simlet: this,
  156. options: options
  157. });
  158. xhr.open(method, url, async);
  159. }
  160. return xhr;
  161. },
  162. parseQueryString: function(str) {
  163. var m = urlRegex.exec(str),
  164. ret = {},
  165. key, value, i, n;
  166. if (m && m[1]) {
  167. var pair,
  168. parts = m[1].split('&');
  169. for (i = 0 , n = parts.length; i < n; ++i) {
  170. if ((pair = parts[i].split('='))[0]) {
  171. key = decodeURIComponent(pair.shift());
  172. value = parseParamValue((pair.length > 1) ? pair.join('=') : pair[0]);
  173. if (!(key in ret)) {
  174. ret[key] = value;
  175. } else if (Ext.isArray(ret[key])) {
  176. ret[key].push(value);
  177. } else {
  178. ret[key] = [
  179. ret[key],
  180. value
  181. ];
  182. }
  183. }
  184. }
  185. }
  186. return ret;
  187. },
  188. redirect: function(method, url, params) {
  189. switch (arguments.length) {
  190. case 2:
  191. if (typeof url == 'string') {
  192. break;
  193. };
  194. params = url;
  195. // fall...
  196. case 1:
  197. url = method;
  198. method = 'GET';
  199. break;
  200. }
  201. if (params) {
  202. url = Ext.urlAppend(url, Ext.Object.toQueryString(params));
  203. }
  204. return this.manager.openRequest(method, url);
  205. },
  206. removeFromData: function(ctx, records) {
  207. var me = this,
  208. data = me.getData(ctx),
  209. model = (ctx.xhr.options.proxy && ctx.xhr.options.proxy.getModel()) || {},
  210. idProperty = model.idProperty || 'id';
  211. Ext.each(records, function(record) {
  212. var id = record.get(idProperty);
  213. for (var i = data.length; i-- > 0; ) {
  214. if (data[i][idProperty] === id) {
  215. me.deleteRecord(i);
  216. break;
  217. }
  218. }
  219. });
  220. }
  221. };
  222. }());
  223. /**
  224. * This base class is used to handle data preparation (e.g., sorting, filtering and
  225. * group summary).
  226. */
  227. Ext.define('Ext.ux.ajax.DataSimlet', function() {
  228. function makeSortFn(def, cmp) {
  229. var order = def.direction,
  230. sign = (order && order.toUpperCase() === 'DESC') ? -1 : 1;
  231. return function(leftRec, rightRec) {
  232. var lhs = leftRec[def.property],
  233. rhs = rightRec[def.property],
  234. c = (lhs < rhs) ? -1 : ((rhs < lhs) ? 1 : 0);
  235. if (c || !cmp) {
  236. return c * sign;
  237. }
  238. return cmp(leftRec, rightRec);
  239. };
  240. }
  241. function makeSortFns(defs, cmp) {
  242. for (var sortFn = cmp,
  243. i = defs && defs.length; i; ) {
  244. sortFn = makeSortFn(defs[--i], sortFn);
  245. }
  246. return sortFn;
  247. }
  248. return {
  249. extend: 'Ext.ux.ajax.Simlet',
  250. buildNodes: function(node, path) {
  251. var me = this,
  252. nodeData = {
  253. data: []
  254. },
  255. len = node.length,
  256. children, i, child, name;
  257. me.nodes[path] = nodeData;
  258. for (i = 0; i < len; ++i) {
  259. nodeData.data.push(child = node[i]);
  260. name = child.text || child.title;
  261. child.id = path ? path + '/' + name : name;
  262. children = child.children;
  263. if (!(child.leaf = !children)) {
  264. delete child.children;
  265. me.buildNodes(children, child.id);
  266. }
  267. }
  268. },
  269. deleteRecord: function(pos) {
  270. if (this.data && typeof this.data !== 'function') {
  271. Ext.Array.removeAt(this.data, pos);
  272. }
  273. },
  274. fixTree: function(ctx, tree) {
  275. var me = this,
  276. node = ctx.params.node,
  277. nodes;
  278. if (!(nodes = me.nodes)) {
  279. me.nodes = nodes = {};
  280. me.buildNodes(tree, '');
  281. }
  282. node = nodes[node];
  283. if (node) {
  284. if (me.node) {
  285. me.node.sortedData = me.sortedData;
  286. me.node.currentOrder = me.currentOrder;
  287. }
  288. me.node = node;
  289. me.data = node.data;
  290. me.sortedData = node.sortedData;
  291. me.currentOrder = node.currentOrder;
  292. } else {
  293. me.data = null;
  294. }
  295. },
  296. getData: function(ctx) {
  297. var me = this,
  298. params = ctx.params,
  299. order = (params.filter || '') + (params.group || '') + '-' + (params.sort || '') + '-' + (params.dir || ''),
  300. tree = me.tree,
  301. dynamicData, data, fields, sortFn;
  302. if (tree) {
  303. me.fixTree(ctx, tree);
  304. }
  305. data = me.data;
  306. if (typeof data === 'function') {
  307. dynamicData = true;
  308. data = data.call(this, ctx);
  309. }
  310. // If order is '--' then it means we had no order passed, due to the string concat above
  311. if (!data || order === '--') {
  312. return data || [];
  313. }
  314. if (!dynamicData && order == me.currentOrder) {
  315. return me.sortedData;
  316. }
  317. ctx.filterSpec = params.filter && Ext.decode(params.filter);
  318. ctx.groupSpec = params.group && Ext.decode(params.group);
  319. fields = params.sort;
  320. if (params.dir) {
  321. fields = [
  322. {
  323. direction: params.dir,
  324. property: fields
  325. }
  326. ];
  327. } else if (params.sort) {
  328. fields = Ext.decode(params.sort);
  329. } else {
  330. fields = null;
  331. }
  332. if (ctx.filterSpec) {
  333. var filters = new Ext.util.FilterCollection();
  334. filters.add(this.processFilters(ctx.filterSpec));
  335. data = Ext.Array.filter(data, filters.getFilterFn());
  336. }
  337. sortFn = makeSortFns((ctx.sortSpec = fields));
  338. if (ctx.groupSpec) {
  339. sortFn = makeSortFns([
  340. ctx.groupSpec
  341. ], sortFn);
  342. }
  343. // If a straight Ajax request, data may not be an array.
  344. // If an Array, preserve 'physical' order of raw data...
  345. data = Ext.isArray(data) ? data.slice(0) : data;
  346. if (sortFn) {
  347. Ext.Array.sort(data, sortFn);
  348. }
  349. me.sortedData = data;
  350. me.currentOrder = order;
  351. return data;
  352. },
  353. processFilters: Ext.identityFn,
  354. getPage: function(ctx, data) {
  355. var ret = data,
  356. length = data.length,
  357. start = ctx.params.start || 0,
  358. end = ctx.params.limit ? Math.min(length, start + ctx.params.limit) : length;
  359. if (start || end < length) {
  360. ret = ret.slice(start, end);
  361. }
  362. return ret;
  363. },
  364. getGroupSummary: function(groupField, rows, ctx) {
  365. return rows[0];
  366. },
  367. getSummary: function(ctx, data, page) {
  368. var me = this,
  369. groupField = ctx.groupSpec.property,
  370. accum,
  371. todo = {},
  372. summary = [],
  373. fieldValue, lastFieldValue;
  374. Ext.each(page, function(rec) {
  375. fieldValue = rec[groupField];
  376. todo[fieldValue] = true;
  377. });
  378. function flush() {
  379. if (accum) {
  380. summary.push(me.getGroupSummary(groupField, accum, ctx));
  381. accum = null;
  382. }
  383. }
  384. // data is ordered primarily by the groupField, so one pass can pick up all
  385. // the summaries one at a time.
  386. Ext.each(data, function(rec) {
  387. fieldValue = rec[groupField];
  388. if (lastFieldValue !== fieldValue) {
  389. flush();
  390. lastFieldValue = fieldValue;
  391. }
  392. if (!todo[fieldValue]) {
  393. // if we have even 1 summary, we have summarized all that we need
  394. // (again because data and page are ordered by groupField)
  395. return !summary.length;
  396. }
  397. if (accum) {
  398. accum.push(rec);
  399. } else {
  400. accum = [
  401. rec
  402. ];
  403. }
  404. return true;
  405. });
  406. flush();
  407. // make sure that last pesky summary goes...
  408. return summary;
  409. }
  410. };
  411. }());
  412. /**
  413. * JSON Simlet.
  414. */
  415. Ext.define('Ext.ux.ajax.JsonSimlet', {
  416. extend: 'Ext.ux.ajax.DataSimlet',
  417. alias: 'simlet.json',
  418. doGet: function(ctx) {
  419. var me = this,
  420. data = me.getData(ctx),
  421. page = me.getPage(ctx, data),
  422. reader = ctx.xhr.options.proxy && ctx.xhr.options.proxy.getReader(),
  423. root = reader && reader.getRootProperty(),
  424. ret = me.callParent(arguments),
  425. // pick up status/statusText
  426. response = {};
  427. if (root && Ext.isArray(page)) {
  428. response[root] = page;
  429. response[reader.getTotalProperty()] = data.length;
  430. } else {
  431. response = page;
  432. }
  433. if (ctx.groupSpec) {
  434. response.summaryData = me.getSummary(ctx, data, page);
  435. }
  436. ret.responseText = Ext.encode(response);
  437. return ret;
  438. },
  439. doPost: function(ctx) {
  440. return this.doGet(ctx);
  441. }
  442. });
  443. /**
  444. * Pivot Simlet does remote pivot calculations.
  445. * Filtering the pivot results doesn't work.
  446. */
  447. Ext.define('Ext.ux.ajax.PivotSimlet', {
  448. extend: 'Ext.ux.ajax.JsonSimlet',
  449. alias: 'simlet.pivot',
  450. lastPost: null,
  451. // last Ajax params sent to this simlet
  452. lastResponse: null,
  453. // last JSON response produced by this simlet
  454. keysSeparator: '',
  455. grandTotalKey: '',
  456. doPost: function(ctx) {
  457. var me = this,
  458. ret = me.callParent(arguments);
  459. // pick up status/statusText
  460. me.lastResponse = me.processData(me.getData(ctx), Ext.decode(ctx.xhr.body));
  461. ret.responseText = Ext.encode(me.lastResponse);
  462. return ret;
  463. },
  464. processData: function(data, params) {
  465. var me = this,
  466. len = data.length,
  467. response = {
  468. success: true,
  469. leftAxis: [],
  470. topAxis: [],
  471. results: []
  472. },
  473. leftAxis = new Ext.util.MixedCollection(),
  474. topAxis = new Ext.util.MixedCollection(),
  475. results = new Ext.util.MixedCollection(),
  476. i, j, k, leftKeys, topKeys, item, agg;
  477. me.lastPost = params;
  478. me.keysSeparator = params.keysSeparator;
  479. me.grandTotalKey = params.grandTotalKey;
  480. for (i = 0; i < len; i++) {
  481. leftKeys = me.extractValues(data[i], params.leftAxis, leftAxis);
  482. topKeys = me.extractValues(data[i], params.topAxis, topAxis);
  483. // add record to grand totals
  484. me.addResult(data[i], me.grandTotalKey, me.grandTotalKey, results);
  485. for (j = 0; j < leftKeys.length; j++) {
  486. // add record to col grand totals
  487. me.addResult(data[i], leftKeys[j], me.grandTotalKey, results);
  488. // add record to left/top keys pair
  489. for (k = 0; k < topKeys.length; k++) {
  490. me.addResult(data[i], leftKeys[j], topKeys[k], results);
  491. }
  492. }
  493. // add record to row grand totals
  494. for (j = 0; j < topKeys.length; j++) {
  495. me.addResult(data[i], me.grandTotalKey, topKeys[j], results);
  496. }
  497. }
  498. // extract items from their left/top collections and build the json response
  499. response.leftAxis = leftAxis.getRange();
  500. response.topAxis = topAxis.getRange();
  501. len = results.getCount();
  502. for (i = 0; i < len; i++) {
  503. item = results.getAt(i);
  504. item.values = {};
  505. for (j = 0; j < params.aggregate.length; j++) {
  506. agg = params.aggregate[j];
  507. item.values[agg.id] = me[agg.aggregator](item.records, agg.dataIndex, item.leftKey, item.topKey);
  508. }
  509. delete (item.records);
  510. response.results.push(item);
  511. }
  512. leftAxis.clear();
  513. topAxis.clear();
  514. results.clear();
  515. return response;
  516. },
  517. getKey: function(value) {
  518. var me = this;
  519. me.keysMap = me.keysMap || {};
  520. if (!Ext.isDefined(me.keysMap[value])) {
  521. me.keysMap[value] = Ext.id();
  522. }
  523. return me.keysMap[value];
  524. },
  525. extractValues: function(record, dimensions, col) {
  526. var len = dimensions.length,
  527. keys = [],
  528. i, j, key, item, dim;
  529. key = '';
  530. for (j = 0; j < len; j++) {
  531. dim = dimensions[j];
  532. key += (j > 0 ? this.keysSeparator : '') + this.getKey(record[dim.dataIndex]);
  533. item = col.getByKey(key);
  534. if (!item) {
  535. item = col.add(key, {
  536. key: key,
  537. value: record[dim.dataIndex],
  538. dimensionId: dim.id
  539. });
  540. }
  541. keys.push(key);
  542. }
  543. return keys;
  544. },
  545. addResult: function(record, leftKey, topKey, results) {
  546. var item = results.getByKey(leftKey + '/' + topKey);
  547. if (!item) {
  548. item = results.add(leftKey + '/' + topKey, {
  549. leftKey: leftKey,
  550. topKey: topKey,
  551. records: []
  552. });
  553. }
  554. item.records.push(record);
  555. },
  556. sum: function(records, measure, rowGroupKey, colGroupKey) {
  557. var length = records.length,
  558. total = 0,
  559. i;
  560. for (i = 0; i < length; i++) {
  561. total += Ext.Number.from(records[i][measure], 0);
  562. }
  563. return total;
  564. },
  565. avg: function(records, measure, rowGroupKey, colGroupKey) {
  566. var length = records.length,
  567. total = 0,
  568. i;
  569. for (i = 0; i < length; i++) {
  570. total += Ext.Number.from(records[i][measure], 0);
  571. }
  572. return length > 0 ? (total / length) : 0;
  573. },
  574. min: function(records, measure, rowGroupKey, colGroupKey) {
  575. var data = [],
  576. length = records.length,
  577. i, v;
  578. for (i = 0; i < length; i++) {
  579. data.push(records[i][measure]);
  580. }
  581. v = Ext.Array.min(data);
  582. return v;
  583. },
  584. max: function(records, measure, rowGroupKey, colGroupKey) {
  585. var data = [],
  586. length = records.length,
  587. i;
  588. for (i = 0; i < length; i++) {
  589. data.push(records[i][measure]);
  590. }
  591. v = Ext.Array.max(data);
  592. return v;
  593. },
  594. count: function(records, measure, rowGroupKey, colGroupKey) {
  595. return records.length;
  596. },
  597. variance: function(records, measure, rowGroupKey, colGroupKey) {
  598. var me = Ext.pivot.Aggregators,
  599. length = records.length,
  600. avg = me.avg.apply(me, arguments),
  601. total = 0,
  602. i;
  603. if (avg > 0) {
  604. for (i = 0; i < length; i++) {
  605. total += Math.pow(Ext.Number.from(records[i][measure], 0) - avg, 2);
  606. }
  607. }
  608. return (total > 0 && length > 1) ? (total / (length - 1)) : 0;
  609. },
  610. varianceP: function(records, measure, rowGroupKey, colGroupKey) {
  611. var me = Ext.pivot.Aggregators,
  612. length = records.length,
  613. avg = me.avg.apply(me, arguments),
  614. total = 0,
  615. i;
  616. if (avg > 0) {
  617. for (i = 0; i < length; i++) {
  618. total += Math.pow(Ext.Number.from(records[i][measure], 0) - avg, 2);
  619. }
  620. }
  621. return (total > 0 && length > 0) ? (total / length) : 0;
  622. },
  623. stdDev: function(records, measure, rowGroupKey, colGroupKey) {
  624. var me = Ext.pivot.Aggregators,
  625. v = me.variance.apply(me, arguments);
  626. return v > 0 ? Math.sqrt(v) : 0;
  627. },
  628. stdDevP: function(records, measure, rowGroupKey, colGroupKey) {
  629. var me = Ext.pivot.Aggregators,
  630. v = me.varianceP.apply(me, arguments);
  631. return v > 0 ? Math.sqrt(v) : 0;
  632. }
  633. });
  634. /**
  635. * Simulates an XMLHttpRequest object's methods and properties but is backed by a
  636. * {@link Ext.ux.ajax.Simlet} instance that provides the data.
  637. */
  638. Ext.define('Ext.ux.ajax.SimXhr', {
  639. readyState: 0,
  640. mgr: null,
  641. simlet: null,
  642. constructor: function(config) {
  643. var me = this;
  644. Ext.apply(me, config);
  645. me.requestHeaders = {};
  646. },
  647. abort: function() {
  648. var me = this;
  649. if (me.timer) {
  650. Ext.undefer(me.timer);
  651. me.timer = null;
  652. }
  653. me.aborted = true;
  654. },
  655. getAllResponseHeaders: function() {
  656. var headers = [];
  657. if (Ext.isObject(this.responseHeaders)) {
  658. Ext.Object.each(this.responseHeaders, function(name, value) {
  659. headers.push(name + ': ' + value);
  660. });
  661. }
  662. return headers.join('\r\n');
  663. },
  664. getResponseHeader: function(header) {
  665. var headers = this.responseHeaders;
  666. return (headers && headers[header]) || null;
  667. },
  668. open: function(method, url, async, user, password) {
  669. var me = this;
  670. me.method = method;
  671. me.url = url;
  672. me.async = async !== false;
  673. me.user = user;
  674. me.password = password;
  675. me.setReadyState(1);
  676. },
  677. overrideMimeType: function(mimeType) {
  678. this.mimeType = mimeType;
  679. },
  680. schedule: function() {
  681. var me = this,
  682. delay = me.simlet.delay || me.mgr.delay;
  683. if (delay) {
  684. me.timer = Ext.defer(function() {
  685. me.onTick();
  686. }, delay);
  687. } else {
  688. me.onTick();
  689. }
  690. },
  691. send: function(body) {
  692. var me = this;
  693. me.body = body;
  694. if (me.async) {
  695. me.schedule();
  696. } else {
  697. me.onComplete();
  698. }
  699. },
  700. setReadyState: function(state) {
  701. var me = this;
  702. if (me.readyState != state) {
  703. me.readyState = state;
  704. me.onreadystatechange();
  705. }
  706. },
  707. setRequestHeader: function(header, value) {
  708. this.requestHeaders[header] = value;
  709. },
  710. // handlers
  711. onreadystatechange: Ext.emptyFn,
  712. onComplete: function() {
  713. var me = this,
  714. callback;
  715. me.readyState = 4;
  716. Ext.apply(me, me.simlet.exec(me));
  717. callback = me.jsonpCallback;
  718. if (callback) {
  719. var text = callback + '(' + me.responseText + ')';
  720. eval(text);
  721. }
  722. },
  723. onTick: function() {
  724. var me = this;
  725. me.timer = null;
  726. me.onComplete();
  727. me.onreadystatechange && me.onreadystatechange();
  728. }
  729. });
  730. /**
  731. * This singleton manages simulated Ajax responses. This allows application logic to be
  732. * written unaware that its Ajax calls are being handled by simulations ("simlets"). This
  733. * is currently done by hooking {@link Ext.data.Connection} methods, so all users of that
  734. * class (and {@link Ext.Ajax} since it is a derived class) qualify for simulation.
  735. *
  736. * The requires hooks are inserted when either the {@link #init} method is called or the
  737. * first {@link Ext.ux.ajax.Simlet} is registered. For example:
  738. *
  739. * Ext.onReady(function () {
  740. * initAjaxSim();
  741. *
  742. * // normal stuff
  743. * });
  744. *
  745. * function initAjaxSim () {
  746. * Ext.ux.ajax.SimManager.init({
  747. * delay: 300
  748. * }).register({
  749. * '/app/data/url': {
  750. * type: 'json', // use JsonSimlet (type is like xtype for components)
  751. * data: [
  752. * { foo: 42, bar: 'abc' },
  753. * ...
  754. * ]
  755. * }
  756. * });
  757. * }
  758. *
  759. * As many URL's as desired can be registered and associated with a {@link Ext.ux.ajax.Simlet}. To make
  760. * non-simulated Ajax requests once this singleton is initialized, add a `nosim:true` option
  761. * to the Ajax options:
  762. *
  763. * Ext.Ajax.request({
  764. * url: 'page.php',
  765. * nosim: true, // ignored by normal Ajax request
  766. * params: {
  767. * id: 1
  768. * },
  769. * success: function(response){
  770. * var text = response.responseText;
  771. * // process server response here
  772. * }
  773. * });
  774. */
  775. Ext.define('Ext.ux.ajax.SimManager', {
  776. singleton: true,
  777. requires: [
  778. 'Ext.data.Connection',
  779. 'Ext.ux.ajax.SimXhr',
  780. 'Ext.ux.ajax.Simlet',
  781. 'Ext.ux.ajax.JsonSimlet'
  782. ],
  783. /**
  784. * @cfg {Ext.ux.ajax.Simlet} defaultSimlet
  785. * The {@link Ext.ux.ajax.Simlet} instance to use for non-matching URL's. By default, this will
  786. * return 404. Set this to null to use real Ajax calls for non-matching URL's.
  787. */
  788. /**
  789. * @cfg {String} defaultType
  790. * The default `type` to apply to generic {@link Ext.ux.ajax.Simlet} configuration objects. The
  791. * default is 'basic'.
  792. */
  793. defaultType: 'basic',
  794. /**
  795. * @cfg {Number} delay
  796. * The number of milliseconds to delay before delivering a response to an async request.
  797. */
  798. delay: 150,
  799. /**
  800. * @property {Boolean} ready
  801. * True once this singleton has initialized and applied its Ajax hooks.
  802. * @private
  803. */
  804. ready: false,
  805. constructor: function() {
  806. this.simlets = [];
  807. },
  808. getSimlet: function(url) {
  809. // Strip down to base URL (no query parameters or hash):
  810. var me = this,
  811. index = url.indexOf('?'),
  812. simlets = me.simlets,
  813. len = simlets.length,
  814. i, simlet, simUrl, match;
  815. if (index < 0) {
  816. index = url.indexOf('#');
  817. }
  818. if (index > 0) {
  819. url = url.substring(0, index);
  820. }
  821. for (i = 0; i < len; ++i) {
  822. simlet = simlets[i];
  823. simUrl = simlet.url;
  824. if (simUrl instanceof RegExp) {
  825. match = simUrl.test(url);
  826. } else {
  827. match = simUrl === url;
  828. }
  829. if (match) {
  830. return simlet;
  831. }
  832. }
  833. return me.defaultSimlet;
  834. },
  835. getXhr: function(method, url, options, async) {
  836. var simlet = this.getSimlet(url);
  837. if (simlet) {
  838. return simlet.openRequest(method, url, options, async);
  839. }
  840. return null;
  841. },
  842. /**
  843. * Initializes this singleton and applies configuration options.
  844. * @param {Object} config An optional object with configuration properties to apply.
  845. * @return {Ext.ux.ajax.SimManager} this
  846. */
  847. init: function(config) {
  848. var me = this;
  849. Ext.apply(me, config);
  850. if (!me.ready) {
  851. me.ready = true;
  852. if (!('defaultSimlet' in me)) {
  853. me.defaultSimlet = new Ext.ux.ajax.Simlet({
  854. status: 404,
  855. statusText: 'Not Found'
  856. });
  857. }
  858. me._openRequest = Ext.data.Connection.prototype.openRequest;
  859. Ext.data.request.Ajax.override({
  860. openRequest: function(options, requestOptions, async) {
  861. var xhr = !options.nosim && me.getXhr(requestOptions.method, requestOptions.url, options, async);
  862. if (!xhr) {
  863. xhr = this.callParent(arguments);
  864. }
  865. return xhr;
  866. }
  867. });
  868. if (Ext.data.JsonP) {
  869. Ext.data.JsonP.self.override({
  870. createScript: function(url, params, options) {
  871. var fullUrl = Ext.urlAppend(url, Ext.Object.toQueryString(params)),
  872. script = !options.nosim && me.getXhr('GET', fullUrl, options, true);
  873. if (!script) {
  874. script = this.callParent(arguments);
  875. }
  876. return script;
  877. },
  878. loadScript: function(request) {
  879. var script = request.script;
  880. if (script.simlet) {
  881. script.jsonpCallback = request.params[request.callbackKey];
  882. script.send(null);
  883. // Ext.data.JsonP will attempt dom removal of a script tag, so emulate its presence
  884. request.script = document.createElement('script');
  885. } else {
  886. this.callParent(arguments);
  887. }
  888. }
  889. });
  890. }
  891. }
  892. return me;
  893. },
  894. openRequest: function(method, url, async) {
  895. var opt = {
  896. method: method,
  897. url: url
  898. };
  899. return this._openRequest.call(Ext.data.Connection.prototype, {}, opt, async);
  900. },
  901. /**
  902. * Registeres one or more {@link Ext.ux.ajax.Simlet} instances.
  903. * @param {Array/Object} simlet Either a {@link Ext.ux.ajax.Simlet} instance or config, an Array
  904. * of such elements or an Object keyed by URL with values that are {@link Ext.ux.ajax.Simlet}
  905. * instances or configs.
  906. */
  907. register: function(simlet) {
  908. var me = this;
  909. me.init();
  910. function reg(one) {
  911. var simlet = one;
  912. if (!simlet.isSimlet) {
  913. simlet = Ext.create('simlet.' + (simlet.type || simlet.stype || me.defaultType), one);
  914. }
  915. me.simlets.push(simlet);
  916. simlet.manager = me;
  917. }
  918. if (Ext.isArray(simlet)) {
  919. Ext.each(simlet, reg);
  920. } else if (simlet.isSimlet || simlet.url) {
  921. reg(simlet);
  922. } else {
  923. Ext.Object.each(simlet, function(url, s) {
  924. s.url = url;
  925. reg(s);
  926. });
  927. }
  928. return me;
  929. }
  930. });
  931. /**
  932. * This class simulates XML-based requests.
  933. */
  934. Ext.define('Ext.ux.ajax.XmlSimlet', {
  935. extend: 'Ext.ux.ajax.DataSimlet',
  936. alias: 'simlet.xml',
  937. /**
  938. * This template is used to populate the XML response. The configuration of the Reader
  939. * is available so that its `root` and `record` properties can be used as well as the
  940. * `fields` of the associated `model`. But beyond that, the way these pieces are put
  941. * together in the document requires the flexibility of a template.
  942. */
  943. xmlTpl: [
  944. '<{root}>\n',
  945. '<tpl for="data">',
  946. ' <{parent.record}>\n',
  947. '<tpl for="parent.fields">',
  948. ' <{name}>{[parent[values.name]]}</{name}>\n',
  949. '</tpl>',
  950. ' </{parent.record}>\n',
  951. '</tpl>',
  952. '</{root}>'
  953. ],
  954. doGet: function(ctx) {
  955. var me = this,
  956. data = me.getData(ctx),
  957. page = me.getPage(ctx, data),
  958. proxy = ctx.xhr.options.operation.getProxy(),
  959. reader = proxy && proxy.getReader(),
  960. model = reader && reader.getModel(),
  961. ret = me.callParent(arguments),
  962. // pick up status/statusText
  963. response = {
  964. data: page,
  965. reader: reader,
  966. fields: model && model.fields,
  967. root: reader && reader.getRootProperty(),
  968. record: reader && reader.record
  969. },
  970. tpl, xml, doc;
  971. if (ctx.groupSpec) {
  972. response.summaryData = me.getSummary(ctx, data, page);
  973. }
  974. // If a straight Ajax request there won't be an xmlTpl.
  975. if (me.xmlTpl) {
  976. tpl = Ext.XTemplate.getTpl(me, 'xmlTpl');
  977. xml = tpl.apply(response);
  978. } else {
  979. xml = data;
  980. }
  981. if (typeof DOMParser != 'undefined') {
  982. doc = (new DOMParser()).parseFromString(xml, "text/xml");
  983. } else {
  984. // IE doesn't have DOMParser, but fortunately, there is an ActiveX for XML
  985. doc = new ActiveXObject("Microsoft.XMLDOM");
  986. doc.async = false;
  987. doc.loadXML(xml);
  988. }
  989. ret.responseText = xml;
  990. ret.responseXML = doc;
  991. return ret;
  992. },
  993. fixTree: function() {
  994. this.callParent(arguments);
  995. var buffer = [];
  996. this.buildTreeXml(this.data, buffer);
  997. this.data = buffer.join('');
  998. },
  999. buildTreeXml: function(nodes, buffer) {
  1000. var rootProperty = this.rootProperty,
  1001. recordProperty = this.recordProperty;
  1002. buffer.push('<', rootProperty, '>');
  1003. Ext.Array.forEach(nodes, function(node) {
  1004. buffer.push('<', recordProperty, '>');
  1005. for (var key in node) {
  1006. if (key == 'children') {
  1007. this.buildTreeXml(node.children, buffer);
  1008. } else {
  1009. buffer.push('<', key, '>', node[key], '</', key, '>');
  1010. }
  1011. }
  1012. buffer.push('</', recordProperty, '>');
  1013. });
  1014. buffer.push('</', rootProperty, '>');
  1015. }
  1016. });
  1017. /**
  1018. * This is the base class for {@link Ext.ux.event.Recorder} and {@link Ext.ux.event.Player}.
  1019. */
  1020. Ext.define('Ext.ux.event.Driver', {
  1021. extend: 'Ext.util.Observable',
  1022. active: null,
  1023. specialKeysByName: {
  1024. PGUP: 33,
  1025. PGDN: 34,
  1026. END: 35,
  1027. HOME: 36,
  1028. LEFT: 37,
  1029. UP: 38,
  1030. RIGHT: 39,
  1031. DOWN: 40
  1032. },
  1033. specialKeysByCode: {},
  1034. /**
  1035. * @event start
  1036. * Fires when this object is started.
  1037. * @param {Ext.ux.event.Driver} this
  1038. */
  1039. /**
  1040. * @event stop
  1041. * Fires when this object is stopped.
  1042. * @param {Ext.ux.event.Driver} this
  1043. */
  1044. getTextSelection: function(el) {
  1045. // See https://code.google.com/p/rangyinputs/source/browse/trunk/rangyinputs_jquery.js
  1046. var doc = el.ownerDocument,
  1047. range, range2, start, end;
  1048. if (typeof el.selectionStart === "number") {
  1049. start = el.selectionStart;
  1050. end = el.selectionEnd;
  1051. } else if (doc.selection) {
  1052. range = doc.selection.createRange();
  1053. range2 = el.createTextRange();
  1054. range2.setEndPoint('EndToStart', range);
  1055. start = range2.text.length;
  1056. end = start + range.text.length;
  1057. }
  1058. return [
  1059. start,
  1060. end
  1061. ];
  1062. },
  1063. getTime: function() {
  1064. return new Date().getTime();
  1065. },
  1066. /**
  1067. * Returns the number of milliseconds since start was called.
  1068. */
  1069. getTimestamp: function() {
  1070. var d = this.getTime();
  1071. return d - this.startTime;
  1072. },
  1073. onStart: function() {},
  1074. onStop: function() {},
  1075. /**
  1076. * Starts this object. If this object is already started, nothing happens.
  1077. */
  1078. start: function() {
  1079. var me = this;
  1080. if (!me.active) {
  1081. me.active = new Date();
  1082. me.startTime = me.getTime();
  1083. me.onStart();
  1084. me.fireEvent('start', me);
  1085. }
  1086. },
  1087. /**
  1088. * Stops this object. If this object is not started, nothing happens.
  1089. */
  1090. stop: function() {
  1091. var me = this;
  1092. if (me.active) {
  1093. me.active = null;
  1094. me.onStop();
  1095. me.fireEvent('stop', me);
  1096. }
  1097. }
  1098. }, function() {
  1099. var proto = this.prototype;
  1100. Ext.Object.each(proto.specialKeysByName, function(name, value) {
  1101. proto.specialKeysByCode[value] = name;
  1102. });
  1103. });
  1104. /**
  1105. * Event maker.
  1106. */
  1107. Ext.define('Ext.ux.event.Maker', {
  1108. eventQueue: [],
  1109. startAfter: 500,
  1110. timerIncrement: 500,
  1111. currentTiming: 0,
  1112. constructor: function(config) {
  1113. var me = this;
  1114. me.currentTiming = me.startAfter;
  1115. if (!Ext.isArray(config)) {
  1116. config = [
  1117. config
  1118. ];
  1119. }
  1120. Ext.Array.each(config, function(item) {
  1121. item.el = item.el || 'el';
  1122. Ext.Array.each(Ext.ComponentQuery.query(item.cmpQuery), function(cmp) {
  1123. var event = {},
  1124. x, y, el;
  1125. if (!item.domQuery) {
  1126. el = cmp[item.el];
  1127. } else {
  1128. el = cmp.el.down(item.domQuery);
  1129. }
  1130. event.target = '#' + el.dom.id;
  1131. event.type = item.type;
  1132. event.button = config.button || 0;
  1133. x = el.getX() + (el.getWidth() / 2);
  1134. y = el.getY() + (el.getHeight() / 2);
  1135. event.xy = [
  1136. x,
  1137. y
  1138. ];
  1139. event.ts = me.currentTiming;
  1140. me.currentTiming += me.timerIncrement;
  1141. me.eventQueue.push(event);
  1142. });
  1143. if (item.screenshot) {
  1144. me.eventQueue[me.eventQueue.length - 1].screenshot = true;
  1145. }
  1146. });
  1147. return me.eventQueue;
  1148. }
  1149. });
  1150. /**
  1151. * @extends Ext.ux.event.Driver
  1152. * This class manages the playback of an array of "event descriptors". For details on the
  1153. * contents of an "event descriptor", see {@link Ext.ux.event.Recorder}. The events recorded by the
  1154. * {@link Ext.ux.event.Recorder} class are designed to serve as input for this class.
  1155. *
  1156. * The simplest use of this class is to instantiate it with an {@link #eventQueue} and call
  1157. * {@link #method-start}. Like so:
  1158. *
  1159. * var player = Ext.create('Ext.ux.event.Player', {
  1160. * eventQueue: [ ... ],
  1161. * speed: 2, // play at 2x speed
  1162. * listeners: {
  1163. * stop: function () {
  1164. * player = null; // all done
  1165. * }
  1166. * }
  1167. * });
  1168. *
  1169. * player.start();
  1170. *
  1171. * A more complex use would be to incorporate keyframe generation after playing certain
  1172. * events.
  1173. *
  1174. * var player = Ext.create('Ext.ux.event.Player', {
  1175. * eventQueue: [ ... ],
  1176. * keyFrameEvents: {
  1177. * click: true
  1178. * },
  1179. * listeners: {
  1180. * stop: function () {
  1181. * // play has completed... probably time for another keyframe...
  1182. * player = null;
  1183. * },
  1184. * keyframe: onKeyFrame
  1185. * }
  1186. * });
  1187. *
  1188. * player.start();
  1189. *
  1190. * If a keyframe can be handled immediately (synchronously), the listener would be:
  1191. *
  1192. * function onKeyFrame () {
  1193. * handleKeyFrame();
  1194. * }
  1195. *
  1196. * If the keyframe event is always handled asynchronously, then the event listener is only
  1197. * a bit more:
  1198. *
  1199. * function onKeyFrame (p, eventDescriptor) {
  1200. * eventDescriptor.defer(); // pause event playback...
  1201. *
  1202. * handleKeyFrame(function () {
  1203. * eventDescriptor.finish(); // ...resume event playback
  1204. * });
  1205. * }
  1206. *
  1207. * Finally, if the keyframe could be either handled synchronously or asynchronously (perhaps
  1208. * differently by browser), a slightly more complex listener is required.
  1209. *
  1210. * function onKeyFrame (p, eventDescriptor) {
  1211. * var async;
  1212. *
  1213. * handleKeyFrame(function () {
  1214. * // either this callback is being called immediately by handleKeyFrame (in
  1215. * // which case async is undefined) or it is being called later (in which case
  1216. * // async will be true).
  1217. *
  1218. * if (async) {
  1219. * eventDescriptor.finish();
  1220. * } else {
  1221. * async = false;
  1222. * }
  1223. * });
  1224. *
  1225. * // either the callback was called (and async is now false) or it was not
  1226. * // called (and async remains undefined).
  1227. *
  1228. * if (async !== false) {
  1229. * eventDescriptor.defer();
  1230. * async = true; // let the callback know that we have gone async
  1231. * }
  1232. * }
  1233. */
  1234. Ext.define('Ext.ux.event.Player', function(Player) {
  1235. var defaults = {},
  1236. mouseEvents = {},
  1237. keyEvents = {},
  1238. doc,
  1239. //HTML events supported
  1240. uiEvents = {},
  1241. //events that bubble by default
  1242. bubbleEvents = {
  1243. //scroll: 1,
  1244. resize: 1,
  1245. reset: 1,
  1246. submit: 1,
  1247. change: 1,
  1248. select: 1,
  1249. error: 1,
  1250. abort: 1
  1251. };
  1252. Ext.each([
  1253. 'click',
  1254. 'dblclick',
  1255. 'mouseover',
  1256. 'mouseout',
  1257. 'mousedown',
  1258. 'mouseup',
  1259. 'mousemove'
  1260. ], function(type) {
  1261. bubbleEvents[type] = defaults[type] = mouseEvents[type] = {
  1262. bubbles: true,
  1263. cancelable: (type != "mousemove"),
  1264. // mousemove cannot be cancelled
  1265. detail: 1,
  1266. screenX: 0,
  1267. screenY: 0,
  1268. clientX: 0,
  1269. clientY: 0,
  1270. ctrlKey: false,
  1271. altKey: false,
  1272. shiftKey: false,
  1273. metaKey: false,
  1274. button: 0
  1275. };
  1276. });
  1277. Ext.each([
  1278. 'keydown',
  1279. 'keyup',
  1280. 'keypress'
  1281. ], function(type) {
  1282. bubbleEvents[type] = defaults[type] = keyEvents[type] = {
  1283. bubbles: true,
  1284. cancelable: true,
  1285. ctrlKey: false,
  1286. altKey: false,
  1287. shiftKey: false,
  1288. metaKey: false,
  1289. keyCode: 0,
  1290. charCode: 0
  1291. };
  1292. });
  1293. Ext.each([
  1294. 'blur',
  1295. 'change',
  1296. 'focus',
  1297. 'resize',
  1298. 'scroll',
  1299. 'select'
  1300. ], function(type) {
  1301. defaults[type] = uiEvents[type] = {
  1302. bubbles: (type in bubbleEvents),
  1303. cancelable: false,
  1304. detail: 1
  1305. };
  1306. });
  1307. var inputSpecialKeys = {
  1308. 8: function(target, start, end) {
  1309. // backspace: 8,
  1310. if (start < end) {
  1311. target.value = target.value.substring(0, start) + target.value.substring(end);
  1312. } else if (start > 0) {
  1313. target.value = target.value.substring(0, --start) + target.value.substring(end);
  1314. }
  1315. this.setTextSelection(target, start, start);
  1316. },
  1317. 46: function(target, start, end) {
  1318. // delete: 46
  1319. if (start < end) {
  1320. target.value = target.value.substring(0, start) + target.value.substring(end);
  1321. } else if (start < target.value.length - 1) {
  1322. target.value = target.value.substring(0, start) + target.value.substring(start + 1);
  1323. }
  1324. this.setTextSelection(target, start, start);
  1325. }
  1326. };
  1327. return {
  1328. extend: 'Ext.ux.event.Driver',
  1329. /**
  1330. * @cfg {Array} eventQueue The event queue to playback. This must be provided before
  1331. * the {@link #method-start} method is called.
  1332. */
  1333. /**
  1334. * @cfg {Object} keyFrameEvents An object that describes the events that should generate
  1335. * keyframe events. For example, `{ click: true }` would generate keyframe events after
  1336. * each `click` event.
  1337. */
  1338. keyFrameEvents: {
  1339. click: true
  1340. },
  1341. /**
  1342. * @cfg {Boolean} pauseForAnimations True to pause event playback during animations, false
  1343. * to ignore animations. Default is true.
  1344. */
  1345. pauseForAnimations: true,
  1346. /**
  1347. * @cfg {Number} speed The playback speed multiplier. Default is 1.0 (to playback at the
  1348. * recorded speed). A value of 2 would playback at 2x speed.
  1349. */
  1350. speed: 1,
  1351. stallTime: 0,
  1352. _inputSpecialKeys: {
  1353. INPUT: inputSpecialKeys,
  1354. TEXTAREA: Ext.apply({}, //13: function (target, start, end) { // enter: 8,
  1355. //TODO ?
  1356. //}
  1357. inputSpecialKeys)
  1358. },
  1359. tagPathRegEx: /(\w+)(?:\[(\d+)\])?/,
  1360. /**
  1361. * @event beforeplay
  1362. * Fires before an event is played.
  1363. * @param {Ext.ux.event.Player} this
  1364. * @param {Object} eventDescriptor The event descriptor about to be played.
  1365. */
  1366. /**
  1367. * @event keyframe
  1368. * Fires when this player reaches a keyframe. Typically, this is after events
  1369. * like `click` are injected and any resulting animations have been completed.
  1370. * @param {Ext.ux.event.Player} this
  1371. * @param {Object} eventDescriptor The keyframe event descriptor.
  1372. */
  1373. constructor: function(config) {
  1374. var me = this;
  1375. me.callParent(arguments);
  1376. me.timerFn = function() {
  1377. me.onTick();
  1378. };
  1379. me.attachTo = me.attachTo || window;
  1380. doc = me.attachTo.document;
  1381. },
  1382. /**
  1383. * Returns the element given is XPath-like description.
  1384. * @param {String} xpath The XPath-like description of the element.
  1385. * @return {HTMLElement}
  1386. */
  1387. getElementFromXPath: function(xpath) {
  1388. var me = this,
  1389. parts = xpath.split('/'),
  1390. regex = me.tagPathRegEx,
  1391. i, n, m, count, tag, child,
  1392. el = me.attachTo.document;
  1393. el = (parts[0] == '~') ? el.body : el.getElementById(parts[0].substring(1));
  1394. // remove '#'
  1395. for (i = 1 , n = parts.length; el && i < n; ++i) {
  1396. m = regex.exec(parts[i]);
  1397. count = m[2] ? parseInt(m[2], 10) : 1;
  1398. tag = m[1].toUpperCase();
  1399. for (child = el.firstChild; child; child = child.nextSibling) {
  1400. if (child.tagName == tag) {
  1401. if (count == 1) {
  1402. break;
  1403. }
  1404. --count;
  1405. }
  1406. }
  1407. el = child;
  1408. }
  1409. return el;
  1410. },
  1411. // Moving across a line break only counts as moving one character in a TextRange, whereas a line break in
  1412. // the textarea value is two characters. This function corrects for that by converting a text offset into a
  1413. // range character offset by subtracting one character for every line break in the textarea prior to the
  1414. // offset
  1415. offsetToRangeCharacterMove: function(el, offset) {
  1416. return offset - (el.value.slice(0, offset).split("\r\n").length - 1);
  1417. },
  1418. setTextSelection: function(el, startOffset, endOffset) {
  1419. // See https://code.google.com/p/rangyinputs/source/browse/trunk/rangyinputs_jquery.js
  1420. if (startOffset < 0) {
  1421. startOffset += el.value.length;
  1422. }
  1423. if (endOffset == null) {
  1424. endOffset = startOffset;
  1425. }
  1426. if (endOffset < 0) {
  1427. endOffset += el.value.length;
  1428. }
  1429. if (typeof el.selectionStart === "number") {
  1430. el.selectionStart = startOffset;
  1431. el.selectionEnd = endOffset;
  1432. } else {
  1433. var range = el.createTextRange();
  1434. var startCharMove = this.offsetToRangeCharacterMove(el, startOffset);
  1435. range.collapse(true);
  1436. if (startOffset == endOffset) {
  1437. range.move("character", startCharMove);
  1438. } else {
  1439. range.moveEnd("character", this.offsetToRangeCharacterMove(el, endOffset));
  1440. range.moveStart("character", startCharMove);
  1441. }
  1442. range.select();
  1443. }
  1444. },
  1445. getTimeIndex: function() {
  1446. var t = this.getTimestamp() - this.stallTime;
  1447. return t * this.speed;
  1448. },
  1449. makeToken: function(eventDescriptor, signal) {
  1450. var me = this,
  1451. t0;
  1452. eventDescriptor[signal] = true;
  1453. eventDescriptor.defer = function() {
  1454. eventDescriptor[signal] = false;
  1455. t0 = me.getTime();
  1456. };
  1457. eventDescriptor.finish = function() {
  1458. eventDescriptor[signal] = true;
  1459. me.stallTime += me.getTime() - t0;
  1460. me.schedule();
  1461. };
  1462. },
  1463. /**
  1464. * This method is called after an event has been played to prepare for the next event.
  1465. * @param {Object} eventDescriptor The descriptor of the event just played.
  1466. */
  1467. nextEvent: function(eventDescriptor) {
  1468. var me = this,
  1469. index = ++me.queueIndex;
  1470. // keyframe events are inserted after a keyFrameEvent is played.
  1471. if (me.keyFrameEvents[eventDescriptor.type]) {
  1472. Ext.Array.insert(me.eventQueue, index, [
  1473. {
  1474. keyframe: true,
  1475. ts: eventDescriptor.ts
  1476. }
  1477. ]);
  1478. }
  1479. },
  1480. /**
  1481. * This method returns the event descriptor at the front of the queue. This does not
  1482. * dequeue the event. Repeated calls return the same object (until {@link #nextEvent}
  1483. * is called).
  1484. */
  1485. peekEvent: function() {
  1486. return this.eventQueue[this.queueIndex] || null;
  1487. },
  1488. /**
  1489. * Replaces an event in the queue with an array of events. This is often used to roll
  1490. * up a multi-step pseudo-event and expand it just-in-time to be played. The process
  1491. * for doing this in a derived class would be this:
  1492. *
  1493. * Ext.define('My.Player', {
  1494. * extend: 'Ext.ux.event.Player',
  1495. *
  1496. * peekEvent: function () {
  1497. * var event = this.callParent();
  1498. *
  1499. * if (event.multiStepSpecial) {
  1500. * this.replaceEvent(null, [
  1501. * ... expand to actual events
  1502. * ]);
  1503. *
  1504. * event = this.callParent(); // get the new next event
  1505. * }
  1506. *
  1507. * return event;
  1508. * }
  1509. * });
  1510. *
  1511. * This method ensures that the `beforeplay` hook (if any) from the replaced event is
  1512. * placed on the first new event and the `afterplay` hook (if any) is placed on the
  1513. * last new event.
  1514. *
  1515. * @param {Number} index The queue index to replace. Pass `null` to replace the event
  1516. * at the current `queueIndex`.
  1517. * @param {Event[]} events The array of events with which to replace the specified
  1518. * event.
  1519. */
  1520. replaceEvent: function(index, events) {
  1521. for (var t,
  1522. i = 0,
  1523. n = events.length; i < n; ++i) {
  1524. if (i) {
  1525. t = events[i - 1];
  1526. delete t.afterplay;
  1527. delete t.screenshot;
  1528. delete events[i].beforeplay;
  1529. }
  1530. }
  1531. Ext.Array.replace(this.eventQueue, (index == null) ? this.queueIndex : index, 1, events);
  1532. },
  1533. /**
  1534. * This method dequeues and injects events until it has arrived at the time index. If
  1535. * no events are ready (based on the time index), this method does nothing.
  1536. * @return {Boolean} True if there is more to do; false if not (at least for now).
  1537. */
  1538. processEvents: function() {
  1539. var me = this,
  1540. animations = me.pauseForAnimations && me.attachTo.Ext.fx.Manager.items,
  1541. eventDescriptor;
  1542. while ((eventDescriptor = me.peekEvent()) !== null) {
  1543. if (animations && animations.getCount()) {
  1544. return true;
  1545. }
  1546. if (eventDescriptor.keyframe) {
  1547. if (!me.processKeyFrame(eventDescriptor)) {
  1548. return false;
  1549. }
  1550. me.nextEvent(eventDescriptor);
  1551. } else if (eventDescriptor.ts <= me.getTimeIndex() && me.fireEvent('beforeplay', me, eventDescriptor) !== false && me.playEvent(eventDescriptor)) {
  1552. me.nextEvent(eventDescriptor);
  1553. } else {
  1554. return true;
  1555. }
  1556. }
  1557. me.stop();
  1558. return false;
  1559. },
  1560. /**
  1561. * This method is called when a keyframe is reached. This will fire the keyframe event.
  1562. * If the keyframe has been handled, true is returned. Otherwise, false is returned.
  1563. * @param {Object} eventDescriptor The event descriptor of the keyframe.
  1564. * @return {Boolean} True if the keyframe was handled, false if not.
  1565. */
  1566. processKeyFrame: function(eventDescriptor) {
  1567. var me = this;
  1568. // only fire keyframe event (and setup the eventDescriptor) once...
  1569. if (!eventDescriptor.defer) {
  1570. me.makeToken(eventDescriptor, 'done');
  1571. me.fireEvent('keyframe', me, eventDescriptor);
  1572. }
  1573. return eventDescriptor.done;
  1574. },
  1575. /**
  1576. * Called to inject the given event on the specified target.
  1577. * @param {HTMLElement} target The target of the event.
  1578. * @param {Object} event The event to inject. The properties of this object should be
  1579. * those of standard DOM events but vary based on the `type` property. For details on
  1580. * event types and their properties, see the class documentation.
  1581. */
  1582. injectEvent: function(target, event) {
  1583. var me = this,
  1584. type = event.type,
  1585. options = Ext.apply({}, event, defaults[type]),
  1586. handler;
  1587. if (type === 'type') {
  1588. handler = me._inputSpecialKeys[target.tagName];
  1589. if (handler) {
  1590. return me.injectTypeInputEvent(target, event, handler);
  1591. }
  1592. return me.injectTypeEvent(target, event);
  1593. }
  1594. if (type === 'focus' && target.focus) {
  1595. target.focus();
  1596. return true;
  1597. }
  1598. if (type === 'blur' && target.blur) {
  1599. target.blur();
  1600. return true;
  1601. }
  1602. if (type === 'scroll') {
  1603. target.scrollLeft = event.pos[0];
  1604. target.scrollTop = event.pos[1];
  1605. return true;
  1606. }
  1607. if (type === 'mduclick') {
  1608. return me.injectEvent(target, Ext.applyIf({
  1609. type: 'mousedown'
  1610. }, event)) && me.injectEvent(target, Ext.applyIf({
  1611. type: 'mouseup'
  1612. }, event)) && me.injectEvent(target, Ext.applyIf({
  1613. type: 'click'
  1614. }, event));
  1615. }
  1616. if (mouseEvents[type]) {
  1617. return Player.injectMouseEvent(target, options, me.attachTo);
  1618. }
  1619. if (keyEvents[type]) {
  1620. return Player.injectKeyEvent(target, options, me.attachTo);
  1621. }
  1622. if (uiEvents[type]) {
  1623. return Player.injectUIEvent(target, type, options.bubbles, options.cancelable, options.view || me.attachTo, options.detail);
  1624. }
  1625. return false;
  1626. },
  1627. injectTypeEvent: function(target, event) {
  1628. var me = this,
  1629. text = event.text,
  1630. xlat = [],
  1631. ch, chUp, i, n, sel, upper, isInput;
  1632. if (text) {
  1633. delete event.text;
  1634. upper = text.toUpperCase();
  1635. for (i = 0 , n = text.length; i < n; ++i) {
  1636. ch = text.charCodeAt(i);
  1637. chUp = upper.charCodeAt(i);
  1638. xlat.push(Ext.applyIf({
  1639. type: 'keydown',
  1640. charCode: chUp,
  1641. keyCode: chUp
  1642. }, event), Ext.applyIf({
  1643. type: 'keypress',
  1644. charCode: ch,
  1645. keyCode: ch
  1646. }, event), Ext.applyIf({
  1647. type: 'keyup',
  1648. charCode: chUp,
  1649. keyCode: chUp
  1650. }, event));
  1651. }
  1652. } else {
  1653. xlat.push(Ext.applyIf({
  1654. type: 'keydown',
  1655. charCode: event.keyCode
  1656. }, event), Ext.applyIf({
  1657. type: 'keyup',
  1658. charCode: event.keyCode
  1659. }, event));
  1660. }
  1661. for (i = 0 , n = xlat.length; i < n; ++i) {
  1662. me.injectEvent(target, xlat[i]);
  1663. }
  1664. return true;
  1665. },
  1666. injectTypeInputEvent: function(target, event, handler) {
  1667. var me = this,
  1668. text = event.text,
  1669. sel, n;
  1670. if (handler) {
  1671. sel = me.getTextSelection(target);
  1672. if (text) {
  1673. n = sel[0];
  1674. target.value = target.value.substring(0, n) + text + target.value.substring(sel[1]);
  1675. n += text.length;
  1676. me.setTextSelection(target, n, n);
  1677. } else {
  1678. if (!(handler = handler[event.keyCode])) {
  1679. // no handler for the special key for this element
  1680. if ('caret' in event) {
  1681. me.setTextSelection(target, event.caret, event.caret);
  1682. } else if (event.selection) {
  1683. me.setTextSelection(target, event.selection[0], event.selection[1]);
  1684. }
  1685. return me.injectTypeEvent(target, event);
  1686. }
  1687. handler.call(this, target, sel[0], sel[1]);
  1688. return true;
  1689. }
  1690. }
  1691. return true;
  1692. },
  1693. playEvent: function(eventDescriptor) {
  1694. var me = this,
  1695. target = me.getElementFromXPath(eventDescriptor.target),
  1696. event;
  1697. if (!target) {
  1698. // not present (yet)... wait for element present...
  1699. // TODO - need a timeout here
  1700. return false;
  1701. }
  1702. if (!me.playEventHook(eventDescriptor, 'beforeplay')) {
  1703. return false;
  1704. }
  1705. if (!eventDescriptor.injected) {
  1706. eventDescriptor.injected = true;
  1707. event = me.translateEvent(eventDescriptor, target);
  1708. me.injectEvent(target, event);
  1709. }
  1710. return me.playEventHook(eventDescriptor, 'afterplay');
  1711. },
  1712. playEventHook: function(eventDescriptor, hookName) {
  1713. var me = this,
  1714. doneName = hookName + '.done',
  1715. firedName = hookName + '.fired',
  1716. hook = eventDescriptor[hookName];
  1717. if (hook && !eventDescriptor[doneName]) {
  1718. if (!eventDescriptor[firedName]) {
  1719. eventDescriptor[firedName] = true;
  1720. me.makeToken(eventDescriptor, doneName);
  1721. if (me.eventScope && Ext.isString(hook)) {
  1722. hook = me.eventScope[hook];
  1723. }
  1724. if (hook) {
  1725. hook.call(me.eventScope || me, eventDescriptor);
  1726. }
  1727. }
  1728. return false;
  1729. }
  1730. return true;
  1731. },
  1732. schedule: function() {
  1733. var me = this;
  1734. if (!me.timer) {
  1735. me.timer = Ext.defer(me.timerFn, 10);
  1736. }
  1737. },
  1738. _translateAcross: [
  1739. 'type',
  1740. 'button',
  1741. 'charCode',
  1742. 'keyCode',
  1743. 'caret',
  1744. 'pos',
  1745. 'text',
  1746. 'selection'
  1747. ],
  1748. translateEvent: function(eventDescriptor, target) {
  1749. var me = this,
  1750. event = {},
  1751. modKeys = eventDescriptor.modKeys || '',
  1752. names = me._translateAcross,
  1753. i = names.length,
  1754. name, xy;
  1755. while (i--) {
  1756. name = names[i];
  1757. if (name in eventDescriptor) {
  1758. event[name] = eventDescriptor[name];
  1759. }
  1760. }
  1761. event.altKey = modKeys.indexOf('A') > 0;
  1762. event.ctrlKey = modKeys.indexOf('C') > 0;
  1763. event.metaKey = modKeys.indexOf('M') > 0;
  1764. event.shiftKey = modKeys.indexOf('S') > 0;
  1765. if (target && 'x' in eventDescriptor) {
  1766. xy = Ext.fly(target).getXY();
  1767. xy[0] += eventDescriptor.x;
  1768. xy[1] += eventDescriptor.y;
  1769. } else if ('x' in eventDescriptor) {
  1770. xy = [
  1771. eventDescriptor.x,
  1772. eventDescriptor.y
  1773. ];
  1774. } else if ('px' in eventDescriptor) {
  1775. xy = [
  1776. eventDescriptor.px,
  1777. eventDescriptor.py
  1778. ];
  1779. }
  1780. if (xy) {
  1781. event.clientX = event.screenX = xy[0];
  1782. event.clientY = event.screenY = xy[1];
  1783. }
  1784. if (eventDescriptor.key) {
  1785. event.keyCode = me.specialKeysByName[eventDescriptor.key];
  1786. }
  1787. if (eventDescriptor.type === 'wheel') {
  1788. if ('onwheel' in me.attachTo.document) {
  1789. event.wheelX = eventDescriptor.dx;
  1790. event.wheelY = eventDescriptor.dy;
  1791. } else {
  1792. event.type = 'mousewheel';
  1793. event.wheelDeltaX = -40 * eventDescriptor.dx;
  1794. event.wheelDeltaY = event.wheelDelta = -40 * eventDescriptor.dy;
  1795. }
  1796. }
  1797. return event;
  1798. },
  1799. //---------------------------------
  1800. // Driver overrides
  1801. onStart: function() {
  1802. var me = this;
  1803. me.queueIndex = 0;
  1804. me.schedule();
  1805. },
  1806. onStop: function() {
  1807. var me = this;
  1808. if (me.timer) {
  1809. Ext.undefer(me.timer);
  1810. me.timer = null;
  1811. }
  1812. },
  1813. //---------------------------------
  1814. onTick: function() {
  1815. var me = this;
  1816. me.timer = null;
  1817. if (me.processEvents()) {
  1818. me.schedule();
  1819. }
  1820. },
  1821. statics: {
  1822. ieButtonCodeMap: {
  1823. 0: 1,
  1824. 1: 4,
  1825. 2: 2
  1826. },
  1827. /**
  1828. * Injects a key event using the given event information to populate the event
  1829. * object.
  1830. *
  1831. * **Note:** `keydown` causes Safari 2.x to crash.
  1832. *
  1833. * @param {HTMLElement} target The target of the given event.
  1834. * @param {Object} options Object object containing all of the event injection
  1835. * options.
  1836. * @param {String} options.type The type of event to fire. This can be any one of
  1837. * the following: `keyup`, `keydown` and `keypress`.
  1838. * @param {Boolean} [options.bubbles=true] `tru` if the event can be bubbled up.
  1839. * DOM Level 3 specifies that all key events bubble by default.
  1840. * @param {Boolean} [options.cancelable=true] `true` if the event can be canceled
  1841. * using `preventDefault`. DOM Level 3 specifies that all key events can be
  1842. * cancelled.
  1843. * @param {Boolean} [options.ctrlKey=false] `true` if one of the CTRL keys is
  1844. * pressed while the event is firing.
  1845. * @param {Boolean} [options.altKey=false] `true` if one of the ALT keys is
  1846. * pressed while the event is firing.
  1847. * @param {Boolean} [options.shiftKey=false] `true` if one of the SHIFT keys is
  1848. * pressed while the event is firing.
  1849. * @param {Boolean} [options.metaKey=false] `true` if one of the META keys is
  1850. * pressed while the event is firing.
  1851. * @param {Number} [options.keyCode=0] The code for the key that is in use.
  1852. * @param {Number} [options.charCode=0] The Unicode code for the character
  1853. * associated with the key being used.
  1854. * @param {Window} [view=window] The view containing the target. This is typically
  1855. * the window object.
  1856. * @private
  1857. */
  1858. injectKeyEvent: function(target, options, view) {
  1859. var type = options.type,
  1860. customEvent = null;
  1861. if (type === 'textevent') {
  1862. type = 'keypress';
  1863. }
  1864. view = view || window;
  1865. //check for DOM-compliant browsers first
  1866. if (doc.createEvent) {
  1867. try {
  1868. customEvent = doc.createEvent("KeyEvents");
  1869. // Interesting problem: Firefox implemented a non-standard
  1870. // version of initKeyEvent() based on DOM Level 2 specs.
  1871. // Key event was removed from DOM Level 2 and re-introduced
  1872. // in DOM Level 3 with a different interface. Firefox is the
  1873. // only browser with any implementation of Key Events, so for
  1874. // now, assume it's Firefox if the above line doesn't error.
  1875. // @TODO: Decipher between Firefox's implementation and a correct one.
  1876. customEvent.initKeyEvent(type, options.bubbles, options.cancelable, view, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.keyCode, options.charCode);
  1877. } catch (ex) {
  1878. // If it got here, that means key events aren't officially supported.
  1879. // Safari/WebKit is a real problem now. WebKit 522 won't let you
  1880. // set keyCode, charCode, or other properties if you use a
  1881. // UIEvent, so we first must try to create a generic event. The
  1882. // fun part is that this will throw an error on Safari 2.x. The
  1883. // end result is that we need another try...catch statement just to
  1884. // deal with this mess.
  1885. try {
  1886. //try to create generic event - will fail in Safari 2.x
  1887. customEvent = doc.createEvent("Events");
  1888. } catch (uierror) {
  1889. //the above failed, so create a UIEvent for Safari 2.x
  1890. customEvent = doc.createEvent("UIEvents");
  1891. } finally {
  1892. customEvent.initEvent(type, options.bubbles, options.cancelable);
  1893. customEvent.view = view;
  1894. customEvent.altKey = options.altKey;
  1895. customEvent.ctrlKey = options.ctrlKey;
  1896. customEvent.shiftKey = options.shiftKey;
  1897. customEvent.metaKey = options.metaKey;
  1898. customEvent.keyCode = options.keyCode;
  1899. customEvent.charCode = options.charCode;
  1900. }
  1901. }
  1902. target.dispatchEvent(customEvent);
  1903. } else if (doc.createEventObject) {
  1904. //IE
  1905. customEvent = doc.createEventObject();
  1906. customEvent.bubbles = options.bubbles;
  1907. customEvent.cancelable = options.cancelable;
  1908. customEvent.view = view;
  1909. customEvent.ctrlKey = options.ctrlKey;
  1910. customEvent.altKey = options.altKey;
  1911. customEvent.shiftKey = options.shiftKey;
  1912. customEvent.metaKey = options.metaKey;
  1913. // IE doesn't support charCode explicitly. CharCode should
  1914. // take precedence over any keyCode value for accurate
  1915. // representation.
  1916. customEvent.keyCode = (options.charCode > 0) ? options.charCode : options.keyCode;
  1917. target.fireEvent("on" + type, customEvent);
  1918. } else {
  1919. return false;
  1920. }
  1921. return true;
  1922. },
  1923. /**
  1924. * Injects a mouse event using the given event information to populate the event
  1925. * object.
  1926. *
  1927. * @param {HTMLElement} target The target of the given event.
  1928. * @param {Object} options Object object containing all of the event injection
  1929. * options.
  1930. * @param {String} options.type The type of event to fire. This can be any one of
  1931. * the following: `click`, `dblclick`, `mousedown`, `mouseup`, `mouseout`,
  1932. * `mouseover` and `mousemove`.
  1933. * @param {Boolean} [options.bubbles=true] `tru` if the event can be bubbled up.
  1934. * DOM Level 2 specifies that all mouse events bubble by default.
  1935. * @param {Boolean} [options.cancelable=true] `true` if the event can be canceled
  1936. * using `preventDefault`. DOM Level 2 specifies that all mouse events except
  1937. * `mousemove` can be cancelled. This defaults to `false` for `mousemove`.
  1938. * @param {Boolean} [options.ctrlKey=false] `true` if one of the CTRL keys is
  1939. * pressed while the event is firing.
  1940. * @param {Boolean} [options.altKey=false] `true` if one of the ALT keys is
  1941. * pressed while the event is firing.
  1942. * @param {Boolean} [options.shiftKey=false] `true` if one of the SHIFT keys is
  1943. * pressed while the event is firing.
  1944. * @param {Boolean} [options.metaKey=false] `true` if one of the META keys is
  1945. * pressed while the event is firing.
  1946. * @param {Number} [options.detail=1] The number of times the mouse button has
  1947. * been used.
  1948. * @param {Number} [options.screenX=0] The x-coordinate on the screen at which point
  1949. * the event occurred.
  1950. * @param {Number} [options.screenY=0] The y-coordinate on the screen at which point
  1951. * the event occurred.
  1952. * @param {Number} [options.clientX=0] The x-coordinate on the client at which point
  1953. * the event occurred.
  1954. * @param {Number} [options.clientY=0] The y-coordinate on the client at which point
  1955. * the event occurred.
  1956. * @param {Number} [options.button=0] The button being pressed while the event is
  1957. * executing. The value should be 0 for the primary mouse button (typically the
  1958. * left button), 1 for the tertiary mouse button (typically the middle button),
  1959. * and 2 for the secondary mouse button (typically the right button).
  1960. * @param {HTMLElement} [options.relatedTarget=null] For `mouseout` events, this
  1961. * is the element that the mouse has moved to. For `mouseover` events, this is
  1962. * the element that the mouse has moved from. This argument is ignored for all
  1963. * other events.
  1964. * @param {Window} [view=window] The view containing the target. This is typically
  1965. * the window object.
  1966. * @private
  1967. */
  1968. injectMouseEvent: function(target, options, view) {
  1969. var type = options.type,
  1970. customEvent = null;
  1971. view = view || window;
  1972. //check for DOM-compliant browsers first
  1973. if (doc.createEvent) {
  1974. customEvent = doc.createEvent("MouseEvents");
  1975. //Safari 2.x (WebKit 418) still doesn't implement initMouseEvent()
  1976. if (customEvent.initMouseEvent) {
  1977. customEvent.initMouseEvent(type, options.bubbles, options.cancelable, view, options.detail, options.screenX, options.screenY, options.clientX, options.clientY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, options.relatedTarget);
  1978. } else {
  1979. //Safari
  1980. //the closest thing available in Safari 2.x is UIEvents
  1981. customEvent = doc.createEvent("UIEvents");
  1982. customEvent.initEvent(type, options.bubbles, options.cancelable);
  1983. customEvent.view = view;
  1984. customEvent.detail = options.detail;
  1985. customEvent.screenX = options.screenX;
  1986. customEvent.screenY = options.screenY;
  1987. customEvent.clientX = options.clientX;
  1988. customEvent.clientY = options.clientY;
  1989. customEvent.ctrlKey = options.ctrlKey;
  1990. customEvent.altKey = options.altKey;
  1991. customEvent.metaKey = options.metaKey;
  1992. customEvent.shiftKey = options.shiftKey;
  1993. customEvent.button = options.button;
  1994. customEvent.relatedTarget = options.relatedTarget;
  1995. }
  1996. /*
  1997. * Check to see if relatedTarget has been assigned. Firefox
  1998. * versions less than 2.0 don't allow it to be assigned via
  1999. * initMouseEvent() and the property is readonly after event
  2000. * creation, so in order to keep YAHOO.util.getRelatedTarget()
  2001. * working, assign to the IE proprietary toElement property
  2002. * for mouseout event and fromElement property for mouseover
  2003. * event.
  2004. */
  2005. if (options.relatedTarget && !customEvent.relatedTarget) {
  2006. if (type == "mouseout") {
  2007. customEvent.toElement = options.relatedTarget;
  2008. } else if (type == "mouseover") {
  2009. customEvent.fromElement = options.relatedTarget;
  2010. }
  2011. }
  2012. target.dispatchEvent(customEvent);
  2013. } else if (doc.createEventObject) {
  2014. //IE
  2015. customEvent = doc.createEventObject();
  2016. customEvent.bubbles = options.bubbles;
  2017. customEvent.cancelable = options.cancelable;
  2018. customEvent.view = view;
  2019. customEvent.detail = options.detail;
  2020. customEvent.screenX = options.screenX;
  2021. customEvent.screenY = options.screenY;
  2022. customEvent.clientX = options.clientX;
  2023. customEvent.clientY = options.clientY;
  2024. customEvent.ctrlKey = options.ctrlKey;
  2025. customEvent.altKey = options.altKey;
  2026. customEvent.metaKey = options.metaKey;
  2027. customEvent.shiftKey = options.shiftKey;
  2028. customEvent.button = Player.ieButtonCodeMap[options.button] || 0;
  2029. /*
  2030. * Have to use relatedTarget because IE won't allow assignment
  2031. * to toElement or fromElement on generic events. This keeps
  2032. * YAHOO.util.customEvent.getRelatedTarget() functional.
  2033. */
  2034. customEvent.relatedTarget = options.relatedTarget;
  2035. target.fireEvent('on' + type, customEvent);
  2036. } else {
  2037. return false;
  2038. }
  2039. return true;
  2040. },
  2041. /**
  2042. * Injects a UI event using the given event information to populate the event
  2043. * object.
  2044. *
  2045. * @param {HTMLElement} target The target of the given event.
  2046. * @param {Object} options
  2047. * @param {String} options.type The type of event to fire. This can be any one of
  2048. * the following: `click`, `dblclick`, `mousedown`, `mouseup`, `mouseout`,
  2049. * `mouseover` and `mousemove`.
  2050. * @param {Boolean} [options.bubbles=true] `tru` if the event can be bubbled up.
  2051. * DOM Level 2 specifies that all mouse events bubble by default.
  2052. * @param {Boolean} [options.cancelable=true] `true` if the event can be canceled
  2053. * using `preventDefault`. DOM Level 2 specifies that all mouse events except
  2054. * `mousemove` can be canceled. This defaults to `false` for `mousemove`.
  2055. * @param {Number} [options.detail=1] The number of times the mouse button has been
  2056. * used.
  2057. * @param {Window} [view=window] The view containing the target. This is typically
  2058. * the window object.
  2059. * @private
  2060. */
  2061. injectUIEvent: function(target, options, view) {
  2062. var customEvent = null;
  2063. view = view || window;
  2064. //check for DOM-compliant browsers first
  2065. if (doc.createEvent) {
  2066. //just a generic UI Event object is needed
  2067. customEvent = doc.createEvent("UIEvents");
  2068. customEvent.initUIEvent(options.type, options.bubbles, options.cancelable, view, options.detail);
  2069. target.dispatchEvent(customEvent);
  2070. } else if (doc.createEventObject) {
  2071. //IE
  2072. customEvent = doc.createEventObject();
  2073. customEvent.bubbles = options.bubbles;
  2074. customEvent.cancelable = options.cancelable;
  2075. customEvent.view = view;
  2076. customEvent.detail = options.detail;
  2077. target.fireEvent("on" + options.type, customEvent);
  2078. } else {
  2079. return false;
  2080. }
  2081. return true;
  2082. }
  2083. }
  2084. };
  2085. });
  2086. // statics
  2087. /**
  2088. * @extends Ext.ux.event.Driver
  2089. * Event recorder.
  2090. */
  2091. Ext.define('Ext.ux.event.Recorder', function(Recorder) {
  2092. function apply() {
  2093. var a = arguments,
  2094. n = a.length,
  2095. obj = {
  2096. kind: 'other'
  2097. },
  2098. i;
  2099. for (i = 0; i < n; ++i) {
  2100. Ext.apply(obj, arguments[i]);
  2101. }
  2102. if (obj.alt && !obj.event) {
  2103. obj.event = obj.alt;
  2104. }
  2105. return obj;
  2106. }
  2107. function key(extra) {
  2108. return apply({
  2109. kind: 'keyboard',
  2110. modKeys: true,
  2111. key: true
  2112. }, extra);
  2113. }
  2114. function mouse(extra) {
  2115. return apply({
  2116. kind: 'mouse',
  2117. button: true,
  2118. modKeys: true,
  2119. xy: true
  2120. }, extra);
  2121. }
  2122. var eventsToRecord = {
  2123. keydown: key(),
  2124. keypress: key(),
  2125. keyup: key(),
  2126. dragmove: mouse({
  2127. alt: 'mousemove',
  2128. pageCoords: true,
  2129. whileDrag: true
  2130. }),
  2131. mousemove: mouse({
  2132. pageCoords: true
  2133. }),
  2134. mouseover: mouse(),
  2135. mouseout: mouse(),
  2136. click: mouse(),
  2137. wheel: mouse({
  2138. wheel: true
  2139. }),
  2140. mousedown: mouse({
  2141. press: true
  2142. }),
  2143. mouseup: mouse({
  2144. release: true
  2145. }),
  2146. scroll: apply({
  2147. listen: false
  2148. }),
  2149. focus: apply(),
  2150. blur: apply()
  2151. };
  2152. for (var key in eventsToRecord) {
  2153. if (!eventsToRecord[key].event) {
  2154. eventsToRecord[key].event = key;
  2155. }
  2156. }
  2157. eventsToRecord.wheel.event = null;
  2158. // must detect later
  2159. return {
  2160. extend: 'Ext.ux.event.Driver',
  2161. /**
  2162. * @event add
  2163. * Fires when an event is added to the recording.
  2164. * @param {Ext.ux.event.Recorder} this
  2165. * @param {Object} eventDescriptor The event descriptor.
  2166. */
  2167. /**
  2168. * @event coalesce
  2169. * Fires when an event is coalesced. This edits the tail of the recorded
  2170. * event list.
  2171. * @param {Ext.ux.event.Recorder} this
  2172. * @param {Object} eventDescriptor The event descriptor that was coalesced.
  2173. */
  2174. eventsToRecord: eventsToRecord,
  2175. ignoreIdRegEx: /ext-gen(?:\d+)/,
  2176. inputRe: /^(input|textarea)$/i,
  2177. constructor: function(config) {
  2178. var me = this,
  2179. events = config && config.eventsToRecord;
  2180. if (events) {
  2181. me.eventsToRecord = Ext.apply(Ext.apply({}, me.eventsToRecord), // duplicate
  2182. events);
  2183. // and merge
  2184. delete config.eventsToRecord;
  2185. }
  2186. // don't smash
  2187. me.callParent(arguments);
  2188. me.clear();
  2189. me.modKeys = [];
  2190. me.attachTo = me.attachTo || window;
  2191. },
  2192. clear: function() {
  2193. this.eventsRecorded = [];
  2194. },
  2195. listenToEvent: function(event) {
  2196. var me = this,
  2197. el = me.attachTo.document.body,
  2198. fn = function() {
  2199. return me.onEvent.apply(me, arguments);
  2200. },
  2201. cleaner = {};
  2202. if (el.attachEvent && el.ownerDocument.documentMode < 10) {
  2203. event = 'on' + event;
  2204. el.attachEvent(event, fn);
  2205. cleaner.destroy = function() {
  2206. if (fn) {
  2207. el.detachEvent(event, fn);
  2208. fn = null;
  2209. }
  2210. };
  2211. } else {
  2212. el.addEventListener(event, fn, true);
  2213. cleaner.destroy = function() {
  2214. if (fn) {
  2215. el.removeEventListener(event, fn, true);
  2216. fn = null;
  2217. }
  2218. };
  2219. }
  2220. return cleaner;
  2221. },
  2222. coalesce: function(rec, ev) {
  2223. var me = this,
  2224. events = me.eventsRecorded,
  2225. length = events.length,
  2226. tail = length && events[length - 1],
  2227. tail2 = (length > 1) && events[length - 2],
  2228. tail3 = (length > 2) && events[length - 3];
  2229. if (!tail) {
  2230. return false;
  2231. }
  2232. if (rec.type === 'mousemove') {
  2233. if (tail.type === 'mousemove' && rec.ts - tail.ts < 200) {
  2234. rec.ts = tail.ts;
  2235. events[length - 1] = rec;
  2236. return true;
  2237. }
  2238. } else if (rec.type === 'click') {
  2239. if (tail2 && tail.type === 'mouseup' && tail2.type === 'mousedown') {
  2240. if (rec.button == tail.button && rec.button == tail2.button && rec.target == tail.target && rec.target == tail2.target && me.samePt(rec, tail) && me.samePt(rec, tail2)) {
  2241. events.pop();
  2242. // remove mouseup
  2243. tail2.type = 'mduclick';
  2244. return true;
  2245. }
  2246. }
  2247. } else if (rec.type === 'keyup') {
  2248. // tail3 = { type: "type", text: "..." },
  2249. // tail2 = { type: "keydown", charCode: 65, keyCode: 65 },
  2250. // tail = { type: "keypress", charCode: 97, keyCode: 97 },
  2251. // rec = { type: "keyup", charCode: 65, keyCode: 65 },
  2252. if (tail2 && tail.type === 'keypress' && tail2.type === 'keydown') {
  2253. if (rec.target === tail.target && rec.target === tail2.target) {
  2254. events.pop();
  2255. // remove keypress
  2256. tail2.type = 'type';
  2257. tail2.text = String.fromCharCode(tail.charCode);
  2258. delete tail2.charCode;
  2259. delete tail2.keyCode;
  2260. if (tail3 && tail3.type === 'type') {
  2261. if (tail3.text && tail3.target === tail2.target) {
  2262. tail3.text += tail2.text;
  2263. events.pop();
  2264. }
  2265. }
  2266. return true;
  2267. }
  2268. }
  2269. // tail = { type: "keydown", charCode: 40, keyCode: 40 },
  2270. // rec = { type: "keyup", charCode: 40, keyCode: 40 },
  2271. else if (me.completeKeyStroke(tail, rec)) {
  2272. tail.type = 'type';
  2273. me.completeSpecialKeyStroke(ev.target, tail, rec);
  2274. return true;
  2275. }
  2276. // tail2 = { type: "keydown", charCode: 40, keyCode: 40 },
  2277. // tail = { type: "scroll", ... },
  2278. // rec = { type: "keyup", charCode: 40, keyCode: 40 },
  2279. else if (tail.type === 'scroll' && me.completeKeyStroke(tail2, rec)) {
  2280. tail2.type = 'type';
  2281. me.completeSpecialKeyStroke(ev.target, tail2, rec);
  2282. // swap the order of type and scroll events
  2283. events.pop();
  2284. events.pop();
  2285. events.push(tail, tail2);
  2286. return true;
  2287. }
  2288. }
  2289. return false;
  2290. },
  2291. completeKeyStroke: function(down, up) {
  2292. if (down && down.type === 'keydown' && down.keyCode === up.keyCode) {
  2293. delete down.charCode;
  2294. return true;
  2295. }
  2296. return false;
  2297. },
  2298. completeSpecialKeyStroke: function(target, down, up) {
  2299. var key = this.specialKeysByCode[up.keyCode];
  2300. if (key && this.inputRe.test(target.tagName)) {
  2301. // home,end,arrow keys + shift get crazy, so encode selection/caret
  2302. delete down.keyCode;
  2303. down.key = key;
  2304. down.selection = this.getTextSelection(target);
  2305. if (down.selection[0] === down.selection[1]) {
  2306. down.caret = down.selection[0];
  2307. delete down.selection;
  2308. }
  2309. return true;
  2310. }
  2311. return false;
  2312. },
  2313. getElementXPath: function(el) {
  2314. var me = this,
  2315. good = false,
  2316. xpath = [],
  2317. count, sibling, t, tag;
  2318. for (t = el; t; t = t.parentNode) {
  2319. if (t == me.attachTo.document.body) {
  2320. xpath.unshift('~');
  2321. good = true;
  2322. break;
  2323. }
  2324. if (t.id && !me.ignoreIdRegEx.test(t.id)) {
  2325. xpath.unshift('#' + t.id);
  2326. good = true;
  2327. break;
  2328. }
  2329. for (count = 1 , sibling = t; !!(sibling = sibling.previousSibling); ) {
  2330. if (sibling.tagName == t.tagName) {
  2331. ++count;
  2332. }
  2333. }
  2334. tag = t.tagName.toLowerCase();
  2335. if (count < 2) {
  2336. xpath.unshift(tag);
  2337. } else {
  2338. xpath.unshift(tag + '[' + count + ']');
  2339. }
  2340. }
  2341. return good ? xpath.join('/') : null;
  2342. },
  2343. getRecordedEvents: function() {
  2344. return this.eventsRecorded;
  2345. },
  2346. onEvent: function(ev) {
  2347. var me = this,
  2348. e = new Ext.event.Event(ev),
  2349. info = me.eventsToRecord[e.type],
  2350. root, modKeys, elXY,
  2351. rec = {
  2352. type: e.type,
  2353. ts: me.getTimestamp(),
  2354. target: me.getElementXPath(e.target)
  2355. },
  2356. xy;
  2357. if (!info || !rec.target) {
  2358. return;
  2359. }
  2360. root = e.target.ownerDocument;
  2361. root = root.defaultView || root.parentWindow;
  2362. // Standards || IE
  2363. if (root !== me.attachTo) {
  2364. return;
  2365. }
  2366. if (me.eventsToRecord.scroll) {
  2367. me.syncScroll(e.target);
  2368. }
  2369. if (info.xy) {
  2370. xy = e.getXY();
  2371. if (info.pageCoords || !rec.target) {
  2372. rec.px = xy[0];
  2373. rec.py = xy[1];
  2374. } else {
  2375. elXY = Ext.fly(e.getTarget()).getXY();
  2376. xy[0] -= elXY[0];
  2377. xy[1] -= elXY[1];
  2378. rec.x = xy[0];
  2379. rec.y = xy[1];
  2380. }
  2381. }
  2382. if (info.button) {
  2383. if ('buttons' in ev) {
  2384. rec.button = ev.buttons;
  2385. } else // LEFT=1, RIGHT=2, MIDDLE=4, etc.
  2386. {
  2387. rec.button = ev.button;
  2388. }
  2389. if (!rec.button && info.whileDrag) {
  2390. return;
  2391. }
  2392. }
  2393. if (info.wheel) {
  2394. rec.type = 'wheel';
  2395. if (info.event === 'wheel') {
  2396. // Current FireFox (technically IE9+ if we use addEventListener but
  2397. // checking document.onwheel does not detect this)
  2398. rec.dx = ev.deltaX;
  2399. rec.dy = ev.deltaY;
  2400. } else if (typeof ev.wheelDeltaX === 'number') {
  2401. // new WebKit has both X & Y
  2402. rec.dx = -1 / 40 * ev.wheelDeltaX;
  2403. rec.dy = -1 / 40 * ev.wheelDeltaY;
  2404. } else if (ev.wheelDelta) {
  2405. // old WebKit and IE
  2406. rec.dy = -1 / 40 * ev.wheelDelta;
  2407. } else if (ev.detail) {
  2408. // Old Gecko
  2409. rec.dy = ev.detail;
  2410. }
  2411. }
  2412. if (info.modKeys) {
  2413. me.modKeys[0] = e.altKey ? 'A' : '';
  2414. me.modKeys[1] = e.ctrlKey ? 'C' : '';
  2415. me.modKeys[2] = e.metaKey ? 'M' : '';
  2416. me.modKeys[3] = e.shiftKey ? 'S' : '';
  2417. modKeys = me.modKeys.join('');
  2418. if (modKeys) {
  2419. rec.modKeys = modKeys;
  2420. }
  2421. }
  2422. if (info.key) {
  2423. rec.charCode = e.getCharCode();
  2424. rec.keyCode = e.getKey();
  2425. }
  2426. if (me.coalesce(rec, e)) {
  2427. me.fireEvent('coalesce', me, rec);
  2428. } else {
  2429. me.eventsRecorded.push(rec);
  2430. me.fireEvent('add', me, rec);
  2431. }
  2432. },
  2433. onStart: function() {
  2434. var me = this,
  2435. ddm = me.attachTo.Ext.dd.DragDropManager,
  2436. evproto = me.attachTo.Ext.EventObjectImpl.prototype,
  2437. special = [];
  2438. // FireFox does not support the 'mousewheel' event but does support the
  2439. // 'wheel' event instead.
  2440. Recorder.prototype.eventsToRecord.wheel.event = ('onwheel' in me.attachTo.document) ? 'wheel' : 'mousewheel';
  2441. me.listeners = [];
  2442. Ext.Object.each(me.eventsToRecord, function(name, value) {
  2443. if (value && value.listen !== false) {
  2444. if (!value.event) {
  2445. value.event = name;
  2446. }
  2447. if (value.alt && value.alt !== name) {
  2448. // The 'drag' event is just mousemove while buttons are pressed,
  2449. // so if there is a mousemove entry as well, ignore the drag
  2450. if (!me.eventsToRecord[value.alt]) {
  2451. special.push(value);
  2452. }
  2453. } else {
  2454. me.listeners.push(me.listenToEvent(value.event));
  2455. }
  2456. }
  2457. });
  2458. Ext.each(special, function(info) {
  2459. me.eventsToRecord[info.alt] = info;
  2460. me.listeners.push(me.listenToEvent(info.alt));
  2461. });
  2462. me.ddmStopEvent = ddm.stopEvent;
  2463. ddm.stopEvent = Ext.Function.createSequence(ddm.stopEvent, function(e) {
  2464. me.onEvent(e);
  2465. });
  2466. me.evStopEvent = evproto.stopEvent;
  2467. evproto.stopEvent = Ext.Function.createSequence(evproto.stopEvent, function() {
  2468. me.onEvent(this);
  2469. });
  2470. },
  2471. onStop: function() {
  2472. var me = this;
  2473. Ext.destroy(me.listeners);
  2474. me.listeners = null;
  2475. me.attachTo.Ext.dd.DragDropManager.stopEvent = me.ddmStopEvent;
  2476. me.attachTo.Ext.EventObjectImpl.prototype.stopEvent = me.evStopEvent;
  2477. },
  2478. samePt: function(pt1, pt2) {
  2479. return pt1.x == pt2.x && pt1.y == pt2.y;
  2480. },
  2481. syncScroll: function(el) {
  2482. var me = this,
  2483. ts = me.getTimestamp(),
  2484. oldX, oldY, x, y, scrolled, rec;
  2485. for (var p = el; p; p = p.parentNode) {
  2486. oldX = p.$lastScrollLeft;
  2487. oldY = p.$lastScrollTop;
  2488. x = p.scrollLeft;
  2489. y = p.scrollTop;
  2490. scrolled = false;
  2491. if (oldX !== x) {
  2492. if (x) {
  2493. scrolled = true;
  2494. }
  2495. p.$lastScrollLeft = x;
  2496. }
  2497. if (oldY !== y) {
  2498. if (y) {
  2499. scrolled = true;
  2500. }
  2501. p.$lastScrollTop = y;
  2502. }
  2503. if (scrolled) {
  2504. //console.log('scroll x:' + x + ' y:' + y, p);
  2505. me.eventsRecorded.push(rec = {
  2506. type: 'scroll',
  2507. target: me.getElementXPath(p),
  2508. ts: ts,
  2509. pos: [
  2510. x,
  2511. y
  2512. ]
  2513. });
  2514. me.fireEvent('add', me, rec);
  2515. }
  2516. if (p.tagName === 'BODY') {
  2517. break;
  2518. }
  2519. }
  2520. }
  2521. };
  2522. });
  2523. /**
  2524. * Describes a gauge needle as a shape defined in SVG path syntax.
  2525. *
  2526. * Note: this class and its subclasses are not supposed to be instantiated directly
  2527. * - an object should be passed the gauge's {@link Ext.ux.gauge.Gauge#needle}
  2528. * config instead. Needle instances are also not supposed to be moved
  2529. * between gauges.
  2530. */
  2531. Ext.define('Ext.ux.gauge.needle.Abstract', {
  2532. mixins: [
  2533. 'Ext.mixin.Factoryable'
  2534. ],
  2535. alias: 'gauge.needle.abstract',
  2536. isNeedle: true,
  2537. config: {
  2538. /**
  2539. * The generator function for the needle's shape.
  2540. * Because the gauge component is resizable, and it is generally
  2541. * desirable to resize the needle along with the gauge, the needle's
  2542. * shape should have an ability to grow, typically non-uniformly,
  2543. * which necessitates a generator function that will update the needle's
  2544. * path, so that its proportions are appropriate for the current gauge size.
  2545. *
  2546. * The generator function is given two parameters: the inner and outer
  2547. * radius of the needle. For example, for a straight arrow, the path
  2548. * definition is expected to have the base of the needle at the origin
  2549. * - (0, 0) coordinates - and point downwards. The needle will be automatically
  2550. * translated to the center of the gauge and rotated to represent the current
  2551. * gauge {@link Ext.ux.gauge.Gauge#value value}.
  2552. *
  2553. * @param {Function} path The path generator function.
  2554. * @param {Number} path.innerRadius The function's first parameter.
  2555. * @param {Number} path.outerRadius The function's second parameter.
  2556. * @return {String} path.return The shape of the needle in the SVG path syntax returned by
  2557. * the generator function.
  2558. */
  2559. path: null,
  2560. /**
  2561. * The inner radius of the needle. This works just like the `innerRadius`
  2562. * config of the {@link Ext.ux.gauge.Gauge#trackStyle}.
  2563. * The default value is `25` to make sure the needle doesn't overlap with
  2564. * the value of the gauge shown at its center by default.
  2565. *
  2566. * @param {Number/String} [innerRadius=25]
  2567. */
  2568. innerRadius: 25,
  2569. /**
  2570. * The outer radius of the needle. This works just like the `outerRadius`
  2571. * config of the {@link Ext.ux.gauge.Gauge#trackStyle}.
  2572. *
  2573. * @param {Number/String} [outerRadius='100% - 20']
  2574. */
  2575. outerRadius: '100% - 20',
  2576. /**
  2577. * The shape generated by the {@link #path} function is used as the value
  2578. * for the `d` attribute of the SVG `<path>` element. This element
  2579. * has the default class name of `.x-gauge-needle`, so that CSS can be used
  2580. * to give all gauge needles some common styling. To style a particular needle,
  2581. * one can use this config to add styles to the needle's `<path>` element directly,
  2582. * or use a custom {@link Ext.ux.gauge.Gauge#cls class} for the needle's gauge
  2583. * and style the needle from there.
  2584. *
  2585. * This config is not supposed to be updated manually, the styles should
  2586. * always be updated by the means of the `setStyle` call. For example,
  2587. * this is not allowed:
  2588. *
  2589. * gauge.getStyle().fill = 'red'; // WRONG!
  2590. * gauge.setStyle({ 'fill': 'red' }); // correct
  2591. *
  2592. * Subsequent calls to the `setStyle` will add to the styles set previously
  2593. * or overwrite their values, but won't remove them. If you'd like to style
  2594. * from a clean slate, setting the style to `null` first will remove the styles
  2595. * previously set:
  2596. *
  2597. * gauge.getNeedle().setStyle(null);
  2598. *
  2599. * If an SVG shape was produced by a designer rather than programmatically,
  2600. * in other words, the {@link #path} function returns the same shape regardless
  2601. * of the parameters it was given, the uniform scaling of said shape is the only
  2602. * option, if one wants to use gauges of different sizes. In this case,
  2603. * it's possible to specify the desired scale by using the `transform` style,
  2604. * for example:
  2605. *
  2606. * transform: 'scale(0.35)'
  2607. *
  2608. * @param {Object} style
  2609. */
  2610. style: null,
  2611. /**
  2612. * @private
  2613. * @param {Number} radius
  2614. */
  2615. radius: 0,
  2616. /**
  2617. * @private
  2618. * Expected in the initial config, required during construction.
  2619. * @param {Ext.ux.gauge.Gauge} gauge
  2620. */
  2621. gauge: null
  2622. },
  2623. constructor: function(config) {
  2624. this.initConfig(config);
  2625. },
  2626. applyInnerRadius: function(innerRadius) {
  2627. return this.getGauge().getRadiusFn(innerRadius);
  2628. },
  2629. applyOuterRadius: function(outerRadius) {
  2630. return this.getGauge().getRadiusFn(outerRadius);
  2631. },
  2632. updateRadius: function() {
  2633. this.regeneratePath();
  2634. },
  2635. setTransform: function(centerX, centerY, rotation) {
  2636. var needleGroup = this.getNeedleGroup();
  2637. needleGroup.setStyle('transform', 'translate(' + centerX + 'px,' + centerY + 'px) ' + 'rotate(' + rotation + 'deg)');
  2638. },
  2639. applyPath: function(path) {
  2640. return Ext.isFunction(path) ? path : null;
  2641. },
  2642. updatePath: function(path) {
  2643. this.regeneratePath(path);
  2644. },
  2645. regeneratePath: function(path) {
  2646. path = path || this.getPath();
  2647. var me = this,
  2648. radius = me.getRadius(),
  2649. inner = me.getInnerRadius()(radius),
  2650. outer = me.getOuterRadius()(radius),
  2651. d = outer > inner ? path(inner, outer) : '';
  2652. me.getNeedlePath().dom.setAttribute('d', d);
  2653. },
  2654. getNeedleGroup: function() {
  2655. var gauge = this.getGauge(),
  2656. group = this.needleGroup;
  2657. // The gauge positions the needle by calling its `setTransform` method,
  2658. // which applies a transformation to the needle's group, that contains
  2659. // the actual path element. This is done because we need the ability to
  2660. // transform the path independently from it's position in the gauge.
  2661. // For example, if the needle has to be made bigger, is shouldn't be
  2662. // part of the transform that centers it in the gauge and rotates it
  2663. // to point at the current value.
  2664. if (!group) {
  2665. group = this.needleGroup = Ext.get(document.createElementNS(gauge.svgNS, 'g'));
  2666. gauge.getSvg().appendChild(group);
  2667. }
  2668. return group;
  2669. },
  2670. getNeedlePath: function() {
  2671. var me = this,
  2672. pathElement = me.pathElement;
  2673. if (!pathElement) {
  2674. pathElement = me.pathElement = Ext.get(document.createElementNS(me.getGauge().svgNS, 'path'));
  2675. pathElement.dom.setAttribute('class', Ext.baseCSSPrefix + 'gauge-needle');
  2676. me.getNeedleGroup().appendChild(pathElement);
  2677. }
  2678. return pathElement;
  2679. },
  2680. updateStyle: function(style) {
  2681. var pathElement = this.getNeedlePath();
  2682. // Note that we are setting the `style` attribute, e.g `style="fill: red"`,
  2683. // instead of path attributes individually, e.g. `fill="red"` because
  2684. // the attribute styles defined in CSS classes will override the values
  2685. // of attributes set on the elements individually.
  2686. if (Ext.isObject(style)) {
  2687. pathElement.setStyle(style);
  2688. } else {
  2689. pathElement.dom.removeAttribute('style');
  2690. }
  2691. },
  2692. destroy: function() {
  2693. var me = this;
  2694. me.pathElement = Ext.destroy(me.pathElement);
  2695. me.needleGroup = Ext.destroy(me.needleGroup);
  2696. me.setGauge(null);
  2697. }
  2698. });
  2699. /**
  2700. * Displays a value within the given interval as a gauge. For example:
  2701. *
  2702. * @example
  2703. * Ext.create({
  2704. * xtype: 'panel',
  2705. * renderTo: document.body,
  2706. * width: 200,
  2707. * height: 200,
  2708. * layout: 'fit',
  2709. * items: {
  2710. * xtype: 'gauge',
  2711. * padding: 20,
  2712. * value: 55,
  2713. * minValue: 40,
  2714. * maxValue: 80
  2715. * }
  2716. * });
  2717. *
  2718. * It's also possible to use gauges to create loading indicators:
  2719. *
  2720. * @example
  2721. * Ext.create({
  2722. * xtype: 'panel',
  2723. * renderTo: document.body,
  2724. * width: 200,
  2725. * height: 200,
  2726. * layout: 'fit',
  2727. * items: {
  2728. * xtype: 'gauge',
  2729. * padding: 20,
  2730. * trackStart: 0,
  2731. * trackLength: 360,
  2732. * value: 20,
  2733. * valueStyle: {
  2734. * round: true
  2735. * },
  2736. * textTpl: 'Loading...',
  2737. * animation: {
  2738. * easing: 'linear',
  2739. * duration: 100000
  2740. * }
  2741. * }
  2742. * }).items.first().setAngleOffset(360 * 100);
  2743. *
  2744. * Gauges can contain needles as well.
  2745. *
  2746. * @example
  2747. * Ext.create({
  2748. * xtype: 'panel',
  2749. * renderTo: document.body,
  2750. * width: 200,
  2751. * height: 200,
  2752. * layout: 'fit',
  2753. * items: {
  2754. * xtype: 'gauge',
  2755. * padding: 20,
  2756. * value: 55,
  2757. * minValue: 40,
  2758. * maxValue: 80,
  2759. * needle: 'wedge'
  2760. * }
  2761. * });
  2762. *
  2763. */
  2764. Ext.define('Ext.ux.gauge.Gauge', {
  2765. alternateClassName: 'Ext.ux.Gauge',
  2766. extend: 'Ext.Gadget',
  2767. xtype: 'gauge',
  2768. requires: [
  2769. 'Ext.ux.gauge.needle.Abstract',
  2770. 'Ext.util.Region'
  2771. ],
  2772. config: {
  2773. /**
  2774. * @cfg {Number/String} padding
  2775. * Gauge sector padding in pixels or percent of width/height, whichever is smaller.
  2776. */
  2777. padding: 10,
  2778. /**
  2779. * @cfg {Number} trackStart
  2780. * The angle in the [0, 360) interval at which the gauge's track sector starts.
  2781. * E.g. 0 for 3 o-clock, 90 for 6 o-clock, 180 for 9 o-clock, 270 for noon.
  2782. */
  2783. trackStart: 135,
  2784. /**
  2785. * @cfg {Number} trackLength
  2786. * The angle in the (0, 360] interval to add to the {@link #trackStart} angle
  2787. * to determine the angle at which the track ends.
  2788. */
  2789. trackLength: 270,
  2790. /**
  2791. * @cfg {Number} angleOffset
  2792. * The angle at which the {@link #minValue} starts in case of a circular gauge.
  2793. */
  2794. angleOffset: 0,
  2795. /**
  2796. * @cfg {Number} minValue
  2797. * The minimum value that the gauge can represent.
  2798. */
  2799. minValue: 0,
  2800. /**
  2801. * @cfg {Number} maxValue
  2802. * The maximum value that the gauge can represent.
  2803. */
  2804. maxValue: 100,
  2805. /**
  2806. * @cfg {Number} value
  2807. * The current value of the gauge.
  2808. */
  2809. value: 50,
  2810. /**
  2811. * @cfg {Ext.ux.gauge.needle.Abstract} needle
  2812. * A config object for the needle to be used by the gauge.
  2813. * The needle will track the current {@link #value}.
  2814. * The default needle type is 'diamond', so if a config like
  2815. *
  2816. * needle: {
  2817. * outerRadius: '100%'
  2818. * }
  2819. *
  2820. * is used, the app/view still has to require
  2821. * the `Ext.ux.gauge.needle.Diamond` class.
  2822. * If a type is specified explicitly
  2823. *
  2824. * needle: {
  2825. * type: 'arrow'
  2826. * }
  2827. *
  2828. * it's straightforward which class should be required.
  2829. */
  2830. needle: null,
  2831. needleDefaults: {
  2832. cached: true,
  2833. $value: {
  2834. type: 'diamond'
  2835. }
  2836. },
  2837. /**
  2838. * @cfg {Boolean} [clockwise=true]
  2839. * `true` - {@link #cfg!value} increments in a clockwise fashion
  2840. * `false` - {@link #cfg!value} increments in an anticlockwise fashion
  2841. */
  2842. clockwise: true,
  2843. /**
  2844. * @cfg {Ext.XTemplate} textTpl
  2845. * The template for the text in the center of the gauge.
  2846. * The available data values are:
  2847. * - `value` - The {@link #cfg!value} of the gauge.
  2848. * - `percent` - The value as a percentage between 0 and 100.
  2849. * - `minValue` - The value of the {@link #cfg!minValue} config.
  2850. * - `maxValue` - The value of the {@link #cfg!maxValue} config.
  2851. * - `delta` - The delta between the {@link #cfg!minValue} and {@link #cfg!maxValue}.
  2852. */
  2853. textTpl: [
  2854. '<tpl>{value:number("0.00")}%</tpl>'
  2855. ],
  2856. /**
  2857. * @cfg {String} [textAlign='c-c']
  2858. * If the gauge has a donut hole, the text will be centered inside it.
  2859. * Otherwise, the text will be centered in the middle of the gauge's
  2860. * bounding box. This config allows to alter the position of the text
  2861. * in the latter case. See the docs for the `align` option to the
  2862. * {@link Ext.util.Region#alignTo} method for possible ways of alignment
  2863. * of the text to the guage's bounding box.
  2864. */
  2865. textAlign: 'c-c',
  2866. /**
  2867. * @cfg {Object} textOffset
  2868. * This config can be used to displace the {@link #textTpl text} from its default
  2869. * position in the center of the gauge by providing values for horizontal and
  2870. * vertical displacement.
  2871. * @cfg {Number} textOffset.dx Horizontal displacement.
  2872. * @cfg {Number} textOffset.dy Vertical displacement.
  2873. */
  2874. textOffset: {
  2875. dx: 0,
  2876. dy: 0
  2877. },
  2878. /**
  2879. * @cfg {Object} trackStyle
  2880. * Track sector styles.
  2881. * @cfg {String/Object[]} trackStyle.fill Track sector fill color. Defaults to CSS value.
  2882. * It's also possible to have a linear gradient fill that starts at the top-left corner
  2883. * of the gauge and ends at its bottom-right corner, by providing an array of color stop
  2884. * objects. For example:
  2885. *
  2886. * trackStyle: {
  2887. * fill: [{
  2888. * offset: 0,
  2889. * color: 'green',
  2890. * opacity: 0.8
  2891. * }, {
  2892. * offset: 1,
  2893. * color: 'gold'
  2894. * }]
  2895. * }
  2896. *
  2897. * @cfg {Number} trackStyle.fillOpacity Track sector fill opacity. Defaults to CSS value.
  2898. * @cfg {String} trackStyle.stroke Track sector stroke color. Defaults to CSS value.
  2899. * @cfg {Number} trackStyle.strokeOpacity Track sector stroke opacity. Defaults to CSS value.
  2900. * @cfg {Number} trackStyle.strokeWidth Track sector stroke width. Defaults to CSS value.
  2901. * @cfg {Number/String} [trackStyle.outerRadius='100%'] The outer radius of the track sector.
  2902. * For example:
  2903. *
  2904. * outerRadius: '90%', // 90% of the maximum radius
  2905. * outerRadius: 100, // radius of 100 pixels
  2906. * outerRadius: '70% + 5', // 70% of the maximum radius plus 5 pixels
  2907. * outerRadius: '80% - 10', // 80% of the maximum radius minus 10 pixels
  2908. *
  2909. * @cfg {Number/String} [trackStyle.innerRadius='50%'] The inner radius of the track sector.
  2910. * See the `trackStyle.outerRadius` config documentation for more information.
  2911. * @cfg {Boolean} [trackStyle.round=false] Whether to round the track sector edges or not.
  2912. */
  2913. trackStyle: {
  2914. outerRadius: '100%',
  2915. innerRadius: '100% - 20',
  2916. round: false
  2917. },
  2918. /**
  2919. * @cfg {Object} valueStyle
  2920. * Value sector styles.
  2921. * @cfg {String/Object[]} valueStyle.fill Value sector fill color. Defaults to CSS value.
  2922. * See the `trackStyle.fill` config documentation for more information.
  2923. * @cfg {Number} valueStyle.fillOpacity Value sector fill opacity. Defaults to CSS value.
  2924. * @cfg {String} valueStyle.stroke Value sector stroke color. Defaults to CSS value.
  2925. * @cfg {Number} valueStyle.strokeOpacity Value sector stroke opacity. Defaults to CSS value.
  2926. * @cfg {Number} valueStyle.strokeWidth Value sector stroke width. Defaults to CSS value.
  2927. * @cfg {Number/String} [valueStyle.outerRadius='100% - 4'] The outer radius of the value sector.
  2928. * See the `trackStyle.outerRadius` config documentation for more information.
  2929. * @cfg {Number/String} [valueStyle.innerRadius='50% + 4'] The inner radius of the value sector.
  2930. * See the `trackStyle.outerRadius` config documentation for more information.
  2931. * @cfg {Boolean} [valueStyle.round=false] Whether to round the value sector edges or not.
  2932. */
  2933. valueStyle: {
  2934. outerRadius: '100% - 2',
  2935. innerRadius: '100% - 18',
  2936. round: false
  2937. },
  2938. /**
  2939. * @cfg {Object/Boolean} [animation=true]
  2940. * The animation applied to the gauge on changes to the {@link #value}
  2941. * and the {@link #angleOffset} configs. Defaults to 1 second animation
  2942. * with the 'out' easing.
  2943. * @cfg {Number} animation.duration The duraction of the animation.
  2944. * @cfg {String} animation.easing The easing function to use for the animation.
  2945. * Possible values are:
  2946. * - `linear` - no easing, no acceleration
  2947. * - `in` - accelerating from zero velocity
  2948. * - `out` - (default) decelerating to zero velocity
  2949. * - `inOut` - acceleration until halfway, then deceleration
  2950. */
  2951. animation: true
  2952. },
  2953. baseCls: Ext.baseCSSPrefix + 'gauge',
  2954. template: [
  2955. {
  2956. reference: 'bodyElement',
  2957. children: [
  2958. {
  2959. reference: 'textElement',
  2960. cls: Ext.baseCSSPrefix + 'gauge-text'
  2961. }
  2962. ]
  2963. }
  2964. ],
  2965. defaultBindProperty: 'value',
  2966. pathAttributes: {
  2967. // The properties in the `trackStyle` and `valueStyle` configs
  2968. // that are path attributes.
  2969. fill: true,
  2970. fillOpacity: true,
  2971. stroke: true,
  2972. strokeOpacity: true,
  2973. strokeWidth: true
  2974. },
  2975. easings: {
  2976. linear: Ext.identityFn,
  2977. // cubic easings
  2978. 'in': function(t) {
  2979. return t * t * t;
  2980. },
  2981. out: function(t) {
  2982. return (--t) * t * t + 1;
  2983. },
  2984. inOut: function(t) {
  2985. return t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
  2986. }
  2987. },
  2988. resizeDelay: 0,
  2989. // in milliseconds
  2990. resizeTimerId: 0,
  2991. size: null,
  2992. // cached size
  2993. svgNS: 'http://www.w3.org/2000/svg',
  2994. svg: null,
  2995. // SVG document
  2996. defs: null,
  2997. // the `defs` section of the SVG document
  2998. trackArc: null,
  2999. valueArc: null,
  3000. trackGradient: null,
  3001. valueGradient: null,
  3002. fx: null,
  3003. // either the `value` or the `angleOffset` animation
  3004. fxValue: 0,
  3005. // the actual value rendered/animated
  3006. fxAngleOffset: 0,
  3007. constructor: function(config) {
  3008. var me = this;
  3009. me.fitSectorInRectCache = {
  3010. startAngle: null,
  3011. lengthAngle: null,
  3012. minX: null,
  3013. maxX: null,
  3014. minY: null,
  3015. maxY: null
  3016. };
  3017. me.interpolator = me.createInterpolator();
  3018. me.callParent([
  3019. config
  3020. ]);
  3021. me.el.on('resize', 'onElementResize', me);
  3022. },
  3023. doDestroy: function() {
  3024. var me = this;
  3025. Ext.undefer(me.resizeTimerId);
  3026. me.el.un('resize', 'onElementResize', me);
  3027. me.stopAnimation();
  3028. me.setNeedle(null);
  3029. me.trackGradient = Ext.destroy(me.trackGradient);
  3030. me.valueGradient = Ext.destroy(me.valueGradient);
  3031. me.defs = Ext.destroy(me.defs);
  3032. me.svg = Ext.destroy(me.svg);
  3033. me.callParent();
  3034. },
  3035. onElementResize: function(element, size) {
  3036. this.handleResize(size);
  3037. },
  3038. handleResize: function(size, instantly) {
  3039. var me = this,
  3040. el = me.element;
  3041. if (!(el && (size = size || el.getSize()) && size.width && size.height)) {
  3042. return;
  3043. }
  3044. me.resizeTimerId = Ext.undefer(me.resizeTimerId);
  3045. if (!instantly && me.resizeDelay) {
  3046. me.resizeTimerId = Ext.defer(me.handleResize, me.resizeDelay, me, [
  3047. size,
  3048. true
  3049. ]);
  3050. return;
  3051. }
  3052. me.size = size;
  3053. me.resizeHandler(size);
  3054. },
  3055. updateMinValue: function(minValue) {
  3056. var me = this;
  3057. me.interpolator.setDomain(minValue, me.getMaxValue());
  3058. if (!me.isConfiguring) {
  3059. me.render();
  3060. }
  3061. },
  3062. updateMaxValue: function(maxValue) {
  3063. var me = this;
  3064. me.interpolator.setDomain(me.getMinValue(), maxValue);
  3065. if (!me.isConfiguring) {
  3066. me.render();
  3067. }
  3068. },
  3069. updateAngleOffset: function(angleOffset, oldAngleOffset) {
  3070. var me = this,
  3071. animation = me.getAnimation();
  3072. me.fxAngleOffset = angleOffset;
  3073. if (me.isConfiguring) {
  3074. return;
  3075. }
  3076. if (animation.duration) {
  3077. me.animate(oldAngleOffset, angleOffset, animation.duration, me.easings[animation.easing], function(angleOffset) {
  3078. me.fxAngleOffset = angleOffset;
  3079. me.render();
  3080. });
  3081. } else {
  3082. me.render();
  3083. }
  3084. },
  3085. //<debug>
  3086. applyTrackStart: function(trackStart) {
  3087. if (trackStart < 0 || trackStart >= 360) {
  3088. Ext.raise("'trackStart' should be within [0, 360).");
  3089. }
  3090. return trackStart;
  3091. },
  3092. applyTrackLength: function(trackLength) {
  3093. if (trackLength <= 0 || trackLength > 360) {
  3094. Ext.raise("'trackLength' should be within (0, 360].");
  3095. }
  3096. return trackLength;
  3097. },
  3098. //</debug>
  3099. updateTrackStart: function(trackStart) {
  3100. var me = this;
  3101. if (!me.isConfiguring) {
  3102. me.render();
  3103. }
  3104. },
  3105. updateTrackLength: function(trackLength) {
  3106. var me = this;
  3107. me.interpolator.setRange(0, trackLength);
  3108. if (!me.isConfiguring) {
  3109. me.render();
  3110. }
  3111. },
  3112. applyPadding: function(padding) {
  3113. if (typeof padding === 'string') {
  3114. var ratio = parseFloat(padding) / 100;
  3115. return function(x) {
  3116. return x * ratio;
  3117. };
  3118. }
  3119. return function() {
  3120. return padding;
  3121. };
  3122. },
  3123. updatePadding: function() {
  3124. if (!this.isConfiguring) {
  3125. this.render();
  3126. }
  3127. },
  3128. applyValue: function(value) {
  3129. var minValue = this.getMinValue(),
  3130. maxValue = this.getMaxValue();
  3131. return Math.min(Math.max(value, minValue), maxValue);
  3132. },
  3133. updateValue: function(value, oldValue) {
  3134. var me = this,
  3135. animation = me.getAnimation();
  3136. me.fxValue = value;
  3137. if (me.isConfiguring) {
  3138. return;
  3139. }
  3140. me.writeText();
  3141. if (animation.duration) {
  3142. me.animate(oldValue, value, animation.duration, me.easings[animation.easing], function(value) {
  3143. me.fxValue = value;
  3144. me.render();
  3145. });
  3146. } else {
  3147. me.render();
  3148. }
  3149. },
  3150. applyTextTpl: function(textTpl) {
  3151. if (textTpl && !textTpl.isTemplate) {
  3152. textTpl = new Ext.XTemplate(textTpl);
  3153. }
  3154. return textTpl;
  3155. },
  3156. applyTextOffset: function(offset) {
  3157. offset = offset || {};
  3158. offset.dx = offset.dx || 0;
  3159. offset.dy = offset.dy || 0;
  3160. return offset;
  3161. },
  3162. updateTextTpl: function() {
  3163. this.writeText();
  3164. if (!this.isConfiguring) {
  3165. this.centerText();
  3166. }
  3167. },
  3168. // text will be centered on first size
  3169. writeText: function(options) {
  3170. var me = this,
  3171. value = me.getValue(),
  3172. minValue = me.getMinValue(),
  3173. maxValue = me.getMaxValue(),
  3174. delta = maxValue - minValue,
  3175. textTpl = me.getTextTpl();
  3176. textTpl.overwrite(me.textElement, {
  3177. value: value,
  3178. percent: (value - minValue) / delta * 100,
  3179. minValue: minValue,
  3180. maxValue: maxValue,
  3181. delta: delta
  3182. });
  3183. },
  3184. centerText: function(cx, cy, sectorRegion, innerRadius, outerRadius) {
  3185. var textElement = this.textElement,
  3186. textAlign = this.getTextAlign(),
  3187. alignedRegion, textBox;
  3188. if (Ext.Number.isEqual(innerRadius, 0, 0.1) || sectorRegion.isOutOfBound({
  3189. x: cx,
  3190. y: cy
  3191. })) {
  3192. alignedRegion = textElement.getRegion().alignTo({
  3193. align: textAlign,
  3194. // align text region's center to sector region's center
  3195. target: sectorRegion
  3196. });
  3197. textElement.setLeft(alignedRegion.left);
  3198. textElement.setTop(alignedRegion.top);
  3199. } else {
  3200. textBox = textElement.getBox();
  3201. textElement.setLeft(cx - textBox.width / 2);
  3202. textElement.setTop(cy - textBox.height / 2);
  3203. }
  3204. },
  3205. camelCaseRe: /([a-z])([A-Z])/g,
  3206. /**
  3207. * @private
  3208. */
  3209. camelToHyphen: function(name) {
  3210. return name.replace(this.camelCaseRe, '$1-$2').toLowerCase();
  3211. },
  3212. applyTrackStyle: function(trackStyle) {
  3213. var me = this,
  3214. trackGradient;
  3215. trackStyle.innerRadius = me.getRadiusFn(trackStyle.innerRadius);
  3216. trackStyle.outerRadius = me.getRadiusFn(trackStyle.outerRadius);
  3217. if (Ext.isArray(trackStyle.fill)) {
  3218. trackGradient = me.getTrackGradient();
  3219. me.setGradientStops(trackGradient, trackStyle.fill);
  3220. trackStyle.fill = 'url(#' + trackGradient.dom.getAttribute('id') + ')';
  3221. }
  3222. return trackStyle;
  3223. },
  3224. updateTrackStyle: function(trackStyle) {
  3225. var me = this,
  3226. trackArc = Ext.fly(me.getTrackArc()),
  3227. name;
  3228. for (name in trackStyle) {
  3229. if (name in me.pathAttributes) {
  3230. trackArc.setStyle(me.camelToHyphen(name), trackStyle[name]);
  3231. } else {
  3232. trackArc.setStyle(name, trackStyle[name]);
  3233. }
  3234. }
  3235. },
  3236. applyValueStyle: function(valueStyle) {
  3237. var me = this,
  3238. valueGradient;
  3239. valueStyle.innerRadius = me.getRadiusFn(valueStyle.innerRadius);
  3240. valueStyle.outerRadius = me.getRadiusFn(valueStyle.outerRadius);
  3241. if (Ext.isArray(valueStyle.fill)) {
  3242. valueGradient = me.getValueGradient();
  3243. me.setGradientStops(valueGradient, valueStyle.fill);
  3244. valueStyle.fill = 'url(#' + valueGradient.dom.getAttribute('id') + ')';
  3245. }
  3246. return valueStyle;
  3247. },
  3248. updateValueStyle: function(valueStyle) {
  3249. var me = this,
  3250. valueArc = Ext.fly(me.getValueArc()),
  3251. name;
  3252. for (name in valueStyle) {
  3253. if (name in me.pathAttributes) {
  3254. valueArc.setStyle(me.camelToHyphen(name), valueStyle[name]);
  3255. } else {
  3256. valueArc.setStyle(name, valueStyle[name]);
  3257. }
  3258. }
  3259. },
  3260. /**
  3261. * @private
  3262. */
  3263. getRadiusFn: function(radius) {
  3264. var result, pos, ratio,
  3265. increment = 0;
  3266. if (Ext.isNumber(radius)) {
  3267. result = function() {
  3268. return radius;
  3269. };
  3270. } else if (Ext.isString(radius)) {
  3271. radius = radius.replace(/ /g, '');
  3272. ratio = parseFloat(radius) / 100;
  3273. pos = radius.search('%');
  3274. // E.g. '100% - 4'
  3275. if (pos < radius.length - 1) {
  3276. increment = parseFloat(radius.substr(pos + 1));
  3277. }
  3278. result = function(radius) {
  3279. return radius * ratio + increment;
  3280. };
  3281. result.ratio = ratio;
  3282. }
  3283. return result;
  3284. },
  3285. getSvg: function() {
  3286. var me = this,
  3287. svg = me.svg;
  3288. if (!svg) {
  3289. svg = me.svg = Ext.get(document.createElementNS(me.svgNS, 'svg'));
  3290. me.bodyElement.append(svg);
  3291. }
  3292. return svg;
  3293. },
  3294. getTrackArc: function() {
  3295. var me = this,
  3296. trackArc = me.trackArc;
  3297. if (!trackArc) {
  3298. trackArc = me.trackArc = document.createElementNS(me.svgNS, 'path');
  3299. me.getSvg().append(trackArc, true);
  3300. // Note: Ext.dom.Element.addCls doesn't work on SVG elements,
  3301. // as it simply assigns a class string to el.dom.className,
  3302. // which in case of SVG is no simple string:
  3303. // SVGAnimatedString {baseVal: "x-gauge-track", animVal: "x-gauge-track"}
  3304. trackArc.setAttribute('class', Ext.baseCSSPrefix + 'gauge-track');
  3305. }
  3306. return trackArc;
  3307. },
  3308. getValueArc: function() {
  3309. var me = this,
  3310. valueArc = me.valueArc;
  3311. me.getTrackArc();
  3312. // make sure the track arc is created first for proper draw order
  3313. if (!valueArc) {
  3314. valueArc = me.valueArc = document.createElementNS(me.svgNS, 'path');
  3315. me.getSvg().append(valueArc, true);
  3316. valueArc.setAttribute('class', Ext.baseCSSPrefix + 'gauge-value');
  3317. }
  3318. return valueArc;
  3319. },
  3320. applyNeedle: function(needle, oldNeedle) {
  3321. // Make sure the track and value elements have been already created,
  3322. // so that the needle element renders on top.
  3323. this.getValueArc();
  3324. return Ext.Factory.gaugeNeedle.update(oldNeedle, needle, this, 'createNeedle', 'needleDefaults');
  3325. },
  3326. createNeedle: function(config) {
  3327. return Ext.apply({
  3328. gauge: this
  3329. }, config);
  3330. },
  3331. getDefs: function() {
  3332. var me = this,
  3333. defs = me.defs;
  3334. if (!defs) {
  3335. defs = me.defs = Ext.get(document.createElementNS(me.svgNS, 'defs'));
  3336. me.getSvg().appendChild(defs);
  3337. }
  3338. return defs;
  3339. },
  3340. /**
  3341. * @private
  3342. */
  3343. setGradientSize: function(gradient, x1, y1, x2, y2) {
  3344. gradient.setAttribute('x1', x1);
  3345. gradient.setAttribute('y1', y1);
  3346. gradient.setAttribute('x2', x2);
  3347. gradient.setAttribute('y2', y2);
  3348. },
  3349. /**
  3350. * @private
  3351. */
  3352. resizeGradients: function(size) {
  3353. var me = this,
  3354. trackGradient = me.getTrackGradient(),
  3355. valueGradient = me.getValueGradient(),
  3356. x1 = 0,
  3357. y1 = size.height / 2,
  3358. x2 = size.width,
  3359. y2 = size.height / 2;
  3360. me.setGradientSize(trackGradient.dom, x1, y1, x2, y2);
  3361. me.setGradientSize(valueGradient.dom, x1, y1, x2, y2);
  3362. },
  3363. /**
  3364. * @private
  3365. */
  3366. setGradientStops: function(gradient, stops) {
  3367. var ln = stops.length,
  3368. i, stopCfg, stopEl;
  3369. while (gradient.firstChild) {
  3370. gradient.removeChild(gradient.firstChild);
  3371. }
  3372. for (i = 0; i < ln; i++) {
  3373. stopCfg = stops[i];
  3374. stopEl = document.createElementNS(this.svgNS, 'stop');
  3375. gradient.appendChild(stopEl);
  3376. stopEl.setAttribute('offset', stopCfg.offset);
  3377. stopEl.setAttribute('stop-color', stopCfg.color);
  3378. ('opacity' in stopCfg) && stopEl.setAttribute('stop-opacity', stopCfg.opacity);
  3379. }
  3380. },
  3381. getTrackGradient: function() {
  3382. var me = this,
  3383. trackGradient = me.trackGradient;
  3384. if (!trackGradient) {
  3385. trackGradient = me.trackGradient = Ext.get(document.createElementNS(me.svgNS, 'linearGradient'));
  3386. // Using absolute values for x1, y1, x2, y2 attributes.
  3387. trackGradient.dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  3388. me.getDefs().appendChild(trackGradient);
  3389. Ext.get(trackGradient);
  3390. }
  3391. // assign unique ID
  3392. return trackGradient;
  3393. },
  3394. getValueGradient: function() {
  3395. var me = this,
  3396. valueGradient = me.valueGradient;
  3397. if (!valueGradient) {
  3398. valueGradient = me.valueGradient = Ext.get(document.createElementNS(me.svgNS, 'linearGradient'));
  3399. // Using absolute values for x1, y1, x2, y2 attributes.
  3400. valueGradient.dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  3401. me.getDefs().appendChild(valueGradient);
  3402. Ext.get(valueGradient);
  3403. }
  3404. // assign unique ID
  3405. return valueGradient;
  3406. },
  3407. getArcPoint: function(centerX, centerY, radius, degrees) {
  3408. var radians = degrees / 180 * Math.PI;
  3409. return [
  3410. centerX + radius * Math.cos(radians),
  3411. centerY + radius * Math.sin(radians)
  3412. ];
  3413. },
  3414. isCircle: function(startAngle, endAngle) {
  3415. return Ext.Number.isEqual(Math.abs(endAngle - startAngle), 360, 0.001);
  3416. },
  3417. getArcPath: function(centerX, centerY, innerRadius, outerRadius, startAngle, endAngle, round) {
  3418. var me = this,
  3419. isCircle = me.isCircle(startAngle, endAngle),
  3420. // It's not possible to draw a circle using arcs.
  3421. endAngle = endAngle - 0.01,
  3422. innerStartPoint = me.getArcPoint(centerX, centerY, innerRadius, startAngle),
  3423. innerEndPoint = me.getArcPoint(centerX, centerY, innerRadius, endAngle),
  3424. outerStartPoint = me.getArcPoint(centerX, centerY, outerRadius, startAngle),
  3425. outerEndPoint = me.getArcPoint(centerX, centerY, outerRadius, endAngle),
  3426. large = endAngle - startAngle <= 180 ? 0 : 1,
  3427. path = [
  3428. 'M',
  3429. innerStartPoint[0],
  3430. innerStartPoint[1],
  3431. 'A',
  3432. innerRadius,
  3433. innerRadius,
  3434. 0,
  3435. large,
  3436. 1,
  3437. innerEndPoint[0],
  3438. innerEndPoint[1]
  3439. ],
  3440. capRadius = (outerRadius - innerRadius) / 2;
  3441. if (isCircle) {
  3442. path.push('M', outerEndPoint[0], outerEndPoint[1]);
  3443. } else {
  3444. if (round) {
  3445. path.push('A', capRadius, capRadius, 0, 0, 0, outerEndPoint[0], outerEndPoint[1]);
  3446. } else {
  3447. path.push('L', outerEndPoint[0], outerEndPoint[1]);
  3448. }
  3449. }
  3450. path.push('A', outerRadius, outerRadius, 0, large, 0, outerStartPoint[0], outerStartPoint[1]);
  3451. if (round && !isCircle) {
  3452. path.push('A', capRadius, capRadius, 0, 0, 0, innerStartPoint[0], innerStartPoint[1]);
  3453. }
  3454. path.push('Z');
  3455. return path.join(' ');
  3456. },
  3457. resizeHandler: function(size) {
  3458. var me = this,
  3459. svg = me.getSvg();
  3460. svg.setSize(size);
  3461. me.resizeGradients(size);
  3462. me.render();
  3463. },
  3464. /**
  3465. * @private
  3466. * Creates a linear interpolator function that itself has a few methods:
  3467. * - `setDomain(from, to)`
  3468. * - `setRange(from, to)`
  3469. * - `getDomain` - returns the domain as a [from, to] array
  3470. * - `getRange` - returns the range as a [from, to] array
  3471. * @param {Boolean} [rangeCheck=false]
  3472. * Whether to allow out of bounds values for domain and range.
  3473. * @return {Function} The interpolator function:
  3474. * `interpolator(domainValue, isInvert)`.
  3475. * If the `isInvert` parameter is `true`, the start of domain will correspond
  3476. * to the end of range. This is useful, for example, when you want to render
  3477. * increasing domain values counter-clockwise instead of clockwise.
  3478. */
  3479. createInterpolator: function(rangeCheck) {
  3480. var domainStart = 0,
  3481. domainDelta = 1,
  3482. rangeStart = 0,
  3483. rangeEnd = 1;
  3484. var interpolator = function(x, invert) {
  3485. var t = 0;
  3486. if (domainDelta) {
  3487. t = (x - domainStart) / domainDelta;
  3488. if (rangeCheck) {
  3489. t = Math.max(0, t);
  3490. t = Math.min(1, t);
  3491. }
  3492. if (invert) {
  3493. t = 1 - t;
  3494. }
  3495. }
  3496. return (1 - t) * rangeStart + t * rangeEnd;
  3497. };
  3498. interpolator.setDomain = function(a, b) {
  3499. domainStart = a;
  3500. domainDelta = b - a;
  3501. return this;
  3502. };
  3503. interpolator.setRange = function(a, b) {
  3504. rangeStart = a;
  3505. rangeEnd = b;
  3506. return this;
  3507. };
  3508. interpolator.getDomain = function() {
  3509. return [
  3510. domainStart,
  3511. domainStart + domainDelta
  3512. ];
  3513. };
  3514. interpolator.getRange = function() {
  3515. return [
  3516. rangeStart,
  3517. rangeEnd
  3518. ];
  3519. };
  3520. return interpolator;
  3521. },
  3522. applyAnimation: function(animation) {
  3523. if (true === animation) {
  3524. animation = {};
  3525. } else if (false === animation) {
  3526. animation = {
  3527. duration: 0
  3528. };
  3529. }
  3530. if (!('duration' in animation)) {
  3531. animation.duration = 1000;
  3532. }
  3533. if (!(animation.easing in this.easings)) {
  3534. animation.easing = 'out';
  3535. }
  3536. return animation;
  3537. },
  3538. updateAnimation: function() {
  3539. this.stopAnimation();
  3540. },
  3541. /**
  3542. * @private
  3543. * @param {Number} from
  3544. * @param {Number} to
  3545. * @param {Number} duration
  3546. * @param {Function} easing
  3547. * @param {Function} fn Function to execute on every frame of animation.
  3548. * The function takes a single parameter - the value in the [from, to]
  3549. * range, interpolated based on current time and easing function.
  3550. * With certain easings, the value may overshoot the range slighly.
  3551. * @param {Object} scope
  3552. */
  3553. animate: function(from, to, duration, easing, fn, scope) {
  3554. var me = this,
  3555. start = Ext.now(),
  3556. interpolator = me.createInterpolator().setRange(from, to);
  3557. function frame() {
  3558. var now = Ext.AnimationQueue.frameStartTime,
  3559. t = Math.min(now - start, duration) / duration,
  3560. value = interpolator(easing(t));
  3561. if (scope) {
  3562. if (typeof fn === 'string') {
  3563. scope[fn].call(scope, value);
  3564. } else {
  3565. fn.call(scope, value);
  3566. }
  3567. } else {
  3568. fn(value);
  3569. }
  3570. if (t >= 1) {
  3571. Ext.AnimationQueue.stop(frame, scope);
  3572. me.fx = null;
  3573. }
  3574. }
  3575. me.stopAnimation();
  3576. Ext.AnimationQueue.start(frame, scope);
  3577. me.fx = {
  3578. frame: frame,
  3579. scope: scope
  3580. };
  3581. },
  3582. /**
  3583. * Stops the current {@link #value} or {@link #angleOffset} animation.
  3584. */
  3585. stopAnimation: function() {
  3586. var me = this;
  3587. if (me.fx) {
  3588. Ext.AnimationQueue.stop(me.fx.frame, me.fx.scope);
  3589. me.fx = null;
  3590. }
  3591. },
  3592. unitCircleExtrema: {
  3593. 0: [
  3594. 1,
  3595. 0
  3596. ],
  3597. 90: [
  3598. 0,
  3599. 1
  3600. ],
  3601. 180: [
  3602. -1,
  3603. 0
  3604. ],
  3605. 270: [
  3606. 0,
  3607. -1
  3608. ],
  3609. 360: [
  3610. 1,
  3611. 0
  3612. ],
  3613. 450: [
  3614. 0,
  3615. 1
  3616. ],
  3617. 540: [
  3618. -1,
  3619. 0
  3620. ],
  3621. 630: [
  3622. 0,
  3623. -1
  3624. ]
  3625. },
  3626. /**
  3627. * @private
  3628. */
  3629. getUnitSectorExtrema: function(startAngle, lengthAngle) {
  3630. var extrema = this.unitCircleExtrema,
  3631. points = [],
  3632. angle;
  3633. for (angle in extrema) {
  3634. if (angle > startAngle && angle < startAngle + lengthAngle) {
  3635. points.push(extrema[angle]);
  3636. }
  3637. }
  3638. return points;
  3639. },
  3640. /**
  3641. * @private
  3642. * Given a rect with a known width and height, find the maximum radius of the donut
  3643. * sector that can fit into it, as well as the center point of such a sector.
  3644. * The end and start angles of the sector are also known, as well as the relationship
  3645. * between the inner and outer radii.
  3646. */
  3647. fitSectorInRect: function(width, height, startAngle, lengthAngle, ratio) {
  3648. if (Ext.Number.isEqual(lengthAngle, 360, 0.001)) {
  3649. return {
  3650. cx: width / 2,
  3651. cy: height / 2,
  3652. radius: Math.min(width, height) / 2,
  3653. region: new Ext.util.Region(0, width, height, 0)
  3654. };
  3655. }
  3656. var me = this,
  3657. points, xx, yy, minX, maxX, minY, maxY,
  3658. cache = me.fitSectorInRectCache,
  3659. sameAngles = cache.startAngle === startAngle && cache.lengthAngle === lengthAngle;
  3660. if (sameAngles) {
  3661. minX = cache.minX;
  3662. maxX = cache.maxX;
  3663. minY = cache.minY;
  3664. maxY = cache.maxY;
  3665. } else {
  3666. points = me.getUnitSectorExtrema(startAngle, lengthAngle).concat([
  3667. me.getArcPoint(0, 0, 1, startAngle),
  3668. // start angle outer radius point
  3669. me.getArcPoint(0, 0, ratio, startAngle),
  3670. // start angle inner radius point
  3671. me.getArcPoint(0, 0, 1, startAngle + lengthAngle),
  3672. // end angle outer radius point
  3673. me.getArcPoint(0, 0, ratio, startAngle + lengthAngle)
  3674. ]);
  3675. // end angle inner radius point
  3676. xx = points.map(function(point) {
  3677. return point[0];
  3678. });
  3679. yy = points.map(function(point) {
  3680. return point[1];
  3681. });
  3682. // The bounding box of a unit sector with the given properties.
  3683. minX = Math.min.apply(null, xx);
  3684. maxX = Math.max.apply(null, xx);
  3685. minY = Math.min.apply(null, yy);
  3686. maxY = Math.max.apply(null, yy);
  3687. cache.startAngle = startAngle;
  3688. cache.lengthAngle = lengthAngle;
  3689. cache.minX = minX;
  3690. cache.maxX = maxX;
  3691. cache.minY = minY;
  3692. cache.maxY = maxY;
  3693. }
  3694. var sectorWidth = maxX - minX,
  3695. sectorHeight = maxY - minY,
  3696. scaleX = width / sectorWidth,
  3697. scaleY = height / sectorHeight,
  3698. scale = Math.min(scaleX, scaleY),
  3699. // Region constructor takes: top, right, bottom, left.
  3700. sectorRegion = new Ext.util.Region(minY * scale, maxX * scale, maxY * scale, minX * scale),
  3701. rectRegion = new Ext.util.Region(0, width, height, 0),
  3702. alignedRegion = sectorRegion.alignTo({
  3703. align: 'c-c',
  3704. // align sector region's center to rect region's center
  3705. target: rectRegion
  3706. }),
  3707. dx = alignedRegion.left - minX * scale,
  3708. dy = alignedRegion.top - minY * scale;
  3709. return {
  3710. cx: dx,
  3711. cy: dy,
  3712. radius: scale,
  3713. region: alignedRegion
  3714. };
  3715. },
  3716. /**
  3717. * @private
  3718. */
  3719. fitSectorInPaddedRect: function(width, height, padding, startAngle, lengthAngle, ratio) {
  3720. var result = this.fitSectorInRect(width - padding * 2, height - padding * 2, startAngle, lengthAngle, ratio);
  3721. result.cx += padding;
  3722. result.cy += padding;
  3723. result.region.translateBy(padding, padding);
  3724. return result;
  3725. },
  3726. /**
  3727. * @private
  3728. */
  3729. normalizeAngle: function(angle) {
  3730. return (angle % 360 + 360) % 360;
  3731. },
  3732. render: function() {
  3733. if (!this.size) {
  3734. return;
  3735. }
  3736. var me = this,
  3737. textOffset = me.getTextOffset(),
  3738. trackArc = me.getTrackArc(),
  3739. valueArc = me.getValueArc(),
  3740. needle = me.getNeedle(),
  3741. clockwise = me.getClockwise(),
  3742. value = me.fxValue,
  3743. angleOffset = me.fxAngleOffset,
  3744. trackLength = me.getTrackLength(),
  3745. width = me.size.width,
  3746. height = me.size.height,
  3747. paddingFn = me.getPadding(),
  3748. padding = paddingFn(Math.min(width, height)),
  3749. trackStart = me.normalizeAngle(me.getTrackStart() + angleOffset),
  3750. // in the range of [0, 360)
  3751. trackEnd = trackStart + trackLength,
  3752. // in the range of (0, 720)
  3753. valueLength = me.interpolator(value),
  3754. trackStyle = me.getTrackStyle(),
  3755. valueStyle = me.getValueStyle(),
  3756. sector = me.fitSectorInPaddedRect(width, height, padding, trackStart, trackLength, trackStyle.innerRadius.ratio),
  3757. cx = sector.cx,
  3758. cy = sector.cy,
  3759. radius = sector.radius,
  3760. trackInnerRadius = Math.max(0, trackStyle.innerRadius(radius)),
  3761. trackOuterRadius = Math.max(0, trackStyle.outerRadius(radius)),
  3762. valueInnerRadius = Math.max(0, valueStyle.innerRadius(radius)),
  3763. valueOuterRadius = Math.max(0, valueStyle.outerRadius(radius)),
  3764. trackPath = me.getArcPath(cx, cy, trackInnerRadius, trackOuterRadius, trackStart, trackEnd, trackStyle.round),
  3765. valuePath = me.getArcPath(cx, cy, valueInnerRadius, valueOuterRadius, clockwise ? trackStart : trackEnd - valueLength, clockwise ? trackStart + valueLength : trackEnd, valueStyle.round);
  3766. me.centerText(cx + textOffset.dx, cy + textOffset.dy, sector.region, trackInnerRadius, trackOuterRadius);
  3767. trackArc.setAttribute('d', trackPath);
  3768. valueArc.setAttribute('d', valuePath);
  3769. if (needle) {
  3770. needle.setRadius(radius);
  3771. needle.setTransform(cx, cy, -90 + trackStart + valueLength);
  3772. }
  3773. me.fireEvent('render', me);
  3774. }
  3775. });
  3776. Ext.define('Ext.ux.gauge.needle.Arrow', {
  3777. extend: 'Ext.ux.gauge.needle.Abstract',
  3778. alias: 'gauge.needle.arrow',
  3779. config: {
  3780. path: function(ir, or) {
  3781. return or - ir > 30 ? "M0," + (ir + 5) + " L-4," + ir + " L-4," + (ir + 10) + " L-1," + (ir + 15) + " L-1," + (or - 7) + " L-5," + (or - 10) + " L0," + or + " L5," + (or - 10) + " L1," + (or - 7) + " L1," + (ir + 15) + " L4," + (ir + 10) + " L4," + ir + " Z" : '';
  3782. }
  3783. }
  3784. });
  3785. Ext.define('Ext.ux.gauge.needle.Diamond', {
  3786. extend: 'Ext.ux.gauge.needle.Abstract',
  3787. alias: 'gauge.needle.diamond',
  3788. config: {
  3789. path: function(ir, or) {
  3790. return or - ir > 10 ? 'M0,' + ir + ' L-4,' + (ir + 5) + ' L0,' + or + ' L4,' + (ir + 5) + ' Z' : '';
  3791. }
  3792. }
  3793. });
  3794. Ext.define('Ext.ux.gauge.needle.Rectangle', {
  3795. extend: 'Ext.ux.gauge.needle.Abstract',
  3796. alias: 'gauge.needle.rectangle',
  3797. config: {
  3798. path: function(ir, or) {
  3799. return or - ir > 10 ? "M-2," + ir + " L2," + ir + " L2," + or + " L-2," + or + " Z" : '';
  3800. }
  3801. }
  3802. });
  3803. Ext.define('Ext.ux.gauge.needle.Spike', {
  3804. extend: 'Ext.ux.gauge.needle.Abstract',
  3805. alias: 'gauge.needle.spike',
  3806. config: {
  3807. path: function(ir, or) {
  3808. return or - ir > 10 ? "M0," + (ir + 5) + " L-4," + ir + " L0," + or + " L4," + ir + " Z" : '';
  3809. }
  3810. }
  3811. });
  3812. Ext.define('Ext.ux.gauge.needle.Wedge', {
  3813. extend: 'Ext.ux.gauge.needle.Abstract',
  3814. alias: 'gauge.needle.wedge',
  3815. config: {
  3816. path: function(ir, or) {
  3817. return or - ir > 10 ? "M-4," + ir + " L0," + or + " L4," + ir + " Z" : '';
  3818. }
  3819. }
  3820. });
  3821. /**
  3822. * A ratings picker based on `Ext.Gadget`.
  3823. *
  3824. * @example
  3825. * Ext.create({
  3826. * xtype: 'rating',
  3827. * renderTo: Ext.getBody(),
  3828. * listeners: {
  3829. * change: function (picker, value) {
  3830. * console.log('Rating ' + value);
  3831. * }
  3832. * }
  3833. * });
  3834. */
  3835. Ext.define('Ext.ux.rating.Picker', {
  3836. extend: 'Ext.Gadget',
  3837. xtype: 'rating',
  3838. focusable: true,
  3839. /*
  3840. * The "cachedConfig" block is basically the same as "config" except that these
  3841. * values are applied specially to the first instance of the class. After processing
  3842. * these configs, the resulting values are stored on the class `prototype` and the
  3843. * template DOM element also reflects these default values.
  3844. */
  3845. cachedConfig: {
  3846. /**
  3847. * @cfg {String} [family]
  3848. * The CSS `font-family` to use for displaying the `{@link #glyphs}`.
  3849. */
  3850. family: 'monospace',
  3851. /**
  3852. * @cfg {String/String[]/Number[]} [glyphs]
  3853. * Either a string containing the two glyph characters, or an array of two strings
  3854. * containing the individual glyph characters or an array of two numbers with the
  3855. * character codes for the individual glyphs.
  3856. *
  3857. * For example:
  3858. *
  3859. * @example
  3860. * Ext.create({
  3861. * xtype: 'rating',
  3862. * renderTo: Ext.getBody(),
  3863. * glyphs: [ 9671, 9670 ], // '◇◆',
  3864. * listeners: {
  3865. * change: function (picker, value) {
  3866. * console.log('Rating ' + value);
  3867. * }
  3868. * }
  3869. * });
  3870. */
  3871. glyphs: '☆★',
  3872. /**
  3873. * @cfg {Number} [minimum=1]
  3874. * The minimum allowed `{@link #value}` (rating).
  3875. */
  3876. minimum: 1,
  3877. /**
  3878. * @cfg {Number} [limit]
  3879. * The maximum allowed `{@link #value}` (rating).
  3880. */
  3881. limit: 5,
  3882. /**
  3883. * @cfg {String/Object} [overStyle]
  3884. * Optional styles to apply to the rating glyphs when `{@link #trackOver}` is
  3885. * enabled.
  3886. */
  3887. overStyle: null,
  3888. /**
  3889. * @cfg {Number} [rounding=1]
  3890. * The rounding to apply to values. Common choices are 0.5 (for half-steps) or
  3891. * 0.25 (for quarter steps).
  3892. */
  3893. rounding: 1,
  3894. /**
  3895. * @cfg {String} [scale="125%"]
  3896. * The CSS `font-size` to apply to the glyphs. This value defaults to 125% because
  3897. * glyphs in the stock font tend to be too small. When using specially designed
  3898. * "icon fonts" you may want to set this to 100%.
  3899. */
  3900. scale: '125%',
  3901. /**
  3902. * @cfg {String/Object} [selectedStyle]
  3903. * Optional styles to apply to the rating value glyphs.
  3904. */
  3905. selectedStyle: null,
  3906. /**
  3907. * @cfg {Object/String/String[]/Ext.XTemplate/Function} tip
  3908. * A template or a function that produces the tooltip text. The `Object`, `String`
  3909. * and `String[]` forms are converted to an `Ext.XTemplate`. If a function is given,
  3910. * it will be called with an object parameter and should return the tooltip text.
  3911. * The object contains these properties:
  3912. *
  3913. * - component: The rating component requesting the tooltip.
  3914. * - tracking: The current value under the mouse cursor.
  3915. * - trackOver: The value of the `{@link #trackOver}` config.
  3916. * - value: The current value.
  3917. *
  3918. * Templates can use these properties to generate the proper text.
  3919. */
  3920. tip: null,
  3921. /**
  3922. * @cfg {Boolean} [trackOver=true]
  3923. * Determines if mouse movements should temporarily update the displayed value.
  3924. * The actual `value` is only updated on `click` but this rather acts as the
  3925. * "preview" of the value prior to click.
  3926. */
  3927. trackOver: true,
  3928. /**
  3929. * @cfg {Number} value
  3930. * The rating value. This value is bounded by `minimum` and `limit` and is also
  3931. * adjusted by the `rounding`.
  3932. */
  3933. value: null,
  3934. //---------------------------------------------------------------------
  3935. // Private configs
  3936. /**
  3937. * @cfg {String} tooltipText
  3938. * The current tooltip text. This value is set into the DOM by the updater (hence
  3939. * only when it changes). This is intended for use by the tip manager
  3940. * (`{@link Ext.tip.QuickTipManager}`). Developers should never need to set this
  3941. * config since it is handled by virtue of setting other configs (such as the
  3942. * {@link #tooltip} or the {@link #value}.).
  3943. * @private
  3944. */
  3945. tooltipText: null,
  3946. /**
  3947. * @cfg {Number} trackingValue
  3948. * This config is used to when `trackOver` is `true` and represents the tracked
  3949. * value. This config is maintained by our `mousemove` handler. This should not
  3950. * need to be set directly by user code.
  3951. * @private
  3952. */
  3953. trackingValue: null
  3954. },
  3955. config: {
  3956. /**
  3957. * @cfg {Boolean/Object} [animate=false]
  3958. * Specifies an animation to use when changing the `{@link #value}`. When setting
  3959. * this config, it is probably best to set `{@link #trackOver}` to `false`.
  3960. */
  3961. animate: null
  3962. },
  3963. // This object describes our element tree from the root.
  3964. element: {
  3965. cls: 'u' + Ext.baseCSSPrefix + 'rating-picker',
  3966. // Since we are replacing the entire "element" tree, we have to assign this
  3967. // "reference" as would our base class.
  3968. reference: 'element',
  3969. children: [
  3970. {
  3971. reference: 'innerEl',
  3972. cls: 'u' + Ext.baseCSSPrefix + 'rating-picker-inner',
  3973. listeners: {
  3974. click: 'onClick',
  3975. mousemove: 'onMouseMove',
  3976. mouseenter: 'onMouseEnter',
  3977. mouseleave: 'onMouseLeave'
  3978. },
  3979. children: [
  3980. {
  3981. reference: 'valueEl',
  3982. cls: 'u' + Ext.baseCSSPrefix + 'rating-picker-value'
  3983. },
  3984. {
  3985. reference: 'trackerEl',
  3986. cls: 'u' + Ext.baseCSSPrefix + 'rating-picker-tracker'
  3987. }
  3988. ]
  3989. }
  3990. ]
  3991. },
  3992. // Tell the Binding system to default to our "value" config.
  3993. defaultBindProperty: 'value',
  3994. // Enable two-way data binding for the "value" config.
  3995. twoWayBindable: 'value',
  3996. overCls: 'u' + Ext.baseCSSPrefix + 'rating-picker-over',
  3997. trackOverCls: 'u' + Ext.baseCSSPrefix + 'rating-picker-track-over',
  3998. //-------------------------------------------------------------------------
  3999. // Config Appliers
  4000. applyGlyphs: function(value) {
  4001. if (typeof value === 'string') {
  4002. //<debug>
  4003. if (value.length !== 2) {
  4004. Ext.raise('Expected 2 characters for "glyphs" not "' + value + '".');
  4005. }
  4006. //</debug>
  4007. value = [
  4008. value.charAt(0),
  4009. value.charAt(1)
  4010. ];
  4011. } else if (typeof value[0] === 'number') {
  4012. value = [
  4013. String.fromCharCode(value[0]),
  4014. String.fromCharCode(value[1])
  4015. ];
  4016. }
  4017. return value;
  4018. },
  4019. applyOverStyle: function(style) {
  4020. this.trackerEl.applyStyles(style);
  4021. },
  4022. applySelectedStyle: function(style) {
  4023. this.valueEl.applyStyles(style);
  4024. },
  4025. applyTip: function(tip) {
  4026. if (tip && typeof tip !== 'function') {
  4027. if (!tip.isTemplate) {
  4028. tip = new Ext.XTemplate(tip);
  4029. }
  4030. tip = tip.apply.bind(tip);
  4031. }
  4032. return tip;
  4033. },
  4034. applyTrackingValue: function(value) {
  4035. return this.applyValue(value);
  4036. },
  4037. // same rounding as normal value
  4038. applyValue: function(v) {
  4039. if (v !== null) {
  4040. var rounding = this.getRounding(),
  4041. limit = this.getLimit(),
  4042. min = this.getMinimum();
  4043. v = Math.round(Math.round(v / rounding) * rounding * 1000) / 1000;
  4044. v = (v < min) ? min : (v > limit ? limit : v);
  4045. }
  4046. return v;
  4047. },
  4048. //-------------------------------------------------------------------------
  4049. // Event Handlers
  4050. onClick: function(event) {
  4051. var value = this.valueFromEvent(event);
  4052. this.setValue(value);
  4053. },
  4054. onMouseEnter: function() {
  4055. this.element.addCls(this.overCls);
  4056. },
  4057. onMouseLeave: function() {
  4058. this.element.removeCls(this.overCls);
  4059. },
  4060. onMouseMove: function(event) {
  4061. var value = this.valueFromEvent(event);
  4062. this.setTrackingValue(value);
  4063. },
  4064. //-------------------------------------------------------------------------
  4065. // Config Updaters
  4066. updateFamily: function(family) {
  4067. this.element.setStyle('fontFamily', "'" + family + "'");
  4068. },
  4069. updateGlyphs: function() {
  4070. this.refreshGlyphs();
  4071. },
  4072. updateLimit: function() {
  4073. this.refreshGlyphs();
  4074. },
  4075. updateScale: function(size) {
  4076. this.element.setStyle('fontSize', size);
  4077. },
  4078. updateTip: function() {
  4079. this.refreshTip();
  4080. },
  4081. updateTooltipText: function(text) {
  4082. this.setTooltip(text);
  4083. },
  4084. // modern only (replaced by classic override)
  4085. updateTrackingValue: function(value) {
  4086. var me = this,
  4087. trackerEl = me.trackerEl,
  4088. newWidth = me.valueToPercent(value);
  4089. trackerEl.setStyle('width', newWidth);
  4090. me.refreshTip();
  4091. },
  4092. updateTrackOver: function(trackOver) {
  4093. this.element.toggleCls(this.trackOverCls, trackOver);
  4094. },
  4095. updateValue: function(value, oldValue) {
  4096. var me = this,
  4097. animate = me.getAnimate(),
  4098. valueEl = me.valueEl,
  4099. newWidth = me.valueToPercent(value),
  4100. column, record;
  4101. if (me.isConfiguring || !animate) {
  4102. valueEl.setStyle('width', newWidth);
  4103. } else {
  4104. valueEl.stopAnimation();
  4105. valueEl.animate(Ext.merge({
  4106. from: {
  4107. width: me.valueToPercent(oldValue)
  4108. },
  4109. to: {
  4110. width: newWidth
  4111. }
  4112. }, animate));
  4113. }
  4114. me.refreshTip();
  4115. if (!me.isConfiguring) {
  4116. // Since we are (re)configured many times as we are used in a grid cell, we
  4117. // avoid firing the change event unless there are listeners.
  4118. if (me.hasListeners.change) {
  4119. me.fireEvent('change', me, value, oldValue);
  4120. }
  4121. column = me.getWidgetColumn && me.getWidgetColumn();
  4122. record = column && me.getWidgetRecord && me.getWidgetRecord();
  4123. if (record && column.dataIndex) {
  4124. // When used in a widgetcolumn, we should update the backing field. The
  4125. // linkages will be cleared as we are being recycled, so this will only
  4126. // reach this line when we are properly attached to a record and the
  4127. // change is coming from the user (or a call to setValue).
  4128. record.set(column.dataIndex, value);
  4129. }
  4130. }
  4131. },
  4132. //-------------------------------------------------------------------------
  4133. // Config System Optimizations
  4134. //
  4135. // These are to deal with configs that combine to determine what should be
  4136. // rendered in the DOM. For example, "glyphs" and "limit" must both be known
  4137. // to render the proper text nodes. The "tip" and "value" likewise are
  4138. // used to update the tooltipText.
  4139. //
  4140. // To avoid multiple updates to the DOM (one for each config), we simply mark
  4141. // the rendering as invalid and post-process these flags on the tail of any
  4142. // bulk updates.
  4143. afterCachedConfig: function() {
  4144. // Now that we are done setting up the initial values we need to refresh the
  4145. // DOM before we allow Ext.Widget's implementation to cloneNode on it.
  4146. this.refresh();
  4147. return this.callParent(arguments);
  4148. },
  4149. initConfig: function(instanceConfig) {
  4150. this.isConfiguring = true;
  4151. this.callParent([
  4152. instanceConfig
  4153. ]);
  4154. // The firstInstance will already have refreshed the DOM (in afterCacheConfig)
  4155. // but all instances beyond the first need to refresh if they have custom values
  4156. // for one or more configs that affect the DOM (such as "glyphs" and "limit").
  4157. this.refresh();
  4158. },
  4159. setConfig: function() {
  4160. var me = this;
  4161. // Since we could be updating multiple configs, save any updates that need
  4162. // multiple values for afterwards.
  4163. me.isReconfiguring = true;
  4164. me.callParent(arguments);
  4165. me.isReconfiguring = false;
  4166. // Now that all new values are set, we can refresh the DOM.
  4167. me.refresh();
  4168. return me;
  4169. },
  4170. //-------------------------------------------------------------------------
  4171. privates: {
  4172. /**
  4173. * This method returns the DOM text node into which glyphs are placed.
  4174. * @param {HTMLElement} dom The DOM node parent of the text node.
  4175. * @return {HTMLElement} The text node.
  4176. * @private
  4177. */
  4178. getGlyphTextNode: function(dom) {
  4179. var node = dom.lastChild;
  4180. // We want all our text nodes to be at the end of the child list, most
  4181. // especially the text node on the innerEl. That text node affects the
  4182. // default left/right position of our absolutely positioned child divs
  4183. // (trackerEl and valueEl).
  4184. if (!node || node.nodeType !== 3) {
  4185. node = dom.ownerDocument.createTextNode('');
  4186. dom.appendChild(node);
  4187. }
  4188. return node;
  4189. },
  4190. getTooltipData: function() {
  4191. var me = this;
  4192. return {
  4193. component: me,
  4194. tracking: me.getTrackingValue(),
  4195. trackOver: me.getTrackOver(),
  4196. value: me.getValue()
  4197. };
  4198. },
  4199. /**
  4200. * Forcibly refreshes both glyph and tooltip rendering.
  4201. * @private
  4202. */
  4203. refresh: function() {
  4204. var me = this;
  4205. if (me.invalidGlyphs) {
  4206. me.refreshGlyphs(true);
  4207. }
  4208. if (me.invalidTip) {
  4209. me.refreshTip(true);
  4210. }
  4211. },
  4212. /**
  4213. * Refreshes the glyph text rendering unless we are currently performing a
  4214. * bulk config change (initConfig or setConfig).
  4215. * @param {Boolean} now Pass `true` to force the refresh to happen now.
  4216. * @private
  4217. */
  4218. refreshGlyphs: function(now) {
  4219. var me = this,
  4220. later = !now && (me.isConfiguring || me.isReconfiguring),
  4221. el, glyphs, limit, on, off, trackerEl, valueEl;
  4222. if (!later) {
  4223. el = me.getGlyphTextNode(me.innerEl.dom);
  4224. valueEl = me.getGlyphTextNode(me.valueEl.dom);
  4225. trackerEl = me.getGlyphTextNode(me.trackerEl.dom);
  4226. glyphs = me.getGlyphs();
  4227. limit = me.getLimit();
  4228. for (on = off = ''; limit--; ) {
  4229. off += glyphs[0];
  4230. on += glyphs[1];
  4231. }
  4232. el.nodeValue = off;
  4233. valueEl.nodeValue = on;
  4234. trackerEl.nodeValue = on;
  4235. }
  4236. me.invalidGlyphs = later;
  4237. },
  4238. /**
  4239. * Refreshes the tooltip text rendering unless we are currently performing a
  4240. * bulk config change (initConfig or setConfig).
  4241. * @param {Boolean} now Pass `true` to force the refresh to happen now.
  4242. * @private
  4243. */
  4244. refreshTip: function(now) {
  4245. var me = this,
  4246. later = !now && (me.isConfiguring || me.isReconfiguring),
  4247. data, text, tooltip;
  4248. if (!later) {
  4249. tooltip = me.getTip();
  4250. if (tooltip) {
  4251. data = me.getTooltipData();
  4252. text = tooltip(data);
  4253. me.setTooltipText(text);
  4254. }
  4255. }
  4256. me.invalidTip = later;
  4257. },
  4258. /**
  4259. * Convert the coordinates of the given `Event` into a rating value.
  4260. * @param {Ext.event.Event} event The event.
  4261. * @return {Number} The rating based on the given event coordinates.
  4262. * @private
  4263. */
  4264. valueFromEvent: function(event) {
  4265. var me = this,
  4266. el = me.innerEl,
  4267. ex = event.getX(),
  4268. rounding = me.getRounding(),
  4269. cx = el.getX(),
  4270. x = ex - cx,
  4271. w = el.getWidth(),
  4272. limit = me.getLimit(),
  4273. v;
  4274. if (me.getInherited().rtl) {
  4275. x = w - x;
  4276. }
  4277. v = x / w * limit;
  4278. // We have to round up here so that the area we are over is considered
  4279. // the value.
  4280. v = Math.ceil(v / rounding) * rounding;
  4281. return v;
  4282. },
  4283. /**
  4284. * Convert the given rating into a width percentage.
  4285. * @param {Number} value The rating value to convert.
  4286. * @return {String} The width percentage to represent the given value.
  4287. * @private
  4288. */
  4289. valueToPercent: function(value) {
  4290. value = (value / this.getLimit()) * 100;
  4291. return value + '%';
  4292. }
  4293. }
  4294. });