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

GQuery.java 158KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038
  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.user.client.DOM;
  61. import com.google.gwt.user.client.Event;
  62. import com.google.gwt.user.client.EventListener;
  63. import com.google.gwt.user.client.Window;
  64. import com.google.gwt.user.client.ui.IsWidget;
  65. import com.google.gwt.user.client.ui.Widget;
  66. import java.util.ArrayList;
  67. import java.util.Arrays;
  68. import java.util.List;
  69. /**
  70. * GwtQuery is a GWT clone of the popular jQuery library.
  71. */
  72. public class GQuery implements Lazy<GQuery, LazyGQuery> {
  73. private enum DomMan {
  74. AFTER, APPEND, BEFORE, PREPEND;
  75. }
  76. /**
  77. * A POJO used to store the top/left CSS positioning values of an element.
  78. */
  79. public static class Offset {
  80. public int left;
  81. public int top;
  82. public Offset(int left, int top) {
  83. this.left = left;
  84. this.top = top;
  85. }
  86. public Offset add(int left, int top) {
  87. return new Offset(this.left + left, this.top + top);
  88. }
  89. public String toString() {
  90. return top + "+" + left;
  91. }
  92. }
  93. /**
  94. * Class used internally to create DOM element from html snippet.
  95. */
  96. private static class TagWrapper {
  97. public static final TagWrapper DEFAULT = new TagWrapper(0, "", "");
  98. private String postWrap;
  99. private String preWrap;
  100. private int wrapDepth;
  101. public TagWrapper(int wrapDepth, String preWrap, String postWrap) {
  102. this.wrapDepth = wrapDepth;
  103. this.postWrap = postWrap;
  104. this.preWrap = preWrap;
  105. }
  106. }
  107. /**
  108. * Implementation class to modify attributes.
  109. */
  110. protected static AttributeImpl attributeImpl;
  111. /**
  112. * The body element in the current page.
  113. */
  114. public static final BodyElement body = GWT.isClient() ? Document.get().getBody() : null;
  115. /**
  116. * A Browser object with a set of browser-specific flags.
  117. */
  118. public static final Browser browser = GWT.isClient() ? GWT.<Browser>create(Browser.class) : null;
  119. /**
  120. * An object with the same methods than window.console.
  121. */
  122. public static final Console console = GWT.isClient() ? GWT.<Console>create(Console.class) : null;
  123. /**
  124. * Object to store element data (public so as we can access to it from tests).
  125. */
  126. public static JsCache dataCache = null;
  127. /**
  128. * The document element in the current page.
  129. */
  130. public static final Document document = GWT.isClient() ? Document.get() : null;
  131. /**
  132. * Static reference Effects plugin.
  133. */
  134. public static Class<Effects> Effects = com.google.gwt.query.client.plugins.Effects.Effects;
  135. /**
  136. * Implementation engine used for CSS selectors.
  137. */
  138. protected static SelectorEngine engine;
  139. /**
  140. * Static reference Events plugin.
  141. */
  142. public static Class<Events> Events = com.google.gwt.query.client.plugins.Events.Events;
  143. /**
  144. * A static reference to the GQuery class.
  145. */
  146. public static Class<GQuery> GQUERY = GQuery.class;
  147. private static final String OLD_DATA_PREFIX = "old-";
  148. private static final String OLD_DISPLAY = OLD_DATA_PREFIX + "display";
  149. private static JsMap<Class<? extends GQuery>, Plugin<? extends GQuery>> plugins;
  150. // Sizzle POS regex : usefull in some methods
  151. // TODO: Share this static with SelectorEngineSizzle
  152. private static RegExp posRegex = RegExp
  153. .compile("^:(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\))?(?=[^\\-]|$)$");
  154. /**
  155. * Implementation class used for style manipulations.
  156. */
  157. private static DocumentStyleImpl styleImpl;
  158. private static RegExp tagNameRegex = RegExp.compile("<([\\w:-]+)");
  159. /**
  160. * Static reference to the Widgets plugin.
  161. */
  162. public static Class<Widgets> Widgets = com.google.gwt.query.client.plugins.Widgets.Widgets;
  163. /**
  164. * The window object.
  165. */
  166. public static final Element window = GWT.isClient() ? ScriptInjector.TOP_WINDOW.<Element> cast()
  167. : null;
  168. private static Element windowData = null;
  169. private static JsNamedArray<TagWrapper> wrapperMap;
  170. /**
  171. * Create an empty GQuery object.
  172. */
  173. public static GQuery $() {
  174. return new GQuery(JsNodeArray.create());
  175. }
  176. /**
  177. * Wrap a GQuery around an existing element.
  178. */
  179. public static GQuery $(Element element) {
  180. return new GQuery(element);
  181. }
  182. /**
  183. * Wrap a GQuery around an event's target element.
  184. */
  185. public static GQuery $(Event event) {
  186. return event == null ? $() : $((Element) event.getCurrentEventTarget().cast());
  187. }
  188. /**
  189. * Wrap a GQuery around the element of a Function callback.
  190. */
  191. public static GQuery $(Function f) {
  192. return $(f.getElement());
  193. }
  194. /**
  195. * Wrap a GQuery around an existing javascript element, event, node, nodelist, function or array.
  196. */
  197. public static GQuery $(JavaScriptObject jso) {
  198. if (jso == null) {
  199. return $();
  200. }
  201. // Execute a native javascript function like jquery does
  202. if (JsUtils.isFunction(jso)) {
  203. new JsUtils.JsFunction(jso).fe();
  204. return $();
  205. }
  206. // Wraps a native array like jquery does
  207. if (!JsUtils.isWindow(jso) && !JsUtils.isElement(jso) && JsUtils.isArray(jso)) {
  208. JsArrayMixed c = jso.cast();
  209. JsNodeArray elms = JsNodeArray.create();
  210. for (int i = 0; i < c.length(); i++) {
  211. Object obj = c.getObject(i);
  212. if (obj instanceof Node) {
  213. elms.addNode((Node) obj);
  214. }
  215. }
  216. return $(elms);
  217. }
  218. return JsUtils.isWindow(jso) ? $(jso.<Element> cast()) :
  219. JsUtils.isElement(jso) ? $(jso.<Element> cast()) :
  220. JsUtils.isEvent(jso) ? $(jso.<Event> cast()) :
  221. JsUtils.isNodeList(jso) ? $(jso.<NodeList<Element>> cast()) :
  222. $(jso.<Element> cast());
  223. }
  224. /**
  225. * Wrap a GQuery around any object, supported objects are:
  226. * String, GQuery, Function, Widget, JavaScriptObject.
  227. *
  228. * In the case of string, we accept a CSS selector which is then used to match a set of
  229. * elements, or a raw HTML to create a GQuery element containing those elements. Xpath
  230. * selector is supported in browsers with native xpath engine.
  231. *
  232. * In the case of a JavaScriptObject we handle:
  233. * Element, Event, Node, Nodelist and native functions or arrays.
  234. *
  235. * If the case of a native function, we execute it and return empty.
  236. */
  237. public static GQuery $(Object o) {
  238. if (o != null) {
  239. if (o instanceof String) {
  240. return $((String) o);
  241. }
  242. if (o instanceof GQuery) {
  243. return (GQuery) o;
  244. }
  245. if (o instanceof Function) {
  246. return $((Function) o);
  247. }
  248. if (JsUtils.isElement(o)) {
  249. return $(JsUtils.<Element> cast(o));
  250. }
  251. if (o instanceof JsonBuilder) {
  252. return new GQuery(((JsonBuilder) o).getDataImpl());
  253. }
  254. if (o instanceof JavaScriptObject) {
  255. return $((JavaScriptObject) o);
  256. }
  257. if (o instanceof IsWidget) {
  258. return $(Arrays.asList(o));
  259. }
  260. console
  261. .log("Error: GQuery.$(Object o) could not wrap the type : ", o.getClass().getName(), o);
  262. }
  263. return $();
  264. }
  265. /**
  266. * Create a new GQuery given a list of {@link com.google.gwt.dom.client.Node} or
  267. * {@link com.google.gwt.user.client.ui.IsWidget}.
  268. */
  269. public static GQuery $(List<?> nodesOrWidgets) {
  270. JsNodeArray elms = JsNodeArray.create();
  271. if (nodesOrWidgets != null) {
  272. for (Object o : nodesOrWidgets) {
  273. if (o instanceof Node) {
  274. elms.addNode((Node) o);
  275. } else if (o instanceof IsWidget) {
  276. elms.addNode(((IsWidget) o).asWidget().getElement());
  277. }
  278. }
  279. }
  280. return new GQuery(elms);
  281. }
  282. /**
  283. * Wrap a GQuery around an existing node.
  284. */
  285. public static GQuery $(Node n) {
  286. return $((Element) n);
  287. }
  288. /**
  289. * Wrap a GQuery around existing Elements.
  290. */
  291. public static GQuery $(NodeList<Element> elms) {
  292. return new GQuery(elms);
  293. }
  294. /**
  295. * This function accepts a string containing a CSS selector which is then used to match a set of
  296. * elements, or it accepts raw HTML creating a GQuery element containing those elements. Xpath
  297. * selector is supported in browsers with native xpath engine.
  298. */
  299. public static GQuery $(String selectorOrHtml) {
  300. return $(selectorOrHtml, document);
  301. }
  302. /**
  303. * This function accepts a string containing a CSS selector which is then used to match a set of
  304. * elements, or it accepts raw HTML creating a GQuery element containing those elements. The
  305. * second parameter is is a class reference to a plugin to be used.
  306. *
  307. * Xpath selector is supported in browsers with native xpath engine.
  308. */
  309. public static <T extends GQuery> T $(String selector, Class<T> plugin) {
  310. return $(selector, document, plugin);
  311. }
  312. /**
  313. * This function accepts a string containing a CSS selector which is then used to match a set of
  314. * elements, or it accepts raw HTML creating a GQuery element containing those elements. The
  315. * second parameter is the context to use for the selector, or the document where the new elements
  316. * will be created.
  317. *
  318. * Xpath selector is supported in browsers with native xpath engine.
  319. */
  320. public static GQuery $(String selectorOrHtml, Node ctx) {
  321. String selector = null;
  322. if (selectorOrHtml == null || (selector = selectorOrHtml.trim()).length() == 0) {
  323. return $();
  324. }
  325. if (selector.startsWith("<")) {
  326. return innerHtml(selectorOrHtml, JsUtils.getOwnerDocument(ctx));
  327. }
  328. return new GQuery().select(selectorOrHtml, ctx);
  329. }
  330. /**
  331. * This function accepts a string containing a CSS selector which is then used to match a set of
  332. * elements, or it accepts raw HTML creating a GQuery element containing those elements. The
  333. * second parameter is the context to use for the selector. The third parameter is the class
  334. * plugin to use.
  335. *
  336. * Xpath selector is supported in browsers with native xpath engine.
  337. */
  338. @SuppressWarnings("unchecked")
  339. public static <T extends GQuery> T $(String selector, Node context, Class<T> plugin) {
  340. try {
  341. if (plugins != null) {
  342. T gquery = (T) plugins.get(plugin).init(new GQuery().select(selector, context));
  343. return gquery;
  344. }
  345. throw new RuntimeException("No plugin for class " + plugin);
  346. } catch (Exception e) {
  347. throw new RuntimeException(e);
  348. }
  349. }
  350. /**
  351. * This function accepts a string containing a CSS selector which is then used to match a set of
  352. * elements, or it accepts raw HTML creating a GQuery element containing those elements. The
  353. * second parameter is the context to use for the selector, or the document where the new elements
  354. * will be created.
  355. *
  356. * Xpath selector is supported in browsers with native xpath engine.
  357. */
  358. public static GQuery $(String selectorOrHtml, Widget context) {
  359. return $(selectorOrHtml, context.getElement());
  360. }
  361. /**
  362. * This function accepts a string containing a CSS selector which is then used to match a set of
  363. * elements, or it accepts raw HTML creating a GQuery element containing those elements. The
  364. * second parameter is the context to use for the selector. The third parameter is the class
  365. * plugin to use.
  366. *
  367. * Xpath selector is supported in browsers with native xpath engine.
  368. */
  369. public static <T extends GQuery> T $(String selector, Widget context, Class<T> plugin) {
  370. return $(selector, context.getElement(), plugin);
  371. }
  372. /**
  373. * Wrap a GQuery around one widget or an array of existing ones.
  374. */
  375. public static GQuery $(Widget... widgets) {
  376. return $(Arrays.asList(widgets));
  377. }
  378. /**
  379. * Wrap a GQuery around one node or an array of existing ones.
  380. */
  381. public static GQuery $(Node... nodes) {
  382. return $(Arrays.asList(nodes));
  383. }
  384. /**
  385. * Create an empty JSON object.
  386. */
  387. public static Properties $$() {
  388. return $$(null);
  389. }
  390. /**
  391. * Wrap a JSON object.
  392. */
  393. public static Properties $$(String properties) {
  394. return Properties.create(properties);
  395. }
  396. /**
  397. * Perform an ajax request to the server.
  398. */
  399. public static Promise ajax(Properties p) {
  400. return Ajax.ajax(p);
  401. }
  402. /**
  403. * Perform an ajax request to the server.
  404. */
  405. public static Promise ajax(Settings settings) {
  406. return Ajax.ajax(settings);
  407. }
  408. /**
  409. * Perform an ajax request to the server.
  410. */
  411. public static Promise ajax(String url, Settings settings) {
  412. return Ajax.ajax(url, settings);
  413. }
  414. protected static GQuery cleanHtmlString(String elem, Document doc) {
  415. MatchResult mResult = tagNameRegex.exec(elem);
  416. if (mResult == null) {
  417. return $(doc.createTextNode(elem));
  418. }
  419. String tag = mResult.getGroup(1);
  420. if (wrapperMap == null) {
  421. initWrapperMap();
  422. }
  423. TagWrapper wrapper = wrapperMap.get(tag.toLowerCase());
  424. if (wrapper == null) {
  425. wrapper = TagWrapper.DEFAULT;
  426. }
  427. // TODO: fix IE link tag serialization
  428. // TODO: fix IE <script> tag
  429. // TODO: add fixes for IE TBODY issue
  430. // We use a temporary element to wrap the elements
  431. Element div = doc.createDivElement();
  432. div.setInnerHTML(wrapper.preWrap + elem.trim() + wrapper.postWrap);
  433. Node n = div;
  434. int depth = wrapper.wrapDepth;
  435. while (depth-- != 0) {
  436. n = n.getLastChild();
  437. }
  438. return
  439. // return all nodes added to the wrapper
  440. $(n.getChildNodes())
  441. // detach nodes from their temporary parent
  442. .remove(null, false);
  443. }
  444. /**
  445. * Return true if the element b is contained in a.
  446. */
  447. public static boolean contains(Element a, Element b) {
  448. return getSelectorEngine().contains(a, b);
  449. }
  450. /**
  451. * Get the element data matching the key.
  452. */
  453. public static <T> T data(Element e, String key) {
  454. return data(e, key, null);
  455. }
  456. /**
  457. * Store arbitrary data associated with the specified element.
  458. *
  459. * We store this data in a global js object having the structure:
  460. * datacache [element.hashCode()] [key] = value
  461. *
  462. * @return the value stored in the element with the given name
  463. */
  464. public static <T> T data(Element element, String key, T value) {
  465. return data(element, key, value, null);
  466. }
  467. private static <T> T data(Element element, String key, T value, Class<? extends T> clz) {
  468. if (dataCache == null) {
  469. windowData = JavaScriptObject.createObject().cast();
  470. dataCache = JavaScriptObject.createObject().cast();
  471. }
  472. element = element == window || element.getNodeName() == null ? windowData : element;
  473. if (element != null && key != null) {
  474. int id = element.hashCode();
  475. if (value == null) {
  476. return dataCache.exists(id) ? dataCache.getCache(id).get(key, clz) : null;
  477. }
  478. if (!dataCache.exists(id)) {
  479. dataCache.put(id, JsCache.createObject().cast());
  480. }
  481. dataCache.getCache(id).put(key, value);
  482. }
  483. return value;
  484. }
  485. /**
  486. * Execute a function around each object.
  487. */
  488. public static void each(JsArrayMixed objects, Function f) {
  489. for (int i = 0, l = objects.length(); i < l; i++) {
  490. f.f(i, objects.getObject(i));
  491. }
  492. }
  493. /**
  494. * Execute a function around each object.
  495. */
  496. public static <T> void each(List<T> objects, Function f) {
  497. for (int i = 0, l = objects.size(); i < l; i++) {
  498. f.f(i, objects.get(i));
  499. }
  500. }
  501. /**
  502. * Execute a function around each object.
  503. */
  504. public static <T> void each(T[] objects, Function f) {
  505. for (int i = 0, l = objects.length; i < l; i++) {
  506. f.f(i, objects[i]);
  507. }
  508. }
  509. /**
  510. * Perform an ajax request to the server using GET.
  511. */
  512. public static Promise get(String url, Properties data, final Function onSuccess) {
  513. return Ajax.get(url, data, onSuccess);
  514. }
  515. /**
  516. * We will use the fact as GWT use the widget itself as EventListener ! If no Widget associated
  517. * with the element, this method returns null.
  518. */
  519. protected static Widget getAssociatedWidget(Element e) {
  520. try {
  521. EventListener listener = DOM.getEventListener((com.google.gwt.user.client.Element) e);
  522. // No listener attached to the element, so no widget exist for this element
  523. if (listener == null) {
  524. return null;
  525. }
  526. if (listener instanceof Widget) {
  527. // GWT uses the widget as event listener
  528. return (Widget) listener;
  529. } else if (listener instanceof EventsListener) {
  530. // GQuery replaces the gwt event listener and save it
  531. EventsListener gQueryListener = (EventsListener) listener;
  532. if (gQueryListener.getOriginalEventListener() != null
  533. && gQueryListener.getOriginalEventListener() instanceof Widget) {
  534. return (Widget) gQueryListener.getOriginalEventListener();
  535. }
  536. }
  537. } catch (Exception e2) {
  538. // Some times this code could raise an exception.
  539. // We do not want GQuery to fail, but in dev-mode we log the error.
  540. e2.printStackTrace();
  541. }
  542. return null;
  543. }
  544. private static AttributeImpl getAttributeImpl() {
  545. if (attributeImpl == null) {
  546. attributeImpl = GWT.create(AttributeImpl.class);
  547. }
  548. return attributeImpl;
  549. }
  550. /**
  551. * Perform an ajax request to the server using POST and parsing the json response.
  552. */
  553. public static Promise getJSON(String url, Properties data, final Function onSuccess) {
  554. return Ajax.getJSON(url, data, onSuccess);
  555. }
  556. /**
  557. * Perform an ajax request to the server using scripts tags and parsing the json response. The
  558. * request is not subject to the same origin policy restrictions.
  559. *
  560. * Server side should accept a parameter to specify the callback funcion name, and it must return
  561. * a valid json object wrapped this callback function.
  562. *
  563. * Example:
  564. *
  565. * <pre>
  566. Client code:
  567. getJSONP("http://server.exampe.com/getData.php",$$("myCallback:'?', otherParameter='whatever'"),
  568. new Function(){ public void f() {
  569. Properties p = getDataProperties();
  570. alert(p.getStr("k1");
  571. }});
  572. Server response:
  573. myCallback({"k1":"v1", "k2":"v2"});
  574. </pre>
  575. *
  576. */
  577. public static Promise getJSONP(String url, Properties data, final Function onSuccess) {
  578. return Ajax.getJSONP(url, data, onSuccess);
  579. }
  580. protected static DocumentStyleImpl getStyleImpl() {
  581. if (styleImpl == null) {
  582. styleImpl = getSelectorEngine().getDocumentStyleImpl();
  583. }
  584. return styleImpl;
  585. }
  586. /**
  587. * Return only the set of objects with match the predicate.
  588. */
  589. @SuppressWarnings("unchecked")
  590. public static <T> T[] grep(T[] objects, Predicate f) {
  591. ArrayList<Object> ret = new ArrayList<Object>();
  592. for (int i = 0, l = objects.length; i < l; i++) {
  593. if (f.f(objects[i], i)) {
  594. ret.add(objects[i]);
  595. }
  596. }
  597. return (T[]) ret.toArray(new Object[0]);
  598. }
  599. private static boolean hasClass(Element e, String clz) {
  600. return e.getClassName().matches("(^|.*\\s)" + clz + "(\\s.*|$)");
  601. }
  602. private static void initWrapperMap() {
  603. TagWrapper tableWrapper = new TagWrapper(1, "<table>", "</table>");
  604. TagWrapper selectWrapper = new TagWrapper(1, "<select multiple=\"multiple\">", "</select>");
  605. TagWrapper trWrapper = new TagWrapper(3, "<table><tbody><tr>", "</tr></tbody></table>");
  606. wrapperMap = JsNamedArray.create();
  607. wrapperMap.put("option", selectWrapper);
  608. wrapperMap.put("optgroup", selectWrapper);
  609. wrapperMap.put("legend", new TagWrapper(1, "<fieldset>", "</fieldset>"));
  610. wrapperMap.put("thead", tableWrapper);
  611. wrapperMap.put("tbody", tableWrapper);
  612. wrapperMap.put("tfoot", tableWrapper);
  613. wrapperMap.put("colgroup", tableWrapper);
  614. wrapperMap.put("caption", tableWrapper);
  615. wrapperMap.put("tr", new TagWrapper(2, "<table><tbody>", "</tbody></table>"));
  616. wrapperMap.put("td", trWrapper);
  617. wrapperMap.put("th", trWrapper);
  618. wrapperMap.put("col", new TagWrapper(2, "<table><tbody></tbody><colgroup>",
  619. "</colgroup></table>"));
  620. wrapperMap.put("area", new TagWrapper(1, "<map>", "</map>"));
  621. }
  622. private static GQuery innerHtml(String html, Document doc) {
  623. return cleanHtmlString(html, doc);
  624. }
  625. protected static String[] jsArrayToString(JsArrayString array) {
  626. if (GWT.isScript()) {
  627. return JsUtils.castArrayString(array);
  628. } else {
  629. String result[] = new String[array.length()];
  630. for (int i = 0, l = result.length; i < l; i++) {
  631. result[i] = array.get(i);
  632. }
  633. return result;
  634. }
  635. }
  636. /**
  637. * Return a lazy version of the GQuery interface. Lazy function calls are simply queued up and not
  638. * executed immediately.
  639. */
  640. public static LazyGQuery<?> lazy() {
  641. return $().createLazy();
  642. }
  643. /**
  644. * Perform an ajax request to the server using POST.
  645. */
  646. public static Promise post(String url, Properties data, final Function onSuccess) {
  647. return Ajax.post(url, data, onSuccess);
  648. }
  649. public static <T extends GQuery> Class<T> registerPlugin(Class<T> plugin, Plugin<T> pluginFactory) {
  650. // TODO: decide whether change plugins type to java.util.list
  651. // Right now we only test static methods in gquery, so this is only needed when initializing
  652. // plugins shortcuts in gquery.
  653. if (GWT.isClient()) {
  654. if (plugins == null) {
  655. plugins = JsMap.createObject().cast();
  656. }
  657. plugins.put(plugin, pluginFactory);
  658. }
  659. return plugin;
  660. }
  661. /**
  662. * Provides a way to execute callback Functions based on one or more objects
  663. * that represent asynchronous events.
  664. *
  665. * Arguments can be of any Object, but normally you would pass Promises.
  666. * In the case you provide a GQuery object it will call the promise() method to return
  667. * a Promise which will be executed when the queue is resolved.
  668. * In the case you provide a normal Object, it will return a promise which will be immediately
  669. * resolved with the object as argument.
  670. * In the case you provide a Function it will executed and if the f(Object...) method returns
  671. * a new promise it will be used, otherwise we will use the returned object like in the last case.
  672. *
  673. * It Returns a new promise which will be finalized when all of its subordinates finish.
  674. * In the case of all subordinates are resolved correctly the promise will be resolved
  675. * otherwise it will be rejected.
  676. */
  677. public static Promise when(Object... subordinates) {
  678. return Deferred.when(subordinates);
  679. }
  680. /**
  681. * A constructor function that returns a chainable utility object with methods to register
  682. * multiple callbacks into callback queues, invoke callback queues, and relay the success
  683. * or failure state of any synchronous or asynchronous function.
  684. */
  685. public static Promise.Deferred Deferred() {
  686. return new Deferred();
  687. }
  688. public static SelectorEngine getSelectorEngine() {
  689. if (engine == null) {
  690. engine = GWT.create(SelectorEngine.class);
  691. }
  692. return engine;
  693. }
  694. private static native void scrollIntoViewImpl(Node n) /*-{
  695. if (n)
  696. n.scrollIntoView()
  697. }-*/;
  698. private static native void setElementValue(Element e, String value) /*-{
  699. e.value = value;
  700. }-*/;
  701. protected Node currentContext;
  702. protected String currentSelector;
  703. /**
  704. * Immutable array of matched elements, modify this using setArray.
  705. */
  706. private Element[] elements = new Element[0];
  707. /**
  708. * The nodeList of matched elements, modify this using setArray.
  709. */
  710. // TODO: remove this and use elements, change return type of get()
  711. private NodeList<Element> nodeList = JavaScriptObject.createArray().cast();
  712. private GQuery previousObject;
  713. private GQuery() {
  714. }
  715. private GQuery(Element element) {
  716. this(JsNodeArray.create(element));
  717. }
  718. protected GQuery(GQuery gq) {
  719. if (gq != null) {
  720. elements = gq.elements;
  721. nodeList = gq.nodeList;
  722. currentSelector = gq.currentSelector;
  723. currentContext = gq.currentContext;
  724. }
  725. }
  726. private GQuery(JsNodeArray nodes) {
  727. this(nodes.<NodeList<Element>> cast());
  728. }
  729. private GQuery(NodeList<Element> list) {
  730. setArray(list);
  731. }
  732. /**
  733. * Add elements to the set of matched elements if they are not included yet.
  734. *
  735. * It construct a new GQuery object and does not modify the original ones.
  736. *
  737. * It also update the selector appending the new one.
  738. */
  739. public GQuery add(GQuery elementsToAdd) {
  740. return pushStack(JsUtils.copyNodeList(nodeList, elementsToAdd.nodeList, true)
  741. .<JsNodeArray> cast(), "add", join(",", getSelector(), elementsToAdd.getSelector()));
  742. }
  743. /**
  744. * Add elements to the set of matched elements if they are not included yet.
  745. */
  746. public GQuery add(String selector) {
  747. return add($(selector));
  748. }
  749. /**
  750. * Add the previous selection to the current selection. Useful for traversing elements, and then
  751. * adding something that was matched before the last traversal.
  752. */
  753. public GQuery addBack() {
  754. return previousObject != null ? add(previousObject) : this;
  755. }
  756. /**
  757. * Adds the specified classes to each matched element.
  758. */
  759. public GQuery addClass(String... classes) {
  760. for (Element e : elements) {
  761. // issue 81 : ensure that the element is an Element node.
  762. if (Element.is(e)) {
  763. for (String clz : classes) {
  764. e.addClassName(clz);
  765. }
  766. }
  767. }
  768. return this;
  769. }
  770. /**
  771. * Insert content after each of the matched elements. The elements must already be inserted into
  772. * the document (you can't insert an element after another if it's not in the page).
  773. */
  774. public GQuery after(GQuery query) {
  775. return domManip(query, DomMan.AFTER);
  776. }
  777. /**
  778. * Insert content after each of the matched elements. The elements must already be inserted into
  779. * the document (you can't insert an element after another if it's not in the page).
  780. */
  781. public GQuery after(Node n) {
  782. return domManip($(n), DomMan.AFTER);
  783. }
  784. /**
  785. * Insert content after each of the matched elements. The elements must already be inserted into
  786. * the document (you can't insert an element after another if it's not in the page).
  787. */
  788. public GQuery after(String html) {
  789. return domManip(html, DomMan.AFTER);
  790. }
  791. private void allNextSiblingElements(Element firstChildElement, JsNodeArray result, Element elem,
  792. GQuery until, String filterSelector) {
  793. while (firstChildElement != null) {
  794. if (until != null && until.index(firstChildElement) != -1) {
  795. return;
  796. }
  797. if (firstChildElement != elem
  798. && (filterSelector == null || $(firstChildElement).is(filterSelector))) {
  799. result.addNode(firstChildElement);
  800. }
  801. firstChildElement = firstChildElement.getNextSiblingElement();
  802. }
  803. }
  804. private void allPreviousSiblingElements(Element firstChildElement, JsNodeArray result,
  805. GQuery until, String filterSelector) {
  806. while (firstChildElement != null) {
  807. if (until != null && until.index(firstChildElement) != -1) {
  808. return;
  809. }
  810. if (filterSelector == null || $(firstChildElement).is(filterSelector)) {
  811. result.addNode(firstChildElement);
  812. }
  813. firstChildElement = getPreviousSiblingElement(firstChildElement);
  814. }
  815. }
  816. /**
  817. * Add the previous selection to the current selection. Useful for traversing elements, and then
  818. * adding something that was matched before the last traversal.
  819. * @deprecated use addBack() instead
  820. */
  821. @Deprecated
  822. public GQuery andSelf() {
  823. return addBack();
  824. }
  825. /**
  826. *
  827. * The animate() method allows you to create animation effects on any numeric HTML Attribute,
  828. * CSS property, or color CSS property.
  829. *
  830. * Concerning to numeric properties, values are treated as a number of pixels unless otherwise
  831. * specified. The units em and % can be specified where applicable.
  832. *
  833. * By default animate considers css properties, if you wanted to animate element attributes you
  834. * should to prepend the symbol dollar to the attribute name. It's useful to animate svg elements.
  835. *
  836. * NOTE: The ability of animating attribute values is only available in gquery but not jquery
  837. *
  838. * Example:
  839. *
  840. * <pre class="code">
  841. * // move the element from its original position to left:500px
  842. * $("#foo").animate("left:'500'");
  843. *
  844. * // Change the width html attribute of a table, note the symbol '$' to
  845. * // tell gquery which it is an html-attribute instead of a css-property.
  846. * $("table").animate("$width:'500'");
  847. * </pre>
  848. *
  849. * In addition to numeric values, each property can take the strings 'show', 'hide', and 'toggle'.
  850. * These shortcuts allow for custom hiding and showing animations that take into account the
  851. * display type of the element. Animated properties can also be relative. If a value is supplied
  852. * with a leading += or -= sequence of characters, then the target value is computed by adding or
  853. * subtracting the given number from the current value of the property.
  854. *
  855. * Example:
  856. *
  857. * <pre class="code">
  858. * // move the element from its original position to 500px to the left for 500ms and
  859. * // change the background color of the element at the end of the animation
  860. *
  861. * $("#foo").animate("left:'+=500'", new Function(){
  862. * public void f(Element e){
  863. * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED);
  864. * }
  865. * });
  866. * </pre>
  867. *
  868. * The default duration of the animation is 500ms.
  869. *
  870. * For color css properties, values can be specified via hexadecimal or rgb or literal values.
  871. *
  872. * Example:
  873. *
  874. * <pre class="code">
  875. * $("#foo").animate("backgroundColor:'red', color:'#ffffff', borderColor:'rgb(129, 0, 70)'");
  876. * </pre>
  877. *
  878. * @param stringOrProperties the property to animate : "cssName:'value'"
  879. * @param funcs an array of {@link Function} called once the animation is complete
  880. */
  881. public GQuery animate(Object stringOrProperties, Function... funcs) {
  882. return as(Effects).animate(stringOrProperties, funcs);
  883. }
  884. /**
  885. *
  886. * The animate() method allows you to create animation effects on any numeric HTML Attribute,
  887. * CSS property, or color CSS property.
  888. *
  889. * Concerning to numeric properties, values are treated as a number of pixels unless otherwise
  890. * specified. The units em and % can be specified where applicable.
  891. *
  892. * By default animate considers css properties, if you wanted to animate element attributes you
  893. * should to prepend the symbol dollar to the attribute name. It's useful to animate svg elements.
  894. *
  895. * NOTE: The ability of animating attribute values is only available in gquery but not jquery
  896. *
  897. * Example:
  898. *
  899. * <pre class="code">
  900. * // move the element from its original position to left:500px for 500ms using a swing easing
  901. * $("#foo").animate("left:'500'", 500, Easing.SWING);
  902. *
  903. * // Change the width html attribute of a table, note the symbol '$' to
  904. * // tell gquery which it is an html-attribute instead of a css-property.
  905. * // the animation will last 400ms, and we use the LINEAR easing algorithm
  906. * $("table").animate(Properties.create("{$width: '500', $border: '10'}"), 400, Easing.LINEAR);
  907. * </pre>
  908. *
  909. * In addition to numeric values, each property can take the strings 'show', 'hide', and 'toggle'.
  910. * These shortcuts allow for custom hiding and showing animations that take into account the
  911. * display type of the element. Animated properties can also be relative. If a value is supplied
  912. * with a leading += or -= sequence of characters, then the target value is computed by adding or
  913. * subtracting the given number from the current value of the property.
  914. *
  915. * Example:
  916. *
  917. * <pre class="code">
  918. * // move the element from its original position to 500px to the left and 5OOpx down for 400ms.
  919. * // use a swing easing function for the transition
  920. * $("#foo").animate(Properties.create("{top:'+=500px',left:'+=500px'}"), 400, Easing.SWING);
  921. * </pre>
  922. *
  923. * For color css properties, values can be specified via hexadecimal or rgb or literal values.
  924. *
  925. * Example:
  926. *
  927. * <pre class="code">
  928. * $("#foo").animate("backgroundColor:'red', color:'#ffffff', borderColor:'rgb(129, 0, 70)'"), 400, Easing.SWING);
  929. * </pre>
  930. *
  931. * @param stringOrProperties a String or a {@link Properties} object containing css properties to
  932. * animate.
  933. * @param funcs an array of {@link Function} called once the animation is complete
  934. * @param duration the duration in milliseconds of the animation
  935. * @param easing the easing function to use for the transition
  936. */
  937. public GQuery animate(Object stringOrProperties, int duration, Easing easing, Function... funcs) {
  938. return as(Effects).animate(stringOrProperties, duration, easing, funcs);
  939. }
  940. /**
  941. * The animate() method allows you to create animation effects on any numeric HTML Attribute,
  942. * CSS property, or color CSS property.
  943. *
  944. * Concerning to numeric properties, values are treated as a number of pixels unless otherwise
  945. * specified. The units em and % can be specified where applicable.
  946. *
  947. * By default animate considers css properties, if you wanted to animate element attributes you
  948. * should to prepend the symbol dollar to the attribute name. It's useful to animate svg elements.
  949. *
  950. * NOTE: The ability of animating attribute values is only available in gquery but not jquery
  951. *
  952. * Example:
  953. *
  954. * <pre class="code">
  955. * // move the element from its original position to left:500px for 500ms
  956. * $("#foo").animate("left:'500'", 500);
  957. *
  958. * // Change the width html attribute of a table, note the symbol '$' to
  959. * // tell gquery which it is an html-attribute instead of a css-property.
  960. * // the animation will last 400ms
  961. * $("table").animate("$width:'500'"), 400);
  962. * </pre>
  963. *
  964. * In addition to numeric values, each property can take the strings 'show', 'hide', and 'toggle'.
  965. * These shortcuts allow for custom hiding and showing animations that take into account the
  966. * display type of the element. Animated properties can also be relative. If a value is supplied
  967. * with a leading += or -= sequence of characters, then the target value is computed by adding or
  968. * subtracting the given number from the current value of the property.
  969. *
  970. * Example:
  971. *
  972. * <pre class="code">
  973. * // move the element from its original position to 500px to the left for 1000ms and
  974. * // change the background color of the element at the end of the animation
  975. * $("#foo").animate("left:'+=500'", 1000, new Function(){
  976. * public void f(Element e){
  977. * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED);
  978. * }
  979. * });
  980. * </pre>
  981. *
  982. * For color css properties, values can be specified via hexadecimal or rgb or literal values.
  983. *
  984. * Example:
  985. *
  986. * <pre class="code">
  987. * $("#foo").animate("backgroundColor:'red', color:'#ffffff', borderColor:'rgb(129, 0, 70)', 1000");
  988. * </pre>
  989. *
  990. * @param stringOrProperties the set of properties to animate : "cssName:'value'"
  991. * @param funcs an array of {@link Function} called once the animation is complete.
  992. */
  993. public GQuery animate(Object stringOrProperties, int duration, Function... funcs) {
  994. return as(Effects).animate(stringOrProperties, duration, funcs);
  995. }
  996. /**
  997. * Append content to the inside of every matched element. This operation is similar to doing an
  998. * appendChild to all the specified elements, adding them into the document.
  999. */
  1000. public GQuery append(GQuery query) {
  1001. return domManip(query, DomMan.APPEND);
  1002. }
  1003. /**
  1004. * Append content to the inside of every matched element. This operation is similar to doing an
  1005. * appendChild to all the specified elements, adding them into the document.
  1006. */
  1007. public GQuery append(Node n) {
  1008. return domManip($(n), DomMan.APPEND);
  1009. }
  1010. /**
  1011. * Append content to the inside of every matched element. This operation is similar to doing an
  1012. * appendChild to all the specified elements, adding them into the document.
  1013. */
  1014. public GQuery append(String html) {
  1015. return domManip(html, DomMan.APPEND);
  1016. }
  1017. /**
  1018. * All of the matched set of elements will be inserted at the end of the element(s) specified by
  1019. * the parameter other.
  1020. *
  1021. * The operation $(A).appendTo(B) is, essentially, the reverse of doing a regular $(A).append(B),
  1022. * instead of appending B to A, you're appending A to B.
  1023. */
  1024. public GQuery appendTo(GQuery other) {
  1025. other.append(this);
  1026. return this;
  1027. }
  1028. /**
  1029. * All of the matched set of elements will be inserted at the end of the element(s) specified by
  1030. * the parameter other.
  1031. *
  1032. * The operation $(A).appendTo(B) is, essentially, the reverse of doing a regular $(A).append(B),
  1033. * instead of appending B to A, you're appending A to B.
  1034. */
  1035. public GQuery appendTo(Node n) {
  1036. GQuery a = $(n);
  1037. GQuery b = this;
  1038. a.append(b);
  1039. return this;
  1040. }
  1041. /**
  1042. * All of the matched set of elements will be inserted at the end of the element(s) specified by
  1043. * the parameter other.
  1044. *
  1045. * The operation $(A).appendTo(B) is, essentially, the reverse of doing a regular $(A).append(B),
  1046. * instead of appending B to A, you're appending A to B.
  1047. */
  1048. public GQuery appendTo(String html) {
  1049. $(html).append(this);
  1050. return this;
  1051. }
  1052. /**
  1053. * Convert to Plugin interface provided by Class literal.
  1054. */
  1055. @SuppressWarnings("unchecked")
  1056. public <T extends GQuery> T as(Class<T> plugin) {
  1057. // GQuery is not a plugin for itself
  1058. if (plugin == GQUERY) {
  1059. return (T) this;
  1060. } else if (plugins != null) {
  1061. Plugin<?> p = plugins.get(plugin);
  1062. if (p != null) {
  1063. return (T) p.init(this);
  1064. }
  1065. }
  1066. throw new RuntimeException("No plugin registered for class " + plugin.getName());
  1067. }
  1068. /**
  1069. * Set a key/value object as properties to all matched elements.
  1070. *
  1071. * Example: $("img").attr(new Properties("src: 'test.jpg', alt: 'Test Image'"))
  1072. */
  1073. public GQuery attr(Properties properties) {
  1074. for (String name : properties.keys()) {
  1075. attr(name, properties.getStr(name));
  1076. }
  1077. return this;
  1078. }
  1079. /**
  1080. * Access a property on the first matched element. This method makes it easy to retrieve a
  1081. * property value from the first matched element. If the element does not have an attribute with
  1082. * such a name, empty string is returned. Attributes include title, alt, src, href, width, style,
  1083. * etc.
  1084. */
  1085. public String attr(String name) {
  1086. return isEmpty() ? "" : get(0).getAttribute(name);
  1087. }
  1088. /**
  1089. * Set a single property to a computed value, on all matched elements.
  1090. */
  1091. public GQuery attr(String key, Function closure) {
  1092. int i = 0;
  1093. for (Element e : elements) {
  1094. Object val = closure.f(e.<com.google.gwt.dom.client.Element> cast(), i++);
  1095. $(e).attr(key, val);
  1096. }
  1097. return this;
  1098. }
  1099. /**
  1100. * Set a single property to a value, on all matched elements.
  1101. */
  1102. public GQuery attr(String key, Object value) {
  1103. assert key != null : "key cannot be null";
  1104. assert !"$H".equalsIgnoreCase(key) : "$H is a GWT reserved attribute. Changing its value will break your application.";
  1105. getAttributeImpl().setAttribute(this, key, value);
  1106. return this;
  1107. }
  1108. /**
  1109. * Insert content before each of the matched elements. The elements must already be inserted into
  1110. * the document (you can't insert an element before another if it's not in the page).
  1111. */
  1112. public GQuery before(GQuery query) {
  1113. return domManip(query, DomMan.BEFORE);
  1114. }
  1115. /**
  1116. * Insert content before each of the matched elements. The elements must already be inserted into
  1117. * the document (you can't insert an element before another if it's not in the page).
  1118. */
  1119. public GQuery before(Node n) {
  1120. return domManip($(n), DomMan.BEFORE);
  1121. }
  1122. /**
  1123. * Insert content before each of the matched elements. The elements must already be inserted into
  1124. * the document (you can't insert an element before another if it's not in the page).
  1125. */
  1126. public GQuery before(String html) {
  1127. return domManip(html, DomMan.BEFORE);
  1128. }
  1129. /**
  1130. * Binds a set of handlers to a particular Event for each matched element.
  1131. *
  1132. * The event handlers are passed as Functions that you can use to prevent default behavior. To
  1133. * stop both default action and event bubbling, the function event handler has to return false.
  1134. *
  1135. * You can pass an additional Object data to your Function as the second parameter
  1136. *
  1137. */
  1138. public GQuery bind(int eventbits, final Object data, final Function... funcs) {
  1139. return as(Events).bind(eventbits, data, funcs);
  1140. }
  1141. /**
  1142. * Binds a set of handlers to a particular Event for each matched element.
  1143. *
  1144. * The event handlers are passed as Functions that you can use to prevent default behavior. To
  1145. * stop both default action and event bubbling, the function event handler has to return false.
  1146. *
  1147. */
  1148. public GQuery bind(int eventbits, final Function... funcs) {
  1149. return as(Events).bind(eventbits, null, funcs);
  1150. }
  1151. /**
  1152. * Binds a set of handlers to a particular Event for each matched element.
  1153. *
  1154. * The event handlers are passed as Functions that you can use to prevent default behavior. To
  1155. * stop both default action and event bubbling, the function event handler has to return false.
  1156. *
  1157. * You can pass an additional Object data to your Function as the second parameter
  1158. *
  1159. */
  1160. public GQuery bind(String eventType, final Object data, final Function... funcs) {
  1161. return as(Events).bind(eventType, data, funcs);
  1162. }
  1163. /**
  1164. * Binds a set of handlers to a particular Event for each matched element.
  1165. *
  1166. * The event handlers are passed as Functions that you can use to prevent default behavior. To
  1167. * stop both default action and event bubbling, the function event handler has to return false.
  1168. *
  1169. */
  1170. public GQuery bind(String eventType, final Function... funcs) {
  1171. return as(Events).bind(eventType, null, funcs);
  1172. }
  1173. /**
  1174. * Bind Handlers or fire Events for each matched element.
  1175. */
  1176. private GQuery bindOrFire(int eventbits, final Object data, final Function... funcs) {
  1177. if (funcs.length == 0) {
  1178. return trigger(eventbits);
  1179. } else {
  1180. return bind(eventbits, data, funcs);
  1181. }
  1182. }
  1183. /**
  1184. * Bind Handlers or fire Events for each matched element.
  1185. */
  1186. private GQuery bindOrFire(String eventname, final Object data, final Function... funcs) {
  1187. if (funcs.length == 0) {
  1188. return as(Events).triggerHtmlEvent(eventname);
  1189. } else {
  1190. return bind(eventname, data, funcs);
  1191. }
  1192. }
  1193. /**
  1194. * Bind a set of functions to the blur event of each matched element. Or trigger the blur event if
  1195. * no functions are provided.
  1196. */
  1197. public GQuery blur(Function... f) {
  1198. bindOrFire(Event.ONBLUR, null, f);
  1199. if (!isEmpty() && f.length == 0) {
  1200. get(0).blur();
  1201. }
  1202. return this;
  1203. }
  1204. /**
  1205. * Bind a set of functions to the change event of each matched element. Or trigger the event if no
  1206. * functions are provided.
  1207. */
  1208. public GQuery change(Function... f) {
  1209. return bindOrFire(Event.ONCHANGE, null, f);
  1210. }
  1211. /**
  1212. * Get a set of elements containing all of the unique immediate children of each of the matched
  1213. * set of elements. Also note: while parents() will look at all ancestors, children() will only
  1214. * consider immediate child elements.
  1215. */
  1216. public GQuery children() {
  1217. JsNodeArray result = JsNodeArray.create();
  1218. for (Element e : elements) {
  1219. allNextSiblingElements(e.getFirstChildElement(), result, null, null, null);
  1220. }
  1221. return new GQuery(unique(result));
  1222. }
  1223. /**
  1224. * Get a set of elements containing all of the unique children of each of the matched set of
  1225. * elements. This set is filtered with the expressions that will cause only elements matching any
  1226. * of the selectors to be collected.
  1227. */
  1228. public GQuery children(String... filters) {
  1229. return children().filter(filters);
  1230. }
  1231. private void cleanGQData(Element... elements) {
  1232. for (Element el : elements) {
  1233. try {
  1234. EventsListener.clean(el);
  1235. removeData(el, null);
  1236. } catch (Exception e) {
  1237. // If for some reason event/data removal fails, do not break the app,
  1238. // just log the error in dev-mode
  1239. // e.g.: this happens when removing iframes which are no fully loaded.
  1240. e.printStackTrace();
  1241. }
  1242. }
  1243. }
  1244. /**
  1245. * Remove from the Effects queue all {@link Function} that have not yet been run.
  1246. */
  1247. public GQuery clearQueue() {
  1248. return as(Queue).clearQueue();
  1249. }
  1250. /**
  1251. * Remove from the queue all {@link Function} that have not yet been run.
  1252. */
  1253. public GQuery clearQueue(String queueName) {
  1254. return as(Queue).clearQueue(queueName);
  1255. }
  1256. /**
  1257. * Bind a set of functions to the click event of each matched element. Or trigger the event if no
  1258. * functions are provided.
  1259. */
  1260. public GQuery click(Function... f) {
  1261. return bindOrFire(Event.ONCLICK, null, f);
  1262. }
  1263. /**
  1264. * Clone matched DOM Elements and select the clones. This is useful for moving copies of the
  1265. * elements to another location in the DOM.
  1266. */
  1267. public GQuery clone() {
  1268. JsNodeArray result = JsNodeArray.create();
  1269. for (Element e : elements) {
  1270. result.addNode(e.cloneNode(true));
  1271. }
  1272. GQuery ret = new GQuery(result);
  1273. ret.currentContext = currentContext;
  1274. ret.currentSelector = currentSelector;
  1275. return ret;
  1276. }
  1277. /**
  1278. * Get the first ancestor element that matches the selector (for each matched element), beginning
  1279. * at the current element and progressing up through the DOM tree.
  1280. *
  1281. * @param selector
  1282. * @return
  1283. */
  1284. public GQuery closest(String selector) {
  1285. return closest(selector, null);
  1286. }
  1287. /**
  1288. * Get the first ancestor element that matches the selector (for each matched element), beginning
  1289. * at the current element and progressing up through the DOM tree until reach the
  1290. * <code>context</code> node.
  1291. *
  1292. * If no context is passed in then the context of the gQuery object will be used instead.
  1293. *
  1294. */
  1295. public GQuery closest(String selector, Node context) {
  1296. assert selector != null;
  1297. if (context == null) {
  1298. context = currentContext;
  1299. }
  1300. GQuery pos = posRegex.test(selector) ? $(selector, context) : null;
  1301. JsNodeArray result = JsNodeArray.create();
  1302. for (Element e : elements) {
  1303. Element current = e;
  1304. while (current != null && current.getOwnerDocument() != null && current != context) {
  1305. boolean match = pos != null ? pos.index(current) > -1 : $(current).is(selector);
  1306. if (match) {
  1307. result.addNode(current);
  1308. break;
  1309. } else {
  1310. current = current.getParentElement();
  1311. }
  1312. }
  1313. }
  1314. return $(unique(result));
  1315. }
  1316. /**
  1317. * Returns a {@link Map} object as key a selector and as value the list of ancestor elements
  1318. * matching this selectors, beginning at the first matched element and progressing up through the
  1319. * DOM. This method allows retrieving the list of ancestors matching many selectors by traversing
  1320. * the DOM only one time.
  1321. *
  1322. * @return
  1323. */
  1324. public JsNamedArray<NodeList<Element>> closest(String[] selectors) {
  1325. return closest(selectors, null);
  1326. }
  1327. /**
  1328. * Returns a {@link Map} object as key a selector and as value the list of ancestor elements
  1329. * matching this selectors, beginning at the first matched element and progressing up through the
  1330. * DOM until reach the <code>context</code> node.. This method allows retrieving the list of
  1331. * ancestors matching many selectors by traversing the DOM only one time.
  1332. *
  1333. * @return
  1334. */
  1335. public JsNamedArray<NodeList<Element>> closest(String[] selectors, Node context) {
  1336. JsNamedArray<NodeList<Element>> results = JsNamedArray.create();
  1337. if (context == null) {
  1338. context = currentContext;
  1339. }
  1340. Element first = get(0);
  1341. if (first != null && selectors != null && selectors.length > 0) {
  1342. JsNamedArray<GQuery> matches = JsNamedArray.create();
  1343. for (String selector : selectors) {
  1344. if (!matches.exists(selector)) {
  1345. matches.put(selector, posRegex.test(selector) ? $(selector, context) : null);
  1346. }
  1347. }
  1348. Element current = first;
  1349. while (current != null && current.getOwnerDocument() != null && current != context) {
  1350. // for each selector, check if the current element match it.
  1351. for (String selector : matches.keys()) {
  1352. GQuery pos = matches.get(selector);
  1353. boolean match = pos != null ? pos.index(current) > -1 : $(current).is(selector);
  1354. if (match) {
  1355. JsNodeArray elementsMatchingSelector = results.get(selector).cast();
  1356. if (elementsMatchingSelector == null) {
  1357. elementsMatchingSelector = JsNodeArray.create();
  1358. results.put(selector, elementsMatchingSelector);
  1359. }
  1360. elementsMatchingSelector.addNode(current);
  1361. }
  1362. }
  1363. current = current.getParentElement();
  1364. }
  1365. }
  1366. return results;
  1367. }
  1368. /**
  1369. * Filter the set of elements to those that contain the specified text.
  1370. */
  1371. public GQuery contains(String text) {
  1372. JsNodeArray array = JsNodeArray.create();
  1373. for (Element e : elements) {
  1374. if ($(e).text().contains(text)) {
  1375. array.addNode(e);
  1376. }
  1377. }
  1378. return $(array);
  1379. }
  1380. /**
  1381. * Find all the child nodes inside the matched elements (including text nodes), or the content
  1382. * document, if the element is an iframe.
  1383. */
  1384. public GQuery contents() {
  1385. JsNodeArray result = JsNodeArray.create();
  1386. for (Element e : elements) {
  1387. if (JsUtils.isWindow(e) || "iframe".equalsIgnoreCase(e.getTagName())) {
  1388. result.addNode(getStyleImpl().getContentDocument(e));
  1389. } else {
  1390. NodeList<Node> children = e.getChildNodes();
  1391. for (int i = 0, l = children.getLength(); i < l; i++) {
  1392. result.addNode(children.getItem(i));
  1393. }
  1394. }
  1395. }
  1396. return new GQuery(unique(result));
  1397. }
  1398. public LazyGQuery<?> createLazy() {
  1399. return GWT.create(GQuery.class);
  1400. }
  1401. /**
  1402. * Set CSS a single style property on every matched element using type-safe enumerations.
  1403. *
  1404. * The best way to use this method (i.e. to generate a CssSetter) is to take the desired css
  1405. * property defined in {@link CSS} class and call the {@link TakesCssValue#with(HasCssName)}
  1406. * method on it.
  1407. *
  1408. * ex :
  1409. *
  1410. * <pre class="code">
  1411. * $("#myDiv").css(CSS.TOP.with(Length.cm(15)));
  1412. * $("#myDiv").css(CSS.BACKGROUND.with(RGBColor.SILVER, ImageValue.url(""),
  1413. * BackgroundRepeat.NO_REPEAT, BackgroundAttachment.FIXED,
  1414. * BackgroundPosition.CENTER));
  1415. * $("#myDiv").css(CSS.BACKGROUND_ATTACHMENT.with(BackgroundAttachment.FIXED));
  1416. *
  1417. * </pre>
  1418. *
  1419. */
  1420. public GQuery css(CssSetter... cssSetter) {
  1421. for (Element e : elements) {
  1422. for (CssSetter s : cssSetter) {
  1423. s.applyCss(e);
  1424. }
  1425. }
  1426. return this;
  1427. }
  1428. /**
  1429. * Return a style property on the first matched element using type-safe enumerations.
  1430. *
  1431. * Ex : $("#myId").css(CSS.BACKGROUND_COLOR);
  1432. */
  1433. public String css(HasCssValue property) {
  1434. return css(property, true);
  1435. }
  1436. /**
  1437. * Return a style property on the first matched element using type-safe enumerations.
  1438. *
  1439. * The parameter force has a special meaning here: - When force is false, returns the value of the
  1440. * css property defined in the style attribute of the element. - Otherwise it returns the real
  1441. * computed value.
  1442. *
  1443. * For instance if you define 'display=none' not in the element style but in the css stylesheet,
  1444. * it returns an empty string unless you pass the parameter force=true.
  1445. *
  1446. * Ex : $("#myId").css(CSS.WIDTH, true);
  1447. */
  1448. public String css(HasCssValue property, boolean force) {
  1449. return css(property.getCssName(), force);
  1450. }
  1451. /**
  1452. * Set a key/value object as style properties to all matched elements. This serves as the best way
  1453. * to set a large number of style properties on all matched elements. You can use either js maps
  1454. * or pure css syntax.
  1455. *
  1456. * Example:
  1457. *
  1458. * <pre class="code">
  1459. * $(".item").css(Properties.create("color: 'red', background:'blue'"))
  1460. * $(".item").css(Properties.create("color: red; background: blue;"))
  1461. * </pre>
  1462. */
  1463. public GQuery css(Properties properties) {
  1464. for (String property : properties.keys()) {
  1465. css(property, properties.getStr(property));
  1466. }
  1467. return this;
  1468. }
  1469. /**
  1470. * Return a style property on the first matched element.
  1471. */
  1472. public String css(String name) {
  1473. return css(name, true);
  1474. }
  1475. /**
  1476. * Return a style property on the first matched element.
  1477. *
  1478. * The parameter force has a special meaning here:
  1479. * <ul>
  1480. * <li>When force is false, returns the value of the css property defined in the style attribute
  1481. * of the element.
  1482. * <li>Otherwise it returns the real computed value.
  1483. * </ul>
  1484. *
  1485. * For instance if you don't define 'display=none'in the element style but in the css stylesheet,
  1486. * it returns an empty string unless you pass the parameter force=true.
  1487. */
  1488. public String css(String name, boolean force) {
  1489. return isEmpty() ? "" : getStyleImpl().curCSS(get(0), name, force);
  1490. }
  1491. /**
  1492. * Set a single style property to a value, on all matched elements.
  1493. *
  1494. */
  1495. public GQuery css(String prop, String val) {
  1496. for (Element e : elements) {
  1497. getStyleImpl().setStyleProperty(e, prop, val);
  1498. }
  1499. return this;
  1500. }
  1501. /**
  1502. * Set CSS a single style property on every matched element using type-safe enumerations. This
  1503. * method allows you to set manually the value or set <i>inherit</i> value
  1504. *
  1505. * ex :
  1506. *
  1507. * <pre class="code">
  1508. * $(#myId).css(CSS.TEXT_DECORATION, CSS.INHERIT);
  1509. * </pre>
  1510. */
  1511. public GQuery css(TakesCssValue<?> cssProperty, String value) {
  1512. return css(cssProperty.getCssName(), value);
  1513. }
  1514. /**
  1515. * Returns the numeric value of a css property.
  1516. */
  1517. public double cur(String prop) {
  1518. return cur(prop, false);
  1519. }
  1520. /**
  1521. * Returns the numeric value of a css property.
  1522. *
  1523. * The parameter force has a special meaning: - When force is false, returns the value of the css
  1524. * property defined in the set of style attributes. - When true returns the real computed value.
  1525. */
  1526. public double cur(String prop, boolean force) {
  1527. return isEmpty() ? 0 : getStyleImpl().cur(get(0), prop, force);
  1528. }
  1529. /**
  1530. * Return the value at the named data store for the first element in the set of matched
  1531. * elements.
  1532. */
  1533. @SuppressWarnings("unchecked")
  1534. public <T> T data(String name) {
  1535. return isEmpty() ? null : (T) data(get(0), name, null);
  1536. }
  1537. /**
  1538. * Return the value at the named data store for the first element in the set of matched
  1539. * elements, as set by data(name, value), with desired return type.
  1540. *
  1541. * @param clz return type class literal
  1542. */
  1543. public <T> T data(String name, Class<? extends T> clz) {
  1544. return isEmpty() ? null : data(get(0), name, null, clz);
  1545. }
  1546. /**
  1547. * Store arbitrary data associated with the matched elements in the named data store.
  1548. */
  1549. public GQuery data(String name, Object value) {
  1550. for (Element e : elements()) {
  1551. data(e, name, value);
  1552. }
  1553. return this;
  1554. }
  1555. /**
  1556. * Bind a set of functions to the dblclick event of each matched element. Or trigger the event if
  1557. * no functions are provided.
  1558. */
  1559. public GQuery dblclick(Function... f) {
  1560. return bindOrFire(Event.ONDBLCLICK, null, f);
  1561. }
  1562. /**
  1563. * Insert a delay (in ms) in the GQuery queue, and optionally execute one o more functions if
  1564. * provided when the delay finishes. It uses the effects queue namespace, so you can stack any of
  1565. * the methods in the effects plugin.
  1566. *
  1567. * Example:
  1568. *
  1569. * <pre class="code">
  1570. * $("#foo").slideUp(300)
  1571. * .delay(800)
  1572. * .fadeIn(400);
  1573. * </pre>
  1574. *
  1575. * When this statement is executed, the element slides up for 300 milliseconds and then pauses for
  1576. * 800 milliseconds before fading in for 400 milliseconds. Aditionally after those 800
  1577. * milliseconds the element color is set to red.
  1578. *
  1579. * NOTE that this methods affects only methods which uses the queue like effects. So the following
  1580. * example is wrong:
  1581. *
  1582. * <pre>
  1583. * $("#foo").css(CSS.COLOR.with(RGBColor.RED)).delay(800).css(CSS.COLOR.with(RGBColor.BLACK));
  1584. * </pre>
  1585. *
  1586. * The code above will not insert a delay of 800 ms between the css() calls ! For this kind of
  1587. * behavior, you should execute these methods puting them in inline functions passed as argument
  1588. * to the delay() method, or adding them to the queue.
  1589. *
  1590. * <pre>
  1591. * $("#foo").css(CSS.COLOR.with(RGBColor.RED)).delay(800, lazy().css(CSS.COLOR.with(RGBColor.BLACK)).done());
  1592. * $("#foo").css(CSS.COLOR.with(RGBColor.RED)).delay(800).queue(lazy().css(CSS.COLOR.with(RGBColor.BLACK)).dequeue().done());
  1593. * </pre>
  1594. */
  1595. public GQuery delay(int milliseconds, Function... f) {
  1596. return as(Queue).delay(milliseconds, f);
  1597. }
  1598. /**
  1599. * Insert a delay (in ms) in the queue identified by the <code>queueName</code> parameter, and
  1600. * optionally execute one o more functions if provided when the delay finishes.
  1601. *
  1602. * If <code>queueName</code> is null or equats to 'fx', the delay will be inserted to the Effects
  1603. * queue.
  1604. *
  1605. * Example :
  1606. *
  1607. * <pre class="code">
  1608. * $("#foo").queue("colorQueue", lazy().css(CSS.COLOR.with(RGBColor.RED)).dequeue("colorQueue").done())
  1609. * .delay(800, "colorQueue")
  1610. * .queue("colorQueue", lazy().css(CSS.COLOR.with(RGBColor.BLACK)).dequeue("colorQueue").done());
  1611. * </pre>
  1612. *
  1613. * When this statement is executed, the text color of the element changes to red and then wait for
  1614. * 800 milliseconds before changes the text color to black.
  1615. *
  1616. */
  1617. public GQuery delay(int milliseconds, String queueName, Function... f) {
  1618. return as(Queue).delay(milliseconds, queueName, f);
  1619. }
  1620. /**
  1621. * Attach <code>handlers</code> to one or more events for all elements that match the
  1622. * <code>selector</code>, now or in the future, based on a specific set of root elements.
  1623. *
  1624. * Example:
  1625. *
  1626. * <pre>
  1627. * $("table").delegate("td", Event.ONCLICK, new Function(){
  1628. * public void f(Element e){
  1629. * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
  1630. * }
  1631. * });
  1632. * </pre>
  1633. *
  1634. * This code above add an handler on click event on all cell (the existing oneand the future cell)
  1635. * of all table. This code is equivalent to :
  1636. *
  1637. * <pre>
  1638. * $("table").each(new Function(){
  1639. * public void f(Element table){
  1640. * $("td", table).live(Event.ONCLICK, new Function(){
  1641. * public void f(Element e){
  1642. * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
  1643. * }
  1644. * }
  1645. * });
  1646. *
  1647. * </pre>
  1648. *
  1649. * You can attach the handlers to many events by using the '|' operator ex:
  1650. *
  1651. * <pre>
  1652. * $("div.main").delegate(".subMain", Event.ONCLICK | Event.ONDBLCLICK, new Function(){...});
  1653. * </pre>
  1654. * @deprecated use {@link #on(String, String, Function...)}
  1655. */
  1656. public GQuery delegate(String selector, int eventbits, Function... handlers) {
  1657. return delegate(selector, eventbits, null, handlers);
  1658. }
  1659. /**
  1660. * Attach <code>handlers</code> to one or more events for all elements that match the
  1661. * <code>selector</code>, now or in the future, based on a specific set of root elements. The
  1662. * <code>data</code> parameter allows us to pass data to the handler.
  1663. *
  1664. * Example:
  1665. *
  1666. * <pre>
  1667. * $("table").delegate("td", "click", new Function(){
  1668. * public void f(Element e){
  1669. * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
  1670. * }
  1671. * });
  1672. * </pre>
  1673. *
  1674. * This code above add an handler on click event on all cell (the existing oneand the future cell)
  1675. * of all table. This code is equivalent to :
  1676. *
  1677. * <pre>
  1678. * $("table").each(new Function(){
  1679. * public void f(Element table){
  1680. * $("td", table).live("click", new Function(){
  1681. * public void f(Element e){
  1682. * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
  1683. * }
  1684. * }
  1685. * });
  1686. *
  1687. * </pre>
  1688. *
  1689. * You can pass attach the handlers to many events by using the '|' operator ex:
  1690. *
  1691. * <pre>
  1692. * $("div.main").delegate(".subMain", Event.ONCLICK | Event.ONDBLCLICK, new Function(){...});
  1693. * </pre>
  1694. * @deprecated use {@link #on(String, String, Object, Function...)}
  1695. */
  1696. public GQuery delegate(String selector, int eventbits, Object data, Function... handlers) {
  1697. for (Element e : elements) {
  1698. $(selector, e).live(eventbits, data, handlers);
  1699. }
  1700. return this;
  1701. }
  1702. /**
  1703. * Attach <code>handlers</code> to one or more events for all elements that match the
  1704. * <code>selector</code>, now or in the future, based on a specific set of root elements.
  1705. *
  1706. * Example:
  1707. *
  1708. * <pre>
  1709. * $("table").delegate("td", "click", new Function(){
  1710. * public void f(Element e){
  1711. * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
  1712. * }
  1713. * });
  1714. * </pre>
  1715. *
  1716. * This code above add an handler on click event on all cell (the existing oneand the future cell)
  1717. * of all table. This code is equivalent to :
  1718. *
  1719. * <pre>
  1720. * $("table").each(new Function(){
  1721. * public void f(Element table){
  1722. * $("td", table).live("click", new Function(){
  1723. * public void f(Element e){
  1724. * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
  1725. * }
  1726. * }
  1727. * });
  1728. *
  1729. * </pre>
  1730. *
  1731. * You can pass attach the handlers to many events by specifying a String with espaced event type.
  1732. * ex:
  1733. *
  1734. * <pre>
  1735. * $("div.main").delegate(".subMain", "click dblclick", new Function(){...});
  1736. * </pre>
  1737. *
  1738. * </pre>
  1739. * @deprecated use {@link #on(String, String, Function...)}
  1740. */
  1741. public GQuery delegate(String selector, String eventType, Function... handlers) {
  1742. return delegate(selector, eventType, null, handlers);
  1743. }
  1744. /**
  1745. * Attach <code>handlers</code> to one or more events for all elements that match the
  1746. * <code>selector</code>, now or in the future, based on a specific set of root elements.
  1747. *
  1748. * Example:
  1749. *
  1750. * <pre>
  1751. * $("table").delegate("td", "click", new Function(){
  1752. * public void f(Element e){
  1753. * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
  1754. * }
  1755. * });
  1756. * </pre>
  1757. *
  1758. * This code above add an handler on click event on all cell (the existing oneand the future cell)
  1759. * of all table. This code is equivalent to :
  1760. *
  1761. * <pre>
  1762. * $("table").each(new Function(){
  1763. * public void f(Element table){
  1764. * $("td", table).live("click", new Function(){
  1765. * public void f(Element e){
  1766. * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
  1767. * }
  1768. * }
  1769. * });
  1770. *
  1771. * You can pass attach the handlers to many events by specifying a String with espaced event type.
  1772. * ex:
  1773. *
  1774. * <pre>
  1775. * $("div.main").delegate(".subMain", "click dblclick", new Function(){...});
  1776. * </pre>
  1777. *
  1778. * </pre>
  1779. * @deprecated use {@link #on(String, String, Object, Function...)}
  1780. */
  1781. public GQuery delegate(String selector, String eventType, Object data, Function... handlers) {
  1782. for (Element e : elements) {
  1783. $(selector, e).live(eventType, data, handlers);
  1784. }
  1785. return this;
  1786. }
  1787. /**
  1788. * Execute the next function on the Effects queue for the matched elements. This method is usefull
  1789. * to tell when a function you add in the Effects queue is ended and so the next function in the
  1790. * queue can start.
  1791. *
  1792. * Note: you should be sure to call dequeue() in all functions of a queue chain, otherwise the
  1793. * queue execution will be stopped.
  1794. */
  1795. public GQuery dequeue() {
  1796. return as(Queue).dequeue();
  1797. }
  1798. /**
  1799. * Execute the next function on the queue named as queueName for the matched elements. This method
  1800. * is usefull to tell when a function you add in the Effects queue is ended and so the next
  1801. * function in the queue can start.
  1802. */
  1803. public GQuery dequeue(String queueName) {
  1804. return as(Queue).dequeue(queueName);
  1805. }
  1806. /**
  1807. * Detach all matched elements from the DOM. This method is the same than {@link #remove()} method
  1808. * except all data and event handlers are not remove from the element. This method is useful when
  1809. * removed elements are to be reinserted into the DOM at a later time.
  1810. */
  1811. public GQuery detach() {
  1812. return remove(null, false);
  1813. }
  1814. /**
  1815. * Detach from the DOM all matched elements filtered by the <code>filter</code>.. This method is
  1816. * the same than {@link #remove(String)} method except all data and event handlers are not remove
  1817. * from the element. This method is useful when removed elements are to be reinserted into the DOM
  1818. * at a later time.
  1819. */
  1820. public GQuery detach(String filter) {
  1821. return remove(filter, false);
  1822. }
  1823. /**
  1824. * Remove all event handlers previously attached using {@link #live(String, Function)}. In order
  1825. * for this method to function correctly, the selector used with it must match exactly the
  1826. * selector initially used with {@link #live(String, Function)}.
  1827. *
  1828. * @deprecated use {@link #off(String, String)} instead
  1829. */
  1830. public GQuery die() {
  1831. return die(0);
  1832. }
  1833. /**
  1834. * Remove an event handlers previously attached using {@link #live(int, Function)} In order for
  1835. * this method to function correctly, the selector used with it must match exactly the selector
  1836. * initially used with {@link #live(int, Function)}.
  1837. * @deprecated use {@link #off(String)}
  1838. */
  1839. public GQuery die(int eventbits) {
  1840. return as(Events).die(eventbits);
  1841. }
  1842. /**
  1843. * Remove an event handlers previously attached using {@link #live(String, Function)} In order for
  1844. * this method to function correctly, the selector used with it must match exactly the selector
  1845. * initially used with {@link #live(String, Function)}.
  1846. */
  1847. public GQuery die(String eventName) {
  1848. return as(Events).die(eventName);
  1849. }
  1850. private GQuery domManip(GQuery g, DomMan type, Element... elms) {
  1851. JsNodeArray newNodes = JsNodeArray.create();
  1852. if (elms.length == 0) {
  1853. elms = elements;
  1854. }
  1855. for (int i = 0, l = elms.length; i < l; i++) {
  1856. Element e = elms[i];
  1857. if (e.getNodeType() == Node.DOCUMENT_NODE) {
  1858. e = e.<Document> cast().getBody();
  1859. }
  1860. for (int j = 0, size = g.size(); j < size; j++) {
  1861. // Widget w = getAssociatedWidget(g.get(j));
  1862. // GqUi.detachWidget(w);
  1863. Node n = g.get(j);
  1864. // If an element selected is inserted elsewhere, it will be moved into the target (not
  1865. // cloned).
  1866. // If there is more than one target element, however, cloned copies of the inserted element
  1867. // will be created for each target after the first
  1868. if (i > 0) {
  1869. n = n.cloneNode(true);
  1870. }
  1871. switch (type) {
  1872. case PREPEND:
  1873. newNodes.addNode(e.insertBefore(n, e.getFirstChild()));
  1874. break;
  1875. case APPEND:
  1876. newNodes.addNode(e.appendChild(n));
  1877. break;
  1878. case AFTER:
  1879. newNodes.addNode(e.getParentNode().insertBefore(n, e.getNextSibling()));
  1880. break;
  1881. case BEFORE:
  1882. newNodes.addNode(e.getParentNode().insertBefore(n, e));
  1883. break;
  1884. }
  1885. EventsListener.rebind(n.<Element> cast());
  1886. // GqUi.attachWidget(w);
  1887. }
  1888. }
  1889. // TODO: newNodes.size() > g.size() makes testRebind fail
  1890. if (newNodes.size() >= g.size()) {
  1891. g.setArray(newNodes);
  1892. }
  1893. return this;
  1894. }
  1895. // TODO: this should be handled by the other domManip method
  1896. private GQuery domManip(String htmlString, DomMan type) {
  1897. JsMap<Document, GQuery> cache = JsMap.createObject().cast();
  1898. for (Element e : elements) {
  1899. Document d = JsUtils.getOwnerDocument(e);
  1900. GQuery g = cache.get(d);
  1901. if (g == null) {
  1902. g = cleanHtmlString(htmlString, d);
  1903. cache.put(d, g);
  1904. }
  1905. domManip(g.clone(), type, e);
  1906. }
  1907. return this;
  1908. }
  1909. /**
  1910. * Run one or more Functions over each element of the GQuery. You have to override one of these
  1911. * funcions: public void f(Element e) public String f(Element e, int i)
  1912. */
  1913. public GQuery each(Function... f) {
  1914. if (f != null) {
  1915. for (Function f1 : f) {
  1916. if (f1 != null) {
  1917. int i = 0;
  1918. for (Element e : elements) {
  1919. f1.f(e.<com.google.gwt.dom.client.Element> cast(), i++);
  1920. }
  1921. }
  1922. }
  1923. }
  1924. return this;
  1925. }
  1926. /**
  1927. * Returns the working set of nodes as a Java array. <b>Do NOT</b> attempt to modify this array,
  1928. * e.g. assign to its elements, or call Arrays.sort()
  1929. */
  1930. public Element[] elements() {
  1931. return elements;
  1932. }
  1933. /**
  1934. * Remove all child nodes from the set of matched elements. In the case of a document element, it
  1935. * removes all the content You should call this method whenever you create a new iframe and you
  1936. * want to add dynamic content to it.
  1937. */
  1938. public GQuery empty() {
  1939. for (Element e : elements) {
  1940. if (e.getNodeType() == Element.DOCUMENT_NODE) {
  1941. getStyleImpl().emptyDocument(e.<Document> cast());
  1942. } else {
  1943. Node c = e.getFirstChild();
  1944. while (c != null) {
  1945. removeData(c.<Element> cast(), null);
  1946. WidgetsUtils.detachWidget(getAssociatedWidget(e));
  1947. EventsListener.clean(c.<Element> cast());
  1948. e.removeChild(c);
  1949. c = e.getFirstChild();
  1950. }
  1951. }
  1952. }
  1953. return this;
  1954. }
  1955. /**
  1956. * Revert the most recent 'destructive' operation, changing the set of matched elements to its
  1957. * previous state (right before the destructive operation).
  1958. */
  1959. public GQuery end() {
  1960. return previousObject != null ? previousObject : new GQuery();
  1961. }
  1962. /**
  1963. * Reduce GQuery to element in the specified position. This method accept negative index. A
  1964. * negative index is counted from the end of the matched set:
  1965. *
  1966. * Example:
  1967. *
  1968. * <pre>
  1969. * $("div").eq(0) will reduce the matched set to the first matched div
  1970. * $("div").eq(1) will reduce the matched set to the second matched div
  1971. *
  1972. * $("div").eq(-1) will reduce the matched set to the last matched div
  1973. * $("div").eq(-2) will reduce the matched set to the second-to-last matched div
  1974. * ...
  1975. * </pre>
  1976. */
  1977. public GQuery eq(int pos) {
  1978. return $(get(pos));
  1979. }
  1980. /**
  1981. * Bind a set of functions to the error event of each matched element. Or trigger the event if no
  1982. * functions are provided.
  1983. */
  1984. public GQuery error(Function... f) {
  1985. return bindOrFire(Event.ONERROR, null, f);
  1986. }
  1987. /**
  1988. * Fade in all matched elements by adjusting their opacity. The effect will take 1000 milliseconds
  1989. * to complete
  1990. */
  1991. public GQuery fadeIn(Function... f) {
  1992. return as(Effects).fadeIn(f);
  1993. }
  1994. /**
  1995. * Fade in all matched elements by adjusting their opacity.
  1996. */
  1997. public GQuery fadeIn(int millisecs, Function... f) {
  1998. return as(Effects).fadeIn(millisecs, f);
  1999. }
  2000. /**
  2001. * Fade the opacity of all matched elements to a specified opacity and firing
  2002. * an optional callback after completion. Only the opacity is adjusted for
  2003. * this animation, meaning that all of the matched elements should already
  2004. * have some form of height and width associated with them.
  2005. */
  2006. public GQuery fadeTo(int millisecs, double opacity, Function... f) {
  2007. return as(Effects).fadeTo(millisecs, opacity, f);
  2008. }
  2009. /**
  2010. * Fade the opacity of all matched elements to a specified opacity and firing
  2011. * an optional callback after completion. Only the opacity is adjusted for
  2012. * this animation, meaning that all of the matched elements should already
  2013. * have some form of height and width associated with them.
  2014. */
  2015. public GQuery fadeTo(double opacity, Function... f) {
  2016. return as(Effects).fadeTo(opacity, f);
  2017. }
  2018. /**
  2019. * Fade out all matched elements by adjusting their opacity. The effect will take 1000
  2020. * milliseconds to complete
  2021. */
  2022. public GQuery fadeOut(Function... f) {
  2023. return as(Effects).fadeOut(f);
  2024. }
  2025. /**
  2026. * Fade out all matched elements by adjusting their opacity.
  2027. */
  2028. public GQuery fadeOut(int millisecs, Function... f) {
  2029. return as(Effects).fadeOut(millisecs, f);
  2030. }
  2031. /**
  2032. * Toggle the visibility of all matched elements by adjusting their opacity and firing an optional
  2033. * callback after completion. Only the opacity is adjusted for this animation, meaning that all of
  2034. * the matched elements should already have some form of height and width associated with them.
  2035. */
  2036. public Effects fadeToggle(int millisecs, Function... f) {
  2037. return as(Effects).fadeToggle(millisecs, f);
  2038. }
  2039. /**
  2040. * Removes all elements from the set of matched elements that do not match the specified function.
  2041. * The function is called with a context equal to the current element. If the function returns
  2042. * false, then the element is removed - anything else and the element is kept.
  2043. */
  2044. public GQuery filter(Predicate filterFn) {
  2045. JsNodeArray result = getSelectorEngine().filter(nodeList, filterFn).cast();
  2046. return pushStack(result, "filter", currentSelector);
  2047. }
  2048. /**
  2049. * Removes all elements from the set of matched elements that do not pass the specified css
  2050. * expression. This method is used to narrow down the results of a search.
  2051. * By default it works for either detached and attached elements unless
  2052. * {@link SelectorEngine#filterDetached} is set to false.
  2053. */
  2054. public GQuery filter(String... filters) {
  2055. String selector = join(", ", filters);
  2056. JsNodeArray result = getSelectorEngine().filter(nodeList, selector).cast();
  2057. return pushStack(result, "filter", selector);
  2058. }
  2059. /**
  2060. * Removes all elements from the set of matched elements that do not pass the specified css
  2061. * expression. This method is used to narrow down the results of a search.
  2062. * Setting filterDetached parameter to true, means that we should consider detached elements
  2063. * as well which implies some performance penalty.
  2064. */
  2065. public GQuery filter(boolean filterDetached, String... filters) {
  2066. String selector = join(", ", filters);
  2067. JsNodeArray result = getSelectorEngine().filter(nodeList, selector, filterDetached).cast();
  2068. return pushStack(result, "filter", selector);
  2069. }
  2070. /**
  2071. * Removes all elements from the set of matched elements that do not pass the specified css
  2072. * expression. This method is used to narrow down the results of a search.
  2073. * Setting considerDetached parameter to true, means that we should consider detached elements
  2074. * as well which implies some performance penalties.
  2075. */
  2076. public GQuery filter(boolean filterDetached, String selector) {
  2077. if (selector.isEmpty()) {
  2078. return this;
  2079. }
  2080. JsNodeArray result = getSelectorEngine().filter(nodeList, selector, filterDetached).cast();
  2081. return pushStack(result, "filter", selector);
  2082. }
  2083. /**
  2084. * Searches for all elements that match the specified css expression. This method is a good way to
  2085. * find additional descendant elements with which to process.
  2086. *
  2087. * Provide a comma-separated list of expressions to apply multiple filters at once.
  2088. */
  2089. public GQuery find(String... filters) {
  2090. JsNodeArray array = JsNodeArray.create();
  2091. for (String selector : filters) {
  2092. for (Element e : elements) {
  2093. for (Element c : $(selector, e).elements) {
  2094. array.addNode(c);
  2095. }
  2096. }
  2097. }
  2098. return pushStack(unique(array), "find", filters[0]);
  2099. }
  2100. /**
  2101. * Reduce the set of matched elements to the first in the set.
  2102. */
  2103. public GQuery first() {
  2104. return eq(0);
  2105. }
  2106. /**
  2107. * Bind a set of functions to the focus event of each matched element. Or trigger the event and
  2108. * move the input focus to the first element if no functions are provided.
  2109. */
  2110. public GQuery focus(Function... f) {
  2111. bindOrFire(Event.ONFOCUS, null, f);
  2112. if (!isEmpty() && f.length == 0) {
  2113. get(0).focus();
  2114. }
  2115. return this;
  2116. }
  2117. /**
  2118. * Return all elements matched in the GQuery as a NodeList. @see #elements() for a method which
  2119. * returns them as an immutable Java array.
  2120. */
  2121. public NodeList<Element> get() {
  2122. return nodeList;
  2123. }
  2124. /**
  2125. * Return the ith element matched. This method accept negative index. A negative index is counted
  2126. * from the end of the matched set.
  2127. *
  2128. * Example:
  2129. *
  2130. * <pre>
  2131. * $("div").get(0) will return the first matched div
  2132. * $("div").get(1) will return the second matched div
  2133. *
  2134. * $("div").get(-1) will return the last matched div
  2135. * $("div").get(-2) will return the secont-to-last matched div
  2136. * ...
  2137. * </pre>
  2138. */
  2139. public Element get(int i) {
  2140. int l = elements.length;
  2141. if (i >= 0 && i < l) {
  2142. return elements[i];
  2143. }
  2144. if (i < 0 && l + i >= 0) {
  2145. return elements[l + i];
  2146. }
  2147. return null;
  2148. }
  2149. public Node getContext() {
  2150. return currentContext;
  2151. }
  2152. /**
  2153. * Return the previous set of matched elements prior to the last destructive operation (e.g.
  2154. * query)
  2155. */
  2156. public GQuery getPreviousObject() {
  2157. return end();
  2158. }
  2159. private native Element getPreviousSiblingElement(Element elem) /*-{
  2160. var sib = elem.previousSibling;
  2161. while (sib && sib.nodeType != 1)
  2162. sib = sib.previousSibling;
  2163. return sib;
  2164. }-*/;
  2165. /**
  2166. * Return the selector representing the current set of matched elements.
  2167. */
  2168. public String getSelector() {
  2169. return currentSelector;
  2170. }
  2171. /**
  2172. * Returns true any of the specified classes are present on any of the matched Reduce the set of
  2173. * matched elements to all elements after a given position. The position of the element in the set
  2174. * of matched elements starts at 0 and goes to length - 1.
  2175. */
  2176. public GQuery gt(int pos) {
  2177. return slice(pos + 1, -1);
  2178. }
  2179. /**
  2180. * Reduce the set of matched elements to those that have a descendant that matches the Element.
  2181. */
  2182. public GQuery has(final Element elem) {
  2183. return filter(new Predicate() {
  2184. public boolean f(Element e, int index) {
  2185. return contains(e, elem);
  2186. }
  2187. });
  2188. }
  2189. /**
  2190. * Reduce the set of matched elements to those that have a descendant that matches the selector.
  2191. */
  2192. public GQuery has(final String selector) {
  2193. return filter(new Predicate() {
  2194. public boolean f(Element e, int index) {
  2195. return !$(selector, e).isEmpty();
  2196. }
  2197. });
  2198. }
  2199. /**
  2200. * Returns true any of the specified classes are present on any of the matched elements.
  2201. */
  2202. public boolean hasClass(String... classes) {
  2203. for (Element e : elements) {
  2204. for (String clz : classes) {
  2205. if (hasClass(e, clz)) {
  2206. return true;
  2207. }
  2208. }
  2209. }
  2210. return false;
  2211. }
  2212. /**
  2213. * Get the current computed, pixel, height of the first matched element. It does not include
  2214. * margin, padding nor border.
  2215. */
  2216. public int height() {
  2217. return (int) cur("height", true);
  2218. }
  2219. /**
  2220. * Set the height of every element in the matched set.
  2221. */
  2222. public GQuery height(int height) {
  2223. for (Element e : elements) {
  2224. e.getStyle().setPropertyPx("height", height);
  2225. }
  2226. return this;
  2227. }
  2228. /**
  2229. * Set the height style property of every matched element. It's useful for using 'percent' or 'em'
  2230. * units Example: $(".a").height("100%")
  2231. */
  2232. public GQuery height(String height) {
  2233. return css("height", height);
  2234. }
  2235. /**
  2236. * Make invisible all matched elements.
  2237. */
  2238. public GQuery hide() {
  2239. for (Element e : elements) {
  2240. String currentDisplay = getStyleImpl().curCSS(e, "display", false);
  2241. Object old = data(e, OLD_DISPLAY, null);
  2242. if (old == null && currentDisplay.length() != 0 && !"none".equals(currentDisplay)) {
  2243. data(e, OLD_DISPLAY, currentDisplay);
  2244. }
  2245. }
  2246. // Set the display value in a separate for loop to avoid constant reflow
  2247. // Reflows is very bad in performance point of view
  2248. for (Element e : elements) {
  2249. e.getStyle().setDisplay(Display.NONE);
  2250. }
  2251. return this;
  2252. }
  2253. /**
  2254. * Bind a function to the mouseover event of each matched element. A method for simulating
  2255. * hovering (moving the mouse on, and off, an object). This is a custom method which provides an
  2256. * 'in' to a frequent task. Whenever the mouse cursor is moved over a matched element, the first
  2257. * specified function is fired. Whenever the mouse moves off of the element, the second specified
  2258. * function fires.
  2259. *
  2260. * Since GQuery 1.4.0, this method binds handlers for both mouseenter and mouseleave events.
  2261. */
  2262. public GQuery hover(Function fover, Function fout) {
  2263. return bind("mouseenter", fover).bind("mouseleave", fout);
  2264. }
  2265. /**
  2266. * Get the innerHTML of the first matched element.
  2267. */
  2268. public String html() {
  2269. return isEmpty() ? "" : get(0).getInnerHTML();
  2270. }
  2271. /**
  2272. * Set the innerHTML of every matched element.
  2273. */
  2274. public GQuery html(String html) {
  2275. for (Element e : elements) {
  2276. if (e.getNodeType() == Node.DOCUMENT_NODE) {
  2277. e = e.<Document> cast().getBody();
  2278. }
  2279. e.setInnerHTML(html);
  2280. }
  2281. return this;
  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<W>();
  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<Element>();
  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<Widget>();
  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<W>();
  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 all the elements in the matched set into a single wrapper element. This is different from
  4480. * .wrap() where each element in the matched set would get wrapped with an element. This wrapping
  4481. * process is most useful for injecting additional structure into a document, without ruining the
  4482. * original semantic qualities of a document.
  4483. *
  4484. * This works by going through the first element provided (which is generated, on the fly, from
  4485. * the provided HTML) and finds the deepest descendant element within its structure -- it is that
  4486. * element that will enwrap everything else.
  4487. */
  4488. public GQuery wrapAll(Element elem) {
  4489. return wrapAll($(elem));
  4490. }
  4491. /**
  4492. * Wrap all the elements in the matched set into a single wrapper element. This is different from
  4493. * .wrap() where each element in the matched set would get wrapped with an element. This wrapping
  4494. * process is most useful for injecting additional structure into a document, without ruining the
  4495. * original semantic qualities of a document.
  4496. *
  4497. * This works by going through the first element provided (which is generated, on the fly, from
  4498. * the provided HTML) and finds the deepest descendant element within its structure -- it is that
  4499. * element that will enwrap everything else.
  4500. */
  4501. public GQuery wrapAll(GQuery query) {
  4502. if (!isEmpty()) {
  4503. GQuery wrap = query.clone();
  4504. if (get(0).getParentNode() != null) {
  4505. wrap.insertBefore(get(0));
  4506. }
  4507. for (Element e : wrap.elements) {
  4508. Node n = e;
  4509. while (n.getFirstChild() != null && n.getFirstChild().getNodeType() == Node.ELEMENT_NODE) {
  4510. n = n.getFirstChild();
  4511. }
  4512. $((Element) n).append(this);
  4513. }
  4514. }
  4515. return this;
  4516. }
  4517. /**
  4518. * Wrap all the elements in the matched set into a single wrapper element. This is different from
  4519. * .wrap() where each element in the matched set would get wrapped with an element. This wrapping
  4520. * process is most useful for injecting additional structure into a document, without ruining the
  4521. * original semantic qualities of a document.
  4522. *
  4523. * This works by going through the first element provided (which is generated, on the fly, from
  4524. * the provided HTML) and finds the deepest descendant element within its structure -- it is that
  4525. * element that will enwrap everything else.
  4526. */
  4527. public GQuery wrapAll(String html) {
  4528. return wrapAll($(html));
  4529. }
  4530. /**
  4531. * Wrap the inner child contents of each matched element (including text nodes) with an HTML
  4532. * structure. This wrapping process is most useful for injecting additional structure into a
  4533. * document, without ruining the original semantic qualities of a document. This works by going
  4534. * through the first element provided (which is generated, on the fly, from the provided HTML) and
  4535. * finds the deepest ancestor element within its structure -- it is that element that will enwrap
  4536. * everything else.
  4537. */
  4538. public GQuery wrapInner(Element elem) {
  4539. return wrapInner($(elem));
  4540. }
  4541. /**
  4542. * Wrap the inner child contents of each matched element (including text nodes) with an HTML
  4543. * structure. This wrapping process is most useful for injecting additional structure into a
  4544. * document, without ruining the original semantic qualities of a document. This works by going
  4545. * through the first element provided (which is generated, on the fly, from the provided HTML) and
  4546. * finds the deepest ancestor element within its structure -- it is that element that will enwrap
  4547. * everything else.
  4548. */
  4549. public GQuery wrapInner(GQuery query) {
  4550. for (Element e : elements) {
  4551. $(e).contents().wrapAll(query);
  4552. }
  4553. return this;
  4554. }
  4555. /**
  4556. * Wrap the inner child contents of each matched element (including text nodes) with an HTML
  4557. * structure. This wrapping process is most useful for injecting additional structure into a
  4558. * document, without ruining the original semantic qualities of a document. This works by going
  4559. * through the first element provided (which is generated, on the fly, from the provided HTML) and
  4560. * finds the deepest ancestor element within its structure -- it is that element that will enwrap
  4561. * everything else.
  4562. */
  4563. public GQuery wrapInner(String html) {
  4564. return wrapInner($(html));
  4565. }
  4566. private String join(String chr, String... values) {
  4567. String value = "";
  4568. for (int i = 0; i < values.length; i++) {
  4569. value += i > 0 ? chr + values[i] : values[i];
  4570. }
  4571. return value;
  4572. }
  4573. }