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

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