Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

GQuery.java 157KB

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