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

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