You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

GQuery.java 158KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019
  1. /*
  2. * Copyright 2011, The gwtquery team.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
  5. * in compliance with the License. You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software distributed under the License
  10. * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
  11. * or implied. See the License for the specific language governing permissions and limitations under
  12. * the License.
  13. */
  14. package com.google.gwt.query.client;
  15. import static com.google.gwt.query.client.plugins.QueuePlugin.Queue;
  16. import com.google.gwt.core.client.GWT;
  17. import com.google.gwt.core.client.JavaScriptObject;
  18. import com.google.gwt.core.client.JsArray;
  19. import com.google.gwt.core.client.JsArrayMixed;
  20. import com.google.gwt.core.client.JsArrayString;
  21. import com.google.gwt.core.client.ScriptInjector;
  22. import com.google.gwt.dom.client.BodyElement;
  23. import com.google.gwt.dom.client.ButtonElement;
  24. import com.google.gwt.dom.client.Document;
  25. import com.google.gwt.dom.client.Element;
  26. import com.google.gwt.dom.client.InputElement;
  27. import com.google.gwt.dom.client.NativeEvent;
  28. import com.google.gwt.dom.client.Node;
  29. import com.google.gwt.dom.client.NodeList;
  30. import com.google.gwt.dom.client.OptionElement;
  31. import com.google.gwt.dom.client.SelectElement;
  32. import com.google.gwt.dom.client.Style.Display;
  33. import com.google.gwt.dom.client.Style.HasCssName;
  34. import com.google.gwt.dom.client.TextAreaElement;
  35. import com.google.gwt.query.client.css.CSS;
  36. import com.google.gwt.query.client.css.HasCssValue;
  37. import com.google.gwt.query.client.css.TakesCssValue;
  38. import com.google.gwt.query.client.css.TakesCssValue.CssSetter;
  39. import com.google.gwt.query.client.impl.AttributeImpl;
  40. import com.google.gwt.query.client.impl.DocumentStyleImpl;
  41. import com.google.gwt.query.client.impl.SelectorEngine;
  42. import com.google.gwt.query.client.js.JsCache;
  43. import com.google.gwt.query.client.js.JsMap;
  44. import com.google.gwt.query.client.js.JsNamedArray;
  45. import com.google.gwt.query.client.js.JsNodeArray;
  46. import com.google.gwt.query.client.js.JsObjectArray;
  47. import com.google.gwt.query.client.js.JsUtils;
  48. import com.google.gwt.query.client.plugins.Effects;
  49. import com.google.gwt.query.client.plugins.Events;
  50. import com.google.gwt.query.client.plugins.Plugin;
  51. import com.google.gwt.query.client.plugins.Widgets;
  52. import com.google.gwt.query.client.plugins.ajax.Ajax;
  53. import com.google.gwt.query.client.plugins.ajax.Ajax.Settings;
  54. import com.google.gwt.query.client.plugins.deferred.Deferred;
  55. import com.google.gwt.query.client.plugins.effects.PropertiesAnimation.Easing;
  56. import com.google.gwt.query.client.plugins.events.EventsListener;
  57. import com.google.gwt.query.client.plugins.widgets.WidgetsUtils;
  58. import com.google.gwt.regexp.shared.MatchResult;
  59. import com.google.gwt.regexp.shared.RegExp;
  60. import com.google.gwt.user.client.DOM;
  61. import com.google.gwt.user.client.Event;
  62. import com.google.gwt.user.client.EventListener;
  63. import com.google.gwt.user.client.Window;
  64. import com.google.gwt.user.client.ui.IsWidget;
  65. import com.google.gwt.user.client.ui.Widget;
  66. import java.util.ArrayList;
  67. import java.util.Arrays;
  68. import java.util.List;
  69. import java.util.Map;
  70. /**
  71. * GwtQuery is a GWT clone of the popular jQuery library.
  72. */
  73. public class GQuery implements Lazy<GQuery, LazyGQuery> {
  74. private enum DomMan {
  75. AFTER, APPEND, BEFORE, PREPEND;
  76. }
  77. /**
  78. * A POJO used to store the top/left CSS positioning values of an element.
  79. */
  80. public static class Offset {
  81. public int left;
  82. public int top;
  83. public Offset(int left, int top) {
  84. this.left = left;
  85. this.top = top;
  86. }
  87. public Offset add(int left, int top) {
  88. return new Offset(this.left + left, this.top + top);
  89. }
  90. public String toString() {
  91. return top + "+" + left;
  92. }
  93. }
  94. /**
  95. * Class used internally to create DOM element from html snippet
  96. */
  97. private static class TagWrapper {
  98. public static final TagWrapper DEFAULT = new TagWrapper(0, "", "");
  99. private String postWrap;
  100. private String preWrap;
  101. private int wrapDepth;
  102. public TagWrapper(int wrapDepth, String preWrap, String postWrap) {
  103. this.wrapDepth = wrapDepth;
  104. this.postWrap = postWrap;
  105. this.preWrap = preWrap;
  106. }
  107. }
  108. /**
  109. * Implementation class to modify attributes.
  110. */
  111. protected static AttributeImpl attributeImpl;
  112. /**
  113. * The body element in the current page.
  114. */
  115. public static final BodyElement body = GWT.isClient() ? Document.get().getBody() : null;
  116. /**
  117. * A Browser object with a set of browser-specific flags.
  118. */
  119. public static final Browser browser = GWT.isClient() ? GWT.<Browser>create(Browser.class) : null;
  120. /**
  121. * An object with the same methods than window.console.
  122. */
  123. public static final Console console = GWT.isClient() ? GWT.<Console>create(Console.class) : null;
  124. /**
  125. * Object to store element data (public so as we can access to it from tests).
  126. */
  127. public static JsCache dataCache = null;
  128. /**
  129. * The document element in the current page.
  130. */
  131. public static final Document document = GWT.isClient() ? Document.get() : null;
  132. /**
  133. * Static reference Effects plugin
  134. */
  135. public static Class<Effects> Effects = com.google.gwt.query.client.plugins.Effects.Effects;
  136. /**
  137. * Implementation engine used for CSS selectors.
  138. */
  139. protected static SelectorEngine engine;
  140. /**
  141. * Static reference Events plugin
  142. */
  143. public static Class<Events> Events = com.google.gwt.query.client.plugins.Events.Events;
  144. /**
  145. * A static reference to the GQuery class.
  146. */
  147. public static Class<GQuery> GQUERY = GQuery.class;
  148. private static final String OLD_DATA_PREFIX = "old-";
  149. private static final String OLD_DISPLAY = OLD_DATA_PREFIX + "display";
  150. private static JsMap<Class<? extends GQuery>, Plugin<? extends GQuery>> plugins;
  151. // Sizzle POS regex : usefull in some methods
  152. // TODO: Share this static with SelectorEngineSizzle
  153. private static RegExp posRegex = RegExp.compile("^:(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\))?(?=[^\\-]|$)$");
  154. /**
  155. * Implementation class used for style manipulations.
  156. */
  157. private static DocumentStyleImpl styleImpl;
  158. private static RegExp tagNameRegex = RegExp.compile("<([\\w:-]+)");
  159. /**
  160. * Static reference to the Widgets plugin
  161. */
  162. public static Class<Widgets> Widgets = com.google.gwt.query.client.plugins.Widgets.Widgets;
  163. /**
  164. * The window object.
  165. */
  166. public static final Element window = GWT.isClient() ? ScriptInjector.TOP_WINDOW.<Element>cast() : null;
  167. private static Element windowData = null;
  168. private static JsNamedArray<TagWrapper> wrapperMap;
  169. /**
  170. * Create an empty GQuery object.
  171. */
  172. public static GQuery $() {
  173. return new GQuery(JsNodeArray.create());
  174. }
  175. /**
  176. * Wrap a GQuery around an existing element.
  177. */
  178. public static GQuery $(Element element) {
  179. return new GQuery(element);
  180. }
  181. /**
  182. * Wrap a GQuery around an event's target element.
  183. */
  184. public static GQuery $(Event event) {
  185. return event == null ? $() : $((Element) event.getCurrentEventTarget().cast());
  186. }
  187. /**
  188. * Wrap a GQuery around the element of a Function callback.
  189. */
  190. public static GQuery $(Function f) {
  191. return $(f.getElement());
  192. }
  193. /**
  194. * Wrap a GQuery around an existing javascript element, event, node, nodelist, function or array.
  195. */
  196. public static GQuery $(JavaScriptObject jso) {
  197. if (jso == null) {
  198. return $();
  199. }
  200. // Execute a native javascript function like jquery does
  201. if (JsUtils.isFunction(jso)) {
  202. new JsUtils.JsFunction(jso).fe();
  203. return $();
  204. }
  205. // Wraps a native array like jquery does
  206. if (!JsUtils.isWindow(jso) && !JsUtils.isElement(jso) && JsUtils.isArray(jso)) {
  207. JsArrayMixed c = jso.cast();
  208. JsNodeArray elms = JsNodeArray.create();
  209. for (int i = 0; i < c.length(); i++) {
  210. Object obj = c.getObject(i);
  211. if (obj instanceof Node) {
  212. elms.addNode((Node) obj);
  213. }
  214. }
  215. return $(elms);
  216. }
  217. return JsUtils.isWindow(jso) ? $(jso.<Element> cast()) :
  218. JsUtils.isElement(jso) ? $(jso.<Element> cast()) :
  219. JsUtils.isEvent(jso) ? $(jso.<Event> cast()) :
  220. JsUtils.isNodeList(jso) ? $(jso.<NodeList<Element>> cast()) :
  221. $(jso.<Element> cast());
  222. }
  223. /**
  224. * Wrap a GQuery around any object, supported objects are:
  225. * String, GQuery, Function, Widget, JavaScriptObject
  226. *
  227. * In the case of string, we accept a CSS selector which is then used to match a set of
  228. * elements, or a raw HTML to create a GQuery element containing those elements. Xpath
  229. * selector is supported in browsers with native xpath engine.
  230. *
  231. * In the case of a JavaScriptObject we handle:
  232. * Element, Event, Node, Nodelist and native functions or arrays.
  233. *
  234. * If the case of a native function, we execute it and return empty.
  235. */
  236. public static GQuery $(Object o) {
  237. if (o != null) {
  238. if (o instanceof String) {
  239. return $((String)o);
  240. }
  241. if (o instanceof GQuery) {
  242. return (GQuery)o;
  243. }
  244. if (o instanceof Function) {
  245. return $((Function)o);
  246. }
  247. if (JsUtils.isElement(o)) {
  248. return $(JsUtils.<Element>cast(o));
  249. }
  250. if (o instanceof JavaScriptObject) {
  251. return $((JavaScriptObject)o);
  252. }
  253. if (o instanceof IsWidget) {
  254. return $(Arrays.asList(o));
  255. }
  256. console.log("Error: GQuery.$(Object o) could not wrap the type : ", o.getClass().getName(), o);
  257. }
  258. return $();
  259. }
  260. /**
  261. * Create a new GQuery given a list of {@link com.google.gwt.dom.client.Node} or
  262. * {@link com.google.gwt.user.client.ui.IsWidget}
  263. */
  264. public static GQuery $(List<?> nodesOrWidgets) {
  265. JsNodeArray elms = JsNodeArray.create();
  266. if (nodesOrWidgets != null) {
  267. for (Object o : nodesOrWidgets) {
  268. if (o instanceof Node) {
  269. elms.addNode((Node) o);
  270. } else if (o instanceof IsWidget) {
  271. elms.addNode(((IsWidget)o).asWidget().getElement());
  272. }
  273. }
  274. }
  275. return new GQuery(elms);
  276. }
  277. /**
  278. * Wrap a GQuery around an existing node.
  279. */
  280. public static GQuery $(Node n) {
  281. return $((Element) n);
  282. }
  283. /**
  284. * Wrap a GQuery around existing Elements.
  285. */
  286. public static GQuery $(NodeList<Element> elms) {
  287. return new GQuery(elms);
  288. }
  289. /**
  290. * This function accepts a string containing a CSS selector which is then used to match a set of
  291. * elements, or it accepts raw HTML creating a GQuery element containing those elements. Xpath
  292. * selector is supported in browsers with native xpath engine.
  293. */
  294. public static GQuery $(String selectorOrHtml) {
  295. return $(selectorOrHtml, document);
  296. }
  297. /**
  298. * This function accepts a string containing a CSS selector which is then used to match a set of
  299. * elements, or it accepts raw HTML creating a GQuery element containing those elements. The
  300. * second parameter is is a class reference to a plugin to be used.
  301. *
  302. * Xpath selector is supported in browsers with native xpath engine.
  303. */
  304. public static <T extends GQuery> T $(String selector, Class<T> plugin) {
  305. return $(selector, document, plugin);
  306. }
  307. /**
  308. * This function accepts a string containing a CSS selector which is then used to match a set of
  309. * elements, or it accepts raw HTML creating a GQuery element containing those elements. The
  310. * second parameter is the context to use for the selector, or the document where the new elements
  311. * will be created.
  312. *
  313. * Xpath selector is supported in browsers with native xpath engine.
  314. */
  315. public static GQuery $(String selectorOrHtml, Node ctx) {
  316. String selector = null;
  317. if (selectorOrHtml == null || (selector = selectorOrHtml.trim()).length() == 0) {
  318. return $();
  319. }
  320. if (selector.startsWith("<")) {
  321. return innerHtml(selectorOrHtml, JsUtils.getOwnerDocument(ctx));
  322. }
  323. return new GQuery().select(selectorOrHtml, ctx);
  324. }
  325. /**
  326. * This function accepts a string containing a CSS selector which is then used to match a set of
  327. * elements, or it accepts raw HTML creating a GQuery element containing those elements. The
  328. * second parameter is the context to use for the selector. The third parameter is the class
  329. * plugin to use.
  330. *
  331. * Xpath selector is supported in browsers with native xpath engine.
  332. */
  333. @SuppressWarnings("unchecked")
  334. public static <T extends GQuery> T $(String selector, Node context, Class<T> plugin) {
  335. try {
  336. if (plugins != null) {
  337. T gquery = (T) plugins.get(plugin).init(new GQuery().select(selector, context));
  338. return gquery;
  339. }
  340. throw new RuntimeException("No plugin for class " + plugin);
  341. } catch (Exception e) {
  342. throw new RuntimeException(e);
  343. }
  344. }
  345. /**
  346. * This function accepts a string containing a CSS selector which is then used to match a set of
  347. * elements, or it accepts raw HTML creating a GQuery element containing those elements. The
  348. * second parameter is the context to use for the selector, or the document where the new elements
  349. * will be created.
  350. *
  351. * Xpath selector is supported in browsers with native xpath engine.
  352. */
  353. public static GQuery $(String selectorOrHtml, Widget context) {
  354. return $(selectorOrHtml, context.getElement());
  355. }
  356. /**
  357. * This function accepts a string containing a CSS selector which is then used to match a set of
  358. * elements, or it accepts raw HTML creating a GQuery element containing those elements. The
  359. * second parameter is the context to use for the selector. The third parameter is the class
  360. * plugin to use.
  361. *
  362. * Xpath selector is supported in browsers with native xpath engine.
  363. */
  364. public static <T extends GQuery> T $(String selector, Widget context, Class<T> plugin) {
  365. return $(selector, context.getElement(), plugin);
  366. }
  367. /**
  368. * Wrap a GQuery around one widget or an array of existing ones.
  369. */
  370. public static GQuery $(Widget... widgets) {
  371. return $(Arrays.asList(widgets));
  372. }
  373. /**
  374. * Wrap a GQuery around one node or an array of existing ones.
  375. */
  376. public static GQuery $(Node... nodes) {
  377. return $(Arrays.asList(nodes));
  378. }
  379. /**
  380. * Create an empty JSON object.
  381. */
  382. public static Properties $$() {
  383. return $$(null);
  384. }
  385. /**
  386. * Wrap a JSON object.
  387. */
  388. public static Properties $$(String properties) {
  389. return Properties.create(properties);
  390. }
  391. /**
  392. * Perform an ajax request to the server.
  393. */
  394. public static Promise ajax(Properties p) {
  395. return Ajax.ajax(p);
  396. }
  397. /**
  398. * Perform an ajax request to the server.
  399. */
  400. public static Promise ajax(Settings settings) {
  401. return Ajax.ajax(settings);
  402. }
  403. /**
  404. * Perform an ajax request to the server.
  405. */
  406. public static Promise ajax(String url, Settings settings) {
  407. return Ajax.ajax(url, settings);
  408. }
  409. protected static GQuery cleanHtmlString(String elem, Document doc) {
  410. MatchResult mResult = tagNameRegex.exec(elem);
  411. if (mResult == null) {
  412. return $(doc.createTextNode(elem));
  413. }
  414. String tag = mResult.getGroup(1);
  415. if (wrapperMap == null) {
  416. initWrapperMap();
  417. }
  418. TagWrapper wrapper = wrapperMap.get(tag.toLowerCase());
  419. if (wrapper == null) {
  420. wrapper = TagWrapper.DEFAULT;
  421. }
  422. // TODO: fix IE link tag serialization
  423. // TODO: fix IE <script> tag
  424. // TODO: add fixes for IE TBODY issue
  425. // We use a temporary element to wrap the elements
  426. Element div = doc.createDivElement();
  427. div.setInnerHTML(wrapper.preWrap + elem.trim() + wrapper.postWrap);
  428. Node n = div;
  429. int depth = wrapper.wrapDepth;
  430. while (depth-- != 0) {
  431. n = n.getLastChild();
  432. }
  433. return
  434. // return all nodes added to the wrapper
  435. $(n.getChildNodes())
  436. // detach nodes from their temporary parent
  437. .remove(null, false);
  438. }
  439. /**
  440. * Return true if the element b is contained in a.
  441. */
  442. public static boolean contains(Element a, Element b) {
  443. return getSelectorEngine().contains(a, b);
  444. }
  445. /**
  446. * Get the element data matching the key.
  447. */
  448. public static <T> T data(Element e, String key) {
  449. return data(e, key, null);
  450. }
  451. /**
  452. * Store arbitrary data associated with the specified element.
  453. *
  454. * We store this data in a global js object having the structure:
  455. * datacache [element.hashCode()] [key] = value
  456. *
  457. * @return the value stored in the element with the given name
  458. */
  459. public static <T> T data(Element element, String key, T value) {
  460. return data(element, key, value, null);
  461. }
  462. private static <T> T data(Element element, String key, T value, Class<? extends T> clz) {
  463. if (dataCache == null) {
  464. windowData = JavaScriptObject.createObject().cast();
  465. dataCache = JavaScriptObject.createObject().cast();
  466. }
  467. element = element == window || element.getNodeName() == null ? windowData : element;
  468. if (element != null && key != null) {
  469. int id = element.hashCode();
  470. if (value == null) {
  471. return dataCache.exists(id) ? dataCache.getCache(id).get(key, clz) : null;
  472. }
  473. if (!dataCache.exists(id)) {
  474. dataCache.put(id, JsCache.createObject().cast());
  475. }
  476. dataCache.getCache(id).put(key, value);
  477. }
  478. return value;
  479. }
  480. /**
  481. * Execute a function around each object
  482. */
  483. public static void each(JsArrayMixed objects, Function f) {
  484. for (int i = 0, l = objects.length(); i < l; i++) {
  485. f.f(i, objects.getObject(i));
  486. }
  487. }
  488. /**
  489. * Execute a function around each object
  490. */
  491. public static <T> void each(List<T> objects, Function f) {
  492. for (int i = 0, l = objects.size(); i < l; i++) {
  493. f.f(i, objects.get(i));
  494. }
  495. }
  496. /**
  497. * Execute a function around each object
  498. */
  499. public static <T> void each(T[] objects, Function f) {
  500. for (int i = 0, l = objects.length; i < l; i++) {
  501. f.f(i, objects[i]);
  502. }
  503. }
  504. /**
  505. * Perform an ajax request to the server using GET.
  506. */
  507. public static Promise get(String url, Properties data, final Function onSuccess) {
  508. return Ajax.get(url, data, onSuccess);
  509. }
  510. /**
  511. * We will use the fact as GWT use the widget itself as EventListener ! If no Widget associated
  512. * with the element, this method returns null.
  513. */
  514. protected static Widget getAssociatedWidget(Element e) {
  515. try {
  516. EventListener listener = DOM.getEventListener((com.google.gwt.user.client.Element) e);
  517. // No listener attached to the element, so no widget exist for this element
  518. if (listener == null) {
  519. return null;
  520. }
  521. if (listener instanceof Widget) {
  522. // GWT uses the widget as event listener
  523. return (Widget) listener;
  524. } else if (listener instanceof EventsListener) {
  525. // GQuery replaces the gwt event listener and save it
  526. EventsListener gQueryListener = (EventsListener) listener;
  527. if (gQueryListener.getOriginalEventListener() != null
  528. && gQueryListener.getOriginalEventListener() instanceof Widget) {
  529. return (Widget) gQueryListener.getOriginalEventListener();
  530. }
  531. }
  532. } catch (Exception e2) {
  533. // Some times this code could raise an exception.
  534. // We do not want GQuery to fail, but in dev-mode we log the error.
  535. e2.printStackTrace();
  536. }
  537. return null;
  538. }
  539. private static AttributeImpl getAttributeImpl() {
  540. if (attributeImpl == null) {
  541. attributeImpl = GWT.create(AttributeImpl.class);
  542. }
  543. return attributeImpl;
  544. }
  545. /**
  546. * Perform an ajax request to the server using POST and parsing the json response.
  547. */
  548. public static Promise getJSON(String url, Properties data, final Function onSuccess) {
  549. return Ajax.getJSON(url, data, onSuccess);
  550. }
  551. /**
  552. * Perform an ajax request to the server using scripts tags and parsing the json response. The
  553. * request is not subject to the same origin policy restrictions.
  554. *
  555. * Server side should accept a parameter to specify the callback funcion name, and it must return
  556. * a valid json object wrapped this callback function.
  557. *
  558. * Example:
  559. *
  560. * <pre>
  561. Client code:
  562. getJSONP("http://server.exampe.com/getData.php",$$("myCallback:'?', otherParameter='whatever'"),
  563. new Function(){ public void f() {
  564. Properties p = getDataProperties();
  565. alert(p.getStr("k1");
  566. }});
  567. Server response:
  568. myCallback({"k1":"v1", "k2":"v2"});
  569. </pre>
  570. *
  571. */
  572. public static Promise getJSONP(String url, Properties data, final Function onSuccess) {
  573. return Ajax.getJSONP(url, data, onSuccess);
  574. }
  575. protected static DocumentStyleImpl getStyleImpl() {
  576. if (styleImpl == null) {
  577. styleImpl = getSelectorEngine().getDocumentStyleImpl();
  578. }
  579. return styleImpl;
  580. }
  581. /**
  582. * Return only the set of objects with match the predicate.
  583. */
  584. @SuppressWarnings("unchecked")
  585. public static <T> T[] grep(T[] objects, Predicate f) {
  586. ArrayList<Object> ret = new ArrayList<Object>();
  587. for (int i = 0, l = objects.length; i < l; i++) {
  588. if (f.f(objects[i], i)) {
  589. ret.add(objects[i]);
  590. }
  591. }
  592. return (T[]) ret.toArray(new Object[0]);
  593. }
  594. private static boolean hasClass(Element e, String clz) {
  595. return e.getClassName().matches("(^|.*\\s)" + clz + "(\\s.*|$)");
  596. }
  597. private static void initWrapperMap() {
  598. TagWrapper tableWrapper = new TagWrapper(1, "<table>", "</table>");
  599. TagWrapper selectWrapper = new TagWrapper(1, "<select multiple=\"multiple\">", "</select>");
  600. TagWrapper trWrapper = new TagWrapper(3, "<table><tbody><tr>", "</tr></tbody></table>");
  601. wrapperMap = JsNamedArray.create();
  602. wrapperMap.put("option", selectWrapper);
  603. wrapperMap.put("optgroup", selectWrapper);
  604. wrapperMap.put("legend", new TagWrapper(1, "<fieldset>", "</fieldset>"));
  605. wrapperMap.put("thead", tableWrapper);
  606. wrapperMap.put("tbody", tableWrapper);
  607. wrapperMap.put("tfoot", tableWrapper);
  608. wrapperMap.put("colgroup", tableWrapper);
  609. wrapperMap.put("caption", tableWrapper);
  610. wrapperMap.put("tr", new TagWrapper(2, "<table><tbody>", "</tbody></table>"));
  611. wrapperMap.put("td", trWrapper);
  612. wrapperMap.put("th", trWrapper);
  613. wrapperMap.put("col", new TagWrapper(2, "<table><tbody></tbody><colgroup>",
  614. "</colgroup></table>"));
  615. wrapperMap.put("area", new TagWrapper(1, "<map>", "</map>"));
  616. }
  617. private static GQuery innerHtml(String html, Document doc) {
  618. return cleanHtmlString(html, doc);
  619. }
  620. protected static String[] jsArrayToString(JsArrayString array) {
  621. if (GWT.isScript()) {
  622. return JsUtils.castArrayString(array);
  623. } else {
  624. String result[] = new String[array.length()];
  625. for (int i = 0, l = result.length; i < l; i++) {
  626. result[i] = array.get(i);
  627. }
  628. return result;
  629. }
  630. }
  631. /**
  632. * Return a lazy version of the GQuery interface. Lazy function calls are simply queued up and not
  633. * executed immediately.
  634. */
  635. public static LazyGQuery<?> lazy() {
  636. return $().createLazy();
  637. }
  638. /**
  639. * Perform an ajax request to the server using POST.
  640. */
  641. public static Promise post(String url, Properties data, final Function onSuccess) {
  642. return Ajax.post(url, data, onSuccess);
  643. }
  644. public static <T extends GQuery> Class<T> registerPlugin(Class<T> plugin, Plugin<T> pluginFactory) {
  645. // TODO: decide whether change plugins type to java.util.list
  646. // Right now we only test static methods in gquery, so this is only needed when initializing
  647. // plugins shortcuts in gquery.
  648. if (GWT.isClient()) {
  649. if (plugins == null) {
  650. plugins = JsMap.createObject().cast();
  651. }
  652. plugins.put(plugin, pluginFactory);
  653. }
  654. return plugin;
  655. }
  656. /**
  657. * Provides a way to execute callback Functions based on one or more objects
  658. * that represent asynchronous events.
  659. *
  660. * Arguments can be of any Object, but normally you would pass Promises.
  661. * In the case you provide a GQuery object it will call the promise() method to return
  662. * a Promise which will be executed when the queue is resolved.
  663. * In the case you provide a normal Object, it will return a promise which will be immediately
  664. * resolved with the object as argument.
  665. * In the case you provide a Function it will executed and if the f(Object...) method returns
  666. * a new promise it will be used, otherwise we will use the returned object like in the last case.
  667. *
  668. * It Returns a new promise which will be finalized when all of its subordinates finish.
  669. * In the case of all subordinates are resolved correctly the promise will be resolved
  670. * otherwise it will be rejected.
  671. */
  672. public static Promise when(Object... subordinates) {
  673. return Deferred.when(subordinates);
  674. }
  675. /**
  676. * A constructor function that returns a chainable utility object with methods to register
  677. * multiple callbacks into callback queues, invoke callback queues, and relay the success
  678. * or failure state of any synchronous or asynchronous function
  679. */
  680. public static Promise.Deferred Deferred() {
  681. return new Deferred();
  682. }
  683. public static SelectorEngine getSelectorEngine() {
  684. if (engine == null) {
  685. engine = GWT.create(SelectorEngine.class);
  686. }
  687. return engine;
  688. }
  689. private static native void scrollIntoViewImpl(Node n) /*-{
  690. if (n)
  691. n.scrollIntoView()
  692. }-*/;
  693. private static native void setElementValue(Element e, String value) /*-{
  694. e.value = value;
  695. }-*/;
  696. protected Node currentContext;
  697. protected String currentSelector;
  698. /**
  699. * Immutable array of matched elements, modify this using setArray
  700. */
  701. private Element[] elements = new Element[0];
  702. /**
  703. * The nodeList of matched elements, modify this using setArray
  704. */
  705. // TODO: remove this and use elements, change return type of get()
  706. private NodeList<Element> nodeList = JavaScriptObject.createArray().cast();
  707. private GQuery previousObject;
  708. private GQuery() {
  709. }
  710. private GQuery(Element element) {
  711. this(JsNodeArray.create(element));
  712. }
  713. protected GQuery(GQuery gq) {
  714. if (gq != null) {
  715. elements = gq.elements;
  716. nodeList = gq.nodeList;
  717. currentSelector = gq.currentSelector;
  718. currentContext = gq.currentContext;
  719. }
  720. }
  721. private GQuery(JsNodeArray nodes) {
  722. this(nodes.<NodeList<Element>> cast());
  723. }
  724. private GQuery(NodeList<Element> list) {
  725. setArray(list);
  726. }
  727. /**
  728. * Add elements to the set of matched elements if they are not included yet.
  729. *
  730. * It construct a new GQuery object and does not modify the original ones.
  731. *
  732. * It also update the selector appending the new one.
  733. */
  734. public GQuery add(GQuery elementsToAdd) {
  735. return pushStack(JsUtils.copyNodeList(nodeList, elementsToAdd.nodeList, true)
  736. .<JsNodeArray> cast(), "add", join(",", getSelector(), elementsToAdd.getSelector()));
  737. }
  738. /**
  739. * Add elements to the set of matched elements if they are not included yet.
  740. */
  741. public GQuery add(String selector) {
  742. return add($(selector));
  743. }
  744. /**
  745. * Add the previous selection to the current selection. Useful for traversing elements, and then
  746. * adding something that was matched before the last traversal.
  747. */
  748. public GQuery addBack() {
  749. return previousObject != null ? add(previousObject) : this;
  750. }
  751. /**
  752. * Adds the specified classes to each matched element.
  753. */
  754. public GQuery addClass(String... classes) {
  755. for (Element e : elements) {
  756. // issue 81 : ensure that the element is an Element node.
  757. if (Element.is(e)) {
  758. for (String clz : classes) {
  759. e.addClassName(clz);
  760. }
  761. }
  762. }
  763. return this;
  764. }
  765. /**
  766. * Insert content after each of the matched elements. The elements must already be inserted into
  767. * the document (you can't insert an element after another if it's not in the page).
  768. */
  769. public GQuery after(GQuery query) {
  770. return domManip(query, DomMan.AFTER);
  771. }
  772. /**
  773. * Insert content after each of the matched elements. The elements must already be inserted into
  774. * the document (you can't insert an element after another if it's not in the page).
  775. */
  776. public GQuery after(Node n) {
  777. return domManip($(n), DomMan.AFTER);
  778. }
  779. /**
  780. * Insert content after each of the matched elements. The elements must already be inserted into
  781. * the document (you can't insert an element after another if it's not in the page).
  782. */
  783. public GQuery after(String html) {
  784. return domManip(html, DomMan.AFTER);
  785. }
  786. private void allNextSiblingElements(Element firstChildElement, JsNodeArray result, Element elem,
  787. GQuery until, String filterSelector) {
  788. while (firstChildElement != null) {
  789. if (until != null && until.index(firstChildElement) != -1) {
  790. return;
  791. }
  792. if (firstChildElement != elem
  793. && (filterSelector == null || $(firstChildElement).is(filterSelector))) {
  794. result.addNode(firstChildElement);
  795. }
  796. firstChildElement = firstChildElement.getNextSiblingElement();
  797. }
  798. }
  799. private void allPreviousSiblingElements(Element firstChildElement, JsNodeArray result,
  800. GQuery until, String filterSelector) {
  801. while (firstChildElement != null) {
  802. if (until != null && until.index(firstChildElement) != -1) {
  803. return;
  804. }
  805. if (filterSelector == null || $(firstChildElement).is(filterSelector)) {
  806. result.addNode(firstChildElement);
  807. }
  808. firstChildElement = getPreviousSiblingElement(firstChildElement);
  809. }
  810. }
  811. /**
  812. * Add the previous selection to the current selection. Useful for traversing elements, and then
  813. * adding something that was matched before the last traversal.
  814. * @deprecated use addBack() instead
  815. */
  816. @Deprecated
  817. public GQuery andSelf() {
  818. return addBack();
  819. }
  820. /**
  821. *
  822. * The animate() method allows you to create animation effects on any numeric HTML Attribute,
  823. * CSS property, or color CSS property.
  824. *
  825. * Concerning to numeric properties, values are treated as a number of pixels unless otherwise
  826. * specified. The units em and % can be specified where applicable.
  827. *
  828. * By default animate considers css properties, if you wanted to animate element attributes you
  829. * should to prepend the symbol dollar to the attribute name. It's useful to animate svg elements.
  830. *
  831. * NOTE: The ability of animating attribute values is only available in gquery but not jquery
  832. *
  833. *
  834. * Example:
  835. *
  836. * <pre class="code">
  837. * //move the element from its original position to left:500px
  838. * $("#foo").animate("left:'500'");
  839. *
  840. * // Change the width html attribute of a table, note the symbol '$' to
  841. * // tell gquery which it is an html-attribute instead of a css-property.
  842. * $("table").animate("$width:'500'");
  843. * </pre>
  844. *
  845. * In addition to numeric values, each property can take the strings 'show', 'hide', and 'toggle'.
  846. * These shortcuts allow for custom hiding and showing animations that take into account the
  847. * display type of the element. Animated properties can also be relative. If a value is supplied
  848. * with a leading += or -= sequence of characters, then the target value is computed by adding or
  849. * subtracting the given number from the current value of the property.
  850. *
  851. * Example:
  852. *
  853. * <pre class="code">
  854. * //move the element from its original position to 500px to the left for 500ms and
  855. * // change the background color of the element at the end of the animation
  856. *
  857. * $("#foo").animate("left:'+=500'", new Function(){
  858. * public void f(Element e){
  859. * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED);
  860. * }
  861. * });
  862. * </pre>
  863. *
  864. * The default duration of the animation is 500ms.
  865. *
  866. * For color css properties, values can be specified via hexadecimal or rgb or literal values.
  867. *
  868. * Example:
  869. *
  870. * <pre class="code">
  871. * $("#foo").animate("backgroundColor:'red', color:'#ffffff', borderColor:'rgb(129, 0, 70)'");
  872. * </pre>
  873. *
  874. * @param stringOrProperties the property to animate : "cssName:'value'"
  875. * @param funcs an array of {@link Function} called once the animation is complete
  876. */
  877. public GQuery animate(Object stringOrProperties, Function... funcs) {
  878. return as(Effects).animate(stringOrProperties, funcs);
  879. }
  880. /**
  881. *
  882. * The animate() method allows you to create animation effects on any numeric HTML Attribute,
  883. * CSS property, or color CSS property.
  884. *
  885. * Concerning to numeric properties, values are treated as a number of pixels unless otherwise
  886. * specified. The units em and % can be specified where applicable.
  887. *
  888. * By default animate considers css properties, if you wanted to animate element attributes you
  889. * should to prepend the symbol dollar to the attribute name. It's useful to animate svg elements.
  890. *
  891. * NOTE: The ability of animating attribute values is only available in gquery but not jquery
  892. *
  893. *
  894. * Example:
  895. *
  896. * <pre class="code">
  897. * //move the element from its original position to left:500px for 500ms using a swing easing
  898. * $("#foo").animate("left:'500'", 500, Easing.SWING);
  899. *
  900. * // Change the width html attribute of a table, note the symbol '$' to
  901. * // tell gquery which it is an html-attribute instead of a css-property.
  902. * // the animation will last 400ms, and we use the LINEAR easing algorithm
  903. * $("table").animate(Properties.create("{$width: '500', $border: '10'}"), 400, Easing.LINEAR);
  904. * </pre>
  905. *
  906. * In addition to numeric values, each property can take the strings 'show', 'hide', and 'toggle'.
  907. * These shortcuts allow for custom hiding and showing animations that take into account the
  908. * display type of the element. Animated properties can also be relative. If a value is supplied
  909. * with a leading += or -= sequence of characters, then the target value is computed by adding or
  910. * subtracting the given number from the current value of the property.
  911. *
  912. * Example:
  913. *
  914. * <pre class="code">
  915. * //move the element from its original position to 500px to the left and 5OOpx down for 400ms.
  916. * //use a swing easing function for the transition
  917. * $("#foo").animate(Properties.create("{top:'+=500px',left:'+=500px'}"), 400, Easing.SWING);
  918. * </pre>
  919. *
  920. * For color css properties, values can be specified via hexadecimal or rgb or literal values.
  921. *
  922. * Example:
  923. *
  924. * <pre class="code">
  925. * $("#foo").animate("backgroundColor:'red', color:'#ffffff', borderColor:'rgb(129, 0, 70)'"), 400, Easing.SWING);
  926. * </pre>
  927. *
  928. * @param stringOrProperties a String or a {@link Properties} object containing css properties to
  929. * animate.
  930. * @param funcs an array of {@link Function} called once the animation is complete
  931. * @param duration the duration in milliseconds of the animation
  932. * @param easing the easing function to use for the transition
  933. */
  934. public GQuery animate(Object stringOrProperties, int duration, Easing easing, Function... funcs) {
  935. return as(Effects).animate(stringOrProperties, duration, easing, funcs);
  936. }
  937. /**
  938. * The animate() method allows you to create animation effects on any numeric HTML Attribute,
  939. * CSS property, or color CSS property.
  940. *
  941. * Concerning to numeric properties, values are treated as a number of pixels unless otherwise
  942. * specified. The units em and % can be specified where applicable.
  943. *
  944. * By default animate considers css properties, if you wanted to animate element attributes you
  945. * should to prepend the symbol dollar to the attribute name. It's useful to animate svg elements.
  946. *
  947. * NOTE: The ability of animating attribute values is only available in gquery but not jquery
  948. *
  949. *
  950. * Example:
  951. *
  952. * <pre class="code">
  953. * //move the element from its original position to left:500px for 500ms
  954. * $("#foo").animate("left:'500'", 500);
  955. *
  956. * // Change the width html attribute of a table, note the symbol '$' to
  957. * // tell gquery which it is an html-attribute instead of a css-property.
  958. * // the animation will last 400ms
  959. * $("table").animate("$width:'500'"), 400);
  960. * </pre>
  961. *
  962. * In addition to numeric values, each property can take the strings 'show', 'hide', and 'toggle'.
  963. * These shortcuts allow for custom hiding and showing animations that take into account the
  964. * display type of the element. Animated properties can also be relative. If a value is supplied
  965. * with a leading += or -= sequence of characters, then the target value is computed by adding or
  966. * subtracting the given number from the current value of the property.
  967. *
  968. * Example:
  969. *
  970. * <pre class="code">
  971. * //move the element from its original position to 500px to the left for 1000ms and
  972. * // change the background color of the element at the end of the animation
  973. * $("#foo").animate("left:'+=500'", 1000, new Function(){
  974. * public void f(Element e){
  975. * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED);
  976. * }
  977. * });
  978. * </pre>
  979. *
  980. *
  981. * For color css properties, values can be specified via hexadecimal or rgb or literal values.
  982. *
  983. * Example:
  984. *
  985. * <pre class="code">
  986. * $("#foo").animate("backgroundColor:'red', color:'#ffffff', borderColor:'rgb(129, 0, 70)', 1000");
  987. * </pre>
  988. *
  989. *
  990. * @param prop the property to animate : "cssName:'value'"
  991. * @param funcs an array of {@link Function} called once the animation is complete
  992. * @param duration the duration in milliseconds of the animation
  993. */
  994. public GQuery animate(Object stringOrProperties, int duration, Function... funcs) {
  995. return as(Effects).animate(stringOrProperties, duration, funcs);
  996. }
  997. /**
  998. * Append content to the inside of every matched element. This operation is similar to doing an
  999. * appendChild to all the specified elements, adding them into the document.
  1000. */
  1001. public GQuery append(GQuery query) {
  1002. return domManip(query, DomMan.APPEND);
  1003. }
  1004. /**
  1005. * Append content to the inside of every matched element. This operation is similar to doing an
  1006. * appendChild to all the specified elements, adding them into the document.
  1007. */
  1008. public GQuery append(Node n) {
  1009. return domManip($(n), DomMan.APPEND);
  1010. }
  1011. /**
  1012. * Append content to the inside of every matched element. This operation is similar to doing an
  1013. * appendChild to all the specified elements, adding them into the document.
  1014. */
  1015. public GQuery append(String html) {
  1016. return domManip(html, DomMan.APPEND);
  1017. }
  1018. /**
  1019. * All of the matched set of elements will be inserted at the end of the element(s) specified by
  1020. * the parameter other.
  1021. *
  1022. * The operation $(A).appendTo(B) is, essentially, the reverse of doing a regular $(A).append(B),
  1023. * instead of appending B to A, you're appending A to B.
  1024. */
  1025. public GQuery appendTo(GQuery other) {
  1026. other.append(this);
  1027. return this;
  1028. }
  1029. /**
  1030. * All of the matched set of elements will be inserted at the end of the element(s) specified by
  1031. * the parameter other.
  1032. *
  1033. * The operation $(A).appendTo(B) is, essentially, the reverse of doing a regular $(A).append(B),
  1034. * instead of appending B to A, you're appending A to B.
  1035. */
  1036. public GQuery appendTo(Node n) {
  1037. GQuery a = $(n);
  1038. GQuery b = this;
  1039. a.append(b);
  1040. return this;
  1041. }
  1042. /**
  1043. * All of the matched set of elements will be inserted at the end of the element(s) specified by
  1044. * the parameter other.
  1045. *
  1046. * The operation $(A).appendTo(B) is, essentially, the reverse of doing a regular $(A).append(B),
  1047. * instead of appending B to A, you're appending A to B.
  1048. */
  1049. public GQuery appendTo(String html) {
  1050. $(html).append(this);
  1051. return this;
  1052. }
  1053. /**
  1054. * Convert to Plugin interface provided by Class literal.
  1055. */
  1056. @SuppressWarnings("unchecked")
  1057. public <T extends GQuery> T as(Class<T> plugin) {
  1058. // GQuery is not a plugin for itself
  1059. if (plugin == GQUERY) {
  1060. return (T)this;
  1061. } else if (plugins != null) {
  1062. Plugin<?> p = plugins.get(plugin);
  1063. if (p != null) {
  1064. return (T)p.init(this);
  1065. }
  1066. }
  1067. throw new RuntimeException("No plugin registered for class " + plugin.getName());
  1068. }
  1069. /**
  1070. * Set a key/value object as properties to all matched elements.
  1071. *
  1072. * Example: $("img").attr(new Properties("src: 'test.jpg', alt: 'Test Image'"))
  1073. */
  1074. public GQuery attr(Properties properties) {
  1075. for (String name : properties.keys()) {
  1076. attr(name, properties.getStr(name));
  1077. }
  1078. return this;
  1079. }
  1080. /**
  1081. * Access a property on the first matched element. This method makes it easy to retrieve a
  1082. * property value from the first matched element. If the element does not have an attribute with
  1083. * such a name, empty string is returned. Attributes include title, alt, src, href, width, style,
  1084. * etc.
  1085. */
  1086. public String attr(String name) {
  1087. return isEmpty() ? "" : get(0).getAttribute(name);
  1088. }
  1089. /**
  1090. * Set a single property to a computed value, on all matched elements.
  1091. */
  1092. public GQuery attr(String key, Function closure) {
  1093. int i = 0;
  1094. for (Element e : elements) {
  1095. Object val = closure.f(e.<com.google.gwt.dom.client.Element> cast(), i++);
  1096. $(e).attr(key, val);
  1097. }
  1098. return this;
  1099. }
  1100. /**
  1101. * Set a single property to a value, on all matched elements.
  1102. */
  1103. public GQuery attr(String key, Object value) {
  1104. assert key != null : "key cannot be null";
  1105. assert !"$H".equalsIgnoreCase(key) : "$H is a GWT reserved attribute. Changing its value will break your application.";
  1106. getAttributeImpl().setAttribute(this, key, value);
  1107. return this;
  1108. }
  1109. /**
  1110. * Insert content before each of the matched elements. The elements must already be inserted into
  1111. * the document (you can't insert an element before another if it's not in the page).
  1112. */
  1113. public GQuery before(GQuery query) {
  1114. return domManip(query, DomMan.BEFORE);
  1115. }
  1116. /**
  1117. * Insert content before each of the matched elements. The elements must already be inserted into
  1118. * the document (you can't insert an element before another if it's not in the page).
  1119. */
  1120. public GQuery before(Node n) {
  1121. return domManip($(n), DomMan.BEFORE);
  1122. }
  1123. /**
  1124. * Insert content before each of the matched elements. The elements must already be inserted into
  1125. * the document (you can't insert an element before another if it's not in the page).
  1126. */
  1127. public GQuery before(String html) {
  1128. return domManip(html, DomMan.BEFORE);
  1129. }
  1130. /**
  1131. * Binds a set of handlers to a particular Event for each matched element.
  1132. *
  1133. * The event handlers are passed as Functions that you can use to prevent default behavior. To
  1134. * stop both default action and event bubbling, the function event handler has to return false.
  1135. *
  1136. * You can pass an additional Object data to your Function as the second parameter
  1137. *
  1138. */
  1139. public GQuery bind(int eventbits, final Object data, final Function... funcs) {
  1140. return as(Events).bind(eventbits, data, funcs);
  1141. }
  1142. /**
  1143. * Binds a set of handlers to a particular Event for each matched element.
  1144. *
  1145. * The event handlers are passed as Functions that you can use to prevent default behavior. To
  1146. * stop both default action and event bubbling, the function event handler has to return false.
  1147. *
  1148. *
  1149. */
  1150. public GQuery bind(int eventbits, final Function... funcs) {
  1151. return as(Events).bind(eventbits, null, funcs);
  1152. }
  1153. /**
  1154. * Binds a set of handlers to a particular Event for each matched element.
  1155. *
  1156. * The event handlers are passed as Functions that you can use to prevent default behavior. To
  1157. * stop both default action and event bubbling, the function event handler has to return false.
  1158. *
  1159. * You can pass an additional Object data to your Function as the second parameter
  1160. *
  1161. */
  1162. public GQuery bind(String eventType, final Object data, final Function... funcs) {
  1163. return as(Events).bind(eventType, data, funcs);
  1164. }
  1165. /**
  1166. * Binds a set of handlers to a particular Event for each matched element.
  1167. *
  1168. * The event handlers are passed as Functions that you can use to prevent default behavior. To
  1169. * stop both default action and event bubbling, the function event handler has to return false.
  1170. *
  1171. *
  1172. */
  1173. public GQuery bind(String eventType, final Function... funcs) {
  1174. return as(Events).bind(eventType, null, funcs);
  1175. }
  1176. /**
  1177. * Bind Handlers or fire Events for each matched element.
  1178. */
  1179. private GQuery bindOrFire(int eventbits, final Object data, final Function... funcs) {
  1180. if (funcs.length == 0) {
  1181. return trigger(eventbits);
  1182. } else {
  1183. return bind(eventbits, data, funcs);
  1184. }
  1185. }
  1186. /**
  1187. * Bind Handlers or fire Events for each matched element.
  1188. */
  1189. private GQuery bindOrFire(String eventname, final Object data, final Function... funcs) {
  1190. if (funcs.length == 0) {
  1191. return as(Events).triggerHtmlEvent(eventname);
  1192. } else {
  1193. return bind(eventname, data, funcs);
  1194. }
  1195. }
  1196. /**
  1197. * Bind a set of functions to the blur event of each matched element. Or trigger the blur event if
  1198. * no functions are provided.
  1199. */
  1200. public GQuery blur(Function... f) {
  1201. bindOrFire(Event.ONBLUR, null, f);
  1202. if (!isEmpty() && f.length == 0) {
  1203. get(0).blur();
  1204. }
  1205. return this;
  1206. }
  1207. /**
  1208. * Bind a set of functions to the change event of each matched element. Or trigger the event if no
  1209. * functions are provided.
  1210. */
  1211. public GQuery change(Function... f) {
  1212. return bindOrFire(Event.ONCHANGE, null, f);
  1213. }
  1214. /**
  1215. * Get a set of elements containing all of the unique immediate children of each of the matched
  1216. * set of elements. Also note: while parents() will look at all ancestors, children() will only
  1217. * consider immediate child elements.
  1218. */
  1219. public GQuery children() {
  1220. JsNodeArray result = JsNodeArray.create();
  1221. for (Element e : elements) {
  1222. allNextSiblingElements(e.getFirstChildElement(), result, null, null, null);
  1223. }
  1224. return new GQuery(unique(result));
  1225. }
  1226. /**
  1227. * Get a set of elements containing all of the unique children of each of the matched set of
  1228. * elements. This set is filtered with the expressions that will cause only elements matching any
  1229. * of the selectors to be collected.
  1230. */
  1231. public GQuery children(String... filters) {
  1232. return children().filter(filters);
  1233. }
  1234. private void cleanGQData(Element... elements) {
  1235. for (Element el : elements) {
  1236. try {
  1237. EventsListener.clean(el);
  1238. removeData(el, null);
  1239. } catch (Exception e) {
  1240. // If for some reason event/data removal fails, do not break the app,
  1241. // just log the error in dev-mode
  1242. // e.g.: this happens when removing iframes which are no fully loaded.
  1243. e.printStackTrace();
  1244. }
  1245. }
  1246. }
  1247. /**
  1248. * Remove from the Effects queue all {@link Function} that have not yet been run.
  1249. */
  1250. public GQuery clearQueue() {
  1251. return as(Queue).clearQueue();
  1252. }
  1253. /**
  1254. * Remove from the queue all {@link Function} that have not yet been run.
  1255. */
  1256. public GQuery clearQueue(String queueName) {
  1257. return as(Queue).clearQueue(queueName);
  1258. }
  1259. /**
  1260. * Bind a set of functions to the click event of each matched element. Or trigger the event if no
  1261. * functions are provided.
  1262. */
  1263. public GQuery click(Function... f) {
  1264. return bindOrFire(Event.ONCLICK, null, f);
  1265. }
  1266. /**
  1267. * Clone matched DOM Elements and select the clones. This is useful for moving copies of the
  1268. * elements to another location in the DOM.
  1269. */
  1270. public GQuery clone() {
  1271. JsNodeArray result = JsNodeArray.create();
  1272. for (Element e : elements) {
  1273. result.addNode(e.cloneNode(true));
  1274. }
  1275. GQuery ret = new GQuery(result);
  1276. ret.currentContext = currentContext;
  1277. ret.currentSelector = currentSelector;
  1278. return ret;
  1279. }
  1280. /**
  1281. * Get the first ancestor element that matches the selector (for each matched element), beginning
  1282. * at the current element and progressing up through the DOM tree.
  1283. *
  1284. * @param selector
  1285. * @return
  1286. */
  1287. public GQuery closest(String selector) {
  1288. return closest(selector, null);
  1289. }
  1290. /**
  1291. * Get the first ancestor element that matches the selector (for each matched element), beginning
  1292. * at the current element and progressing up through the DOM tree until reach the
  1293. * <code>context</code> node.
  1294. *
  1295. * If no context is passed in then the context of the gQuery object will be used instead.
  1296. *
  1297. */
  1298. public GQuery closest(String selector, Node context) {
  1299. assert selector != null;
  1300. if (context == null) {
  1301. context = currentContext;
  1302. }
  1303. GQuery pos = posRegex.test(selector) ? $(selector, context) : null;
  1304. JsNodeArray result = JsNodeArray.create();
  1305. for (Element e : elements) {
  1306. Element current = e;
  1307. while (current != null && current.getOwnerDocument() != null && current != context) {
  1308. boolean match = pos != null ? pos.index(current) > -1 : $(current).is(selector);
  1309. if (match) {
  1310. result.addNode(current);
  1311. break;
  1312. } else {
  1313. current = current.getParentElement();
  1314. }
  1315. }
  1316. }
  1317. return $(unique(result));
  1318. }
  1319. /**
  1320. * Returns a {@link Map} object as key a selector and as value the list of ancestor elements
  1321. * matching this selectors, beginning at the first matched element and progressing up through the
  1322. * DOM. This method allows retrieving the list of ancestors matching many selectors by traversing
  1323. * the DOM only one time.
  1324. *
  1325. * @return
  1326. */
  1327. public JsNamedArray<NodeList<Element>> closest(String[] selectors) {
  1328. return closest(selectors, null);
  1329. }
  1330. /**
  1331. * Returns a {@link Map} object as key a selector and as value the list of ancestor elements
  1332. * matching this selectors, beginning at the first matched element and progressing up through the
  1333. * DOM until reach the <code>context</code> node.. This method allows retrieving the list of
  1334. * ancestors matching many selectors by traversing the DOM only one time.
  1335. *
  1336. * @return
  1337. */
  1338. public JsNamedArray<NodeList<Element>> closest(String[] selectors, Node context) {
  1339. JsNamedArray<NodeList<Element>> results = JsNamedArray.create();
  1340. if (context == null) {
  1341. context = currentContext;
  1342. }
  1343. Element first = get(0);
  1344. if (first != null && selectors != null && selectors.length > 0) {
  1345. JsNamedArray<GQuery> matches = JsNamedArray.create();
  1346. for (String selector : selectors) {
  1347. if (!matches.exists(selector)) {
  1348. matches.put(selector, posRegex.test(selector) ? $(selector, context) : null);
  1349. }
  1350. }
  1351. Element current = first;
  1352. while (current != null && current.getOwnerDocument() != null && current != context) {
  1353. // for each selector, check if the current element match it.
  1354. for (String selector : matches.keys()) {
  1355. GQuery pos = matches.get(selector);
  1356. boolean match = pos != null ? pos.index(current) > -1 : $(current).is(selector);
  1357. if (match) {
  1358. JsNodeArray elementsMatchingSelector = results.get(selector).cast();
  1359. if (elementsMatchingSelector == null) {
  1360. elementsMatchingSelector = JsNodeArray.create();
  1361. results.put(selector, elementsMatchingSelector);
  1362. }
  1363. elementsMatchingSelector.addNode(current);
  1364. }
  1365. }
  1366. current = current.getParentElement();
  1367. }
  1368. }
  1369. return results;
  1370. }
  1371. /**
  1372. * Filter the set of elements to those that contain the specified text.
  1373. */
  1374. public GQuery contains(String text) {
  1375. JsNodeArray array = JsNodeArray.create();
  1376. for (Element e : elements) {
  1377. if ($(e).text().contains(text)) {
  1378. array.addNode(e);
  1379. }
  1380. }
  1381. return $(array);
  1382. }
  1383. /**
  1384. * Find all the child nodes inside the matched elements (including text nodes), or the content
  1385. * document, if the element is an iframe.
  1386. */
  1387. public GQuery contents() {
  1388. JsNodeArray result = JsNodeArray.create();
  1389. for (Element e : elements) {
  1390. if (JsUtils.isWindow(e) || "iframe".equalsIgnoreCase(e.getTagName())) {
  1391. result.addNode(getStyleImpl().getContentDocument(e));
  1392. } else {
  1393. NodeList<Node> children = e.getChildNodes();
  1394. for (int i = 0, l = children.getLength(); i < l; i++) {
  1395. result.addNode(children.getItem(i));
  1396. }
  1397. }
  1398. }
  1399. return new GQuery(unique(result));
  1400. }
  1401. public LazyGQuery<?> createLazy() {
  1402. return GWT.create(GQuery.class);
  1403. }
  1404. /**
  1405. * Set CSS a single style property on every matched element using type-safe enumerations.
  1406. *
  1407. * The best way to use this method (i.e. to generate a CssSetter) is to take the desired css
  1408. * property defined in {@link CSS} class and call the {@link TakesCssValue#with(HasCssName)}
  1409. * method on it.
  1410. *
  1411. *
  1412. * ex :
  1413. *
  1414. * <pre class="code">
  1415. * $("#myDiv").css(CSS.TOP.with(Length.cm(15)));
  1416. * $("#myDiv").css(CSS.BACKGROUND.with(RGBColor.SILVER, ImageValue.url(""),
  1417. * BackgroundRepeat.NO_REPEAT, BackgroundAttachment.FIXED,
  1418. * BackgroundPosition.CENTER));
  1419. * $("#myDiv").css(CSS.BACKGROUND_ATTACHMENT.with(BackgroundAttachment.FIXED));
  1420. *
  1421. * </pre>
  1422. *
  1423. */
  1424. public GQuery css(CssSetter... cssSetter) {
  1425. for (Element e : elements) {
  1426. for (CssSetter s : cssSetter) {
  1427. s.applyCss(e);
  1428. }
  1429. }
  1430. return this;
  1431. }
  1432. /**
  1433. * Return a style property on the first matched element using type-safe enumerations.
  1434. *
  1435. * Ex : $("#myId").css(CSS.BACKGROUND_COLOR);
  1436. */
  1437. public String css(HasCssValue property) {
  1438. return css(property, true);
  1439. }
  1440. /**
  1441. * Return a style property on the first matched element using type-safe enumerations.
  1442. *
  1443. * The parameter force has a special meaning here: - When force is false, returns the value of the
  1444. * css property defined in the style attribute of the element. - Otherwise it returns the real
  1445. * computed value.
  1446. *
  1447. * For instance if you define 'display=none' not in the element style but in the css stylesheet,
  1448. * it returns an empty string unless you pass the parameter force=true.
  1449. *
  1450. * Ex : $("#myId").css(CSS.WIDTH, true);
  1451. */
  1452. public String css(HasCssValue property, boolean force) {
  1453. return css(property.getCssName(), force);
  1454. }
  1455. /**
  1456. * Set a key/value object as style properties to all matched elements. This serves as the best way
  1457. * to set a large number of style properties on all matched elements. You can use either js maps
  1458. * or pure css syntax.
  1459. *
  1460. * Example:
  1461. *
  1462. * <pre class="code">
  1463. * $(".item").css(Properties.create("color: 'red', background:'blue'"))
  1464. * $(".item").css(Properties.create("color: red; background: blue;"))
  1465. * </pre>
  1466. */
  1467. public GQuery css(Properties properties) {
  1468. for (String property : properties.keys()) {
  1469. css(property, properties.getStr(property));
  1470. }
  1471. return this;
  1472. }
  1473. /**
  1474. * Return a style property on the first matched element.
  1475. */
  1476. public String css(String name) {
  1477. return css(name, true);
  1478. }
  1479. /**
  1480. * Return a style property on the first matched element.
  1481. *
  1482. * The parameter force has a special meaning here:
  1483. * <ul>
  1484. * <li>When force is false, returns the value of the css property defined in the style attribute
  1485. * of the element.
  1486. * <li>Otherwise it returns the real computed value.
  1487. * </ul>
  1488. *
  1489. * For instance if you don't define 'display=none'in the element style but in the css stylesheet,
  1490. * it returns an empty string unless you pass the parameter force=true.
  1491. */
  1492. public String css(String name, boolean force) {
  1493. return isEmpty() ? "" : getStyleImpl().curCSS(get(0), name, force);
  1494. }
  1495. /**
  1496. * Set a single style property to a value, on all matched elements.
  1497. *
  1498. */
  1499. public GQuery css(String prop, String val) {
  1500. for (Element e : elements) {
  1501. getStyleImpl().setStyleProperty(e, prop, val);
  1502. }
  1503. return this;
  1504. }
  1505. /**
  1506. * Set CSS a single style property on every matched element using type-safe enumerations. This
  1507. * method allows you to set manually the value or set <i>inherit</i> value
  1508. *
  1509. * ex :
  1510. *
  1511. * <pre class="code">
  1512. * $(#myId).css(CSS.TEXT_DECORATION, CSS.INHERIT);
  1513. * </pre>
  1514. */
  1515. public GQuery css(TakesCssValue<?> cssProperty, String value) {
  1516. return css(cssProperty.getCssName(), value);
  1517. }
  1518. /**
  1519. * Returns the numeric value of a css property.
  1520. */
  1521. public double cur(String prop) {
  1522. return cur(prop, false);
  1523. }
  1524. /**
  1525. * Returns the numeric value of a css property.
  1526. *
  1527. * The parameter force has a special meaning: - When force is false, returns the value of the css
  1528. * property defined in the set of style attributes. - When true returns the real computed value.
  1529. */
  1530. public double cur(String prop, boolean force) {
  1531. return isEmpty() ? 0 : getStyleImpl().cur(get(0), prop, force);
  1532. }
  1533. /**
  1534. * Return the value at the named data store for the first element in the set of matched
  1535. * elements.
  1536. */
  1537. @SuppressWarnings("unchecked")
  1538. public <T> T data(String name) {
  1539. return isEmpty() ? null : (T)data(get(0), name, null);
  1540. }
  1541. /**
  1542. * Return the value at the named data store for the first element in the set of matched
  1543. * elements, as set by data(name, value), with desired return type.
  1544. *
  1545. * @param clz return type class literal
  1546. */
  1547. public <T> T data(String name, Class<? extends T> clz) {
  1548. return isEmpty() ? null : data(get(0), name, null, clz);
  1549. }
  1550. /**
  1551. * Store arbitrary data associated with the matched elements in the named data store.
  1552. */
  1553. public GQuery data(String name, Object value) {
  1554. for (Element e : elements()) {
  1555. data(e, name, value);
  1556. }
  1557. return this;
  1558. }
  1559. /**
  1560. * Bind a set of functions to the dblclick event of each matched element. Or trigger the event if
  1561. * no functions are provided.
  1562. */
  1563. public GQuery dblclick(Function... f) {
  1564. return bindOrFire(Event.ONDBLCLICK, null, f);
  1565. }
  1566. /**
  1567. * Insert a delay (in ms) in the GQuery queue, and optionally execute one o more functions if
  1568. * provided when the delay finishes. It uses the effects queue namespace, so you can stack any of
  1569. * the methods in the effects plugin.
  1570. *
  1571. * Example:
  1572. *
  1573. * <pre class="code">
  1574. * $("#foo").slideUp(300)
  1575. * .delay(800)
  1576. * .fadeIn(400);
  1577. * </pre>
  1578. *
  1579. * When this statement is executed, the element slides up for 300 milliseconds and then pauses for
  1580. * 800 milliseconds before fading in for 400 milliseconds. Aditionally after those 800
  1581. * milliseconds the element color is set to red.
  1582. *
  1583. * NOTE that this methods affects only methods which uses the queue like effects. So the following
  1584. * example is wrong:
  1585. *
  1586. * <pre>
  1587. * $("#foo").css(CSS.COLOR.with(RGBColor.RED)).delay(800).css(CSS.COLOR.with(RGBColor.BLACK));
  1588. * </pre>
  1589. *
  1590. * The code above will not insert a delay of 800 ms between the css() calls ! For this kind of
  1591. * behavior, you should execute these methods puting them in inline functions passed as argument
  1592. * to the delay() method, or adding them to the queue.
  1593. *
  1594. * <pre>
  1595. * $("#foo").css(CSS.COLOR.with(RGBColor.RED)).delay(800, lazy().css(CSS.COLOR.with(RGBColor.BLACK)).done());
  1596. * $("#foo").css(CSS.COLOR.with(RGBColor.RED)).delay(800).queue(lazy().css(CSS.COLOR.with(RGBColor.BLACK)).dequeue().done());
  1597. * </pre>
  1598. */
  1599. public GQuery delay(int milliseconds, Function... f) {
  1600. return as(Queue).delay(milliseconds, f);
  1601. }
  1602. /**
  1603. * Insert a delay (in ms) in the queue identified by the <code>queueName</code> parameter, and
  1604. * optionally execute one o more functions if provided when the delay finishes.
  1605. *
  1606. * If <code>queueName</code> is null or equats to 'fx', the delay will be inserted to the Effects
  1607. * queue.
  1608. *
  1609. * Example :
  1610. *
  1611. * <pre class="code">
  1612. * $("#foo").queue("colorQueue", lazy().css(CSS.COLOR.with(RGBColor.RED)).dequeue("colorQueue").done())
  1613. * .delay(800, "colorQueue")
  1614. * .queue("colorQueue", lazy().css(CSS.COLOR.with(RGBColor.BLACK)).dequeue("colorQueue").done());
  1615. * </pre>
  1616. *
  1617. * When this statement is executed, the text color of the element changes to red and then wait for
  1618. * 800 milliseconds before changes the text color to black.
  1619. *
  1620. */
  1621. public GQuery delay(int milliseconds, String queueName, Function... f) {
  1622. return as(Queue).delay(milliseconds, queueName, f);
  1623. }
  1624. /**
  1625. * Attach <code>handlers</code> to one or more events for all elements that match the
  1626. * <code>selector</code>, now or in the future, based on a specific set of root elements.
  1627. *
  1628. * Example:
  1629. *
  1630. * <pre>
  1631. * $("table").delegate("td", Event.ONCLICK, new Function(){
  1632. * public void f(Element e){
  1633. * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
  1634. * }
  1635. * });
  1636. * </pre>
  1637. *
  1638. * This code above add an handler on click event on all cell (the existing oneand the future cell)
  1639. * of all table. This code is equivalent to :
  1640. *
  1641. * <pre>
  1642. * $("table").each(new Function(){
  1643. * public void f(Element table){
  1644. * $("td", table).live(Event.ONCLICK, new Function(){
  1645. * public void f(Element e){
  1646. * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
  1647. * }
  1648. * }
  1649. * });
  1650. *
  1651. * </pre>
  1652. *
  1653. * You can attach the handlers to many events by using the '|' operator ex:
  1654. *
  1655. * <pre>
  1656. * $("div.main").delegate(".subMain", Event.ONCLICK | Event.ONDBLCLICK, new Function(){...});
  1657. * </pre>
  1658. * @deprecated use {@link #on(String, String, Function...)}
  1659. */
  1660. public GQuery delegate(String selector, int eventbits, Function... handlers) {
  1661. return delegate(selector, eventbits, null, handlers);
  1662. }
  1663. /**
  1664. * Attach <code>handlers</code> to one or more events for all elements that match the
  1665. * <code>selector</code>, now or in the future, based on a specific set of root elements. The
  1666. * <code>data</code> parameter allows us to pass data to the handler.
  1667. *
  1668. * Example:
  1669. *
  1670. * <pre>
  1671. * $("table").delegate("td", "click", new Function(){
  1672. * public void f(Element e){
  1673. * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
  1674. * }
  1675. * });
  1676. * </pre>
  1677. *
  1678. * This code above add an handler on click event on all cell (the existing oneand the future cell)
  1679. * of all table. This code is equivalent to :
  1680. *
  1681. * <pre>
  1682. * $("table").each(new Function(){
  1683. * public void f(Element table){
  1684. * $("td", table).live("click", new Function(){
  1685. * public void f(Element e){
  1686. * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
  1687. * }
  1688. * }
  1689. * });
  1690. *
  1691. * </pre>
  1692. *
  1693. * You can pass attach the handlers to many events by using the '|' operator ex:
  1694. *
  1695. * <pre>
  1696. * $("div.main").delegate(".subMain", Event.ONCLICK | Event.ONDBLCLICK, new Function(){...});
  1697. * </pre>
  1698. * @deprecated use {@link #on(String, String, Object, Function...)}
  1699. */
  1700. public GQuery delegate(String selector, int eventbits, Object data, Function... handlers) {
  1701. for (Element e : elements) {
  1702. $(selector, e).live(eventbits, data, handlers);
  1703. }
  1704. return this;
  1705. }
  1706. /**
  1707. * Attach <code>handlers</code> to one or more events for all elements that match the
  1708. * <code>selector</code>, now or in the future, based on a specific set of root elements.
  1709. *
  1710. * Example:
  1711. *
  1712. * <pre>
  1713. * $("table").delegate("td", "click", new Function(){
  1714. * public void f(Element e){
  1715. * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
  1716. * }
  1717. * });
  1718. * </pre>
  1719. *
  1720. * This code above add an handler on click event on all cell (the existing oneand the future cell)
  1721. * of all table. This code is equivalent to :
  1722. *
  1723. * <pre>
  1724. * $("table").each(new Function(){
  1725. * public void f(Element table){
  1726. * $("td", table).live("click", new Function(){
  1727. * public void f(Element e){
  1728. * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
  1729. * }
  1730. * }
  1731. * });
  1732. *
  1733. * </pre>
  1734. *
  1735. * You can pass attach the handlers to many events by specifying a String with espaced event type.
  1736. * ex:
  1737. *
  1738. * <pre>
  1739. * $("div.main").delegate(".subMain", "click dblclick", new Function(){...});
  1740. * </pre>
  1741. *
  1742. * </pre>
  1743. * @deprecated use {@link #on(String, String, Function...)}
  1744. */
  1745. public GQuery delegate(String selector, String eventType, Function... handlers) {
  1746. return delegate(selector, eventType, null, handlers);
  1747. }
  1748. /**
  1749. * Attach <code>handlers</code> to one or more events for all elements that match the
  1750. * <code>selector</code>, now or in the future, based on a specific set of root elements.
  1751. *
  1752. * Example:
  1753. *
  1754. * <pre>
  1755. * $("table").delegate("td", "click", new Function(){
  1756. * public void f(Element e){
  1757. * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
  1758. * }
  1759. * });
  1760. * </pre>
  1761. *
  1762. * This code above add an handler on click event on all cell (the existing oneand the future cell)
  1763. * of all table. This code is equivalent to :
  1764. *
  1765. * <pre>
  1766. * $("table").each(new Function(){
  1767. * public void f(Element table){
  1768. * $("td", table).live("click", new Function(){
  1769. * public void f(Element e){
  1770. * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
  1771. * }
  1772. * }
  1773. * });
  1774. *
  1775. * You can pass attach the handlers to many events by specifying a String with espaced event type.
  1776. * ex:
  1777. *
  1778. * <pre>
  1779. * $("div.main").delegate(".subMain", "click dblclick", new Function(){...});
  1780. * </pre>
  1781. *
  1782. * </pre>
  1783. * @deprecated use {@link #on(String, String, Object, Function...)}
  1784. */
  1785. public GQuery delegate(String selector, String eventType, Object data, Function... handlers) {
  1786. for (Element e : elements) {
  1787. $(selector, e).live(eventType, data, handlers);
  1788. }
  1789. return this;
  1790. }
  1791. /**
  1792. * Execute the next function on the Effects queue for the matched elements. This method is usefull
  1793. * to tell when a function you add in the Effects queue is ended and so the next function in the
  1794. * queue can start.
  1795. *
  1796. * Note: you should be sure to call dequeue() in all functions of a queue chain, otherwise the
  1797. * queue execution will be stopped.
  1798. */
  1799. public GQuery dequeue() {
  1800. return as(Queue).dequeue();
  1801. }
  1802. /**
  1803. * Execute the next function on the queue named as queueName for the matched elements. This method
  1804. * is usefull to tell when a function you add in the Effects queue is ended and so the next
  1805. * function in the queue can start.
  1806. */
  1807. public GQuery dequeue(String queueName) {
  1808. return as(Queue).dequeue(queueName);
  1809. }
  1810. /**
  1811. * Detach all matched elements from the DOM. This method is the same than {@link #remove()} method
  1812. * except all data and event handlers are not remove from the element. This method is useful when
  1813. * removed elements are to be reinserted into the DOM at a later time.
  1814. */
  1815. public GQuery detach() {
  1816. return remove(null, false);
  1817. }
  1818. /**
  1819. * Detach from the DOM all matched elements filtered by the <code>filter</code>.. This method is
  1820. * the same than {@link #remove(String)} method except all data and event handlers are not remove
  1821. * from the element. This method is useful when removed elements are to be reinserted into the DOM
  1822. * at a later time.
  1823. */
  1824. public GQuery detach(String filter) {
  1825. return remove(filter, false);
  1826. }
  1827. /**
  1828. * Remove all event handlers previously attached using {@link #live(String, Function)}. In order
  1829. * for this method to function correctly, the selector used with it must match exactly the
  1830. * selector initially used with {@link #live(String, Function)}
  1831. * @deprecated use {@link #off(String, String)} instead
  1832. */
  1833. public GQuery die() {
  1834. return die(0);
  1835. }
  1836. /**
  1837. * Remove an event handlers previously attached using {@link #live(int, Function)} In order for
  1838. * this method to function correctly, the selector used with it must match exactly the selector
  1839. * initially used with {@link #live(int, Function)}
  1840. * @deprecated use {@link #off(String)}
  1841. */
  1842. public GQuery die(int eventbits) {
  1843. return as(Events).die(eventbits);
  1844. }
  1845. /**
  1846. * Remove an event handlers previously attached using {@link #live(String, Function)} In order for
  1847. * this method to function correctly, the selector used with it must match exactly the selector
  1848. * initially used with {@link #live(String, Function)}
  1849. */
  1850. public GQuery die(String eventName) {
  1851. return as(Events).die(eventName);
  1852. }
  1853. private GQuery domManip(GQuery g, DomMan type, Element... elms) {
  1854. JsNodeArray newNodes = JsNodeArray.create();
  1855. if (elms.length == 0) {
  1856. elms = elements;
  1857. }
  1858. for (int i = 0, l = elms.length; i < l; i++) {
  1859. Element e = elms[i];
  1860. if (e.getNodeType() == Node.DOCUMENT_NODE) {
  1861. e = e.<Document> cast().getBody();
  1862. }
  1863. for (int j = 0, size = g.size(); j < size; j++) {
  1864. // Widget w = getAssociatedWidget(g.get(j));
  1865. // GqUi.detachWidget(w);
  1866. Node n = g.get(j);
  1867. // If an element selected is inserted elsewhere, it will be moved into the target (not
  1868. // cloned).
  1869. // If there is more than one target element, however, cloned copies of the inserted element
  1870. // will be created for each target after the first
  1871. if (i > 0) {
  1872. n = n.cloneNode(true);
  1873. }
  1874. switch (type) {
  1875. case PREPEND:
  1876. newNodes.addNode(e.insertBefore(n, e.getFirstChild()));
  1877. break;
  1878. case APPEND:
  1879. newNodes.addNode(e.appendChild(n));
  1880. break;
  1881. case AFTER:
  1882. newNodes.addNode(e.getParentNode().insertBefore(n, e.getNextSibling()));
  1883. break;
  1884. case BEFORE:
  1885. newNodes.addNode(e.getParentNode().insertBefore(n, e));
  1886. break;
  1887. }
  1888. EventsListener.rebind(n.<Element> cast());
  1889. // GqUi.attachWidget(w);
  1890. }
  1891. }
  1892. // TODO: newNodes.size() > g.size() makes testRebind fail
  1893. if (newNodes.size() >= g.size()) {
  1894. g.setArray(newNodes);
  1895. }
  1896. return this;
  1897. }
  1898. // TODO: this should be handled by the other domManip method
  1899. private GQuery domManip(String htmlString, DomMan type) {
  1900. JsMap<Document, GQuery> cache = JsMap.createObject().cast();
  1901. for (Element e : elements) {
  1902. Document d = JsUtils.getOwnerDocument(e);
  1903. GQuery g = cache.get(d);
  1904. if (g == null) {
  1905. g = cleanHtmlString(htmlString, d);
  1906. cache.put(d, g);
  1907. }
  1908. domManip(g.clone(), type, e);
  1909. }
  1910. return this;
  1911. }
  1912. /**
  1913. * Run one or more Functions over each element of the GQuery. You have to override one of these
  1914. * funcions: public void f(Element e) public String f(Element e, int i)
  1915. */
  1916. public GQuery each(Function... f) {
  1917. if (f != null) {
  1918. for (Function f1 : f) {
  1919. if (f1 != null) {
  1920. int i = 0;
  1921. for (Element e : elements) {
  1922. f1.f(e.<com.google.gwt.dom.client.Element> cast(), i++);
  1923. }
  1924. }
  1925. }
  1926. }
  1927. return this;
  1928. }
  1929. /**
  1930. * Returns the working set of nodes as a Java array. <b>Do NOT</b> attempt to modify this array,
  1931. * e.g. assign to its elements, or call Arrays.sort()
  1932. */
  1933. public Element[] elements() {
  1934. return elements;
  1935. }
  1936. /**
  1937. * Remove all child nodes from the set of matched elements. In the case of a document element, it
  1938. * removes all the content You should call this method whenever you create a new iframe and you
  1939. * want to add dynamic content to it.
  1940. */
  1941. public GQuery empty() {
  1942. for (Element e : elements) {
  1943. if (e.getNodeType() == Element.DOCUMENT_NODE) {
  1944. getStyleImpl().emptyDocument(e.<Document> cast());
  1945. } else {
  1946. Node c = e.getFirstChild();
  1947. while (c != null) {
  1948. removeData(c.<Element> cast(), null);
  1949. WidgetsUtils.detachWidget(getAssociatedWidget(e));
  1950. EventsListener.clean(c.<Element> cast());
  1951. e.removeChild(c);
  1952. c = e.getFirstChild();
  1953. }
  1954. }
  1955. }
  1956. return this;
  1957. }
  1958. /**
  1959. * Revert the most recent 'destructive' operation, changing the set of matched elements to its
  1960. * previous state (right before the destructive operation).
  1961. */
  1962. public GQuery end() {
  1963. return previousObject != null ? previousObject : new GQuery();
  1964. }
  1965. /**
  1966. * Reduce GQuery to element in the specified position. This method accept negative index. A
  1967. * negative index is counted from the end of the matched set:
  1968. *
  1969. * Example:
  1970. *
  1971. * <pre>
  1972. * $("div").eq(0) will reduce the matched set to the first matched div
  1973. * $("div").eq(1) will reduce the matched set to the second matched div
  1974. *
  1975. * $("div").eq(-1) will reduce the matched set to the last matched div
  1976. * $("div").eq(-2) will reduce the matched set to the second-to-last matched div
  1977. * ...
  1978. * </pre>
  1979. */
  1980. public GQuery eq(int pos) {
  1981. return $(get(pos));
  1982. }
  1983. /**
  1984. * Bind a set of functions to the error event of each matched element. Or trigger the event if no
  1985. * functions are provided.
  1986. */
  1987. public GQuery error(Function... f) {
  1988. return bindOrFire(Event.ONERROR, null, f);
  1989. }
  1990. /**
  1991. * Fade in all matched elements by adjusting their opacity. The effect will take 1000 milliseconds
  1992. * to complete
  1993. */
  1994. public GQuery fadeIn(Function... f) {
  1995. return as(Effects).fadeIn(f);
  1996. }
  1997. /**
  1998. * Fade in all matched elements by adjusting their opacity.
  1999. */
  2000. public GQuery fadeIn(int millisecs, Function... f) {
  2001. return as(Effects).fadeIn(millisecs, f);
  2002. }
  2003. /**
  2004. * Fade the opacity of all matched elements to a specified opacity and firing
  2005. * an optional callback after completion. Only the opacity is adjusted for
  2006. * this animation, meaning that all of the matched elements should already
  2007. * have some form of height and width associated with them.
  2008. */
  2009. public GQuery fadeTo(int millisecs, double opacity, Function... f) {
  2010. return as(Effects).fadeTo(millisecs, opacity, f);
  2011. }
  2012. /**
  2013. * Fade the opacity of all matched elements to a specified opacity and firing
  2014. * an optional callback after completion. Only the opacity is adjusted for
  2015. * this animation, meaning that all of the matched elements should already
  2016. * have some form of height and width associated with them.
  2017. */
  2018. public GQuery fadeTo(double opacity, Function... f) {
  2019. return as(Effects).fadeTo(opacity, f);
  2020. }
  2021. /**
  2022. * Fade out all matched elements by adjusting their opacity. The effect will take 1000
  2023. * milliseconds to complete
  2024. */
  2025. public GQuery fadeOut(Function... f) {
  2026. return as(Effects).fadeOut(f);
  2027. }
  2028. /**
  2029. * Fade out all matched elements by adjusting their opacity.
  2030. */
  2031. public GQuery fadeOut(int millisecs, Function... f) {
  2032. return as(Effects).fadeOut(millisecs, f);
  2033. }
  2034. /**
  2035. * Toggle the visibility of all matched elements by adjusting their opacity and firing an optional
  2036. * callback after completion. Only the opacity is adjusted for this animation, meaning that all of
  2037. * the matched elements should already have some form of height and width associated with them.
  2038. */
  2039. public Effects fadeToggle(int millisecs, Function... f) {
  2040. return as(Effects).fadeToggle(millisecs, f);
  2041. }
  2042. /**
  2043. * Removes all elements from the set of matched elements that do not match the specified function.
  2044. * The function is called with a context equal to the current element. If the function returns
  2045. * false, then the element is removed - anything else and the element is kept.
  2046. */
  2047. public GQuery filter(Predicate filterFn) {
  2048. JsNodeArray result = getSelectorEngine().filter(nodeList, filterFn).cast();
  2049. return pushStack(result, "filter", currentSelector);
  2050. }
  2051. /**
  2052. * Removes all elements from the set of matched elements that do not pass the specified css
  2053. * expression. This method is used to narrow down the results of a search.
  2054. * By default it works for either detached and attached elements unless
  2055. * {@link SelectorEngine#filterDetached} is set to false.
  2056. */
  2057. public GQuery filter(String... filters) {
  2058. String selector = join(", ", filters);
  2059. JsNodeArray result = getSelectorEngine().filter(nodeList, selector).cast();
  2060. return pushStack(result, "filter", selector);
  2061. }
  2062. /**
  2063. * Removes all elements from the set of matched elements that do not pass the specified css
  2064. * expression. This method is used to narrow down the results of a search.
  2065. * Setting filterDetached parameter to true, means that we should consider detached elements
  2066. * as well which implies some performance penalty.
  2067. */
  2068. public GQuery filter(boolean filterDetached, String... filters) {
  2069. String selector = join(", ", filters);
  2070. JsNodeArray result = getSelectorEngine().filter(nodeList, selector, filterDetached).cast();
  2071. return pushStack(result, "filter", selector);
  2072. }
  2073. /**
  2074. * Removes all elements from the set of matched elements that do not pass the specified css
  2075. * expression. This method is used to narrow down the results of a search.
  2076. * Setting considerDetached parameter to true, means that we should consider detached elements
  2077. * as well which implies some performance penalties.
  2078. */
  2079. public GQuery filter(boolean filterDetached, String selector) {
  2080. if (selector.isEmpty()) {
  2081. return this;
  2082. }
  2083. JsNodeArray result = getSelectorEngine().filter(nodeList, selector, filterDetached).cast();
  2084. return pushStack(result, "filter", selector);
  2085. }
  2086. /**
  2087. * Searches for all elements that match the specified css expression. This method is a good way to
  2088. * find additional descendant elements with which to process.
  2089. *
  2090. * Provide a comma-separated list of expressions to apply multiple filters at once.
  2091. */
  2092. public GQuery find(String... filters) {
  2093. JsNodeArray array = JsNodeArray.create();
  2094. for (String selector : filters) {
  2095. for (Element e : elements) {
  2096. for (Element c : $(selector, e).elements) {
  2097. array.addNode(c);
  2098. }
  2099. }
  2100. }
  2101. return pushStack(unique(array), "find", filters[0]);
  2102. }
  2103. /**
  2104. * Reduce the set of matched elements to the first in the set.
  2105. */
  2106. public GQuery first() {
  2107. return eq(0);
  2108. }
  2109. /**
  2110. * Bind a set of functions to the focus event of each matched element. Or trigger the event and
  2111. * move the input focus to the first element if no functions are provided.
  2112. */
  2113. public GQuery focus(Function... f) {
  2114. bindOrFire(Event.ONFOCUS, null, f);
  2115. if (!isEmpty() && f.length == 0) {
  2116. get(0).focus();
  2117. }
  2118. return this;
  2119. }
  2120. /**
  2121. * Return all elements matched in the GQuery as a NodeList. @see #elements() for a method which
  2122. * returns them as an immutable Java array.
  2123. */
  2124. public NodeList<Element> get() {
  2125. return nodeList;
  2126. }
  2127. /**
  2128. * Return the ith element matched. This method accept negative index. A negative index is counted
  2129. * from the end of the matched set.
  2130. *
  2131. * Example:
  2132. *
  2133. * <pre>
  2134. * $("div").get(0) will return the first matched div
  2135. * $("div").get(1) will return the second matched div
  2136. *
  2137. * $("div").get(-1) will return the last matched div
  2138. * $("div").get(-2) will return the secont-to-last matched div
  2139. * ...
  2140. * </pre>
  2141. */
  2142. public Element get(int i) {
  2143. int l = elements.length;
  2144. if (i >= 0 && i < l) {
  2145. return elements[i];
  2146. }
  2147. if (i < 0 && l + i >= 0) {
  2148. return elements[l + i];
  2149. }
  2150. return null;
  2151. }
  2152. public Node getContext() {
  2153. return currentContext;
  2154. }
  2155. /**
  2156. * Return the previous set of matched elements prior to the last destructive operation (e.g.
  2157. * query)
  2158. */
  2159. public GQuery getPreviousObject() {
  2160. return end();
  2161. }
  2162. private native Element getPreviousSiblingElement(Element elem) /*-{
  2163. var sib = elem.previousSibling;
  2164. while (sib && sib.nodeType != 1)
  2165. sib = sib.previousSibling;
  2166. return sib;
  2167. }-*/;
  2168. /**
  2169. * Return the selector representing the current set of matched elements.
  2170. */
  2171. public String getSelector() {
  2172. return currentSelector;
  2173. }
  2174. /**
  2175. * Returns true any of the specified classes are present on any of the matched Reduce the set of
  2176. * matched elements to all elements after a given position. The position of the element in the set
  2177. * of matched elements starts at 0 and goes to length - 1.
  2178. */
  2179. public GQuery gt(int pos) {
  2180. return slice(pos + 1, -1);
  2181. }
  2182. /**
  2183. * Reduce the set of matched elements to those that have a descendant that matches the Element.
  2184. */
  2185. public GQuery has(final Element elem) {
  2186. return filter(new Predicate() {
  2187. public boolean f(Element e, int index) {
  2188. return contains(e, elem);
  2189. }
  2190. });
  2191. }
  2192. /**
  2193. * Reduce the set of matched elements to those that have a descendant that matches the selector.
  2194. */
  2195. public GQuery has(final String selector) {
  2196. return filter(new Predicate() {
  2197. public boolean f(Element e, int index) {
  2198. return !$(selector, e).isEmpty();
  2199. }
  2200. });
  2201. }
  2202. /**
  2203. * Returns true any of the specified classes are present on any of the matched elements.
  2204. */
  2205. public boolean hasClass(String... classes) {
  2206. for (Element e : elements) {
  2207. for (String clz : classes) {
  2208. if (hasClass(e, clz)) {
  2209. return true;
  2210. }
  2211. }
  2212. }
  2213. return false;
  2214. }
  2215. /**
  2216. * Get the current computed, pixel, height of the first matched element. It does not include
  2217. * margin, padding nor border.
  2218. */
  2219. public int height() {
  2220. return (int) cur("height", true);
  2221. }
  2222. /**
  2223. * Set the height of every element in the matched set.
  2224. */
  2225. public GQuery height(int height) {
  2226. for (Element e : elements) {
  2227. e.getStyle().setPropertyPx("height", height);
  2228. }
  2229. return this;
  2230. }
  2231. /**
  2232. * Set the height style property of every matched element. It's useful for using 'percent' or 'em'
  2233. * units Example: $(".a").height("100%")
  2234. */
  2235. public GQuery height(String height) {
  2236. return css("height", height);
  2237. }
  2238. /**
  2239. * Make invisible all matched elements.
  2240. */
  2241. public GQuery hide() {
  2242. for (Element e : elements) {
  2243. String currentDisplay = getStyleImpl().curCSS(e, "display", false);
  2244. Object old = data(e, OLD_DISPLAY, null);
  2245. if (old == null && currentDisplay.length() != 0 && !"none".equals(currentDisplay)) {
  2246. data(e, OLD_DISPLAY, currentDisplay);
  2247. }
  2248. }
  2249. // Set the display value in a separate for loop to avoid constant reflow
  2250. // Reflows is very bad in performance point of view
  2251. for (Element e : elements) {
  2252. e.getStyle().setDisplay(Display.NONE);
  2253. }
  2254. return this;
  2255. }
  2256. /**
  2257. * Bind a function to the mouseover event of each matched element. A method for simulating
  2258. * hovering (moving the mouse on, and off, an object). This is a custom method which provides an
  2259. * 'in' to a frequent task. Whenever the mouse cursor is moved over a matched element, the first
  2260. * specified function is fired. Whenever the mouse moves off of the element, the second specified
  2261. * function fires.
  2262. *
  2263. * Since GQuery 1.4.0, this method binds handlers for both mouseenter and mouseleave events.
  2264. */
  2265. public GQuery hover(Function fover, Function fout) {
  2266. return bind("mouseenter", null, fover).bind("mouseleave", null, fout);
  2267. }
  2268. /**
  2269. * Get the innerHTML of the first matched element.
  2270. */
  2271. public String html() {
  2272. return isEmpty() ? "" : get(0).getInnerHTML();
  2273. }
  2274. /**
  2275. * Set the innerHTML of every matched element.
  2276. */
  2277. public GQuery html(String html) {
  2278. for (Element e : elements) {
  2279. if (e.getNodeType() == Node.DOCUMENT_NODE) {
  2280. e = e.<Document> cast().getBody();
  2281. }
  2282. e.setInnerHTML(html);
  2283. }
  2284. return this;
  2285. }
  2286. /**
  2287. * Get the id of the first matched element.
  2288. */
  2289. public String id() {
  2290. return attr("id");
  2291. }
  2292. /**
  2293. * Set the id of the first matched element.
  2294. */
  2295. public GQuery id(String id) {
  2296. return eq(0).attr("id", id);
  2297. }
  2298. /**
  2299. * Find the index of the specified Element.
  2300. */
  2301. public int index(Element element) {
  2302. int i = 0;
  2303. for (Element e : elements) {
  2304. if (e == element) {
  2305. return i;
  2306. }
  2307. i++;
  2308. }
  2309. return -1;
  2310. }
  2311. /**
  2312. * Return the position of the first matched element in relation with its sibblings.
  2313. */
  2314. public int index() {
  2315. return prevAll().size();
  2316. }
  2317. /**
  2318. * Returns the inner height of the first matched element, including padding but not the vertical
  2319. * scrollbar height, border, or margin.
  2320. */
  2321. public int innerHeight() {
  2322. return (int) cur("clientHeight", true);
  2323. }
  2324. /**
  2325. * Returns the inner width of the first matched element, including padding but not the vertical
  2326. * scrollbar width, border, or margin.
  2327. */
  2328. public int innerWidth() {
  2329. return (int) cur("clientWidth", true);
  2330. }
  2331. /**
  2332. * Insert all of the matched elements after another, specified, set of elements.
  2333. */
  2334. public GQuery insertAfter(Element elem) {
  2335. return insertAfter($(elem));
  2336. }
  2337. /**
  2338. * Insert all of the matched elements after another, specified, set of elements.
  2339. */
  2340. public GQuery insertAfter(GQuery query) {
  2341. for (Element e : elements) {
  2342. query.after(e);
  2343. }
  2344. return this;
  2345. }
  2346. /**
  2347. * Insert all of the matched elements after another, specified, set of elements.
  2348. */
  2349. public GQuery insertAfter(String selector) {
  2350. return insertAfter($(selector));
  2351. }
  2352. /**
  2353. * Insert all of the matched elements before another, specified, set of elements.
  2354. *
  2355. * The elements must already be inserted into the document (you can't insert an element after
  2356. * another if it's not in the page).
  2357. */
  2358. public GQuery insertBefore(Element item) {
  2359. return insertBefore($(item));
  2360. }
  2361. /**
  2362. * Insert all of the matched elements before another, specified, set of elements.
  2363. *
  2364. * The elements must already be inserted into the document (you can't insert an element after
  2365. * another if it's not in the page).
  2366. */
  2367. public GQuery insertBefore(GQuery query) {
  2368. for (Element e : elements) {
  2369. query.before(e);
  2370. }
  2371. return this;
  2372. }
  2373. /**
  2374. * Insert all of the matched elements before another, specified, set of elements.
  2375. *
  2376. * The elements must already be inserted into the document (you can't insert an element after
  2377. * another if it's not in the page).
  2378. */
  2379. public GQuery insertBefore(String selector) {
  2380. return insertBefore($(selector));
  2381. }
  2382. /**
  2383. * Checks the current selection against an expression and returns true, if at least one element of
  2384. * the selection fits the given expression. Does return false, if no element fits or the
  2385. * expression is not valid.
  2386. */
  2387. public boolean is(String... filters) {
  2388. return !filter(filters).isEmpty();
  2389. }
  2390. /**
  2391. * Returns true if the number of matched elements is 0.
  2392. */
  2393. public boolean isEmpty() {
  2394. return size() == 0;
  2395. }
  2396. /**
  2397. * Return true if the first element is visible.isVisible
  2398. */
  2399. public boolean isVisible() {
  2400. return isEmpty() ? false : getStyleImpl().isVisible(get(0));
  2401. }
  2402. /**
  2403. * Bind a set of functions to the keydown event of each matched element. Or trigger the event if
  2404. * no functions are provided.
  2405. */
  2406. public GQuery keydown(Function... f) {
  2407. return bindOrFire(Event.ONKEYDOWN, null, f);
  2408. }
  2409. /**
  2410. * Trigger a keydown event passing the key pushed.
  2411. */
  2412. public GQuery keydown(int key) {
  2413. return trigger(Event.ONKEYDOWN, key);
  2414. }
  2415. /**
  2416. * Bind a set of functions to the keypress event of each matched element. Or trigger the event if
  2417. * no functions are provided.
  2418. */
  2419. public GQuery keypress(Function... f) {
  2420. return bindOrFire(Event.ONKEYPRESS, null, f);
  2421. }
  2422. /**
  2423. * Trigger a keypress event passing the key pushed.
  2424. */
  2425. public GQuery keypress(int key) {
  2426. return trigger(Event.ONKEYPRESS, key);
  2427. }
  2428. /**
  2429. * Bind a set of functions to the keyup event of each matched element. Or trigger the event if no
  2430. * functions are provided.
  2431. */
  2432. public GQuery keyup(Function... f) {
  2433. return bindOrFire(Event.ONKEYUP, null, f);
  2434. }
  2435. /**
  2436. * Trigger a keyup event passing the key pushed.
  2437. */
  2438. public GQuery keyup(int key) {
  2439. return trigger(Event.ONKEYUP, key);
  2440. }
  2441. /**
  2442. * Reduce the set of matched elements to the final one in the set.
  2443. */
  2444. public GQuery last() {
  2445. return eq(size() - 1);
  2446. }
  2447. /**
  2448. * Returns the computed left position of the first element matched.
  2449. */
  2450. public int left() {
  2451. return (int) cur("left", true);
  2452. }
  2453. /**
  2454. * Returns the number of elements currently matched. The size function will return the same value.
  2455. */
  2456. public int length() {
  2457. return size();
  2458. }
  2459. /**
  2460. * Attach a handler for this event to all elements which match the current selector, now and in
  2461. * the future.
  2462. * @deprecated use {@link #on(String, Function...)}
  2463. */
  2464. public GQuery live(int eventbits, Function... funcs) {
  2465. return as(Events).live(eventbits, null, funcs);
  2466. }
  2467. /**
  2468. * Attach a handler for this event to all elements which match the current selector, now and in
  2469. * the future.
  2470. * @deprecated use {@link #on(String, Object, Function...)}
  2471. */
  2472. public GQuery live(int eventbits, Object data, Function... funcs) {
  2473. return as(Events).live(eventbits, data, funcs);
  2474. }
  2475. /**
  2476. * <p>
  2477. * Attach a handler for this event to all elements which match the current selector, now and in
  2478. * the future.
  2479. * <p>
  2480. * <p>
  2481. * Ex :
  2482. *
  2483. * <pre>
  2484. * $(".clickable").live("click", new Function(){
  2485. * public void f(Element e){
  2486. * $(e).css(CSS.COLOR.with(RGBColor.RED));
  2487. * }
  2488. * });
  2489. * </pre>
  2490. *
  2491. * With this code, all elements with class "clickable" present in the DOM or added to the DOM in
  2492. * the future will be clickable. The text color will be changed to red when they will be clicked.
  2493. * So if after in the code, you add another element :
  2494. *
  2495. * <pre>
  2496. * $("body").append("<div class='clickable'>Click me and I will be red</div>");
  2497. * </pre>
  2498. *
  2499. * The click on this new element will also trigger the handler.
  2500. * </p>
  2501. * <p>
  2502. * In the same way, if you add "clickable" class on some existing element, these elements will be
  2503. * clickable also.
  2504. * </p>
  2505. * <p>
  2506. * <h3>important remarks</h3>
  2507. * <ul>
  2508. * <li>
  2509. * The live method should be always called after a selector</li>
  2510. * <li>
  2511. * Live events are bound to the context of the {@link GQuery} object :
  2512. *
  2513. * <pre>
  2514. * $(".clickable", myElement).live("click", new Function(){
  2515. * public void f(Element e){
  2516. * $(e).css(CSS.COLOR.with(RGBColor.RED));
  2517. * }
  2518. * });
  2519. * </pre>
  2520. * The {@link Function} will be called only on elements having the class "clickable" and being
  2521. * descendant of myElement.</li>
  2522. * </ul>
  2523. * </p>
  2524. * @deprecated use {@link #on(String, Function...)}
  2525. */
  2526. public GQuery live(String eventName, Function... funcs) {
  2527. return as(Events).live(eventName, null, funcs);
  2528. }
  2529. /**
  2530. * <p>
  2531. * Attach a handler for this event to all elements which match the current selector, now and in
  2532. * the future. The <code>data</code> parameter allows us to pass data to the handler.
  2533. * <p>
  2534. * <p>
  2535. * Ex :
  2536. *
  2537. * <pre>
  2538. * $(".clickable").live("click", new Function(){
  2539. * public void f(Element e){
  2540. * $(e).css(CSS.COLOR.with(RGBColor.RED));
  2541. * }
  2542. * });
  2543. * </pre>
  2544. *
  2545. * With this code, all elements with class "clickable" present in the DOM or added to the DOM in
  2546. * the future will be clickable. The text color will be changed to red when they will be clicked.
  2547. * So if after in the code, you add another element :
  2548. *
  2549. * <pre>
  2550. * $("body").append("<div class='clickable'>Click me and I will be red</div>");
  2551. * </pre>
  2552. *
  2553. * The click on this new element will also trigger the handler.
  2554. * </p>
  2555. * <p>
  2556. * In the same way, if you add "clickable" class on some existing element, these elements will be
  2557. * clickable also.
  2558. * </p>
  2559. * <p>
  2560. * <h3>important remarks</h3>
  2561. * <ul>
  2562. * <li>
  2563. * The live method should be always called after a selector</li>
  2564. * <li>
  2565. * Live events are bound to the context of the {@link GQuery} object :
  2566. *
  2567. * <pre>
  2568. * $(".clickable", myElement).live("click", new Function(){
  2569. * public void f(Element e){
  2570. * $(e).css(CSS.COLOR.with(RGBColor.RED));
  2571. * }
  2572. * });
  2573. * </pre>
  2574. * The {@link Function} will be called only on elements having the class "clickable" and being
  2575. * descendant of myElement.</li>
  2576. * </ul>
  2577. * </p>
  2578. * @deprecated use {@link #on(String, Object, Function...)}
  2579. */
  2580. public GQuery live(String eventName, Object data, Function... funcs) {
  2581. return as(Events).live(eventName, data, funcs);
  2582. }
  2583. /**
  2584. * Bind a function to the load event of each matched element.
  2585. */
  2586. @Deprecated
  2587. public GQuery load(Function f) {
  2588. return bind(Event.ONLOAD, null, f);
  2589. }
  2590. /**
  2591. * Load data from the server and place the returned HTML into the matched element.
  2592. *
  2593. * The url allows us to specify a portion of the remote document to be inserted. This is achieved
  2594. * with a special syntax for the url parameter. If one or more space characters are included in
  2595. * the string, the portion of the string following the first space is assumed to be a GQuery
  2596. * selector that determines the content to be loaded.
  2597. *
  2598. */
  2599. public GQuery load(String url) {
  2600. return load(url, null, null);
  2601. }
  2602. /**
  2603. * Load data from the server and place the returned HTML into the matched element.
  2604. *
  2605. * The url allows us to specify a portion of the remote document to be inserted. This is achieved
  2606. * with a special syntax for the url parameter. If one or more space characters are included in
  2607. * the string, the portion of the string following the first space is assumed to be a GQuery
  2608. * selector that determines the content to be loaded.
  2609. *
  2610. */
  2611. public GQuery load(String url, IsProperties data, final Function onSuccess) {
  2612. return as(Ajax.Ajax).load(url, data, onSuccess);
  2613. }
  2614. /**
  2615. * Reduce the set of matched elements to all elements before a given position. The position of the
  2616. * element in the set of matched elements starts at 0 and goes to length - 1.
  2617. */
  2618. public GQuery lt(int pos) {
  2619. return slice(0, pos);
  2620. }
  2621. /**
  2622. * Pass each element in the current matched set through a function, producing a new array
  2623. * containing the return values. When the call to the function returns a null it is not added to
  2624. * the array.
  2625. */
  2626. public <W> List<W> map(Function f) {
  2627. ArrayList<W> ret = new ArrayList<W>();
  2628. int i = 0;
  2629. for (Element e : elements) {
  2630. @SuppressWarnings("unchecked")
  2631. W o = (W) f.f(e.<com.google.gwt.dom.client.Element> cast(), i++);
  2632. if (o != null) {
  2633. ret.add(o);
  2634. }
  2635. }
  2636. return ret;
  2637. }
  2638. /**
  2639. * Bind a set of functions to the mousedown event of each matched element. Or trigger the event if
  2640. * no functions are provided.
  2641. */
  2642. public GQuery mousedown(Function... f) {
  2643. return bindOrFire(Event.ONMOUSEDOWN, null, f);
  2644. }
  2645. /**
  2646. * Bind an event handler to be fired when the mouse enter an element, or trigger that handler on
  2647. * an element if no functions are provided.
  2648. *
  2649. * The mouseenter event differs from mouseover in the way it handles event bubbling. When
  2650. * mouseover is used on an element having inner element(s), then when the mouse pointer moves hover
  2651. * of the Inner element, the handler would be triggered. This is usually undesirable behavior. The
  2652. * mouseenter event, on the other hand, only triggers its handler when the mouse enters the
  2653. * element it is bound to, not a descendant.
  2654. */
  2655. public GQuery mouseenter(Function... f) {
  2656. return as(Events).mouseenter(f);
  2657. }
  2658. /**
  2659. * Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on
  2660. * an element if no functions are provided.
  2661. *
  2662. * The mouseleave event differs from mouseout in the way it handles event bubbling. When
  2663. * mouseout is used on an element having inner element(s), then when the mouse pointer moves out
  2664. * of the Inner element, the handler would be triggered. This is usually undesirable behavior. The
  2665. * mouseleave event, on the other hand, only triggers its handler when the mouse leaves the
  2666. * element it is bound to, not a descendant.
  2667. */
  2668. public GQuery mouseleave(Function... f) {
  2669. return as(Events).mouseleave(f);
  2670. }
  2671. /**
  2672. * Bind a set of functions to the mousemove event of each matched element. Or trigger the event if
  2673. * no functions are provided.
  2674. */
  2675. public GQuery mousemove(Function... f) {
  2676. return bindOrFire(Event.ONMOUSEMOVE, null, f);
  2677. }
  2678. /**
  2679. * Bind a set of functions to the mouseout event of each matched element. Or trigger the event if
  2680. * no functions are provided.
  2681. */
  2682. public GQuery mouseout(Function... f) {
  2683. return bindOrFire(Event.ONMOUSEOUT, null, f);
  2684. }
  2685. /**
  2686. * Bind a set of functions to the mouseover event of each matched element. Or trigger the event if
  2687. * no functions are provided.
  2688. */
  2689. public GQuery mouseover(Function... f) {
  2690. return bindOrFire(Event.ONMOUSEOVER, null, f);
  2691. }
  2692. /**
  2693. * Bind a set of functions to the mouseup event of each matched element. Or trigger the event if
  2694. * no functions are provided.
  2695. */
  2696. public GQuery mouseup(Function... f) {
  2697. return bindOrFire(Event.ONMOUSEUP, null, f);
  2698. }
  2699. /**
  2700. * Get a set of elements containing the unique next siblings of each of the given set of elements.
  2701. * next only returns the very next sibling for each element, not all next siblings see {#nextAll}.
  2702. */
  2703. public GQuery next() {
  2704. JsNodeArray result = JsNodeArray.create();
  2705. for (Element e : elements) {
  2706. Element next = e.getNextSiblingElement();
  2707. if (next != null) {
  2708. result.addNode(next);
  2709. }
  2710. }
  2711. return pushStack(unique(result), "next", getSelector());
  2712. }
  2713. /**
  2714. * Get a set of elements containing the unique next siblings of each of the given set of elements
  2715. * filtered by 1 or more selectors. next only returns the very next sibling for each element, not
  2716. * all next siblings see {#nextAll}.
  2717. */
  2718. public GQuery next(String... selectors) {
  2719. JsNodeArray result = JsNodeArray.create();
  2720. for (Element e : elements) {
  2721. Element next = e.getNextSiblingElement();
  2722. if (next != null) {
  2723. result.addNode(next);
  2724. }
  2725. }
  2726. return pushStack(result, "next", selectors[0]).filter(selectors);
  2727. }
  2728. /**
  2729. * Get all following siblings of each element in the set of matched elements.
  2730. */
  2731. public GQuery nextAll() {
  2732. return nextAll(null);
  2733. }
  2734. /**
  2735. * Get all following siblings of each element in the set of matched elements, filtered by a
  2736. * selector.
  2737. */
  2738. public GQuery nextAll(String filter) {
  2739. JsNodeArray result = JsNodeArray.create();
  2740. for (Element e : elements) {
  2741. allNextSiblingElements(e.getNextSiblingElement(), result, null, null, filter);
  2742. }
  2743. return pushStack(unique(result), "nextAll", getSelector());
  2744. }
  2745. /**
  2746. * Get all following siblings of each element up to but not including the element matched by the
  2747. * selector.
  2748. *
  2749. * @param selector
  2750. * @return
  2751. */
  2752. public GQuery nextUntil(String selector) {
  2753. return nextUntil($(selector), null);
  2754. }
  2755. /**
  2756. * Get all following siblings of each element up to but not including the element matched by the
  2757. * selector, filtered by a selector.
  2758. *
  2759. * @param selector
  2760. * @return
  2761. */
  2762. public GQuery nextUntil(String selector, String filter) {
  2763. return nextUntil($(selector), filter);
  2764. }
  2765. /**
  2766. * Get all following siblings of each element up to but not including the element matched by the
  2767. * DOM node.
  2768. *
  2769. * @param selector
  2770. * @return
  2771. */
  2772. public GQuery nextUntil(Element until) {
  2773. return nextUntil($(until), null);
  2774. }
  2775. /**
  2776. * Get all following siblings of each element up to but not including the element matched by the
  2777. * DOM node, filtered by a selector.
  2778. *
  2779. * @return
  2780. */
  2781. public GQuery nextUntil(Element until, String filter) {
  2782. return nextUntil($(until), filter);
  2783. }
  2784. /**
  2785. * Get all following siblings of each element up to but not including the element matched by the
  2786. * GQuery object.
  2787. *
  2788. * @return
  2789. */
  2790. public GQuery nextUntil(GQuery until) {
  2791. return nextUntil(until, null);
  2792. }
  2793. /**
  2794. * Get all following siblings of each element up to but not including the element matched by the
  2795. * GQuery object, filtered by a selector
  2796. *
  2797. * @return
  2798. */
  2799. public GQuery nextUntil(GQuery until, String filter) {
  2800. JsNodeArray result = JsNodeArray.create();
  2801. for (Element e : elements) {
  2802. allNextSiblingElements(e.getNextSiblingElement(), result, null, until, filter);
  2803. }
  2804. return pushStack(unique(result), "nextUntil", getSelector());
  2805. }
  2806. /**
  2807. * Removes the specified Element from the set of matched elements. This method is used to remove a
  2808. * single Element from a jQuery object.
  2809. */
  2810. public GQuery not(Element elem) {
  2811. JsNodeArray array = JsNodeArray.create();
  2812. for (Element e : elements) {
  2813. if (e != elem) {
  2814. array.addNode(e);
  2815. }
  2816. }
  2817. return $(array);
  2818. }
  2819. /**
  2820. * Removes any elements inside the passed set of elements from the set of matched elements.
  2821. */
  2822. public GQuery not(GQuery gq) {
  2823. GQuery ret = this;
  2824. for (Element e : gq.elements) {
  2825. ret = ret.not(e);
  2826. }
  2827. return ret;
  2828. }
  2829. /**
  2830. * Removes elements matching the specified expression from the set of matched elements.
  2831. */
  2832. public GQuery not(String... filters) {
  2833. GQuery ret = this;
  2834. for (String f : filters) {
  2835. ret = ret.not($(f));
  2836. }
  2837. return ret;
  2838. }
  2839. /**
  2840. * Get the current offset of the first matched element, in pixels, relative to the document. The
  2841. * returned object contains two integer properties, top and left. The method works only with
  2842. * visible elements.
  2843. */
  2844. public Offset offset() {
  2845. Element e = get(0);
  2846. return e == null ? new Offset(0, 0) : new Offset(e.getAbsoluteLeft(), e.getAbsoluteTop());
  2847. }
  2848. /**
  2849. * Set the current coordinates of every element in the set of matched elements, relative to the document.
  2850. */
  2851. public GQuery offset(Offset offset) {
  2852. assert offset() != null : "offset cannot be null";
  2853. return offset(offset.top, offset.left);
  2854. }
  2855. /**
  2856. * Set the current coordinates of every element in the set of matched elements, relative to the document.
  2857. */
  2858. public GQuery offset(int top, int left) {
  2859. for (Element element : elements()){
  2860. GQuery $element = $(element);
  2861. String position = $element.css("position", true);
  2862. if ("static".equals(position)) {
  2863. css("position", "relative");
  2864. }
  2865. Offset curOffset = $element.offset();
  2866. String curCSSTop = $element.css("top", true);
  2867. String curCSSLeft = $element.css("left", true);
  2868. long curTop = 0;
  2869. long curLeft = 0;
  2870. if (("absolute".equals(position) || "fixed".equals(position)) && ("auto".equals(curCSSTop) || "auto".equals
  2871. (curCSSLeft))) {
  2872. Offset curPosition = $element.position();
  2873. curTop = curPosition.top;
  2874. curLeft = curPosition.left;
  2875. } else {
  2876. try {
  2877. curTop = Long.parseLong(curCSSTop);
  2878. } catch (NumberFormatException e) {
  2879. curTop = 0;
  2880. }
  2881. try {
  2882. curLeft = Long.parseLong(curCSSLeft);
  2883. } catch (NumberFormatException e) {
  2884. curLeft = 0;
  2885. }
  2886. }
  2887. long newTop = top - curOffset.top + curTop;
  2888. long newLeft = left - curOffset.left + curLeft;
  2889. $element.css("top", "" + newTop).css("left", "" + newLeft);
  2890. }
  2891. return this;
  2892. }
  2893. /**
  2894. * Returns a GQuery collection with the positioned parent of the first matched element. This is
  2895. * the first parent of the element that has position (as in relative or absolute). This method
  2896. * only works with visible elements.
  2897. */
  2898. public GQuery offsetParent() {
  2899. if (isEmpty()) {
  2900. return $();
  2901. }
  2902. Element offParent = JsUtils.or(get(0).getOffsetParent(), body);
  2903. while (offParent != null && !"body".equalsIgnoreCase(offParent.getTagName())
  2904. && !"html".equalsIgnoreCase(offParent.getTagName())
  2905. && "static".equals(getStyleImpl().curCSS(offParent, "position", true))) {
  2906. offParent = offParent.getOffsetParent();
  2907. }
  2908. return new GQuery(offParent);
  2909. }
  2910. /**
  2911. * Attach an event handler function for one or more events to the selected elements.
  2912. */
  2913. public GQuery on(String eventName, Function... funcs) {
  2914. return bind(eventName, funcs);
  2915. }
  2916. /**
  2917. * Attach an event handler function for one or more events to the selected elements.
  2918. */
  2919. public GQuery on(String eventName, Object data, Function... funcs) {
  2920. return bind(eventName, data, funcs);
  2921. }
  2922. /**
  2923. * Attach an event handler function for one or more events to the selected elements.
  2924. */
  2925. public GQuery on(String eventName, String selector, Function... funcs) {
  2926. if (selector == null || selector.isEmpty()) {
  2927. return on(eventName, funcs);
  2928. }
  2929. return delegate(selector, eventName, funcs);
  2930. }
  2931. /**
  2932. * Attach an event handler function for one or more events to the selected elements.
  2933. */
  2934. public GQuery on(String eventName, String selector, Object data, Function... funcs) {
  2935. if (selector == null || selector.isEmpty()) {
  2936. return on(eventName, data, funcs);
  2937. }
  2938. return delegate(selector, eventName, data, funcs);
  2939. }
  2940. /**
  2941. * Remove all event handlers.
  2942. */
  2943. public GQuery off() {
  2944. return as(Events).off();
  2945. }
  2946. /**
  2947. * Remove an event handler
  2948. */
  2949. public GQuery off(String eventName) {
  2950. return unbind(eventName, null);
  2951. }
  2952. /**
  2953. * Remove an event handler
  2954. */
  2955. public GQuery off(String eventName, Function f) {
  2956. return unbind(eventName, f);
  2957. }
  2958. /**
  2959. * Remove an event handler
  2960. */
  2961. public GQuery off(String eventName, String selector) {
  2962. if (selector == null || selector.isEmpty()) {
  2963. return off(eventName);
  2964. }
  2965. return undelegate(selector, eventName);
  2966. }
  2967. /**
  2968. * Binds a handler to a particular Event (like Event.ONCLICK) for each matched element. The
  2969. * handler is executed only once for each element.
  2970. *
  2971. * The event handler is passed as a Function that you can use to prevent default behavior. To stop
  2972. * both default action and event bubbling, the function event handler has to return false.
  2973. *
  2974. * You can pass an additional Object data to your Function as the second parameter
  2975. */
  2976. public GQuery one(int eventbits, final Object data, final Function f) {
  2977. return as(Events).one(eventbits, data, f);
  2978. }
  2979. /**
  2980. * Get the current computed height for the first element in the set of matched elements, including
  2981. * padding, border, but not the margin.
  2982. */
  2983. public int outerHeight() {
  2984. return outerHeight(false);
  2985. }
  2986. /**
  2987. * Get the current computed height for the first element in the set of matched elements, including
  2988. * padding, border, and optionally margin.
  2989. */
  2990. public int outerHeight(boolean includeMargin) {
  2991. if (isEmpty()) {
  2992. return 0;
  2993. }
  2994. // height including padding and border
  2995. int outerHeight = (int)cur("offsetHeight", true);
  2996. if (includeMargin) {
  2997. outerHeight += cur("marginTop", true) + cur("marginBottom", true);
  2998. }
  2999. return outerHeight;
  3000. }
  3001. /**
  3002. * Get the current computed width for the first element in the set of matched elements, including
  3003. * padding, border, but not the margin.
  3004. */
  3005. public int outerWidth() {
  3006. return outerWidth(false);
  3007. }
  3008. /**
  3009. * Get the current computed width for the first element in the set of matched elements, including
  3010. * padding and border and optionally margin.
  3011. */
  3012. public int outerWidth(boolean includeMargin) {
  3013. if (isEmpty()) {
  3014. return 0;
  3015. }
  3016. // width including padding and border
  3017. int outerWidth = (int)cur("offsetWidth", true);
  3018. if (includeMargin) {
  3019. outerWidth += cur("marginRight", true) + cur("marginLeft", true);
  3020. }
  3021. return outerWidth;
  3022. }
  3023. /**
  3024. * Get a set of elements containing the unique parents of the matched set of elements.
  3025. */
  3026. public GQuery parent() {
  3027. JsNodeArray result = JsNodeArray.create();
  3028. for (Element e : elements) {
  3029. Element p = e.getParentElement();
  3030. if (p != null) {
  3031. result.addNode(p);
  3032. }
  3033. }
  3034. return new GQuery(unique(result));
  3035. }
  3036. /**
  3037. * Get a set of elements containing the unique parents of the matched set of elements. You may use
  3038. * an optional expressions to filter the set of parent elements that will match one of them.
  3039. */
  3040. public GQuery parent(String... filters) {
  3041. return parent().filter(filters);
  3042. }
  3043. /**
  3044. * Get a set of elements containing the unique ancestors of the matched set of elements (except
  3045. * for the root element).
  3046. */
  3047. public GQuery parents() {
  3048. return parentsUntil((String) null);
  3049. }
  3050. /**
  3051. * Get a set of elements containing the unique ancestors of the matched set of elements (except
  3052. * for the root element). The matched elements are filtered, returning those that match any of the
  3053. * filters.
  3054. */
  3055. public GQuery parents(String... filters) {
  3056. return parents().filter(filters);
  3057. }
  3058. /**
  3059. * Get the ancestors of each element in the current set of matched elements, up to but not
  3060. * including the element matched by the selector.
  3061. */
  3062. public GQuery parentsUntil(final String selector) {
  3063. return parentsUntil(new Predicate(){
  3064. @Override
  3065. public <T> boolean f(T e, int index) {
  3066. return selector != null && $(e).is(selector);
  3067. }
  3068. });
  3069. }
  3070. /**
  3071. * Get the ancestors of each element in the current set of matched elements, up to but not
  3072. * including the node.
  3073. */
  3074. public GQuery parentsUntil(final Node node) {
  3075. return parentsUntil(new Predicate() {
  3076. @Override
  3077. public <T> boolean f(T e, int index) {
  3078. return node != null && e == node;
  3079. }
  3080. });
  3081. }
  3082. private GQuery parentsUntil(Predicate predicate) {
  3083. JsNodeArray result = JsNodeArray.create();
  3084. for (Element e : elements) {
  3085. int i = 0;
  3086. Node par = e.getParentNode();
  3087. while (par != null && par != document) {
  3088. if (predicate.f(par, i)) {
  3089. break;
  3090. }
  3091. result.addNode(par);
  3092. par = par.getParentNode();
  3093. i++;
  3094. }
  3095. }
  3096. return new GQuery(unique(result)).setPreviousObject(this);
  3097. }
  3098. /**
  3099. * Gets the top and left position of an element relative to its offset parent. The returned object
  3100. * contains two Integer properties, top and left. For accurate calculations make sure to use pixel
  3101. * values for margins, borders and padding. This method only works with visible elements.
  3102. */
  3103. public Offset position() {
  3104. if (isEmpty()) {
  3105. return new Offset(0, 0);
  3106. }
  3107. Element element = get(0);
  3108. // Get *real* offsetParent
  3109. Element offsetParent = get(0).getOffsetParent();
  3110. // Get correct offsets
  3111. Offset offset = offset();
  3112. Offset parentOffset = null;
  3113. if (offsetParent == body || offsetParent == (Node) document) {
  3114. parentOffset = new Offset(0, 0);
  3115. } else {
  3116. parentOffset = $(offsetParent).offset();
  3117. }
  3118. // Subtract element margins
  3119. int topMargin = (int) getStyleImpl().cur(element, "marginTop", true);
  3120. // TODO: move this check to getStyleImpl()
  3121. // When margin-left = auto, Safari and chrome return a value while IE and
  3122. // Firefox return 0
  3123. // force the margin-left to 0 if margin-left = auto.
  3124. int leftMargin = 0;
  3125. if (!"auto".equals(element.getStyle().getMarginLeft())) {
  3126. leftMargin = (int) getStyleImpl().cur(element, "marginLeft", true);
  3127. }
  3128. offset = offset.add(-leftMargin, -topMargin);
  3129. // Add offsetParent borders
  3130. int parentOffsetBorderTop = (int) getStyleImpl().cur(offsetParent, "borderTopWidth", true);
  3131. int parentOffsetBorderLeft = (int) getStyleImpl().cur(offsetParent, "borderLeftWidth", true);
  3132. parentOffset = parentOffset.add(parentOffsetBorderLeft, parentOffsetBorderTop);
  3133. // Subtract the two offsets
  3134. return offset.add(-parentOffset.left, -parentOffset.top);
  3135. }
  3136. /**
  3137. * Prepend content to the inside of every matched element. This operation is the best way to
  3138. * insert elements inside, at the beginning, of all matched elements.
  3139. */
  3140. public GQuery prepend(GQuery query) {
  3141. return domManip(query, DomMan.PREPEND);
  3142. }
  3143. /**
  3144. * Prepend content to the inside of every matched element. This operation is the best way to
  3145. * insert elements inside, at the beginning, of all matched elements.
  3146. */
  3147. public GQuery prepend(Node n) {
  3148. return domManip($(n), DomMan.PREPEND);
  3149. }
  3150. /**
  3151. * Prepend content to the inside of every matched element. This operation is the best way to
  3152. * insert elements inside, at the beginning, of all matched elements.
  3153. */
  3154. public GQuery prepend(String html) {
  3155. return domManip(html, DomMan.PREPEND);
  3156. }
  3157. /**
  3158. * All of the matched set of elements will be inserted at the beginning of the element(s)
  3159. * specified by the parameter other.
  3160. *
  3161. * The operation $(A).prependTo(B) is, essentially, the reverse of doing a regular
  3162. * $(A).prepend(B), instead of prepending B to A, you're prepending A to B.
  3163. */
  3164. public GQuery prependTo(GQuery other) {
  3165. other.prepend(this);
  3166. return this;
  3167. }
  3168. /**
  3169. * All of the matched set of elements will be inserted at the beginning of the element(s)
  3170. * specified by the parameter other.
  3171. *
  3172. * The operation $(A).prependTo(B) is, essentially, the reverse of doing a regular
  3173. * $(A).prepend(B), instead of prepending B to A, you're prepending A to B.
  3174. */
  3175. public GQuery prependTo(Node n) {
  3176. $(n).prepend(this);
  3177. return this;
  3178. }
  3179. /**
  3180. * All of the matched set of elements will be inserted at the beginning of the element(s)
  3181. * specified by the parameter other.
  3182. *
  3183. * The operation $(A).prependTo(B) is, essentially, the reverse of doing a regular
  3184. * $(A).prepend(B), instead of prepending B to A, you're prepending A to B.
  3185. */
  3186. public GQuery prependTo(String html) {
  3187. $(html).prepend(this);
  3188. return this;
  3189. }
  3190. /**
  3191. * Get a set of elements containing the unique previous siblings of each of the matched set of
  3192. * elements. Only the immediately previous sibling is returned, not all previous siblings.
  3193. */
  3194. public GQuery prev() {
  3195. JsNodeArray result = JsNodeArray.create();
  3196. for (Element e : elements) {
  3197. Element next = getPreviousSiblingElement(e);
  3198. if (next != null) {
  3199. result.addNode(next);
  3200. }
  3201. }
  3202. return new GQuery(unique(result));
  3203. }
  3204. /**
  3205. * Get a set of elements containing the unique previous siblings of each of the matched set of
  3206. * elements filtered by selector. Only the immediately previous sibling is returned, not all
  3207. * previous siblings.
  3208. */
  3209. public GQuery prev(String... selectors) {
  3210. JsNodeArray result = JsNodeArray.create();
  3211. for (Element e : elements) {
  3212. Element next = getPreviousSiblingElement(e);
  3213. if (next != null) {
  3214. result.addNode(next);
  3215. }
  3216. }
  3217. return new GQuery(unique(result)).filter(selectors);
  3218. }
  3219. /**
  3220. * Get all preceding siblings of each element in the set of matched elements.
  3221. */
  3222. public GQuery prevAll() {
  3223. return prevAll(null);
  3224. }
  3225. /**
  3226. * Get all preceding siblings of each element in the set of matched elements filtered by a
  3227. * selector.
  3228. */
  3229. public GQuery prevAll(String selector) {
  3230. JsNodeArray result = JsNodeArray.create();
  3231. for (Element e : elements) {
  3232. allPreviousSiblingElements(getPreviousSiblingElement(e), result, null, selector);
  3233. }
  3234. return pushStack(unique(result), "prevAll", getSelector());
  3235. }
  3236. /**
  3237. * Get all preceding siblings of each element up to but not including the element matched by the
  3238. * <code>selector</code>.
  3239. *
  3240. * The elements are returned in order from the closest sibling to the farthest.
  3241. */
  3242. public GQuery prevUntil(String selector) {
  3243. return prevUntil($(selector), null);
  3244. }
  3245. /**
  3246. * Get all preceding siblings of each element up to but not including the <code>until</code>
  3247. * element.
  3248. *
  3249. * The elements are returned in order from the closest sibling to the farthest.
  3250. */
  3251. public GQuery prevUntil(Element until) {
  3252. return prevUntil($(until), null);
  3253. }
  3254. /**
  3255. * Get all preceding siblings of each element up to but not including the <code>until</code>
  3256. * element.
  3257. *
  3258. * The elements are returned in order from the closest sibling to the farthest.
  3259. */
  3260. public GQuery prevUntil(GQuery until) {
  3261. return prevUntil(until, null);
  3262. }
  3263. /**
  3264. * Get all preceding siblings of each element matching the <code>filter</code> up to but not
  3265. * including the element matched by the <code>selector</code>.
  3266. *
  3267. * The elements are returned in order from the closest sibling to the farthest.
  3268. */
  3269. public GQuery prevUntil(String selector, String filter) {
  3270. return prevUntil($(selector), filter);
  3271. }
  3272. /**
  3273. * Get all preceding siblings of each element matching the <code>filter</code> up to but not
  3274. * including the <code>until</code> element.
  3275. *
  3276. */
  3277. public GQuery prevUntil(Element until, String filter) {
  3278. return prevUntil($(until), filter);
  3279. }
  3280. /**
  3281. * Get all preceding siblings of each element matching the <code>filter</code> up to but not
  3282. * including the element matched by the <code>until</code> element.
  3283. *
  3284. */
  3285. public GQuery prevUntil(GQuery until, String filter) {
  3286. JsNodeArray result = JsNodeArray.create();
  3287. for (Element e : elements) {
  3288. allPreviousSiblingElements(getPreviousSiblingElement(e), result, until, filter);
  3289. }
  3290. return pushStack(unique(result), "prevUntil", getSelector());
  3291. }
  3292. /**
  3293. * Returns a dynamically generated Promise that is resolved once all actions
  3294. * in the queue have ended.
  3295. */
  3296. public Promise promise() {
  3297. return as(Queue).promise();
  3298. }
  3299. /**
  3300. * Returns a dynamically generated Promise that is resolved once all actions
  3301. * in the named queue have ended.
  3302. */
  3303. public Promise promise(String name) {
  3304. return as(Queue).promise(name);
  3305. }
  3306. /**
  3307. * Get the value of a property for the first element in the set of matched elements.
  3308. *
  3309. * @param key the name of the property to be accessed
  3310. * @return the value of the property, in the case the property is a 'boolean' it
  3311. * returns a Boolean object, and a Double if is a 'number', so be prepared
  3312. * if you cast to other numeric objects. In the case of the property is undefined
  3313. * it returns null.
  3314. */
  3315. public <T> T prop(String key) {
  3316. assert key != null : "Key is null";
  3317. return isEmpty() ? null : JsUtils.<T>prop(get(0), key);
  3318. }
  3319. /**
  3320. * Get the value of a property for the first element in the set of matched elements.
  3321. *
  3322. * @param key the name of the property to be accessed
  3323. * @param clz the class of the type to return
  3324. *
  3325. * @return the value of the property, it safely check the type passed as parameter
  3326. * and preform the aproproate transformations for numbers and booleans.
  3327. * In the case of the property is undefined it returns null.
  3328. */
  3329. public <T> T prop(String key, Class<? extends T> clz) {
  3330. assert key != null : "Key is null";
  3331. return isEmpty() ? null : JsUtils.<T>prop(get(0), key, clz);
  3332. }
  3333. /**
  3334. * Sets a property to a value on all matched elements.
  3335. *
  3336. * @param key the name of the boolean property to be set
  3337. * @param value the value specified. In the case the value is a Number, it is set
  3338. * as a 'number' in the javascript object and the same with Boolean.
  3339. *
  3340. * @return this <code>GQuery</code> object
  3341. *
  3342. */
  3343. public GQuery prop(String key, Object value) {
  3344. assert key != null : "Key is null";
  3345. for (Element e : elements) {
  3346. JsUtils.prop(e, key, value);
  3347. }
  3348. return this;
  3349. }
  3350. /**
  3351. * Sets a boolean property to a computed value on all matched elements.
  3352. *
  3353. * @param key the name of the boolean property to be set
  3354. * @param closure the closure to be used to compute the value the specified boolean property
  3355. * should be set to; the <code>closure</code> is
  3356. * {@linkplain Function#f(com.google.gwt.dom.client.Element, int) passed} the target
  3357. * element and its index as arguments and is expected to return either a
  3358. * <code>Boolean</code> value or an object whose textual representation is converted to a
  3359. * <code>Boolean</code> value; <code>null</code> return values are ignored
  3360. *
  3361. * @return this <code>GQuery</code> object
  3362. *
  3363. */
  3364. public GQuery prop(String key, Function closure) {
  3365. assert key != null : "Key is null";
  3366. assert closure != null : "Closure is null";
  3367. int i = 0;
  3368. for (Element e : elements) {
  3369. Object value = closure.f(e, i++);
  3370. JsUtils.prop(e, key, value);
  3371. }
  3372. return this;
  3373. }
  3374. protected GQuery pushStack(JsNodeArray elts, String name, String selector) {
  3375. GQuery g = new GQuery(elts);
  3376. g.setPreviousObject(this);
  3377. g.setSelector(selector);
  3378. g.currentContext = currentContext;
  3379. return g;
  3380. }
  3381. /**
  3382. * Show the number of functions in the efects queue to be executed on the first matched element.
  3383. */
  3384. public int queue() {
  3385. return as(Queue).queue();
  3386. }
  3387. /**
  3388. * Put a set of {@link Function} at the end of the Effects queue.
  3389. *
  3390. * Example:
  3391. *
  3392. * <pre class="code">
  3393. * $("#foo").animate("left:'+=500'", 400)
  3394. * .queue(new Function(){
  3395. * public void f(Element e){
  3396. * $(e).css(CSS.BACKGROUNG_COLOR.with(RGBColor.RED));
  3397. * $(e).dequeue();
  3398. * }
  3399. * })
  3400. * .animate("left:'-=500'", 400)
  3401. * .queue(lazy().css("color", "yellow");
  3402. *
  3403. * </pre>
  3404. *
  3405. * When this statement is executed, the element move to 500 px to left for 400 ms, then its
  3406. * background color is changed to red and then move to 500px to right for 400ms, and finally its
  3407. * color is set to yellow.
  3408. *
  3409. * Please note that {@link #dequeue()} function is needed at the end of your function to start the
  3410. * next function in the queue. In lazy() methods you should call dequeue() just before the done()
  3411. * call. {@see #dequeue()}
  3412. */
  3413. public GQuery queue(Function... f) {
  3414. return as(Queue).queue(f);
  3415. }
  3416. /**
  3417. * Show the number of functions in the queued named as queueName to be executed on the first
  3418. * matched element.
  3419. */
  3420. public int queue(String queueName) {
  3421. return as(Queue).queue(queueName);
  3422. }
  3423. /**
  3424. * Put a set of {@link Function} at the end of a queue.
  3425. *
  3426. * Example:
  3427. *
  3428. * <pre class="code">
  3429. * $("#foo").queue("myQueue", new Function(){
  3430. * public void f(Element e){
  3431. * $(e).css(CSS.BACKGROUNG_COLOR.with(RGBColor.RED));
  3432. * dequeue("myQueue");
  3433. * }
  3434. * })
  3435. * .delay(500, "myQueue")
  3436. * .queue("myQueue", lazy().css(CSS.COLOR.with(RGBColor.YELLOW)).dequeue("myQueue").done());
  3437. * </pre>
  3438. *
  3439. * When this statement is executed, the background color of the element is set to red, then wait
  3440. * 500ms before to set the text color of the element to yellow. right for 400ms.
  3441. *
  3442. * Please note that {@link #dequeue()} function is needed at the end of your function to start the
  3443. * next function in the queue. In lazy() methods you should call dequeue() just before the done()
  3444. * call. {@see #dequeue()}
  3445. */
  3446. public GQuery queue(String queueName, Function... f) {
  3447. return as(Queue).queue(queueName, f);
  3448. }
  3449. /**
  3450. * Removes all matched elements from the DOM.
  3451. */
  3452. public GQuery remove() {
  3453. return remove(null, true);
  3454. }
  3455. /**
  3456. * Removes from the DOM all matched elements filtered by the <code>filter</code>.
  3457. */
  3458. public GQuery remove(String filter) {
  3459. return remove(filter, true);
  3460. }
  3461. /**
  3462. * Removes all matched elements from the DOM and cleans their data and bound events if the value
  3463. * of <code>clean</code> parameter is set to true. The <code> filter</code> parameter allows to
  3464. * filter the matched set to remove.
  3465. */
  3466. protected GQuery remove(String filter, boolean clean) {
  3467. for (Element e : elements) {
  3468. if (filter == null || $(e).filter(filter).length() == 1) {
  3469. if (clean) {
  3470. // clean data linked to the children
  3471. // TODO: "*" fails in queryselectorall (webkit mobile)
  3472. cleanGQData($("*", e).elements());
  3473. // clean data linked to the element itself
  3474. cleanGQData(e);
  3475. }
  3476. Widget w = getAssociatedWidget(e);
  3477. if (w != null) {
  3478. w.removeFromParent();
  3479. } else {
  3480. e.removeFromParent();
  3481. }
  3482. }
  3483. }
  3484. return this;
  3485. }
  3486. /**
  3487. * Remove the named attribute from every element in the matched set.
  3488. */
  3489. public GQuery removeAttr(String key) {
  3490. getAttributeImpl().removeAttribute(this, key);
  3491. return this;
  3492. }
  3493. /**
  3494. * Removes the specified classes to each matched element.
  3495. *
  3496. * If no arguments are provided, it removes all classes like jquery does.
  3497. */
  3498. public GQuery removeClass(String... classes) {
  3499. for (Element e : elements) {
  3500. if (Element.is(e)) {
  3501. if (classes.length == 0) {
  3502. e.setClassName(null);
  3503. } else {
  3504. for (String clz : classes) {
  3505. e.removeClassName(clz);
  3506. }
  3507. }
  3508. }
  3509. }
  3510. return this;
  3511. }
  3512. protected void removeData(Element item, String name) {
  3513. if (dataCache == null) {
  3514. windowData = JavaScriptObject.createObject().cast();
  3515. dataCache = JavaScriptObject.createObject().cast();
  3516. }
  3517. item = item == window || item.getNodeName() == null ? windowData : item;
  3518. int id = item.hashCode();
  3519. if (name != null) {
  3520. if (dataCache.exists(id)) {
  3521. dataCache.getCache(id).delete(name);
  3522. if (dataCache.getCache(id).isEmpty()) {
  3523. // Save memory
  3524. removeData(item, null);
  3525. }
  3526. }
  3527. } else {
  3528. // when the element cache is empty we remove its entry to save memory (issue 132)
  3529. dataCache.delete(id);
  3530. }
  3531. }
  3532. /**
  3533. * Removes named data store from an element.
  3534. */
  3535. public GQuery removeData(String name) {
  3536. for (Element e : elements) {
  3537. removeData(e, name);
  3538. }
  3539. return this;
  3540. }
  3541. /**
  3542. * Remove a property for the set of matched elements.
  3543. */
  3544. public GQuery removeProp(String name) {
  3545. for (Element e : elements) {
  3546. e.<JsCache>cast().delete(name);
  3547. }
  3548. return this;
  3549. }
  3550. /**
  3551. * Replaces the element <code>elem</code> by the specified selector with the matched elements.
  3552. * This function is the complement to replaceWith() which does the same task with the parameters
  3553. * reversed.
  3554. *
  3555. * @return a {@link GQuery} object containing the new elements.
  3556. */
  3557. public GQuery replaceAll(Element elem) {
  3558. return replaceAll($(elem));
  3559. }
  3560. /**
  3561. * Replaces the elements matched by the target with the selected elements. This function is the
  3562. * complement to replaceWith() which does the same task with the parameters reversed.
  3563. *
  3564. * @return a {@link GQuery} object containing the new elements.
  3565. */
  3566. public GQuery replaceAll(GQuery target) {
  3567. // if there is only one element and it is not attached to the dom, we have
  3568. // to clone it to be reused on each element of target (if target contains
  3569. // more than one element)
  3570. boolean mustBeCloned = length() == 1 && parents().filter("body").length() == 0;
  3571. List<Element> newElements = new ArrayList<Element>();
  3572. for (int i = 0, l = target.size(); i < l; i++) {
  3573. GQuery _this = (i > 0 && mustBeCloned) ? this.clone() : this;
  3574. $(target.get(i)).replaceWith(_this);
  3575. newElements.addAll(Arrays.asList(_this.elements));
  3576. }
  3577. return $(newElements);
  3578. }
  3579. /**
  3580. * Replaces the elements matched by the specified selector with the matched elements. This
  3581. * function is the complement to replaceWith() which does the same task with the parameters
  3582. * reversed.
  3583. *
  3584. * @return a {@link GQuery} object containing the new elements.
  3585. */
  3586. public GQuery replaceAll(String selector) {
  3587. return replaceAll($(selector));
  3588. }
  3589. /**
  3590. * Replaces all matched elements with the specified element.
  3591. *
  3592. * @return the GQuery element that was just replaced, which has been removed from the DOM and not
  3593. * the new element that has replaced it.
  3594. */
  3595. public GQuery replaceWith(Element elem) {
  3596. return replaceWith($(elem));
  3597. }
  3598. /**
  3599. * Replaces all matched elements with elements selected by <code>target</code> .
  3600. *
  3601. * @return the GQuery element that was just replaced, which has been removed from the DOM and not
  3602. * the new element that has replaced it.
  3603. */
  3604. public GQuery replaceWith(GQuery target) {
  3605. for (Element el : elements) {
  3606. Element nextSibling = el.getNextSiblingElement();
  3607. if (nextSibling != null) {
  3608. $(nextSibling).before(target);
  3609. } else {
  3610. Element parent = el.getParentElement();
  3611. $(parent).append(target);
  3612. }
  3613. $(el).remove();
  3614. }
  3615. return this;
  3616. }
  3617. /**
  3618. * Replaces all matched elements with the specified HTML.
  3619. *
  3620. * @return the GQuery element that was just replaced, which has been removed from the DOM and not
  3621. * the new element that has replaced it.
  3622. */
  3623. public GQuery replaceWith(String html) {
  3624. for (Element el : elements) {
  3625. Element nextSibling = el.getNextSiblingElement();
  3626. if (nextSibling != null) {
  3627. $(nextSibling).before(html);
  3628. } else {
  3629. Element parent = el.getParentElement();
  3630. $(parent).append(html);
  3631. }
  3632. $(el).remove();
  3633. }
  3634. return this;
  3635. }
  3636. /**
  3637. * Bind a set of functions to the resize event of each matched element, or tigger the resize event
  3638. * if no functions are provided.
  3639. *
  3640. * Note that although all elements can be configured to handle resize events, by default only
  3641. * window will trigger it when it is resized, for an arbitrary element you have to trigger the
  3642. * event after resizing the object.
  3643. *
  3644. */
  3645. public GQuery resize(Function... f) {
  3646. return bindOrFire("resize", null, f);
  3647. }
  3648. /**
  3649. * Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.
  3650. */
  3651. public GQuery resize(final Function f) {
  3652. return bindOrFire("resize", null, f);
  3653. }
  3654. /**
  3655. * Save a set of Css properties of every matched element.
  3656. */
  3657. public void restoreCssAttrs(String... cssProps) {
  3658. for (Element e : elements) {
  3659. for (String a : cssProps) {
  3660. String datakey = OLD_DATA_PREFIX + a;
  3661. getStyleImpl().setStyleProperty(e, a, (String) data(e, datakey, null));
  3662. removeData(e, datakey);
  3663. }
  3664. }
  3665. }
  3666. /**
  3667. * Restore a set of previously saved Css properties in every matched element.
  3668. */
  3669. public void saveCssAttrs(String... cssProps) {
  3670. for (Element e : elements) {
  3671. for (String a : cssProps) {
  3672. data(OLD_DATA_PREFIX + a, getStyleImpl().curCSS(e, a, false));
  3673. }
  3674. }
  3675. }
  3676. /**
  3677. * Bind a set of functions to the scroll event of each matched element. Or trigger the event if no
  3678. * functions are provided.
  3679. */
  3680. public GQuery scroll(Function... f) {
  3681. return bindOrFire(Event.ONSCROLL, null, f);
  3682. }
  3683. /**
  3684. * Scrolls the first matched element into view.
  3685. */
  3686. public GQuery scrollIntoView() {
  3687. if (!isEmpty())
  3688. scrollIntoViewImpl(get(0));
  3689. return this;
  3690. }
  3691. /**
  3692. * Scrolls the first matched element into view.
  3693. *
  3694. * If ensure == true, it crawls up the DOM hierarchy, adjusting the scrollLeft and scrollTop
  3695. * properties of each scroll-able element to ensure that the specified element is completely in
  3696. * view. It adjusts each scroll position by the minimum amount necessary.
  3697. */
  3698. public GQuery scrollIntoView(boolean ensure) {
  3699. if (!isEmpty() && ensure) {
  3700. DOM.scrollIntoView((com.google.gwt.user.client.Element) get(0));
  3701. } else {
  3702. scrollIntoView();
  3703. }
  3704. return this;
  3705. }
  3706. /**
  3707. * Gets the scroll left offset of the first matched element. This method works for both visible
  3708. * and hidden elements.
  3709. */
  3710. public int scrollLeft() {
  3711. Element e = get(0);
  3712. if (e == null) {
  3713. return 0;
  3714. }
  3715. if (e == window || e.getNodeName() == null) {
  3716. return Window.getScrollLeft();
  3717. } else if (e == (Node) document) {
  3718. return document.getScrollLeft();
  3719. } else {
  3720. return e.getScrollLeft();
  3721. }
  3722. }
  3723. /**
  3724. * The scroll left offset is set to the passed value on all matched elements. This method works
  3725. * for both visible and hidden elements.
  3726. */
  3727. public GQuery scrollLeft(int left) {
  3728. for (Element e : elements) {
  3729. if (e == window || e.getNodeName() == null || e == (Node) document) {
  3730. Window.scrollTo(left, $(e).scrollTop());
  3731. } else {
  3732. e.setPropertyInt("scrollLeft", left);
  3733. }
  3734. }
  3735. return this;
  3736. }
  3737. /**
  3738. *
  3739. * Scrolls the contents of all matched elements to the specified co-ordinate becoming the top left
  3740. * corner of the viewable area.
  3741. *
  3742. * This method is only useful where there are areas of the document not viewable within the
  3743. * current viewable area of the window and the visible property of the window's scrollbar must be
  3744. * set to true.
  3745. *
  3746. */
  3747. public GQuery scrollTo(int left, int top) {
  3748. scrollLeft(left).scrollTop(top);
  3749. return this;
  3750. }
  3751. /**
  3752. * Gets the scroll top offset of the first matched element. This method works for both visible and
  3753. * hidden elements.
  3754. */
  3755. public int scrollTop() {
  3756. Element e = get(0);
  3757. if (e == null) {
  3758. return 0;
  3759. }
  3760. if (e == window || e.getNodeName() == null) {
  3761. return Window.getScrollTop();
  3762. } else if (e == (Node) document) {
  3763. return document.getScrollTop();
  3764. } else {
  3765. return e.getScrollTop();
  3766. }
  3767. }
  3768. /**
  3769. * The scroll top offset is set to the passed value on all matched elements. This method works for
  3770. * both visible and hidden elements.
  3771. */
  3772. public GQuery scrollTop(int top) {
  3773. for (Element e : elements) {
  3774. if (e == window || e.getNodeName() == null || e == (Node) document) {
  3775. Window.scrollTo($(e).scrollLeft(), top);
  3776. } else {
  3777. e.setPropertyInt("scrollTop", top);
  3778. }
  3779. }
  3780. return this;
  3781. }
  3782. public GQuery select() {
  3783. return as(Events).triggerHtmlEvent("select");
  3784. }
  3785. private GQuery select(String selector, Node context) {
  3786. NodeList<Element> n = getSelectorEngine().select(selector, context == null ? document :
  3787. context);
  3788. currentSelector = selector;
  3789. currentContext = context != null ? context : document;
  3790. return setArray(n);
  3791. }
  3792. /**
  3793. * Force the current matched set of elements to become the specified array of elements.
  3794. */
  3795. public GQuery setArray(NodeList<Element> list) {
  3796. if (list != null) {
  3797. nodeList.<JsCache> cast().clear();
  3798. int l = list.getLength();
  3799. elements = new Element[l];
  3800. for (int i = 0; i < l; i++) {
  3801. elements[i] = list.getItem(i);
  3802. nodeList.<JsObjectArray<Element>> cast().add(list.getItem(i));
  3803. }
  3804. }
  3805. return this;
  3806. }
  3807. public GQuery setPreviousObject(GQuery previousObject) {
  3808. this.previousObject = previousObject;
  3809. return this;
  3810. }
  3811. public GQuery setSelector(String selector) {
  3812. this.currentSelector = selector;
  3813. return this;
  3814. }
  3815. /**
  3816. * Make all matched elements visible
  3817. */
  3818. public GQuery show() {
  3819. for (Element e : elements) {
  3820. String currentDisplay = e.getStyle().getDisplay();
  3821. String oldDisplay = (String) data(e, OLD_DISPLAY, null);
  3822. // reset the display
  3823. if (oldDisplay == null && "none".equals(currentDisplay)) {
  3824. getStyleImpl().setStyleProperty(e, "display", "");
  3825. currentDisplay = "";
  3826. }
  3827. // check if the stylesheet impose display: none. If it is the case, determine
  3828. // the default display for the tag and store it at the element level
  3829. if ("".equals(currentDisplay) && !getStyleImpl().isVisible(e)) {
  3830. data(e, OLD_DISPLAY, getStyleImpl().defaultDisplay(e.getNodeName()));
  3831. }
  3832. }
  3833. // set the display value in a separate for loop to avoid constant reflow
  3834. // because broswer reflow is triggered each time we gonna set and after get (in
  3835. // isVisibleProperty() method)
  3836. // the diplay property. Reflows is very bad in performance point of view
  3837. for (Element e : elements) {
  3838. String currentDisplay = e.getStyle().getDisplay();
  3839. if ("".equals(currentDisplay) || "none".equals(currentDisplay)) {
  3840. getStyleImpl().setStyleProperty(e, "display",
  3841. JsUtils.or((String) data(e, OLD_DISPLAY, null), ""));
  3842. }
  3843. }
  3844. removeData(OLD_DISPLAY);
  3845. return this;
  3846. }
  3847. /**
  3848. * Get a set of elements containing all of the unique siblings of each of the matched set of
  3849. * elements.
  3850. */
  3851. public GQuery siblings() {
  3852. JsNodeArray result = JsNodeArray.create();
  3853. for (Element e : elements) {
  3854. allNextSiblingElements(e.getParentElement().getFirstChildElement(), result, e, null, null);
  3855. }
  3856. return new GQuery(unique(result));
  3857. }
  3858. /**
  3859. * Get a set of elements containing all of the unique siblings of each of the matched set of
  3860. * elements filtered by the provided set of selectors.
  3861. */
  3862. public GQuery siblings(String... selectors) {
  3863. return siblings().filter(selectors);
  3864. }
  3865. /**
  3866. * Return the number of elements in the matched set.
  3867. */
  3868. public int size() {
  3869. return elements.length;
  3870. }
  3871. /**
  3872. * Selects a subset of the matched elements.
  3873. */
  3874. public GQuery slice(int start, int end) {
  3875. JsNodeArray slice = JsNodeArray.create();
  3876. int l = size();
  3877. if (end == -1 || end > l) {
  3878. end = l;
  3879. }
  3880. for (int i = start; i < end; i++) {
  3881. slice.addNode(get(i));
  3882. }
  3883. return new GQuery(slice);
  3884. }
  3885. /**
  3886. * Reveal all matched elements by adjusting their height and firing an optional callback after
  3887. * completion.
  3888. */
  3889. public Effects slideDown(Function... f) {
  3890. return as(Effects).slideDown(f);
  3891. }
  3892. /**
  3893. * Reveal all matched elements by adjusting their height and firing an optional callback after
  3894. * completion.
  3895. */
  3896. public Effects slideDown(int millisecs, Function... f) {
  3897. return as(Effects).slideDown(millisecs, f);
  3898. }
  3899. /**
  3900. * Toggle the visibility of all matched elements by adjusting their height and firing an optional
  3901. * callback after completion. Only the height is adjusted for this animation, causing all matched
  3902. * elements to be hidden or shown in a "sliding" manner
  3903. */
  3904. public Effects slideToggle(Function... f) {
  3905. return as(Effects).slideToggle(f);
  3906. }
  3907. /**
  3908. * Toggle the visibility of all matched elements by adjusting their height and firing an optional
  3909. * callback after completion. Only the height is adjusted for this animation, causing all matched
  3910. * elements to be hidden or shown in a "sliding" manner
  3911. */
  3912. public Effects slideToggle(int millisecs, Function... f) {
  3913. return as(Effects).slideToggle(millisecs, f);
  3914. }
  3915. /**
  3916. * Hide all matched elements by adjusting their height and firing an optional callback after
  3917. * completion.
  3918. */
  3919. public Effects slideUp(Function... f) {
  3920. return as(Effects).slideUp(f);
  3921. }
  3922. /**
  3923. * Hide all matched elements by adjusting their height and firing an optional callback after
  3924. * completion.
  3925. */
  3926. public Effects slideUp(int millisecs, Function... f) {
  3927. return as(Effects).slideUp(millisecs, f);
  3928. }
  3929. /**
  3930. * When .stop() is called on an element, the currently-running animation (if any) is immediately
  3931. * stopped. If, for instance, an element is being hidden with .slideUp() when .stop() is called,
  3932. * the element will now still be displayed, but will be a fraction of its previous height.
  3933. * Callback functions are not called but the next animation in the queue begins immediately.
  3934. */
  3935. public GQuery stop() {
  3936. return stop(false);
  3937. }
  3938. /**
  3939. * When .stop() is called on an element, the currently-running animation (if any) is immediately
  3940. * stopped. If, for instance, an element is being hidden with .slideUp() when .stop() is called,
  3941. * the element will now still be displayed, but will be a fraction of its previous height.
  3942. * Callback functions are not called but the next animation in the queue begins immediately.
  3943. *
  3944. * If the clearQueue parameter is provided with a value of true, then the rest of the animations
  3945. * in the queue are removed and never run.
  3946. */
  3947. public GQuery stop(boolean clearQueue) {
  3948. return stop(clearQueue, false);
  3949. }
  3950. /**
  3951. * When .stop() is called on an element, the currently-running animation (if any) is immediately
  3952. * stopped. If, for instance, an element is being hidden with .slideUp() when .stop() is called,
  3953. * the element will now still be displayed, but will be a fraction of its previous height.
  3954. * Callback functions are not called but the next animation in the queue begins immediately.
  3955. *
  3956. * If the clearQueue parameter is provided with a value of true, then the rest of the animations
  3957. * in the queue are removed and never run.
  3958. *
  3959. * If the jumpToEnd property is provided with a value of true, the current animation stops, but
  3960. * the element is immediately given its target values for each CSS property. The callback
  3961. * functions are then immediately called, if provided.
  3962. */
  3963. public GQuery stop(boolean clearQueue, boolean jumpToEnd) {
  3964. return as(Queue).stop(clearQueue, jumpToEnd);
  3965. }
  3966. /**
  3967. * Bind a set of functions to the submit event of each matched element. Or submit a form if no
  3968. * functions are provided.
  3969. */
  3970. public GQuery submit(Function... funcs) {
  3971. return bindOrFire("submit", null, funcs);
  3972. }
  3973. /**
  3974. * Return the concatened text contained in the matched elements.
  3975. */
  3976. public String text() {
  3977. String result = "";
  3978. for (Element e : elements) {
  3979. result += JsUtils.text(e);
  3980. }
  3981. return result;
  3982. }
  3983. /**
  3984. * Set the innerText of every matched element.
  3985. */
  3986. public GQuery text(String txt) {
  3987. for (Element e : elements) {
  3988. e.setInnerText(txt);
  3989. }
  3990. return this;
  3991. }
  3992. /**
  3993. * Toggle visibility of elements.
  3994. */
  3995. public GQuery toggle() {
  3996. for (Element e : elements) {
  3997. if (getStyleImpl().isVisible(e)) {
  3998. $(e).hide();
  3999. } else {
  4000. $(e).show();
  4001. e.getStyle().setDisplay(Display.BLOCK);
  4002. }
  4003. }
  4004. return this;
  4005. }
  4006. /**
  4007. * Toggle among two or more function calls every other click.
  4008. */
  4009. public GQuery toggle(final Function... fn) {
  4010. for (Element e : elements) {
  4011. $(e).click(new Function() {
  4012. int click = 0;
  4013. public boolean f(Event e) {
  4014. int n = fn.length == 1 ? 0 : (click++ % fn.length);
  4015. return fn[n].f(e);
  4016. }
  4017. });
  4018. }
  4019. return this;
  4020. }
  4021. /**
  4022. * Adds or removes the specified classes to each matched element depending on the class's
  4023. * presence.
  4024. */
  4025. public GQuery toggleClass(String... classes) {
  4026. for (Element e : elements) {
  4027. for (String clz : classes) {
  4028. if (hasClass(e, clz)) {
  4029. e.removeClassName(clz);
  4030. } else {
  4031. e.addClassName(clz);
  4032. }
  4033. }
  4034. }
  4035. return this;
  4036. }
  4037. /**
  4038. * Adds or removes the specified classes to each matched element depending on the value of the
  4039. * switch argument.
  4040. *
  4041. * if addOrRemove is true, the class is added and in the case of false it is removed.
  4042. */
  4043. public GQuery toggleClass(String clz, boolean addOrRemove) {
  4044. if (addOrRemove) {
  4045. addClass(clz);
  4046. } else {
  4047. removeClass(clz);
  4048. }
  4049. return this;
  4050. }
  4051. /**
  4052. * Returns the computed top position of the first element matched.
  4053. */
  4054. public int top() {
  4055. return (int) cur("top", true);
  4056. }
  4057. /**
  4058. * Produces a string representation of the matched elements.
  4059. */
  4060. public String toString() {
  4061. return toString(false);
  4062. }
  4063. /**
  4064. * Produces a string representation of the matched elements.
  4065. */
  4066. public String toString(boolean pretty) {
  4067. String r = "";
  4068. for (Element e : elements) {
  4069. if (window.equals(e)) {
  4070. continue;
  4071. }
  4072. String elStr;
  4073. try {
  4074. elStr = JsUtils.isXML(e) ? JsUtils.XML2String(e) : e.getString();
  4075. } catch (Exception e2) {
  4076. elStr =
  4077. "< " + (e == null ? "null" : e.getNodeName())
  4078. + "(gquery, error getting the element string representation: " + e2.getMessage()
  4079. + ")/>";
  4080. }
  4081. r += (pretty && r.length() > 0 ? "\n " : "") + elStr;
  4082. }
  4083. return r;
  4084. }
  4085. /**
  4086. * Trigger a browser native event on each matched element.
  4087. */
  4088. public GQuery trigger(NativeEvent event) {
  4089. return as(Events).trigger(event, new Function[] {});
  4090. }
  4091. /**
  4092. * Trigger a set of events on each matched element.
  4093. *
  4094. * For keyboard events you can pass a second parameter which represents the key-code of the pushed
  4095. * key.
  4096. *
  4097. * Example: fire(Event.ONCLICK | Event.ONFOCUS) Example: fire(Event.ONKEYDOWN. 'a');
  4098. */
  4099. public GQuery trigger(int eventbits, int... keys) {
  4100. return as(Events).trigger(eventbits, keys);
  4101. }
  4102. /**
  4103. * Trigger a event in all matched elements.
  4104. *
  4105. * @param eventName An string representing the type of the event desired
  4106. * @param datas Additional parameters to pass along to the event handlers.
  4107. */
  4108. public GQuery trigger(String eventName, Object... datas) {
  4109. return as(Events).triggerHtmlEvent(eventName, datas);
  4110. }
  4111. /**
  4112. * Removes all events that match the eventbits.
  4113. */
  4114. public GQuery unbind(int eventbits) {
  4115. return as(Events).unbind(eventbits);
  4116. }
  4117. /**
  4118. * Removes the function passed from the set of events which match the eventbits.
  4119. */
  4120. public GQuery unbind(int eventbits, Function f) {
  4121. return as(Events).unbind(eventbits, null, f);
  4122. }
  4123. /**
  4124. * Removes all events that match the eventList.
  4125. */
  4126. public GQuery unbind(String eventList) {
  4127. return unbind(eventList, null);
  4128. }
  4129. /**
  4130. * Removes all events that match the eventList.
  4131. */
  4132. public GQuery unbind(String eventList, Function f) {
  4133. return as(Events).unbind(eventList, f);
  4134. }
  4135. /**
  4136. * Remove all event delegation that have been bound using
  4137. * {@link #delegate(String, int, Function...)} {@link #live(int, Function...)} methods
  4138. * @deprecated use {@link #off()}
  4139. */
  4140. public GQuery undelegate() {
  4141. return as(Events).undelegate();
  4142. }
  4143. /**
  4144. * Undelegate is a way of removing event handlers that have been bound using
  4145. * {@link #delegate(String, int, Function...)} method
  4146. * @deprecated use {@link #off(String)}
  4147. */
  4148. public GQuery undelegate(String selector) {
  4149. for (Element e : elements) {
  4150. $(selector, e).die();
  4151. }
  4152. return this;
  4153. }
  4154. /**
  4155. * Undelegate is a way of removing event handlers that have been bound using
  4156. * {@link #delegate(String, int, Function...)} method
  4157. * @deprecated use {@link #off(String)}
  4158. */
  4159. public GQuery undelegate(String selector, int eventBit) {
  4160. for (Element e : elements) {
  4161. $(selector, e).die(eventBit);
  4162. }
  4163. return this;
  4164. }
  4165. /**
  4166. * Undelegate is a way of removing event handlers that have been bound using
  4167. * {@link #delegate(String, int, Function...)} method
  4168. * @deprecated use {@link #off(String, String)}
  4169. */
  4170. public GQuery undelegate(String selector, String eventName) {
  4171. for (Element e : elements) {
  4172. $(selector, e).die(eventName);
  4173. }
  4174. return this;
  4175. }
  4176. /**
  4177. * Remove all duplicate elements from an array of elements. Note that this only works on arrays of
  4178. * DOM elements, not strings or numbers.
  4179. */
  4180. public JsNodeArray unique(NodeList<Element> result) {
  4181. return JsUtils.unique(result.<JsArray<Element>> cast()).cast();
  4182. }
  4183. /**
  4184. * This method removes the element's parent. The matched elements replaces their parents within
  4185. * the DOM structure. It is the inverse of {@link GQuery#wrap(GQuery)} method
  4186. *
  4187. * @return
  4188. */
  4189. public GQuery unwrap() {
  4190. for (Element parent : parent().elements) {
  4191. if (!"body".equalsIgnoreCase(parent.getTagName())) {
  4192. GQuery $parent = $(parent);
  4193. $parent.replaceWith($parent.children());
  4194. }
  4195. }
  4196. return this;
  4197. }
  4198. /**
  4199. * Gets the content of the value attribute of the first matched element, returns only the first
  4200. * value even if it is a multivalued element. To get an array of all values in multivalues
  4201. * elements use vals()
  4202. *
  4203. * When the first element is a radio-button and is not checked, then it looks for the first
  4204. * checked radio-button that has the same name in the list of matched elements.
  4205. *
  4206. * When there are not matched elements it returns null.
  4207. */
  4208. public String val() {
  4209. if (isEmpty()) {
  4210. return null;
  4211. }
  4212. String[] v = vals();
  4213. return v == null ? null : v.length > 0 ? v[0] : "";
  4214. }
  4215. /**
  4216. * Sets the value attribute of every matched element based in the return value of the function
  4217. * evaluated for this element.
  4218. *
  4219. * NOTE: in jquery the function receives the arguments in different way, first index and them the
  4220. * actual value, but we use the normal way in gquery Function, first the element and second the
  4221. * index.
  4222. */
  4223. public GQuery val(Function f) {
  4224. for (int i = 0; i < size(); i++) {
  4225. eq(i).val(f.f(get(i), i).toString());
  4226. }
  4227. return this;
  4228. }
  4229. /**
  4230. * Sets the 'value' attribute of every matched element, but does not set the checked flag to
  4231. * checkboxes or radiobuttons.
  4232. *
  4233. * If you wanted to set values in collections of checkboxes o radiobuttons use val(String[])
  4234. * instead
  4235. */
  4236. public GQuery val(String value) {
  4237. for (Element e : elements) {
  4238. setElementValue(e, value);
  4239. }
  4240. return this;
  4241. }
  4242. /**
  4243. * Sets the value of every matched element.
  4244. *
  4245. * There is a different behaviour depending on the element type:
  4246. * <ul>
  4247. * <li>select multiple: options whose value match any of the passed values will be set.
  4248. * <li>select single: the last option whose value matches any of the passed values will be set.
  4249. * <li>input radio: the last input whose value matches any of the passed values will be set.
  4250. * <li>input checkbox: inputs whose value match any of the passed values will be set.
  4251. * <li>textarea, button, and other input: value will set to a string result of joining with coma,
  4252. * all passed values
  4253. * </ul>
  4254. *
  4255. * NOTE: if you wanted call this function with just one parameter, you have to pass an array
  4256. * signature to avoid call the overloaded val(String) method:
  4257. *
  4258. * $(...).val(new String[]{"value"});
  4259. */
  4260. public GQuery val(String... values) {
  4261. String value = join(",", values);
  4262. for (Element e : elements) {
  4263. String name = e.getNodeName();
  4264. if ("select".equalsIgnoreCase(name)) {
  4265. SelectElement s = SelectElement.as(e);
  4266. s.setSelectedIndex(-1);
  4267. for (String v : values) {
  4268. if (s.isMultiple()) {
  4269. for (int i = 0, l = s.getOptions().getLength(); i < l; i++) {
  4270. if (v.equals(s.getOptions().getItem(i).getValue())) {
  4271. s.getOptions().getItem(i).setSelected(true);
  4272. }
  4273. }
  4274. } else {
  4275. s.setValue(v);
  4276. }
  4277. }
  4278. } else if ("input".equalsIgnoreCase(name)) {
  4279. InputElement ie = InputElement.as(e);
  4280. String type = ie.getType();
  4281. if ("radio".equalsIgnoreCase((type)) || "checkbox".equalsIgnoreCase(type)) {
  4282. ie.setChecked(false);
  4283. for (String v : values) {
  4284. if (ie.getValue().equals(v)) {
  4285. ie.setChecked(true);
  4286. break;
  4287. }
  4288. }
  4289. } else {
  4290. ie.setValue(value);
  4291. }
  4292. } else {
  4293. setElementValue(e, value);
  4294. }
  4295. }
  4296. return this;
  4297. }
  4298. /**
  4299. * Gets the content of the value attribute of the first matched element, returns more than one
  4300. * value if it is a multiple select.
  4301. *
  4302. * When the first element is a radio-button and is not checked, then it looks for a the first
  4303. * checked radio-button that has the same name in the list of matched elements.
  4304. *
  4305. * This method always returns an array. If no valid value can be determined the array will be
  4306. * empty, otherwise it will contain one or more values.
  4307. */
  4308. public String[] vals() {
  4309. if (!isEmpty()) {
  4310. Element e = get(0);
  4311. if (e.getNodeName().equalsIgnoreCase("select")) {
  4312. SelectElement se = SelectElement.as(e);
  4313. if (se.isMultiple()) {
  4314. JsArrayString result = JsArrayString.createArray().cast();
  4315. for (int i = 0, l = se.getOptions().getLength(); i < l; i++) {
  4316. OptionElement oe = se.getOptions().getItem(i);
  4317. if (oe.isSelected()) {
  4318. result.set(result.length(), oe.getValue());
  4319. }
  4320. }
  4321. return result.length() > 0 ? jsArrayToString(result) : null;
  4322. } else if (se.getSelectedIndex() >= 0) {
  4323. return new String[] {se.getOptions().getItem(se.getSelectedIndex()).getValue()};
  4324. }
  4325. } else if (e.getNodeName().equalsIgnoreCase("input")) {
  4326. InputElement ie = InputElement.as(e);
  4327. return new String[] {ie.getValue()};
  4328. } else if (e.getNodeName().equalsIgnoreCase("textarea")) {
  4329. return new String[] {TextAreaElement.as(e).getValue()};
  4330. } else if (e.getNodeName().equalsIgnoreCase("button")) {
  4331. return new String[] {ButtonElement.as(e).getValue()};
  4332. }
  4333. }
  4334. return new String[0];
  4335. }
  4336. @Deprecated
  4337. public boolean visible() {
  4338. return isVisible();
  4339. }
  4340. /**
  4341. * Return the first non null attached widget from the matched elements or null if there isn't any.
  4342. */
  4343. @SuppressWarnings("unchecked")
  4344. public <W extends Widget> W widget() {
  4345. return (W) widget(0);
  4346. }
  4347. /**
  4348. * Return the nth non null attached widget from the matched elements or null if there isn't any.
  4349. */
  4350. public <W extends Widget> W widget(int n) {
  4351. for (Element e : elements) {
  4352. @SuppressWarnings("unchecked")
  4353. W w = (W) getAssociatedWidget(e);
  4354. if (w != null) {
  4355. if (n == 0) {
  4356. return w;
  4357. }
  4358. n--;
  4359. }
  4360. }
  4361. return null;
  4362. }
  4363. /**
  4364. * return the list of attached widgets matching the query
  4365. */
  4366. public List<Widget> widgets() {
  4367. List<Widget> widgets = new ArrayList<Widget>();
  4368. for (Element e : elements) {
  4369. Widget w = getAssociatedWidget(e);
  4370. if (w != null) {
  4371. widgets.add(w);
  4372. }
  4373. }
  4374. return widgets;
  4375. }
  4376. /**
  4377. * Return the list of attached widgets instance of the provided class matching the query.
  4378. *
  4379. * This method is very useful for decoupled views, so as we can access widgets from other views
  4380. * without maintaining methods which export them.
  4381. *
  4382. */
  4383. @SuppressWarnings("unchecked")
  4384. public <W extends Widget> List<W> widgets(Class<W> clazz) {
  4385. List<W> ret = new ArrayList<W>();
  4386. for (Widget w : widgets()) {
  4387. // isAssignableFrom does not work in gwt.
  4388. Class<?> c = w.getClass();
  4389. do {
  4390. if (c.equals(clazz)) {
  4391. ret.add((W) w);
  4392. break;
  4393. }
  4394. c = c.getSuperclass();
  4395. } while (c != null);
  4396. }
  4397. return ret;
  4398. }
  4399. /**
  4400. * Get the current computed, pixel, width of the first matched element. It does not include
  4401. * margin, padding nor border.
  4402. */
  4403. public int width() {
  4404. return (int) cur("width", true);
  4405. }
  4406. /**
  4407. * Set the width of every matched element.
  4408. */
  4409. public GQuery width(int width) {
  4410. for (Element e : elements) {
  4411. e.getStyle().setPropertyPx("width", width);
  4412. }
  4413. return this;
  4414. }
  4415. /**
  4416. * Set the width style property of every matched element. It's useful for using 'percent' or 'em'
  4417. * units Example: $(".a").width("100%")
  4418. */
  4419. public GQuery width(String width) {
  4420. return css("width", width);
  4421. }
  4422. /**
  4423. * Wrap each matched element with the specified HTML content. This wrapping process is most useful
  4424. * for injecting additional structure into a document, without ruining the original semantic
  4425. * qualities of a document. This works by going through the first element provided (which is
  4426. * generated, on the fly, from the provided HTML) and finds the deepest descendant element within
  4427. * its structure -- it is that element that will enwrap everything else.
  4428. */
  4429. public GQuery wrap(Element elem) {
  4430. return wrap($(elem));
  4431. }
  4432. /**
  4433. * Wrap each matched element with the specified HTML content. This wrapping process is most useful
  4434. * for injecting additional structure into a document, without ruining the original semantic
  4435. * qualities of a document. This works by going through the first element provided (which is
  4436. * generated, on the fly, from the provided HTML) and finds the deepest descendant element within
  4437. * its structure -- it is that element that will enwrap everything else.
  4438. */
  4439. public GQuery wrap(GQuery query) {
  4440. for (Element e : elements) {
  4441. $(e).wrapAll(query);
  4442. }
  4443. return this;
  4444. }
  4445. /**
  4446. * Wrap each matched element with the specified HTML content. This wrapping process is most useful
  4447. * for injecting additional structure into a document, without ruining the original semantic
  4448. * qualities of a document. This works by going through the first element provided (which is
  4449. * generated, on the fly, from the provided HTML) and finds the deepest descendant element within
  4450. * its structure -- it is that element that will enwrap everything else.
  4451. */
  4452. public GQuery wrap(String html) {
  4453. return wrap($(html));
  4454. }
  4455. /**
  4456. * Wrap all the elements in the matched set into a single wrapper element. This is different from
  4457. * .wrap() where each element in the matched set would get wrapped with an element. This wrapping
  4458. * process is most useful for injecting additional structure into a document, without ruining the
  4459. * original semantic qualities of a document.
  4460. *
  4461. * This works by going through the first element provided (which is generated, on the fly, from
  4462. * the provided HTML) and finds the deepest descendant element within its structure -- it is that
  4463. * element that will enwrap everything else.
  4464. */
  4465. public GQuery wrapAll(Element elem) {
  4466. return wrapAll($(elem));
  4467. }
  4468. /**
  4469. * Wrap all the elements in the matched set into a single wrapper element. This is different from
  4470. * .wrap() where each element in the matched set would get wrapped with an element. This wrapping
  4471. * process is most useful for injecting additional structure into a document, without ruining the
  4472. * original semantic qualities of a document.
  4473. *
  4474. * This works by going through the first element provided (which is generated, on the fly, from
  4475. * the provided HTML) and finds the deepest descendant element within its structure -- it is that
  4476. * element that will enwrap everything else.
  4477. */
  4478. public GQuery wrapAll(GQuery query) {
  4479. if (!isEmpty()) {
  4480. GQuery wrap = query.clone();
  4481. if (get(0).getParentNode() != null) {
  4482. wrap.insertBefore(get(0));
  4483. }
  4484. for (Element e : wrap.elements) {
  4485. Node n = e;
  4486. while (n.getFirstChild() != null && n.getFirstChild().getNodeType() == Node.ELEMENT_NODE) {
  4487. n = n.getFirstChild();
  4488. }
  4489. $((Element) n).append(this);
  4490. }
  4491. }
  4492. return this;
  4493. }
  4494. /**
  4495. * Wrap all the elements in the matched set into a single wrapper element. This is different from
  4496. * .wrap() where each element in the matched set would get wrapped with an element. This wrapping
  4497. * process is most useful for injecting additional structure into a document, without ruining the
  4498. * original semantic qualities of a document.
  4499. *
  4500. * This works by going through the first element provided (which is generated, on the fly, from
  4501. * the provided HTML) and finds the deepest descendant element within its structure -- it is that
  4502. * element that will enwrap everything else.
  4503. */
  4504. public GQuery wrapAll(String html) {
  4505. return wrapAll($(html));
  4506. }
  4507. /**
  4508. * Wrap the inner child contents of each matched element (including text nodes) with an HTML
  4509. * structure. This wrapping process is most useful for injecting additional structure into a
  4510. * document, without ruining the original semantic qualities of a document. This works by going
  4511. * through the first element provided (which is generated, on the fly, from the provided HTML) and
  4512. * finds the deepest ancestor element within its structure -- it is that element that will enwrap
  4513. * everything else.
  4514. */
  4515. public GQuery wrapInner(Element elem) {
  4516. return wrapInner($(elem));
  4517. }
  4518. /**
  4519. * Wrap the inner child contents of each matched element (including text nodes) with an HTML
  4520. * structure. This wrapping process is most useful for injecting additional structure into a
  4521. * document, without ruining the original semantic qualities of a document. This works by going
  4522. * through the first element provided (which is generated, on the fly, from the provided HTML) and
  4523. * finds the deepest ancestor element within its structure -- it is that element that will enwrap
  4524. * everything else.
  4525. */
  4526. public GQuery wrapInner(GQuery query) {
  4527. for (Element e : elements) {
  4528. $(e).contents().wrapAll(query);
  4529. }
  4530. return this;
  4531. }
  4532. /**
  4533. * Wrap the inner child contents of each matched element (including text nodes) with an HTML
  4534. * structure. This wrapping process is most useful for injecting additional structure into a
  4535. * document, without ruining the original semantic qualities of a document. This works by going
  4536. * through the first element provided (which is generated, on the fly, from the provided HTML) and
  4537. * finds the deepest ancestor element within its structure -- it is that element that will enwrap
  4538. * everything else.
  4539. */
  4540. public GQuery wrapInner(String html) {
  4541. return wrapInner($(html));
  4542. }
  4543. private String join(String chr, String... values) {
  4544. String value = "";
  4545. for (int i = 0; i < values.length; i++) {
  4546. value += i > 0 ? chr + values[i] : values[i];
  4547. }
  4548. return value;
  4549. }
  4550. }