ext-foundation-dev.js 371 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682
  1. /*
  2. Ext JS 4.1 - JavaScript Library
  3. Copyright (c) 2006-2012, Sencha Inc.
  4. All rights reserved.
  5. licensing@sencha.com
  6. http://www.sencha.com/license
  7. Open Source License
  8. ------------------------------------------------------------------------------------------
  9. This version of Ext JS is licensed under the terms of the Open Source GPL 3.0 license.
  10. http://www.gnu.org/licenses/gpl.html
  11. There are several FLOSS exceptions available for use with this release for
  12. open source applications that are distributed under a license other than GPL.
  13. * Open Source License Exception for Applications
  14. http://www.sencha.com/products/floss-exception.php
  15. * Open Source License Exception for Development
  16. http://www.sencha.com/products/ux-exception.php
  17. Alternate Licensing
  18. ------------------------------------------------------------------------------------------
  19. Commercial and OEM Licenses are available for an alternate download of Ext JS.
  20. This is the appropriate option if you are creating proprietary applications and you are
  21. not prepared to distribute and share the source code of your application under the
  22. GPL v3 license. Please visit http://www.sencha.com/license for more details.
  23. --
  24. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF THIRD-PARTY INTELLECTUAL PROPERTY RIGHTS. See the GNU General Public License for more details.
  25. */
  26. //@tag foundation,core
  27. /**
  28. * @class Ext
  29. * @singleton
  30. */
  31. var Ext = Ext || {};
  32. Ext._startTime = new Date().getTime();
  33. (function() {
  34. var global = this,
  35. objectPrototype = Object.prototype,
  36. toString = objectPrototype.toString,
  37. enumerables = true,
  38. enumerablesTest = { toString: 1 },
  39. emptyFn = function () {},
  40. // This is the "$previous" method of a hook function on an instance. When called, it
  41. // calls through the class prototype by the name of the called method.
  42. callOverrideParent = function () {
  43. var method = callOverrideParent.caller.caller; // skip callParent (our caller)
  44. return method.$owner.prototype[method.$name].apply(this, arguments);
  45. },
  46. i;
  47. Ext.global = global;
  48. for (i in enumerablesTest) {
  49. enumerables = null;
  50. }
  51. if (enumerables) {
  52. enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable',
  53. 'toLocaleString', 'toString', 'constructor'];
  54. }
  55. /**
  56. * An array containing extra enumerables for old browsers
  57. * @property {String[]}
  58. */
  59. Ext.enumerables = enumerables;
  60. /**
  61. * Copies all the properties of config to the specified object.
  62. * Note that if recursive merging and cloning without referencing the original objects / arrays is needed, use
  63. * {@link Ext.Object#merge} instead.
  64. * @param {Object} object The receiver of the properties
  65. * @param {Object} config The source of the properties
  66. * @param {Object} [defaults] A different object that will also be applied for default values
  67. * @return {Object} returns obj
  68. */
  69. Ext.apply = function(object, config, defaults) {
  70. if (defaults) {
  71. Ext.apply(object, defaults);
  72. }
  73. if (object && config && typeof config === 'object') {
  74. var i, j, k;
  75. for (i in config) {
  76. object[i] = config[i];
  77. }
  78. if (enumerables) {
  79. for (j = enumerables.length; j--;) {
  80. k = enumerables[j];
  81. if (config.hasOwnProperty(k)) {
  82. object[k] = config[k];
  83. }
  84. }
  85. }
  86. }
  87. return object;
  88. };
  89. Ext.buildSettings = Ext.apply({
  90. baseCSSPrefix: 'x-',
  91. scopeResetCSS: false
  92. }, Ext.buildSettings || {});
  93. Ext.apply(Ext, {
  94. /**
  95. * @property {String} [name='Ext']
  96. * <p>The name of the property in the global namespace (The <code>window</code> in browser environments) which refers to the current instance of Ext.</p>
  97. * <p>This is usually <code>"Ext"</code>, but if a sandboxed build of ExtJS is being used, this will be an alternative name.</p>
  98. * <p>If code is being generated for use by <code>eval</code> or to create a <code>new Function</code>, and the global instance
  99. * of Ext must be referenced, this is the name that should be built into the code.</p>
  100. */
  101. name: Ext.sandboxName || 'Ext',
  102. /**
  103. * A reusable empty function
  104. */
  105. emptyFn: emptyFn,
  106. /**
  107. * A zero length string which will pass a truth test. Useful for passing to methods
  108. * which use a truth test to reject <i>falsy</i> values where a string value must be cleared.
  109. */
  110. emptyString: new String(),
  111. baseCSSPrefix: Ext.buildSettings.baseCSSPrefix,
  112. /**
  113. * Copies all the properties of config to object if they don't already exist.
  114. * @param {Object} object The receiver of the properties
  115. * @param {Object} config The source of the properties
  116. * @return {Object} returns obj
  117. */
  118. applyIf: function(object, config) {
  119. var property;
  120. if (object) {
  121. for (property in config) {
  122. if (object[property] === undefined) {
  123. object[property] = config[property];
  124. }
  125. }
  126. }
  127. return object;
  128. },
  129. /**
  130. * Iterates either an array or an object. This method delegates to
  131. * {@link Ext.Array#each Ext.Array.each} if the given value is iterable, and {@link Ext.Object#each Ext.Object.each} otherwise.
  132. *
  133. * @param {Object/Array} object The object or array to be iterated.
  134. * @param {Function} fn The function to be called for each iteration. See and {@link Ext.Array#each Ext.Array.each} and
  135. * {@link Ext.Object#each Ext.Object.each} for detailed lists of arguments passed to this function depending on the given object
  136. * type that is being iterated.
  137. * @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed.
  138. * Defaults to the object being iterated itself.
  139. * @markdown
  140. */
  141. iterate: function(object, fn, scope) {
  142. if (Ext.isEmpty(object)) {
  143. return;
  144. }
  145. if (scope === undefined) {
  146. scope = object;
  147. }
  148. if (Ext.isIterable(object)) {
  149. Ext.Array.each.call(Ext.Array, object, fn, scope);
  150. }
  151. else {
  152. Ext.Object.each.call(Ext.Object, object, fn, scope);
  153. }
  154. }
  155. });
  156. Ext.apply(Ext, {
  157. /**
  158. * This method deprecated. Use {@link Ext#define Ext.define} instead.
  159. * @method
  160. * @param {Function} superclass
  161. * @param {Object} overrides
  162. * @return {Function} The subclass constructor from the <tt>overrides</tt> parameter, or a generated one if not provided.
  163. * @deprecated 4.0.0 Use {@link Ext#define Ext.define} instead
  164. */
  165. extend: (function() {
  166. // inline overrides
  167. var objectConstructor = objectPrototype.constructor,
  168. inlineOverrides = function(o) {
  169. for (var m in o) {
  170. if (!o.hasOwnProperty(m)) {
  171. continue;
  172. }
  173. this[m] = o[m];
  174. }
  175. };
  176. return function(subclass, superclass, overrides) {
  177. // First we check if the user passed in just the superClass with overrides
  178. if (Ext.isObject(superclass)) {
  179. overrides = superclass;
  180. superclass = subclass;
  181. subclass = overrides.constructor !== objectConstructor ? overrides.constructor : function() {
  182. superclass.apply(this, arguments);
  183. };
  184. }
  185. if (!superclass) {
  186. Ext.Error.raise({
  187. sourceClass: 'Ext',
  188. sourceMethod: 'extend',
  189. msg: 'Attempting to extend from a class which has not been loaded on the page.'
  190. });
  191. }
  192. // We create a new temporary class
  193. var F = function() {},
  194. subclassProto, superclassProto = superclass.prototype;
  195. F.prototype = superclassProto;
  196. subclassProto = subclass.prototype = new F();
  197. subclassProto.constructor = subclass;
  198. subclass.superclass = superclassProto;
  199. if (superclassProto.constructor === objectConstructor) {
  200. superclassProto.constructor = superclass;
  201. }
  202. subclass.override = function(overrides) {
  203. Ext.override(subclass, overrides);
  204. };
  205. subclassProto.override = inlineOverrides;
  206. subclassProto.proto = subclassProto;
  207. subclass.override(overrides);
  208. subclass.extend = function(o) {
  209. return Ext.extend(subclass, o);
  210. };
  211. return subclass;
  212. };
  213. }()),
  214. /**
  215. * Overrides members of the specified `target` with the given values.
  216. *
  217. * If the `target` is a class declared using {@link Ext#define Ext.define}, the
  218. * `override` method of that class is called (see {@link Ext.Base#override}) given
  219. * the `overrides`.
  220. *
  221. * If the `target` is a function, it is assumed to be a constructor and the contents
  222. * of `overrides` are applied to its `prototype` using {@link Ext#apply Ext.apply}.
  223. *
  224. * If the `target` is an instance of a class declared using {@link Ext#define Ext.define},
  225. * the `overrides` are applied to only that instance. In this case, methods are
  226. * specially processed to allow them to use {@link Ext.Base#callParent}.
  227. *
  228. * var panel = new Ext.Panel({ ... });
  229. *
  230. * Ext.override(panel, {
  231. * initComponent: function () {
  232. * // extra processing...
  233. *
  234. * this.callParent();
  235. * }
  236. * });
  237. *
  238. * If the `target` is none of these, the `overrides` are applied to the `target`
  239. * using {@link Ext#apply Ext.apply}.
  240. *
  241. * Please refer to {@link Ext#define Ext.define} and {@link Ext.Base#override} for
  242. * further details.
  243. *
  244. * @param {Object} target The target to override.
  245. * @param {Object} overrides The properties to add or replace on `target`.
  246. * @method override
  247. */
  248. override: function (target, overrides) {
  249. if (target.$isClass) {
  250. target.override(overrides);
  251. } else if (typeof target == 'function') {
  252. Ext.apply(target.prototype, overrides);
  253. } else {
  254. var owner = target.self,
  255. name, value;
  256. if (owner && owner.$isClass) { // if (instance of Ext.define'd class)
  257. for (name in overrides) {
  258. if (overrides.hasOwnProperty(name)) {
  259. value = overrides[name];
  260. if (typeof value == 'function') {
  261. if (owner.$className) {
  262. value.displayName = owner.$className + '#' + name;
  263. }
  264. value.$name = name;
  265. value.$owner = owner;
  266. value.$previous = target.hasOwnProperty(name)
  267. ? target[name] // already hooked, so call previous hook
  268. : callOverrideParent; // calls by name on prototype
  269. }
  270. target[name] = value;
  271. }
  272. }
  273. } else {
  274. Ext.apply(target, overrides);
  275. }
  276. }
  277. return target;
  278. }
  279. });
  280. // A full set of static methods to do type checking
  281. Ext.apply(Ext, {
  282. /**
  283. * Returns the given value itself if it's not empty, as described in {@link Ext#isEmpty}; returns the default
  284. * value (second argument) otherwise.
  285. *
  286. * @param {Object} value The value to test
  287. * @param {Object} defaultValue The value to return if the original value is empty
  288. * @param {Boolean} allowBlank (optional) true to allow zero length strings to qualify as non-empty (defaults to false)
  289. * @return {Object} value, if non-empty, else defaultValue
  290. */
  291. valueFrom: function(value, defaultValue, allowBlank){
  292. return Ext.isEmpty(value, allowBlank) ? defaultValue : value;
  293. },
  294. /**
  295. * Returns the type of the given variable in string format. List of possible values are:
  296. *
  297. * - `undefined`: If the given value is `undefined`
  298. * - `null`: If the given value is `null`
  299. * - `string`: If the given value is a string
  300. * - `number`: If the given value is a number
  301. * - `boolean`: If the given value is a boolean value
  302. * - `date`: If the given value is a `Date` object
  303. * - `function`: If the given value is a function reference
  304. * - `object`: If the given value is an object
  305. * - `array`: If the given value is an array
  306. * - `regexp`: If the given value is a regular expression
  307. * - `element`: If the given value is a DOM Element
  308. * - `textnode`: If the given value is a DOM text node and contains something other than whitespace
  309. * - `whitespace`: If the given value is a DOM text node and contains only whitespace
  310. *
  311. * @param {Object} value
  312. * @return {String}
  313. * @markdown
  314. */
  315. typeOf: function(value) {
  316. var type,
  317. typeToString;
  318. if (value === null) {
  319. return 'null';
  320. }
  321. type = typeof value;
  322. if (type === 'undefined' || type === 'string' || type === 'number' || type === 'boolean') {
  323. return type;
  324. }
  325. typeToString = toString.call(value);
  326. switch(typeToString) {
  327. case '[object Array]':
  328. return 'array';
  329. case '[object Date]':
  330. return 'date';
  331. case '[object Boolean]':
  332. return 'boolean';
  333. case '[object Number]':
  334. return 'number';
  335. case '[object RegExp]':
  336. return 'regexp';
  337. }
  338. if (type === 'function') {
  339. return 'function';
  340. }
  341. if (type === 'object') {
  342. if (value.nodeType !== undefined) {
  343. if (value.nodeType === 3) {
  344. return (/\S/).test(value.nodeValue) ? 'textnode' : 'whitespace';
  345. }
  346. else {
  347. return 'element';
  348. }
  349. }
  350. return 'object';
  351. }
  352. Ext.Error.raise({
  353. sourceClass: 'Ext',
  354. sourceMethod: 'typeOf',
  355. msg: 'Failed to determine the type of the specified value "' + value + '". This is most likely a bug.'
  356. });
  357. },
  358. /**
  359. * Returns true if the passed value is empty, false otherwise. The value is deemed to be empty if it is either:
  360. *
  361. * - `null`
  362. * - `undefined`
  363. * - a zero-length array
  364. * - a zero-length string (Unless the `allowEmptyString` parameter is set to `true`)
  365. *
  366. * @param {Object} value The value to test
  367. * @param {Boolean} allowEmptyString (optional) true to allow empty strings (defaults to false)
  368. * @return {Boolean}
  369. * @markdown
  370. */
  371. isEmpty: function(value, allowEmptyString) {
  372. return (value === null) || (value === undefined) || (!allowEmptyString ? value === '' : false) || (Ext.isArray(value) && value.length === 0);
  373. },
  374. /**
  375. * Returns true if the passed value is a JavaScript Array, false otherwise.
  376. *
  377. * @param {Object} target The target to test
  378. * @return {Boolean}
  379. * @method
  380. */
  381. isArray: ('isArray' in Array) ? Array.isArray : function(value) {
  382. return toString.call(value) === '[object Array]';
  383. },
  384. /**
  385. * Returns true if the passed value is a JavaScript Date object, false otherwise.
  386. * @param {Object} object The object to test
  387. * @return {Boolean}
  388. */
  389. isDate: function(value) {
  390. return toString.call(value) === '[object Date]';
  391. },
  392. /**
  393. * Returns true if the passed value is a JavaScript Object, false otherwise.
  394. * @param {Object} value The value to test
  395. * @return {Boolean}
  396. * @method
  397. */
  398. isObject: (toString.call(null) === '[object Object]') ?
  399. function(value) {
  400. // check ownerDocument here as well to exclude DOM nodes
  401. return value !== null && value !== undefined && toString.call(value) === '[object Object]' && value.ownerDocument === undefined;
  402. } :
  403. function(value) {
  404. return toString.call(value) === '[object Object]';
  405. },
  406. /**
  407. * @private
  408. */
  409. isSimpleObject: function(value) {
  410. return value instanceof Object && value.constructor === Object;
  411. },
  412. /**
  413. * Returns true if the passed value is a JavaScript 'primitive', a string, number or boolean.
  414. * @param {Object} value The value to test
  415. * @return {Boolean}
  416. */
  417. isPrimitive: function(value) {
  418. var type = typeof value;
  419. return type === 'string' || type === 'number' || type === 'boolean';
  420. },
  421. /**
  422. * Returns true if the passed value is a JavaScript Function, false otherwise.
  423. * @param {Object} value The value to test
  424. * @return {Boolean}
  425. * @method
  426. */
  427. isFunction:
  428. // Safari 3.x and 4.x returns 'function' for typeof <NodeList>, hence we need to fall back to using
  429. // Object.prototype.toString (slower)
  430. (typeof document !== 'undefined' && typeof document.getElementsByTagName('body') === 'function') ? function(value) {
  431. return toString.call(value) === '[object Function]';
  432. } : function(value) {
  433. return typeof value === 'function';
  434. },
  435. /**
  436. * Returns true if the passed value is a number. Returns false for non-finite numbers.
  437. * @param {Object} value The value to test
  438. * @return {Boolean}
  439. */
  440. isNumber: function(value) {
  441. return typeof value === 'number' && isFinite(value);
  442. },
  443. /**
  444. * Validates that a value is numeric.
  445. * @param {Object} value Examples: 1, '1', '2.34'
  446. * @return {Boolean} True if numeric, false otherwise
  447. */
  448. isNumeric: function(value) {
  449. return !isNaN(parseFloat(value)) && isFinite(value);
  450. },
  451. /**
  452. * Returns true if the passed value is a string.
  453. * @param {Object} value The value to test
  454. * @return {Boolean}
  455. */
  456. isString: function(value) {
  457. return typeof value === 'string';
  458. },
  459. /**
  460. * Returns true if the passed value is a boolean.
  461. *
  462. * @param {Object} value The value to test
  463. * @return {Boolean}
  464. */
  465. isBoolean: function(value) {
  466. return typeof value === 'boolean';
  467. },
  468. /**
  469. * Returns true if the passed value is an HTMLElement
  470. * @param {Object} value The value to test
  471. * @return {Boolean}
  472. */
  473. isElement: function(value) {
  474. return value ? value.nodeType === 1 : false;
  475. },
  476. /**
  477. * Returns true if the passed value is a TextNode
  478. * @param {Object} value The value to test
  479. * @return {Boolean}
  480. */
  481. isTextNode: function(value) {
  482. return value ? value.nodeName === "#text" : false;
  483. },
  484. /**
  485. * Returns true if the passed value is defined.
  486. * @param {Object} value The value to test
  487. * @return {Boolean}
  488. */
  489. isDefined: function(value) {
  490. return typeof value !== 'undefined';
  491. },
  492. /**
  493. * Returns true if the passed value is iterable, false otherwise
  494. * @param {Object} value The value to test
  495. * @return {Boolean}
  496. */
  497. isIterable: function(value) {
  498. var type = typeof value,
  499. checkLength = false;
  500. if (value && type != 'string') {
  501. // Functions have a length property, so we need to filter them out
  502. if (type == 'function') {
  503. // In Safari, NodeList/HTMLCollection both return "function" when using typeof, so we need
  504. // to explicitly check them here.
  505. if (Ext.isSafari) {
  506. checkLength = value instanceof NodeList || value instanceof HTMLCollection;
  507. }
  508. } else {
  509. checkLength = true;
  510. }
  511. }
  512. return checkLength ? value.length !== undefined : false;
  513. }
  514. });
  515. Ext.apply(Ext, {
  516. /**
  517. * Clone simple variables including array, {}-like objects, DOM nodes and Date without keeping the old reference.
  518. * A reference for the object itself is returned if it's not a direct decendant of Object. For model cloning,
  519. * see {@link Ext.data.Model#copy Model.copy}.
  520. *
  521. * @param {Object} item The variable to clone
  522. * @return {Object} clone
  523. */
  524. clone: function(item) {
  525. var type,
  526. i,
  527. j,
  528. k,
  529. clone,
  530. key;
  531. if (item === null || item === undefined) {
  532. return item;
  533. }
  534. // DOM nodes
  535. // TODO proxy this to Ext.Element.clone to handle automatic id attribute changing
  536. // recursively
  537. if (item.nodeType && item.cloneNode) {
  538. return item.cloneNode(true);
  539. }
  540. type = toString.call(item);
  541. // Date
  542. if (type === '[object Date]') {
  543. return new Date(item.getTime());
  544. }
  545. // Array
  546. if (type === '[object Array]') {
  547. i = item.length;
  548. clone = [];
  549. while (i--) {
  550. clone[i] = Ext.clone(item[i]);
  551. }
  552. }
  553. // Object
  554. else if (type === '[object Object]' && item.constructor === Object) {
  555. clone = {};
  556. for (key in item) {
  557. clone[key] = Ext.clone(item[key]);
  558. }
  559. if (enumerables) {
  560. for (j = enumerables.length; j--;) {
  561. k = enumerables[j];
  562. clone[k] = item[k];
  563. }
  564. }
  565. }
  566. return clone || item;
  567. },
  568. /**
  569. * @private
  570. * Generate a unique reference of Ext in the global scope, useful for sandboxing
  571. */
  572. getUniqueGlobalNamespace: function() {
  573. var uniqueGlobalNamespace = this.uniqueGlobalNamespace,
  574. i;
  575. if (uniqueGlobalNamespace === undefined) {
  576. i = 0;
  577. do {
  578. uniqueGlobalNamespace = 'ExtBox' + (++i);
  579. } while (Ext.global[uniqueGlobalNamespace] !== undefined);
  580. Ext.global[uniqueGlobalNamespace] = Ext;
  581. this.uniqueGlobalNamespace = uniqueGlobalNamespace;
  582. }
  583. return uniqueGlobalNamespace;
  584. },
  585. /**
  586. * @private
  587. */
  588. functionFactoryCache: {},
  589. cacheableFunctionFactory: function() {
  590. var me = this,
  591. args = Array.prototype.slice.call(arguments),
  592. cache = me.functionFactoryCache,
  593. idx, fn, ln;
  594. if (Ext.isSandboxed) {
  595. ln = args.length;
  596. if (ln > 0) {
  597. ln--;
  598. args[ln] = 'var Ext=window.' + Ext.name + ';' + args[ln];
  599. }
  600. }
  601. idx = args.join('');
  602. fn = cache[idx];
  603. if (!fn) {
  604. fn = Function.prototype.constructor.apply(Function.prototype, args);
  605. cache[idx] = fn;
  606. }
  607. return fn;
  608. },
  609. functionFactory: function() {
  610. var me = this,
  611. args = Array.prototype.slice.call(arguments),
  612. ln;
  613. if (Ext.isSandboxed) {
  614. ln = args.length;
  615. if (ln > 0) {
  616. ln--;
  617. args[ln] = 'var Ext=window.' + Ext.name + ';' + args[ln];
  618. }
  619. }
  620. return Function.prototype.constructor.apply(Function.prototype, args);
  621. },
  622. /**
  623. * @private
  624. * @property
  625. */
  626. Logger: {
  627. verbose: emptyFn,
  628. log: emptyFn,
  629. info: emptyFn,
  630. warn: emptyFn,
  631. error: function(message) {
  632. throw new Error(message);
  633. },
  634. deprecate: emptyFn
  635. }
  636. });
  637. /**
  638. * Old alias to {@link Ext#typeOf}
  639. * @deprecated 4.0.0 Use {@link Ext#typeOf} instead
  640. * @method
  641. * @inheritdoc Ext#typeOf
  642. */
  643. Ext.type = Ext.typeOf;
  644. }());
  645. /*
  646. * This method evaluates the given code free of any local variable. In some browsers this
  647. * will be at global scope, in others it will be in a function.
  648. * @parma {String} code The code to evaluate.
  649. * @private
  650. * @method
  651. */
  652. Ext.globalEval = Ext.global.execScript
  653. ? function(code) {
  654. execScript(code);
  655. }
  656. : function($$code) {
  657. // IMPORTANT: because we use eval we cannot place this in the above function or it
  658. // will break the compressor's ability to rename local variables...
  659. (function(){
  660. eval($$code);
  661. }());
  662. };
  663. //@tag foundation,core
  664. //@require ../Ext.js
  665. /**
  666. * @author Jacky Nguyen <jacky@sencha.com>
  667. * @docauthor Jacky Nguyen <jacky@sencha.com>
  668. * @class Ext.Version
  669. *
  670. * A utility class that wrap around a string version number and provide convenient
  671. * method to perform comparison. See also: {@link Ext.Version#compare compare}. Example:
  672. *
  673. * var version = new Ext.Version('1.0.2beta');
  674. * console.log("Version is " + version); // Version is 1.0.2beta
  675. *
  676. * console.log(version.getMajor()); // 1
  677. * console.log(version.getMinor()); // 0
  678. * console.log(version.getPatch()); // 2
  679. * console.log(version.getBuild()); // 0
  680. * console.log(version.getRelease()); // beta
  681. *
  682. * console.log(version.isGreaterThan('1.0.1')); // True
  683. * console.log(version.isGreaterThan('1.0.2alpha')); // True
  684. * console.log(version.isGreaterThan('1.0.2RC')); // False
  685. * console.log(version.isGreaterThan('1.0.2')); // False
  686. * console.log(version.isLessThan('1.0.2')); // True
  687. *
  688. * console.log(version.match(1.0)); // True
  689. * console.log(version.match('1.0.2')); // True
  690. *
  691. */
  692. (function() {
  693. // Current core version
  694. var version = '4.1.1.1', Version;
  695. Ext.Version = Version = Ext.extend(Object, {
  696. /**
  697. * @param {String/Number} version The version number in the following standard format:
  698. *
  699. * major[.minor[.patch[.build[release]]]]
  700. *
  701. * Examples:
  702. *
  703. * 1.0
  704. * 1.2.3beta
  705. * 1.2.3.4RC
  706. *
  707. * @return {Ext.Version} this
  708. */
  709. constructor: function(version) {
  710. var parts, releaseStartIndex;
  711. if (version instanceof Version) {
  712. return version;
  713. }
  714. this.version = this.shortVersion = String(version).toLowerCase().replace(/_/g, '.').replace(/[\-+]/g, '');
  715. releaseStartIndex = this.version.search(/([^\d\.])/);
  716. if (releaseStartIndex !== -1) {
  717. this.release = this.version.substr(releaseStartIndex, version.length);
  718. this.shortVersion = this.version.substr(0, releaseStartIndex);
  719. }
  720. this.shortVersion = this.shortVersion.replace(/[^\d]/g, '');
  721. parts = this.version.split('.');
  722. this.major = parseInt(parts.shift() || 0, 10);
  723. this.minor = parseInt(parts.shift() || 0, 10);
  724. this.patch = parseInt(parts.shift() || 0, 10);
  725. this.build = parseInt(parts.shift() || 0, 10);
  726. return this;
  727. },
  728. /**
  729. * Override the native toString method
  730. * @private
  731. * @return {String} version
  732. */
  733. toString: function() {
  734. return this.version;
  735. },
  736. /**
  737. * Override the native valueOf method
  738. * @private
  739. * @return {String} version
  740. */
  741. valueOf: function() {
  742. return this.version;
  743. },
  744. /**
  745. * Returns the major component value
  746. * @return {Number} major
  747. */
  748. getMajor: function() {
  749. return this.major || 0;
  750. },
  751. /**
  752. * Returns the minor component value
  753. * @return {Number} minor
  754. */
  755. getMinor: function() {
  756. return this.minor || 0;
  757. },
  758. /**
  759. * Returns the patch component value
  760. * @return {Number} patch
  761. */
  762. getPatch: function() {
  763. return this.patch || 0;
  764. },
  765. /**
  766. * Returns the build component value
  767. * @return {Number} build
  768. */
  769. getBuild: function() {
  770. return this.build || 0;
  771. },
  772. /**
  773. * Returns the release component value
  774. * @return {Number} release
  775. */
  776. getRelease: function() {
  777. return this.release || '';
  778. },
  779. /**
  780. * Returns whether this version if greater than the supplied argument
  781. * @param {String/Number} target The version to compare with
  782. * @return {Boolean} True if this version if greater than the target, false otherwise
  783. */
  784. isGreaterThan: function(target) {
  785. return Version.compare(this.version, target) === 1;
  786. },
  787. /**
  788. * Returns whether this version if greater than or equal to the supplied argument
  789. * @param {String/Number} target The version to compare with
  790. * @return {Boolean} True if this version if greater than or equal to the target, false otherwise
  791. */
  792. isGreaterThanOrEqual: function(target) {
  793. return Version.compare(this.version, target) >= 0;
  794. },
  795. /**
  796. * Returns whether this version if smaller than the supplied argument
  797. * @param {String/Number} target The version to compare with
  798. * @return {Boolean} True if this version if smaller than the target, false otherwise
  799. */
  800. isLessThan: function(target) {
  801. return Version.compare(this.version, target) === -1;
  802. },
  803. /**
  804. * Returns whether this version if less than or equal to the supplied argument
  805. * @param {String/Number} target The version to compare with
  806. * @return {Boolean} True if this version if less than or equal to the target, false otherwise
  807. */
  808. isLessThanOrEqual: function(target) {
  809. return Version.compare(this.version, target) <= 0;
  810. },
  811. /**
  812. * Returns whether this version equals to the supplied argument
  813. * @param {String/Number} target The version to compare with
  814. * @return {Boolean} True if this version equals to the target, false otherwise
  815. */
  816. equals: function(target) {
  817. return Version.compare(this.version, target) === 0;
  818. },
  819. /**
  820. * Returns whether this version matches the supplied argument. Example:
  821. *
  822. * var version = new Ext.Version('1.0.2beta');
  823. * console.log(version.match(1)); // True
  824. * console.log(version.match(1.0)); // True
  825. * console.log(version.match('1.0.2')); // True
  826. * console.log(version.match('1.0.2RC')); // False
  827. *
  828. * @param {String/Number} target The version to compare with
  829. * @return {Boolean} True if this version matches the target, false otherwise
  830. */
  831. match: function(target) {
  832. target = String(target);
  833. return this.version.substr(0, target.length) === target;
  834. },
  835. /**
  836. * Returns this format: [major, minor, patch, build, release]. Useful for comparison
  837. * @return {Number[]}
  838. */
  839. toArray: function() {
  840. return [this.getMajor(), this.getMinor(), this.getPatch(), this.getBuild(), this.getRelease()];
  841. },
  842. /**
  843. * Returns shortVersion version without dots and release
  844. * @return {String}
  845. */
  846. getShortVersion: function() {
  847. return this.shortVersion;
  848. },
  849. /**
  850. * Convenient alias to {@link Ext.Version#isGreaterThan isGreaterThan}
  851. * @param {String/Number} target
  852. * @return {Boolean}
  853. */
  854. gt: function() {
  855. return this.isGreaterThan.apply(this, arguments);
  856. },
  857. /**
  858. * Convenient alias to {@link Ext.Version#isLessThan isLessThan}
  859. * @param {String/Number} target
  860. * @return {Boolean}
  861. */
  862. lt: function() {
  863. return this.isLessThan.apply(this, arguments);
  864. },
  865. /**
  866. * Convenient alias to {@link Ext.Version#isGreaterThanOrEqual isGreaterThanOrEqual}
  867. * @param {String/Number} target
  868. * @return {Boolean}
  869. */
  870. gtEq: function() {
  871. return this.isGreaterThanOrEqual.apply(this, arguments);
  872. },
  873. /**
  874. * Convenient alias to {@link Ext.Version#isLessThanOrEqual isLessThanOrEqual}
  875. * @param {String/Number} target
  876. * @return {Boolean}
  877. */
  878. ltEq: function() {
  879. return this.isLessThanOrEqual.apply(this, arguments);
  880. }
  881. });
  882. Ext.apply(Version, {
  883. // @private
  884. releaseValueMap: {
  885. 'dev': -6,
  886. 'alpha': -5,
  887. 'a': -5,
  888. 'beta': -4,
  889. 'b': -4,
  890. 'rc': -3,
  891. '#': -2,
  892. 'p': -1,
  893. 'pl': -1
  894. },
  895. /**
  896. * Converts a version component to a comparable value
  897. *
  898. * @static
  899. * @param {Object} value The value to convert
  900. * @return {Object}
  901. */
  902. getComponentValue: function(value) {
  903. return !value ? 0 : (isNaN(value) ? this.releaseValueMap[value] || value : parseInt(value, 10));
  904. },
  905. /**
  906. * Compare 2 specified versions, starting from left to right. If a part contains special version strings,
  907. * they are handled in the following order:
  908. * 'dev' < 'alpha' = 'a' < 'beta' = 'b' < 'RC' = 'rc' < '#' < 'pl' = 'p' < 'anything else'
  909. *
  910. * @static
  911. * @param {String} current The current version to compare to
  912. * @param {String} target The target version to compare to
  913. * @return {Number} Returns -1 if the current version is smaller than the target version, 1 if greater, and 0 if they're equivalent
  914. */
  915. compare: function(current, target) {
  916. var currentValue, targetValue, i;
  917. current = new Version(current).toArray();
  918. target = new Version(target).toArray();
  919. for (i = 0; i < Math.max(current.length, target.length); i++) {
  920. currentValue = this.getComponentValue(current[i]);
  921. targetValue = this.getComponentValue(target[i]);
  922. if (currentValue < targetValue) {
  923. return -1;
  924. } else if (currentValue > targetValue) {
  925. return 1;
  926. }
  927. }
  928. return 0;
  929. }
  930. });
  931. /**
  932. * @class Ext
  933. */
  934. Ext.apply(Ext, {
  935. /**
  936. * @private
  937. */
  938. versions: {},
  939. /**
  940. * @private
  941. */
  942. lastRegisteredVersion: null,
  943. /**
  944. * Set version number for the given package name.
  945. *
  946. * @param {String} packageName The package name, for example: 'core', 'touch', 'extjs'
  947. * @param {String/Ext.Version} version The version, for example: '1.2.3alpha', '2.4.0-dev'
  948. * @return {Ext}
  949. */
  950. setVersion: function(packageName, version) {
  951. Ext.versions[packageName] = new Version(version);
  952. Ext.lastRegisteredVersion = Ext.versions[packageName];
  953. return this;
  954. },
  955. /**
  956. * Get the version number of the supplied package name; will return the last registered version
  957. * (last Ext.setVersion call) if there's no package name given.
  958. *
  959. * @param {String} packageName (Optional) The package name, for example: 'core', 'touch', 'extjs'
  960. * @return {Ext.Version} The version
  961. */
  962. getVersion: function(packageName) {
  963. if (packageName === undefined) {
  964. return Ext.lastRegisteredVersion;
  965. }
  966. return Ext.versions[packageName];
  967. },
  968. /**
  969. * Create a closure for deprecated code.
  970. *
  971. * // This means Ext.oldMethod is only supported in 4.0.0beta and older.
  972. * // If Ext.getVersion('extjs') returns a version that is later than '4.0.0beta', for example '4.0.0RC',
  973. * // the closure will not be invoked
  974. * Ext.deprecate('extjs', '4.0.0beta', function() {
  975. * Ext.oldMethod = Ext.newMethod;
  976. *
  977. * ...
  978. * });
  979. *
  980. * @param {String} packageName The package name
  981. * @param {String} since The last version before it's deprecated
  982. * @param {Function} closure The callback function to be executed with the specified version is less than the current version
  983. * @param {Object} scope The execution scope (`this`) if the closure
  984. */
  985. deprecate: function(packageName, since, closure, scope) {
  986. if (Version.compare(Ext.getVersion(packageName), since) < 1) {
  987. closure.call(scope);
  988. }
  989. }
  990. }); // End Versioning
  991. Ext.setVersion('core', version);
  992. }());
  993. //@tag foundation,core
  994. //@require ../version/Version.js
  995. /**
  996. * @class Ext.String
  997. *
  998. * A collection of useful static methods to deal with strings
  999. * @singleton
  1000. */
  1001. Ext.String = (function() {
  1002. var trimRegex = /^[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+|[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+$/g,
  1003. escapeRe = /('|\\)/g,
  1004. formatRe = /\{(\d+)\}/g,
  1005. escapeRegexRe = /([-.*+?\^${}()|\[\]\/\\])/g,
  1006. basicTrimRe = /^\s+|\s+$/g,
  1007. whitespaceRe = /\s+/,
  1008. varReplace = /(^[^a-z]*|[^\w])/gi,
  1009. charToEntity,
  1010. entityToChar,
  1011. charToEntityRegex,
  1012. entityToCharRegex,
  1013. htmlEncodeReplaceFn = function(match, capture) {
  1014. return charToEntity[capture];
  1015. },
  1016. htmlDecodeReplaceFn = function(match, capture) {
  1017. return (capture in entityToChar) ? entityToChar[capture] : String.fromCharCode(parseInt(capture.substr(2), 10));
  1018. };
  1019. return {
  1020. /**
  1021. * Converts a string of characters into a legal, parseable Javascript `var` name as long as the passed
  1022. * string contains at least one alphabetic character. Non alphanumeric characters, and *leading* non alphabetic
  1023. * characters will be removed.
  1024. * @param {String} s A string to be converted into a `var` name.
  1025. * @return {String} A legal Javascript `var` name.
  1026. */
  1027. createVarName: function(s) {
  1028. return s.replace(varReplace, '');
  1029. },
  1030. /**
  1031. * Convert certain characters (&, <, >, ', and ") to their HTML character equivalents for literal display in web pages.
  1032. * @param {String} value The string to encode
  1033. * @return {String} The encoded text
  1034. * @method
  1035. */
  1036. htmlEncode: function(value) {
  1037. return (!value) ? value : String(value).replace(charToEntityRegex, htmlEncodeReplaceFn);
  1038. },
  1039. /**
  1040. * Convert certain characters (&, <, >, ', and ") from their HTML character equivalents.
  1041. * @param {String} value The string to decode
  1042. * @return {String} The decoded text
  1043. * @method
  1044. */
  1045. htmlDecode: function(value) {
  1046. return (!value) ? value : String(value).replace(entityToCharRegex, htmlDecodeReplaceFn);
  1047. },
  1048. /**
  1049. * Adds a set of character entity definitions to the set used by
  1050. * {@link Ext.String#htmlEncode} and {@link Ext.String#htmlDecode}.
  1051. *
  1052. * This object should be keyed by the entity name sequence,
  1053. * with the value being the textual representation of the entity.
  1054. *
  1055. * Ext.String.addCharacterEntities({
  1056. * '&amp;Uuml;':'Ü',
  1057. * '&amp;ccedil;':'ç',
  1058. * '&amp;ntilde;':'ñ',
  1059. * '&amp;egrave;':'è'
  1060. * });
  1061. * var s = Ext.String.htmlEncode("A string with entities: èÜçñ");
  1062. *
  1063. * Note: the values of the character entites defined on this object are expected
  1064. * to be single character values. As such, the actual values represented by the
  1065. * characters are sensitive to the character encoding of the javascript source
  1066. * file when defined in string literal form. Script tasgs referencing server
  1067. * resources with character entities must ensure that the 'charset' attribute
  1068. * of the script node is consistent with the actual character encoding of the
  1069. * server resource.
  1070. *
  1071. * The set of character entities may be reset back to the default state by using
  1072. * the {@link Ext.String#resetCharacterEntities} method
  1073. *
  1074. * @param {Object} entities The set of character entities to add to the current
  1075. * definitions.
  1076. */
  1077. addCharacterEntities: function(newEntities) {
  1078. var charKeys = [],
  1079. entityKeys = [],
  1080. key, echar;
  1081. for (key in newEntities) {
  1082. echar = newEntities[key];
  1083. entityToChar[key] = echar;
  1084. charToEntity[echar] = key;
  1085. charKeys.push(echar);
  1086. entityKeys.push(key);
  1087. }
  1088. charToEntityRegex = new RegExp('(' + charKeys.join('|') + ')', 'g');
  1089. entityToCharRegex = new RegExp('(' + entityKeys.join('|') + '|&#[0-9]{1,5};' + ')', 'g');
  1090. },
  1091. /**
  1092. * Resets the set of character entity definitions used by
  1093. * {@link Ext.String#htmlEncode} and {@link Ext.String#htmlDecode} back to the
  1094. * default state.
  1095. */
  1096. resetCharacterEntities: function() {
  1097. charToEntity = {};
  1098. entityToChar = {};
  1099. // add the default set
  1100. this.addCharacterEntities({
  1101. '&amp;' : '&',
  1102. '&gt;' : '>',
  1103. '&lt;' : '<',
  1104. '&quot;' : '"',
  1105. '&#39;' : "'"
  1106. });
  1107. },
  1108. /**
  1109. * Appends content to the query string of a URL, handling logic for whether to place
  1110. * a question mark or ampersand.
  1111. * @param {String} url The URL to append to.
  1112. * @param {String} string The content to append to the URL.
  1113. * @return {String} The resulting URL
  1114. */
  1115. urlAppend : function(url, string) {
  1116. if (!Ext.isEmpty(string)) {
  1117. return url + (url.indexOf('?') === -1 ? '?' : '&') + string;
  1118. }
  1119. return url;
  1120. },
  1121. /**
  1122. * Trims whitespace from either end of a string, leaving spaces within the string intact. Example:
  1123. * @example
  1124. var s = ' foo bar ';
  1125. alert('-' + s + '-'); //alerts "- foo bar -"
  1126. alert('-' + Ext.String.trim(s) + '-'); //alerts "-foo bar-"
  1127. * @param {String} string The string to escape
  1128. * @return {String} The trimmed string
  1129. */
  1130. trim: function(string) {
  1131. return string.replace(trimRegex, "");
  1132. },
  1133. /**
  1134. * Capitalize the given string
  1135. * @param {String} string
  1136. * @return {String}
  1137. */
  1138. capitalize: function(string) {
  1139. return string.charAt(0).toUpperCase() + string.substr(1);
  1140. },
  1141. /**
  1142. * Uncapitalize the given string
  1143. * @param {String} string
  1144. * @return {String}
  1145. */
  1146. uncapitalize: function(string) {
  1147. return string.charAt(0).toLowerCase() + string.substr(1);
  1148. },
  1149. /**
  1150. * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
  1151. * @param {String} value The string to truncate
  1152. * @param {Number} length The maximum length to allow before truncating
  1153. * @param {Boolean} word True to try to find a common word break
  1154. * @return {String} The converted text
  1155. */
  1156. ellipsis: function(value, len, word) {
  1157. if (value && value.length > len) {
  1158. if (word) {
  1159. var vs = value.substr(0, len - 2),
  1160. index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?'));
  1161. if (index !== -1 && index >= (len - 15)) {
  1162. return vs.substr(0, index) + "...";
  1163. }
  1164. }
  1165. return value.substr(0, len - 3) + "...";
  1166. }
  1167. return value;
  1168. },
  1169. /**
  1170. * Escapes the passed string for use in a regular expression
  1171. * @param {String} string
  1172. * @return {String}
  1173. */
  1174. escapeRegex: function(string) {
  1175. return string.replace(escapeRegexRe, "\\$1");
  1176. },
  1177. /**
  1178. * Escapes the passed string for ' and \
  1179. * @param {String} string The string to escape
  1180. * @return {String} The escaped string
  1181. */
  1182. escape: function(string) {
  1183. return string.replace(escapeRe, "\\$1");
  1184. },
  1185. /**
  1186. * Utility function that allows you to easily switch a string between two alternating values. The passed value
  1187. * is compared to the current string, and if they are equal, the other value that was passed in is returned. If
  1188. * they are already different, the first value passed in is returned. Note that this method returns the new value
  1189. * but does not change the current string.
  1190. * <pre><code>
  1191. // alternate sort directions
  1192. sort = Ext.String.toggle(sort, 'ASC', 'DESC');
  1193. // instead of conditional logic:
  1194. sort = (sort == 'ASC' ? 'DESC' : 'ASC');
  1195. </code></pre>
  1196. * @param {String} string The current string
  1197. * @param {String} value The value to compare to the current string
  1198. * @param {String} other The new value to use if the string already equals the first value passed in
  1199. * @return {String} The new value
  1200. */
  1201. toggle: function(string, value, other) {
  1202. return string === value ? other : value;
  1203. },
  1204. /**
  1205. * Pads the left side of a string with a specified character. This is especially useful
  1206. * for normalizing number and date strings. Example usage:
  1207. *
  1208. * <pre><code>
  1209. var s = Ext.String.leftPad('123', 5, '0');
  1210. // s now contains the string: '00123'
  1211. </code></pre>
  1212. * @param {String} string The original string
  1213. * @param {Number} size The total length of the output string
  1214. * @param {String} character (optional) The character with which to pad the original string (defaults to empty string " ")
  1215. * @return {String} The padded string
  1216. */
  1217. leftPad: function(string, size, character) {
  1218. var result = String(string);
  1219. character = character || " ";
  1220. while (result.length < size) {
  1221. result = character + result;
  1222. }
  1223. return result;
  1224. },
  1225. /**
  1226. * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
  1227. * token must be unique, and must increment in the format {0}, {1}, etc. Example usage:
  1228. * <pre><code>
  1229. var cls = 'my-class', text = 'Some text';
  1230. var s = Ext.String.format('&lt;div class="{0}">{1}&lt;/div>', cls, text);
  1231. // s now contains the string: '&lt;div class="my-class">Some text&lt;/div>'
  1232. </code></pre>
  1233. * @param {String} string The tokenized string to be formatted
  1234. * @param {String} value1 The value to replace token {0}
  1235. * @param {String} value2 Etc...
  1236. * @return {String} The formatted string
  1237. */
  1238. format: function(format) {
  1239. var args = Ext.Array.toArray(arguments, 1);
  1240. return format.replace(formatRe, function(m, i) {
  1241. return args[i];
  1242. });
  1243. },
  1244. /**
  1245. * Returns a string with a specified number of repititions a given string pattern.
  1246. * The pattern be separated by a different string.
  1247. *
  1248. * var s = Ext.String.repeat('---', 4); // = '------------'
  1249. * var t = Ext.String.repeat('--', 3, '/'); // = '--/--/--'
  1250. *
  1251. * @param {String} pattern The pattern to repeat.
  1252. * @param {Number} count The number of times to repeat the pattern (may be 0).
  1253. * @param {String} sep An option string to separate each pattern.
  1254. */
  1255. repeat: function(pattern, count, sep) {
  1256. for (var buf = [], i = count; i--; ) {
  1257. buf.push(pattern);
  1258. }
  1259. return buf.join(sep || '');
  1260. },
  1261. /**
  1262. * Splits a string of space separated words into an array, trimming as needed. If the
  1263. * words are already an array, it is returned.
  1264. *
  1265. * @param {String/Array} words
  1266. */
  1267. splitWords: function (words) {
  1268. if (words && typeof words == 'string') {
  1269. return words.replace(basicTrimRe, '').split(whitespaceRe);
  1270. }
  1271. return words || [];
  1272. }
  1273. };
  1274. }());
  1275. // initialize the default encode / decode entities
  1276. Ext.String.resetCharacterEntities();
  1277. /**
  1278. * Old alias to {@link Ext.String#htmlEncode}
  1279. * @deprecated Use {@link Ext.String#htmlEncode} instead
  1280. * @method
  1281. * @member Ext
  1282. * @inheritdoc Ext.String#htmlEncode
  1283. */
  1284. Ext.htmlEncode = Ext.String.htmlEncode;
  1285. /**
  1286. * Old alias to {@link Ext.String#htmlDecode}
  1287. * @deprecated Use {@link Ext.String#htmlDecode} instead
  1288. * @method
  1289. * @member Ext
  1290. * @inheritdoc Ext.String#htmlDecode
  1291. */
  1292. Ext.htmlDecode = Ext.String.htmlDecode;
  1293. /**
  1294. * Old alias to {@link Ext.String#urlAppend}
  1295. * @deprecated Use {@link Ext.String#urlAppend} instead
  1296. * @method
  1297. * @member Ext
  1298. * @inheritdoc Ext.String#urlAppend
  1299. */
  1300. Ext.urlAppend = Ext.String.urlAppend;
  1301. //@tag foundation,core
  1302. //@require String.js
  1303. //@define Ext.Number
  1304. /**
  1305. * @class Ext.Number
  1306. *
  1307. * A collection of useful static methods to deal with numbers
  1308. * @singleton
  1309. */
  1310. Ext.Number = new function() {
  1311. var me = this,
  1312. isToFixedBroken = (0.9).toFixed() !== '1',
  1313. math = Math;
  1314. Ext.apply(this, {
  1315. /**
  1316. * Checks whether or not the passed number is within a desired range. If the number is already within the
  1317. * range it is returned, otherwise the min or max value is returned depending on which side of the range is
  1318. * exceeded. Note that this method returns the constrained value but does not change the current number.
  1319. * @param {Number} number The number to check
  1320. * @param {Number} min The minimum number in the range
  1321. * @param {Number} max The maximum number in the range
  1322. * @return {Number} The constrained value if outside the range, otherwise the current value
  1323. */
  1324. constrain: function(number, min, max) {
  1325. var x = parseFloat(number);
  1326. // Watch out for NaN in Chrome 18
  1327. // V8bug: http://code.google.com/p/v8/issues/detail?id=2056
  1328. // Operators are faster than Math.min/max. See http://jsperf.com/number-constrain
  1329. // ... and (x < Nan) || (x < undefined) == false
  1330. // ... same for (x > NaN) || (x > undefined)
  1331. // so if min or max are undefined or NaN, we never return them... sadly, this
  1332. // is not true of null (but even Math.max(-1,null)==0 and isNaN(null)==false)
  1333. return (x < min) ? min : ((x > max) ? max : x);
  1334. },
  1335. /**
  1336. * Snaps the passed number between stopping points based upon a passed increment value.
  1337. *
  1338. * The difference between this and {@link #snapInRange} is that {@link #snapInRange} uses the minValue
  1339. * when calculating snap points:
  1340. *
  1341. * r = Ext.Number.snap(56, 2, 55, 65); // Returns 56 - snap points are zero based
  1342. *
  1343. * r = Ext.Number.snapInRange(56, 2, 55, 65); // Returns 57 - snap points are based from minValue
  1344. *
  1345. * @param {Number} value The unsnapped value.
  1346. * @param {Number} increment The increment by which the value must move.
  1347. * @param {Number} minValue The minimum value to which the returned value must be constrained. Overrides the increment.
  1348. * @param {Number} maxValue The maximum value to which the returned value must be constrained. Overrides the increment.
  1349. * @return {Number} The value of the nearest snap target.
  1350. */
  1351. snap : function(value, increment, minValue, maxValue) {
  1352. var m;
  1353. // If no value passed, or minValue was passed and value is less than minValue (anything < undefined is false)
  1354. // Then use the minValue (or zero if the value was undefined)
  1355. if (value === undefined || value < minValue) {
  1356. return minValue || 0;
  1357. }
  1358. if (increment) {
  1359. m = value % increment;
  1360. if (m !== 0) {
  1361. value -= m;
  1362. if (m * 2 >= increment) {
  1363. value += increment;
  1364. } else if (m * 2 < -increment) {
  1365. value -= increment;
  1366. }
  1367. }
  1368. }
  1369. return me.constrain(value, minValue, maxValue);
  1370. },
  1371. /**
  1372. * Snaps the passed number between stopping points based upon a passed increment value.
  1373. *
  1374. * The difference between this and {@link #snap} is that {@link #snap} does not use the minValue
  1375. * when calculating snap points:
  1376. *
  1377. * r = Ext.Number.snap(56, 2, 55, 65); // Returns 56 - snap points are zero based
  1378. *
  1379. * r = Ext.Number.snapInRange(56, 2, 55, 65); // Returns 57 - snap points are based from minValue
  1380. *
  1381. * @param {Number} value The unsnapped value.
  1382. * @param {Number} increment The increment by which the value must move.
  1383. * @param {Number} [minValue=0] The minimum value to which the returned value must be constrained.
  1384. * @param {Number} [maxValue=Infinity] The maximum value to which the returned value must be constrained.
  1385. * @return {Number} The value of the nearest snap target.
  1386. */
  1387. snapInRange : function(value, increment, minValue, maxValue) {
  1388. var tween;
  1389. // default minValue to zero
  1390. minValue = (minValue || 0);
  1391. // If value is undefined, or less than minValue, use minValue
  1392. if (value === undefined || value < minValue) {
  1393. return minValue;
  1394. }
  1395. // Calculate how many snap points from the minValue the passed value is.
  1396. if (increment && (tween = ((value - minValue) % increment))) {
  1397. value -= tween;
  1398. tween *= 2;
  1399. if (tween >= increment) {
  1400. value += increment;
  1401. }
  1402. }
  1403. // If constraining within a maximum, ensure the maximum is on a snap point
  1404. if (maxValue !== undefined) {
  1405. if (value > (maxValue = me.snapInRange(maxValue, increment, minValue))) {
  1406. value = maxValue;
  1407. }
  1408. }
  1409. return value;
  1410. },
  1411. /**
  1412. * Formats a number using fixed-point notation
  1413. * @param {Number} value The number to format
  1414. * @param {Number} precision The number of digits to show after the decimal point
  1415. */
  1416. toFixed: isToFixedBroken ? function(value, precision) {
  1417. precision = precision || 0;
  1418. var pow = math.pow(10, precision);
  1419. return (math.round(value * pow) / pow).toFixed(precision);
  1420. } : function(value, precision) {
  1421. return value.toFixed(precision);
  1422. },
  1423. /**
  1424. * Validate that a value is numeric and convert it to a number if necessary. Returns the specified default value if
  1425. * it is not.
  1426. Ext.Number.from('1.23', 1); // returns 1.23
  1427. Ext.Number.from('abc', 1); // returns 1
  1428. * @param {Object} value
  1429. * @param {Number} defaultValue The value to return if the original value is non-numeric
  1430. * @return {Number} value, if numeric, defaultValue otherwise
  1431. */
  1432. from: function(value, defaultValue) {
  1433. if (isFinite(value)) {
  1434. value = parseFloat(value);
  1435. }
  1436. return !isNaN(value) ? value : defaultValue;
  1437. },
  1438. /**
  1439. * Returns a random integer between the specified range (inclusive)
  1440. * @param {Number} from Lowest value to return.
  1441. * @param {Number} to Highst value to return.
  1442. * @return {Number} A random integer within the specified range.
  1443. */
  1444. randomInt: function (from, to) {
  1445. return math.floor(math.random() * (to - from + 1) + from);
  1446. }
  1447. });
  1448. /**
  1449. * @deprecated 4.0.0 Please use {@link Ext.Number#from} instead.
  1450. * @member Ext
  1451. * @method num
  1452. * @inheritdoc Ext.Number#from
  1453. */
  1454. Ext.num = function() {
  1455. return me.from.apply(this, arguments);
  1456. };
  1457. };
  1458. //@tag foundation,core
  1459. //@require Number.js
  1460. /**
  1461. * @class Ext.Array
  1462. * @singleton
  1463. * @author Jacky Nguyen <jacky@sencha.com>
  1464. * @docauthor Jacky Nguyen <jacky@sencha.com>
  1465. *
  1466. * A set of useful static methods to deal with arrays; provide missing methods for older browsers.
  1467. */
  1468. (function() {
  1469. var arrayPrototype = Array.prototype,
  1470. slice = arrayPrototype.slice,
  1471. supportsSplice = (function () {
  1472. var array = [],
  1473. lengthBefore,
  1474. j = 20;
  1475. if (!array.splice) {
  1476. return false;
  1477. }
  1478. // This detects a bug in IE8 splice method:
  1479. // see http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/6e946d03-e09f-4b22-a4dd-cd5e276bf05a/
  1480. while (j--) {
  1481. array.push("A");
  1482. }
  1483. array.splice(15, 0, "F", "F", "F", "F", "F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F");
  1484. lengthBefore = array.length; //41
  1485. array.splice(13, 0, "XXX"); // add one element
  1486. if (lengthBefore+1 != array.length) {
  1487. return false;
  1488. }
  1489. // end IE8 bug
  1490. return true;
  1491. }()),
  1492. supportsForEach = 'forEach' in arrayPrototype,
  1493. supportsMap = 'map' in arrayPrototype,
  1494. supportsIndexOf = 'indexOf' in arrayPrototype,
  1495. supportsEvery = 'every' in arrayPrototype,
  1496. supportsSome = 'some' in arrayPrototype,
  1497. supportsFilter = 'filter' in arrayPrototype,
  1498. supportsSort = (function() {
  1499. var a = [1,2,3,4,5].sort(function(){ return 0; });
  1500. return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5;
  1501. }()),
  1502. supportsSliceOnNodeList = true,
  1503. ExtArray,
  1504. erase,
  1505. replace,
  1506. splice;
  1507. try {
  1508. // IE 6 - 8 will throw an error when using Array.prototype.slice on NodeList
  1509. if (typeof document !== 'undefined') {
  1510. slice.call(document.getElementsByTagName('body'));
  1511. }
  1512. } catch (e) {
  1513. supportsSliceOnNodeList = false;
  1514. }
  1515. function fixArrayIndex (array, index) {
  1516. return (index < 0) ? Math.max(0, array.length + index)
  1517. : Math.min(array.length, index);
  1518. }
  1519. /*
  1520. Does the same work as splice, but with a slightly more convenient signature. The splice
  1521. method has bugs in IE8, so this is the implementation we use on that platform.
  1522. The rippling of items in the array can be tricky. Consider two use cases:
  1523. index=2
  1524. removeCount=2
  1525. /=====\
  1526. +---+---+---+---+---+---+---+---+
  1527. | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
  1528. +---+---+---+---+---+---+---+---+
  1529. / \/ \/ \/ \
  1530. / /\ /\ /\ \
  1531. / / \/ \/ \ +--------------------------+
  1532. / / /\ /\ +--------------------------+ \
  1533. / / / \/ +--------------------------+ \ \
  1534. / / / /+--------------------------+ \ \ \
  1535. / / / / \ \ \ \
  1536. v v v v v v v v
  1537. +---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+---+
  1538. | 0 | 1 | 4 | 5 | 6 | 7 | | 0 | 1 | a | b | c | 4 | 5 | 6 | 7 |
  1539. +---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+---+
  1540. A B \=========/
  1541. insert=[a,b,c]
  1542. In case A, it is obvious that copying of [4,5,6,7] must be left-to-right so
  1543. that we don't end up with [0,1,6,7,6,7]. In case B, we have the opposite; we
  1544. must go right-to-left or else we would end up with [0,1,a,b,c,4,4,4,4].
  1545. */
  1546. function replaceSim (array, index, removeCount, insert) {
  1547. var add = insert ? insert.length : 0,
  1548. length = array.length,
  1549. pos = fixArrayIndex(array, index),
  1550. remove,
  1551. tailOldPos,
  1552. tailNewPos,
  1553. tailCount,
  1554. lengthAfterRemove,
  1555. i;
  1556. // we try to use Array.push when we can for efficiency...
  1557. if (pos === length) {
  1558. if (add) {
  1559. array.push.apply(array, insert);
  1560. }
  1561. } else {
  1562. remove = Math.min(removeCount, length - pos);
  1563. tailOldPos = pos + remove;
  1564. tailNewPos = tailOldPos + add - remove;
  1565. tailCount = length - tailOldPos;
  1566. lengthAfterRemove = length - remove;
  1567. if (tailNewPos < tailOldPos) { // case A
  1568. for (i = 0; i < tailCount; ++i) {
  1569. array[tailNewPos+i] = array[tailOldPos+i];
  1570. }
  1571. } else if (tailNewPos > tailOldPos) { // case B
  1572. for (i = tailCount; i--; ) {
  1573. array[tailNewPos+i] = array[tailOldPos+i];
  1574. }
  1575. } // else, add == remove (nothing to do)
  1576. if (add && pos === lengthAfterRemove) {
  1577. array.length = lengthAfterRemove; // truncate array
  1578. array.push.apply(array, insert);
  1579. } else {
  1580. array.length = lengthAfterRemove + add; // reserves space
  1581. for (i = 0; i < add; ++i) {
  1582. array[pos+i] = insert[i];
  1583. }
  1584. }
  1585. }
  1586. return array;
  1587. }
  1588. function replaceNative (array, index, removeCount, insert) {
  1589. if (insert && insert.length) {
  1590. if (index < array.length) {
  1591. array.splice.apply(array, [index, removeCount].concat(insert));
  1592. } else {
  1593. array.push.apply(array, insert);
  1594. }
  1595. } else {
  1596. array.splice(index, removeCount);
  1597. }
  1598. return array;
  1599. }
  1600. function eraseSim (array, index, removeCount) {
  1601. return replaceSim(array, index, removeCount);
  1602. }
  1603. function eraseNative (array, index, removeCount) {
  1604. array.splice(index, removeCount);
  1605. return array;
  1606. }
  1607. function spliceSim (array, index, removeCount) {
  1608. var pos = fixArrayIndex(array, index),
  1609. removed = array.slice(index, fixArrayIndex(array, pos+removeCount));
  1610. if (arguments.length < 4) {
  1611. replaceSim(array, pos, removeCount);
  1612. } else {
  1613. replaceSim(array, pos, removeCount, slice.call(arguments, 3));
  1614. }
  1615. return removed;
  1616. }
  1617. function spliceNative (array) {
  1618. return array.splice.apply(array, slice.call(arguments, 1));
  1619. }
  1620. erase = supportsSplice ? eraseNative : eraseSim;
  1621. replace = supportsSplice ? replaceNative : replaceSim;
  1622. splice = supportsSplice ? spliceNative : spliceSim;
  1623. // NOTE: from here on, use erase, replace or splice (not native methods)...
  1624. ExtArray = Ext.Array = {
  1625. /**
  1626. * Iterates an array or an iterable value and invoke the given callback function for each item.
  1627. *
  1628. * var countries = ['Vietnam', 'Singapore', 'United States', 'Russia'];
  1629. *
  1630. * Ext.Array.each(countries, function(name, index, countriesItSelf) {
  1631. * console.log(name);
  1632. * });
  1633. *
  1634. * var sum = function() {
  1635. * var sum = 0;
  1636. *
  1637. * Ext.Array.each(arguments, function(value) {
  1638. * sum += value;
  1639. * });
  1640. *
  1641. * return sum;
  1642. * };
  1643. *
  1644. * sum(1, 2, 3); // returns 6
  1645. *
  1646. * The iteration can be stopped by returning false in the function callback.
  1647. *
  1648. * Ext.Array.each(countries, function(name, index, countriesItSelf) {
  1649. * if (name === 'Singapore') {
  1650. * return false; // break here
  1651. * }
  1652. * });
  1653. *
  1654. * {@link Ext#each Ext.each} is alias for {@link Ext.Array#each Ext.Array.each}
  1655. *
  1656. * @param {Array/NodeList/Object} iterable The value to be iterated. If this
  1657. * argument is not iterable, the callback function is called once.
  1658. * @param {Function} fn The callback function. If it returns false, the iteration stops and this method returns
  1659. * the current `index`.
  1660. * @param {Object} fn.item The item at the current `index` in the passed `array`
  1661. * @param {Number} fn.index The current `index` within the `array`
  1662. * @param {Array} fn.allItems The `array` itself which was passed as the first argument
  1663. * @param {Boolean} fn.return Return false to stop iteration.
  1664. * @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed.
  1665. * @param {Boolean} reverse (Optional) Reverse the iteration order (loop from the end to the beginning)
  1666. * Defaults false
  1667. * @return {Boolean} See description for the `fn` parameter.
  1668. */
  1669. each: function(array, fn, scope, reverse) {
  1670. array = ExtArray.from(array);
  1671. var i,
  1672. ln = array.length;
  1673. if (reverse !== true) {
  1674. for (i = 0; i < ln; i++) {
  1675. if (fn.call(scope || array[i], array[i], i, array) === false) {
  1676. return i;
  1677. }
  1678. }
  1679. }
  1680. else {
  1681. for (i = ln - 1; i > -1; i--) {
  1682. if (fn.call(scope || array[i], array[i], i, array) === false) {
  1683. return i;
  1684. }
  1685. }
  1686. }
  1687. return true;
  1688. },
  1689. /**
  1690. * Iterates an array and invoke the given callback function for each item. Note that this will simply
  1691. * delegate to the native Array.prototype.forEach method if supported. It doesn't support stopping the
  1692. * iteration by returning false in the callback function like {@link Ext.Array#each}. However, performance
  1693. * could be much better in modern browsers comparing with {@link Ext.Array#each}
  1694. *
  1695. * @param {Array} array The array to iterate
  1696. * @param {Function} fn The callback function.
  1697. * @param {Object} fn.item The item at the current `index` in the passed `array`
  1698. * @param {Number} fn.index The current `index` within the `array`
  1699. * @param {Array} fn.allItems The `array` itself which was passed as the first argument
  1700. * @param {Object} scope (Optional) The execution scope (`this`) in which the specified function is executed.
  1701. */
  1702. forEach: supportsForEach ? function(array, fn, scope) {
  1703. return array.forEach(fn, scope);
  1704. } : function(array, fn, scope) {
  1705. var i = 0,
  1706. ln = array.length;
  1707. for (; i < ln; i++) {
  1708. fn.call(scope, array[i], i, array);
  1709. }
  1710. },
  1711. /**
  1712. * Get the index of the provided `item` in the given `array`, a supplement for the
  1713. * missing arrayPrototype.indexOf in Internet Explorer.
  1714. *
  1715. * @param {Array} array The array to check
  1716. * @param {Object} item The item to look for
  1717. * @param {Number} from (Optional) The index at which to begin the search
  1718. * @return {Number} The index of item in the array (or -1 if it is not found)
  1719. */
  1720. indexOf: supportsIndexOf ? function(array, item, from) {
  1721. return array.indexOf(item, from);
  1722. } : function(array, item, from) {
  1723. var i, length = array.length;
  1724. for (i = (from < 0) ? Math.max(0, length + from) : from || 0; i < length; i++) {
  1725. if (array[i] === item) {
  1726. return i;
  1727. }
  1728. }
  1729. return -1;
  1730. },
  1731. /**
  1732. * Checks whether or not the given `array` contains the specified `item`
  1733. *
  1734. * @param {Array} array The array to check
  1735. * @param {Object} item The item to look for
  1736. * @return {Boolean} True if the array contains the item, false otherwise
  1737. */
  1738. contains: supportsIndexOf ? function(array, item) {
  1739. return array.indexOf(item) !== -1;
  1740. } : function(array, item) {
  1741. var i, ln;
  1742. for (i = 0, ln = array.length; i < ln; i++) {
  1743. if (array[i] === item) {
  1744. return true;
  1745. }
  1746. }
  1747. return false;
  1748. },
  1749. /**
  1750. * Converts any iterable (numeric indices and a length property) into a true array.
  1751. *
  1752. * function test() {
  1753. * var args = Ext.Array.toArray(arguments),
  1754. * fromSecondToLastArgs = Ext.Array.toArray(arguments, 1);
  1755. *
  1756. * alert(args.join(' '));
  1757. * alert(fromSecondToLastArgs.join(' '));
  1758. * }
  1759. *
  1760. * test('just', 'testing', 'here'); // alerts 'just testing here';
  1761. * // alerts 'testing here';
  1762. *
  1763. * Ext.Array.toArray(document.getElementsByTagName('div')); // will convert the NodeList into an array
  1764. * Ext.Array.toArray('splitted'); // returns ['s', 'p', 'l', 'i', 't', 't', 'e', 'd']
  1765. * Ext.Array.toArray('splitted', 0, 3); // returns ['s', 'p', 'l']
  1766. *
  1767. * {@link Ext#toArray Ext.toArray} is alias for {@link Ext.Array#toArray Ext.Array.toArray}
  1768. *
  1769. * @param {Object} iterable the iterable object to be turned into a true Array.
  1770. * @param {Number} start (Optional) a zero-based index that specifies the start of extraction. Defaults to 0
  1771. * @param {Number} end (Optional) a 1-based index that specifies the end of extraction. Defaults to the last
  1772. * index of the iterable value
  1773. * @return {Array} array
  1774. */
  1775. toArray: function(iterable, start, end){
  1776. if (!iterable || !iterable.length) {
  1777. return [];
  1778. }
  1779. if (typeof iterable === 'string') {
  1780. iterable = iterable.split('');
  1781. }
  1782. if (supportsSliceOnNodeList) {
  1783. return slice.call(iterable, start || 0, end || iterable.length);
  1784. }
  1785. var array = [],
  1786. i;
  1787. start = start || 0;
  1788. end = end ? ((end < 0) ? iterable.length + end : end) : iterable.length;
  1789. for (i = start; i < end; i++) {
  1790. array.push(iterable[i]);
  1791. }
  1792. return array;
  1793. },
  1794. /**
  1795. * Plucks the value of a property from each item in the Array. Example:
  1796. *
  1797. * Ext.Array.pluck(Ext.query("p"), "className"); // [el1.className, el2.className, ..., elN.className]
  1798. *
  1799. * @param {Array/NodeList} array The Array of items to pluck the value from.
  1800. * @param {String} propertyName The property name to pluck from each element.
  1801. * @return {Array} The value from each item in the Array.
  1802. */
  1803. pluck: function(array, propertyName) {
  1804. var ret = [],
  1805. i, ln, item;
  1806. for (i = 0, ln = array.length; i < ln; i++) {
  1807. item = array[i];
  1808. ret.push(item[propertyName]);
  1809. }
  1810. return ret;
  1811. },
  1812. /**
  1813. * Creates a new array with the results of calling a provided function on every element in this array.
  1814. *
  1815. * @param {Array} array
  1816. * @param {Function} fn Callback function for each item
  1817. * @param {Object} scope Callback function scope
  1818. * @return {Array} results
  1819. */
  1820. map: supportsMap ? function(array, fn, scope) {
  1821. if (!fn) {
  1822. Ext.Error.raise('Ext.Array.map must have a callback function passed as second argument.');
  1823. }
  1824. return array.map(fn, scope);
  1825. } : function(array, fn, scope) {
  1826. if (!fn) {
  1827. Ext.Error.raise('Ext.Array.map must have a callback function passed as second argument.');
  1828. }
  1829. var results = [],
  1830. i = 0,
  1831. len = array.length;
  1832. for (; i < len; i++) {
  1833. results[i] = fn.call(scope, array[i], i, array);
  1834. }
  1835. return results;
  1836. },
  1837. /**
  1838. * Executes the specified function for each array element until the function returns a falsy value.
  1839. * If such an item is found, the function will return false immediately.
  1840. * Otherwise, it will return true.
  1841. *
  1842. * @param {Array} array
  1843. * @param {Function} fn Callback function for each item
  1844. * @param {Object} scope Callback function scope
  1845. * @return {Boolean} True if no false value is returned by the callback function.
  1846. */
  1847. every: supportsEvery ? function(array, fn, scope) {
  1848. if (!fn) {
  1849. Ext.Error.raise('Ext.Array.every must have a callback function passed as second argument.');
  1850. }
  1851. return array.every(fn, scope);
  1852. } : function(array, fn, scope) {
  1853. if (!fn) {
  1854. Ext.Error.raise('Ext.Array.every must have a callback function passed as second argument.');
  1855. }
  1856. var i = 0,
  1857. ln = array.length;
  1858. for (; i < ln; ++i) {
  1859. if (!fn.call(scope, array[i], i, array)) {
  1860. return false;
  1861. }
  1862. }
  1863. return true;
  1864. },
  1865. /**
  1866. * Executes the specified function for each array element until the function returns a truthy value.
  1867. * If such an item is found, the function will return true immediately. Otherwise, it will return false.
  1868. *
  1869. * @param {Array} array
  1870. * @param {Function} fn Callback function for each item
  1871. * @param {Object} scope Callback function scope
  1872. * @return {Boolean} True if the callback function returns a truthy value.
  1873. */
  1874. some: supportsSome ? function(array, fn, scope) {
  1875. if (!fn) {
  1876. Ext.Error.raise('Ext.Array.some must have a callback function passed as second argument.');
  1877. }
  1878. return array.some(fn, scope);
  1879. } : function(array, fn, scope) {
  1880. if (!fn) {
  1881. Ext.Error.raise('Ext.Array.some must have a callback function passed as second argument.');
  1882. }
  1883. var i = 0,
  1884. ln = array.length;
  1885. for (; i < ln; ++i) {
  1886. if (fn.call(scope, array[i], i, array)) {
  1887. return true;
  1888. }
  1889. }
  1890. return false;
  1891. },
  1892. /**
  1893. * Filter through an array and remove empty item as defined in {@link Ext#isEmpty Ext.isEmpty}
  1894. *
  1895. * See {@link Ext.Array#filter}
  1896. *
  1897. * @param {Array} array
  1898. * @return {Array} results
  1899. */
  1900. clean: function(array) {
  1901. var results = [],
  1902. i = 0,
  1903. ln = array.length,
  1904. item;
  1905. for (; i < ln; i++) {
  1906. item = array[i];
  1907. if (!Ext.isEmpty(item)) {
  1908. results.push(item);
  1909. }
  1910. }
  1911. return results;
  1912. },
  1913. /**
  1914. * Returns a new array with unique items
  1915. *
  1916. * @param {Array} array
  1917. * @return {Array} results
  1918. */
  1919. unique: function(array) {
  1920. var clone = [],
  1921. i = 0,
  1922. ln = array.length,
  1923. item;
  1924. for (; i < ln; i++) {
  1925. item = array[i];
  1926. if (ExtArray.indexOf(clone, item) === -1) {
  1927. clone.push(item);
  1928. }
  1929. }
  1930. return clone;
  1931. },
  1932. /**
  1933. * Creates a new array with all of the elements of this array for which
  1934. * the provided filtering function returns true.
  1935. *
  1936. * @param {Array} array
  1937. * @param {Function} fn Callback function for each item
  1938. * @param {Object} scope Callback function scope
  1939. * @return {Array} results
  1940. */
  1941. filter: supportsFilter ? function(array, fn, scope) {
  1942. if (!fn) {
  1943. Ext.Error.raise('Ext.Array.filter must have a callback function passed as second argument.');
  1944. }
  1945. return array.filter(fn, scope);
  1946. } : function(array, fn, scope) {
  1947. if (!fn) {
  1948. Ext.Error.raise('Ext.Array.filter must have a callback function passed as second argument.');
  1949. }
  1950. var results = [],
  1951. i = 0,
  1952. ln = array.length;
  1953. for (; i < ln; i++) {
  1954. if (fn.call(scope, array[i], i, array)) {
  1955. results.push(array[i]);
  1956. }
  1957. }
  1958. return results;
  1959. },
  1960. /**
  1961. * Converts a value to an array if it's not already an array; returns:
  1962. *
  1963. * - An empty array if given value is `undefined` or `null`
  1964. * - Itself if given value is already an array
  1965. * - An array copy if given value is {@link Ext#isIterable iterable} (arguments, NodeList and alike)
  1966. * - An array with one item which is the given value, otherwise
  1967. *
  1968. * @param {Object} value The value to convert to an array if it's not already is an array
  1969. * @param {Boolean} newReference (Optional) True to clone the given array and return a new reference if necessary,
  1970. * defaults to false
  1971. * @return {Array} array
  1972. */
  1973. from: function(value, newReference) {
  1974. if (value === undefined || value === null) {
  1975. return [];
  1976. }
  1977. if (Ext.isArray(value)) {
  1978. return (newReference) ? slice.call(value) : value;
  1979. }
  1980. var type = typeof value;
  1981. // Both strings and functions will have a length property. In phantomJS, NodeList
  1982. // instances report typeof=='function' but don't have an apply method...
  1983. if (value && value.length !== undefined && type !== 'string' && (type !== 'function' || !value.apply)) {
  1984. return ExtArray.toArray(value);
  1985. }
  1986. return [value];
  1987. },
  1988. /**
  1989. * Removes the specified item from the array if it exists
  1990. *
  1991. * @param {Array} array The array
  1992. * @param {Object} item The item to remove
  1993. * @return {Array} The passed array itself
  1994. */
  1995. remove: function(array, item) {
  1996. var index = ExtArray.indexOf(array, item);
  1997. if (index !== -1) {
  1998. erase(array, index, 1);
  1999. }
  2000. return array;
  2001. },
  2002. /**
  2003. * Push an item into the array only if the array doesn't contain it yet
  2004. *
  2005. * @param {Array} array The array
  2006. * @param {Object} item The item to include
  2007. */
  2008. include: function(array, item) {
  2009. if (!ExtArray.contains(array, item)) {
  2010. array.push(item);
  2011. }
  2012. },
  2013. /**
  2014. * Clone a flat array without referencing the previous one. Note that this is different
  2015. * from Ext.clone since it doesn't handle recursive cloning. It's simply a convenient, easy-to-remember method
  2016. * for Array.prototype.slice.call(array)
  2017. *
  2018. * @param {Array} array The array
  2019. * @return {Array} The clone array
  2020. */
  2021. clone: function(array) {
  2022. return slice.call(array);
  2023. },
  2024. /**
  2025. * Merge multiple arrays into one with unique items.
  2026. *
  2027. * {@link Ext.Array#union} is alias for {@link Ext.Array#merge}
  2028. *
  2029. * @param {Array} array1
  2030. * @param {Array} array2
  2031. * @param {Array} etc
  2032. * @return {Array} merged
  2033. */
  2034. merge: function() {
  2035. var args = slice.call(arguments),
  2036. array = [],
  2037. i, ln;
  2038. for (i = 0, ln = args.length; i < ln; i++) {
  2039. array = array.concat(args[i]);
  2040. }
  2041. return ExtArray.unique(array);
  2042. },
  2043. /**
  2044. * Merge multiple arrays into one with unique items that exist in all of the arrays.
  2045. *
  2046. * @param {Array} array1
  2047. * @param {Array} array2
  2048. * @param {Array} etc
  2049. * @return {Array} intersect
  2050. */
  2051. intersect: function() {
  2052. var intersection = [],
  2053. arrays = slice.call(arguments),
  2054. arraysLength,
  2055. array,
  2056. arrayLength,
  2057. minArray,
  2058. minArrayIndex,
  2059. minArrayCandidate,
  2060. minArrayLength,
  2061. element,
  2062. elementCandidate,
  2063. elementCount,
  2064. i, j, k;
  2065. if (!arrays.length) {
  2066. return intersection;
  2067. }
  2068. // Find the smallest array
  2069. arraysLength = arrays.length;
  2070. for (i = minArrayIndex = 0; i < arraysLength; i++) {
  2071. minArrayCandidate = arrays[i];
  2072. if (!minArray || minArrayCandidate.length < minArray.length) {
  2073. minArray = minArrayCandidate;
  2074. minArrayIndex = i;
  2075. }
  2076. }
  2077. minArray = ExtArray.unique(minArray);
  2078. erase(arrays, minArrayIndex, 1);
  2079. // Use the smallest unique'd array as the anchor loop. If the other array(s) do contain
  2080. // an item in the small array, we're likely to find it before reaching the end
  2081. // of the inner loop and can terminate the search early.
  2082. minArrayLength = minArray.length;
  2083. arraysLength = arrays.length;
  2084. for (i = 0; i < minArrayLength; i++) {
  2085. element = minArray[i];
  2086. elementCount = 0;
  2087. for (j = 0; j < arraysLength; j++) {
  2088. array = arrays[j];
  2089. arrayLength = array.length;
  2090. for (k = 0; k < arrayLength; k++) {
  2091. elementCandidate = array[k];
  2092. if (element === elementCandidate) {
  2093. elementCount++;
  2094. break;
  2095. }
  2096. }
  2097. }
  2098. if (elementCount === arraysLength) {
  2099. intersection.push(element);
  2100. }
  2101. }
  2102. return intersection;
  2103. },
  2104. /**
  2105. * Perform a set difference A-B by subtracting all items in array B from array A.
  2106. *
  2107. * @param {Array} arrayA
  2108. * @param {Array} arrayB
  2109. * @return {Array} difference
  2110. */
  2111. difference: function(arrayA, arrayB) {
  2112. var clone = slice.call(arrayA),
  2113. ln = clone.length,
  2114. i, j, lnB;
  2115. for (i = 0,lnB = arrayB.length; i < lnB; i++) {
  2116. for (j = 0; j < ln; j++) {
  2117. if (clone[j] === arrayB[i]) {
  2118. erase(clone, j, 1);
  2119. j--;
  2120. ln--;
  2121. }
  2122. }
  2123. }
  2124. return clone;
  2125. },
  2126. /**
  2127. * Returns a shallow copy of a part of an array. This is equivalent to the native
  2128. * call "Array.prototype.slice.call(array, begin, end)". This is often used when "array"
  2129. * is "arguments" since the arguments object does not supply a slice method but can
  2130. * be the context object to Array.prototype.slice.
  2131. *
  2132. * @param {Array} array The array (or arguments object).
  2133. * @param {Number} begin The index at which to begin. Negative values are offsets from
  2134. * the end of the array.
  2135. * @param {Number} end The index at which to end. The copied items do not include
  2136. * end. Negative values are offsets from the end of the array. If end is omitted,
  2137. * all items up to the end of the array are copied.
  2138. * @return {Array} The copied piece of the array.
  2139. * @method slice
  2140. */
  2141. // Note: IE6 will return [] on slice.call(x, undefined).
  2142. slice: ([1,2].slice(1, undefined).length ?
  2143. function (array, begin, end) {
  2144. return slice.call(array, begin, end);
  2145. } :
  2146. // at least IE6 uses arguments.length for variadic signature
  2147. function (array, begin, end) {
  2148. // After tested for IE 6, the one below is of the best performance
  2149. // see http://jsperf.com/slice-fix
  2150. if (typeof begin === 'undefined') {
  2151. return slice.call(array);
  2152. }
  2153. if (typeof end === 'undefined') {
  2154. return slice.call(array, begin);
  2155. }
  2156. return slice.call(array, begin, end);
  2157. }
  2158. ),
  2159. /**
  2160. * Sorts the elements of an Array.
  2161. * By default, this method sorts the elements alphabetically and ascending.
  2162. *
  2163. * @param {Array} array The array to sort.
  2164. * @param {Function} sortFn (optional) The comparison function.
  2165. * @return {Array} The sorted array.
  2166. */
  2167. sort: supportsSort ? function(array, sortFn) {
  2168. if (sortFn) {
  2169. return array.sort(sortFn);
  2170. } else {
  2171. return array.sort();
  2172. }
  2173. } : function(array, sortFn) {
  2174. var length = array.length,
  2175. i = 0,
  2176. comparison,
  2177. j, min, tmp;
  2178. for (; i < length; i++) {
  2179. min = i;
  2180. for (j = i + 1; j < length; j++) {
  2181. if (sortFn) {
  2182. comparison = sortFn(array[j], array[min]);
  2183. if (comparison < 0) {
  2184. min = j;
  2185. }
  2186. } else if (array[j] < array[min]) {
  2187. min = j;
  2188. }
  2189. }
  2190. if (min !== i) {
  2191. tmp = array[i];
  2192. array[i] = array[min];
  2193. array[min] = tmp;
  2194. }
  2195. }
  2196. return array;
  2197. },
  2198. /**
  2199. * Recursively flattens into 1-d Array. Injects Arrays inline.
  2200. *
  2201. * @param {Array} array The array to flatten
  2202. * @return {Array} The 1-d array.
  2203. */
  2204. flatten: function(array) {
  2205. var worker = [];
  2206. function rFlatten(a) {
  2207. var i, ln, v;
  2208. for (i = 0, ln = a.length; i < ln; i++) {
  2209. v = a[i];
  2210. if (Ext.isArray(v)) {
  2211. rFlatten(v);
  2212. } else {
  2213. worker.push(v);
  2214. }
  2215. }
  2216. return worker;
  2217. }
  2218. return rFlatten(array);
  2219. },
  2220. /**
  2221. * Returns the minimum value in the Array.
  2222. *
  2223. * @param {Array/NodeList} array The Array from which to select the minimum value.
  2224. * @param {Function} comparisonFn (optional) a function to perform the comparision which determines minimization.
  2225. * If omitted the "<" operator will be used. Note: gt = 1; eq = 0; lt = -1
  2226. * @return {Object} minValue The minimum value
  2227. */
  2228. min: function(array, comparisonFn) {
  2229. var min = array[0],
  2230. i, ln, item;
  2231. for (i = 0, ln = array.length; i < ln; i++) {
  2232. item = array[i];
  2233. if (comparisonFn) {
  2234. if (comparisonFn(min, item) === 1) {
  2235. min = item;
  2236. }
  2237. }
  2238. else {
  2239. if (item < min) {
  2240. min = item;
  2241. }
  2242. }
  2243. }
  2244. return min;
  2245. },
  2246. /**
  2247. * Returns the maximum value in the Array.
  2248. *
  2249. * @param {Array/NodeList} array The Array from which to select the maximum value.
  2250. * @param {Function} comparisonFn (optional) a function to perform the comparision which determines maximization.
  2251. * If omitted the ">" operator will be used. Note: gt = 1; eq = 0; lt = -1
  2252. * @return {Object} maxValue The maximum value
  2253. */
  2254. max: function(array, comparisonFn) {
  2255. var max = array[0],
  2256. i, ln, item;
  2257. for (i = 0, ln = array.length; i < ln; i++) {
  2258. item = array[i];
  2259. if (comparisonFn) {
  2260. if (comparisonFn(max, item) === -1) {
  2261. max = item;
  2262. }
  2263. }
  2264. else {
  2265. if (item > max) {
  2266. max = item;
  2267. }
  2268. }
  2269. }
  2270. return max;
  2271. },
  2272. /**
  2273. * Calculates the mean of all items in the array.
  2274. *
  2275. * @param {Array} array The Array to calculate the mean value of.
  2276. * @return {Number} The mean.
  2277. */
  2278. mean: function(array) {
  2279. return array.length > 0 ? ExtArray.sum(array) / array.length : undefined;
  2280. },
  2281. /**
  2282. * Calculates the sum of all items in the given array.
  2283. *
  2284. * @param {Array} array The Array to calculate the sum value of.
  2285. * @return {Number} The sum.
  2286. */
  2287. sum: function(array) {
  2288. var sum = 0,
  2289. i, ln, item;
  2290. for (i = 0,ln = array.length; i < ln; i++) {
  2291. item = array[i];
  2292. sum += item;
  2293. }
  2294. return sum;
  2295. },
  2296. /**
  2297. * Creates a map (object) keyed by the elements of the given array. The values in
  2298. * the map are the index+1 of the array element. For example:
  2299. *
  2300. * var map = Ext.Array.toMap(['a','b','c']);
  2301. *
  2302. * // map = { a: 1, b: 2, c: 3 };
  2303. *
  2304. * Or a key property can be specified:
  2305. *
  2306. * var map = Ext.Array.toMap([
  2307. * { name: 'a' },
  2308. * { name: 'b' },
  2309. * { name: 'c' }
  2310. * ], 'name');
  2311. *
  2312. * // map = { a: 1, b: 2, c: 3 };
  2313. *
  2314. * Lastly, a key extractor can be provided:
  2315. *
  2316. * var map = Ext.Array.toMap([
  2317. * { name: 'a' },
  2318. * { name: 'b' },
  2319. * { name: 'c' }
  2320. * ], function (obj) { return obj.name.toUpperCase(); });
  2321. *
  2322. * // map = { A: 1, B: 2, C: 3 };
  2323. */
  2324. toMap: function(array, getKey, scope) {
  2325. var map = {},
  2326. i = array.length;
  2327. if (!getKey) {
  2328. while (i--) {
  2329. map[array[i]] = i+1;
  2330. }
  2331. } else if (typeof getKey == 'string') {
  2332. while (i--) {
  2333. map[array[i][getKey]] = i+1;
  2334. }
  2335. } else {
  2336. while (i--) {
  2337. map[getKey.call(scope, array[i])] = i+1;
  2338. }
  2339. }
  2340. return map;
  2341. },
  2342. _replaceSim: replaceSim, // for unit testing
  2343. _spliceSim: spliceSim,
  2344. /**
  2345. * Removes items from an array. This is functionally equivalent to the splice method
  2346. * of Array, but works around bugs in IE8's splice method and does not copy the
  2347. * removed elements in order to return them (because very often they are ignored).
  2348. *
  2349. * @param {Array} array The Array on which to replace.
  2350. * @param {Number} index The index in the array at which to operate.
  2351. * @param {Number} removeCount The number of items to remove at index.
  2352. * @return {Array} The array passed.
  2353. * @method
  2354. */
  2355. erase: erase,
  2356. /**
  2357. * Inserts items in to an array.
  2358. *
  2359. * @param {Array} array The Array in which to insert.
  2360. * @param {Number} index The index in the array at which to operate.
  2361. * @param {Array} items The array of items to insert at index.
  2362. * @return {Array} The array passed.
  2363. */
  2364. insert: function (array, index, items) {
  2365. return replace(array, index, 0, items);
  2366. },
  2367. /**
  2368. * Replaces items in an array. This is functionally equivalent to the splice method
  2369. * of Array, but works around bugs in IE8's splice method and is often more convenient
  2370. * to call because it accepts an array of items to insert rather than use a variadic
  2371. * argument list.
  2372. *
  2373. * @param {Array} array The Array on which to replace.
  2374. * @param {Number} index The index in the array at which to operate.
  2375. * @param {Number} removeCount The number of items to remove at index (can be 0).
  2376. * @param {Array} insert (optional) An array of items to insert at index.
  2377. * @return {Array} The array passed.
  2378. * @method
  2379. */
  2380. replace: replace,
  2381. /**
  2382. * Replaces items in an array. This is equivalent to the splice method of Array, but
  2383. * works around bugs in IE8's splice method. The signature is exactly the same as the
  2384. * splice method except that the array is the first argument. All arguments following
  2385. * removeCount are inserted in the array at index.
  2386. *
  2387. * @param {Array} array The Array on which to replace.
  2388. * @param {Number} index The index in the array at which to operate.
  2389. * @param {Number} removeCount The number of items to remove at index (can be 0).
  2390. * @param {Object...} elements The elements to add to the array. If you don't specify
  2391. * any elements, splice simply removes elements from the array.
  2392. * @return {Array} An array containing the removed items.
  2393. * @method
  2394. */
  2395. splice: splice,
  2396. /**
  2397. * Pushes new items onto the end of an Array.
  2398. *
  2399. * Passed parameters may be single items, or arrays of items. If an Array is found in the argument list, all its
  2400. * elements are pushed into the end of the target Array.
  2401. *
  2402. * @param {Array} target The Array onto which to push new items
  2403. * @param {Object...} elements The elements to add to the array. Each parameter may
  2404. * be an Array, in which case all the elements of that Array will be pushed into the end of the
  2405. * destination Array.
  2406. * @return {Array} An array containing all the new items push onto the end.
  2407. *
  2408. */
  2409. push: function(array) {
  2410. var len = arguments.length,
  2411. i = 1,
  2412. newItem;
  2413. if (array === undefined) {
  2414. array = [];
  2415. } else if (!Ext.isArray(array)) {
  2416. array = [array];
  2417. }
  2418. for (; i < len; i++) {
  2419. newItem = arguments[i];
  2420. Array.prototype.push[Ext.isArray(newItem) ? 'apply' : 'call'](array, newItem);
  2421. }
  2422. return array;
  2423. }
  2424. };
  2425. /**
  2426. * @method
  2427. * @member Ext
  2428. * @inheritdoc Ext.Array#each
  2429. */
  2430. Ext.each = ExtArray.each;
  2431. /**
  2432. * @method
  2433. * @member Ext.Array
  2434. * @inheritdoc Ext.Array#merge
  2435. */
  2436. ExtArray.union = ExtArray.merge;
  2437. /**
  2438. * Old alias to {@link Ext.Array#min}
  2439. * @deprecated 4.0.0 Use {@link Ext.Array#min} instead
  2440. * @method
  2441. * @member Ext
  2442. * @inheritdoc Ext.Array#min
  2443. */
  2444. Ext.min = ExtArray.min;
  2445. /**
  2446. * Old alias to {@link Ext.Array#max}
  2447. * @deprecated 4.0.0 Use {@link Ext.Array#max} instead
  2448. * @method
  2449. * @member Ext
  2450. * @inheritdoc Ext.Array#max
  2451. */
  2452. Ext.max = ExtArray.max;
  2453. /**
  2454. * Old alias to {@link Ext.Array#sum}
  2455. * @deprecated 4.0.0 Use {@link Ext.Array#sum} instead
  2456. * @method
  2457. * @member Ext
  2458. * @inheritdoc Ext.Array#sum
  2459. */
  2460. Ext.sum = ExtArray.sum;
  2461. /**
  2462. * Old alias to {@link Ext.Array#mean}
  2463. * @deprecated 4.0.0 Use {@link Ext.Array#mean} instead
  2464. * @method
  2465. * @member Ext
  2466. * @inheritdoc Ext.Array#mean
  2467. */
  2468. Ext.mean = ExtArray.mean;
  2469. /**
  2470. * Old alias to {@link Ext.Array#flatten}
  2471. * @deprecated 4.0.0 Use {@link Ext.Array#flatten} instead
  2472. * @method
  2473. * @member Ext
  2474. * @inheritdoc Ext.Array#flatten
  2475. */
  2476. Ext.flatten = ExtArray.flatten;
  2477. /**
  2478. * Old alias to {@link Ext.Array#clean}
  2479. * @deprecated 4.0.0 Use {@link Ext.Array#clean} instead
  2480. * @method
  2481. * @member Ext
  2482. * @inheritdoc Ext.Array#clean
  2483. */
  2484. Ext.clean = ExtArray.clean;
  2485. /**
  2486. * Old alias to {@link Ext.Array#unique}
  2487. * @deprecated 4.0.0 Use {@link Ext.Array#unique} instead
  2488. * @method
  2489. * @member Ext
  2490. * @inheritdoc Ext.Array#unique
  2491. */
  2492. Ext.unique = ExtArray.unique;
  2493. /**
  2494. * Old alias to {@link Ext.Array#pluck Ext.Array.pluck}
  2495. * @deprecated 4.0.0 Use {@link Ext.Array#pluck Ext.Array.pluck} instead
  2496. * @method
  2497. * @member Ext
  2498. * @inheritdoc Ext.Array#pluck
  2499. */
  2500. Ext.pluck = ExtArray.pluck;
  2501. /**
  2502. * @method
  2503. * @member Ext
  2504. * @inheritdoc Ext.Array#toArray
  2505. */
  2506. Ext.toArray = function() {
  2507. return ExtArray.toArray.apply(ExtArray, arguments);
  2508. };
  2509. }());
  2510. //@tag foundation,core
  2511. //@require Array.js
  2512. /**
  2513. * @class Ext.Function
  2514. *
  2515. * A collection of useful static methods to deal with function callbacks
  2516. * @singleton
  2517. * @alternateClassName Ext.util.Functions
  2518. */
  2519. Ext.Function = {
  2520. /**
  2521. * A very commonly used method throughout the framework. It acts as a wrapper around another method
  2522. * which originally accepts 2 arguments for `name` and `value`.
  2523. * The wrapped function then allows "flexible" value setting of either:
  2524. *
  2525. * - `name` and `value` as 2 arguments
  2526. * - one single object argument with multiple key - value pairs
  2527. *
  2528. * For example:
  2529. *
  2530. * var setValue = Ext.Function.flexSetter(function(name, value) {
  2531. * this[name] = value;
  2532. * });
  2533. *
  2534. * // Afterwards
  2535. * // Setting a single name - value
  2536. * setValue('name1', 'value1');
  2537. *
  2538. * // Settings multiple name - value pairs
  2539. * setValue({
  2540. * name1: 'value1',
  2541. * name2: 'value2',
  2542. * name3: 'value3'
  2543. * });
  2544. *
  2545. * @param {Function} setter
  2546. * @returns {Function} flexSetter
  2547. */
  2548. flexSetter: function(fn) {
  2549. return function(a, b) {
  2550. var k, i;
  2551. if (a === null) {
  2552. return this;
  2553. }
  2554. if (typeof a !== 'string') {
  2555. for (k in a) {
  2556. if (a.hasOwnProperty(k)) {
  2557. fn.call(this, k, a[k]);
  2558. }
  2559. }
  2560. if (Ext.enumerables) {
  2561. for (i = Ext.enumerables.length; i--;) {
  2562. k = Ext.enumerables[i];
  2563. if (a.hasOwnProperty(k)) {
  2564. fn.call(this, k, a[k]);
  2565. }
  2566. }
  2567. }
  2568. } else {
  2569. fn.call(this, a, b);
  2570. }
  2571. return this;
  2572. };
  2573. },
  2574. /**
  2575. * Create a new function from the provided `fn`, change `this` to the provided scope, optionally
  2576. * overrides arguments for the call. (Defaults to the arguments passed by the caller)
  2577. *
  2578. * {@link Ext#bind Ext.bind} is alias for {@link Ext.Function#bind Ext.Function.bind}
  2579. *
  2580. * @param {Function} fn The function to delegate.
  2581. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
  2582. * **If omitted, defaults to the default global environment object (usually the browser window).**
  2583. * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
  2584. * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
  2585. * if a number the args are inserted at the specified position
  2586. * @return {Function} The new function
  2587. */
  2588. bind: function(fn, scope, args, appendArgs) {
  2589. if (arguments.length === 2) {
  2590. return function() {
  2591. return fn.apply(scope, arguments);
  2592. };
  2593. }
  2594. var method = fn,
  2595. slice = Array.prototype.slice;
  2596. return function() {
  2597. var callArgs = args || arguments;
  2598. if (appendArgs === true) {
  2599. callArgs = slice.call(arguments, 0);
  2600. callArgs = callArgs.concat(args);
  2601. }
  2602. else if (typeof appendArgs == 'number') {
  2603. callArgs = slice.call(arguments, 0); // copy arguments first
  2604. Ext.Array.insert(callArgs, appendArgs, args);
  2605. }
  2606. return method.apply(scope || Ext.global, callArgs);
  2607. };
  2608. },
  2609. /**
  2610. * Create a new function from the provided `fn`, the arguments of which are pre-set to `args`.
  2611. * New arguments passed to the newly created callback when it's invoked are appended after the pre-set ones.
  2612. * This is especially useful when creating callbacks.
  2613. *
  2614. * For example:
  2615. *
  2616. * var originalFunction = function(){
  2617. * alert(Ext.Array.from(arguments).join(' '));
  2618. * };
  2619. *
  2620. * var callback = Ext.Function.pass(originalFunction, ['Hello', 'World']);
  2621. *
  2622. * callback(); // alerts 'Hello World'
  2623. * callback('by Me'); // alerts 'Hello World by Me'
  2624. *
  2625. * {@link Ext#pass Ext.pass} is alias for {@link Ext.Function#pass Ext.Function.pass}
  2626. *
  2627. * @param {Function} fn The original function
  2628. * @param {Array} args The arguments to pass to new callback
  2629. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
  2630. * @return {Function} The new callback function
  2631. */
  2632. pass: function(fn, args, scope) {
  2633. if (!Ext.isArray(args)) {
  2634. if (Ext.isIterable(args)) {
  2635. args = Ext.Array.clone(args);
  2636. } else {
  2637. args = args !== undefined ? [args] : [];
  2638. }
  2639. }
  2640. return function() {
  2641. var fnArgs = [].concat(args);
  2642. fnArgs.push.apply(fnArgs, arguments);
  2643. return fn.apply(scope || this, fnArgs);
  2644. };
  2645. },
  2646. /**
  2647. * Create an alias to the provided method property with name `methodName` of `object`.
  2648. * Note that the execution scope will still be bound to the provided `object` itself.
  2649. *
  2650. * @param {Object/Function} object
  2651. * @param {String} methodName
  2652. * @return {Function} aliasFn
  2653. */
  2654. alias: function(object, methodName) {
  2655. return function() {
  2656. return object[methodName].apply(object, arguments);
  2657. };
  2658. },
  2659. /**
  2660. * Create a "clone" of the provided method. The returned method will call the given
  2661. * method passing along all arguments and the "this" pointer and return its result.
  2662. *
  2663. * @param {Function} method
  2664. * @return {Function} cloneFn
  2665. */
  2666. clone: function(method) {
  2667. return function() {
  2668. return method.apply(this, arguments);
  2669. };
  2670. },
  2671. /**
  2672. * Creates an interceptor function. The passed function is called before the original one. If it returns false,
  2673. * the original one is not called. The resulting function returns the results of the original function.
  2674. * The passed function is called with the parameters of the original function. Example usage:
  2675. *
  2676. * var sayHi = function(name){
  2677. * alert('Hi, ' + name);
  2678. * }
  2679. *
  2680. * sayHi('Fred'); // alerts "Hi, Fred"
  2681. *
  2682. * // create a new function that validates input without
  2683. * // directly modifying the original function:
  2684. * var sayHiToFriend = Ext.Function.createInterceptor(sayHi, function(name){
  2685. * return name == 'Brian';
  2686. * });
  2687. *
  2688. * sayHiToFriend('Fred'); // no alert
  2689. * sayHiToFriend('Brian'); // alerts "Hi, Brian"
  2690. *
  2691. * @param {Function} origFn The original function.
  2692. * @param {Function} newFn The function to call before the original
  2693. * @param {Object} scope (optional) The scope (`this` reference) in which the passed function is executed.
  2694. * **If omitted, defaults to the scope in which the original function is called or the browser window.**
  2695. * @param {Object} returnValue (optional) The value to return if the passed function return false (defaults to null).
  2696. * @return {Function} The new function
  2697. */
  2698. createInterceptor: function(origFn, newFn, scope, returnValue) {
  2699. var method = origFn;
  2700. if (!Ext.isFunction(newFn)) {
  2701. return origFn;
  2702. }
  2703. else {
  2704. return function() {
  2705. var me = this,
  2706. args = arguments;
  2707. newFn.target = me;
  2708. newFn.method = origFn;
  2709. return (newFn.apply(scope || me || Ext.global, args) !== false) ? origFn.apply(me || Ext.global, args) : returnValue || null;
  2710. };
  2711. }
  2712. },
  2713. /**
  2714. * Creates a delegate (callback) which, when called, executes after a specific delay.
  2715. *
  2716. * @param {Function} fn The function which will be called on a delay when the returned function is called.
  2717. * Optionally, a replacement (or additional) argument list may be specified.
  2718. * @param {Number} delay The number of milliseconds to defer execution by whenever called.
  2719. * @param {Object} scope (optional) The scope (`this` reference) used by the function at execution time.
  2720. * @param {Array} args (optional) Override arguments for the call. (Defaults to the arguments passed by the caller)
  2721. * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
  2722. * if a number the args are inserted at the specified position.
  2723. * @return {Function} A function which, when called, executes the original function after the specified delay.
  2724. */
  2725. createDelayed: function(fn, delay, scope, args, appendArgs) {
  2726. if (scope || args) {
  2727. fn = Ext.Function.bind(fn, scope, args, appendArgs);
  2728. }
  2729. return function() {
  2730. var me = this,
  2731. args = Array.prototype.slice.call(arguments);
  2732. setTimeout(function() {
  2733. fn.apply(me, args);
  2734. }, delay);
  2735. };
  2736. },
  2737. /**
  2738. * Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage:
  2739. *
  2740. * var sayHi = function(name){
  2741. * alert('Hi, ' + name);
  2742. * }
  2743. *
  2744. * // executes immediately:
  2745. * sayHi('Fred');
  2746. *
  2747. * // executes after 2 seconds:
  2748. * Ext.Function.defer(sayHi, 2000, this, ['Fred']);
  2749. *
  2750. * // this syntax is sometimes useful for deferring
  2751. * // execution of an anonymous function:
  2752. * Ext.Function.defer(function(){
  2753. * alert('Anonymous');
  2754. * }, 100);
  2755. *
  2756. * {@link Ext#defer Ext.defer} is alias for {@link Ext.Function#defer Ext.Function.defer}
  2757. *
  2758. * @param {Function} fn The function to defer.
  2759. * @param {Number} millis The number of milliseconds for the setTimeout call
  2760. * (if less than or equal to 0 the function is executed immediately)
  2761. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
  2762. * **If omitted, defaults to the browser window.**
  2763. * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
  2764. * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
  2765. * if a number the args are inserted at the specified position
  2766. * @return {Number} The timeout id that can be used with clearTimeout
  2767. */
  2768. defer: function(fn, millis, scope, args, appendArgs) {
  2769. fn = Ext.Function.bind(fn, scope, args, appendArgs);
  2770. if (millis > 0) {
  2771. return setTimeout(Ext.supports.TimeoutActualLateness ? function () {
  2772. fn();
  2773. } : fn, millis);
  2774. }
  2775. fn();
  2776. return 0;
  2777. },
  2778. /**
  2779. * Create a combined function call sequence of the original function + the passed function.
  2780. * The resulting function returns the results of the original function.
  2781. * The passed function is called with the parameters of the original function. Example usage:
  2782. *
  2783. * var sayHi = function(name){
  2784. * alert('Hi, ' + name);
  2785. * }
  2786. *
  2787. * sayHi('Fred'); // alerts "Hi, Fred"
  2788. *
  2789. * var sayGoodbye = Ext.Function.createSequence(sayHi, function(name){
  2790. * alert('Bye, ' + name);
  2791. * });
  2792. *
  2793. * sayGoodbye('Fred'); // both alerts show
  2794. *
  2795. * @param {Function} originalFn The original function.
  2796. * @param {Function} newFn The function to sequence
  2797. * @param {Object} scope (optional) The scope (`this` reference) in which the passed function is executed.
  2798. * If omitted, defaults to the scope in which the original function is called or the default global environment object (usually the browser window).
  2799. * @return {Function} The new function
  2800. */
  2801. createSequence: function(originalFn, newFn, scope) {
  2802. if (!newFn) {
  2803. return originalFn;
  2804. }
  2805. else {
  2806. return function() {
  2807. var result = originalFn.apply(this, arguments);
  2808. newFn.apply(scope || this, arguments);
  2809. return result;
  2810. };
  2811. }
  2812. },
  2813. /**
  2814. * Creates a delegate function, optionally with a bound scope which, when called, buffers
  2815. * the execution of the passed function for the configured number of milliseconds.
  2816. * If called again within that period, the impending invocation will be canceled, and the
  2817. * timeout period will begin again.
  2818. *
  2819. * @param {Function} fn The function to invoke on a buffered timer.
  2820. * @param {Number} buffer The number of milliseconds by which to buffer the invocation of the
  2821. * function.
  2822. * @param {Object} scope (optional) The scope (`this` reference) in which
  2823. * the passed function is executed. If omitted, defaults to the scope specified by the caller.
  2824. * @param {Array} args (optional) Override arguments for the call. Defaults to the arguments
  2825. * passed by the caller.
  2826. * @return {Function} A function which invokes the passed function after buffering for the specified time.
  2827. */
  2828. createBuffered: function(fn, buffer, scope, args) {
  2829. var timerId;
  2830. return function() {
  2831. var callArgs = args || Array.prototype.slice.call(arguments, 0),
  2832. me = scope || this;
  2833. if (timerId) {
  2834. clearTimeout(timerId);
  2835. }
  2836. timerId = setTimeout(function(){
  2837. fn.apply(me, callArgs);
  2838. }, buffer);
  2839. };
  2840. },
  2841. /**
  2842. * Creates a throttled version of the passed function which, when called repeatedly and
  2843. * rapidly, invokes the passed function only after a certain interval has elapsed since the
  2844. * previous invocation.
  2845. *
  2846. * This is useful for wrapping functions which may be called repeatedly, such as
  2847. * a handler of a mouse move event when the processing is expensive.
  2848. *
  2849. * @param {Function} fn The function to execute at a regular time interval.
  2850. * @param {Number} interval The interval **in milliseconds** on which the passed function is executed.
  2851. * @param {Object} scope (optional) The scope (`this` reference) in which
  2852. * the passed function is executed. If omitted, defaults to the scope specified by the caller.
  2853. * @returns {Function} A function which invokes the passed function at the specified interval.
  2854. */
  2855. createThrottled: function(fn, interval, scope) {
  2856. var lastCallTime, elapsed, lastArgs, timer, execute = function() {
  2857. fn.apply(scope || this, lastArgs);
  2858. lastCallTime = new Date().getTime();
  2859. };
  2860. return function() {
  2861. elapsed = new Date().getTime() - lastCallTime;
  2862. lastArgs = arguments;
  2863. clearTimeout(timer);
  2864. if (!lastCallTime || (elapsed >= interval)) {
  2865. execute();
  2866. } else {
  2867. timer = setTimeout(execute, interval - elapsed);
  2868. }
  2869. };
  2870. },
  2871. /**
  2872. * Adds behavior to an existing method that is executed before the
  2873. * original behavior of the function. For example:
  2874. *
  2875. * var soup = {
  2876. * contents: [],
  2877. * add: function(ingredient) {
  2878. * this.contents.push(ingredient);
  2879. * }
  2880. * };
  2881. * Ext.Function.interceptBefore(soup, "add", function(ingredient){
  2882. * if (!this.contents.length && ingredient !== "water") {
  2883. * // Always add water to start with
  2884. * this.contents.push("water");
  2885. * }
  2886. * });
  2887. * soup.add("onions");
  2888. * soup.add("salt");
  2889. * soup.contents; // will contain: water, onions, salt
  2890. *
  2891. * @param {Object} object The target object
  2892. * @param {String} methodName Name of the method to override
  2893. * @param {Function} fn Function with the new behavior. It will
  2894. * be called with the same arguments as the original method. The
  2895. * return value of this function will be the return value of the
  2896. * new method.
  2897. * @param {Object} [scope] The scope to execute the interceptor function. Defaults to the object.
  2898. * @return {Function} The new function just created.
  2899. */
  2900. interceptBefore: function(object, methodName, fn, scope) {
  2901. var method = object[methodName] || Ext.emptyFn;
  2902. return (object[methodName] = function() {
  2903. var ret = fn.apply(scope || this, arguments);
  2904. method.apply(this, arguments);
  2905. return ret;
  2906. });
  2907. },
  2908. /**
  2909. * Adds behavior to an existing method that is executed after the
  2910. * original behavior of the function. For example:
  2911. *
  2912. * var soup = {
  2913. * contents: [],
  2914. * add: function(ingredient) {
  2915. * this.contents.push(ingredient);
  2916. * }
  2917. * };
  2918. * Ext.Function.interceptAfter(soup, "add", function(ingredient){
  2919. * // Always add a bit of extra salt
  2920. * this.contents.push("salt");
  2921. * });
  2922. * soup.add("water");
  2923. * soup.add("onions");
  2924. * soup.contents; // will contain: water, salt, onions, salt
  2925. *
  2926. * @param {Object} object The target object
  2927. * @param {String} methodName Name of the method to override
  2928. * @param {Function} fn Function with the new behavior. It will
  2929. * be called with the same arguments as the original method. The
  2930. * return value of this function will be the return value of the
  2931. * new method.
  2932. * @param {Object} [scope] The scope to execute the interceptor function. Defaults to the object.
  2933. * @return {Function} The new function just created.
  2934. */
  2935. interceptAfter: function(object, methodName, fn, scope) {
  2936. var method = object[methodName] || Ext.emptyFn;
  2937. return (object[methodName] = function() {
  2938. method.apply(this, arguments);
  2939. return fn.apply(scope || this, arguments);
  2940. });
  2941. }
  2942. };
  2943. /**
  2944. * @method
  2945. * @member Ext
  2946. * @inheritdoc Ext.Function#defer
  2947. */
  2948. Ext.defer = Ext.Function.alias(Ext.Function, 'defer');
  2949. /**
  2950. * @method
  2951. * @member Ext
  2952. * @inheritdoc Ext.Function#pass
  2953. */
  2954. Ext.pass = Ext.Function.alias(Ext.Function, 'pass');
  2955. /**
  2956. * @method
  2957. * @member Ext
  2958. * @inheritdoc Ext.Function#bind
  2959. */
  2960. Ext.bind = Ext.Function.alias(Ext.Function, 'bind');
  2961. //@tag foundation,core
  2962. //@require Function.js
  2963. /**
  2964. * @author Jacky Nguyen <jacky@sencha.com>
  2965. * @docauthor Jacky Nguyen <jacky@sencha.com>
  2966. * @class Ext.Object
  2967. *
  2968. * A collection of useful static methods to deal with objects.
  2969. *
  2970. * @singleton
  2971. */
  2972. (function() {
  2973. // The "constructor" for chain:
  2974. var TemplateClass = function(){},
  2975. ExtObject = Ext.Object = {
  2976. /**
  2977. * Returns a new object with the given object as the prototype chain.
  2978. * @param {Object} object The prototype chain for the new object.
  2979. */
  2980. chain: function (object) {
  2981. TemplateClass.prototype = object;
  2982. var result = new TemplateClass();
  2983. TemplateClass.prototype = null;
  2984. return result;
  2985. },
  2986. /**
  2987. * Converts a `name` - `value` pair to an array of objects with support for nested structures. Useful to construct
  2988. * query strings. For example:
  2989. *
  2990. * var objects = Ext.Object.toQueryObjects('hobbies', ['reading', 'cooking', 'swimming']);
  2991. *
  2992. * // objects then equals:
  2993. * [
  2994. * { name: 'hobbies', value: 'reading' },
  2995. * { name: 'hobbies', value: 'cooking' },
  2996. * { name: 'hobbies', value: 'swimming' },
  2997. * ];
  2998. *
  2999. * var objects = Ext.Object.toQueryObjects('dateOfBirth', {
  3000. * day: 3,
  3001. * month: 8,
  3002. * year: 1987,
  3003. * extra: {
  3004. * hour: 4
  3005. * minute: 30
  3006. * }
  3007. * }, true); // Recursive
  3008. *
  3009. * // objects then equals:
  3010. * [
  3011. * { name: 'dateOfBirth[day]', value: 3 },
  3012. * { name: 'dateOfBirth[month]', value: 8 },
  3013. * { name: 'dateOfBirth[year]', value: 1987 },
  3014. * { name: 'dateOfBirth[extra][hour]', value: 4 },
  3015. * { name: 'dateOfBirth[extra][minute]', value: 30 },
  3016. * ];
  3017. *
  3018. * @param {String} name
  3019. * @param {Object/Array} value
  3020. * @param {Boolean} [recursive=false] True to traverse object recursively
  3021. * @return {Array}
  3022. */
  3023. toQueryObjects: function(name, value, recursive) {
  3024. var self = ExtObject.toQueryObjects,
  3025. objects = [],
  3026. i, ln;
  3027. if (Ext.isArray(value)) {
  3028. for (i = 0, ln = value.length; i < ln; i++) {
  3029. if (recursive) {
  3030. objects = objects.concat(self(name + '[' + i + ']', value[i], true));
  3031. }
  3032. else {
  3033. objects.push({
  3034. name: name,
  3035. value: value[i]
  3036. });
  3037. }
  3038. }
  3039. }
  3040. else if (Ext.isObject(value)) {
  3041. for (i in value) {
  3042. if (value.hasOwnProperty(i)) {
  3043. if (recursive) {
  3044. objects = objects.concat(self(name + '[' + i + ']', value[i], true));
  3045. }
  3046. else {
  3047. objects.push({
  3048. name: name,
  3049. value: value[i]
  3050. });
  3051. }
  3052. }
  3053. }
  3054. }
  3055. else {
  3056. objects.push({
  3057. name: name,
  3058. value: value
  3059. });
  3060. }
  3061. return objects;
  3062. },
  3063. /**
  3064. * Takes an object and converts it to an encoded query string.
  3065. *
  3066. * Non-recursive:
  3067. *
  3068. * Ext.Object.toQueryString({foo: 1, bar: 2}); // returns "foo=1&bar=2"
  3069. * Ext.Object.toQueryString({foo: null, bar: 2}); // returns "foo=&bar=2"
  3070. * Ext.Object.toQueryString({'some price': '$300'}); // returns "some%20price=%24300"
  3071. * Ext.Object.toQueryString({date: new Date(2011, 0, 1)}); // returns "date=%222011-01-01T00%3A00%3A00%22"
  3072. * Ext.Object.toQueryString({colors: ['red', 'green', 'blue']}); // returns "colors=red&colors=green&colors=blue"
  3073. *
  3074. * Recursive:
  3075. *
  3076. * Ext.Object.toQueryString({
  3077. * username: 'Jacky',
  3078. * dateOfBirth: {
  3079. * day: 1,
  3080. * month: 2,
  3081. * year: 1911
  3082. * },
  3083. * hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']]
  3084. * }, true); // returns the following string (broken down and url-decoded for ease of reading purpose):
  3085. * // username=Jacky
  3086. * // &dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911
  3087. * // &hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&hobbies[3][0]=nested&hobbies[3][1]=stuff
  3088. *
  3089. * @param {Object} object The object to encode
  3090. * @param {Boolean} [recursive=false] Whether or not to interpret the object in recursive format.
  3091. * (PHP / Ruby on Rails servers and similar).
  3092. * @return {String} queryString
  3093. */
  3094. toQueryString: function(object, recursive) {
  3095. var paramObjects = [],
  3096. params = [],
  3097. i, j, ln, paramObject, value;
  3098. for (i in object) {
  3099. if (object.hasOwnProperty(i)) {
  3100. paramObjects = paramObjects.concat(ExtObject.toQueryObjects(i, object[i], recursive));
  3101. }
  3102. }
  3103. for (j = 0, ln = paramObjects.length; j < ln; j++) {
  3104. paramObject = paramObjects[j];
  3105. value = paramObject.value;
  3106. if (Ext.isEmpty(value)) {
  3107. value = '';
  3108. }
  3109. else if (Ext.isDate(value)) {
  3110. value = Ext.Date.toString(value);
  3111. }
  3112. params.push(encodeURIComponent(paramObject.name) + '=' + encodeURIComponent(String(value)));
  3113. }
  3114. return params.join('&');
  3115. },
  3116. /**
  3117. * Converts a query string back into an object.
  3118. *
  3119. * Non-recursive:
  3120. *
  3121. * Ext.Object.fromQueryString("foo=1&bar=2"); // returns {foo: 1, bar: 2}
  3122. * Ext.Object.fromQueryString("foo=&bar=2"); // returns {foo: null, bar: 2}
  3123. * Ext.Object.fromQueryString("some%20price=%24300"); // returns {'some price': '$300'}
  3124. * Ext.Object.fromQueryString("colors=red&colors=green&colors=blue"); // returns {colors: ['red', 'green', 'blue']}
  3125. *
  3126. * Recursive:
  3127. *
  3128. * Ext.Object.fromQueryString(
  3129. * "username=Jacky&"+
  3130. * "dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911&"+
  3131. * "hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&"+
  3132. * "hobbies[3][0]=nested&hobbies[3][1]=stuff", true);
  3133. *
  3134. * // returns
  3135. * {
  3136. * username: 'Jacky',
  3137. * dateOfBirth: {
  3138. * day: '1',
  3139. * month: '2',
  3140. * year: '1911'
  3141. * },
  3142. * hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']]
  3143. * }
  3144. *
  3145. * @param {String} queryString The query string to decode
  3146. * @param {Boolean} [recursive=false] Whether or not to recursively decode the string. This format is supported by
  3147. * PHP / Ruby on Rails servers and similar.
  3148. * @return {Object}
  3149. */
  3150. fromQueryString: function(queryString, recursive) {
  3151. var parts = queryString.replace(/^\?/, '').split('&'),
  3152. object = {},
  3153. temp, components, name, value, i, ln,
  3154. part, j, subLn, matchedKeys, matchedName,
  3155. keys, key, nextKey;
  3156. for (i = 0, ln = parts.length; i < ln; i++) {
  3157. part = parts[i];
  3158. if (part.length > 0) {
  3159. components = part.split('=');
  3160. name = decodeURIComponent(components[0]);
  3161. value = (components[1] !== undefined) ? decodeURIComponent(components[1]) : '';
  3162. if (!recursive) {
  3163. if (object.hasOwnProperty(name)) {
  3164. if (!Ext.isArray(object[name])) {
  3165. object[name] = [object[name]];
  3166. }
  3167. object[name].push(value);
  3168. }
  3169. else {
  3170. object[name] = value;
  3171. }
  3172. }
  3173. else {
  3174. matchedKeys = name.match(/(\[):?([^\]]*)\]/g);
  3175. matchedName = name.match(/^([^\[]+)/);
  3176. if (!matchedName) {
  3177. throw new Error('[Ext.Object.fromQueryString] Malformed query string given, failed parsing name from "' + part + '"');
  3178. }
  3179. name = matchedName[0];
  3180. keys = [];
  3181. if (matchedKeys === null) {
  3182. object[name] = value;
  3183. continue;
  3184. }
  3185. for (j = 0, subLn = matchedKeys.length; j < subLn; j++) {
  3186. key = matchedKeys[j];
  3187. key = (key.length === 2) ? '' : key.substring(1, key.length - 1);
  3188. keys.push(key);
  3189. }
  3190. keys.unshift(name);
  3191. temp = object;
  3192. for (j = 0, subLn = keys.length; j < subLn; j++) {
  3193. key = keys[j];
  3194. if (j === subLn - 1) {
  3195. if (Ext.isArray(temp) && key === '') {
  3196. temp.push(value);
  3197. }
  3198. else {
  3199. temp[key] = value;
  3200. }
  3201. }
  3202. else {
  3203. if (temp[key] === undefined || typeof temp[key] === 'string') {
  3204. nextKey = keys[j+1];
  3205. temp[key] = (Ext.isNumeric(nextKey) || nextKey === '') ? [] : {};
  3206. }
  3207. temp = temp[key];
  3208. }
  3209. }
  3210. }
  3211. }
  3212. }
  3213. return object;
  3214. },
  3215. /**
  3216. * Iterates through an object and invokes the given callback function for each iteration.
  3217. * The iteration can be stopped by returning `false` in the callback function. For example:
  3218. *
  3219. * var person = {
  3220. * name: 'Jacky'
  3221. * hairColor: 'black'
  3222. * loves: ['food', 'sleeping', 'wife']
  3223. * };
  3224. *
  3225. * Ext.Object.each(person, function(key, value, myself) {
  3226. * console.log(key + ":" + value);
  3227. *
  3228. * if (key === 'hairColor') {
  3229. * return false; // stop the iteration
  3230. * }
  3231. * });
  3232. *
  3233. * @param {Object} object The object to iterate
  3234. * @param {Function} fn The callback function.
  3235. * @param {String} fn.key
  3236. * @param {Object} fn.value
  3237. * @param {Object} fn.object The object itself
  3238. * @param {Object} [scope] The execution scope (`this`) of the callback function
  3239. */
  3240. each: function(object, fn, scope) {
  3241. for (var property in object) {
  3242. if (object.hasOwnProperty(property)) {
  3243. if (fn.call(scope || object, property, object[property], object) === false) {
  3244. return;
  3245. }
  3246. }
  3247. }
  3248. },
  3249. /**
  3250. * Merges any number of objects recursively without referencing them or their children.
  3251. *
  3252. * var extjs = {
  3253. * companyName: 'Ext JS',
  3254. * products: ['Ext JS', 'Ext GWT', 'Ext Designer'],
  3255. * isSuperCool: true,
  3256. * office: {
  3257. * size: 2000,
  3258. * location: 'Palo Alto',
  3259. * isFun: true
  3260. * }
  3261. * };
  3262. *
  3263. * var newStuff = {
  3264. * companyName: 'Sencha Inc.',
  3265. * products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'],
  3266. * office: {
  3267. * size: 40000,
  3268. * location: 'Redwood City'
  3269. * }
  3270. * };
  3271. *
  3272. * var sencha = Ext.Object.merge(extjs, newStuff);
  3273. *
  3274. * // extjs and sencha then equals to
  3275. * {
  3276. * companyName: 'Sencha Inc.',
  3277. * products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'],
  3278. * isSuperCool: true,
  3279. * office: {
  3280. * size: 40000,
  3281. * location: 'Redwood City',
  3282. * isFun: true
  3283. * }
  3284. * }
  3285. *
  3286. * @param {Object} destination The object into which all subsequent objects are merged.
  3287. * @param {Object...} object Any number of objects to merge into the destination.
  3288. * @return {Object} merged The destination object with all passed objects merged in.
  3289. */
  3290. merge: function(destination) {
  3291. var i = 1,
  3292. ln = arguments.length,
  3293. mergeFn = ExtObject.merge,
  3294. cloneFn = Ext.clone,
  3295. object, key, value, sourceKey;
  3296. for (; i < ln; i++) {
  3297. object = arguments[i];
  3298. for (key in object) {
  3299. value = object[key];
  3300. if (value && value.constructor === Object) {
  3301. sourceKey = destination[key];
  3302. if (sourceKey && sourceKey.constructor === Object) {
  3303. mergeFn(sourceKey, value);
  3304. }
  3305. else {
  3306. destination[key] = cloneFn(value);
  3307. }
  3308. }
  3309. else {
  3310. destination[key] = value;
  3311. }
  3312. }
  3313. }
  3314. return destination;
  3315. },
  3316. /**
  3317. * @private
  3318. * @param destination
  3319. */
  3320. mergeIf: function(destination) {
  3321. var i = 1,
  3322. ln = arguments.length,
  3323. cloneFn = Ext.clone,
  3324. object, key, value;
  3325. for (; i < ln; i++) {
  3326. object = arguments[i];
  3327. for (key in object) {
  3328. if (!(key in destination)) {
  3329. value = object[key];
  3330. if (value && value.constructor === Object) {
  3331. destination[key] = cloneFn(value);
  3332. }
  3333. else {
  3334. destination[key] = value;
  3335. }
  3336. }
  3337. }
  3338. }
  3339. return destination;
  3340. },
  3341. /**
  3342. * Returns the first matching key corresponding to the given value.
  3343. * If no matching value is found, null is returned.
  3344. *
  3345. * var person = {
  3346. * name: 'Jacky',
  3347. * loves: 'food'
  3348. * };
  3349. *
  3350. * alert(Ext.Object.getKey(person, 'food')); // alerts 'loves'
  3351. *
  3352. * @param {Object} object
  3353. * @param {Object} value The value to find
  3354. */
  3355. getKey: function(object, value) {
  3356. for (var property in object) {
  3357. if (object.hasOwnProperty(property) && object[property] === value) {
  3358. return property;
  3359. }
  3360. }
  3361. return null;
  3362. },
  3363. /**
  3364. * Gets all values of the given object as an array.
  3365. *
  3366. * var values = Ext.Object.getValues({
  3367. * name: 'Jacky',
  3368. * loves: 'food'
  3369. * }); // ['Jacky', 'food']
  3370. *
  3371. * @param {Object} object
  3372. * @return {Array} An array of values from the object
  3373. */
  3374. getValues: function(object) {
  3375. var values = [],
  3376. property;
  3377. for (property in object) {
  3378. if (object.hasOwnProperty(property)) {
  3379. values.push(object[property]);
  3380. }
  3381. }
  3382. return values;
  3383. },
  3384. /**
  3385. * Gets all keys of the given object as an array.
  3386. *
  3387. * var values = Ext.Object.getKeys({
  3388. * name: 'Jacky',
  3389. * loves: 'food'
  3390. * }); // ['name', 'loves']
  3391. *
  3392. * @param {Object} object
  3393. * @return {String[]} An array of keys from the object
  3394. * @method
  3395. */
  3396. getKeys: (typeof Object.keys == 'function')
  3397. ? function(object){
  3398. if (!object) {
  3399. return [];
  3400. }
  3401. return Object.keys(object);
  3402. }
  3403. : function(object) {
  3404. var keys = [],
  3405. property;
  3406. for (property in object) {
  3407. if (object.hasOwnProperty(property)) {
  3408. keys.push(property);
  3409. }
  3410. }
  3411. return keys;
  3412. },
  3413. /**
  3414. * Gets the total number of this object's own properties
  3415. *
  3416. * var size = Ext.Object.getSize({
  3417. * name: 'Jacky',
  3418. * loves: 'food'
  3419. * }); // size equals 2
  3420. *
  3421. * @param {Object} object
  3422. * @return {Number} size
  3423. */
  3424. getSize: function(object) {
  3425. var size = 0,
  3426. property;
  3427. for (property in object) {
  3428. if (object.hasOwnProperty(property)) {
  3429. size++;
  3430. }
  3431. }
  3432. return size;
  3433. },
  3434. /**
  3435. * @private
  3436. */
  3437. classify: function(object) {
  3438. var prototype = object,
  3439. objectProperties = [],
  3440. propertyClassesMap = {},
  3441. objectClass = function() {
  3442. var i = 0,
  3443. ln = objectProperties.length,
  3444. property;
  3445. for (; i < ln; i++) {
  3446. property = objectProperties[i];
  3447. this[property] = new propertyClassesMap[property]();
  3448. }
  3449. },
  3450. key, value;
  3451. for (key in object) {
  3452. if (object.hasOwnProperty(key)) {
  3453. value = object[key];
  3454. if (value && value.constructor === Object) {
  3455. objectProperties.push(key);
  3456. propertyClassesMap[key] = ExtObject.classify(value);
  3457. }
  3458. }
  3459. }
  3460. objectClass.prototype = prototype;
  3461. return objectClass;
  3462. }
  3463. };
  3464. /**
  3465. * A convenient alias method for {@link Ext.Object#merge}.
  3466. *
  3467. * @member Ext
  3468. * @method merge
  3469. * @inheritdoc Ext.Object#merge
  3470. */
  3471. Ext.merge = Ext.Object.merge;
  3472. /**
  3473. * @private
  3474. * @member Ext
  3475. */
  3476. Ext.mergeIf = Ext.Object.mergeIf;
  3477. /**
  3478. *
  3479. * @member Ext
  3480. * @method urlEncode
  3481. * @inheritdoc Ext.Object#toQueryString
  3482. * @deprecated 4.0.0 Use {@link Ext.Object#toQueryString} instead
  3483. */
  3484. Ext.urlEncode = function() {
  3485. var args = Ext.Array.from(arguments),
  3486. prefix = '';
  3487. // Support for the old `pre` argument
  3488. if ((typeof args[1] === 'string')) {
  3489. prefix = args[1] + '&';
  3490. args[1] = false;
  3491. }
  3492. return prefix + ExtObject.toQueryString.apply(ExtObject, args);
  3493. };
  3494. /**
  3495. * Alias for {@link Ext.Object#fromQueryString}.
  3496. *
  3497. * @member Ext
  3498. * @method urlDecode
  3499. * @inheritdoc Ext.Object#fromQueryString
  3500. * @deprecated 4.0.0 Use {@link Ext.Object#fromQueryString} instead
  3501. */
  3502. Ext.urlDecode = function() {
  3503. return ExtObject.fromQueryString.apply(ExtObject, arguments);
  3504. };
  3505. }());
  3506. //@tag foundation,core
  3507. //@require Object.js
  3508. //@define Ext.Date
  3509. /**
  3510. * @class Ext.Date
  3511. * A set of useful static methods to deal with date
  3512. * Note that if Ext.Date is required and loaded, it will copy all methods / properties to
  3513. * this object for convenience
  3514. *
  3515. * The date parsing and formatting syntax contains a subset of
  3516. * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
  3517. * supported will provide results equivalent to their PHP versions.
  3518. *
  3519. * The following is a list of all currently supported formats:
  3520. * <pre class="">
  3521. Format Description Example returned values
  3522. ------ ----------------------------------------------------------------------- -----------------------
  3523. d Day of the month, 2 digits with leading zeros 01 to 31
  3524. D A short textual representation of the day of the week Mon to Sun
  3525. j Day of the month without leading zeros 1 to 31
  3526. l A full textual representation of the day of the week Sunday to Saturday
  3527. N ISO-8601 numeric representation of the day of the week 1 (for Monday) through 7 (for Sunday)
  3528. S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
  3529. w Numeric representation of the day of the week 0 (for Sunday) to 6 (for Saturday)
  3530. z The day of the year (starting from 0) 0 to 364 (365 in leap years)
  3531. W ISO-8601 week number of year, weeks starting on Monday 01 to 53
  3532. F A full textual representation of a month, such as January or March January to December
  3533. m Numeric representation of a month, with leading zeros 01 to 12
  3534. M A short textual representation of a month Jan to Dec
  3535. n Numeric representation of a month, without leading zeros 1 to 12
  3536. t Number of days in the given month 28 to 31
  3537. L Whether it&#39;s a leap year 1 if it is a leap year, 0 otherwise.
  3538. o ISO-8601 year number (identical to (Y), but if the ISO week number (W) Examples: 1998 or 2004
  3539. belongs to the previous or next year, that year is used instead)
  3540. Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
  3541. y A two digit representation of a year Examples: 99 or 03
  3542. a Lowercase Ante meridiem and Post meridiem am or pm
  3543. A Uppercase Ante meridiem and Post meridiem AM or PM
  3544. g 12-hour format of an hour without leading zeros 1 to 12
  3545. G 24-hour format of an hour without leading zeros 0 to 23
  3546. h 12-hour format of an hour with leading zeros 01 to 12
  3547. H 24-hour format of an hour with leading zeros 00 to 23
  3548. i Minutes, with leading zeros 00 to 59
  3549. s Seconds, with leading zeros 00 to 59
  3550. u Decimal fraction of a second Examples:
  3551. (minimum 1 digit, arbitrary number of digits allowed) 001 (i.e. 0.001s) or
  3552. 100 (i.e. 0.100s) or
  3553. 999 (i.e. 0.999s) or
  3554. 999876543210 (i.e. 0.999876543210s)
  3555. O Difference to Greenwich time (GMT) in hours and minutes Example: +1030
  3556. P Difference to Greenwich time (GMT) with colon between hours and minutes Example: -08:00
  3557. T Timezone abbreviation of the machine running the code Examples: EST, MDT, PDT ...
  3558. Z Timezone offset in seconds (negative if west of UTC, positive if east) -43200 to 50400
  3559. c ISO 8601 date
  3560. Notes: Examples:
  3561. 1) If unspecified, the month / day defaults to the current month / day, 1991 or
  3562. the time defaults to midnight, while the timezone defaults to the 1992-10 or
  3563. browser's timezone. If a time is specified, it must include both hours 1993-09-20 or
  3564. and minutes. The "T" delimiter, seconds, milliseconds and timezone 1994-08-19T16:20+01:00 or
  3565. are optional. 1995-07-18T17:21:28-02:00 or
  3566. 2) The decimal fraction of a second, if specified, must contain at 1996-06-17T18:22:29.98765+03:00 or
  3567. least 1 digit (there is no limit to the maximum number 1997-05-16T19:23:30,12345-0400 or
  3568. of digits allowed), and may be delimited by either a '.' or a ',' 1998-04-15T20:24:31.2468Z or
  3569. Refer to the examples on the right for the various levels of 1999-03-14T20:24:32Z or
  3570. date-time granularity which are supported, or see 2000-02-13T21:25:33
  3571. http://www.w3.org/TR/NOTE-datetime for more info. 2001-01-12 22:26:34
  3572. U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) 1193432466 or -2138434463
  3573. MS Microsoft AJAX serialized dates \/Date(1238606590509)\/ (i.e. UTC milliseconds since epoch) or
  3574. \/Date(1238606590509+0800)\/
  3575. </pre>
  3576. *
  3577. * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
  3578. * <pre><code>
  3579. // Sample date:
  3580. // 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
  3581. var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
  3582. console.log(Ext.Date.format(dt, 'Y-m-d')); // 2007-01-10
  3583. console.log(Ext.Date.format(dt, 'F j, Y, g:i a')); // January 10, 2007, 3:05 pm
  3584. console.log(Ext.Date.format(dt, 'l, \\t\\he jS \\of F Y h:i:s A')); // Wednesday, the 10th of January 2007 03:05:01 PM
  3585. </code></pre>
  3586. *
  3587. * Here are some standard date/time patterns that you might find helpful. They
  3588. * are not part of the source of Ext.Date, but to use them you can simply copy this
  3589. * block of code into any script that is included after Ext.Date and they will also become
  3590. * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
  3591. * <pre><code>
  3592. Ext.Date.patterns = {
  3593. ISO8601Long:"Y-m-d H:i:s",
  3594. ISO8601Short:"Y-m-d",
  3595. ShortDate: "n/j/Y",
  3596. LongDate: "l, F d, Y",
  3597. FullDateTime: "l, F d, Y g:i:s A",
  3598. MonthDay: "F d",
  3599. ShortTime: "g:i A",
  3600. LongTime: "g:i:s A",
  3601. SortableDateTime: "Y-m-d\\TH:i:s",
  3602. UniversalSortableDateTime: "Y-m-d H:i:sO",
  3603. YearMonth: "F, Y"
  3604. };
  3605. </code></pre>
  3606. *
  3607. * Example usage:
  3608. * <pre><code>
  3609. var dt = new Date();
  3610. console.log(Ext.Date.format(dt, Ext.Date.patterns.ShortDate));
  3611. </code></pre>
  3612. * <p>Developer-written, custom formats may be used by supplying both a formatting and a parsing function
  3613. * which perform to specialized requirements. The functions are stored in {@link #parseFunctions} and {@link #formatFunctions}.</p>
  3614. * @singleton
  3615. */
  3616. /*
  3617. * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
  3618. * (see http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/)
  3619. * They generate precompiled functions from format patterns instead of parsing and
  3620. * processing each pattern every time a date is formatted. These functions are available
  3621. * on every Date object.
  3622. */
  3623. (function() {
  3624. // create private copy of Ext's Ext.util.Format.format() method
  3625. // - to remove unnecessary dependency
  3626. // - to resolve namespace conflict with MS-Ajax's implementation
  3627. function xf(format) {
  3628. var args = Array.prototype.slice.call(arguments, 1);
  3629. return format.replace(/\{(\d+)\}/g, function(m, i) {
  3630. return args[i];
  3631. });
  3632. }
  3633. Ext.Date = {
  3634. /**
  3635. * Returns the current timestamp.
  3636. * @return {Number} Milliseconds since UNIX epoch.
  3637. * @method
  3638. */
  3639. now: Date.now || function() {
  3640. return +new Date();
  3641. },
  3642. /**
  3643. * @private
  3644. * Private for now
  3645. */
  3646. toString: function(date) {
  3647. var pad = Ext.String.leftPad;
  3648. return date.getFullYear() + "-"
  3649. + pad(date.getMonth() + 1, 2, '0') + "-"
  3650. + pad(date.getDate(), 2, '0') + "T"
  3651. + pad(date.getHours(), 2, '0') + ":"
  3652. + pad(date.getMinutes(), 2, '0') + ":"
  3653. + pad(date.getSeconds(), 2, '0');
  3654. },
  3655. /**
  3656. * Returns the number of milliseconds between two dates
  3657. * @param {Date} dateA The first date
  3658. * @param {Date} dateB (optional) The second date, defaults to now
  3659. * @return {Number} The difference in milliseconds
  3660. */
  3661. getElapsed: function(dateA, dateB) {
  3662. return Math.abs(dateA - (dateB || new Date()));
  3663. },
  3664. /**
  3665. * Global flag which determines if strict date parsing should be used.
  3666. * Strict date parsing will not roll-over invalid dates, which is the
  3667. * default behaviour of javascript Date objects.
  3668. * (see {@link #parse} for more information)
  3669. * Defaults to <tt>false</tt>.
  3670. * @type Boolean
  3671. */
  3672. useStrict: false,
  3673. // private
  3674. formatCodeToRegex: function(character, currentGroup) {
  3675. // Note: currentGroup - position in regex result array (see notes for Ext.Date.parseCodes below)
  3676. var p = utilDate.parseCodes[character];
  3677. if (p) {
  3678. p = typeof p == 'function'? p() : p;
  3679. utilDate.parseCodes[character] = p; // reassign function result to prevent repeated execution
  3680. }
  3681. return p ? Ext.applyIf({
  3682. c: p.c ? xf(p.c, currentGroup || "{0}") : p.c
  3683. }, p) : {
  3684. g: 0,
  3685. c: null,
  3686. s: Ext.String.escapeRegex(character) // treat unrecognised characters as literals
  3687. };
  3688. },
  3689. /**
  3690. * <p>An object hash in which each property is a date parsing function. The property name is the
  3691. * format string which that function parses.</p>
  3692. * <p>This object is automatically populated with date parsing functions as
  3693. * date formats are requested for Ext standard formatting strings.</p>
  3694. * <p>Custom parsing functions may be inserted into this object, keyed by a name which from then on
  3695. * may be used as a format string to {@link #parse}.<p>
  3696. * <p>Example:</p><pre><code>
  3697. Ext.Date.parseFunctions['x-date-format'] = myDateParser;
  3698. </code></pre>
  3699. * <p>A parsing function should return a Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
  3700. * <li><code>date</code> : String<div class="sub-desc">The date string to parse.</div></li>
  3701. * <li><code>strict</code> : Boolean<div class="sub-desc">True to validate date strings while parsing
  3702. * (i.e. prevent javascript Date "rollover") (The default must be false).
  3703. * Invalid date strings should return null when parsed.</div></li>
  3704. * </ul></div></p>
  3705. * <p>To enable Dates to also be <i>formatted</i> according to that format, a corresponding
  3706. * formatting function must be placed into the {@link #formatFunctions} property.
  3707. * @property parseFunctions
  3708. * @type Object
  3709. */
  3710. parseFunctions: {
  3711. "MS": function(input, strict) {
  3712. // note: the timezone offset is ignored since the MS Ajax server sends
  3713. // a UTC milliseconds-since-Unix-epoch value (negative values are allowed)
  3714. var re = new RegExp('\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/'),
  3715. r = (input || '').match(re);
  3716. return r? new Date(((r[1] || '') + r[2]) * 1) : null;
  3717. }
  3718. },
  3719. parseRegexes: [],
  3720. /**
  3721. * <p>An object hash in which each property is a date formatting function. The property name is the
  3722. * format string which corresponds to the produced formatted date string.</p>
  3723. * <p>This object is automatically populated with date formatting functions as
  3724. * date formats are requested for Ext standard formatting strings.</p>
  3725. * <p>Custom formatting functions may be inserted into this object, keyed by a name which from then on
  3726. * may be used as a format string to {@link #format}. Example:</p><pre><code>
  3727. Ext.Date.formatFunctions['x-date-format'] = myDateFormatter;
  3728. </code></pre>
  3729. * <p>A formatting function should return a string representation of the passed Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
  3730. * <li><code>date</code> : Date<div class="sub-desc">The Date to format.</div></li>
  3731. * </ul></div></p>
  3732. * <p>To enable date strings to also be <i>parsed</i> according to that format, a corresponding
  3733. * parsing function must be placed into the {@link #parseFunctions} property.
  3734. * @property formatFunctions
  3735. * @type Object
  3736. */
  3737. formatFunctions: {
  3738. "MS": function() {
  3739. // UTC milliseconds since Unix epoch (MS-AJAX serialized date format (MRSF))
  3740. return '\\/Date(' + this.getTime() + ')\\/';
  3741. }
  3742. },
  3743. y2kYear : 50,
  3744. /**
  3745. * Date interval constant
  3746. * @type String
  3747. */
  3748. MILLI : "ms",
  3749. /**
  3750. * Date interval constant
  3751. * @type String
  3752. */
  3753. SECOND : "s",
  3754. /**
  3755. * Date interval constant
  3756. * @type String
  3757. */
  3758. MINUTE : "mi",
  3759. /** Date interval constant
  3760. * @type String
  3761. */
  3762. HOUR : "h",
  3763. /**
  3764. * Date interval constant
  3765. * @type String
  3766. */
  3767. DAY : "d",
  3768. /**
  3769. * Date interval constant
  3770. * @type String
  3771. */
  3772. MONTH : "mo",
  3773. /**
  3774. * Date interval constant
  3775. * @type String
  3776. */
  3777. YEAR : "y",
  3778. /**
  3779. * <p>An object hash containing default date values used during date parsing.</p>
  3780. * <p>The following properties are available:<div class="mdetail-params"><ul>
  3781. * <li><code>y</code> : Number<div class="sub-desc">The default year value. (defaults to undefined)</div></li>
  3782. * <li><code>m</code> : Number<div class="sub-desc">The default 1-based month value. (defaults to undefined)</div></li>
  3783. * <li><code>d</code> : Number<div class="sub-desc">The default day value. (defaults to undefined)</div></li>
  3784. * <li><code>h</code> : Number<div class="sub-desc">The default hour value. (defaults to undefined)</div></li>
  3785. * <li><code>i</code> : Number<div class="sub-desc">The default minute value. (defaults to undefined)</div></li>
  3786. * <li><code>s</code> : Number<div class="sub-desc">The default second value. (defaults to undefined)</div></li>
  3787. * <li><code>ms</code> : Number<div class="sub-desc">The default millisecond value. (defaults to undefined)</div></li>
  3788. * </ul></div></p>
  3789. * <p>Override these properties to customize the default date values used by the {@link #parse} method.</p>
  3790. * <p><b>Note: In countries which experience Daylight Saving Time (i.e. DST), the <tt>h</tt>, <tt>i</tt>, <tt>s</tt>
  3791. * and <tt>ms</tt> properties may coincide with the exact time in which DST takes effect.
  3792. * It is the responsiblity of the developer to account for this.</b></p>
  3793. * Example Usage:
  3794. * <pre><code>
  3795. // set default day value to the first day of the month
  3796. Ext.Date.defaults.d = 1;
  3797. // parse a February date string containing only year and month values.
  3798. // setting the default day value to 1 prevents weird date rollover issues
  3799. // when attempting to parse the following date string on, for example, March 31st 2009.
  3800. Ext.Date.parse('2009-02', 'Y-m'); // returns a Date object representing February 1st 2009
  3801. </code></pre>
  3802. * @property defaults
  3803. * @type Object
  3804. */
  3805. defaults: {},
  3806. //<locale type="array">
  3807. /**
  3808. * @property {String[]} dayNames
  3809. * An array of textual day names.
  3810. * Override these values for international dates.
  3811. * Example:
  3812. * <pre><code>
  3813. Ext.Date.dayNames = [
  3814. 'SundayInYourLang',
  3815. 'MondayInYourLang',
  3816. ...
  3817. ];
  3818. </code></pre>
  3819. */
  3820. dayNames : [
  3821. "Sunday",
  3822. "Monday",
  3823. "Tuesday",
  3824. "Wednesday",
  3825. "Thursday",
  3826. "Friday",
  3827. "Saturday"
  3828. ],
  3829. //</locale>
  3830. //<locale type="array">
  3831. /**
  3832. * @property {String[]} monthNames
  3833. * An array of textual month names.
  3834. * Override these values for international dates.
  3835. * Example:
  3836. * <pre><code>
  3837. Ext.Date.monthNames = [
  3838. 'JanInYourLang',
  3839. 'FebInYourLang',
  3840. ...
  3841. ];
  3842. </code></pre>
  3843. */
  3844. monthNames : [
  3845. "January",
  3846. "February",
  3847. "March",
  3848. "April",
  3849. "May",
  3850. "June",
  3851. "July",
  3852. "August",
  3853. "September",
  3854. "October",
  3855. "November",
  3856. "December"
  3857. ],
  3858. //</locale>
  3859. //<locale type="object">
  3860. /**
  3861. * @property {Object} monthNumbers
  3862. * An object hash of zero-based javascript month numbers (with short month names as keys. note: keys are case-sensitive).
  3863. * Override these values for international dates.
  3864. * Example:
  3865. * <pre><code>
  3866. Ext.Date.monthNumbers = {
  3867. 'LongJanNameInYourLang': 0,
  3868. 'ShortJanNameInYourLang':0,
  3869. 'LongFebNameInYourLang':1,
  3870. 'ShortFebNameInYourLang':1,
  3871. ...
  3872. };
  3873. </code></pre>
  3874. */
  3875. monthNumbers : {
  3876. January: 0,
  3877. Jan: 0,
  3878. February: 1,
  3879. Feb: 1,
  3880. March: 2,
  3881. Mar: 2,
  3882. April: 3,
  3883. Apr: 3,
  3884. May: 4,
  3885. June: 5,
  3886. Jun: 5,
  3887. July: 6,
  3888. Jul: 6,
  3889. August: 7,
  3890. Aug: 7,
  3891. September: 8,
  3892. Sep: 8,
  3893. October: 9,
  3894. Oct: 9,
  3895. November: 10,
  3896. Nov: 10,
  3897. December: 11,
  3898. Dec: 11
  3899. },
  3900. //</locale>
  3901. //<locale>
  3902. /**
  3903. * @property {String} defaultFormat
  3904. * <p>The date format string that the {@link Ext.util.Format#dateRenderer}
  3905. * and {@link Ext.util.Format#date} functions use. See {@link Ext.Date} for details.</p>
  3906. * <p>This may be overridden in a locale file.</p>
  3907. */
  3908. defaultFormat : "m/d/Y",
  3909. //</locale>
  3910. //<locale type="function">
  3911. /**
  3912. * Get the short month name for the given month number.
  3913. * Override this function for international dates.
  3914. * @param {Number} month A zero-based javascript month number.
  3915. * @return {String} The short month name.
  3916. */
  3917. getShortMonthName : function(month) {
  3918. return Ext.Date.monthNames[month].substring(0, 3);
  3919. },
  3920. //</locale>
  3921. //<locale type="function">
  3922. /**
  3923. * Get the short day name for the given day number.
  3924. * Override this function for international dates.
  3925. * @param {Number} day A zero-based javascript day number.
  3926. * @return {String} The short day name.
  3927. */
  3928. getShortDayName : function(day) {
  3929. return Ext.Date.dayNames[day].substring(0, 3);
  3930. },
  3931. //</locale>
  3932. //<locale type="function">
  3933. /**
  3934. * Get the zero-based javascript month number for the given short/full month name.
  3935. * Override this function for international dates.
  3936. * @param {String} name The short/full month name.
  3937. * @return {Number} The zero-based javascript month number.
  3938. */
  3939. getMonthNumber : function(name) {
  3940. // handle camel casing for english month names (since the keys for the Ext.Date.monthNumbers hash are case sensitive)
  3941. return Ext.Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()];
  3942. },
  3943. //</locale>
  3944. /**
  3945. * Checks if the specified format contains hour information
  3946. * @param {String} format The format to check
  3947. * @return {Boolean} True if the format contains hour information
  3948. * @method
  3949. */
  3950. formatContainsHourInfo : (function(){
  3951. var stripEscapeRe = /(\\.)/g,
  3952. hourInfoRe = /([gGhHisucUOPZ]|MS)/;
  3953. return function(format){
  3954. return hourInfoRe.test(format.replace(stripEscapeRe, ''));
  3955. };
  3956. }()),
  3957. /**
  3958. * Checks if the specified format contains information about
  3959. * anything other than the time.
  3960. * @param {String} format The format to check
  3961. * @return {Boolean} True if the format contains information about
  3962. * date/day information.
  3963. * @method
  3964. */
  3965. formatContainsDateInfo : (function(){
  3966. var stripEscapeRe = /(\\.)/g,
  3967. dateInfoRe = /([djzmnYycU]|MS)/;
  3968. return function(format){
  3969. return dateInfoRe.test(format.replace(stripEscapeRe, ''));
  3970. };
  3971. }()),
  3972. /**
  3973. * Removes all escaping for a date format string. In date formats,
  3974. * using a '\' can be used to escape special characters.
  3975. * @param {String} format The format to unescape
  3976. * @return {String} The unescaped format
  3977. * @method
  3978. */
  3979. unescapeFormat: (function() {
  3980. var slashRe = /\\/gi;
  3981. return function(format) {
  3982. // Escape the format, since \ can be used to escape special
  3983. // characters in a date format. For example, in a spanish
  3984. // locale the format may be: 'd \\de F \\de Y'
  3985. return format.replace(slashRe, '');
  3986. }
  3987. }()),
  3988. /**
  3989. * The base format-code to formatting-function hashmap used by the {@link #format} method.
  3990. * Formatting functions are strings (or functions which return strings) which
  3991. * will return the appropriate value when evaluated in the context of the Date object
  3992. * from which the {@link #format} method is called.
  3993. * Add to / override these mappings for custom date formatting.
  3994. * Note: Ext.Date.format() treats characters as literals if an appropriate mapping cannot be found.
  3995. * Example:
  3996. * <pre><code>
  3997. Ext.Date.formatCodes.x = "Ext.util.Format.leftPad(this.getDate(), 2, '0')";
  3998. console.log(Ext.Date.format(new Date(), 'X'); // returns the current day of the month
  3999. </code></pre>
  4000. * @type Object
  4001. */
  4002. formatCodes : {
  4003. d: "Ext.String.leftPad(this.getDate(), 2, '0')",
  4004. D: "Ext.Date.getShortDayName(this.getDay())", // get localised short day name
  4005. j: "this.getDate()",
  4006. l: "Ext.Date.dayNames[this.getDay()]",
  4007. N: "(this.getDay() ? this.getDay() : 7)",
  4008. S: "Ext.Date.getSuffix(this)",
  4009. w: "this.getDay()",
  4010. z: "Ext.Date.getDayOfYear(this)",
  4011. W: "Ext.String.leftPad(Ext.Date.getWeekOfYear(this), 2, '0')",
  4012. F: "Ext.Date.monthNames[this.getMonth()]",
  4013. m: "Ext.String.leftPad(this.getMonth() + 1, 2, '0')",
  4014. M: "Ext.Date.getShortMonthName(this.getMonth())", // get localised short month name
  4015. n: "(this.getMonth() + 1)",
  4016. t: "Ext.Date.getDaysInMonth(this)",
  4017. L: "(Ext.Date.isLeapYear(this) ? 1 : 0)",
  4018. o: "(this.getFullYear() + (Ext.Date.getWeekOfYear(this) == 1 && this.getMonth() > 0 ? +1 : (Ext.Date.getWeekOfYear(this) >= 52 && this.getMonth() < 11 ? -1 : 0)))",
  4019. Y: "Ext.String.leftPad(this.getFullYear(), 4, '0')",
  4020. y: "('' + this.getFullYear()).substring(2, 4)",
  4021. a: "(this.getHours() < 12 ? 'am' : 'pm')",
  4022. A: "(this.getHours() < 12 ? 'AM' : 'PM')",
  4023. g: "((this.getHours() % 12) ? this.getHours() % 12 : 12)",
  4024. G: "this.getHours()",
  4025. h: "Ext.String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')",
  4026. H: "Ext.String.leftPad(this.getHours(), 2, '0')",
  4027. i: "Ext.String.leftPad(this.getMinutes(), 2, '0')",
  4028. s: "Ext.String.leftPad(this.getSeconds(), 2, '0')",
  4029. u: "Ext.String.leftPad(this.getMilliseconds(), 3, '0')",
  4030. O: "Ext.Date.getGMTOffset(this)",
  4031. P: "Ext.Date.getGMTOffset(this, true)",
  4032. T: "Ext.Date.getTimezone(this)",
  4033. Z: "(this.getTimezoneOffset() * -60)",
  4034. c: function() { // ISO-8601 -- GMT format
  4035. var c, code, i, l, e;
  4036. for (c = "Y-m-dTH:i:sP", code = [], i = 0, l = c.length; i < l; ++i) {
  4037. e = c.charAt(i);
  4038. code.push(e == "T" ? "'T'" : utilDate.getFormatCode(e)); // treat T as a character literal
  4039. }
  4040. return code.join(" + ");
  4041. },
  4042. /*
  4043. c: function() { // ISO-8601 -- UTC format
  4044. return [
  4045. "this.getUTCFullYear()", "'-'",
  4046. "Ext.util.Format.leftPad(this.getUTCMonth() + 1, 2, '0')", "'-'",
  4047. "Ext.util.Format.leftPad(this.getUTCDate(), 2, '0')",
  4048. "'T'",
  4049. "Ext.util.Format.leftPad(this.getUTCHours(), 2, '0')", "':'",
  4050. "Ext.util.Format.leftPad(this.getUTCMinutes(), 2, '0')", "':'",
  4051. "Ext.util.Format.leftPad(this.getUTCSeconds(), 2, '0')",
  4052. "'Z'"
  4053. ].join(" + ");
  4054. },
  4055. */
  4056. U: "Math.round(this.getTime() / 1000)"
  4057. },
  4058. /**
  4059. * Checks if the passed Date parameters will cause a javascript Date "rollover".
  4060. * @param {Number} year 4-digit year
  4061. * @param {Number} month 1-based month-of-year
  4062. * @param {Number} day Day of month
  4063. * @param {Number} hour (optional) Hour
  4064. * @param {Number} minute (optional) Minute
  4065. * @param {Number} second (optional) Second
  4066. * @param {Number} millisecond (optional) Millisecond
  4067. * @return {Boolean} true if the passed parameters do not cause a Date "rollover", false otherwise.
  4068. */
  4069. isValid : function(y, m, d, h, i, s, ms) {
  4070. // setup defaults
  4071. h = h || 0;
  4072. i = i || 0;
  4073. s = s || 0;
  4074. ms = ms || 0;
  4075. // Special handling for year < 100
  4076. var dt = utilDate.add(new Date(y < 100 ? 100 : y, m - 1, d, h, i, s, ms), utilDate.YEAR, y < 100 ? y - 100 : 0);
  4077. return y == dt.getFullYear() &&
  4078. m == dt.getMonth() + 1 &&
  4079. d == dt.getDate() &&
  4080. h == dt.getHours() &&
  4081. i == dt.getMinutes() &&
  4082. s == dt.getSeconds() &&
  4083. ms == dt.getMilliseconds();
  4084. },
  4085. /**
  4086. * Parses the passed string using the specified date format.
  4087. * Note that this function expects normal calendar dates, meaning that months are 1-based (i.e. 1 = January).
  4088. * The {@link #defaults} hash will be used for any date value (i.e. year, month, day, hour, minute, second or millisecond)
  4089. * which cannot be found in the passed string. If a corresponding default date value has not been specified in the {@link #defaults} hash,
  4090. * the current date's year, month, day or DST-adjusted zero-hour time value will be used instead.
  4091. * Keep in mind that the input date string must precisely match the specified format string
  4092. * in order for the parse operation to be successful (failed parse operations return a null value).
  4093. * <p>Example:</p><pre><code>
  4094. //dt = Fri May 25 2007 (current date)
  4095. var dt = new Date();
  4096. //dt = Thu May 25 2006 (today&#39;s month/day in 2006)
  4097. dt = Ext.Date.parse("2006", "Y");
  4098. //dt = Sun Jan 15 2006 (all date parts specified)
  4099. dt = Ext.Date.parse("2006-01-15", "Y-m-d");
  4100. //dt = Sun Jan 15 2006 15:20:01
  4101. dt = Ext.Date.parse("2006-01-15 3:20:01 PM", "Y-m-d g:i:s A");
  4102. // attempt to parse Sun Feb 29 2006 03:20:01 in strict mode
  4103. dt = Ext.Date.parse("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
  4104. </code></pre>
  4105. * @param {String} input The raw date string.
  4106. * @param {String} format The expected date string format.
  4107. * @param {Boolean} strict (optional) True to validate date strings while parsing (i.e. prevents javascript Date "rollover")
  4108. (defaults to false). Invalid date strings will return null when parsed.
  4109. * @return {Date} The parsed Date.
  4110. */
  4111. parse : function(input, format, strict) {
  4112. var p = utilDate.parseFunctions;
  4113. if (p[format] == null) {
  4114. utilDate.createParser(format);
  4115. }
  4116. return p[format](input, Ext.isDefined(strict) ? strict : utilDate.useStrict);
  4117. },
  4118. // Backwards compat
  4119. parseDate: function(input, format, strict){
  4120. return utilDate.parse(input, format, strict);
  4121. },
  4122. // private
  4123. getFormatCode : function(character) {
  4124. var f = utilDate.formatCodes[character];
  4125. if (f) {
  4126. f = typeof f == 'function'? f() : f;
  4127. utilDate.formatCodes[character] = f; // reassign function result to prevent repeated execution
  4128. }
  4129. // note: unknown characters are treated as literals
  4130. return f || ("'" + Ext.String.escape(character) + "'");
  4131. },
  4132. // private
  4133. createFormat : function(format) {
  4134. var code = [],
  4135. special = false,
  4136. ch = '',
  4137. i;
  4138. for (i = 0; i < format.length; ++i) {
  4139. ch = format.charAt(i);
  4140. if (!special && ch == "\\") {
  4141. special = true;
  4142. } else if (special) {
  4143. special = false;
  4144. code.push("'" + Ext.String.escape(ch) + "'");
  4145. } else {
  4146. code.push(utilDate.getFormatCode(ch));
  4147. }
  4148. }
  4149. utilDate.formatFunctions[format] = Ext.functionFactory("return " + code.join('+'));
  4150. },
  4151. // private
  4152. createParser : (function() {
  4153. var code = [
  4154. "var dt, y, m, d, h, i, s, ms, o, z, zz, u, v,",
  4155. "def = Ext.Date.defaults,",
  4156. "results = String(input).match(Ext.Date.parseRegexes[{0}]);", // either null, or an array of matched strings
  4157. "if(results){",
  4158. "{1}",
  4159. "if(u != null){", // i.e. unix time is defined
  4160. "v = new Date(u * 1000);", // give top priority to UNIX time
  4161. "}else{",
  4162. // create Date object representing midnight of the current day;
  4163. // this will provide us with our date defaults
  4164. // (note: clearTime() handles Daylight Saving Time automatically)
  4165. "dt = Ext.Date.clearTime(new Date);",
  4166. // date calculations (note: these calculations create a dependency on Ext.Number.from())
  4167. "y = Ext.Number.from(y, Ext.Number.from(def.y, dt.getFullYear()));",
  4168. "m = Ext.Number.from(m, Ext.Number.from(def.m - 1, dt.getMonth()));",
  4169. "d = Ext.Number.from(d, Ext.Number.from(def.d, dt.getDate()));",
  4170. // time calculations (note: these calculations create a dependency on Ext.Number.from())
  4171. "h = Ext.Number.from(h, Ext.Number.from(def.h, dt.getHours()));",
  4172. "i = Ext.Number.from(i, Ext.Number.from(def.i, dt.getMinutes()));",
  4173. "s = Ext.Number.from(s, Ext.Number.from(def.s, dt.getSeconds()));",
  4174. "ms = Ext.Number.from(ms, Ext.Number.from(def.ms, dt.getMilliseconds()));",
  4175. "if(z >= 0 && y >= 0){",
  4176. // both the year and zero-based day of year are defined and >= 0.
  4177. // these 2 values alone provide sufficient info to create a full date object
  4178. // create Date object representing January 1st for the given year
  4179. // handle years < 100 appropriately
  4180. "v = Ext.Date.add(new Date(y < 100 ? 100 : y, 0, 1, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
  4181. // then add day of year, checking for Date "rollover" if necessary
  4182. "v = !strict? v : (strict === true && (z <= 364 || (Ext.Date.isLeapYear(v) && z <= 365))? Ext.Date.add(v, Ext.Date.DAY, z) : null);",
  4183. "}else if(strict === true && !Ext.Date.isValid(y, m + 1, d, h, i, s, ms)){", // check for Date "rollover"
  4184. "v = null;", // invalid date, so return null
  4185. "}else{",
  4186. // plain old Date object
  4187. // handle years < 100 properly
  4188. "v = Ext.Date.add(new Date(y < 100 ? 100 : y, m, d, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
  4189. "}",
  4190. "}",
  4191. "}",
  4192. "if(v){",
  4193. // favour UTC offset over GMT offset
  4194. "if(zz != null){",
  4195. // reset to UTC, then add offset
  4196. "v = Ext.Date.add(v, Ext.Date.SECOND, -v.getTimezoneOffset() * 60 - zz);",
  4197. "}else if(o){",
  4198. // reset to GMT, then add offset
  4199. "v = Ext.Date.add(v, Ext.Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));",
  4200. "}",
  4201. "}",
  4202. "return v;"
  4203. ].join('\n');
  4204. return function(format) {
  4205. var regexNum = utilDate.parseRegexes.length,
  4206. currentGroup = 1,
  4207. calc = [],
  4208. regex = [],
  4209. special = false,
  4210. ch = "",
  4211. i = 0,
  4212. len = format.length,
  4213. atEnd = [],
  4214. obj;
  4215. for (; i < len; ++i) {
  4216. ch = format.charAt(i);
  4217. if (!special && ch == "\\") {
  4218. special = true;
  4219. } else if (special) {
  4220. special = false;
  4221. regex.push(Ext.String.escape(ch));
  4222. } else {
  4223. obj = utilDate.formatCodeToRegex(ch, currentGroup);
  4224. currentGroup += obj.g;
  4225. regex.push(obj.s);
  4226. if (obj.g && obj.c) {
  4227. if (obj.calcAtEnd) {
  4228. atEnd.push(obj.c);
  4229. } else {
  4230. calc.push(obj.c);
  4231. }
  4232. }
  4233. }
  4234. }
  4235. calc = calc.concat(atEnd);
  4236. utilDate.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$", 'i');
  4237. utilDate.parseFunctions[format] = Ext.functionFactory("input", "strict", xf(code, regexNum, calc.join('')));
  4238. };
  4239. }()),
  4240. // private
  4241. parseCodes : {
  4242. /*
  4243. * Notes:
  4244. * g = {Number} calculation group (0 or 1. only group 1 contributes to date calculations.)
  4245. * c = {String} calculation method (required for group 1. null for group 0. {0} = currentGroup - position in regex result array)
  4246. * s = {String} regex pattern. all matches are stored in results[], and are accessible by the calculation mapped to 'c'
  4247. */
  4248. d: {
  4249. g:1,
  4250. c:"d = parseInt(results[{0}], 10);\n",
  4251. s:"(3[0-1]|[1-2][0-9]|0[1-9])" // day of month with leading zeroes (01 - 31)
  4252. },
  4253. j: {
  4254. g:1,
  4255. c:"d = parseInt(results[{0}], 10);\n",
  4256. s:"(3[0-1]|[1-2][0-9]|[1-9])" // day of month without leading zeroes (1 - 31)
  4257. },
  4258. D: function() {
  4259. for (var a = [], i = 0; i < 7; a.push(utilDate.getShortDayName(i)), ++i); // get localised short day names
  4260. return {
  4261. g:0,
  4262. c:null,
  4263. s:"(?:" + a.join("|") +")"
  4264. };
  4265. },
  4266. l: function() {
  4267. return {
  4268. g:0,
  4269. c:null,
  4270. s:"(?:" + utilDate.dayNames.join("|") + ")"
  4271. };
  4272. },
  4273. N: {
  4274. g:0,
  4275. c:null,
  4276. s:"[1-7]" // ISO-8601 day number (1 (monday) - 7 (sunday))
  4277. },
  4278. //<locale type="object" property="parseCodes">
  4279. S: {
  4280. g:0,
  4281. c:null,
  4282. s:"(?:st|nd|rd|th)"
  4283. },
  4284. //</locale>
  4285. w: {
  4286. g:0,
  4287. c:null,
  4288. s:"[0-6]" // javascript day number (0 (sunday) - 6 (saturday))
  4289. },
  4290. z: {
  4291. g:1,
  4292. c:"z = parseInt(results[{0}], 10);\n",
  4293. s:"(\\d{1,3})" // day of the year (0 - 364 (365 in leap years))
  4294. },
  4295. W: {
  4296. g:0,
  4297. c:null,
  4298. s:"(?:\\d{2})" // ISO-8601 week number (with leading zero)
  4299. },
  4300. F: function() {
  4301. return {
  4302. g:1,
  4303. c:"m = parseInt(Ext.Date.getMonthNumber(results[{0}]), 10);\n", // get localised month number
  4304. s:"(" + utilDate.monthNames.join("|") + ")"
  4305. };
  4306. },
  4307. M: function() {
  4308. for (var a = [], i = 0; i < 12; a.push(utilDate.getShortMonthName(i)), ++i); // get localised short month names
  4309. return Ext.applyIf({
  4310. s:"(" + a.join("|") + ")"
  4311. }, utilDate.formatCodeToRegex("F"));
  4312. },
  4313. m: {
  4314. g:1,
  4315. c:"m = parseInt(results[{0}], 10) - 1;\n",
  4316. s:"(1[0-2]|0[1-9])" // month number with leading zeros (01 - 12)
  4317. },
  4318. n: {
  4319. g:1,
  4320. c:"m = parseInt(results[{0}], 10) - 1;\n",
  4321. s:"(1[0-2]|[1-9])" // month number without leading zeros (1 - 12)
  4322. },
  4323. t: {
  4324. g:0,
  4325. c:null,
  4326. s:"(?:\\d{2})" // no. of days in the month (28 - 31)
  4327. },
  4328. L: {
  4329. g:0,
  4330. c:null,
  4331. s:"(?:1|0)"
  4332. },
  4333. o: function() {
  4334. return utilDate.formatCodeToRegex("Y");
  4335. },
  4336. Y: {
  4337. g:1,
  4338. c:"y = parseInt(results[{0}], 10);\n",
  4339. s:"(\\d{4})" // 4-digit year
  4340. },
  4341. y: {
  4342. g:1,
  4343. c:"var ty = parseInt(results[{0}], 10);\n"
  4344. + "y = ty > Ext.Date.y2kYear ? 1900 + ty : 2000 + ty;\n", // 2-digit year
  4345. s:"(\\d{1,2})"
  4346. },
  4347. /*
  4348. * In the am/pm parsing routines, we allow both upper and lower case
  4349. * even though it doesn't exactly match the spec. It gives much more flexibility
  4350. * in being able to specify case insensitive regexes.
  4351. */
  4352. //<locale type="object" property="parseCodes">
  4353. a: {
  4354. g:1,
  4355. c:"if (/(am)/i.test(results[{0}])) {\n"
  4356. + "if (!h || h == 12) { h = 0; }\n"
  4357. + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
  4358. s:"(am|pm|AM|PM)",
  4359. calcAtEnd: true
  4360. },
  4361. //</locale>
  4362. //<locale type="object" property="parseCodes">
  4363. A: {
  4364. g:1,
  4365. c:"if (/(am)/i.test(results[{0}])) {\n"
  4366. + "if (!h || h == 12) { h = 0; }\n"
  4367. + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
  4368. s:"(AM|PM|am|pm)",
  4369. calcAtEnd: true
  4370. },
  4371. //</locale>
  4372. g: {
  4373. g:1,
  4374. c:"h = parseInt(results[{0}], 10);\n",
  4375. s:"(1[0-2]|[0-9])" // 12-hr format of an hour without leading zeroes (1 - 12)
  4376. },
  4377. G: {
  4378. g:1,
  4379. c:"h = parseInt(results[{0}], 10);\n",
  4380. s:"(2[0-3]|1[0-9]|[0-9])" // 24-hr format of an hour without leading zeroes (0 - 23)
  4381. },
  4382. h: {
  4383. g:1,
  4384. c:"h = parseInt(results[{0}], 10);\n",
  4385. s:"(1[0-2]|0[1-9])" // 12-hr format of an hour with leading zeroes (01 - 12)
  4386. },
  4387. H: {
  4388. g:1,
  4389. c:"h = parseInt(results[{0}], 10);\n",
  4390. s:"(2[0-3]|[0-1][0-9])" // 24-hr format of an hour with leading zeroes (00 - 23)
  4391. },
  4392. i: {
  4393. g:1,
  4394. c:"i = parseInt(results[{0}], 10);\n",
  4395. s:"([0-5][0-9])" // minutes with leading zeros (00 - 59)
  4396. },
  4397. s: {
  4398. g:1,
  4399. c:"s = parseInt(results[{0}], 10);\n",
  4400. s:"([0-5][0-9])" // seconds with leading zeros (00 - 59)
  4401. },
  4402. u: {
  4403. g:1,
  4404. c:"ms = results[{0}]; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n",
  4405. s:"(\\d+)" // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
  4406. },
  4407. O: {
  4408. g:1,
  4409. c:[
  4410. "o = results[{0}];",
  4411. "var sn = o.substring(0,1),", // get + / - sign
  4412. "hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
  4413. "mn = o.substring(3,5) % 60;", // get minutes
  4414. "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.String.leftPad(hr, 2, '0') + Ext.String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs
  4415. ].join("\n"),
  4416. s: "([+-]\\d{4})" // GMT offset in hrs and mins
  4417. },
  4418. P: {
  4419. g:1,
  4420. c:[
  4421. "o = results[{0}];",
  4422. "var sn = o.substring(0,1),", // get + / - sign
  4423. "hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
  4424. "mn = o.substring(4,6) % 60;", // get minutes
  4425. "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.String.leftPad(hr, 2, '0') + Ext.String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs
  4426. ].join("\n"),
  4427. s: "([+-]\\d{2}:\\d{2})" // GMT offset in hrs and mins (with colon separator)
  4428. },
  4429. T: {
  4430. g:0,
  4431. c:null,
  4432. s:"[A-Z]{1,4}" // timezone abbrev. may be between 1 - 4 chars
  4433. },
  4434. Z: {
  4435. g:1,
  4436. c:"zz = results[{0}] * 1;\n" // -43200 <= UTC offset <= 50400
  4437. + "zz = (-43200 <= zz && zz <= 50400)? zz : null;\n",
  4438. s:"([+-]?\\d{1,5})" // leading '+' sign is optional for UTC offset
  4439. },
  4440. c: function() {
  4441. var calc = [],
  4442. arr = [
  4443. utilDate.formatCodeToRegex("Y", 1), // year
  4444. utilDate.formatCodeToRegex("m", 2), // month
  4445. utilDate.formatCodeToRegex("d", 3), // day
  4446. utilDate.formatCodeToRegex("H", 4), // hour
  4447. utilDate.formatCodeToRegex("i", 5), // minute
  4448. utilDate.formatCodeToRegex("s", 6), // second
  4449. {c:"ms = results[7] || '0'; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n"}, // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
  4450. {c:[ // allow either "Z" (i.e. UTC) or "-0530" or "+08:00" (i.e. UTC offset) timezone delimiters. assumes local timezone if no timezone is specified
  4451. "if(results[8]) {", // timezone specified
  4452. "if(results[8] == 'Z'){",
  4453. "zz = 0;", // UTC
  4454. "}else if (results[8].indexOf(':') > -1){",
  4455. utilDate.formatCodeToRegex("P", 8).c, // timezone offset with colon separator
  4456. "}else{",
  4457. utilDate.formatCodeToRegex("O", 8).c, // timezone offset without colon separator
  4458. "}",
  4459. "}"
  4460. ].join('\n')}
  4461. ],
  4462. i,
  4463. l;
  4464. for (i = 0, l = arr.length; i < l; ++i) {
  4465. calc.push(arr[i].c);
  4466. }
  4467. return {
  4468. g:1,
  4469. c:calc.join(""),
  4470. s:[
  4471. arr[0].s, // year (required)
  4472. "(?:", "-", arr[1].s, // month (optional)
  4473. "(?:", "-", arr[2].s, // day (optional)
  4474. "(?:",
  4475. "(?:T| )?", // time delimiter -- either a "T" or a single blank space
  4476. arr[3].s, ":", arr[4].s, // hour AND minute, delimited by a single colon (optional). MUST be preceded by either a "T" or a single blank space
  4477. "(?::", arr[5].s, ")?", // seconds (optional)
  4478. "(?:(?:\\.|,)(\\d+))?", // decimal fraction of a second (e.g. ",12345" or ".98765") (optional)
  4479. "(Z|(?:[-+]\\d{2}(?::)?\\d{2}))?", // "Z" (UTC) or "-0530" (UTC offset without colon delimiter) or "+08:00" (UTC offset with colon delimiter) (optional)
  4480. ")?",
  4481. ")?",
  4482. ")?"
  4483. ].join("")
  4484. };
  4485. },
  4486. U: {
  4487. g:1,
  4488. c:"u = parseInt(results[{0}], 10);\n",
  4489. s:"(-?\\d+)" // leading minus sign indicates seconds before UNIX epoch
  4490. }
  4491. },
  4492. //Old Ext.Date prototype methods.
  4493. // private
  4494. dateFormat: function(date, format) {
  4495. return utilDate.format(date, format);
  4496. },
  4497. /**
  4498. * Compares if two dates are equal by comparing their values.
  4499. * @param {Date} date1
  4500. * @param {Date} date2
  4501. * @return {Boolean} True if the date values are equal
  4502. */
  4503. isEqual: function(date1, date2) {
  4504. // check we have 2 date objects
  4505. if (date1 && date2) {
  4506. return (date1.getTime() === date2.getTime());
  4507. }
  4508. // one or both isn't a date, only equal if both are falsey
  4509. return !(date1 || date2);
  4510. },
  4511. /**
  4512. * Formats a date given the supplied format string.
  4513. * @param {Date} date The date to format
  4514. * @param {String} format The format string
  4515. * @return {String} The formatted date or an empty string if date parameter is not a JavaScript Date object
  4516. */
  4517. format: function(date, format) {
  4518. var formatFunctions = utilDate.formatFunctions;
  4519. if (!Ext.isDate(date)) {
  4520. return '';
  4521. }
  4522. if (formatFunctions[format] == null) {
  4523. utilDate.createFormat(format);
  4524. }
  4525. return formatFunctions[format].call(date) + '';
  4526. },
  4527. /**
  4528. * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
  4529. *
  4530. * Note: The date string returned by the javascript Date object's toString() method varies
  4531. * between browsers (e.g. FF vs IE) and system region settings (e.g. IE in Asia vs IE in America).
  4532. * For a given date string e.g. "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)",
  4533. * getTimezone() first tries to get the timezone abbreviation from between a pair of parentheses
  4534. * (which may or may not be present), failing which it proceeds to get the timezone abbreviation
  4535. * from the GMT offset portion of the date string.
  4536. * @param {Date} date The date
  4537. * @return {String} The abbreviated timezone name (e.g. 'CST', 'PDT', 'EDT', 'MPST' ...).
  4538. */
  4539. getTimezone : function(date) {
  4540. // the following list shows the differences between date strings from different browsers on a WinXP SP2 machine from an Asian locale:
  4541. //
  4542. // Opera : "Thu, 25 Oct 2007 22:53:45 GMT+0800" -- shortest (weirdest) date string of the lot
  4543. // Safari : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone (same as FF)
  4544. // FF : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone
  4545. // IE : "Thu Oct 25 22:54:35 UTC+0800 2007" -- (Asian system setting) look for 3-4 letter timezone abbrev
  4546. // IE : "Thu Oct 25 17:06:37 PDT 2007" -- (American system setting) look for 3-4 letter timezone abbrev
  4547. //
  4548. // this crazy regex attempts to guess the correct timezone abbreviation despite these differences.
  4549. // step 1: (?:\((.*)\) -- find timezone in parentheses
  4550. // step 2: ([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?) -- if nothing was found in step 1, find timezone from timezone offset portion of date string
  4551. // step 3: remove all non uppercase characters found in step 1 and 2
  4552. return date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, "");
  4553. },
  4554. /**
  4555. * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
  4556. * @param {Date} date The date
  4557. * @param {Boolean} colon (optional) true to separate the hours and minutes with a colon (defaults to false).
  4558. * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600').
  4559. */
  4560. getGMTOffset : function(date, colon) {
  4561. var offset = date.getTimezoneOffset();
  4562. return (offset > 0 ? "-" : "+")
  4563. + Ext.String.leftPad(Math.floor(Math.abs(offset) / 60), 2, "0")
  4564. + (colon ? ":" : "")
  4565. + Ext.String.leftPad(Math.abs(offset % 60), 2, "0");
  4566. },
  4567. /**
  4568. * Get the numeric day number of the year, adjusted for leap year.
  4569. * @param {Date} date The date
  4570. * @return {Number} 0 to 364 (365 in leap years).
  4571. */
  4572. getDayOfYear: function(date) {
  4573. var num = 0,
  4574. d = Ext.Date.clone(date),
  4575. m = date.getMonth(),
  4576. i;
  4577. for (i = 0, d.setDate(1), d.setMonth(0); i < m; d.setMonth(++i)) {
  4578. num += utilDate.getDaysInMonth(d);
  4579. }
  4580. return num + date.getDate() - 1;
  4581. },
  4582. /**
  4583. * Get the numeric ISO-8601 week number of the year.
  4584. * (equivalent to the format specifier 'W', but without a leading zero).
  4585. * @param {Date} date The date
  4586. * @return {Number} 1 to 53
  4587. * @method
  4588. */
  4589. getWeekOfYear : (function() {
  4590. // adapted from http://www.merlyn.demon.co.uk/weekcalc.htm
  4591. var ms1d = 864e5, // milliseconds in a day
  4592. ms7d = 7 * ms1d; // milliseconds in a week
  4593. return function(date) { // return a closure so constants get calculated only once
  4594. var DC3 = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate() + 3) / ms1d, // an Absolute Day Number
  4595. AWN = Math.floor(DC3 / 7), // an Absolute Week Number
  4596. Wyr = new Date(AWN * ms7d).getUTCFullYear();
  4597. return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1;
  4598. };
  4599. }()),
  4600. /**
  4601. * Checks if the current date falls within a leap year.
  4602. * @param {Date} date The date
  4603. * @return {Boolean} True if the current date falls within a leap year, false otherwise.
  4604. */
  4605. isLeapYear : function(date) {
  4606. var year = date.getFullYear();
  4607. return !!((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
  4608. },
  4609. /**
  4610. * Get the first day of the current month, adjusted for leap year. The returned value
  4611. * is the numeric day index within the week (0-6) which can be used in conjunction with
  4612. * the {@link #monthNames} array to retrieve the textual day name.
  4613. * Example:
  4614. * <pre><code>
  4615. var dt = new Date('1/10/2007'),
  4616. firstDay = Ext.Date.getFirstDayOfMonth(dt);
  4617. console.log(Ext.Date.dayNames[firstDay]); //output: 'Monday'
  4618. * </code></pre>
  4619. * @param {Date} date The date
  4620. * @return {Number} The day number (0-6).
  4621. */
  4622. getFirstDayOfMonth : function(date) {
  4623. var day = (date.getDay() - (date.getDate() - 1)) % 7;
  4624. return (day < 0) ? (day + 7) : day;
  4625. },
  4626. /**
  4627. * Get the last day of the current month, adjusted for leap year. The returned value
  4628. * is the numeric day index within the week (0-6) which can be used in conjunction with
  4629. * the {@link #monthNames} array to retrieve the textual day name.
  4630. * Example:
  4631. * <pre><code>
  4632. var dt = new Date('1/10/2007'),
  4633. lastDay = Ext.Date.getLastDayOfMonth(dt);
  4634. console.log(Ext.Date.dayNames[lastDay]); //output: 'Wednesday'
  4635. * </code></pre>
  4636. * @param {Date} date The date
  4637. * @return {Number} The day number (0-6).
  4638. */
  4639. getLastDayOfMonth : function(date) {
  4640. return utilDate.getLastDateOfMonth(date).getDay();
  4641. },
  4642. /**
  4643. * Get the date of the first day of the month in which this date resides.
  4644. * @param {Date} date The date
  4645. * @return {Date}
  4646. */
  4647. getFirstDateOfMonth : function(date) {
  4648. return new Date(date.getFullYear(), date.getMonth(), 1);
  4649. },
  4650. /**
  4651. * Get the date of the last day of the month in which this date resides.
  4652. * @param {Date} date The date
  4653. * @return {Date}
  4654. */
  4655. getLastDateOfMonth : function(date) {
  4656. return new Date(date.getFullYear(), date.getMonth(), utilDate.getDaysInMonth(date));
  4657. },
  4658. /**
  4659. * Get the number of days in the current month, adjusted for leap year.
  4660. * @param {Date} date The date
  4661. * @return {Number} The number of days in the month.
  4662. * @method
  4663. */
  4664. getDaysInMonth: (function() {
  4665. var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  4666. return function(date) { // return a closure for efficiency
  4667. var m = date.getMonth();
  4668. return m == 1 && utilDate.isLeapYear(date) ? 29 : daysInMonth[m];
  4669. };
  4670. }()),
  4671. //<locale type="function">
  4672. /**
  4673. * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
  4674. * @param {Date} date The date
  4675. * @return {String} 'st, 'nd', 'rd' or 'th'.
  4676. */
  4677. getSuffix : function(date) {
  4678. switch (date.getDate()) {
  4679. case 1:
  4680. case 21:
  4681. case 31:
  4682. return "st";
  4683. case 2:
  4684. case 22:
  4685. return "nd";
  4686. case 3:
  4687. case 23:
  4688. return "rd";
  4689. default:
  4690. return "th";
  4691. }
  4692. },
  4693. //</locale>
  4694. /**
  4695. * Creates and returns a new Date instance with the exact same date value as the called instance.
  4696. * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
  4697. * variable will also be changed. When the intention is to create a new variable that will not
  4698. * modify the original instance, you should create a clone.
  4699. *
  4700. * Example of correctly cloning a date:
  4701. * <pre><code>
  4702. //wrong way:
  4703. var orig = new Date('10/1/2006');
  4704. var copy = orig;
  4705. copy.setDate(5);
  4706. console.log(orig); //returns 'Thu Oct 05 2006'!
  4707. //correct way:
  4708. var orig = new Date('10/1/2006'),
  4709. copy = Ext.Date.clone(orig);
  4710. copy.setDate(5);
  4711. console.log(orig); //returns 'Thu Oct 01 2006'
  4712. * </code></pre>
  4713. * @param {Date} date The date
  4714. * @return {Date} The new Date instance.
  4715. */
  4716. clone : function(date) {
  4717. return new Date(date.getTime());
  4718. },
  4719. /**
  4720. * Checks if the current date is affected by Daylight Saving Time (DST).
  4721. * @param {Date} date The date
  4722. * @return {Boolean} True if the current date is affected by DST.
  4723. */
  4724. isDST : function(date) {
  4725. // adapted from http://sencha.com/forum/showthread.php?p=247172#post247172
  4726. // courtesy of @geoffrey.mcgill
  4727. return new Date(date.getFullYear(), 0, 1).getTimezoneOffset() != date.getTimezoneOffset();
  4728. },
  4729. /**
  4730. * Attempts to clear all time information from this Date by setting the time to midnight of the same day,
  4731. * automatically adjusting for Daylight Saving Time (DST) where applicable.
  4732. * (note: DST timezone information for the browser's host operating system is assumed to be up-to-date)
  4733. * @param {Date} date The date
  4734. * @param {Boolean} clone true to create a clone of this date, clear the time and return it (defaults to false).
  4735. * @return {Date} this or the clone.
  4736. */
  4737. clearTime : function(date, clone) {
  4738. if (clone) {
  4739. return Ext.Date.clearTime(Ext.Date.clone(date));
  4740. }
  4741. // get current date before clearing time
  4742. var d = date.getDate(),
  4743. hr,
  4744. c;
  4745. // clear time
  4746. date.setHours(0);
  4747. date.setMinutes(0);
  4748. date.setSeconds(0);
  4749. date.setMilliseconds(0);
  4750. if (date.getDate() != d) { // account for DST (i.e. day of month changed when setting hour = 0)
  4751. // note: DST adjustments are assumed to occur in multiples of 1 hour (this is almost always the case)
  4752. // refer to http://www.timeanddate.com/time/aboutdst.html for the (rare) exceptions to this rule
  4753. // increment hour until cloned date == current date
  4754. for (hr = 1, c = utilDate.add(date, Ext.Date.HOUR, hr); c.getDate() != d; hr++, c = utilDate.add(date, Ext.Date.HOUR, hr));
  4755. date.setDate(d);
  4756. date.setHours(c.getHours());
  4757. }
  4758. return date;
  4759. },
  4760. /**
  4761. * Provides a convenient method for performing basic date arithmetic. This method
  4762. * does not modify the Date instance being called - it creates and returns
  4763. * a new Date instance containing the resulting date value.
  4764. *
  4765. * Examples:
  4766. * <pre><code>
  4767. // Basic usage:
  4768. var dt = Ext.Date.add(new Date('10/29/2006'), Ext.Date.DAY, 5);
  4769. console.log(dt); //returns 'Fri Nov 03 2006 00:00:00'
  4770. // Negative values will be subtracted:
  4771. var dt2 = Ext.Date.add(new Date('10/1/2006'), Ext.Date.DAY, -5);
  4772. console.log(dt2); //returns 'Tue Sep 26 2006 00:00:00'
  4773. * </code></pre>
  4774. *
  4775. * @param {Date} date The date to modify
  4776. * @param {String} interval A valid date interval enum value.
  4777. * @param {Number} value The amount to add to the current date.
  4778. * @return {Date} The new Date instance.
  4779. */
  4780. add : function(date, interval, value) {
  4781. var d = Ext.Date.clone(date),
  4782. Date = Ext.Date,
  4783. day;
  4784. if (!interval || value === 0) {
  4785. return d;
  4786. }
  4787. switch(interval.toLowerCase()) {
  4788. case Ext.Date.MILLI:
  4789. d.setMilliseconds(d.getMilliseconds() + value);
  4790. break;
  4791. case Ext.Date.SECOND:
  4792. d.setSeconds(d.getSeconds() + value);
  4793. break;
  4794. case Ext.Date.MINUTE:
  4795. d.setMinutes(d.getMinutes() + value);
  4796. break;
  4797. case Ext.Date.HOUR:
  4798. d.setHours(d.getHours() + value);
  4799. break;
  4800. case Ext.Date.DAY:
  4801. d.setDate(d.getDate() + value);
  4802. break;
  4803. case Ext.Date.MONTH:
  4804. day = date.getDate();
  4805. if (day > 28) {
  4806. day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), Ext.Date.MONTH, value)).getDate());
  4807. }
  4808. d.setDate(day);
  4809. d.setMonth(date.getMonth() + value);
  4810. break;
  4811. case Ext.Date.YEAR:
  4812. day = date.getDate();
  4813. if (day > 28) {
  4814. day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), Ext.Date.YEAR, value)).getDate());
  4815. }
  4816. d.setDate(day);
  4817. d.setFullYear(date.getFullYear() + value);
  4818. break;
  4819. }
  4820. return d;
  4821. },
  4822. /**
  4823. * Checks if a date falls on or between the given start and end dates.
  4824. * @param {Date} date The date to check
  4825. * @param {Date} start Start date
  4826. * @param {Date} end End date
  4827. * @return {Boolean} true if this date falls on or between the given start and end dates.
  4828. */
  4829. between : function(date, start, end) {
  4830. var t = date.getTime();
  4831. return start.getTime() <= t && t <= end.getTime();
  4832. },
  4833. //Maintains compatibility with old static and prototype window.Date methods.
  4834. compat: function() {
  4835. var nativeDate = window.Date,
  4836. p, u,
  4837. statics = ['useStrict', 'formatCodeToRegex', 'parseFunctions', 'parseRegexes', 'formatFunctions', 'y2kYear', 'MILLI', 'SECOND', 'MINUTE', 'HOUR', 'DAY', 'MONTH', 'YEAR', 'defaults', 'dayNames', 'monthNames', 'monthNumbers', 'getShortMonthName', 'getShortDayName', 'getMonthNumber', 'formatCodes', 'isValid', 'parseDate', 'getFormatCode', 'createFormat', 'createParser', 'parseCodes'],
  4838. proto = ['dateFormat', 'format', 'getTimezone', 'getGMTOffset', 'getDayOfYear', 'getWeekOfYear', 'isLeapYear', 'getFirstDayOfMonth', 'getLastDayOfMonth', 'getDaysInMonth', 'getSuffix', 'clone', 'isDST', 'clearTime', 'add', 'between'],
  4839. sLen = statics.length,
  4840. pLen = proto.length,
  4841. stat, prot, s;
  4842. //Append statics
  4843. for (s = 0; s < sLen; s++) {
  4844. stat = statics[s];
  4845. nativeDate[stat] = utilDate[stat];
  4846. }
  4847. //Append to prototype
  4848. for (p = 0; p < pLen; p++) {
  4849. prot = proto[p];
  4850. nativeDate.prototype[prot] = function() {
  4851. var args = Array.prototype.slice.call(arguments);
  4852. args.unshift(this);
  4853. return utilDate[prot].apply(utilDate, args);
  4854. };
  4855. }
  4856. }
  4857. };
  4858. var utilDate = Ext.Date;
  4859. }());
  4860. //@tag foundation,core
  4861. //@require ../lang/Date.js
  4862. /**
  4863. * @author Jacky Nguyen <jacky@sencha.com>
  4864. * @docauthor Jacky Nguyen <jacky@sencha.com>
  4865. * @class Ext.Base
  4866. *
  4867. * The root of all classes created with {@link Ext#define}.
  4868. *
  4869. * Ext.Base is the building block of all Ext classes. All classes in Ext inherit from Ext.Base.
  4870. * All prototype and static members of this class are inherited by all other classes.
  4871. */
  4872. (function(flexSetter) {
  4873. var noArgs = [],
  4874. Base = function(){};
  4875. // These static properties will be copied to every newly created class with {@link Ext#define}
  4876. Ext.apply(Base, {
  4877. $className: 'Ext.Base',
  4878. $isClass: true,
  4879. /**
  4880. * Create a new instance of this Class.
  4881. *
  4882. * Ext.define('My.cool.Class', {
  4883. * ...
  4884. * });
  4885. *
  4886. * My.cool.Class.create({
  4887. * someConfig: true
  4888. * });
  4889. *
  4890. * All parameters are passed to the constructor of the class.
  4891. *
  4892. * @return {Object} the created instance.
  4893. * @static
  4894. * @inheritable
  4895. */
  4896. create: function() {
  4897. return Ext.create.apply(Ext, [this].concat(Array.prototype.slice.call(arguments, 0)));
  4898. },
  4899. /**
  4900. * @private
  4901. * @static
  4902. * @inheritable
  4903. * @param config
  4904. */
  4905. extend: function(parent) {
  4906. var parentPrototype = parent.prototype,
  4907. basePrototype, prototype, i, ln, name, statics;
  4908. prototype = this.prototype = Ext.Object.chain(parentPrototype);
  4909. prototype.self = this;
  4910. this.superclass = prototype.superclass = parentPrototype;
  4911. if (!parent.$isClass) {
  4912. basePrototype = Ext.Base.prototype;
  4913. for (i in basePrototype) {
  4914. if (i in prototype) {
  4915. prototype[i] = basePrototype[i];
  4916. }
  4917. }
  4918. }
  4919. // Statics inheritance
  4920. statics = parentPrototype.$inheritableStatics;
  4921. if (statics) {
  4922. for (i = 0,ln = statics.length; i < ln; i++) {
  4923. name = statics[i];
  4924. if (!this.hasOwnProperty(name)) {
  4925. this[name] = parent[name];
  4926. }
  4927. }
  4928. }
  4929. if (parent.$onExtended) {
  4930. this.$onExtended = parent.$onExtended.slice();
  4931. }
  4932. prototype.config = new prototype.configClass();
  4933. prototype.initConfigList = prototype.initConfigList.slice();
  4934. prototype.initConfigMap = Ext.clone(prototype.initConfigMap);
  4935. prototype.configMap = Ext.Object.chain(prototype.configMap);
  4936. },
  4937. /**
  4938. * @private
  4939. * @static
  4940. * @inheritable
  4941. */
  4942. $onExtended: [],
  4943. /**
  4944. * @private
  4945. * @static
  4946. * @inheritable
  4947. */
  4948. triggerExtended: function() {
  4949. var callbacks = this.$onExtended,
  4950. ln = callbacks.length,
  4951. i, callback;
  4952. if (ln > 0) {
  4953. for (i = 0; i < ln; i++) {
  4954. callback = callbacks[i];
  4955. callback.fn.apply(callback.scope || this, arguments);
  4956. }
  4957. }
  4958. },
  4959. /**
  4960. * @private
  4961. * @static
  4962. * @inheritable
  4963. */
  4964. onExtended: function(fn, scope) {
  4965. this.$onExtended.push({
  4966. fn: fn,
  4967. scope: scope
  4968. });
  4969. return this;
  4970. },
  4971. /**
  4972. * @private
  4973. * @static
  4974. * @inheritable
  4975. * @param config
  4976. */
  4977. addConfig: function(config, fullMerge) {
  4978. var prototype = this.prototype,
  4979. configNameCache = Ext.Class.configNameCache,
  4980. hasConfig = prototype.configMap,
  4981. initConfigList = prototype.initConfigList,
  4982. initConfigMap = prototype.initConfigMap,
  4983. defaultConfig = prototype.config,
  4984. initializedName, name, value;
  4985. for (name in config) {
  4986. if (config.hasOwnProperty(name)) {
  4987. if (!hasConfig[name]) {
  4988. hasConfig[name] = true;
  4989. }
  4990. value = config[name];
  4991. initializedName = configNameCache[name].initialized;
  4992. if (!initConfigMap[name] && value !== null && !prototype[initializedName]) {
  4993. initConfigMap[name] = true;
  4994. initConfigList.push(name);
  4995. }
  4996. }
  4997. }
  4998. if (fullMerge) {
  4999. Ext.merge(defaultConfig, config);
  5000. }
  5001. else {
  5002. Ext.mergeIf(defaultConfig, config);
  5003. }
  5004. prototype.configClass = Ext.Object.classify(defaultConfig);
  5005. },
  5006. /**
  5007. * Add / override static properties of this class.
  5008. *
  5009. * Ext.define('My.cool.Class', {
  5010. * ...
  5011. * });
  5012. *
  5013. * My.cool.Class.addStatics({
  5014. * someProperty: 'someValue', // My.cool.Class.someProperty = 'someValue'
  5015. * method1: function() { ... }, // My.cool.Class.method1 = function() { ... };
  5016. * method2: function() { ... } // My.cool.Class.method2 = function() { ... };
  5017. * });
  5018. *
  5019. * @param {Object} members
  5020. * @return {Ext.Base} this
  5021. * @static
  5022. * @inheritable
  5023. */
  5024. addStatics: function(members) {
  5025. var member, name;
  5026. for (name in members) {
  5027. if (members.hasOwnProperty(name)) {
  5028. member = members[name];
  5029. if (typeof member == 'function' && !member.$isClass && member !== Ext.emptyFn && member !== Ext.identityFn) {
  5030. member.$owner = this;
  5031. member.$name = name;
  5032. member.displayName = Ext.getClassName(this) + '.' + name;
  5033. }
  5034. this[name] = member;
  5035. }
  5036. }
  5037. return this;
  5038. },
  5039. /**
  5040. * @private
  5041. * @static
  5042. * @inheritable
  5043. * @param {Object} members
  5044. */
  5045. addInheritableStatics: function(members) {
  5046. var inheritableStatics,
  5047. hasInheritableStatics,
  5048. prototype = this.prototype,
  5049. name, member;
  5050. inheritableStatics = prototype.$inheritableStatics;
  5051. hasInheritableStatics = prototype.$hasInheritableStatics;
  5052. if (!inheritableStatics) {
  5053. inheritableStatics = prototype.$inheritableStatics = [];
  5054. hasInheritableStatics = prototype.$hasInheritableStatics = {};
  5055. }
  5056. for (name in members) {
  5057. if (members.hasOwnProperty(name)) {
  5058. member = members[name];
  5059. if (typeof member == 'function') {
  5060. member.displayName = Ext.getClassName(this) + '.' + name;
  5061. }
  5062. this[name] = member;
  5063. if (!hasInheritableStatics[name]) {
  5064. hasInheritableStatics[name] = true;
  5065. inheritableStatics.push(name);
  5066. }
  5067. }
  5068. }
  5069. return this;
  5070. },
  5071. /**
  5072. * Add methods / properties to the prototype of this class.
  5073. *
  5074. * Ext.define('My.awesome.Cat', {
  5075. * constructor: function() {
  5076. * ...
  5077. * }
  5078. * });
  5079. *
  5080. * My.awesome.Cat.addMembers({
  5081. * meow: function() {
  5082. * alert('Meowww...');
  5083. * }
  5084. * });
  5085. *
  5086. * var kitty = new My.awesome.Cat;
  5087. * kitty.meow();
  5088. *
  5089. * @param {Object} members
  5090. * @static
  5091. * @inheritable
  5092. */
  5093. addMembers: function(members) {
  5094. var prototype = this.prototype,
  5095. enumerables = Ext.enumerables,
  5096. names = [],
  5097. i, ln, name, member;
  5098. for (name in members) {
  5099. names.push(name);
  5100. }
  5101. if (enumerables) {
  5102. names.push.apply(names, enumerables);
  5103. }
  5104. for (i = 0,ln = names.length; i < ln; i++) {
  5105. name = names[i];
  5106. if (members.hasOwnProperty(name)) {
  5107. member = members[name];
  5108. if (typeof member == 'function' && !member.$isClass && member !== Ext.emptyFn) {
  5109. member.$owner = this;
  5110. member.$name = name;
  5111. member.displayName = (this.$className || '') + '#' + name;
  5112. }
  5113. prototype[name] = member;
  5114. }
  5115. }
  5116. return this;
  5117. },
  5118. /**
  5119. * @private
  5120. * @static
  5121. * @inheritable
  5122. * @param name
  5123. * @param member
  5124. */
  5125. addMember: function(name, member) {
  5126. if (typeof member == 'function' && !member.$isClass && member !== Ext.emptyFn) {
  5127. member.$owner = this;
  5128. member.$name = name;
  5129. member.displayName = (this.$className || '') + '#' + name;
  5130. }
  5131. this.prototype[name] = member;
  5132. return this;
  5133. },
  5134. /**
  5135. * Adds members to class.
  5136. * @static
  5137. * @inheritable
  5138. * @deprecated 4.1 Use {@link #addMembers} instead.
  5139. */
  5140. implement: function() {
  5141. this.addMembers.apply(this, arguments);
  5142. },
  5143. /**
  5144. * Borrow another class' members to the prototype of this class.
  5145. *
  5146. * Ext.define('Bank', {
  5147. * money: '$$$',
  5148. * printMoney: function() {
  5149. * alert('$$$$$$$');
  5150. * }
  5151. * });
  5152. *
  5153. * Ext.define('Thief', {
  5154. * ...
  5155. * });
  5156. *
  5157. * Thief.borrow(Bank, ['money', 'printMoney']);
  5158. *
  5159. * var steve = new Thief();
  5160. *
  5161. * alert(steve.money); // alerts '$$$'
  5162. * steve.printMoney(); // alerts '$$$$$$$'
  5163. *
  5164. * @param {Ext.Base} fromClass The class to borrow members from
  5165. * @param {Array/String} members The names of the members to borrow
  5166. * @return {Ext.Base} this
  5167. * @static
  5168. * @inheritable
  5169. * @private
  5170. */
  5171. borrow: function(fromClass, members) {
  5172. var prototype = this.prototype,
  5173. fromPrototype = fromClass.prototype,
  5174. className = Ext.getClassName(this),
  5175. i, ln, name, fn, toBorrow;
  5176. members = Ext.Array.from(members);
  5177. for (i = 0,ln = members.length; i < ln; i++) {
  5178. name = members[i];
  5179. toBorrow = fromPrototype[name];
  5180. if (typeof toBorrow == 'function') {
  5181. fn = Ext.Function.clone(toBorrow);
  5182. if (className) {
  5183. fn.displayName = className + '#' + name;
  5184. }
  5185. fn.$owner = this;
  5186. fn.$name = name;
  5187. prototype[name] = fn;
  5188. }
  5189. else {
  5190. prototype[name] = toBorrow;
  5191. }
  5192. }
  5193. return this;
  5194. },
  5195. /**
  5196. * Override members of this class. Overridden methods can be invoked via
  5197. * {@link Ext.Base#callParent}.
  5198. *
  5199. * Ext.define('My.Cat', {
  5200. * constructor: function() {
  5201. * alert("I'm a cat!");
  5202. * }
  5203. * });
  5204. *
  5205. * My.Cat.override({
  5206. * constructor: function() {
  5207. * alert("I'm going to be a cat!");
  5208. *
  5209. * this.callParent(arguments);
  5210. *
  5211. * alert("Meeeeoooowwww");
  5212. * }
  5213. * });
  5214. *
  5215. * var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
  5216. * // alerts "I'm a cat!"
  5217. * // alerts "Meeeeoooowwww"
  5218. *
  5219. * As of 4.1, direct use of this method is deprecated. Use {@link Ext#define Ext.define}
  5220. * instead:
  5221. *
  5222. * Ext.define('My.CatOverride', {
  5223. * override: 'My.Cat',
  5224. * constructor: function() {
  5225. * alert("I'm going to be a cat!");
  5226. *
  5227. * this.callParent(arguments);
  5228. *
  5229. * alert("Meeeeoooowwww");
  5230. * }
  5231. * });
  5232. *
  5233. * The above accomplishes the same result but can be managed by the {@link Ext.Loader}
  5234. * which can properly order the override and its target class and the build process
  5235. * can determine whether the override is needed based on the required state of the
  5236. * target class (My.Cat).
  5237. *
  5238. * @param {Object} members The properties to add to this class. This should be
  5239. * specified as an object literal containing one or more properties.
  5240. * @return {Ext.Base} this class
  5241. * @static
  5242. * @inheritable
  5243. * @markdown
  5244. * @deprecated 4.1.0 Use {@link Ext#define Ext.define} instead
  5245. */
  5246. override: function(members) {
  5247. var me = this,
  5248. enumerables = Ext.enumerables,
  5249. target = me.prototype,
  5250. cloneFunction = Ext.Function.clone,
  5251. name, index, member, statics, names, previous;
  5252. if (arguments.length === 2) {
  5253. name = members;
  5254. members = {};
  5255. members[name] = arguments[1];
  5256. enumerables = null;
  5257. }
  5258. do {
  5259. names = []; // clean slate for prototype (1st pass) and static (2nd pass)
  5260. statics = null; // not needed 1st pass, but needs to be cleared for 2nd pass
  5261. for (name in members) { // hasOwnProperty is checked in the next loop...
  5262. if (name == 'statics') {
  5263. statics = members[name];
  5264. } else if (name == 'config') {
  5265. me.addConfig(members[name], true);
  5266. } else {
  5267. names.push(name);
  5268. }
  5269. }
  5270. if (enumerables) {
  5271. names.push.apply(names, enumerables);
  5272. }
  5273. for (index = names.length; index--; ) {
  5274. name = names[index];
  5275. if (members.hasOwnProperty(name)) {
  5276. member = members[name];
  5277. if (typeof member == 'function' && !member.$className && member !== Ext.emptyFn) {
  5278. if (typeof member.$owner != 'undefined') {
  5279. member = cloneFunction(member);
  5280. }
  5281. if (me.$className) {
  5282. member.displayName = me.$className + '#' + name;
  5283. }
  5284. member.$owner = me;
  5285. member.$name = name;
  5286. previous = target[name];
  5287. if (previous) {
  5288. member.$previous = previous;
  5289. }
  5290. }
  5291. target[name] = member;
  5292. }
  5293. }
  5294. target = me; // 2nd pass is for statics
  5295. members = statics; // statics will be null on 2nd pass
  5296. } while (members);
  5297. return this;
  5298. },
  5299. // Documented downwards
  5300. callParent: function(args) {
  5301. var method;
  5302. // This code is intentionally inlined for the least number of debugger stepping
  5303. return (method = this.callParent.caller) && (method.$previous ||
  5304. ((method = method.$owner ? method : method.caller) &&
  5305. method.$owner.superclass.self[method.$name])).apply(this, args || noArgs);
  5306. },
  5307. // Documented downwards
  5308. callSuper: function(args) {
  5309. var method;
  5310. // This code is intentionally inlined for the least number of debugger stepping
  5311. return (method = this.callSuper.caller) &&
  5312. ((method = method.$owner ? method : method.caller) &&
  5313. method.$owner.superclass.self[method.$name]).apply(this, args || noArgs);
  5314. },
  5315. /**
  5316. * Used internally by the mixins pre-processor
  5317. * @private
  5318. * @static
  5319. * @inheritable
  5320. */
  5321. mixin: function(name, mixinClass) {
  5322. var mixin = mixinClass.prototype,
  5323. prototype = this.prototype,
  5324. key;
  5325. if (typeof mixin.onClassMixedIn != 'undefined') {
  5326. mixin.onClassMixedIn.call(mixinClass, this);
  5327. }
  5328. if (!prototype.hasOwnProperty('mixins')) {
  5329. if ('mixins' in prototype) {
  5330. prototype.mixins = Ext.Object.chain(prototype.mixins);
  5331. }
  5332. else {
  5333. prototype.mixins = {};
  5334. }
  5335. }
  5336. for (key in mixin) {
  5337. if (key === 'mixins') {
  5338. Ext.merge(prototype.mixins, mixin[key]);
  5339. }
  5340. else if (typeof prototype[key] == 'undefined' && key != 'mixinId' && key != 'config') {
  5341. prototype[key] = mixin[key];
  5342. }
  5343. }
  5344. if ('config' in mixin) {
  5345. this.addConfig(mixin.config, false);
  5346. }
  5347. prototype.mixins[name] = mixin;
  5348. },
  5349. /**
  5350. * Get the current class' name in string format.
  5351. *
  5352. * Ext.define('My.cool.Class', {
  5353. * constructor: function() {
  5354. * alert(this.self.getName()); // alerts 'My.cool.Class'
  5355. * }
  5356. * });
  5357. *
  5358. * My.cool.Class.getName(); // 'My.cool.Class'
  5359. *
  5360. * @return {String} className
  5361. * @static
  5362. * @inheritable
  5363. */
  5364. getName: function() {
  5365. return Ext.getClassName(this);
  5366. },
  5367. /**
  5368. * Create aliases for existing prototype methods. Example:
  5369. *
  5370. * Ext.define('My.cool.Class', {
  5371. * method1: function() { ... },
  5372. * method2: function() { ... }
  5373. * });
  5374. *
  5375. * var test = new My.cool.Class();
  5376. *
  5377. * My.cool.Class.createAlias({
  5378. * method3: 'method1',
  5379. * method4: 'method2'
  5380. * });
  5381. *
  5382. * test.method3(); // test.method1()
  5383. *
  5384. * My.cool.Class.createAlias('method5', 'method3');
  5385. *
  5386. * test.method5(); // test.method3() -> test.method1()
  5387. *
  5388. * @param {String/Object} alias The new method name, or an object to set multiple aliases. See
  5389. * {@link Ext.Function#flexSetter flexSetter}
  5390. * @param {String/Object} origin The original method name
  5391. * @static
  5392. * @inheritable
  5393. * @method
  5394. */
  5395. createAlias: flexSetter(function(alias, origin) {
  5396. this.override(alias, function() {
  5397. return this[origin].apply(this, arguments);
  5398. });
  5399. }),
  5400. /**
  5401. * @private
  5402. * @static
  5403. * @inheritable
  5404. */
  5405. addXtype: function(xtype) {
  5406. var prototype = this.prototype,
  5407. xtypesMap = prototype.xtypesMap,
  5408. xtypes = prototype.xtypes,
  5409. xtypesChain = prototype.xtypesChain;
  5410. if (!prototype.hasOwnProperty('xtypesMap')) {
  5411. xtypesMap = prototype.xtypesMap = Ext.merge({}, prototype.xtypesMap || {});
  5412. xtypes = prototype.xtypes = prototype.xtypes ? [].concat(prototype.xtypes) : [];
  5413. xtypesChain = prototype.xtypesChain = prototype.xtypesChain ? [].concat(prototype.xtypesChain) : [];
  5414. prototype.xtype = xtype;
  5415. }
  5416. if (!xtypesMap[xtype]) {
  5417. xtypesMap[xtype] = true;
  5418. xtypes.push(xtype);
  5419. xtypesChain.push(xtype);
  5420. Ext.ClassManager.setAlias(this, 'widget.' + xtype);
  5421. }
  5422. return this;
  5423. }
  5424. });
  5425. Base.implement({
  5426. /** @private */
  5427. isInstance: true,
  5428. /** @private */
  5429. $className: 'Ext.Base',
  5430. /** @private */
  5431. configClass: Ext.emptyFn,
  5432. /** @private */
  5433. initConfigList: [],
  5434. /** @private */
  5435. configMap: {},
  5436. /** @private */
  5437. initConfigMap: {},
  5438. /**
  5439. * Get the reference to the class from which this object was instantiated. Note that unlike {@link Ext.Base#self},
  5440. * `this.statics()` is scope-independent and it always returns the class from which it was called, regardless of what
  5441. * `this` points to during run-time
  5442. *
  5443. * Ext.define('My.Cat', {
  5444. * statics: {
  5445. * totalCreated: 0,
  5446. * speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
  5447. * },
  5448. *
  5449. * constructor: function() {
  5450. * var statics = this.statics();
  5451. *
  5452. * alert(statics.speciesName); // always equals to 'Cat' no matter what 'this' refers to
  5453. * // equivalent to: My.Cat.speciesName
  5454. *
  5455. * alert(this.self.speciesName); // dependent on 'this'
  5456. *
  5457. * statics.totalCreated++;
  5458. * },
  5459. *
  5460. * clone: function() {
  5461. * var cloned = new this.self; // dependent on 'this'
  5462. *
  5463. * cloned.groupName = this.statics().speciesName; // equivalent to: My.Cat.speciesName
  5464. *
  5465. * return cloned;
  5466. * }
  5467. * });
  5468. *
  5469. *
  5470. * Ext.define('My.SnowLeopard', {
  5471. * extend: 'My.Cat',
  5472. *
  5473. * statics: {
  5474. * speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
  5475. * },
  5476. *
  5477. * constructor: function() {
  5478. * this.callParent();
  5479. * }
  5480. * });
  5481. *
  5482. * var cat = new My.Cat(); // alerts 'Cat', then alerts 'Cat'
  5483. *
  5484. * var snowLeopard = new My.SnowLeopard(); // alerts 'Cat', then alerts 'Snow Leopard'
  5485. *
  5486. * var clone = snowLeopard.clone();
  5487. * alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard'
  5488. * alert(clone.groupName); // alerts 'Cat'
  5489. *
  5490. * alert(My.Cat.totalCreated); // alerts 3
  5491. *
  5492. * @protected
  5493. * @return {Ext.Class}
  5494. */
  5495. statics: function() {
  5496. var method = this.statics.caller,
  5497. self = this.self;
  5498. if (!method) {
  5499. return self;
  5500. }
  5501. return method.$owner;
  5502. },
  5503. /**
  5504. * Call the "parent" method of the current method. That is the method previously
  5505. * overridden by derivation or by an override (see {@link Ext#define}).
  5506. *
  5507. * Ext.define('My.Base', {
  5508. * constructor: function (x) {
  5509. * this.x = x;
  5510. * },
  5511. *
  5512. * statics: {
  5513. * method: function (x) {
  5514. * return x;
  5515. * }
  5516. * }
  5517. * });
  5518. *
  5519. * Ext.define('My.Derived', {
  5520. * extend: 'My.Base',
  5521. *
  5522. * constructor: function () {
  5523. * this.callParent([21]);
  5524. * }
  5525. * });
  5526. *
  5527. * var obj = new My.Derived();
  5528. *
  5529. * alert(obj.x); // alerts 21
  5530. *
  5531. * This can be used with an override as follows:
  5532. *
  5533. * Ext.define('My.DerivedOverride', {
  5534. * override: 'My.Derived',
  5535. *
  5536. * constructor: function (x) {
  5537. * this.callParent([x*2]); // calls original My.Derived constructor
  5538. * }
  5539. * });
  5540. *
  5541. * var obj = new My.Derived();
  5542. *
  5543. * alert(obj.x); // now alerts 42
  5544. *
  5545. * This also works with static methods.
  5546. *
  5547. * Ext.define('My.Derived2', {
  5548. * extend: 'My.Base',
  5549. *
  5550. * statics: {
  5551. * method: function (x) {
  5552. * return this.callParent([x*2]); // calls My.Base.method
  5553. * }
  5554. * }
  5555. * });
  5556. *
  5557. * alert(My.Base.method(10); // alerts 10
  5558. * alert(My.Derived2.method(10); // alerts 20
  5559. *
  5560. * Lastly, it also works with overridden static methods.
  5561. *
  5562. * Ext.define('My.Derived2Override', {
  5563. * override: 'My.Derived2',
  5564. *
  5565. * statics: {
  5566. * method: function (x) {
  5567. * return this.callParent([x*2]); // calls My.Derived2.method
  5568. * }
  5569. * }
  5570. * });
  5571. *
  5572. * alert(My.Derived2.method(10); // now alerts 40
  5573. *
  5574. * To override a method and replace it and also call the superclass method, use
  5575. * {@link #callSuper}. This is often done to patch a method to fix a bug.
  5576. *
  5577. * @protected
  5578. * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
  5579. * from the current method, for example: `this.callParent(arguments)`
  5580. * @return {Object} Returns the result of calling the parent method
  5581. */
  5582. callParent: function(args) {
  5583. // NOTE: this code is deliberately as few expressions (and no function calls)
  5584. // as possible so that a debugger can skip over this noise with the minimum number
  5585. // of steps. Basically, just hit Step Into until you are where you really wanted
  5586. // to be.
  5587. var method,
  5588. superMethod = (method = this.callParent.caller) && (method.$previous ||
  5589. ((method = method.$owner ? method : method.caller) &&
  5590. method.$owner.superclass[method.$name]));
  5591. if (!superMethod) {
  5592. method = this.callParent.caller;
  5593. var parentClass, methodName;
  5594. if (!method.$owner) {
  5595. if (!method.caller) {
  5596. throw new Error("Attempting to call a protected method from the public scope, which is not allowed");
  5597. }
  5598. method = method.caller;
  5599. }
  5600. parentClass = method.$owner.superclass;
  5601. methodName = method.$name;
  5602. if (!(methodName in parentClass)) {
  5603. throw new Error("this.callParent() was called but there's no such method (" + methodName +
  5604. ") found in the parent class (" + (Ext.getClassName(parentClass) || 'Object') + ")");
  5605. }
  5606. }
  5607. return superMethod.apply(this, args || noArgs);
  5608. },
  5609. /**
  5610. * This method is used by an override to call the superclass method but bypass any
  5611. * overridden method. This is often done to "patch" a method that contains a bug
  5612. * but for whatever reason cannot be fixed directly.
  5613. *
  5614. * Consider:
  5615. *
  5616. * Ext.define('Ext.some.Class', {
  5617. * method: function () {
  5618. * console.log('Good');
  5619. * }
  5620. * });
  5621. *
  5622. * Ext.define('Ext.some.DerivedClass', {
  5623. * method: function () {
  5624. * console.log('Bad');
  5625. *
  5626. * // ... logic but with a bug ...
  5627. *
  5628. * this.callParent();
  5629. * }
  5630. * });
  5631. *
  5632. * To patch the bug in `DerivedClass.method`, the typical solution is to create an
  5633. * override:
  5634. *
  5635. * Ext.define('App.paches.DerivedClass', {
  5636. * override: 'Ext.some.DerivedClass',
  5637. *
  5638. * method: function () {
  5639. * console.log('Fixed');
  5640. *
  5641. * // ... logic but with bug fixed ...
  5642. *
  5643. * this.callSuper();
  5644. * }
  5645. * });
  5646. *
  5647. * The patch method cannot use `callParent` to call the superclass `method` since
  5648. * that would call the overridden method containing the bug. In other words, the
  5649. * above patch would only produce "Fixed" then "Good" in the console log, whereas,
  5650. * using `callParent` would produce "Fixed" then "Bad" then "Good".
  5651. *
  5652. * @protected
  5653. * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
  5654. * from the current method, for example: `this.callSuper(arguments)`
  5655. * @return {Object} Returns the result of calling the superclass method
  5656. */
  5657. callSuper: function(args) {
  5658. // NOTE: this code is deliberately as few expressions (and no function calls)
  5659. // as possible so that a debugger can skip over this noise with the minimum number
  5660. // of steps. Basically, just hit Step Into until you are where you really wanted
  5661. // to be.
  5662. var method,
  5663. superMethod = (method = this.callSuper.caller) &&
  5664. ((method = method.$owner ? method : method.caller) &&
  5665. method.$owner.superclass[method.$name]);
  5666. if (!superMethod) {
  5667. method = this.callSuper.caller;
  5668. var parentClass, methodName;
  5669. if (!method.$owner) {
  5670. if (!method.caller) {
  5671. throw new Error("Attempting to call a protected method from the public scope, which is not allowed");
  5672. }
  5673. method = method.caller;
  5674. }
  5675. parentClass = method.$owner.superclass;
  5676. methodName = method.$name;
  5677. if (!(methodName in parentClass)) {
  5678. throw new Error("this.callSuper() was called but there's no such method (" + methodName +
  5679. ") found in the parent class (" + (Ext.getClassName(parentClass) || 'Object') + ")");
  5680. }
  5681. }
  5682. return superMethod.apply(this, args || noArgs);
  5683. },
  5684. /**
  5685. * @property {Ext.Class} self
  5686. *
  5687. * Get the reference to the current class from which this object was instantiated. Unlike {@link Ext.Base#statics},
  5688. * `this.self` is scope-dependent and it's meant to be used for dynamic inheritance. See {@link Ext.Base#statics}
  5689. * for a detailed comparison
  5690. *
  5691. * Ext.define('My.Cat', {
  5692. * statics: {
  5693. * speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
  5694. * },
  5695. *
  5696. * constructor: function() {
  5697. * alert(this.self.speciesName); // dependent on 'this'
  5698. * },
  5699. *
  5700. * clone: function() {
  5701. * return new this.self();
  5702. * }
  5703. * });
  5704. *
  5705. *
  5706. * Ext.define('My.SnowLeopard', {
  5707. * extend: 'My.Cat',
  5708. * statics: {
  5709. * speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
  5710. * }
  5711. * });
  5712. *
  5713. * var cat = new My.Cat(); // alerts 'Cat'
  5714. * var snowLeopard = new My.SnowLeopard(); // alerts 'Snow Leopard'
  5715. *
  5716. * var clone = snowLeopard.clone();
  5717. * alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard'
  5718. *
  5719. * @protected
  5720. */
  5721. self: Base,
  5722. // Default constructor, simply returns `this`
  5723. constructor: function() {
  5724. return this;
  5725. },
  5726. /**
  5727. * Initialize configuration for this class. a typical example:
  5728. *
  5729. * Ext.define('My.awesome.Class', {
  5730. * // The default config
  5731. * config: {
  5732. * name: 'Awesome',
  5733. * isAwesome: true
  5734. * },
  5735. *
  5736. * constructor: function(config) {
  5737. * this.initConfig(config);
  5738. * }
  5739. * });
  5740. *
  5741. * var awesome = new My.awesome.Class({
  5742. * name: 'Super Awesome'
  5743. * });
  5744. *
  5745. * alert(awesome.getName()); // 'Super Awesome'
  5746. *
  5747. * @protected
  5748. * @param {Object} config
  5749. * @return {Ext.Base} this
  5750. */
  5751. initConfig: function(config) {
  5752. var instanceConfig = config,
  5753. configNameCache = Ext.Class.configNameCache,
  5754. defaultConfig = new this.configClass(),
  5755. defaultConfigList = this.initConfigList,
  5756. hasConfig = this.configMap,
  5757. nameMap, i, ln, name, initializedName;
  5758. this.initConfig = Ext.emptyFn;
  5759. this.initialConfig = instanceConfig || {};
  5760. this.config = config = (instanceConfig) ? Ext.merge(defaultConfig, config) : defaultConfig;
  5761. if (instanceConfig) {
  5762. defaultConfigList = defaultConfigList.slice();
  5763. for (name in instanceConfig) {
  5764. if (hasConfig[name]) {
  5765. if (instanceConfig[name] !== null) {
  5766. defaultConfigList.push(name);
  5767. this[configNameCache[name].initialized] = false;
  5768. }
  5769. }
  5770. }
  5771. }
  5772. for (i = 0,ln = defaultConfigList.length; i < ln; i++) {
  5773. name = defaultConfigList[i];
  5774. nameMap = configNameCache[name];
  5775. initializedName = nameMap.initialized;
  5776. if (!this[initializedName]) {
  5777. this[initializedName] = true;
  5778. this[nameMap.set].call(this, config[name]);
  5779. }
  5780. }
  5781. return this;
  5782. },
  5783. /**
  5784. * @private
  5785. * @param config
  5786. */
  5787. hasConfig: function(name) {
  5788. return Boolean(this.configMap[name]);
  5789. },
  5790. /**
  5791. * @private
  5792. */
  5793. setConfig: function(config, applyIfNotSet) {
  5794. if (!config) {
  5795. return this;
  5796. }
  5797. var configNameCache = Ext.Class.configNameCache,
  5798. currentConfig = this.config,
  5799. hasConfig = this.configMap,
  5800. initialConfig = this.initialConfig,
  5801. name, value;
  5802. applyIfNotSet = Boolean(applyIfNotSet);
  5803. for (name in config) {
  5804. if (applyIfNotSet && initialConfig.hasOwnProperty(name)) {
  5805. continue;
  5806. }
  5807. value = config[name];
  5808. currentConfig[name] = value;
  5809. if (hasConfig[name]) {
  5810. this[configNameCache[name].set](value);
  5811. }
  5812. }
  5813. return this;
  5814. },
  5815. /**
  5816. * @private
  5817. * @param name
  5818. */
  5819. getConfig: function(name) {
  5820. var configNameCache = Ext.Class.configNameCache;
  5821. return this[configNameCache[name].get]();
  5822. },
  5823. /**
  5824. * Returns the initial configuration passed to constructor when instantiating
  5825. * this class.
  5826. * @param {String} [name] Name of the config option to return.
  5827. * @return {Object/Mixed} The full config object or a single config value
  5828. * when `name` parameter specified.
  5829. */
  5830. getInitialConfig: function(name) {
  5831. var config = this.config;
  5832. if (!name) {
  5833. return config;
  5834. }
  5835. else {
  5836. return config[name];
  5837. }
  5838. },
  5839. /**
  5840. * @private
  5841. * @param names
  5842. * @param callback
  5843. * @param scope
  5844. */
  5845. onConfigUpdate: function(names, callback, scope) {
  5846. var self = this.self,
  5847. className = self.$className,
  5848. i, ln, name,
  5849. updaterName, updater, newUpdater;
  5850. names = Ext.Array.from(names);
  5851. scope = scope || this;
  5852. for (i = 0,ln = names.length; i < ln; i++) {
  5853. name = names[i];
  5854. updaterName = 'update' + Ext.String.capitalize(name);
  5855. updater = this[updaterName] || Ext.emptyFn;
  5856. newUpdater = function() {
  5857. updater.apply(this, arguments);
  5858. scope[callback].apply(scope, arguments);
  5859. };
  5860. newUpdater.$name = updaterName;
  5861. newUpdater.$owner = self;
  5862. newUpdater.displayName = className + '#' + updaterName;
  5863. this[updaterName] = newUpdater;
  5864. }
  5865. },
  5866. /**
  5867. * @private
  5868. */
  5869. destroy: function() {
  5870. this.destroy = Ext.emptyFn;
  5871. }
  5872. });
  5873. /**
  5874. * Call the original method that was previously overridden with {@link Ext.Base#override}
  5875. *
  5876. * Ext.define('My.Cat', {
  5877. * constructor: function() {
  5878. * alert("I'm a cat!");
  5879. * }
  5880. * });
  5881. *
  5882. * My.Cat.override({
  5883. * constructor: function() {
  5884. * alert("I'm going to be a cat!");
  5885. *
  5886. * this.callOverridden();
  5887. *
  5888. * alert("Meeeeoooowwww");
  5889. * }
  5890. * });
  5891. *
  5892. * var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
  5893. * // alerts "I'm a cat!"
  5894. * // alerts "Meeeeoooowwww"
  5895. *
  5896. * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
  5897. * from the current method, for example: `this.callOverridden(arguments)`
  5898. * @return {Object} Returns the result of calling the overridden method
  5899. * @protected
  5900. * @deprecated as of 4.1. Use {@link #callParent} instead.
  5901. */
  5902. Base.prototype.callOverridden = Base.prototype.callParent;
  5903. Ext.Base = Base;
  5904. }(Ext.Function.flexSetter));
  5905. //@tag foundation,core
  5906. //@require Base.js
  5907. /**
  5908. * @author Jacky Nguyen <jacky@sencha.com>
  5909. * @docauthor Jacky Nguyen <jacky@sencha.com>
  5910. * @class Ext.Class
  5911. *
  5912. * Handles class creation throughout the framework. This is a low level factory that is used by Ext.ClassManager and generally
  5913. * should not be used directly. If you choose to use Ext.Class you will lose out on the namespace, aliasing and depency loading
  5914. * features made available by Ext.ClassManager. The only time you would use Ext.Class directly is to create an anonymous class.
  5915. *
  5916. * If you wish to create a class you should use {@link Ext#define Ext.define} which aliases
  5917. * {@link Ext.ClassManager#create Ext.ClassManager.create} to enable namespacing and dynamic dependency resolution.
  5918. *
  5919. * Ext.Class is the factory and **not** the superclass of everything. For the base class that **all** Ext classes inherit
  5920. * from, see {@link Ext.Base}.
  5921. */
  5922. (function() {
  5923. var ExtClass,
  5924. Base = Ext.Base,
  5925. baseStaticMembers = [],
  5926. baseStaticMember, baseStaticMemberLength;
  5927. for (baseStaticMember in Base) {
  5928. if (Base.hasOwnProperty(baseStaticMember)) {
  5929. baseStaticMembers.push(baseStaticMember);
  5930. }
  5931. }
  5932. baseStaticMemberLength = baseStaticMembers.length;
  5933. // Creates a constructor that has nothing extra in its scope chain.
  5934. function makeCtor (className) {
  5935. function constructor () {
  5936. // Opera has some problems returning from a constructor when Dragonfly isn't running. The || null seems to
  5937. // be sufficient to stop it misbehaving. Known to be required against 10.53, 11.51 and 11.61.
  5938. return this.constructor.apply(this, arguments) || null;
  5939. }
  5940. if (className) {
  5941. constructor.displayName = className;
  5942. }
  5943. return constructor;
  5944. }
  5945. /**
  5946. * @method constructor
  5947. * Create a new anonymous class.
  5948. *
  5949. * @param {Object} data An object represent the properties of this class
  5950. * @param {Function} onCreated Optional, the callback function to be executed when this class is fully created.
  5951. * Note that the creation process can be asynchronous depending on the pre-processors used.
  5952. *
  5953. * @return {Ext.Base} The newly created class
  5954. */
  5955. Ext.Class = ExtClass = function(Class, data, onCreated) {
  5956. if (typeof Class != 'function') {
  5957. onCreated = data;
  5958. data = Class;
  5959. Class = null;
  5960. }
  5961. if (!data) {
  5962. data = {};
  5963. }
  5964. Class = ExtClass.create(Class, data);
  5965. ExtClass.process(Class, data, onCreated);
  5966. return Class;
  5967. };
  5968. Ext.apply(ExtClass, {
  5969. /**
  5970. * @private
  5971. * @param Class
  5972. * @param data
  5973. * @param hooks
  5974. */
  5975. onBeforeCreated: function(Class, data, hooks) {
  5976. Class.addMembers(data);
  5977. hooks.onCreated.call(Class, Class);
  5978. },
  5979. /**
  5980. * @private
  5981. * @param Class
  5982. * @param classData
  5983. * @param onClassCreated
  5984. */
  5985. create: function(Class, data) {
  5986. var name, i;
  5987. if (!Class) {
  5988. Class = makeCtor(
  5989. data.$className
  5990. );
  5991. }
  5992. for (i = 0; i < baseStaticMemberLength; i++) {
  5993. name = baseStaticMembers[i];
  5994. Class[name] = Base[name];
  5995. }
  5996. return Class;
  5997. },
  5998. /**
  5999. * @private
  6000. * @param Class
  6001. * @param data
  6002. * @param onCreated
  6003. */
  6004. process: function(Class, data, onCreated) {
  6005. var preprocessorStack = data.preprocessors || ExtClass.defaultPreprocessors,
  6006. registeredPreprocessors = this.preprocessors,
  6007. hooks = {
  6008. onBeforeCreated: this.onBeforeCreated
  6009. },
  6010. preprocessors = [],
  6011. preprocessor, preprocessorsProperties,
  6012. i, ln, j, subLn, preprocessorProperty, process;
  6013. delete data.preprocessors;
  6014. for (i = 0,ln = preprocessorStack.length; i < ln; i++) {
  6015. preprocessor = preprocessorStack[i];
  6016. if (typeof preprocessor == 'string') {
  6017. preprocessor = registeredPreprocessors[preprocessor];
  6018. preprocessorsProperties = preprocessor.properties;
  6019. if (preprocessorsProperties === true) {
  6020. preprocessors.push(preprocessor.fn);
  6021. }
  6022. else if (preprocessorsProperties) {
  6023. for (j = 0,subLn = preprocessorsProperties.length; j < subLn; j++) {
  6024. preprocessorProperty = preprocessorsProperties[j];
  6025. if (data.hasOwnProperty(preprocessorProperty)) {
  6026. preprocessors.push(preprocessor.fn);
  6027. break;
  6028. }
  6029. }
  6030. }
  6031. }
  6032. else {
  6033. preprocessors.push(preprocessor);
  6034. }
  6035. }
  6036. hooks.onCreated = onCreated ? onCreated : Ext.emptyFn;
  6037. hooks.preprocessors = preprocessors;
  6038. this.doProcess(Class, data, hooks);
  6039. },
  6040. doProcess: function(Class, data, hooks){
  6041. var me = this,
  6042. preprocessor = hooks.preprocessors.shift();
  6043. if (!preprocessor) {
  6044. hooks.onBeforeCreated.apply(me, arguments);
  6045. return;
  6046. }
  6047. if (preprocessor.call(me, Class, data, hooks, me.doProcess) !== false) {
  6048. me.doProcess(Class, data, hooks);
  6049. }
  6050. },
  6051. /** @private */
  6052. preprocessors: {},
  6053. /**
  6054. * Register a new pre-processor to be used during the class creation process
  6055. *
  6056. * @param {String} name The pre-processor's name
  6057. * @param {Function} fn The callback function to be executed. Typical format:
  6058. *
  6059. * function(cls, data, fn) {
  6060. * // Your code here
  6061. *
  6062. * // Execute this when the processing is finished.
  6063. * // Asynchronous processing is perfectly ok
  6064. * if (fn) {
  6065. * fn.call(this, cls, data);
  6066. * }
  6067. * });
  6068. *
  6069. * @param {Function} fn.cls The created class
  6070. * @param {Object} fn.data The set of properties passed in {@link Ext.Class} constructor
  6071. * @param {Function} fn.fn The callback function that **must** to be executed when this
  6072. * pre-processor finishes, regardless of whether the processing is synchronous or aynchronous.
  6073. * @return {Ext.Class} this
  6074. * @private
  6075. * @static
  6076. */
  6077. registerPreprocessor: function(name, fn, properties, position, relativeTo) {
  6078. if (!position) {
  6079. position = 'last';
  6080. }
  6081. if (!properties) {
  6082. properties = [name];
  6083. }
  6084. this.preprocessors[name] = {
  6085. name: name,
  6086. properties: properties || false,
  6087. fn: fn
  6088. };
  6089. this.setDefaultPreprocessorPosition(name, position, relativeTo);
  6090. return this;
  6091. },
  6092. /**
  6093. * Retrieve a pre-processor callback function by its name, which has been registered before
  6094. *
  6095. * @param {String} name
  6096. * @return {Function} preprocessor
  6097. * @private
  6098. * @static
  6099. */
  6100. getPreprocessor: function(name) {
  6101. return this.preprocessors[name];
  6102. },
  6103. /**
  6104. * @private
  6105. */
  6106. getPreprocessors: function() {
  6107. return this.preprocessors;
  6108. },
  6109. /**
  6110. * @private
  6111. */
  6112. defaultPreprocessors: [],
  6113. /**
  6114. * Retrieve the array stack of default pre-processors
  6115. * @return {Function[]} defaultPreprocessors
  6116. * @private
  6117. * @static
  6118. */
  6119. getDefaultPreprocessors: function() {
  6120. return this.defaultPreprocessors;
  6121. },
  6122. /**
  6123. * Set the default array stack of default pre-processors
  6124. *
  6125. * @private
  6126. * @param {Array} preprocessors
  6127. * @return {Ext.Class} this
  6128. * @static
  6129. */
  6130. setDefaultPreprocessors: function(preprocessors) {
  6131. this.defaultPreprocessors = Ext.Array.from(preprocessors);
  6132. return this;
  6133. },
  6134. /**
  6135. * Insert this pre-processor at a specific position in the stack, optionally relative to
  6136. * any existing pre-processor. For example:
  6137. *
  6138. * Ext.Class.registerPreprocessor('debug', function(cls, data, fn) {
  6139. * // Your code here
  6140. *
  6141. * if (fn) {
  6142. * fn.call(this, cls, data);
  6143. * }
  6144. * }).setDefaultPreprocessorPosition('debug', 'last');
  6145. *
  6146. * @private
  6147. * @param {String} name The pre-processor name. Note that it needs to be registered with
  6148. * {@link Ext.Class#registerPreprocessor registerPreprocessor} before this
  6149. * @param {String} offset The insertion position. Four possible values are:
  6150. * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument)
  6151. * @param {String} relativeName
  6152. * @return {Ext.Class} this
  6153. * @static
  6154. */
  6155. setDefaultPreprocessorPosition: function(name, offset, relativeName) {
  6156. var defaultPreprocessors = this.defaultPreprocessors,
  6157. index;
  6158. if (typeof offset == 'string') {
  6159. if (offset === 'first') {
  6160. defaultPreprocessors.unshift(name);
  6161. return this;
  6162. }
  6163. else if (offset === 'last') {
  6164. defaultPreprocessors.push(name);
  6165. return this;
  6166. }
  6167. offset = (offset === 'after') ? 1 : -1;
  6168. }
  6169. index = Ext.Array.indexOf(defaultPreprocessors, relativeName);
  6170. if (index !== -1) {
  6171. Ext.Array.splice(defaultPreprocessors, Math.max(0, index + offset), 0, name);
  6172. }
  6173. return this;
  6174. },
  6175. configNameCache: {},
  6176. getConfigNameMap: function(name) {
  6177. var cache = this.configNameCache,
  6178. map = cache[name],
  6179. capitalizedName;
  6180. if (!map) {
  6181. capitalizedName = name.charAt(0).toUpperCase() + name.substr(1);
  6182. map = cache[name] = {
  6183. internal: name,
  6184. initialized: '_is' + capitalizedName + 'Initialized',
  6185. apply: 'apply' + capitalizedName,
  6186. update: 'update' + capitalizedName,
  6187. 'set': 'set' + capitalizedName,
  6188. 'get': 'get' + capitalizedName,
  6189. doSet : 'doSet' + capitalizedName,
  6190. changeEvent: name.toLowerCase() + 'change'
  6191. };
  6192. }
  6193. return map;
  6194. }
  6195. });
  6196. /**
  6197. * @cfg {String} extend
  6198. * The parent class that this class extends. For example:
  6199. *
  6200. * Ext.define('Person', {
  6201. * say: function(text) { alert(text); }
  6202. * });
  6203. *
  6204. * Ext.define('Developer', {
  6205. * extend: 'Person',
  6206. * say: function(text) { this.callParent(["print "+text]); }
  6207. * });
  6208. */
  6209. ExtClass.registerPreprocessor('extend', function(Class, data) {
  6210. var Base = Ext.Base,
  6211. basePrototype = Base.prototype,
  6212. extend = data.extend,
  6213. Parent, parentPrototype, i;
  6214. delete data.extend;
  6215. if (extend && extend !== Object) {
  6216. Parent = extend;
  6217. }
  6218. else {
  6219. Parent = Base;
  6220. }
  6221. parentPrototype = Parent.prototype;
  6222. if (!Parent.$isClass) {
  6223. for (i in basePrototype) {
  6224. if (!parentPrototype[i]) {
  6225. parentPrototype[i] = basePrototype[i];
  6226. }
  6227. }
  6228. }
  6229. Class.extend(Parent);
  6230. Class.triggerExtended.apply(Class, arguments);
  6231. if (data.onClassExtended) {
  6232. Class.onExtended(data.onClassExtended, Class);
  6233. delete data.onClassExtended;
  6234. }
  6235. }, true);
  6236. /**
  6237. * @cfg {Object} statics
  6238. * List of static methods for this class. For example:
  6239. *
  6240. * Ext.define('Computer', {
  6241. * statics: {
  6242. * factory: function(brand) {
  6243. * // 'this' in static methods refer to the class itself
  6244. * return new this(brand);
  6245. * }
  6246. * },
  6247. *
  6248. * constructor: function() { ... }
  6249. * });
  6250. *
  6251. * var dellComputer = Computer.factory('Dell');
  6252. */
  6253. ExtClass.registerPreprocessor('statics', function(Class, data) {
  6254. Class.addStatics(data.statics);
  6255. delete data.statics;
  6256. });
  6257. /**
  6258. * @cfg {Object} inheritableStatics
  6259. * List of inheritable static methods for this class.
  6260. * Otherwise just like {@link #statics} but subclasses inherit these methods.
  6261. */
  6262. ExtClass.registerPreprocessor('inheritableStatics', function(Class, data) {
  6263. Class.addInheritableStatics(data.inheritableStatics);
  6264. delete data.inheritableStatics;
  6265. });
  6266. /**
  6267. * @cfg {Object} config
  6268. * List of configuration options with their default values, for which automatically
  6269. * accessor methods are generated. For example:
  6270. *
  6271. * Ext.define('SmartPhone', {
  6272. * config: {
  6273. * hasTouchScreen: false,
  6274. * operatingSystem: 'Other',
  6275. * price: 500
  6276. * },
  6277. * constructor: function(cfg) {
  6278. * this.initConfig(cfg);
  6279. * }
  6280. * });
  6281. *
  6282. * var iPhone = new SmartPhone({
  6283. * hasTouchScreen: true,
  6284. * operatingSystem: 'iOS'
  6285. * });
  6286. *
  6287. * iPhone.getPrice(); // 500;
  6288. * iPhone.getOperatingSystem(); // 'iOS'
  6289. * iPhone.getHasTouchScreen(); // true;
  6290. */
  6291. ExtClass.registerPreprocessor('config', function(Class, data) {
  6292. var config = data.config,
  6293. prototype = Class.prototype;
  6294. delete data.config;
  6295. Ext.Object.each(config, function(name, value) {
  6296. var nameMap = ExtClass.getConfigNameMap(name),
  6297. internalName = nameMap.internal,
  6298. initializedName = nameMap.initialized,
  6299. applyName = nameMap.apply,
  6300. updateName = nameMap.update,
  6301. setName = nameMap.set,
  6302. getName = nameMap.get,
  6303. hasOwnSetter = (setName in prototype) || data.hasOwnProperty(setName),
  6304. hasOwnApplier = (applyName in prototype) || data.hasOwnProperty(applyName),
  6305. hasOwnUpdater = (updateName in prototype) || data.hasOwnProperty(updateName),
  6306. optimizedGetter, customGetter;
  6307. if (value === null || (!hasOwnSetter && !hasOwnApplier && !hasOwnUpdater)) {
  6308. prototype[internalName] = value;
  6309. prototype[initializedName] = true;
  6310. }
  6311. else {
  6312. prototype[initializedName] = false;
  6313. }
  6314. if (!hasOwnSetter) {
  6315. data[setName] = function(value) {
  6316. var oldValue = this[internalName],
  6317. applier = this[applyName],
  6318. updater = this[updateName];
  6319. if (!this[initializedName]) {
  6320. this[initializedName] = true;
  6321. }
  6322. if (applier) {
  6323. value = applier.call(this, value, oldValue);
  6324. }
  6325. if (typeof value != 'undefined') {
  6326. this[internalName] = value;
  6327. if (updater && value !== oldValue) {
  6328. updater.call(this, value, oldValue);
  6329. }
  6330. }
  6331. return this;
  6332. };
  6333. }
  6334. if (!(getName in prototype) || data.hasOwnProperty(getName)) {
  6335. customGetter = data[getName] || false;
  6336. if (customGetter) {
  6337. optimizedGetter = function() {
  6338. return customGetter.apply(this, arguments);
  6339. };
  6340. }
  6341. else {
  6342. optimizedGetter = function() {
  6343. return this[internalName];
  6344. };
  6345. }
  6346. data[getName] = function() {
  6347. var currentGetter;
  6348. if (!this[initializedName]) {
  6349. this[initializedName] = true;
  6350. this[setName](this.config[name]);
  6351. }
  6352. currentGetter = this[getName];
  6353. if ('$previous' in currentGetter) {
  6354. currentGetter.$previous = optimizedGetter;
  6355. }
  6356. else {
  6357. this[getName] = optimizedGetter;
  6358. }
  6359. return optimizedGetter.apply(this, arguments);
  6360. };
  6361. }
  6362. });
  6363. Class.addConfig(config, true);
  6364. });
  6365. /**
  6366. * @cfg {String[]/Object} mixins
  6367. * List of classes to mix into this class. For example:
  6368. *
  6369. * Ext.define('CanSing', {
  6370. * sing: function() {
  6371. * alert("I'm on the highway to hell...")
  6372. * }
  6373. * });
  6374. *
  6375. * Ext.define('Musician', {
  6376. * mixins: ['CanSing']
  6377. * })
  6378. *
  6379. * In this case the Musician class will get a `sing` method from CanSing mixin.
  6380. *
  6381. * But what if the Musician already has a `sing` method? Or you want to mix
  6382. * in two classes, both of which define `sing`? In such a cases it's good
  6383. * to define mixins as an object, where you assign a name to each mixin:
  6384. *
  6385. * Ext.define('Musician', {
  6386. * mixins: {
  6387. * canSing: 'CanSing'
  6388. * },
  6389. *
  6390. * sing: function() {
  6391. * // delegate singing operation to mixin
  6392. * this.mixins.canSing.sing.call(this);
  6393. * }
  6394. * })
  6395. *
  6396. * In this case the `sing` method of Musician will overwrite the
  6397. * mixed in `sing` method. But you can access the original mixed in method
  6398. * through special `mixins` property.
  6399. */
  6400. ExtClass.registerPreprocessor('mixins', function(Class, data, hooks) {
  6401. var mixins = data.mixins,
  6402. name, mixin, i, ln;
  6403. delete data.mixins;
  6404. Ext.Function.interceptBefore(hooks, 'onCreated', function() {
  6405. if (mixins instanceof Array) {
  6406. for (i = 0,ln = mixins.length; i < ln; i++) {
  6407. mixin = mixins[i];
  6408. name = mixin.prototype.mixinId || mixin.$className;
  6409. Class.mixin(name, mixin);
  6410. }
  6411. }
  6412. else {
  6413. for (var mixinName in mixins) {
  6414. if (mixins.hasOwnProperty(mixinName)) {
  6415. Class.mixin(mixinName, mixins[mixinName]);
  6416. }
  6417. }
  6418. }
  6419. });
  6420. });
  6421. // Backwards compatible
  6422. Ext.extend = function(Class, Parent, members) {
  6423. if (arguments.length === 2 && Ext.isObject(Parent)) {
  6424. members = Parent;
  6425. Parent = Class;
  6426. Class = null;
  6427. }
  6428. var cls;
  6429. if (!Parent) {
  6430. throw new Error("[Ext.extend] Attempting to extend from a class which has not been loaded on the page.");
  6431. }
  6432. members.extend = Parent;
  6433. members.preprocessors = [
  6434. 'extend'
  6435. ,'statics'
  6436. ,'inheritableStatics'
  6437. ,'mixins'
  6438. ,'config'
  6439. ];
  6440. if (Class) {
  6441. cls = new ExtClass(Class, members);
  6442. // The 'constructor' is given as 'Class' but also needs to be on prototype
  6443. cls.prototype.constructor = Class;
  6444. } else {
  6445. cls = new ExtClass(members);
  6446. }
  6447. cls.prototype.override = function(o) {
  6448. for (var m in o) {
  6449. if (o.hasOwnProperty(m)) {
  6450. this[m] = o[m];
  6451. }
  6452. }
  6453. };
  6454. return cls;
  6455. };
  6456. }());
  6457. //@tag foundation,core
  6458. //@require Class.js
  6459. /**
  6460. * @author Jacky Nguyen <jacky@sencha.com>
  6461. * @docauthor Jacky Nguyen <jacky@sencha.com>
  6462. * @class Ext.ClassManager
  6463. *
  6464. * Ext.ClassManager manages all classes and handles mapping from string class name to
  6465. * actual class objects throughout the whole framework. It is not generally accessed directly, rather through
  6466. * these convenient shorthands:
  6467. *
  6468. * - {@link Ext#define Ext.define}
  6469. * - {@link Ext#create Ext.create}
  6470. * - {@link Ext#widget Ext.widget}
  6471. * - {@link Ext#getClass Ext.getClass}
  6472. * - {@link Ext#getClassName Ext.getClassName}
  6473. *
  6474. * # Basic syntax:
  6475. *
  6476. * Ext.define(className, properties);
  6477. *
  6478. * in which `properties` is an object represent a collection of properties that apply to the class. See
  6479. * {@link Ext.ClassManager#create} for more detailed instructions.
  6480. *
  6481. * Ext.define('Person', {
  6482. * name: 'Unknown',
  6483. *
  6484. * constructor: function(name) {
  6485. * if (name) {
  6486. * this.name = name;
  6487. * }
  6488. * },
  6489. *
  6490. * eat: function(foodType) {
  6491. * alert("I'm eating: " + foodType);
  6492. *
  6493. * return this;
  6494. * }
  6495. * });
  6496. *
  6497. * var aaron = new Person("Aaron");
  6498. * aaron.eat("Sandwich"); // alert("I'm eating: Sandwich");
  6499. *
  6500. * Ext.Class has a powerful set of extensible {@link Ext.Class#registerPreprocessor pre-processors} which takes care of
  6501. * everything related to class creation, including but not limited to inheritance, mixins, configuration, statics, etc.
  6502. *
  6503. * # Inheritance:
  6504. *
  6505. * Ext.define('Developer', {
  6506. * extend: 'Person',
  6507. *
  6508. * constructor: function(name, isGeek) {
  6509. * this.isGeek = isGeek;
  6510. *
  6511. * // Apply a method from the parent class' prototype
  6512. * this.callParent([name]);
  6513. * },
  6514. *
  6515. * code: function(language) {
  6516. * alert("I'm coding in: " + language);
  6517. *
  6518. * this.eat("Bugs");
  6519. *
  6520. * return this;
  6521. * }
  6522. * });
  6523. *
  6524. * var jacky = new Developer("Jacky", true);
  6525. * jacky.code("JavaScript"); // alert("I'm coding in: JavaScript");
  6526. * // alert("I'm eating: Bugs");
  6527. *
  6528. * See {@link Ext.Base#callParent} for more details on calling superclass' methods
  6529. *
  6530. * # Mixins:
  6531. *
  6532. * Ext.define('CanPlayGuitar', {
  6533. * playGuitar: function() {
  6534. * alert("F#...G...D...A");
  6535. * }
  6536. * });
  6537. *
  6538. * Ext.define('CanComposeSongs', {
  6539. * composeSongs: function() { ... }
  6540. * });
  6541. *
  6542. * Ext.define('CanSing', {
  6543. * sing: function() {
  6544. * alert("I'm on the highway to hell...")
  6545. * }
  6546. * });
  6547. *
  6548. * Ext.define('Musician', {
  6549. * extend: 'Person',
  6550. *
  6551. * mixins: {
  6552. * canPlayGuitar: 'CanPlayGuitar',
  6553. * canComposeSongs: 'CanComposeSongs',
  6554. * canSing: 'CanSing'
  6555. * }
  6556. * })
  6557. *
  6558. * Ext.define('CoolPerson', {
  6559. * extend: 'Person',
  6560. *
  6561. * mixins: {
  6562. * canPlayGuitar: 'CanPlayGuitar',
  6563. * canSing: 'CanSing'
  6564. * },
  6565. *
  6566. * sing: function() {
  6567. * alert("Ahem....");
  6568. *
  6569. * this.mixins.canSing.sing.call(this);
  6570. *
  6571. * alert("[Playing guitar at the same time...]");
  6572. *
  6573. * this.playGuitar();
  6574. * }
  6575. * });
  6576. *
  6577. * var me = new CoolPerson("Jacky");
  6578. *
  6579. * me.sing(); // alert("Ahem...");
  6580. * // alert("I'm on the highway to hell...");
  6581. * // alert("[Playing guitar at the same time...]");
  6582. * // alert("F#...G...D...A");
  6583. *
  6584. * # Config:
  6585. *
  6586. * Ext.define('SmartPhone', {
  6587. * config: {
  6588. * hasTouchScreen: false,
  6589. * operatingSystem: 'Other',
  6590. * price: 500
  6591. * },
  6592. *
  6593. * isExpensive: false,
  6594. *
  6595. * constructor: function(config) {
  6596. * this.initConfig(config);
  6597. * },
  6598. *
  6599. * applyPrice: function(price) {
  6600. * this.isExpensive = (price > 500);
  6601. *
  6602. * return price;
  6603. * },
  6604. *
  6605. * applyOperatingSystem: function(operatingSystem) {
  6606. * if (!(/^(iOS|Android|BlackBerry)$/i).test(operatingSystem)) {
  6607. * return 'Other';
  6608. * }
  6609. *
  6610. * return operatingSystem;
  6611. * }
  6612. * });
  6613. *
  6614. * var iPhone = new SmartPhone({
  6615. * hasTouchScreen: true,
  6616. * operatingSystem: 'iOS'
  6617. * });
  6618. *
  6619. * iPhone.getPrice(); // 500;
  6620. * iPhone.getOperatingSystem(); // 'iOS'
  6621. * iPhone.getHasTouchScreen(); // true;
  6622. * iPhone.hasTouchScreen(); // true
  6623. *
  6624. * iPhone.isExpensive; // false;
  6625. * iPhone.setPrice(600);
  6626. * iPhone.getPrice(); // 600
  6627. * iPhone.isExpensive; // true;
  6628. *
  6629. * iPhone.setOperatingSystem('AlienOS');
  6630. * iPhone.getOperatingSystem(); // 'Other'
  6631. *
  6632. * # Statics:
  6633. *
  6634. * Ext.define('Computer', {
  6635. * statics: {
  6636. * factory: function(brand) {
  6637. * // 'this' in static methods refer to the class itself
  6638. * return new this(brand);
  6639. * }
  6640. * },
  6641. *
  6642. * constructor: function() { ... }
  6643. * });
  6644. *
  6645. * var dellComputer = Computer.factory('Dell');
  6646. *
  6647. * Also see {@link Ext.Base#statics} and {@link Ext.Base#self} for more details on accessing
  6648. * static properties within class methods
  6649. *
  6650. * @singleton
  6651. */
  6652. (function(Class, alias, arraySlice, arrayFrom, global) {
  6653. // Creates a constructor that has nothing extra in its scope chain.
  6654. function makeCtor () {
  6655. function constructor () {
  6656. // Opera has some problems returning from a constructor when Dragonfly isn't running. The || null seems to
  6657. // be sufficient to stop it misbehaving. Known to be required against 10.53, 11.51 and 11.61.
  6658. return this.constructor.apply(this, arguments) || null;
  6659. }
  6660. return constructor;
  6661. }
  6662. var Manager = Ext.ClassManager = {
  6663. /**
  6664. * @property {Object} classes
  6665. * All classes which were defined through the ClassManager. Keys are the
  6666. * name of the classes and the values are references to the classes.
  6667. * @private
  6668. */
  6669. classes: {},
  6670. /**
  6671. * @private
  6672. */
  6673. existCache: {},
  6674. /**
  6675. * @private
  6676. */
  6677. namespaceRewrites: [{
  6678. from: 'Ext.',
  6679. to: Ext
  6680. }],
  6681. /**
  6682. * @private
  6683. */
  6684. maps: {
  6685. alternateToName: {},
  6686. aliasToName: {},
  6687. nameToAliases: {},
  6688. nameToAlternates: {}
  6689. },
  6690. /** @private */
  6691. enableNamespaceParseCache: true,
  6692. /** @private */
  6693. namespaceParseCache: {},
  6694. /** @private */
  6695. instantiators: [],
  6696. /**
  6697. * Checks if a class has already been created.
  6698. *
  6699. * @param {String} className
  6700. * @return {Boolean} exist
  6701. */
  6702. isCreated: function(className) {
  6703. var existCache = this.existCache,
  6704. i, ln, part, root, parts;
  6705. if (typeof className != 'string' || className.length < 1) {
  6706. throw new Error("[Ext.ClassManager] Invalid classname, must be a string and must not be empty");
  6707. }
  6708. if (this.classes[className] || existCache[className]) {
  6709. return true;
  6710. }
  6711. root = global;
  6712. parts = this.parseNamespace(className);
  6713. for (i = 0, ln = parts.length; i < ln; i++) {
  6714. part = parts[i];
  6715. if (typeof part != 'string') {
  6716. root = part;
  6717. } else {
  6718. if (!root || !root[part]) {
  6719. return false;
  6720. }
  6721. root = root[part];
  6722. }
  6723. }
  6724. existCache[className] = true;
  6725. this.triggerCreated(className);
  6726. return true;
  6727. },
  6728. /**
  6729. * @private
  6730. */
  6731. createdListeners: [],
  6732. /**
  6733. * @private
  6734. */
  6735. nameCreatedListeners: {},
  6736. /**
  6737. * @private
  6738. */
  6739. triggerCreated: function(className) {
  6740. var listeners = this.createdListeners,
  6741. nameListeners = this.nameCreatedListeners,
  6742. alternateNames = this.maps.nameToAlternates[className],
  6743. names = [className],
  6744. i, ln, j, subLn, listener, name;
  6745. for (i = 0,ln = listeners.length; i < ln; i++) {
  6746. listener = listeners[i];
  6747. listener.fn.call(listener.scope, className);
  6748. }
  6749. if (alternateNames) {
  6750. names.push.apply(names, alternateNames);
  6751. }
  6752. for (i = 0,ln = names.length; i < ln; i++) {
  6753. name = names[i];
  6754. listeners = nameListeners[name];
  6755. if (listeners) {
  6756. for (j = 0,subLn = listeners.length; j < subLn; j++) {
  6757. listener = listeners[j];
  6758. listener.fn.call(listener.scope, name);
  6759. }
  6760. delete nameListeners[name];
  6761. }
  6762. }
  6763. },
  6764. /**
  6765. * @private
  6766. */
  6767. onCreated: function(fn, scope, className) {
  6768. var listeners = this.createdListeners,
  6769. nameListeners = this.nameCreatedListeners,
  6770. listener = {
  6771. fn: fn,
  6772. scope: scope
  6773. };
  6774. if (className) {
  6775. if (this.isCreated(className)) {
  6776. fn.call(scope, className);
  6777. return;
  6778. }
  6779. if (!nameListeners[className]) {
  6780. nameListeners[className] = [];
  6781. }
  6782. nameListeners[className].push(listener);
  6783. }
  6784. else {
  6785. listeners.push(listener);
  6786. }
  6787. },
  6788. /**
  6789. * Supports namespace rewriting
  6790. * @private
  6791. */
  6792. parseNamespace: function(namespace) {
  6793. if (typeof namespace != 'string') {
  6794. throw new Error("[Ext.ClassManager] Invalid namespace, must be a string");
  6795. }
  6796. var cache = this.namespaceParseCache,
  6797. parts,
  6798. rewrites,
  6799. root,
  6800. name,
  6801. rewrite, from, to, i, ln;
  6802. if (this.enableNamespaceParseCache) {
  6803. if (cache.hasOwnProperty(namespace)) {
  6804. return cache[namespace];
  6805. }
  6806. }
  6807. parts = [];
  6808. rewrites = this.namespaceRewrites;
  6809. root = global;
  6810. name = namespace;
  6811. for (i = 0, ln = rewrites.length; i < ln; i++) {
  6812. rewrite = rewrites[i];
  6813. from = rewrite.from;
  6814. to = rewrite.to;
  6815. if (name === from || name.substring(0, from.length) === from) {
  6816. name = name.substring(from.length);
  6817. if (typeof to != 'string') {
  6818. root = to;
  6819. } else {
  6820. parts = parts.concat(to.split('.'));
  6821. }
  6822. break;
  6823. }
  6824. }
  6825. parts.push(root);
  6826. parts = parts.concat(name.split('.'));
  6827. if (this.enableNamespaceParseCache) {
  6828. cache[namespace] = parts;
  6829. }
  6830. return parts;
  6831. },
  6832. /**
  6833. * Creates a namespace and assign the `value` to the created object
  6834. *
  6835. * Ext.ClassManager.setNamespace('MyCompany.pkg.Example', someObject);
  6836. *
  6837. * alert(MyCompany.pkg.Example === someObject); // alerts true
  6838. *
  6839. * @param {String} name
  6840. * @param {Object} value
  6841. */
  6842. setNamespace: function(name, value) {
  6843. var root = global,
  6844. parts = this.parseNamespace(name),
  6845. ln = parts.length - 1,
  6846. leaf = parts[ln],
  6847. i, part;
  6848. for (i = 0; i < ln; i++) {
  6849. part = parts[i];
  6850. if (typeof part != 'string') {
  6851. root = part;
  6852. } else {
  6853. if (!root[part]) {
  6854. root[part] = {};
  6855. }
  6856. root = root[part];
  6857. }
  6858. }
  6859. root[leaf] = value;
  6860. return root[leaf];
  6861. },
  6862. /**
  6863. * The new Ext.ns, supports namespace rewriting
  6864. * @private
  6865. */
  6866. createNamespaces: function() {
  6867. var root = global,
  6868. parts, part, i, j, ln, subLn;
  6869. for (i = 0, ln = arguments.length; i < ln; i++) {
  6870. parts = this.parseNamespace(arguments[i]);
  6871. for (j = 0, subLn = parts.length; j < subLn; j++) {
  6872. part = parts[j];
  6873. if (typeof part != 'string') {
  6874. root = part;
  6875. } else {
  6876. if (!root[part]) {
  6877. root[part] = {};
  6878. }
  6879. root = root[part];
  6880. }
  6881. }
  6882. }
  6883. return root;
  6884. },
  6885. /**
  6886. * Sets a name reference to a class.
  6887. *
  6888. * @param {String} name
  6889. * @param {Object} value
  6890. * @return {Ext.ClassManager} this
  6891. */
  6892. set: function(name, value) {
  6893. var me = this,
  6894. maps = me.maps,
  6895. nameToAlternates = maps.nameToAlternates,
  6896. targetName = me.getName(value),
  6897. alternates;
  6898. me.classes[name] = me.setNamespace(name, value);
  6899. if (targetName && targetName !== name) {
  6900. maps.alternateToName[name] = targetName;
  6901. alternates = nameToAlternates[targetName] || (nameToAlternates[targetName] = []);
  6902. alternates.push(name);
  6903. }
  6904. return this;
  6905. },
  6906. /**
  6907. * Retrieve a class by its name.
  6908. *
  6909. * @param {String} name
  6910. * @return {Ext.Class} class
  6911. */
  6912. get: function(name) {
  6913. var classes = this.classes,
  6914. root,
  6915. parts,
  6916. part, i, ln;
  6917. if (classes[name]) {
  6918. return classes[name];
  6919. }
  6920. root = global;
  6921. parts = this.parseNamespace(name);
  6922. for (i = 0, ln = parts.length; i < ln; i++) {
  6923. part = parts[i];
  6924. if (typeof part != 'string') {
  6925. root = part;
  6926. } else {
  6927. if (!root || !root[part]) {
  6928. return null;
  6929. }
  6930. root = root[part];
  6931. }
  6932. }
  6933. return root;
  6934. },
  6935. /**
  6936. * Register the alias for a class.
  6937. *
  6938. * @param {Ext.Class/String} cls a reference to a class or a className
  6939. * @param {String} alias Alias to use when referring to this class
  6940. */
  6941. setAlias: function(cls, alias) {
  6942. var aliasToNameMap = this.maps.aliasToName,
  6943. nameToAliasesMap = this.maps.nameToAliases,
  6944. className;
  6945. if (typeof cls == 'string') {
  6946. className = cls;
  6947. } else {
  6948. className = this.getName(cls);
  6949. }
  6950. if (alias && aliasToNameMap[alias] !== className) {
  6951. if (aliasToNameMap[alias] && Ext.isDefined(global.console)) {
  6952. global.console.log("[Ext.ClassManager] Overriding existing alias: '" + alias + "' " +
  6953. "of: '" + aliasToNameMap[alias] + "' with: '" + className + "'. Be sure it's intentional.");
  6954. }
  6955. aliasToNameMap[alias] = className;
  6956. }
  6957. if (!nameToAliasesMap[className]) {
  6958. nameToAliasesMap[className] = [];
  6959. }
  6960. if (alias) {
  6961. Ext.Array.include(nameToAliasesMap[className], alias);
  6962. }
  6963. return this;
  6964. },
  6965. /**
  6966. * Adds a batch of class name to alias mappings
  6967. * @param {Object} aliases The set of mappings of the form
  6968. * className : [values...]
  6969. */
  6970. addNameAliasMappings: function(aliases){
  6971. var aliasToNameMap = this.maps.aliasToName,
  6972. nameToAliasesMap = this.maps.nameToAliases,
  6973. className, aliasList, alias, i;
  6974. for (className in aliases) {
  6975. aliasList = nameToAliasesMap[className] ||
  6976. (nameToAliasesMap[className] = []);
  6977. for (i = 0; i < aliases[className].length; i++) {
  6978. alias = aliases[className][i];
  6979. if (!aliasToNameMap[alias]) {
  6980. aliasToNameMap[alias] = className;
  6981. aliasList.push(alias);
  6982. }
  6983. }
  6984. }
  6985. return this;
  6986. },
  6987. /**
  6988. *
  6989. * @param {Object} alternates The set of mappings of the form
  6990. * className : [values...]
  6991. */
  6992. addNameAlternateMappings: function(alternates) {
  6993. var alternateToName = this.maps.alternateToName,
  6994. nameToAlternates = this.maps.nameToAlternates,
  6995. className, aliasList, alternate, i;
  6996. for (className in alternates) {
  6997. aliasList = nameToAlternates[className] ||
  6998. (nameToAlternates[className] = []);
  6999. for (i = 0; i < alternates[className].length; i++) {
  7000. alternate = alternates[className];
  7001. if (!alternateToName[alternate]) {
  7002. alternateToName[alternate] = className;
  7003. aliasList.push(alternate);
  7004. }
  7005. }
  7006. }
  7007. return this;
  7008. },
  7009. /**
  7010. * Get a reference to the class by its alias.
  7011. *
  7012. * @param {String} alias
  7013. * @return {Ext.Class} class
  7014. */
  7015. getByAlias: function(alias) {
  7016. return this.get(this.getNameByAlias(alias));
  7017. },
  7018. /**
  7019. * Get the name of a class by its alias.
  7020. *
  7021. * @param {String} alias
  7022. * @return {String} className
  7023. */
  7024. getNameByAlias: function(alias) {
  7025. return this.maps.aliasToName[alias] || '';
  7026. },
  7027. /**
  7028. * Get the name of a class by its alternate name.
  7029. *
  7030. * @param {String} alternate
  7031. * @return {String} className
  7032. */
  7033. getNameByAlternate: function(alternate) {
  7034. return this.maps.alternateToName[alternate] || '';
  7035. },
  7036. /**
  7037. * Get the aliases of a class by the class name
  7038. *
  7039. * @param {String} name
  7040. * @return {Array} aliases
  7041. */
  7042. getAliasesByName: function(name) {
  7043. return this.maps.nameToAliases[name] || [];
  7044. },
  7045. /**
  7046. * Get the name of the class by its reference or its instance;
  7047. * usually invoked by the shorthand {@link Ext#getClassName Ext.getClassName}
  7048. *
  7049. * Ext.ClassManager.getName(Ext.Action); // returns "Ext.Action"
  7050. *
  7051. * @param {Ext.Class/Object} object
  7052. * @return {String} className
  7053. */
  7054. getName: function(object) {
  7055. return object && object.$className || '';
  7056. },
  7057. /**
  7058. * Get the class of the provided object; returns null if it's not an instance
  7059. * of any class created with Ext.define. This is usually invoked by the shorthand {@link Ext#getClass Ext.getClass}
  7060. *
  7061. * var component = new Ext.Component();
  7062. *
  7063. * Ext.ClassManager.getClass(component); // returns Ext.Component
  7064. *
  7065. * @param {Object} object
  7066. * @return {Ext.Class} class
  7067. */
  7068. getClass: function(object) {
  7069. return object && object.self || null;
  7070. },
  7071. /**
  7072. * Defines a class.
  7073. * @deprecated 4.1.0 Use {@link Ext#define} instead, as that also supports creating overrides.
  7074. */
  7075. create: function(className, data, createdFn) {
  7076. if (className != null && typeof className != 'string') {
  7077. throw new Error("[Ext.define] Invalid class name '" + className + "' specified, must be a non-empty string");
  7078. }
  7079. var ctor = makeCtor();
  7080. if (typeof data == 'function') {
  7081. data = data(ctor);
  7082. }
  7083. if (className) {
  7084. ctor.displayName = className;
  7085. }
  7086. data.$className = className;
  7087. return new Class(ctor, data, function() {
  7088. var postprocessorStack = data.postprocessors || Manager.defaultPostprocessors,
  7089. registeredPostprocessors = Manager.postprocessors,
  7090. postprocessors = [],
  7091. postprocessor, i, ln, j, subLn, postprocessorProperties, postprocessorProperty;
  7092. delete data.postprocessors;
  7093. for (i = 0,ln = postprocessorStack.length; i < ln; i++) {
  7094. postprocessor = postprocessorStack[i];
  7095. if (typeof postprocessor == 'string') {
  7096. postprocessor = registeredPostprocessors[postprocessor];
  7097. postprocessorProperties = postprocessor.properties;
  7098. if (postprocessorProperties === true) {
  7099. postprocessors.push(postprocessor.fn);
  7100. }
  7101. else if (postprocessorProperties) {
  7102. for (j = 0,subLn = postprocessorProperties.length; j < subLn; j++) {
  7103. postprocessorProperty = postprocessorProperties[j];
  7104. if (data.hasOwnProperty(postprocessorProperty)) {
  7105. postprocessors.push(postprocessor.fn);
  7106. break;
  7107. }
  7108. }
  7109. }
  7110. }
  7111. else {
  7112. postprocessors.push(postprocessor);
  7113. }
  7114. }
  7115. data.postprocessors = postprocessors;
  7116. data.createdFn = createdFn;
  7117. Manager.processCreate(className, this, data);
  7118. });
  7119. },
  7120. processCreate: function(className, cls, clsData){
  7121. var me = this,
  7122. postprocessor = clsData.postprocessors.shift(),
  7123. createdFn = clsData.createdFn;
  7124. if (!postprocessor) {
  7125. if (className) {
  7126. me.set(className, cls);
  7127. }
  7128. if (createdFn) {
  7129. createdFn.call(cls, cls);
  7130. }
  7131. if (className) {
  7132. me.triggerCreated(className);
  7133. }
  7134. return;
  7135. }
  7136. if (postprocessor.call(me, className, cls, clsData, me.processCreate) !== false) {
  7137. me.processCreate(className, cls, clsData);
  7138. }
  7139. },
  7140. createOverride: function (className, data, createdFn) {
  7141. var me = this,
  7142. overriddenClassName = data.override,
  7143. requires = data.requires,
  7144. uses = data.uses,
  7145. classReady = function () {
  7146. var cls, temp;
  7147. if (requires) {
  7148. temp = requires;
  7149. requires = null; // do the real thing next time (which may be now)
  7150. // Since the override is going to be used (its target class is now
  7151. // created), we need to fetch the required classes for the override
  7152. // and call us back once they are loaded:
  7153. Ext.Loader.require(temp, classReady);
  7154. } else {
  7155. // The target class and the required classes for this override are
  7156. // ready, so we can apply the override now:
  7157. cls = me.get(overriddenClassName);
  7158. // We don't want to apply these:
  7159. delete data.override;
  7160. delete data.requires;
  7161. delete data.uses;
  7162. Ext.override(cls, data);
  7163. // This pushes the overridding file itself into Ext.Loader.history
  7164. // Hence if the target class never exists, the overriding file will
  7165. // never be included in the build.
  7166. me.triggerCreated(className);
  7167. if (uses) {
  7168. Ext.Loader.addUsedClasses(uses); // get these classes too!
  7169. }
  7170. if (createdFn) {
  7171. createdFn.call(cls); // last but not least!
  7172. }
  7173. }
  7174. };
  7175. me.existCache[className] = true;
  7176. // Override the target class right after it's created
  7177. me.onCreated(classReady, me, overriddenClassName);
  7178. return me;
  7179. },
  7180. /**
  7181. * Instantiate a class by its alias; usually invoked by the convenient shorthand {@link Ext#createByAlias Ext.createByAlias}
  7182. * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has not been defined yet, it will
  7183. * attempt to load the class via synchronous loading.
  7184. *
  7185. * var window = Ext.ClassManager.instantiateByAlias('widget.window', { width: 600, height: 800, ... });
  7186. *
  7187. * @param {String} alias
  7188. * @param {Object...} args Additional arguments after the alias will be passed to the
  7189. * class constructor.
  7190. * @return {Object} instance
  7191. */
  7192. instantiateByAlias: function() {
  7193. var alias = arguments[0],
  7194. args = arraySlice.call(arguments),
  7195. className = this.getNameByAlias(alias);
  7196. if (!className) {
  7197. className = this.maps.aliasToName[alias];
  7198. if (!className) {
  7199. throw new Error("[Ext.createByAlias] Cannot create an instance of unrecognized alias: " + alias);
  7200. }
  7201. if (global.console) {
  7202. global.console.warn("[Ext.Loader] Synchronously loading '" + className + "'; consider adding " +
  7203. "Ext.require('" + alias + "') above Ext.onReady");
  7204. }
  7205. Ext.syncRequire(className);
  7206. }
  7207. args[0] = className;
  7208. return this.instantiate.apply(this, args);
  7209. },
  7210. /**
  7211. * @private
  7212. */
  7213. instantiate: function() {
  7214. var name = arguments[0],
  7215. nameType = typeof name,
  7216. args = arraySlice.call(arguments, 1),
  7217. alias = name,
  7218. possibleName, cls;
  7219. if (nameType != 'function') {
  7220. if (nameType != 'string' && args.length === 0) {
  7221. args = [name];
  7222. name = name.xclass;
  7223. }
  7224. if (typeof name != 'string' || name.length < 1) {
  7225. throw new Error("[Ext.create] Invalid class name or alias '" + name + "' specified, must be a non-empty string");
  7226. }
  7227. cls = this.get(name);
  7228. }
  7229. else {
  7230. cls = name;
  7231. }
  7232. // No record of this class name, it's possibly an alias, so look it up
  7233. if (!cls) {
  7234. possibleName = this.getNameByAlias(name);
  7235. if (possibleName) {
  7236. name = possibleName;
  7237. cls = this.get(name);
  7238. }
  7239. }
  7240. // Still no record of this class name, it's possibly an alternate name, so look it up
  7241. if (!cls) {
  7242. possibleName = this.getNameByAlternate(name);
  7243. if (possibleName) {
  7244. name = possibleName;
  7245. cls = this.get(name);
  7246. }
  7247. }
  7248. // Still not existing at this point, try to load it via synchronous mode as the last resort
  7249. if (!cls) {
  7250. if (global.console) {
  7251. global.console.warn("[Ext.Loader] Synchronously loading '" + name + "'; consider adding " +
  7252. "Ext.require('" + ((possibleName) ? alias : name) + "') above Ext.onReady");
  7253. }
  7254. Ext.syncRequire(name);
  7255. cls = this.get(name);
  7256. }
  7257. if (!cls) {
  7258. throw new Error("[Ext.create] Cannot create an instance of unrecognized class name / alias: " + alias);
  7259. }
  7260. if (typeof cls != 'function') {
  7261. throw new Error("[Ext.create] '" + name + "' is a singleton and cannot be instantiated");
  7262. }
  7263. return this.getInstantiator(args.length)(cls, args);
  7264. },
  7265. /**
  7266. * @private
  7267. * @param name
  7268. * @param args
  7269. */
  7270. dynInstantiate: function(name, args) {
  7271. args = arrayFrom(args, true);
  7272. args.unshift(name);
  7273. return this.instantiate.apply(this, args);
  7274. },
  7275. /**
  7276. * @private
  7277. * @param length
  7278. */
  7279. getInstantiator: function(length) {
  7280. var instantiators = this.instantiators,
  7281. instantiator,
  7282. i,
  7283. args;
  7284. instantiator = instantiators[length];
  7285. if (!instantiator) {
  7286. i = length;
  7287. args = [];
  7288. for (i = 0; i < length; i++) {
  7289. args.push('a[' + i + ']');
  7290. }
  7291. instantiator = instantiators[length] = new Function('c', 'a', 'return new c(' + args.join(',') + ')');
  7292. instantiator.displayName = "Ext.ClassManager.instantiate" + length;
  7293. }
  7294. return instantiator;
  7295. },
  7296. /**
  7297. * @private
  7298. */
  7299. postprocessors: {},
  7300. /**
  7301. * @private
  7302. */
  7303. defaultPostprocessors: [],
  7304. /**
  7305. * Register a post-processor function.
  7306. *
  7307. * @private
  7308. * @param {String} name
  7309. * @param {Function} postprocessor
  7310. */
  7311. registerPostprocessor: function(name, fn, properties, position, relativeTo) {
  7312. if (!position) {
  7313. position = 'last';
  7314. }
  7315. if (!properties) {
  7316. properties = [name];
  7317. }
  7318. this.postprocessors[name] = {
  7319. name: name,
  7320. properties: properties || false,
  7321. fn: fn
  7322. };
  7323. this.setDefaultPostprocessorPosition(name, position, relativeTo);
  7324. return this;
  7325. },
  7326. /**
  7327. * Set the default post processors array stack which are applied to every class.
  7328. *
  7329. * @private
  7330. * @param {String/Array} The name of a registered post processor or an array of registered names.
  7331. * @return {Ext.ClassManager} this
  7332. */
  7333. setDefaultPostprocessors: function(postprocessors) {
  7334. this.defaultPostprocessors = arrayFrom(postprocessors);
  7335. return this;
  7336. },
  7337. /**
  7338. * Insert this post-processor at a specific position in the stack, optionally relative to
  7339. * any existing post-processor
  7340. *
  7341. * @private
  7342. * @param {String} name The post-processor name. Note that it needs to be registered with
  7343. * {@link Ext.ClassManager#registerPostprocessor} before this
  7344. * @param {String} offset The insertion position. Four possible values are:
  7345. * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument)
  7346. * @param {String} relativeName
  7347. * @return {Ext.ClassManager} this
  7348. */
  7349. setDefaultPostprocessorPosition: function(name, offset, relativeName) {
  7350. var defaultPostprocessors = this.defaultPostprocessors,
  7351. index;
  7352. if (typeof offset == 'string') {
  7353. if (offset === 'first') {
  7354. defaultPostprocessors.unshift(name);
  7355. return this;
  7356. }
  7357. else if (offset === 'last') {
  7358. defaultPostprocessors.push(name);
  7359. return this;
  7360. }
  7361. offset = (offset === 'after') ? 1 : -1;
  7362. }
  7363. index = Ext.Array.indexOf(defaultPostprocessors, relativeName);
  7364. if (index !== -1) {
  7365. Ext.Array.splice(defaultPostprocessors, Math.max(0, index + offset), 0, name);
  7366. }
  7367. return this;
  7368. },
  7369. /**
  7370. * Converts a string expression to an array of matching class names. An expression can either refers to class aliases
  7371. * or class names. Expressions support wildcards:
  7372. *
  7373. * // returns ['Ext.window.Window']
  7374. * var window = Ext.ClassManager.getNamesByExpression('widget.window');
  7375. *
  7376. * // returns ['widget.panel', 'widget.window', ...]
  7377. * var allWidgets = Ext.ClassManager.getNamesByExpression('widget.*');
  7378. *
  7379. * // returns ['Ext.data.Store', 'Ext.data.ArrayProxy', ...]
  7380. * var allData = Ext.ClassManager.getNamesByExpression('Ext.data.*');
  7381. *
  7382. * @param {String} expression
  7383. * @return {String[]} classNames
  7384. */
  7385. getNamesByExpression: function(expression) {
  7386. var nameToAliasesMap = this.maps.nameToAliases,
  7387. names = [],
  7388. name, alias, aliases, possibleName, regex, i, ln;
  7389. if (typeof expression != 'string' || expression.length < 1) {
  7390. throw new Error("[Ext.ClassManager.getNamesByExpression] Expression " + expression + " is invalid, must be a non-empty string");
  7391. }
  7392. if (expression.indexOf('*') !== -1) {
  7393. expression = expression.replace(/\*/g, '(.*?)');
  7394. regex = new RegExp('^' + expression + '$');
  7395. for (name in nameToAliasesMap) {
  7396. if (nameToAliasesMap.hasOwnProperty(name)) {
  7397. aliases = nameToAliasesMap[name];
  7398. if (name.search(regex) !== -1) {
  7399. names.push(name);
  7400. }
  7401. else {
  7402. for (i = 0, ln = aliases.length; i < ln; i++) {
  7403. alias = aliases[i];
  7404. if (alias.search(regex) !== -1) {
  7405. names.push(name);
  7406. break;
  7407. }
  7408. }
  7409. }
  7410. }
  7411. }
  7412. } else {
  7413. possibleName = this.getNameByAlias(expression);
  7414. if (possibleName) {
  7415. names.push(possibleName);
  7416. } else {
  7417. possibleName = this.getNameByAlternate(expression);
  7418. if (possibleName) {
  7419. names.push(possibleName);
  7420. } else {
  7421. names.push(expression);
  7422. }
  7423. }
  7424. }
  7425. return names;
  7426. }
  7427. };
  7428. /**
  7429. * @cfg {String[]} alias
  7430. * @member Ext.Class
  7431. * List of short aliases for class names. Most useful for defining xtypes for widgets:
  7432. *
  7433. * Ext.define('MyApp.CoolPanel', {
  7434. * extend: 'Ext.panel.Panel',
  7435. * alias: ['widget.coolpanel'],
  7436. * title: 'Yeah!'
  7437. * });
  7438. *
  7439. * // Using Ext.create
  7440. * Ext.create('widget.coolpanel');
  7441. *
  7442. * // Using the shorthand for defining widgets by xtype
  7443. * Ext.widget('panel', {
  7444. * items: [
  7445. * {xtype: 'coolpanel', html: 'Foo'},
  7446. * {xtype: 'coolpanel', html: 'Bar'}
  7447. * ]
  7448. * });
  7449. *
  7450. * Besides "widget" for xtype there are alias namespaces like "feature" for ftype and "plugin" for ptype.
  7451. */
  7452. Manager.registerPostprocessor('alias', function(name, cls, data) {
  7453. var aliases = data.alias,
  7454. i, ln;
  7455. for (i = 0,ln = aliases.length; i < ln; i++) {
  7456. alias = aliases[i];
  7457. this.setAlias(cls, alias);
  7458. }
  7459. }, ['xtype', 'alias']);
  7460. /**
  7461. * @cfg {Boolean} singleton
  7462. * @member Ext.Class
  7463. * When set to true, the class will be instantiated as singleton. For example:
  7464. *
  7465. * Ext.define('Logger', {
  7466. * singleton: true,
  7467. * log: function(msg) {
  7468. * console.log(msg);
  7469. * }
  7470. * });
  7471. *
  7472. * Logger.log('Hello');
  7473. */
  7474. Manager.registerPostprocessor('singleton', function(name, cls, data, fn) {
  7475. fn.call(this, name, new cls(), data);
  7476. return false;
  7477. });
  7478. /**
  7479. * @cfg {String/String[]} alternateClassName
  7480. * @member Ext.Class
  7481. * Defines alternate names for this class. For example:
  7482. *
  7483. * Ext.define('Developer', {
  7484. * alternateClassName: ['Coder', 'Hacker'],
  7485. * code: function(msg) {
  7486. * alert('Typing... ' + msg);
  7487. * }
  7488. * });
  7489. *
  7490. * var joe = Ext.create('Developer');
  7491. * joe.code('stackoverflow');
  7492. *
  7493. * var rms = Ext.create('Hacker');
  7494. * rms.code('hack hack');
  7495. */
  7496. Manager.registerPostprocessor('alternateClassName', function(name, cls, data) {
  7497. var alternates = data.alternateClassName,
  7498. i, ln, alternate;
  7499. if (!(alternates instanceof Array)) {
  7500. alternates = [alternates];
  7501. }
  7502. for (i = 0, ln = alternates.length; i < ln; i++) {
  7503. alternate = alternates[i];
  7504. if (typeof alternate != 'string') {
  7505. throw new Error("[Ext.define] Invalid alternate of: '" + alternate + "' for class: '" + name + "'; must be a valid string");
  7506. }
  7507. this.set(alternate, cls);
  7508. }
  7509. });
  7510. Ext.apply(Ext, {
  7511. /**
  7512. * Instantiate a class by either full name, alias or alternate name.
  7513. *
  7514. * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has
  7515. * not been defined yet, it will attempt to load the class via synchronous loading.
  7516. *
  7517. * For example, all these three lines return the same result:
  7518. *
  7519. * // alias
  7520. * var window = Ext.create('widget.window', {
  7521. * width: 600,
  7522. * height: 800,
  7523. * ...
  7524. * });
  7525. *
  7526. * // alternate name
  7527. * var window = Ext.create('Ext.Window', {
  7528. * width: 600,
  7529. * height: 800,
  7530. * ...
  7531. * });
  7532. *
  7533. * // full class name
  7534. * var window = Ext.create('Ext.window.Window', {
  7535. * width: 600,
  7536. * height: 800,
  7537. * ...
  7538. * });
  7539. *
  7540. * // single object with xclass property:
  7541. * var window = Ext.create({
  7542. * xclass: 'Ext.window.Window', // any valid value for 'name' (above)
  7543. * width: 600,
  7544. * height: 800,
  7545. * ...
  7546. * });
  7547. *
  7548. * @param {String} [name] The class name or alias. Can be specified as `xclass`
  7549. * property if only one object parameter is specified.
  7550. * @param {Object...} [args] Additional arguments after the name will be passed to
  7551. * the class' constructor.
  7552. * @return {Object} instance
  7553. * @member Ext
  7554. * @method create
  7555. */
  7556. create: alias(Manager, 'instantiate'),
  7557. /**
  7558. * Convenient shorthand to create a widget by its xtype or a config object.
  7559. * See also {@link Ext.ClassManager#instantiateByAlias}.
  7560. *
  7561. * var button = Ext.widget('button'); // Equivalent to Ext.create('widget.button');
  7562. *
  7563. * var panel = Ext.widget('panel', { // Equivalent to Ext.create('widget.panel')
  7564. * title: 'Panel'
  7565. * });
  7566. *
  7567. * var grid = Ext.widget({
  7568. * xtype: 'grid',
  7569. * ...
  7570. * });
  7571. *
  7572. * If a {@link Ext.Component component} instance is passed, it is simply returned.
  7573. *
  7574. * @member Ext
  7575. * @param {String} [name] The xtype of the widget to create.
  7576. * @param {Object} [config] The configuration object for the widget constructor.
  7577. * @return {Object} The widget instance
  7578. */
  7579. widget: function(name, config) {
  7580. // forms:
  7581. // 1: (xtype)
  7582. // 2: (xtype, config)
  7583. // 3: (config)
  7584. // 4: (xtype, component)
  7585. // 5: (component)
  7586. //
  7587. var xtype = name,
  7588. alias, className, T, load;
  7589. if (typeof xtype != 'string') { // if (form 3 or 5)
  7590. // first arg is config or component
  7591. config = name; // arguments[0]
  7592. xtype = config.xtype;
  7593. } else {
  7594. config = config || {};
  7595. }
  7596. if (config.isComponent) {
  7597. return config;
  7598. }
  7599. alias = 'widget.' + xtype;
  7600. className = Manager.getNameByAlias(alias);
  7601. // this is needed to support demand loading of the class
  7602. if (!className) {
  7603. load = true;
  7604. }
  7605. T = Manager.get(className);
  7606. if (load || !T) {
  7607. return Manager.instantiateByAlias(alias, config);
  7608. }
  7609. return new T(config);
  7610. },
  7611. /**
  7612. * Convenient shorthand, see {@link Ext.ClassManager#instantiateByAlias}
  7613. * @member Ext
  7614. * @method createByAlias
  7615. */
  7616. createByAlias: alias(Manager, 'instantiateByAlias'),
  7617. /**
  7618. * @method
  7619. * Defines a class or override. A basic class is defined like this:
  7620. *
  7621. * Ext.define('My.awesome.Class', {
  7622. * someProperty: 'something',
  7623. *
  7624. * someMethod: function(s) {
  7625. * alert(s + this.someProperty);
  7626. * }
  7627. *
  7628. * ...
  7629. * });
  7630. *
  7631. * var obj = new My.awesome.Class();
  7632. *
  7633. * obj.someMethod('Say '); // alerts 'Say something'
  7634. *
  7635. * To create an anonymous class, pass `null` for the `className`:
  7636. *
  7637. * Ext.define(null, {
  7638. * constructor: function () {
  7639. * // ...
  7640. * }
  7641. * });
  7642. *
  7643. * In some cases, it is helpful to create a nested scope to contain some private
  7644. * properties. The best way to do this is to pass a function instead of an object
  7645. * as the second parameter. This function will be called to produce the class
  7646. * body:
  7647. *
  7648. * Ext.define('MyApp.foo.Bar', function () {
  7649. * var id = 0;
  7650. *
  7651. * return {
  7652. * nextId: function () {
  7653. * return ++id;
  7654. * }
  7655. * };
  7656. * });
  7657. *
  7658. * When using this form of `Ext.define`, the function is passed a reference to its
  7659. * class. This can be used as an efficient way to access any static properties you
  7660. * may have:
  7661. *
  7662. * Ext.define('MyApp.foo.Bar', function (Bar) {
  7663. * return {
  7664. * statics: {
  7665. * staticMethod: function () {
  7666. * // ...
  7667. * }
  7668. * },
  7669. *
  7670. * method: function () {
  7671. * return Bar.staticMethod();
  7672. * }
  7673. * };
  7674. * });
  7675. *
  7676. * To define an override, include the `override` property. The content of an
  7677. * override is aggregated with the specified class in order to extend or modify
  7678. * that class. This can be as simple as setting default property values or it can
  7679. * extend and/or replace methods. This can also extend the statics of the class.
  7680. *
  7681. * One use for an override is to break a large class into manageable pieces.
  7682. *
  7683. * // File: /src/app/Panel.js
  7684. *
  7685. * Ext.define('My.app.Panel', {
  7686. * extend: 'Ext.panel.Panel',
  7687. * requires: [
  7688. * 'My.app.PanelPart2',
  7689. * 'My.app.PanelPart3'
  7690. * ]
  7691. *
  7692. * constructor: function (config) {
  7693. * this.callParent(arguments); // calls Ext.panel.Panel's constructor
  7694. * //...
  7695. * },
  7696. *
  7697. * statics: {
  7698. * method: function () {
  7699. * return 'abc';
  7700. * }
  7701. * }
  7702. * });
  7703. *
  7704. * // File: /src/app/PanelPart2.js
  7705. * Ext.define('My.app.PanelPart2', {
  7706. * override: 'My.app.Panel',
  7707. *
  7708. * constructor: function (config) {
  7709. * this.callParent(arguments); // calls My.app.Panel's constructor
  7710. * //...
  7711. * }
  7712. * });
  7713. *
  7714. * Another use of overrides is to provide optional parts of classes that can be
  7715. * independently required. In this case, the class may even be unaware of the
  7716. * override altogether.
  7717. *
  7718. * Ext.define('My.ux.CoolTip', {
  7719. * override: 'Ext.tip.ToolTip',
  7720. *
  7721. * constructor: function (config) {
  7722. * this.callParent(arguments); // calls Ext.tip.ToolTip's constructor
  7723. * //...
  7724. * }
  7725. * });
  7726. *
  7727. * The above override can now be required as normal.
  7728. *
  7729. * Ext.define('My.app.App', {
  7730. * requires: [
  7731. * 'My.ux.CoolTip'
  7732. * ]
  7733. * });
  7734. *
  7735. * Overrides can also contain statics:
  7736. *
  7737. * Ext.define('My.app.BarMod', {
  7738. * override: 'Ext.foo.Bar',
  7739. *
  7740. * statics: {
  7741. * method: function (x) {
  7742. * return this.callParent([x * 2]); // call Ext.foo.Bar.method
  7743. * }
  7744. * }
  7745. * });
  7746. *
  7747. * IMPORTANT: An override is only included in a build if the class it overrides is
  7748. * required. Otherwise, the override, like the target class, is not included.
  7749. *
  7750. * @param {String} className The class name to create in string dot-namespaced format, for example:
  7751. * 'My.very.awesome.Class', 'FeedViewer.plugin.CoolPager'
  7752. * It is highly recommended to follow this simple convention:
  7753. * - The root and the class name are 'CamelCased'
  7754. * - Everything else is lower-cased
  7755. * Pass `null` to create an anonymous class.
  7756. * @param {Object} data The key - value pairs of properties to apply to this class. Property names can be of any valid
  7757. * strings, except those in the reserved listed below:
  7758. * - `mixins`
  7759. * - `statics`
  7760. * - `config`
  7761. * - `alias`
  7762. * - `self`
  7763. * - `singleton`
  7764. * - `alternateClassName`
  7765. * - `override`
  7766. *
  7767. * @param {Function} createdFn Optional callback to execute after the class is created, the execution scope of which
  7768. * (`this`) will be the newly created class itself.
  7769. * @return {Ext.Base}
  7770. * @markdown
  7771. * @member Ext
  7772. * @method define
  7773. */
  7774. define: function (className, data, createdFn) {
  7775. if (data.override) {
  7776. return Manager.createOverride.apply(Manager, arguments);
  7777. }
  7778. return Manager.create.apply(Manager, arguments);
  7779. },
  7780. /**
  7781. * Convenient shorthand, see {@link Ext.ClassManager#getName}
  7782. * @member Ext
  7783. * @method getClassName
  7784. */
  7785. getClassName: alias(Manager, 'getName'),
  7786. /**
  7787. * Returns the displayName property or className or object. When all else fails, returns "Anonymous".
  7788. * @param {Object} object
  7789. * @return {String}
  7790. */
  7791. getDisplayName: function(object) {
  7792. if (object) {
  7793. if (object.displayName) {
  7794. return object.displayName;
  7795. }
  7796. if (object.$name && object.$class) {
  7797. return Ext.getClassName(object.$class) + '#' + object.$name;
  7798. }
  7799. if (object.$className) {
  7800. return object.$className;
  7801. }
  7802. }
  7803. return 'Anonymous';
  7804. },
  7805. /**
  7806. * Convenient shorthand, see {@link Ext.ClassManager#getClass}
  7807. * @member Ext
  7808. * @method getClass
  7809. */
  7810. getClass: alias(Manager, 'getClass'),
  7811. /**
  7812. * Creates namespaces to be used for scoping variables and classes so that they are not global.
  7813. * Specifying the last node of a namespace implicitly creates all other nodes. Usage:
  7814. *
  7815. * Ext.namespace('Company', 'Company.data');
  7816. *
  7817. * // equivalent and preferable to the above syntax
  7818. * Ext.ns('Company.data');
  7819. *
  7820. * Company.Widget = function() { ... };
  7821. *
  7822. * Company.data.CustomStore = function(config) { ... };
  7823. *
  7824. * @param {String...} namespaces
  7825. * @return {Object} The namespace object.
  7826. * (If multiple arguments are passed, this will be the last namespace created)
  7827. * @member Ext
  7828. * @method namespace
  7829. */
  7830. namespace: alias(Manager, 'createNamespaces')
  7831. });
  7832. /**
  7833. * Old name for {@link Ext#widget}.
  7834. * @deprecated 4.0.0 Use {@link Ext#widget} instead.
  7835. * @method createWidget
  7836. * @member Ext
  7837. */
  7838. Ext.createWidget = Ext.widget;
  7839. /**
  7840. * Convenient alias for {@link Ext#namespace Ext.namespace}.
  7841. * @inheritdoc Ext#namespace
  7842. * @member Ext
  7843. * @method ns
  7844. */
  7845. Ext.ns = Ext.namespace;
  7846. Class.registerPreprocessor('className', function(cls, data) {
  7847. if (data.$className) {
  7848. cls.$className = data.$className;
  7849. cls.displayName = cls.$className;
  7850. }
  7851. }, true, 'first');
  7852. Class.registerPreprocessor('alias', function(cls, data) {
  7853. var prototype = cls.prototype,
  7854. xtypes = arrayFrom(data.xtype),
  7855. aliases = arrayFrom(data.alias),
  7856. widgetPrefix = 'widget.',
  7857. widgetPrefixLength = widgetPrefix.length,
  7858. xtypesChain = Array.prototype.slice.call(prototype.xtypesChain || []),
  7859. xtypesMap = Ext.merge({}, prototype.xtypesMap || {}),
  7860. i, ln, alias, xtype;
  7861. for (i = 0,ln = aliases.length; i < ln; i++) {
  7862. alias = aliases[i];
  7863. if (typeof alias != 'string' || alias.length < 1) {
  7864. throw new Error("[Ext.define] Invalid alias of: '" + alias + "' for class: '" + name + "'; must be a valid string");
  7865. }
  7866. if (alias.substring(0, widgetPrefixLength) === widgetPrefix) {
  7867. xtype = alias.substring(widgetPrefixLength);
  7868. Ext.Array.include(xtypes, xtype);
  7869. }
  7870. }
  7871. cls.xtype = data.xtype = xtypes[0];
  7872. data.xtypes = xtypes;
  7873. for (i = 0,ln = xtypes.length; i < ln; i++) {
  7874. xtype = xtypes[i];
  7875. if (!xtypesMap[xtype]) {
  7876. xtypesMap[xtype] = true;
  7877. xtypesChain.push(xtype);
  7878. }
  7879. }
  7880. data.xtypesChain = xtypesChain;
  7881. data.xtypesMap = xtypesMap;
  7882. Ext.Function.interceptAfter(data, 'onClassCreated', function() {
  7883. var mixins = prototype.mixins,
  7884. key, mixin;
  7885. for (key in mixins) {
  7886. if (mixins.hasOwnProperty(key)) {
  7887. mixin = mixins[key];
  7888. xtypes = mixin.xtypes;
  7889. if (xtypes) {
  7890. for (i = 0,ln = xtypes.length; i < ln; i++) {
  7891. xtype = xtypes[i];
  7892. if (!xtypesMap[xtype]) {
  7893. xtypesMap[xtype] = true;
  7894. xtypesChain.push(xtype);
  7895. }
  7896. }
  7897. }
  7898. }
  7899. }
  7900. });
  7901. for (i = 0,ln = xtypes.length; i < ln; i++) {
  7902. xtype = xtypes[i];
  7903. if (typeof xtype != 'string' || xtype.length < 1) {
  7904. throw new Error("[Ext.define] Invalid xtype of: '" + xtype + "' for class: '" + name + "'; must be a valid non-empty string");
  7905. }
  7906. Ext.Array.include(aliases, widgetPrefix + xtype);
  7907. }
  7908. data.alias = aliases;
  7909. }, ['xtype', 'alias']);
  7910. }(Ext.Class, Ext.Function.alias, Array.prototype.slice, Ext.Array.from, Ext.global));
  7911. //@tag foundation,core
  7912. //@require ClassManager.js
  7913. //@define Ext.Loader
  7914. /**
  7915. * @author Jacky Nguyen <jacky@sencha.com>
  7916. * @docauthor Jacky Nguyen <jacky@sencha.com>
  7917. * @class Ext.Loader
  7918. *
  7919. * Ext.Loader is the heart of the new dynamic dependency loading capability in Ext JS 4+. It is most commonly used
  7920. * via the {@link Ext#require} shorthand. Ext.Loader supports both asynchronous and synchronous loading
  7921. * approaches, and leverage their advantages for the best development flow. We'll discuss about the pros and cons of each approach:
  7922. *
  7923. * # Asynchronous Loading #
  7924. *
  7925. * - Advantages:
  7926. * + Cross-domain
  7927. * + No web server needed: you can run the application via the file system protocol (i.e: `file://path/to/your/index
  7928. * .html`)
  7929. * + Best possible debugging experience: error messages come with the exact file name and line number
  7930. *
  7931. * - Disadvantages:
  7932. * + Dependencies need to be specified before-hand
  7933. *
  7934. * ### Method 1: Explicitly include what you need: ###
  7935. *
  7936. * // Syntax
  7937. * Ext.require({String/Array} expressions);
  7938. *
  7939. * // Example: Single alias
  7940. * Ext.require('widget.window');
  7941. *
  7942. * // Example: Single class name
  7943. * Ext.require('Ext.window.Window');
  7944. *
  7945. * // Example: Multiple aliases / class names mix
  7946. * Ext.require(['widget.window', 'layout.border', 'Ext.data.Connection']);
  7947. *
  7948. * // Wildcards
  7949. * Ext.require(['widget.*', 'layout.*', 'Ext.data.*']);
  7950. *
  7951. * ### Method 2: Explicitly exclude what you don't need: ###
  7952. *
  7953. * // Syntax: Note that it must be in this chaining format.
  7954. * Ext.exclude({String/Array} expressions)
  7955. * .require({String/Array} expressions);
  7956. *
  7957. * // Include everything except Ext.data.*
  7958. * Ext.exclude('Ext.data.*').require('*');
  7959. *
  7960. * // Include all widgets except widget.checkbox*,
  7961. * // which will match widget.checkbox, widget.checkboxfield, widget.checkboxgroup, etc.
  7962. * Ext.exclude('widget.checkbox*').require('widget.*');
  7963. *
  7964. * # Synchronous Loading on Demand #
  7965. *
  7966. * - Advantages:
  7967. * + There's no need to specify dependencies before-hand, which is always the convenience of including ext-all.js
  7968. * before
  7969. *
  7970. * - Disadvantages:
  7971. * + Not as good debugging experience since file name won't be shown (except in Firebug at the moment)
  7972. * + Must be from the same domain due to XHR restriction
  7973. * + Need a web server, same reason as above
  7974. *
  7975. * There's one simple rule to follow: Instantiate everything with Ext.create instead of the `new` keyword
  7976. *
  7977. * Ext.create('widget.window', { ... }); // Instead of new Ext.window.Window({...});
  7978. *
  7979. * Ext.create('Ext.window.Window', {}); // Same as above, using full class name instead of alias
  7980. *
  7981. * Ext.widget('window', {}); // Same as above, all you need is the traditional `xtype`
  7982. *
  7983. * Behind the scene, {@link Ext.ClassManager} will automatically check whether the given class name / alias has already
  7984. * existed on the page. If it's not, Ext.Loader will immediately switch itself to synchronous mode and automatic load the given
  7985. * class and all its dependencies.
  7986. *
  7987. * # Hybrid Loading - The Best of Both Worlds #
  7988. *
  7989. * It has all the advantages combined from asynchronous and synchronous loading. The development flow is simple:
  7990. *
  7991. * ### Step 1: Start writing your application using synchronous approach.
  7992. *
  7993. * Ext.Loader will automatically fetch all dependencies on demand as they're needed during run-time. For example:
  7994. *
  7995. * Ext.onReady(function(){
  7996. * var window = Ext.widget('window', {
  7997. * width: 500,
  7998. * height: 300,
  7999. * layout: {
  8000. * type: 'border',
  8001. * padding: 5
  8002. * },
  8003. * title: 'Hello Dialog',
  8004. * items: [{
  8005. * title: 'Navigation',
  8006. * collapsible: true,
  8007. * region: 'west',
  8008. * width: 200,
  8009. * html: 'Hello',
  8010. * split: true
  8011. * }, {
  8012. * title: 'TabPanel',
  8013. * region: 'center'
  8014. * }]
  8015. * });
  8016. *
  8017. * window.show();
  8018. * })
  8019. *
  8020. * ### Step 2: Along the way, when you need better debugging ability, watch the console for warnings like these: ###
  8021. *
  8022. * [Ext.Loader] Synchronously loading 'Ext.window.Window'; consider adding Ext.require('Ext.window.Window') before your application's code
  8023. * ClassManager.js:432
  8024. * [Ext.Loader] Synchronously loading 'Ext.layout.container.Border'; consider adding Ext.require('Ext.layout.container.Border') before your application's code
  8025. *
  8026. * Simply copy and paste the suggested code above `Ext.onReady`, i.e:
  8027. *
  8028. * Ext.require('Ext.window.Window');
  8029. * Ext.require('Ext.layout.container.Border');
  8030. *
  8031. * Ext.onReady(...);
  8032. *
  8033. * Everything should now load via asynchronous mode.
  8034. *
  8035. * # Deployment #
  8036. *
  8037. * It's important to note that dynamic loading should only be used during development on your local machines.
  8038. * During production, all dependencies should be combined into one single JavaScript file. Ext.Loader makes
  8039. * the whole process of transitioning from / to between development / maintenance and production as easy as
  8040. * possible. Internally {@link Ext.Loader#history Ext.Loader.history} maintains the list of all dependencies your application
  8041. * needs in the exact loading sequence. It's as simple as concatenating all files in this array into one,
  8042. * then include it on top of your application.
  8043. *
  8044. * This process will be automated with Sencha Command, to be released and documented towards Ext JS 4 Final.
  8045. *
  8046. * @singleton
  8047. */
  8048. Ext.Loader = new function() {
  8049. var Loader = this,
  8050. Manager = Ext.ClassManager,
  8051. Class = Ext.Class,
  8052. flexSetter = Ext.Function.flexSetter,
  8053. alias = Ext.Function.alias,
  8054. pass = Ext.Function.pass,
  8055. defer = Ext.Function.defer,
  8056. arrayErase = Ext.Array.erase,
  8057. dependencyProperties = ['extend', 'mixins', 'requires'],
  8058. isInHistory = {},
  8059. history = [],
  8060. slashDotSlashRe = /\/\.\//g,
  8061. dotRe = /\./g;
  8062. Ext.apply(Loader, {
  8063. /**
  8064. * @private
  8065. */
  8066. isInHistory: isInHistory,
  8067. /**
  8068. * An array of class names to keep track of the dependency loading order.
  8069. * This is not guaranteed to be the same everytime due to the asynchronous
  8070. * nature of the Loader.
  8071. *
  8072. * @property {Array} history
  8073. */
  8074. history: history,
  8075. /**
  8076. * Configuration
  8077. * @private
  8078. */
  8079. config: {
  8080. /**
  8081. * @cfg {Boolean} enabled
  8082. * Whether or not to enable the dynamic dependency loading feature.
  8083. */
  8084. enabled: false,
  8085. /**
  8086. * @cfg {Boolean} scriptChainDelay
  8087. * millisecond delay between asynchronous script injection (prevents stack overflow on some user agents)
  8088. * 'false' disables delay but potentially increases stack load.
  8089. */
  8090. scriptChainDelay : false,
  8091. /**
  8092. * @cfg {Boolean} disableCaching
  8093. * Appends current timestamp to script files to prevent caching.
  8094. */
  8095. disableCaching: true,
  8096. /**
  8097. * @cfg {String} disableCachingParam
  8098. * The get parameter name for the cache buster's timestamp.
  8099. */
  8100. disableCachingParam: '_dc',
  8101. /**
  8102. * @cfg {Boolean} garbageCollect
  8103. * True to prepare an asynchronous script tag for garbage collection (effective only
  8104. * if {@link #preserveScripts preserveScripts} is false)
  8105. */
  8106. garbageCollect : false,
  8107. /**
  8108. * @cfg {Object} paths
  8109. * The mapping from namespaces to file paths
  8110. *
  8111. * {
  8112. * 'Ext': '.', // This is set by default, Ext.layout.container.Container will be
  8113. * // loaded from ./layout/Container.js
  8114. *
  8115. * 'My': './src/my_own_folder' // My.layout.Container will be loaded from
  8116. * // ./src/my_own_folder/layout/Container.js
  8117. * }
  8118. *
  8119. * Note that all relative paths are relative to the current HTML document.
  8120. * If not being specified, for example, <code>Other.awesome.Class</code>
  8121. * will simply be loaded from <code>./Other/awesome/Class.js</code>
  8122. */
  8123. paths: {
  8124. 'Ext': '.'
  8125. },
  8126. /**
  8127. * @cfg {Boolean} preserveScripts
  8128. * False to remove and optionally {@link #garbageCollect garbage-collect} asynchronously loaded scripts,
  8129. * True to retain script element for browser debugger compatibility and improved load performance.
  8130. */
  8131. preserveScripts : true,
  8132. /**
  8133. * @cfg {String} scriptCharset
  8134. * Optional charset to specify encoding of dynamic script content.
  8135. */
  8136. scriptCharset : undefined
  8137. },
  8138. /**
  8139. * Set the configuration for the loader. This should be called right after ext-(debug).js
  8140. * is included in the page, and before Ext.onReady. i.e:
  8141. *
  8142. * <script type="text/javascript" src="ext-core-debug.js"></script>
  8143. * <script type="text/javascript">
  8144. * Ext.Loader.setConfig({
  8145. * enabled: true,
  8146. * paths: {
  8147. * 'My': 'my_own_path'
  8148. * }
  8149. * });
  8150. * </script>
  8151. * <script type="text/javascript">
  8152. * Ext.require(...);
  8153. *
  8154. * Ext.onReady(function() {
  8155. * // application code here
  8156. * });
  8157. * </script>
  8158. *
  8159. * Refer to config options of {@link Ext.Loader} for the list of possible properties
  8160. *
  8161. * @param {Object} config The config object to override the default values
  8162. * @return {Ext.Loader} this
  8163. */
  8164. setConfig: function(name, value) {
  8165. if (Ext.isObject(name) && arguments.length === 1) {
  8166. Ext.merge(Loader.config, name);
  8167. }
  8168. else {
  8169. Loader.config[name] = (Ext.isObject(value)) ? Ext.merge(Loader.config[name], value) : value;
  8170. }
  8171. return Loader;
  8172. },
  8173. /**
  8174. * Get the config value corresponding to the specified name. If no name is given, will return the config object
  8175. * @param {String} name The config property name
  8176. * @return {Object}
  8177. */
  8178. getConfig: function(name) {
  8179. if (name) {
  8180. return Loader.config[name];
  8181. }
  8182. return Loader.config;
  8183. },
  8184. /**
  8185. * Sets the path of a namespace.
  8186. * For Example:
  8187. *
  8188. * Ext.Loader.setPath('Ext', '.');
  8189. *
  8190. * @param {String/Object} name See {@link Ext.Function#flexSetter flexSetter}
  8191. * @param {String} path See {@link Ext.Function#flexSetter flexSetter}
  8192. * @return {Ext.Loader} this
  8193. * @method
  8194. */
  8195. setPath: flexSetter(function(name, path) {
  8196. Loader.config.paths[name] = path;
  8197. return Loader;
  8198. }),
  8199. /**
  8200. * Sets a batch of path entries
  8201. *
  8202. * @param {Object } paths a set of className: path mappings
  8203. * @return {Ext.Loader} this
  8204. */
  8205. addClassPathMappings: function(paths) {
  8206. var name;
  8207. for(name in paths){
  8208. Loader.config.paths[name] = paths[name];
  8209. }
  8210. return Loader;
  8211. },
  8212. /**
  8213. * Translates a className to a file path by adding the
  8214. * the proper prefix and converting the .'s to /'s. For example:
  8215. *
  8216. * Ext.Loader.setPath('My', '/path/to/My');
  8217. *
  8218. * alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/path/to/My/awesome/Class.js'
  8219. *
  8220. * Note that the deeper namespace levels, if explicitly set, are always resolved first. For example:
  8221. *
  8222. * Ext.Loader.setPath({
  8223. * 'My': '/path/to/lib',
  8224. * 'My.awesome': '/other/path/for/awesome/stuff',
  8225. * 'My.awesome.more': '/more/awesome/path'
  8226. * });
  8227. *
  8228. * alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/other/path/for/awesome/stuff/Class.js'
  8229. *
  8230. * alert(Ext.Loader.getPath('My.awesome.more.Class')); // alerts '/more/awesome/path/Class.js'
  8231. *
  8232. * alert(Ext.Loader.getPath('My.cool.Class')); // alerts '/path/to/lib/cool/Class.js'
  8233. *
  8234. * alert(Ext.Loader.getPath('Unknown.strange.Stuff')); // alerts 'Unknown/strange/Stuff.js'
  8235. *
  8236. * @param {String} className
  8237. * @return {String} path
  8238. */
  8239. getPath: function(className) {
  8240. var path = '',
  8241. paths = Loader.config.paths,
  8242. prefix = Loader.getPrefix(className);
  8243. if (prefix.length > 0) {
  8244. if (prefix === className) {
  8245. return paths[prefix];
  8246. }
  8247. path = paths[prefix];
  8248. className = className.substring(prefix.length + 1);
  8249. }
  8250. if (path.length > 0) {
  8251. path += '/';
  8252. }
  8253. return path.replace(slashDotSlashRe, '/') + className.replace(dotRe, "/") + '.js';
  8254. },
  8255. /**
  8256. * @private
  8257. * @param {String} className
  8258. */
  8259. getPrefix: function(className) {
  8260. var paths = Loader.config.paths,
  8261. prefix, deepestPrefix = '';
  8262. if (paths.hasOwnProperty(className)) {
  8263. return className;
  8264. }
  8265. for (prefix in paths) {
  8266. if (paths.hasOwnProperty(prefix) && prefix + '.' === className.substring(0, prefix.length + 1)) {
  8267. if (prefix.length > deepestPrefix.length) {
  8268. deepestPrefix = prefix;
  8269. }
  8270. }
  8271. }
  8272. return deepestPrefix;
  8273. },
  8274. /**
  8275. * @private
  8276. * @param {String} className
  8277. */
  8278. isAClassNameWithAKnownPrefix: function(className) {
  8279. var prefix = Loader.getPrefix(className);
  8280. // we can only say it's really a class if className is not equal to any known namespace
  8281. return prefix !== '' && prefix !== className;
  8282. },
  8283. /**
  8284. * Loads all classes by the given names and all their direct dependencies; optionally executes the given callback function when
  8285. * finishes, within the optional scope. This method is aliased by {@link Ext#require Ext.require} for convenience
  8286. * @param {String/Array} expressions Can either be a string or an array of string
  8287. * @param {Function} fn (Optional) The callback function
  8288. * @param {Object} scope (Optional) The execution scope (`this`) of the callback function
  8289. * @param {String/Array} excludes (Optional) Classes to be excluded, useful when being used with expressions
  8290. */
  8291. require: function(expressions, fn, scope, excludes) {
  8292. if (fn) {
  8293. fn.call(scope);
  8294. }
  8295. },
  8296. /**
  8297. * Synchronously loads all classes by the given names and all their direct dependencies; optionally executes the given callback function when finishes, within the optional scope. This method is aliased by {@link Ext#syncRequire} for convenience
  8298. * @param {String/Array} expressions Can either be a string or an array of string
  8299. * @param {Function} fn (Optional) The callback function
  8300. * @param {Object} scope (Optional) The execution scope (`this`) of the callback function
  8301. * @param {String/Array} excludes (Optional) Classes to be excluded, useful when being used with expressions
  8302. */
  8303. syncRequire: function() {},
  8304. /**
  8305. * Explicitly exclude files from being loaded. Useful when used in conjunction with a broad include expression.
  8306. * Can be chained with more `require` and `exclude` methods, eg:
  8307. *
  8308. * Ext.exclude('Ext.data.*').require('*');
  8309. *
  8310. * Ext.exclude('widget.button*').require('widget.*');
  8311. *
  8312. * @param {Array} excludes
  8313. * @return {Object} object contains `require` method for chaining
  8314. */
  8315. exclude: function(excludes) {
  8316. return {
  8317. require: function(expressions, fn, scope) {
  8318. return Loader.require(expressions, fn, scope, excludes);
  8319. },
  8320. syncRequire: function(expressions, fn, scope) {
  8321. return Loader.syncRequire(expressions, fn, scope, excludes);
  8322. }
  8323. };
  8324. },
  8325. /**
  8326. * Add a new listener to be executed when all required scripts are fully loaded
  8327. *
  8328. * @param {Function} fn The function callback to be executed
  8329. * @param {Object} scope The execution scope (<code>this</code>) of the callback function
  8330. * @param {Boolean} withDomReady Whether or not to wait for document dom ready as well
  8331. */
  8332. onReady: function(fn, scope, withDomReady, options) {
  8333. var oldFn;
  8334. if (withDomReady !== false && Ext.onDocumentReady) {
  8335. oldFn = fn;
  8336. fn = function() {
  8337. Ext.onDocumentReady(oldFn, scope, options);
  8338. };
  8339. }
  8340. fn.call(scope);
  8341. }
  8342. });
  8343. var queue = [],
  8344. isClassFileLoaded = {},
  8345. isFileLoaded = {},
  8346. classNameToFilePathMap = {},
  8347. scriptElements = {},
  8348. readyListeners = [],
  8349. usedClasses = [],
  8350. requiresMap = {};
  8351. Ext.apply(Loader, {
  8352. /**
  8353. * @private
  8354. */
  8355. documentHead: typeof document != 'undefined' && (document.head || document.getElementsByTagName('head')[0]),
  8356. /**
  8357. * Flag indicating whether there are still files being loaded
  8358. * @private
  8359. */
  8360. isLoading: false,
  8361. /**
  8362. * Maintain the queue for all dependencies. Each item in the array is an object of the format:
  8363. *
  8364. * {
  8365. * requires: [...], // The required classes for this queue item
  8366. * callback: function() { ... } // The function to execute when all classes specified in requires exist
  8367. * }
  8368. *
  8369. * @private
  8370. */
  8371. queue: queue,
  8372. /**
  8373. * Maintain the list of files that have already been handled so that they never get double-loaded
  8374. * @private
  8375. */
  8376. isClassFileLoaded: isClassFileLoaded,
  8377. /**
  8378. * @private
  8379. */
  8380. isFileLoaded: isFileLoaded,
  8381. /**
  8382. * Maintain the list of listeners to execute when all required scripts are fully loaded
  8383. * @private
  8384. */
  8385. readyListeners: readyListeners,
  8386. /**
  8387. * Contains classes referenced in `uses` properties.
  8388. * @private
  8389. */
  8390. optionalRequires: usedClasses,
  8391. /**
  8392. * Map of fully qualified class names to an array of dependent classes.
  8393. * @private
  8394. */
  8395. requiresMap: requiresMap,
  8396. /**
  8397. * @private
  8398. */
  8399. numPendingFiles: 0,
  8400. /**
  8401. * @private
  8402. */
  8403. numLoadedFiles: 0,
  8404. /** @private */
  8405. hasFileLoadError: false,
  8406. /**
  8407. * @private
  8408. */
  8409. classNameToFilePathMap: classNameToFilePathMap,
  8410. /**
  8411. * The number of scripts loading via loadScript.
  8412. * @private
  8413. */
  8414. scriptsLoading: 0,
  8415. /**
  8416. * @private
  8417. */
  8418. syncModeEnabled: false,
  8419. scriptElements: scriptElements,
  8420. /**
  8421. * Refresh all items in the queue. If all dependencies for an item exist during looping,
  8422. * it will execute the callback and call refreshQueue again. Triggers onReady when the queue is
  8423. * empty
  8424. * @private
  8425. */
  8426. refreshQueue: function() {
  8427. var ln = queue.length,
  8428. i, item, j, requires;
  8429. // When the queue of loading classes reaches zero, trigger readiness
  8430. if (!ln && !Loader.scriptsLoading) {
  8431. return Loader.triggerReady();
  8432. }
  8433. for (i = 0; i < ln; i++) {
  8434. item = queue[i];
  8435. if (item) {
  8436. requires = item.requires;
  8437. // Don't bother checking when the number of files loaded
  8438. // is still less than the array length
  8439. if (requires.length > Loader.numLoadedFiles) {
  8440. continue;
  8441. }
  8442. // Remove any required classes that are loaded
  8443. for (j = 0; j < requires.length; ) {
  8444. if (Manager.isCreated(requires[j])) {
  8445. // Take out from the queue
  8446. arrayErase(requires, j, 1);
  8447. }
  8448. else {
  8449. j++;
  8450. }
  8451. }
  8452. // If we've ended up with no required classes, call the callback
  8453. if (item.requires.length === 0) {
  8454. arrayErase(queue, i, 1);
  8455. item.callback.call(item.scope);
  8456. Loader.refreshQueue();
  8457. break;
  8458. }
  8459. }
  8460. }
  8461. return Loader;
  8462. },
  8463. /**
  8464. * Inject a script element to document's head, call onLoad and onError accordingly
  8465. * @private
  8466. */
  8467. injectScriptElement: function(url, onLoad, onError, scope, charset) {
  8468. var script = document.createElement('script'),
  8469. dispatched = false,
  8470. config = Loader.config,
  8471. onLoadFn = function() {
  8472. if(!dispatched) {
  8473. dispatched = true;
  8474. script.onload = script.onreadystatechange = script.onerror = null;
  8475. if (typeof config.scriptChainDelay == 'number') {
  8476. //free the stack (and defer the next script)
  8477. defer(onLoad, config.scriptChainDelay, scope);
  8478. } else {
  8479. onLoad.call(scope);
  8480. }
  8481. Loader.cleanupScriptElement(script, config.preserveScripts === false, config.garbageCollect);
  8482. }
  8483. },
  8484. onErrorFn = function(arg) {
  8485. defer(onError, 1, scope); //free the stack
  8486. Loader.cleanupScriptElement(script, config.preserveScripts === false, config.garbageCollect);
  8487. };
  8488. script.type = 'text/javascript';
  8489. script.onerror = onErrorFn;
  8490. charset = charset || config.scriptCharset;
  8491. if (charset) {
  8492. script.charset = charset;
  8493. }
  8494. /*
  8495. * IE9 Standards mode (and others) SHOULD follow the load event only
  8496. * (Note: IE9 supports both onload AND readystatechange events)
  8497. */
  8498. if ('addEventListener' in script ) {
  8499. script.onload = onLoadFn;
  8500. } else if ('readyState' in script) { // for <IE9 Compatability
  8501. script.onreadystatechange = function() {
  8502. if ( this.readyState == 'loaded' || this.readyState == 'complete' ) {
  8503. onLoadFn();
  8504. }
  8505. };
  8506. } else {
  8507. script.onload = onLoadFn;
  8508. }
  8509. script.src = url;
  8510. (Loader.documentHead || document.getElementsByTagName('head')[0]).appendChild(script);
  8511. return script;
  8512. },
  8513. /**
  8514. * @private
  8515. */
  8516. removeScriptElement: function(url) {
  8517. if (scriptElements[url]) {
  8518. Loader.cleanupScriptElement(scriptElements[url], true, !!Loader.getConfig('garbageCollect'));
  8519. delete scriptElements[url];
  8520. }
  8521. return Loader;
  8522. },
  8523. /**
  8524. * @private
  8525. */
  8526. cleanupScriptElement: function(script, remove, collect) {
  8527. var prop;
  8528. script.onload = script.onreadystatechange = script.onerror = null;
  8529. if (remove) {
  8530. Ext.removeNode(script); // Remove, since its useless now
  8531. if (collect) {
  8532. for (prop in script) {
  8533. try {
  8534. script[prop] = null;
  8535. delete script[prop]; // and prepare for GC
  8536. } catch (cleanEx) {
  8537. //ignore
  8538. }
  8539. }
  8540. }
  8541. }
  8542. return Loader;
  8543. },
  8544. /**
  8545. * Loads the specified script URL and calls the supplied callbacks. If this method
  8546. * is called before {@link Ext#isReady}, the script's load will delay the transition
  8547. * to ready. This can be used to load arbitrary scripts that may contain further
  8548. * {@link Ext#require Ext.require} calls.
  8549. *
  8550. * @param {Object/String} options The options object or simply the URL to load.
  8551. * @param {String} options.url The URL from which to load the script.
  8552. * @param {Function} [options.onLoad] The callback to call on successful load.
  8553. * @param {Function} [options.onError] The callback to call on failure to load.
  8554. * @param {Object} [options.scope] The scope (`this`) for the supplied callbacks.
  8555. */
  8556. loadScript: function (options) {
  8557. var config = Loader.getConfig(),
  8558. isString = typeof options == 'string',
  8559. url = isString ? options : options.url,
  8560. onError = !isString && options.onError,
  8561. onLoad = !isString && options.onLoad,
  8562. scope = !isString && options.scope,
  8563. onScriptError = function() {
  8564. Loader.numPendingFiles--;
  8565. Loader.scriptsLoading--;
  8566. if (onError) {
  8567. onError.call(scope, "Failed loading '" + url + "', please verify that the file exists");
  8568. }
  8569. if (Loader.numPendingFiles + Loader.scriptsLoading === 0) {
  8570. Loader.refreshQueue();
  8571. }
  8572. },
  8573. onScriptLoad = function () {
  8574. Loader.numPendingFiles--;
  8575. Loader.scriptsLoading--;
  8576. if (onLoad) {
  8577. onLoad.call(scope);
  8578. }
  8579. if (Loader.numPendingFiles + Loader.scriptsLoading === 0) {
  8580. Loader.refreshQueue();
  8581. }
  8582. },
  8583. src;
  8584. Loader.isLoading = true;
  8585. Loader.numPendingFiles++;
  8586. Loader.scriptsLoading++;
  8587. src = config.disableCaching ?
  8588. (url + '?' + config.disableCachingParam + '=' + Ext.Date.now()) : url;
  8589. scriptElements[url] = Loader.injectScriptElement(src, onScriptLoad, onScriptError);
  8590. },
  8591. /**
  8592. * Load a script file, supports both asynchronous and synchronous approaches
  8593. * @private
  8594. */
  8595. loadScriptFile: function(url, onLoad, onError, scope, synchronous) {
  8596. if (isFileLoaded[url]) {
  8597. return Loader;
  8598. }
  8599. var config = Loader.getConfig(),
  8600. noCacheUrl = url + (config.disableCaching ? ('?' + config.disableCachingParam + '=' + Ext.Date.now()) : ''),
  8601. isCrossOriginRestricted = false,
  8602. xhr, status, onScriptError,
  8603. debugSourceURL = "";
  8604. scope = scope || Loader;
  8605. Loader.isLoading = true;
  8606. if (!synchronous) {
  8607. onScriptError = function() {
  8608. onError.call(scope, "Failed loading '" + url + "', please verify that the file exists", synchronous);
  8609. };
  8610. scriptElements[url] = Loader.injectScriptElement(noCacheUrl, onLoad, onScriptError, scope);
  8611. } else {
  8612. if (typeof XMLHttpRequest != 'undefined') {
  8613. xhr = new XMLHttpRequest();
  8614. } else {
  8615. xhr = new ActiveXObject('Microsoft.XMLHTTP');
  8616. }
  8617. try {
  8618. xhr.open('GET', noCacheUrl, false);
  8619. xhr.send(null);
  8620. } catch (e) {
  8621. isCrossOriginRestricted = true;
  8622. }
  8623. status = (xhr.status === 1223) ? 204 :
  8624. (xhr.status === 0 && (self.location || {}).protocol == 'file:') ? 200 : xhr.status;
  8625. isCrossOriginRestricted = isCrossOriginRestricted || (status === 0);
  8626. if (isCrossOriginRestricted
  8627. ) {
  8628. onError.call(Loader, "Failed loading synchronously via XHR: '" + url + "'; It's likely that the file is either " +
  8629. "being loaded from a different domain or from the local file system whereby cross origin " +
  8630. "requests are not allowed due to security reasons. Use asynchronous loading with " +
  8631. "Ext.require instead.", synchronous);
  8632. }
  8633. else if ((status >= 200 && status < 300) || (status === 304)
  8634. ) {
  8635. // Debugger friendly, file names are still shown even though they're eval'ed code
  8636. // Breakpoints work on both Firebug and Chrome's Web Inspector
  8637. if (!Ext.isIE) {
  8638. debugSourceURL = "\n//@ sourceURL=" + url;
  8639. }
  8640. Ext.globalEval(xhr.responseText + debugSourceURL);
  8641. onLoad.call(scope);
  8642. }
  8643. else {
  8644. onError.call(Loader, "Failed loading synchronously via XHR: '" + url + "'; please " +
  8645. "verify that the file exists. " +
  8646. "XHR status code: " + status, synchronous);
  8647. }
  8648. // Prevent potential IE memory leak
  8649. xhr = null;
  8650. }
  8651. },
  8652. // documented above
  8653. syncRequire: function() {
  8654. var syncModeEnabled = Loader.syncModeEnabled;
  8655. if (!syncModeEnabled) {
  8656. Loader.syncModeEnabled = true;
  8657. }
  8658. Loader.require.apply(Loader, arguments);
  8659. if (!syncModeEnabled) {
  8660. Loader.syncModeEnabled = false;
  8661. }
  8662. Loader.refreshQueue();
  8663. },
  8664. // documented above
  8665. require: function(expressions, fn, scope, excludes) {
  8666. var excluded = {},
  8667. included = {},
  8668. excludedClassNames = [],
  8669. possibleClassNames = [],
  8670. classNames = [],
  8671. references = [],
  8672. callback,
  8673. syncModeEnabled,
  8674. filePath, expression, exclude, className,
  8675. possibleClassName, i, j, ln, subLn;
  8676. if (excludes) {
  8677. // Convert possible single string to an array.
  8678. excludes = (typeof excludes === 'string') ? [ excludes ] : excludes;
  8679. for (i = 0,ln = excludes.length; i < ln; i++) {
  8680. exclude = excludes[i];
  8681. if (typeof exclude == 'string' && exclude.length > 0) {
  8682. excludedClassNames = Manager.getNamesByExpression(exclude);
  8683. for (j = 0,subLn = excludedClassNames.length; j < subLn; j++) {
  8684. excluded[excludedClassNames[j]] = true;
  8685. }
  8686. }
  8687. }
  8688. }
  8689. // Convert possible single string to an array.
  8690. expressions = (typeof expressions === 'string') ? [ expressions ] : (expressions ? expressions : []);
  8691. if (fn) {
  8692. if (fn.length > 0) {
  8693. callback = function() {
  8694. var classes = [],
  8695. i, ln;
  8696. for (i = 0,ln = references.length; i < ln; i++) {
  8697. classes.push(Manager.get(references[i]));
  8698. }
  8699. return fn.apply(this, classes);
  8700. };
  8701. }
  8702. else {
  8703. callback = fn;
  8704. }
  8705. }
  8706. else {
  8707. callback = Ext.emptyFn;
  8708. }
  8709. scope = scope || Ext.global;
  8710. for (i = 0,ln = expressions.length; i < ln; i++) {
  8711. expression = expressions[i];
  8712. if (typeof expression == 'string' && expression.length > 0) {
  8713. possibleClassNames = Manager.getNamesByExpression(expression);
  8714. subLn = possibleClassNames.length;
  8715. for (j = 0; j < subLn; j++) {
  8716. possibleClassName = possibleClassNames[j];
  8717. if (excluded[possibleClassName] !== true) {
  8718. references.push(possibleClassName);
  8719. if (!Manager.isCreated(possibleClassName) && !included[possibleClassName]) {
  8720. included[possibleClassName] = true;
  8721. classNames.push(possibleClassName);
  8722. }
  8723. }
  8724. }
  8725. }
  8726. }
  8727. // If the dynamic dependency feature is not being used, throw an error
  8728. // if the dependencies are not defined
  8729. if (classNames.length > 0) {
  8730. if (!Loader.config.enabled) {
  8731. throw new Error("Ext.Loader is not enabled, so dependencies cannot be resolved dynamically. " +
  8732. "Missing required class" + ((classNames.length > 1) ? "es" : "") + ": " + classNames.join(', '));
  8733. }
  8734. }
  8735. else {
  8736. callback.call(scope);
  8737. return Loader;
  8738. }
  8739. syncModeEnabled = Loader.syncModeEnabled;
  8740. if (!syncModeEnabled) {
  8741. queue.push({
  8742. requires: classNames.slice(), // this array will be modified as the queue is processed,
  8743. // so we need a copy of it
  8744. callback: callback,
  8745. scope: scope
  8746. });
  8747. }
  8748. ln = classNames.length;
  8749. for (i = 0; i < ln; i++) {
  8750. className = classNames[i];
  8751. filePath = Loader.getPath(className);
  8752. // If we are synchronously loading a file that has already been asychronously loaded before
  8753. // we need to destroy the script tag and revert the count
  8754. // This file will then be forced loaded in synchronous
  8755. if (syncModeEnabled && isClassFileLoaded.hasOwnProperty(className)) {
  8756. Loader.numPendingFiles--;
  8757. Loader.removeScriptElement(filePath);
  8758. delete isClassFileLoaded[className];
  8759. }
  8760. if (!isClassFileLoaded.hasOwnProperty(className)) {
  8761. isClassFileLoaded[className] = false;
  8762. classNameToFilePathMap[className] = filePath;
  8763. Loader.numPendingFiles++;
  8764. Loader.loadScriptFile(
  8765. filePath,
  8766. pass(Loader.onFileLoaded, [className, filePath], Loader),
  8767. pass(Loader.onFileLoadError, [className, filePath], Loader),
  8768. Loader,
  8769. syncModeEnabled
  8770. );
  8771. }
  8772. }
  8773. if (syncModeEnabled) {
  8774. callback.call(scope);
  8775. if (ln === 1) {
  8776. return Manager.get(className);
  8777. }
  8778. }
  8779. return Loader;
  8780. },
  8781. /**
  8782. * @private
  8783. * @param {String} className
  8784. * @param {String} filePath
  8785. */
  8786. onFileLoaded: function(className, filePath) {
  8787. Loader.numLoadedFiles++;
  8788. isClassFileLoaded[className] = true;
  8789. isFileLoaded[filePath] = true;
  8790. Loader.numPendingFiles--;
  8791. if (Loader.numPendingFiles === 0) {
  8792. Loader.refreshQueue();
  8793. }
  8794. if (!Loader.syncModeEnabled && Loader.numPendingFiles === 0 && Loader.isLoading && !Loader.hasFileLoadError) {
  8795. var missingClasses = [],
  8796. missingPaths = [],
  8797. requires,
  8798. i, ln, j, subLn;
  8799. for (i = 0,ln = queue.length; i < ln; i++) {
  8800. requires = queue[i].requires;
  8801. for (j = 0,subLn = requires.length; j < subLn; j++) {
  8802. if (isClassFileLoaded[requires[j]]) {
  8803. missingClasses.push(requires[j]);
  8804. }
  8805. }
  8806. }
  8807. if (missingClasses.length < 1) {
  8808. return;
  8809. }
  8810. missingClasses = Ext.Array.filter(Ext.Array.unique(missingClasses), function(item) {
  8811. return !requiresMap.hasOwnProperty(item);
  8812. }, Loader);
  8813. for (i = 0,ln = missingClasses.length; i < ln; i++) {
  8814. missingPaths.push(classNameToFilePathMap[missingClasses[i]]);
  8815. }
  8816. throw new Error("The following classes are not declared even if their files have been " +
  8817. "loaded: '" + missingClasses.join("', '") + "'. Please check the source code of their " +
  8818. "corresponding files for possible typos: '" + missingPaths.join("', '"));
  8819. }
  8820. },
  8821. /**
  8822. * @private
  8823. */
  8824. onFileLoadError: function(className, filePath, errorMessage, isSynchronous) {
  8825. Loader.numPendingFiles--;
  8826. Loader.hasFileLoadError = true;
  8827. throw new Error("[Ext.Loader] " + errorMessage);
  8828. },
  8829. /**
  8830. * @private
  8831. * Ensure that any classes referenced in the `uses` property are loaded.
  8832. */
  8833. addUsedClasses: function (classes) {
  8834. var cls, i, ln;
  8835. if (classes) {
  8836. classes = (typeof classes == 'string') ? [classes] : classes;
  8837. for (i = 0, ln = classes.length; i < ln; i++) {
  8838. cls = classes[i];
  8839. if (typeof cls == 'string' && !Ext.Array.contains(usedClasses, cls)) {
  8840. usedClasses.push(cls);
  8841. }
  8842. }
  8843. }
  8844. return Loader;
  8845. },
  8846. /**
  8847. * @private
  8848. */
  8849. triggerReady: function() {
  8850. var listener,
  8851. i, refClasses = usedClasses;
  8852. if (Loader.isLoading) {
  8853. Loader.isLoading = false;
  8854. if (refClasses.length !== 0) {
  8855. // Clone then empty the array to eliminate potential recursive loop issue
  8856. refClasses = refClasses.slice();
  8857. usedClasses.length = 0;
  8858. // this may immediately call us back if all 'uses' classes
  8859. // have been loaded
  8860. Loader.require(refClasses, Loader.triggerReady, Loader);
  8861. return Loader;
  8862. }
  8863. }
  8864. // this method can be called with Loader.isLoading either true or false
  8865. // (can be called with false when all 'uses' classes are already loaded)
  8866. // this may bypass the above if condition
  8867. while (readyListeners.length && !Loader.isLoading) {
  8868. // calls to refreshQueue may re-enter triggerReady
  8869. // so we cannot necessarily iterate the readyListeners array
  8870. listener = readyListeners.shift();
  8871. listener.fn.call(listener.scope);
  8872. }
  8873. return Loader;
  8874. },
  8875. // Documented above already
  8876. onReady: function(fn, scope, withDomReady, options) {
  8877. var oldFn;
  8878. if (withDomReady !== false && Ext.onDocumentReady) {
  8879. oldFn = fn;
  8880. fn = function() {
  8881. Ext.onDocumentReady(oldFn, scope, options);
  8882. };
  8883. }
  8884. if (!Loader.isLoading) {
  8885. fn.call(scope);
  8886. }
  8887. else {
  8888. readyListeners.push({
  8889. fn: fn,
  8890. scope: scope
  8891. });
  8892. }
  8893. },
  8894. /**
  8895. * @private
  8896. * @param {String} className
  8897. */
  8898. historyPush: function(className) {
  8899. if (className && isClassFileLoaded.hasOwnProperty(className) && !isInHistory[className]) {
  8900. isInHistory[className] = true;
  8901. history.push(className);
  8902. }
  8903. return Loader;
  8904. }
  8905. });
  8906. /**
  8907. * Turns on or off the "cache buster" applied to dynamically loaded scripts. Normally
  8908. * dynamically loaded scripts have an extra query parameter appended to avoid stale
  8909. * cached scripts. This method can be used to disable this mechanism, and is primarily
  8910. * useful for testing. This is done using a cookie.
  8911. * @param {Boolean} disable True to disable the cache buster.
  8912. * @param {String} [path="/"] An optional path to scope the cookie.
  8913. * @private
  8914. */
  8915. Ext.disableCacheBuster = function (disable, path) {
  8916. var date = new Date();
  8917. date.setTime(date.getTime() + (disable ? 10*365 : -1) * 24*60*60*1000);
  8918. date = date.toGMTString();
  8919. document.cookie = 'ext-cache=1; expires=' + date + '; path='+(path || '/');
  8920. };
  8921. /**
  8922. * Convenient alias of {@link Ext.Loader#require}. Please see the introduction documentation of
  8923. * {@link Ext.Loader} for examples.
  8924. * @member Ext
  8925. * @method require
  8926. */
  8927. Ext.require = alias(Loader, 'require');
  8928. /**
  8929. * Synchronous version of {@link Ext#require}, convenient alias of {@link Ext.Loader#syncRequire}.
  8930. *
  8931. * @member Ext
  8932. * @method syncRequire
  8933. */
  8934. Ext.syncRequire = alias(Loader, 'syncRequire');
  8935. /**
  8936. * Convenient shortcut to {@link Ext.Loader#exclude}
  8937. * @member Ext
  8938. * @method exclude
  8939. */
  8940. Ext.exclude = alias(Loader, 'exclude');
  8941. /**
  8942. * @member Ext
  8943. * @method onReady
  8944. * @ignore
  8945. */
  8946. Ext.onReady = function(fn, scope, options) {
  8947. Loader.onReady(fn, scope, true, options);
  8948. };
  8949. /**
  8950. * @cfg {String[]} requires
  8951. * @member Ext.Class
  8952. * List of classes that have to be loaded before instantiating this class.
  8953. * For example:
  8954. *
  8955. * Ext.define('Mother', {
  8956. * requires: ['Child'],
  8957. * giveBirth: function() {
  8958. * // we can be sure that child class is available.
  8959. * return new Child();
  8960. * }
  8961. * });
  8962. */
  8963. Class.registerPreprocessor('loader', function(cls, data, hooks, continueFn) {
  8964. var me = this,
  8965. dependencies = [],
  8966. dependency,
  8967. className = Manager.getName(cls),
  8968. i, j, ln, subLn, value, propertyName, propertyValue,
  8969. requiredMap, requiredDep;
  8970. /*
  8971. Loop through the dependencyProperties, look for string class names and push
  8972. them into a stack, regardless of whether the property's value is a string, array or object. For example:
  8973. {
  8974. extend: 'Ext.MyClass',
  8975. requires: ['Ext.some.OtherClass'],
  8976. mixins: {
  8977. observable: 'Ext.util.Observable';
  8978. }
  8979. }
  8980. which will later be transformed into:
  8981. {
  8982. extend: Ext.MyClass,
  8983. requires: [Ext.some.OtherClass],
  8984. mixins: {
  8985. observable: Ext.util.Observable;
  8986. }
  8987. }
  8988. */
  8989. for (i = 0,ln = dependencyProperties.length; i < ln; i++) {
  8990. propertyName = dependencyProperties[i];
  8991. if (data.hasOwnProperty(propertyName)) {
  8992. propertyValue = data[propertyName];
  8993. if (typeof propertyValue == 'string') {
  8994. dependencies.push(propertyValue);
  8995. }
  8996. else if (propertyValue instanceof Array) {
  8997. for (j = 0, subLn = propertyValue.length; j < subLn; j++) {
  8998. value = propertyValue[j];
  8999. if (typeof value == 'string') {
  9000. dependencies.push(value);
  9001. }
  9002. }
  9003. }
  9004. else if (typeof propertyValue != 'function') {
  9005. for (j in propertyValue) {
  9006. if (propertyValue.hasOwnProperty(j)) {
  9007. value = propertyValue[j];
  9008. if (typeof value == 'string') {
  9009. dependencies.push(value);
  9010. }
  9011. }
  9012. }
  9013. }
  9014. }
  9015. }
  9016. if (dependencies.length === 0) {
  9017. return;
  9018. }
  9019. var deadlockPath = [],
  9020. detectDeadlock;
  9021. /*
  9022. Automatically detect deadlocks before-hand,
  9023. will throw an error with detailed path for ease of debugging. Examples of deadlock cases:
  9024. - A extends B, then B extends A
  9025. - A requires B, B requires C, then C requires A
  9026. The detectDeadlock function will recursively transverse till the leaf, hence it can detect deadlocks
  9027. no matter how deep the path is.
  9028. */
  9029. if (className) {
  9030. requiresMap[className] = dependencies;
  9031. requiredMap = Loader.requiredByMap || (Loader.requiredByMap = {});
  9032. for (i = 0,ln = dependencies.length; i < ln; i++) {
  9033. dependency = dependencies[i];
  9034. (requiredMap[dependency] || (requiredMap[dependency] = [])).push(className);
  9035. }
  9036. detectDeadlock = function(cls) {
  9037. deadlockPath.push(cls);
  9038. if (requiresMap[cls]) {
  9039. if (Ext.Array.contains(requiresMap[cls], className)) {
  9040. throw new Error("Deadlock detected while loading dependencies! '" + className + "' and '" +
  9041. deadlockPath[1] + "' " + "mutually require each other. Path: " +
  9042. deadlockPath.join(' -> ') + " -> " + deadlockPath[0]);
  9043. }
  9044. for (i = 0,ln = requiresMap[cls].length; i < ln; i++) {
  9045. detectDeadlock(requiresMap[cls][i]);
  9046. }
  9047. }
  9048. };
  9049. detectDeadlock(className);
  9050. }
  9051. Loader.require(dependencies, function() {
  9052. for (i = 0,ln = dependencyProperties.length; i < ln; i++) {
  9053. propertyName = dependencyProperties[i];
  9054. if (data.hasOwnProperty(propertyName)) {
  9055. propertyValue = data[propertyName];
  9056. if (typeof propertyValue == 'string') {
  9057. data[propertyName] = Manager.get(propertyValue);
  9058. }
  9059. else if (propertyValue instanceof Array) {
  9060. for (j = 0, subLn = propertyValue.length; j < subLn; j++) {
  9061. value = propertyValue[j];
  9062. if (typeof value == 'string') {
  9063. data[propertyName][j] = Manager.get(value);
  9064. }
  9065. }
  9066. }
  9067. else if (typeof propertyValue != 'function') {
  9068. for (var k in propertyValue) {
  9069. if (propertyValue.hasOwnProperty(k)) {
  9070. value = propertyValue[k];
  9071. if (typeof value == 'string') {
  9072. data[propertyName][k] = Manager.get(value);
  9073. }
  9074. }
  9075. }
  9076. }
  9077. }
  9078. }
  9079. continueFn.call(me, cls, data, hooks);
  9080. });
  9081. return false;
  9082. }, true, 'after', 'className');
  9083. /**
  9084. * @cfg {String[]} uses
  9085. * @member Ext.Class
  9086. * List of optional classes to load together with this class. These aren't neccessarily loaded before
  9087. * this class is created, but are guaranteed to be available before Ext.onReady listeners are
  9088. * invoked. For example:
  9089. *
  9090. * Ext.define('Mother', {
  9091. * uses: ['Child'],
  9092. * giveBirth: function() {
  9093. * // This code might, or might not work:
  9094. * // return new Child();
  9095. *
  9096. * // Instead use Ext.create() to load the class at the spot if not loaded already:
  9097. * return Ext.create('Child');
  9098. * }
  9099. * });
  9100. */
  9101. Manager.registerPostprocessor('uses', function(name, cls, data) {
  9102. var uses = data.uses;
  9103. if (uses) {
  9104. Loader.addUsedClasses(uses);
  9105. }
  9106. });
  9107. Manager.onCreated(Loader.historyPush);
  9108. };
  9109. // simple mechanism for automated means of injecting large amounts of dependency info
  9110. // at the appropriate time in the load cycle
  9111. if (Ext._classPathMetadata) {
  9112. Ext.Loader.addClassPathMappings(Ext._classPathMetadata);
  9113. Ext._classPathMetadata = null;
  9114. }
  9115. // initalize the default path of the framework
  9116. (function() {
  9117. var scripts = document.getElementsByTagName('script'),
  9118. currentScript = scripts[scripts.length - 1],
  9119. src = currentScript.src,
  9120. path = src.substring(0, src.lastIndexOf('/') + 1),
  9121. Loader = Ext.Loader;
  9122. if(src.indexOf("/platform/core/src/class/") != -1) {
  9123. path = path + "../../../../extjs/";
  9124. } else if(src.indexOf("/core/src/class/") != -1) {
  9125. path = path + "../../../";
  9126. }
  9127. Loader.setConfig({
  9128. enabled: true,
  9129. disableCaching: true,
  9130. paths: {
  9131. 'Ext': path + 'src'
  9132. }
  9133. });
  9134. })();
  9135. // allows a tools like dynatrace to deterministically detect onReady state by invoking
  9136. // a callback (intended for external consumption)
  9137. Ext._endTime = new Date().getTime();
  9138. if (Ext._beforereadyhandler){
  9139. Ext._beforereadyhandler();
  9140. }
  9141. //@tag foundation,core
  9142. //@require ../class/Loader.js
  9143. /**
  9144. * @author Brian Moeskau <brian@sencha.com>
  9145. * @docauthor Brian Moeskau <brian@sencha.com>
  9146. *
  9147. * A wrapper class for the native JavaScript Error object that adds a few useful capabilities for handling
  9148. * errors in an Ext application. When you use Ext.Error to {@link #raise} an error from within any class that
  9149. * uses the Ext 4 class system, the Error class can automatically add the source class and method from which
  9150. * the error was raised. It also includes logic to automatically log the eroor to the console, if available,
  9151. * with additional metadata about the error. In all cases, the error will always be thrown at the end so that
  9152. * execution will halt.
  9153. *
  9154. * Ext.Error also offers a global error {@link #handle handling} method that can be overridden in order to
  9155. * handle application-wide errors in a single spot. You can optionally {@link #ignore} errors altogether,
  9156. * although in a real application it's usually a better idea to override the handling function and perform
  9157. * logging or some other method of reporting the errors in a way that is meaningful to the application.
  9158. *
  9159. * At its simplest you can simply raise an error as a simple string from within any code:
  9160. *
  9161. * Example usage:
  9162. *
  9163. * Ext.Error.raise('Something bad happened!');
  9164. *
  9165. * If raised from plain JavaScript code, the error will be logged to the console (if available) and the message
  9166. * displayed. In most cases however you'll be raising errors from within a class, and it may often be useful to add
  9167. * additional metadata about the error being raised. The {@link #raise} method can also take a config object.
  9168. * In this form the `msg` attribute becomes the error description, and any other data added to the config gets
  9169. * added to the error object and, if the console is available, logged to the console for inspection.
  9170. *
  9171. * Example usage:
  9172. *
  9173. * Ext.define('Ext.Foo', {
  9174. * doSomething: function(option){
  9175. * if (someCondition === false) {
  9176. * Ext.Error.raise({
  9177. * msg: 'You cannot do that!',
  9178. * option: option, // whatever was passed into the method
  9179. * 'error code': 100 // other arbitrary info
  9180. * });
  9181. * }
  9182. * }
  9183. * });
  9184. *
  9185. * If a console is available (that supports the `console.dir` function) you'll see console output like:
  9186. *
  9187. * An error was raised with the following data:
  9188. * option: Object { foo: "bar"}
  9189. * foo: "bar"
  9190. * error code: 100
  9191. * msg: "You cannot do that!"
  9192. * sourceClass: "Ext.Foo"
  9193. * sourceMethod: "doSomething"
  9194. *
  9195. * uncaught exception: You cannot do that!
  9196. *
  9197. * As you can see, the error will report exactly where it was raised and will include as much information as the
  9198. * raising code can usefully provide.
  9199. *
  9200. * If you want to handle all application errors globally you can simply override the static {@link #handle} method
  9201. * and provide whatever handling logic you need. If the method returns true then the error is considered handled
  9202. * and will not be thrown to the browser. If anything but true is returned then the error will be thrown normally.
  9203. *
  9204. * Example usage:
  9205. *
  9206. * Ext.Error.handle = function(err) {
  9207. * if (err.someProperty == 'NotReallyAnError') {
  9208. * // maybe log something to the application here if applicable
  9209. * return true;
  9210. * }
  9211. * // any non-true return value (including none) will cause the error to be thrown
  9212. * }
  9213. *
  9214. */
  9215. Ext.Error = Ext.extend(Error, {
  9216. statics: {
  9217. /**
  9218. * @property {Boolean} ignore
  9219. * Static flag that can be used to globally disable error reporting to the browser if set to true
  9220. * (defaults to false). Note that if you ignore Ext errors it's likely that some other code may fail
  9221. * and throw a native JavaScript error thereafter, so use with caution. In most cases it will probably
  9222. * be preferable to supply a custom error {@link #handle handling} function instead.
  9223. *
  9224. * Example usage:
  9225. *
  9226. * Ext.Error.ignore = true;
  9227. *
  9228. * @static
  9229. */
  9230. ignore: false,
  9231. /**
  9232. * @property {Boolean} notify
  9233. * Static flag that can be used to globally control error notification to the user. Unlike
  9234. * Ex.Error.ignore, this does not effect exceptions. They are still thrown. This value can be
  9235. * set to false to disable the alert notification (default is true for IE6 and IE7).
  9236. *
  9237. * Only the first error will generate an alert. Internally this flag is set to false when the
  9238. * first error occurs prior to displaying the alert.
  9239. *
  9240. * This flag is not used in a release build.
  9241. *
  9242. * Example usage:
  9243. *
  9244. * Ext.Error.notify = false;
  9245. *
  9246. * @static
  9247. */
  9248. //notify: Ext.isIE6 || Ext.isIE7,
  9249. /**
  9250. * Raise an error that can include additional data and supports automatic console logging if available.
  9251. * You can pass a string error message or an object with the `msg` attribute which will be used as the
  9252. * error message. The object can contain any other name-value attributes (or objects) to be logged
  9253. * along with the error.
  9254. *
  9255. * Note that after displaying the error message a JavaScript error will ultimately be thrown so that
  9256. * execution will halt.
  9257. *
  9258. * Example usage:
  9259. *
  9260. * Ext.Error.raise('A simple string error message');
  9261. *
  9262. * // or...
  9263. *
  9264. * Ext.define('Ext.Foo', {
  9265. * doSomething: function(option){
  9266. * if (someCondition === false) {
  9267. * Ext.Error.raise({
  9268. * msg: 'You cannot do that!',
  9269. * option: option, // whatever was passed into the method
  9270. * 'error code': 100 // other arbitrary info
  9271. * });
  9272. * }
  9273. * }
  9274. * });
  9275. *
  9276. * @param {String/Object} err The error message string, or an object containing the attribute "msg" that will be
  9277. * used as the error message. Any other data included in the object will also be logged to the browser console,
  9278. * if available.
  9279. * @static
  9280. */
  9281. raise: function(err){
  9282. err = err || {};
  9283. if (Ext.isString(err)) {
  9284. err = { msg: err };
  9285. }
  9286. var method = this.raise.caller,
  9287. msg;
  9288. if (method) {
  9289. if (method.$name) {
  9290. err.sourceMethod = method.$name;
  9291. }
  9292. if (method.$owner) {
  9293. err.sourceClass = method.$owner.$className;
  9294. }
  9295. }
  9296. if (Ext.Error.handle(err) !== true) {
  9297. msg = Ext.Error.prototype.toString.call(err);
  9298. Ext.log({
  9299. msg: msg,
  9300. level: 'error',
  9301. dump: err,
  9302. stack: true
  9303. });
  9304. throw new Ext.Error(err);
  9305. }
  9306. },
  9307. /**
  9308. * Globally handle any Ext errors that may be raised, optionally providing custom logic to
  9309. * handle different errors individually. Return true from the function to bypass throwing the
  9310. * error to the browser, otherwise the error will be thrown and execution will halt.
  9311. *
  9312. * Example usage:
  9313. *
  9314. * Ext.Error.handle = function(err) {
  9315. * if (err.someProperty == 'NotReallyAnError') {
  9316. * // maybe log something to the application here if applicable
  9317. * return true;
  9318. * }
  9319. * // any non-true return value (including none) will cause the error to be thrown
  9320. * }
  9321. *
  9322. * @param {Ext.Error} err The Ext.Error object being raised. It will contain any attributes that were originally
  9323. * raised with it, plus properties about the method and class from which the error originated (if raised from a
  9324. * class that uses the Ext 4 class system).
  9325. * @static
  9326. */
  9327. handle: function(){
  9328. return Ext.Error.ignore;
  9329. }
  9330. },
  9331. // This is the standard property that is the name of the constructor.
  9332. name: 'Ext.Error',
  9333. /**
  9334. * Creates new Error object.
  9335. * @param {String/Object} config The error message string, or an object containing the
  9336. * attribute "msg" that will be used as the error message. Any other data included in
  9337. * the object will be applied to the error instance and logged to the browser console, if available.
  9338. */
  9339. constructor: function(config){
  9340. if (Ext.isString(config)) {
  9341. config = { msg: config };
  9342. }
  9343. var me = this;
  9344. Ext.apply(me, config);
  9345. me.message = me.message || me.msg; // 'message' is standard ('msg' is non-standard)
  9346. // note: the above does not work in old WebKit (me.message is readonly) (Safari 4)
  9347. },
  9348. /**
  9349. * Provides a custom string representation of the error object. This is an override of the base JavaScript
  9350. * `Object.toString` method, which is useful so that when logged to the browser console, an error object will
  9351. * be displayed with a useful message instead of `[object Object]`, the default `toString` result.
  9352. *
  9353. * The default implementation will include the error message along with the raising class and method, if available,
  9354. * but this can be overridden with a custom implementation either at the prototype level (for all errors) or on
  9355. * a particular error instance, if you want to provide a custom description that will show up in the console.
  9356. * @return {String} The error message. If raised from within the Ext 4 class system, the error message will also
  9357. * include the raising class and method names, if available.
  9358. */
  9359. toString: function(){
  9360. var me = this,
  9361. className = me.sourceClass ? me.sourceClass : '',
  9362. methodName = me.sourceMethod ? '.' + me.sourceMethod + '(): ' : '',
  9363. msg = me.msg || '(No description provided)';
  9364. return className + methodName + msg;
  9365. }
  9366. });
  9367. /*
  9368. * Create a function that will throw an error if called (in debug mode) with a message that
  9369. * indicates the method has been removed.
  9370. * @param {String} suggestion Optional text to include in the message (a workaround perhaps).
  9371. * @return {Function} The generated function.
  9372. * @private
  9373. */
  9374. Ext.deprecated = function (suggestion) {
  9375. if (!suggestion) {
  9376. suggestion = '';
  9377. }
  9378. function fail () {
  9379. Ext.Error.raise('The method "' + fail.$owner.$className + '.' + fail.$name +
  9380. '" has been removed. ' + suggestion);
  9381. }
  9382. return fail;
  9383. return Ext.emptyFn;
  9384. };
  9385. /*
  9386. * This mechanism is used to notify the user of the first error encountered on the page. This
  9387. * was previously internal to Ext.Error.raise and is a desirable feature since errors often
  9388. * slip silently under the radar. It cannot live in Ext.Error.raise since there are times
  9389. * where exceptions are handled in a try/catch.
  9390. */
  9391. (function () {
  9392. var timer, errors = 0,
  9393. win = Ext.global,
  9394. msg;
  9395. if (typeof window === 'undefined') {
  9396. return; // build system or some such environment...
  9397. }
  9398. // This method is called to notify the user of the current error status.
  9399. function notify () {
  9400. var counters = Ext.log.counters,
  9401. supports = Ext.supports,
  9402. hasOnError = supports && supports.WindowOnError; // TODO - timing
  9403. // Put log counters to the status bar (for most browsers):
  9404. if (counters && (counters.error + counters.warn + counters.info + counters.log)) {
  9405. msg = [ 'Logged Errors:',counters.error, 'Warnings:',counters.warn,
  9406. 'Info:',counters.info, 'Log:',counters.log].join(' ');
  9407. if (errors) {
  9408. msg = '*** Errors: ' + errors + ' - ' + msg;
  9409. } else if (counters.error) {
  9410. msg = '*** ' + msg;
  9411. }
  9412. win.status = msg;
  9413. }
  9414. // Display an alert on the first error:
  9415. if (!Ext.isDefined(Ext.Error.notify)) {
  9416. Ext.Error.notify = Ext.isIE6 || Ext.isIE7; // TODO - timing
  9417. }
  9418. if (Ext.Error.notify && (hasOnError ? errors : (counters && counters.error))) {
  9419. Ext.Error.notify = false;
  9420. if (timer) {
  9421. win.clearInterval(timer); // ticks can queue up so stop...
  9422. timer = null;
  9423. }
  9424. alert('Unhandled error on page: See console or log');
  9425. poll();
  9426. }
  9427. }
  9428. // Sets up polling loop. This is the only way to know about errors in some browsers
  9429. // (Opera/Safari) and is the only way to update the status bar for warnings and other
  9430. // non-errors.
  9431. function poll () {
  9432. timer = win.setInterval(notify, 1000);
  9433. }
  9434. // window.onerror sounds ideal but it prevents the built-in error dialog from doing
  9435. // its (better) thing.
  9436. poll();
  9437. }());