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.

Grid.java 164KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803
  1. /*
  2. * Copyright 2000-2018 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.ui;
  17. import java.io.Serializable;
  18. import java.lang.reflect.Method;
  19. import java.lang.reflect.Type;
  20. import java.util.ArrayList;
  21. import java.util.Arrays;
  22. import java.util.Collection;
  23. import java.util.Collections;
  24. import java.util.Comparator;
  25. import java.util.HashMap;
  26. import java.util.HashSet;
  27. import java.util.Iterator;
  28. import java.util.LinkedHashSet;
  29. import java.util.List;
  30. import java.util.Map;
  31. import java.util.Objects;
  32. import java.util.Optional;
  33. import java.util.Set;
  34. import java.util.UUID;
  35. import java.util.function.BinaryOperator;
  36. import java.util.function.Function;
  37. import java.util.stream.Collectors;
  38. import java.util.stream.Stream;
  39. import org.jsoup.nodes.Attributes;
  40. import org.jsoup.nodes.Element;
  41. import org.jsoup.select.Elements;
  42. import com.vaadin.data.BeanPropertySet;
  43. import com.vaadin.data.Binder;
  44. import com.vaadin.data.Binder.Binding;
  45. import com.vaadin.data.HasDataProvider;
  46. import com.vaadin.data.HasValue;
  47. import com.vaadin.data.PropertyDefinition;
  48. import com.vaadin.data.PropertySet;
  49. import com.vaadin.data.ValueProvider;
  50. import com.vaadin.data.provider.CallbackDataProvider;
  51. import com.vaadin.data.provider.DataCommunicator;
  52. import com.vaadin.data.provider.DataGenerator;
  53. import com.vaadin.data.provider.DataProvider;
  54. import com.vaadin.data.provider.GridSortOrder;
  55. import com.vaadin.data.provider.GridSortOrderBuilder;
  56. import com.vaadin.data.provider.InMemoryDataProvider;
  57. import com.vaadin.data.provider.Query;
  58. import com.vaadin.data.provider.QuerySortOrder;
  59. import com.vaadin.event.ConnectorEvent;
  60. import com.vaadin.event.ContextClickEvent;
  61. import com.vaadin.event.HasUserOriginated;
  62. import com.vaadin.event.SortEvent;
  63. import com.vaadin.event.SortEvent.SortListener;
  64. import com.vaadin.event.SortEvent.SortNotifier;
  65. import com.vaadin.event.selection.MultiSelectionListener;
  66. import com.vaadin.event.selection.SelectionListener;
  67. import com.vaadin.event.selection.SingleSelectionListener;
  68. import com.vaadin.server.AbstractExtension;
  69. import com.vaadin.server.EncodeResult;
  70. import com.vaadin.server.Extension;
  71. import com.vaadin.server.JsonCodec;
  72. import com.vaadin.server.SerializableComparator;
  73. import com.vaadin.server.SerializableSupplier;
  74. import com.vaadin.server.Setter;
  75. import com.vaadin.server.VaadinServiceClassLoaderUtil;
  76. import com.vaadin.shared.Connector;
  77. import com.vaadin.shared.MouseEventDetails;
  78. import com.vaadin.shared.Registration;
  79. import com.vaadin.shared.data.DataCommunicatorConstants;
  80. import com.vaadin.shared.data.sort.SortDirection;
  81. import com.vaadin.shared.ui.ContentMode;
  82. import com.vaadin.shared.ui.grid.AbstractGridExtensionState;
  83. import com.vaadin.shared.ui.grid.ColumnResizeMode;
  84. import com.vaadin.shared.ui.grid.ColumnState;
  85. import com.vaadin.shared.ui.grid.DetailsManagerState;
  86. import com.vaadin.shared.ui.grid.GridClientRpc;
  87. import com.vaadin.shared.ui.grid.GridConstants;
  88. import com.vaadin.shared.ui.grid.GridConstants.Section;
  89. import com.vaadin.shared.ui.grid.GridServerRpc;
  90. import com.vaadin.shared.ui.grid.GridState;
  91. import com.vaadin.shared.ui.grid.GridStaticCellType;
  92. import com.vaadin.shared.ui.grid.HeightMode;
  93. import com.vaadin.shared.ui.grid.ScrollDestination;
  94. import com.vaadin.shared.ui.grid.SectionState;
  95. import com.vaadin.ui.components.grid.ColumnReorderListener;
  96. import com.vaadin.ui.components.grid.ColumnResizeListener;
  97. import com.vaadin.ui.components.grid.ColumnVisibilityChangeListener;
  98. import com.vaadin.ui.components.grid.DetailsGenerator;
  99. import com.vaadin.ui.components.grid.Editor;
  100. import com.vaadin.ui.components.grid.EditorImpl;
  101. import com.vaadin.ui.components.grid.Footer;
  102. import com.vaadin.ui.components.grid.FooterRow;
  103. import com.vaadin.ui.components.grid.GridMultiSelect;
  104. import com.vaadin.ui.components.grid.GridSelectionModel;
  105. import com.vaadin.ui.components.grid.GridSingleSelect;
  106. import com.vaadin.ui.components.grid.Header;
  107. import com.vaadin.ui.components.grid.Header.Row;
  108. import com.vaadin.ui.components.grid.HeaderCell;
  109. import com.vaadin.ui.components.grid.HeaderRow;
  110. import com.vaadin.ui.components.grid.ItemClickListener;
  111. import com.vaadin.ui.components.grid.MultiSelectionModel;
  112. import com.vaadin.ui.components.grid.MultiSelectionModelImpl;
  113. import com.vaadin.ui.components.grid.NoSelectionModel;
  114. import com.vaadin.ui.components.grid.SingleSelectionModel;
  115. import com.vaadin.ui.components.grid.SingleSelectionModelImpl;
  116. import com.vaadin.ui.components.grid.SortOrderProvider;
  117. import com.vaadin.ui.declarative.DesignAttributeHandler;
  118. import com.vaadin.ui.declarative.DesignContext;
  119. import com.vaadin.ui.declarative.DesignException;
  120. import com.vaadin.ui.declarative.DesignFormatter;
  121. import com.vaadin.ui.renderers.AbstractRenderer;
  122. import com.vaadin.ui.renderers.ComponentRenderer;
  123. import com.vaadin.ui.renderers.HtmlRenderer;
  124. import com.vaadin.ui.renderers.Renderer;
  125. import com.vaadin.ui.renderers.TextRenderer;
  126. import com.vaadin.util.ReflectTools;
  127. import elemental.json.Json;
  128. import elemental.json.JsonObject;
  129. import elemental.json.JsonValue;
  130. /**
  131. * A grid component for displaying tabular data.
  132. *
  133. * @author Vaadin Ltd
  134. * @since 8.0
  135. *
  136. * @param <T>
  137. * the grid bean type
  138. */
  139. public class Grid<T> extends AbstractListing<T> implements HasComponents,
  140. HasDataProvider<T>, SortNotifier<GridSortOrder<T>> {
  141. private static final String DECLARATIVE_DATA_ITEM_TYPE = "data-item-type";
  142. /**
  143. * A callback method for fetching items. The callback is provided with a
  144. * list of sort orders, offset index and limit.
  145. *
  146. * @param <T>
  147. * the grid bean type
  148. */
  149. @FunctionalInterface
  150. public interface FetchItemsCallback<T> extends Serializable {
  151. /**
  152. * Returns a stream of items ordered by given sort orders, limiting the
  153. * results with given offset and limit.
  154. * <p>
  155. * This method is called after the size of the data set is asked from a
  156. * related size callback. The offset and limit are promised to be within
  157. * the size of the data set.
  158. *
  159. * @param sortOrder
  160. * a list of sort orders
  161. * @param offset
  162. * the first index to fetch
  163. * @param limit
  164. * the fetched item count
  165. * @return stream of items
  166. */
  167. public Stream<T> fetchItems(List<QuerySortOrder> sortOrder, int offset,
  168. int limit);
  169. }
  170. @Deprecated
  171. private static final Method COLUMN_REORDER_METHOD = ReflectTools.findMethod(
  172. ColumnReorderListener.class, "columnReorder",
  173. ColumnReorderEvent.class);
  174. private static final Method SORT_ORDER_CHANGE_METHOD = ReflectTools
  175. .findMethod(SortListener.class, "sort", SortEvent.class);
  176. @Deprecated
  177. private static final Method COLUMN_RESIZE_METHOD = ReflectTools.findMethod(
  178. ColumnResizeListener.class, "columnResize",
  179. ColumnResizeEvent.class);
  180. @Deprecated
  181. private static final Method ITEM_CLICK_METHOD = ReflectTools
  182. .findMethod(ItemClickListener.class, "itemClick", ItemClick.class);
  183. @Deprecated
  184. private static final Method COLUMN_VISIBILITY_METHOD = ReflectTools
  185. .findMethod(ColumnVisibilityChangeListener.class,
  186. "columnVisibilityChanged",
  187. ColumnVisibilityChangeEvent.class);
  188. /**
  189. * Selection mode representing the built-in selection models in grid.
  190. * <p>
  191. * These enums can be used in {@link Grid#setSelectionMode(SelectionMode)}
  192. * to easily switch between the build-in selection models.
  193. *
  194. * @see Grid#setSelectionMode(SelectionMode)
  195. * @see Grid#setSelectionModel(GridSelectionModel)
  196. */
  197. public enum SelectionMode {
  198. /**
  199. * Single selection mode that maps to build-in
  200. * {@link SingleSelectionModel}.
  201. *
  202. * @see SingleSelectionModelImpl
  203. */
  204. SINGLE {
  205. @Override
  206. protected <T> GridSelectionModel<T> createModel() {
  207. return new SingleSelectionModelImpl<>();
  208. }
  209. },
  210. /**
  211. * Multiselection mode that maps to build-in {@link MultiSelectionModel}
  212. * .
  213. *
  214. * @see MultiSelectionModelImpl
  215. */
  216. MULTI {
  217. @Override
  218. protected <T> GridSelectionModel<T> createModel() {
  219. return new MultiSelectionModelImpl<>();
  220. }
  221. },
  222. /**
  223. * Selection model that doesn't allow selection.
  224. *
  225. * @see NoSelectionModel
  226. */
  227. NONE {
  228. @Override
  229. protected <T> GridSelectionModel<T> createModel() {
  230. return new NoSelectionModel<>();
  231. }
  232. };
  233. /**
  234. * Creates the selection model to use with this enum.
  235. *
  236. * @param <T>
  237. * the type of items in the grid
  238. * @return the selection model
  239. */
  240. protected abstract <T> GridSelectionModel<T> createModel();
  241. }
  242. /**
  243. * An event that is fired when the columns are reordered.
  244. */
  245. public static class ColumnReorderEvent extends Component.Event
  246. implements HasUserOriginated {
  247. private final boolean userOriginated;
  248. /**
  249. *
  250. * @param source
  251. * the grid where the event originated from
  252. * @param userOriginated
  253. * <code>true</code> if event is a result of user
  254. * interaction, <code>false</code> if from API call
  255. */
  256. public ColumnReorderEvent(Grid source, boolean userOriginated) {
  257. super(source);
  258. this.userOriginated = userOriginated;
  259. }
  260. /**
  261. * Returns <code>true</code> if the column reorder was done by the user,
  262. * <code>false</code> if not and it was triggered by server side code.
  263. *
  264. * @return <code>true</code> if event is a result of user interaction
  265. */
  266. @Override
  267. public boolean isUserOriginated() {
  268. return userOriginated;
  269. }
  270. }
  271. /**
  272. * An event that is fired when a column is resized, either programmatically
  273. * or by the user.
  274. */
  275. public static class ColumnResizeEvent extends Component.Event
  276. implements HasUserOriginated {
  277. private final Column<?, ?> column;
  278. private final boolean userOriginated;
  279. /**
  280. *
  281. * @param source
  282. * the grid where the event originated from
  283. * @param userOriginated
  284. * <code>true</code> if event is a result of user
  285. * interaction, <code>false</code> if from API call
  286. */
  287. public ColumnResizeEvent(Grid<?> source, Column<?, ?> column,
  288. boolean userOriginated) {
  289. super(source);
  290. this.column = column;
  291. this.userOriginated = userOriginated;
  292. }
  293. /**
  294. * Returns the column that was resized.
  295. *
  296. * @return the resized column.
  297. */
  298. public Column<?, ?> getColumn() {
  299. return column;
  300. }
  301. /**
  302. * Returns <code>true</code> if the column resize was done by the user,
  303. * <code>false</code> if not and it was triggered by server side code.
  304. *
  305. * @return <code>true</code> if event is a result of user interaction
  306. */
  307. @Override
  308. public boolean isUserOriginated() {
  309. return userOriginated;
  310. }
  311. }
  312. /**
  313. * An event fired when an item in the Grid has been clicked.
  314. *
  315. * @param <T>
  316. * the grid bean type
  317. */
  318. public static class ItemClick<T> extends ConnectorEvent {
  319. private final T item;
  320. private final Column<T, ?> column;
  321. private final MouseEventDetails mouseEventDetails;
  322. private final int rowIndex;
  323. /**
  324. * Creates a new {@code ItemClick} event containing the given item and
  325. * Column originating from the given Grid.
  326. *
  327. */
  328. public ItemClick(Grid<T> source, Column<T, ?> column, T item,
  329. MouseEventDetails mouseEventDetails, int rowIndex) {
  330. super(source);
  331. this.column = column;
  332. this.item = item;
  333. this.mouseEventDetails = mouseEventDetails;
  334. this.rowIndex = rowIndex;
  335. }
  336. /**
  337. * Returns the clicked item.
  338. *
  339. * @return the clicked item
  340. */
  341. public T getItem() {
  342. return item;
  343. }
  344. /**
  345. * Returns the clicked column.
  346. *
  347. * @return the clicked column
  348. */
  349. public Column<T, ?> getColumn() {
  350. return column;
  351. }
  352. /**
  353. * Returns the source Grid.
  354. *
  355. * @return the grid
  356. */
  357. @Override
  358. public Grid<T> getSource() {
  359. return (Grid<T>) super.getSource();
  360. }
  361. /**
  362. * Returns the mouse event details.
  363. *
  364. * @return the mouse event details
  365. */
  366. public MouseEventDetails getMouseEventDetails() {
  367. return mouseEventDetails;
  368. }
  369. /**
  370. * Returns the clicked rowIndex.
  371. *
  372. * @return the clicked rowIndex
  373. * @since 8.4
  374. */
  375. public int getRowIndex() {
  376. return rowIndex;
  377. }
  378. }
  379. /**
  380. * ContextClickEvent for the Grid Component.
  381. *
  382. * <p>
  383. * Usage:
  384. *
  385. * <pre>
  386. * grid.addContextClickListener(event -&gt; Notification.show(
  387. * ((GridContextClickEvent&lt;Person&gt;) event).getItem() + " Clicked"));
  388. * </pre>
  389. *
  390. * @param <T>
  391. * the grid bean type
  392. */
  393. public static class GridContextClickEvent<T> extends ContextClickEvent {
  394. private final T item;
  395. private final int rowIndex;
  396. private final Column<T, ?> column;
  397. private final Section section;
  398. /**
  399. * Creates a new context click event.
  400. *
  401. * @param source
  402. * the grid where the context click occurred
  403. * @param mouseEventDetails
  404. * details about mouse position
  405. * @param section
  406. * the section of the grid which was clicked
  407. * @param rowIndex
  408. * the index of the row which was clicked
  409. * @param item
  410. * the item which was clicked
  411. * @param column
  412. * the column which was clicked
  413. */
  414. public GridContextClickEvent(Grid<T> source,
  415. MouseEventDetails mouseEventDetails, Section section,
  416. int rowIndex, T item, Column<T, ?> column) {
  417. super(source, mouseEventDetails);
  418. this.item = item;
  419. this.section = section;
  420. this.column = column;
  421. this.rowIndex = rowIndex;
  422. }
  423. /**
  424. * Returns the item of context clicked row.
  425. *
  426. * @return item of clicked row; <code>null</code> if header or footer
  427. */
  428. public T getItem() {
  429. return item;
  430. }
  431. /**
  432. * Returns the clicked column.
  433. *
  434. * @return the clicked column
  435. */
  436. public Column<T, ?> getColumn() {
  437. return column;
  438. }
  439. /**
  440. * Return the clicked section of Grid.
  441. *
  442. * @return section of grid
  443. */
  444. public Section getSection() {
  445. return section;
  446. }
  447. /**
  448. * Returns the clicked row index.
  449. * <p>
  450. * Header and Footer rows for index can be fetched with
  451. * {@link Grid#getHeaderRow(int)} and {@link Grid#getFooterRow(int)}.
  452. *
  453. * @return row index in section
  454. */
  455. public int getRowIndex() {
  456. return rowIndex;
  457. }
  458. @Override
  459. public Grid<T> getComponent() {
  460. return (Grid<T>) super.getComponent();
  461. }
  462. }
  463. /**
  464. * An event that is fired when a column's visibility changes.
  465. *
  466. * @since 7.5.0
  467. */
  468. public static class ColumnVisibilityChangeEvent extends Component.Event
  469. implements HasUserOriginated {
  470. private final Column<?, ?> column;
  471. private final boolean userOriginated;
  472. private final boolean hidden;
  473. /**
  474. * Constructor for a column visibility change event.
  475. *
  476. * @param source
  477. * the grid from which this event originates
  478. * @param column
  479. * the column that changed its visibility
  480. * @param hidden
  481. * <code>true</code> if the column was hidden,
  482. * <code>false</code> if it became visible
  483. * @param isUserOriginated
  484. * <code>true</code> if the event was triggered by an UI
  485. * interaction
  486. */
  487. public ColumnVisibilityChangeEvent(Grid<?> source, Column<?, ?> column,
  488. boolean hidden, boolean isUserOriginated) {
  489. super(source);
  490. this.column = column;
  491. this.hidden = hidden;
  492. userOriginated = isUserOriginated;
  493. }
  494. /**
  495. * Gets the column that became hidden or visible.
  496. *
  497. * @return the column that became hidden or visible.
  498. * @see Column#isHidden()
  499. */
  500. public Column<?, ?> getColumn() {
  501. return column;
  502. }
  503. /**
  504. * Was the column set hidden or visible.
  505. *
  506. * @return <code>true</code> if the column was hidden <code>false</code>
  507. * if it was set visible
  508. */
  509. public boolean isHidden() {
  510. return hidden;
  511. }
  512. @Override
  513. public boolean isUserOriginated() {
  514. return userOriginated;
  515. }
  516. }
  517. /**
  518. * A helper base class for creating extensions for the Grid component.
  519. *
  520. * @param <T>
  521. */
  522. public abstract static class AbstractGridExtension<T>
  523. extends AbstractListingExtension<T> {
  524. @Override
  525. public void extend(AbstractListing<T> grid) {
  526. if (!(grid instanceof Grid)) {
  527. throw new IllegalArgumentException(
  528. getClass().getSimpleName() + " can only extend Grid");
  529. }
  530. super.extend(grid);
  531. }
  532. /**
  533. * Adds given component to the connector hierarchy of Grid.
  534. *
  535. * @param c
  536. * the component to add
  537. */
  538. protected void addComponentToGrid(Component c) {
  539. getParent().addExtensionComponent(c);
  540. }
  541. /**
  542. * Removes given component from the connector hierarchy of Grid.
  543. *
  544. * @param c
  545. * the component to remove
  546. */
  547. protected void removeComponentFromGrid(Component c) {
  548. getParent().removeExtensionComponent(c);
  549. }
  550. @Override
  551. public Grid<T> getParent() {
  552. return (Grid<T>) super.getParent();
  553. }
  554. @Override
  555. protected AbstractGridExtensionState getState() {
  556. return (AbstractGridExtensionState) super.getState();
  557. }
  558. @Override
  559. protected AbstractGridExtensionState getState(boolean markAsDirty) {
  560. return (AbstractGridExtensionState) super.getState(markAsDirty);
  561. }
  562. protected String getInternalIdForColumn(Column<T, ?> column) {
  563. return getParent().getInternalIdForColumn(column);
  564. }
  565. }
  566. private final class GridServerRpcImpl implements GridServerRpc {
  567. @Override
  568. public void sort(String[] columnInternalIds, SortDirection[] directions,
  569. boolean isUserOriginated) {
  570. assert columnInternalIds.length == directions.length : "Column and sort direction counts don't match.";
  571. List<GridSortOrder<T>> list = new ArrayList<>(directions.length);
  572. for (int i = 0; i < columnInternalIds.length; ++i) {
  573. Column<T, ?> column = columnKeys.get(columnInternalIds[i]);
  574. list.add(new GridSortOrder<>(column, directions[i]));
  575. }
  576. setSortOrder(list, isUserOriginated);
  577. }
  578. @Override
  579. public void itemClick(String rowKey, String columnInternalId,
  580. MouseEventDetails details, int rowIndex) {
  581. Column<T, ?> column = getColumnByInternalId(columnInternalId);
  582. T item = getDataCommunicator().getKeyMapper().get(rowKey);
  583. fireEvent(new ItemClick<>(Grid.this, column, item, details,
  584. rowIndex));
  585. }
  586. @Override
  587. public void contextClick(int rowIndex, String rowKey,
  588. String columnInternalId, Section section,
  589. MouseEventDetails details) {
  590. T item = null;
  591. if (rowKey != null) {
  592. item = getDataCommunicator().getKeyMapper().get(rowKey);
  593. }
  594. fireEvent(new GridContextClickEvent<>(Grid.this, details, section,
  595. rowIndex, item, getColumnByInternalId(columnInternalId)));
  596. }
  597. @Override
  598. public void columnsReordered(List<String> newColumnOrder,
  599. List<String> oldColumnOrder) {
  600. final String diffStateKey = "columnOrder";
  601. ConnectorTracker connectorTracker = getUI().getConnectorTracker();
  602. JsonObject diffState = connectorTracker.getDiffState(Grid.this);
  603. // discard the change if the columns have been reordered from
  604. // the server side, as the server side is always right
  605. if (getState(false).columnOrder.equals(oldColumnOrder)) {
  606. // Don't mark as dirty since client has the state already
  607. getState(false).columnOrder = newColumnOrder;
  608. // write changes to diffState so that possible reverting the
  609. // column order is sent to client
  610. assert diffState
  611. .hasKey(diffStateKey) : "Field name has changed";
  612. Type type = null;
  613. try {
  614. type = getState(false).getClass().getField(diffStateKey)
  615. .getGenericType();
  616. } catch (NoSuchFieldException | SecurityException e) {
  617. e.printStackTrace();
  618. }
  619. EncodeResult encodeResult = JsonCodec.encode(
  620. getState(false).columnOrder, diffState, type,
  621. connectorTracker);
  622. diffState.put(diffStateKey, encodeResult.getEncodedValue());
  623. fireColumnReorderEvent(true);
  624. } else {
  625. // make sure the client is reverted to the order that the
  626. // server thinks it is
  627. diffState.remove(diffStateKey);
  628. markAsDirty();
  629. }
  630. }
  631. @Override
  632. public void columnVisibilityChanged(String internalId, boolean hidden) {
  633. Column<T, ?> column = getColumnByInternalId(internalId);
  634. if (column.isHidden() != hidden) {
  635. column.setHidden(hidden);
  636. fireColumnVisibilityChangeEvent(column, hidden, true);
  637. }
  638. }
  639. @Override
  640. public void columnResized(String internalId, double pixels) {
  641. final Column<T, ?> column = getColumnByInternalId(internalId);
  642. if (column != null && column.isResizable()) {
  643. column.getState().width = pixels;
  644. fireColumnResizeEvent(column, true);
  645. }
  646. }
  647. }
  648. /**
  649. * Class for managing visible details rows.
  650. *
  651. * @param <T>
  652. * the grid bean type
  653. */
  654. public static class DetailsManager<T> extends AbstractGridExtension<T> {
  655. private final Set<T> visibleDetails = new HashSet<>();
  656. private final Map<T, Component> components = new HashMap<>();
  657. private DetailsGenerator<T> generator;
  658. /**
  659. * Sets the details component generator.
  660. *
  661. * @param generator
  662. * the generator for details components
  663. */
  664. public void setDetailsGenerator(DetailsGenerator<T> generator) {
  665. if (this.generator != generator) {
  666. removeAllComponents();
  667. }
  668. this.generator = generator;
  669. visibleDetails.forEach(this::refresh);
  670. }
  671. @Override
  672. public void remove() {
  673. removeAllComponents();
  674. super.remove();
  675. }
  676. private void removeAllComponents() {
  677. // Clean up old components
  678. components.values().forEach(this::removeComponentFromGrid);
  679. components.clear();
  680. }
  681. @Override
  682. public void generateData(T item, JsonObject jsonObject) {
  683. if (generator == null || !visibleDetails.contains(item)) {
  684. return;
  685. }
  686. if (!components.containsKey(item)) {
  687. Component detailsComponent = generator.apply(item);
  688. Objects.requireNonNull(detailsComponent,
  689. "Details generator can't create null components");
  690. if (detailsComponent.getParent() != null) {
  691. throw new IllegalStateException(
  692. "Details component was already attached");
  693. }
  694. addComponentToGrid(detailsComponent);
  695. components.put(item, detailsComponent);
  696. }
  697. jsonObject.put(GridState.JSONKEY_DETAILS_VISIBLE,
  698. components.get(item).getConnectorId());
  699. }
  700. @Override
  701. public void destroyData(T item) {
  702. // No clean up needed. Components are removed when hiding details
  703. // and/or changing details generator
  704. }
  705. /**
  706. * Sets the visibility of details component for given item.
  707. *
  708. * @param item
  709. * the item to show details for
  710. * @param visible
  711. * {@code true} if details component should be visible;
  712. * {@code false} if it should be hidden
  713. */
  714. public void setDetailsVisible(T item, boolean visible) {
  715. boolean refresh = false;
  716. if (!visible) {
  717. refresh = visibleDetails.remove(item);
  718. if (components.containsKey(item)) {
  719. removeComponentFromGrid(components.remove(item));
  720. }
  721. } else {
  722. refresh = visibleDetails.add(item);
  723. }
  724. if (refresh) {
  725. refresh(item);
  726. }
  727. }
  728. /**
  729. * Returns the visibility of details component for given item.
  730. *
  731. * @param item
  732. * the item to show details for
  733. *
  734. * @return {@code true} if details component should be visible;
  735. * {@code false} if it should be hidden
  736. */
  737. public boolean isDetailsVisible(T item) {
  738. return visibleDetails.contains(item);
  739. }
  740. @Override
  741. public Grid<T> getParent() {
  742. return super.getParent();
  743. }
  744. @Override
  745. protected DetailsManagerState getState() {
  746. return (DetailsManagerState) super.getState();
  747. }
  748. @Override
  749. protected DetailsManagerState getState(boolean markAsDirty) {
  750. return (DetailsManagerState) super.getState(markAsDirty);
  751. }
  752. }
  753. /**
  754. * This extension manages the configuration and data communication for a
  755. * Column inside of a Grid component.
  756. *
  757. * @param <T>
  758. * the grid bean type
  759. * @param <V>
  760. * the column value type
  761. */
  762. public static class Column<T, V> extends AbstractExtension {
  763. private final ValueProvider<T, V> valueProvider;
  764. private ValueProvider<V, ?> presentationProvider;
  765. private SortOrderProvider sortOrderProvider = direction -> {
  766. String id = getId();
  767. if (id == null) {
  768. return Stream.empty();
  769. }
  770. return Stream.of(new QuerySortOrder(id, direction));
  771. };
  772. private boolean sortable = true;
  773. private SerializableComparator<T> comparator;
  774. private StyleGenerator<T> styleGenerator = item -> null;
  775. private DescriptionGenerator<T> descriptionGenerator;
  776. private DataGenerator<T> dataGenerator = new DataGenerator<T>() {
  777. @Override
  778. public void generateData(T item, JsonObject jsonObject) {
  779. ColumnState state = getState(false);
  780. String communicationId = getConnectorId();
  781. assert communicationId != null : "No communication ID set for column "
  782. + state.caption;
  783. JsonObject obj = getDataObject(jsonObject,
  784. DataCommunicatorConstants.DATA);
  785. obj.put(communicationId, generateRendererValue(item,
  786. presentationProvider, state.renderer));
  787. String style = styleGenerator.apply(item);
  788. if (style != null && !style.isEmpty()) {
  789. JsonObject styleObj = getDataObject(jsonObject,
  790. GridState.JSONKEY_CELLSTYLES);
  791. styleObj.put(communicationId, style);
  792. }
  793. if (descriptionGenerator != null) {
  794. String description = descriptionGenerator.apply(item);
  795. if (description != null && !description.isEmpty()) {
  796. JsonObject descriptionObj = getDataObject(jsonObject,
  797. GridState.JSONKEY_CELLDESCRIPTION);
  798. descriptionObj.put(communicationId, description);
  799. }
  800. }
  801. }
  802. @Override
  803. public void destroyData(T item) {
  804. removeComponent(getGrid().getDataProvider().getId(item));
  805. }
  806. @Override
  807. public void destroyAllData() {
  808. // Make a defensive copy of keys, as the map gets cleared when
  809. // removing components.
  810. new HashSet<>(activeComponents.keySet())
  811. .forEach(component -> removeComponent(component));
  812. }
  813. };
  814. private Binding<T, ?> editorBinding;
  815. private Map<Object, Component> activeComponents = new HashMap<>();
  816. private String userId;
  817. /**
  818. * Constructs a new Column configuration with given renderer and value
  819. * provider.
  820. *
  821. * @param valueProvider
  822. * the function to get values from items, not
  823. * <code>null</code>
  824. * @param renderer
  825. * the value renderer, not <code>null</code>
  826. */
  827. protected Column(ValueProvider<T, V> valueProvider,
  828. Renderer<? super V> renderer) {
  829. this(valueProvider, ValueProvider.identity(), renderer);
  830. }
  831. /**
  832. * Constructs a new Column configuration with given renderer and value
  833. * provider.
  834. * <p>
  835. * For a more complete explanation on presentation provider, see
  836. * {@link #setRenderer(ValueProvider, Renderer)}.
  837. *
  838. * @param valueProvider
  839. * the function to get values from items, not
  840. * <code>null</code>
  841. * @param presentationProvider
  842. * the function to get presentations from the value of this
  843. * column, not <code>null</code>. For more details, see
  844. * {@link #setRenderer(ValueProvider, Renderer)}
  845. * @param renderer
  846. * the presentation renderer, not <code>null</code>
  847. * @param <P>
  848. * the presentation type
  849. *
  850. * @since 8.1
  851. */
  852. protected <P> Column(ValueProvider<T, V> valueProvider,
  853. ValueProvider<V, P> presentationProvider,
  854. Renderer<? super P> renderer) {
  855. Objects.requireNonNull(valueProvider,
  856. "Value provider can't be null");
  857. Objects.requireNonNull(presentationProvider,
  858. "Presentation provider can't be null");
  859. Objects.requireNonNull(renderer, "Renderer can't be null");
  860. ColumnState state = getState();
  861. this.valueProvider = valueProvider;
  862. this.presentationProvider = presentationProvider;
  863. state.renderer = renderer;
  864. state.caption = "";
  865. // Add the renderer as a child extension of this extension, thus
  866. // ensuring the renderer will be unregistered when this column is
  867. // removed
  868. addExtension(renderer);
  869. Class<? super P> valueType = renderer.getPresentationType();
  870. if (Comparable.class.isAssignableFrom(valueType)) {
  871. comparator = (a, b) -> compareComparables(
  872. valueProvider.apply(a), valueProvider.apply(b));
  873. } else if (Number.class.isAssignableFrom(valueType)) {
  874. /*
  875. * Value type will be Number whenever using NumberRenderer.
  876. * Provide explicit comparison support in this case even though
  877. * Number itself isn't Comparable.
  878. */
  879. comparator = (a, b) -> compareNumbers(
  880. (Number) valueProvider.apply(a),
  881. (Number) valueProvider.apply(b));
  882. } else {
  883. comparator = (a, b) -> compareMaybeComparables(
  884. valueProvider.apply(a), valueProvider.apply(b));
  885. }
  886. }
  887. private static int compareMaybeComparables(Object a, Object b) {
  888. if (hasCommonComparableBaseType(a, b)) {
  889. return compareComparables(a, b);
  890. }
  891. return compareComparables(Objects.toString(a, ""),
  892. Objects.toString(b, ""));
  893. }
  894. private static boolean hasCommonComparableBaseType(Object a, Object b) {
  895. if (a instanceof Comparable<?> && b instanceof Comparable<?>) {
  896. Class<?> aClass = a.getClass();
  897. Class<?> bClass = b.getClass();
  898. if (aClass == bClass) {
  899. return true;
  900. }
  901. Class<?> baseType = ReflectTools.findCommonBaseType(aClass,
  902. bClass);
  903. if (Comparable.class.isAssignableFrom(baseType)) {
  904. return true;
  905. }
  906. }
  907. if ((a == null && b instanceof Comparable<?>)
  908. || (b == null && a instanceof Comparable<?>)) {
  909. return true;
  910. }
  911. return false;
  912. }
  913. @SuppressWarnings({ "unchecked", "rawtypes" })
  914. private static int compareComparables(Object a, Object b) {
  915. return ((Comparator) Comparator
  916. .nullsLast(Comparator.naturalOrder())).compare(a, b);
  917. }
  918. @SuppressWarnings("unchecked")
  919. private static int compareNumbers(Number a, Number b) {
  920. Number valueA = a != null ? a : Double.POSITIVE_INFINITY;
  921. Number valueB = b != null ? b : Double.POSITIVE_INFINITY;
  922. // Most Number implementations are Comparable
  923. if (valueA instanceof Comparable
  924. && valueA.getClass().isInstance(valueB)) {
  925. return ((Comparable<Number>) valueA).compareTo(valueB);
  926. }
  927. if (valueA.equals(valueB)) {
  928. return 0;
  929. }
  930. // Fall back to comparing based on potentially truncated values
  931. int compare = Long.compare(valueA.longValue(), valueB.longValue());
  932. if (compare == 0) {
  933. // This might still produce 0 even though the values are not
  934. // equals, but there's nothing more we can do about that
  935. compare = Double.compare(valueA.doubleValue(),
  936. valueB.doubleValue());
  937. }
  938. return compare;
  939. }
  940. @SuppressWarnings("unchecked")
  941. private <P> JsonValue generateRendererValue(T item,
  942. ValueProvider<V, P> presentationProvider, Connector renderer) {
  943. P presentationValue = presentationProvider
  944. .apply(valueProvider.apply(item));
  945. // Make Grid track components.
  946. if (renderer instanceof ComponentRenderer
  947. && presentationValue instanceof Component) {
  948. addComponent(getGrid().getDataProvider().getId(item),
  949. (Component) presentationValue);
  950. }
  951. return ((Renderer<P>) renderer).encode(presentationValue);
  952. }
  953. private void addComponent(Object item, Component component) {
  954. if (activeComponents.containsKey(item)) {
  955. if (activeComponents.get(item).equals(component)) {
  956. // Reusing old component
  957. return;
  958. }
  959. removeComponent(item);
  960. }
  961. activeComponents.put(item, component);
  962. getGrid().addExtensionComponent(component);
  963. }
  964. private void removeComponent(Object item) {
  965. Component component = activeComponents.remove(item);
  966. if (component != null) {
  967. getGrid().removeExtensionComponent(component);
  968. }
  969. }
  970. /**
  971. * Gets a data object with the given key from the given JsonObject. If
  972. * there is no object with the key, this method creates a new
  973. * JsonObject.
  974. *
  975. * @param jsonObject
  976. * the json object
  977. * @param key
  978. * the key where the desired data object is stored
  979. * @return data object for the given key
  980. */
  981. private JsonObject getDataObject(JsonObject jsonObject, String key) {
  982. if (!jsonObject.hasKey(key)) {
  983. jsonObject.put(key, Json.createObject());
  984. }
  985. return jsonObject.getObject(key);
  986. }
  987. @Override
  988. protected ColumnState getState() {
  989. return getState(true);
  990. }
  991. @Override
  992. protected ColumnState getState(boolean markAsDirty) {
  993. return (ColumnState) super.getState(markAsDirty);
  994. }
  995. /**
  996. * This method extends the given Grid with this Column.
  997. *
  998. * @param grid
  999. * the grid to extend
  1000. */
  1001. private void extend(Grid<T> grid) {
  1002. super.extend(grid);
  1003. }
  1004. /**
  1005. * Returns the identifier used with this Column in communication.
  1006. *
  1007. * @return the identifier string
  1008. */
  1009. private String getInternalId() {
  1010. return getState(false).internalId;
  1011. }
  1012. /**
  1013. * Sets the identifier to use with this Column in communication.
  1014. *
  1015. * @param id
  1016. * the identifier string
  1017. */
  1018. private void setInternalId(String id) {
  1019. Objects.requireNonNull(id, "Communication ID can't be null");
  1020. getState().internalId = id;
  1021. }
  1022. /**
  1023. * Returns the user-defined identifier for this column.
  1024. *
  1025. * @return the identifier string
  1026. */
  1027. public String getId() {
  1028. return userId;
  1029. }
  1030. /**
  1031. * Sets the user-defined identifier to map this column. The identifier
  1032. * can be used for example in {@link Grid#getColumn(String)}.
  1033. * <p>
  1034. * The id is also used as the {@link #setSortProperty(String...) backend
  1035. * sort property} for this column if no sort property or sort order
  1036. * provider has been set for this column.
  1037. *
  1038. * @see #setSortProperty(String...)
  1039. * @see #setSortOrderProvider(SortOrderProvider)
  1040. *
  1041. * @param id
  1042. * the identifier string
  1043. * @return this column
  1044. */
  1045. public Column<T, V> setId(String id) {
  1046. Objects.requireNonNull(id, "Column identifier cannot be null");
  1047. if (userId != null) {
  1048. throw new IllegalStateException(
  1049. "Column identifier cannot be changed");
  1050. }
  1051. userId = id;
  1052. getGrid().setColumnId(id, this);
  1053. updateSortable();
  1054. return this;
  1055. }
  1056. private void updateSortable() {
  1057. boolean inMemory = getGrid().getDataProvider().isInMemory();
  1058. boolean hasSortOrder = getSortOrder(SortDirection.ASCENDING)
  1059. .count() != 0;
  1060. getState().sortable = this.sortable && (inMemory || hasSortOrder);
  1061. }
  1062. /**
  1063. * Gets the function used to produce the value for data in this column
  1064. * based on the row item.
  1065. *
  1066. * @return the value provider function
  1067. *
  1068. * @since 8.0.3
  1069. */
  1070. public ValueProvider<T, V> getValueProvider() {
  1071. return valueProvider;
  1072. }
  1073. /**
  1074. * Sets whether the user can sort this column or not. Whether the column
  1075. * is actually sortable after {@code setSortable(true)} depends on the
  1076. * {@link DataProvider} and the defined sort order for this column. When
  1077. * using an {@link InMemoryDataProvider} sorting can be automatic.
  1078. *
  1079. * @param sortable
  1080. * {@code true} to enable sorting for this column;
  1081. * {@code false} to disable it
  1082. * @return this column
  1083. */
  1084. public Column<T, V> setSortable(boolean sortable) {
  1085. if (this.sortable != sortable) {
  1086. this.sortable = sortable;
  1087. updateSortable();
  1088. }
  1089. return this;
  1090. }
  1091. /**
  1092. * Gets whether sorting is enabled for this column.
  1093. *
  1094. * @return {@code true} if the sorting is enabled for this column;
  1095. * {@code false} if not
  1096. */
  1097. public boolean isSortable() {
  1098. return sortable;
  1099. }
  1100. /**
  1101. * Gets whether the user can actually sort this column.
  1102. *
  1103. * @return {@code true} if the column can be sorted by the user;
  1104. * {@code false} if not
  1105. *
  1106. * @since 8.3.2
  1107. */
  1108. public boolean isSortableByUser() {
  1109. return getState(false).sortable;
  1110. }
  1111. /**
  1112. * Sets the header aria-label for this column.
  1113. *
  1114. * @param caption
  1115. * the header aria-label, null removes the aria-label from
  1116. * this column
  1117. *
  1118. * @return this column
  1119. *
  1120. * @since 8.2
  1121. */
  1122. public Column<T, V> setAssistiveCaption(String caption) {
  1123. if (Objects.equals(caption, getAssistiveCaption())) {
  1124. return this;
  1125. }
  1126. getState().assistiveCaption = caption;
  1127. return this;
  1128. }
  1129. /**
  1130. * Gets the header caption for this column.
  1131. *
  1132. * @return header caption
  1133. *
  1134. * @since 8.2
  1135. */
  1136. public String getAssistiveCaption() {
  1137. return getState(false).assistiveCaption;
  1138. }
  1139. /**
  1140. * Sets the header caption for this column.
  1141. *
  1142. * @param caption
  1143. * the header caption, not null
  1144. *
  1145. * @return this column
  1146. */
  1147. public Column<T, V> setCaption(String caption) {
  1148. Objects.requireNonNull(caption, "Header caption can't be null");
  1149. if (caption.equals(getState(false).caption)) {
  1150. return this;
  1151. }
  1152. getState().caption = caption;
  1153. HeaderRow row = getGrid().getDefaultHeaderRow();
  1154. if (row != null) {
  1155. row.getCell(this).setText(caption);
  1156. }
  1157. return this;
  1158. }
  1159. /**
  1160. * Gets the header caption for this column.
  1161. *
  1162. * @return header caption
  1163. */
  1164. public String getCaption() {
  1165. return getState(false).caption;
  1166. }
  1167. /**
  1168. * Sets a comparator to use with in-memory sorting with this column.
  1169. * Sorting with a back-end is done using
  1170. * {@link Column#setSortProperty(String...)}.
  1171. *
  1172. * @param comparator
  1173. * the comparator to use when sorting data in this column
  1174. * @return this column
  1175. */
  1176. public Column<T, V> setComparator(
  1177. SerializableComparator<T> comparator) {
  1178. Objects.requireNonNull(comparator, "Comparator can't be null");
  1179. this.comparator = comparator;
  1180. return this;
  1181. }
  1182. /**
  1183. * Gets the comparator to use with in-memory sorting for this column
  1184. * when sorting in the given direction.
  1185. *
  1186. * @param sortDirection
  1187. * the direction this column is sorted by
  1188. * @return comparator for this column
  1189. */
  1190. public SerializableComparator<T> getComparator(
  1191. SortDirection sortDirection) {
  1192. Objects.requireNonNull(comparator,
  1193. "No comparator defined for sorted column.");
  1194. boolean reverse = sortDirection != SortDirection.ASCENDING;
  1195. return reverse ? (t1, t2) -> comparator.reversed().compare(t1, t2)
  1196. : comparator;
  1197. }
  1198. /**
  1199. * Sets strings describing back end properties to be used when sorting
  1200. * this column.
  1201. * <p>
  1202. * By default, the {@link #setId(String) column id} will be used as the
  1203. * sort property.
  1204. *
  1205. * @param properties
  1206. * the array of strings describing backend properties
  1207. * @return this column
  1208. */
  1209. public Column<T, V> setSortProperty(String... properties) {
  1210. Objects.requireNonNull(properties, "Sort properties can't be null");
  1211. return setSortOrderProvider(dir -> Arrays.stream(properties)
  1212. .map(s -> new QuerySortOrder(s, dir)));
  1213. }
  1214. /**
  1215. * Sets the sort orders when sorting this column. The sort order
  1216. * provider is a function which provides {@link QuerySortOrder} objects
  1217. * to describe how to sort by this column.
  1218. * <p>
  1219. * By default, the {@link #setId(String) column id} will be used as the
  1220. * sort property.
  1221. *
  1222. * @param provider
  1223. * the function to use when generating sort orders with the
  1224. * given direction
  1225. * @return this column
  1226. */
  1227. public Column<T, V> setSortOrderProvider(SortOrderProvider provider) {
  1228. Objects.requireNonNull(provider,
  1229. "Sort order provider can't be null");
  1230. sortOrderProvider = provider;
  1231. // Update state
  1232. updateSortable();
  1233. return this;
  1234. }
  1235. /**
  1236. * Gets the sort orders to use with back-end sorting for this column
  1237. * when sorting in the given direction.
  1238. *
  1239. * @see #setSortProperty(String...)
  1240. * @see #setId(String)
  1241. * @see #setSortOrderProvider(SortOrderProvider)
  1242. *
  1243. * @param direction
  1244. * the sorting direction
  1245. * @return stream of sort orders
  1246. */
  1247. public Stream<QuerySortOrder> getSortOrder(SortDirection direction) {
  1248. return sortOrderProvider.apply(direction);
  1249. }
  1250. /**
  1251. * Sets the style generator that is used for generating class names for
  1252. * cells in this column. Returning null from the generator results in no
  1253. * custom style name being set.
  1254. *
  1255. * Note: The style generator is applied only to the body cells, not to
  1256. * the Editor.
  1257. *
  1258. * @param cellStyleGenerator
  1259. * the cell style generator to set, not null
  1260. * @return this column
  1261. * @throws NullPointerException
  1262. * if {@code cellStyleGenerator} is {@code null}
  1263. */
  1264. public Column<T, V> setStyleGenerator(
  1265. StyleGenerator<T> cellStyleGenerator) {
  1266. Objects.requireNonNull(cellStyleGenerator,
  1267. "Cell style generator must not be null");
  1268. this.styleGenerator = cellStyleGenerator;
  1269. getGrid().getDataCommunicator().reset();
  1270. return this;
  1271. }
  1272. /**
  1273. * Gets the style generator that is used for generating styles for
  1274. * cells.
  1275. *
  1276. * @return the cell style generator
  1277. */
  1278. public StyleGenerator<T> getStyleGenerator() {
  1279. return styleGenerator;
  1280. }
  1281. /**
  1282. * Sets the description generator that is used for generating
  1283. * descriptions for cells in this column. This method uses the
  1284. * {@link ContentMode#PREFORMATTED} content mode.
  1285. *
  1286. * @see #setDescriptionGenerator(DescriptionGenerator, ContentMode)
  1287. *
  1288. * @param cellDescriptionGenerator
  1289. * the cell description generator to set, or {@code null} to
  1290. * remove a previously set generator
  1291. * @return this column
  1292. */
  1293. public Column<T, V> setDescriptionGenerator(
  1294. DescriptionGenerator<T> cellDescriptionGenerator) {
  1295. return setDescriptionGenerator(cellDescriptionGenerator,
  1296. ContentMode.PREFORMATTED);
  1297. }
  1298. /**
  1299. * Sets the description generator that is used for generating
  1300. * descriptions for cells in this column. This method uses the given
  1301. * content mode.
  1302. *
  1303. * @see #setDescriptionGenerator(DescriptionGenerator)
  1304. *
  1305. * @param cellDescriptionGenerator
  1306. * the cell description generator to set, or {@code null} to
  1307. * remove a previously set generator
  1308. * @param tooltipContentMode
  1309. * the content mode for tooltips
  1310. * @return this column
  1311. *
  1312. * @since 8.2
  1313. */
  1314. public Column<T, V> setDescriptionGenerator(
  1315. DescriptionGenerator<T> cellDescriptionGenerator,
  1316. ContentMode tooltipContentMode) {
  1317. this.descriptionGenerator = cellDescriptionGenerator;
  1318. getState().tooltipContentMode = tooltipContentMode;
  1319. getGrid().getDataCommunicator().reset();
  1320. return this;
  1321. }
  1322. /**
  1323. * Gets the description generator that is used for generating
  1324. * descriptions for cells.
  1325. *
  1326. * @return the cell description generator, or <code>null</code> if no
  1327. * generator is set
  1328. */
  1329. public DescriptionGenerator<T> getDescriptionGenerator() {
  1330. return descriptionGenerator;
  1331. }
  1332. /**
  1333. * Sets the ratio with which the column expands.
  1334. * <p>
  1335. * By default, all columns expand equally (treated as if all of them had
  1336. * an expand ratio of 1). Once at least one column gets a defined expand
  1337. * ratio, the implicit expand ratio is removed, and only the defined
  1338. * expand ratios are taken into account.
  1339. * <p>
  1340. * If a column has a defined width ({@link #setWidth(double)}), it
  1341. * overrides this method's effects.
  1342. * <p>
  1343. * <em>Example:</em> A grid with three columns, with expand ratios 0, 1
  1344. * and 2, respectively. The column with a <strong>ratio of 0 is exactly
  1345. * as wide as its contents requires</strong>. The column with a ratio of
  1346. * 1 is as wide as it needs, <strong>plus a third of any excess
  1347. * space</strong>, because we have 3 parts total, and this column
  1348. * reserves only one of those. The column with a ratio of 2, is as wide
  1349. * as it needs to be, <strong>plus two thirds</strong> of the excess
  1350. * width.
  1351. *
  1352. * @param expandRatio
  1353. * the expand ratio of this column. {@code 0} to not have it
  1354. * expand at all. A negative number to clear the expand
  1355. * value.
  1356. * @throws IllegalStateException
  1357. * if the column is no longer attached to any grid
  1358. * @see #setWidth(double)
  1359. */
  1360. public Column<T, V> setExpandRatio(int expandRatio)
  1361. throws IllegalStateException {
  1362. checkColumnIsAttached();
  1363. if (expandRatio != getExpandRatio()) {
  1364. getState().expandRatio = expandRatio;
  1365. getGrid().markAsDirty();
  1366. }
  1367. return this;
  1368. }
  1369. /**
  1370. * Returns the column's expand ratio.
  1371. *
  1372. * @return the column's expand ratio
  1373. * @see #setExpandRatio(int)
  1374. */
  1375. public int getExpandRatio() {
  1376. return getState(false).expandRatio;
  1377. }
  1378. /**
  1379. * Clears the expand ratio for this column.
  1380. * <p>
  1381. * Equal to calling {@link #setExpandRatio(int) setExpandRatio(-1)}
  1382. *
  1383. * @throws IllegalStateException
  1384. * if the column is no longer attached to any grid
  1385. */
  1386. public Column<T, V> clearExpandRatio() throws IllegalStateException {
  1387. return setExpandRatio(-1);
  1388. }
  1389. /**
  1390. * Returns the width (in pixels). By default a column is 100px wide.
  1391. *
  1392. * @return the width in pixels of the column
  1393. * @throws IllegalStateException
  1394. * if the column is no longer attached to any grid
  1395. */
  1396. public double getWidth() throws IllegalStateException {
  1397. checkColumnIsAttached();
  1398. return getState(false).width;
  1399. }
  1400. /**
  1401. * Sets the width (in pixels).
  1402. * <p>
  1403. * This overrides any configuration set by any of
  1404. * {@link #setExpandRatio(int)}, {@link #setMinimumWidth(double)} or
  1405. * {@link #setMaximumWidth(double)}.
  1406. *
  1407. * @param pixelWidth
  1408. * the new pixel width of the column
  1409. * @return the column itself
  1410. *
  1411. * @throws IllegalStateException
  1412. * if the column is no longer attached to any grid
  1413. * @throws IllegalArgumentException
  1414. * thrown if pixel width is less than zero
  1415. */
  1416. public Column<T, V> setWidth(double pixelWidth)
  1417. throws IllegalStateException, IllegalArgumentException {
  1418. checkColumnIsAttached();
  1419. if (pixelWidth < 0) {
  1420. throw new IllegalArgumentException(
  1421. "Pixel width should be greated than 0 (in " + toString()
  1422. + ")");
  1423. }
  1424. if (pixelWidth != getWidth()) {
  1425. getState().width = pixelWidth;
  1426. getGrid().markAsDirty();
  1427. getGrid().fireColumnResizeEvent(this, false);
  1428. }
  1429. return this;
  1430. }
  1431. /**
  1432. * Returns whether this column has an undefined width.
  1433. *
  1434. * @since 7.6
  1435. * @return whether the width is undefined
  1436. * @throws IllegalStateException
  1437. * if the column is no longer attached to any grid
  1438. */
  1439. public boolean isWidthUndefined() {
  1440. checkColumnIsAttached();
  1441. return getState(false).width < 0;
  1442. }
  1443. /**
  1444. * Marks the column width as undefined. An undefined width means the
  1445. * grid is free to resize the column based on the cell contents and
  1446. * available space in the grid.
  1447. *
  1448. * @return the column itself
  1449. */
  1450. public Column<T, V> setWidthUndefined() {
  1451. checkColumnIsAttached();
  1452. if (!isWidthUndefined()) {
  1453. getState().width = -1;
  1454. getGrid().markAsDirty();
  1455. getGrid().fireColumnResizeEvent(this, false);
  1456. }
  1457. return this;
  1458. }
  1459. /**
  1460. * Sets the minimum width for this column.
  1461. * <p>
  1462. * This defines the minimum guaranteed pixel width of the column
  1463. * <em>when it is set to expand</em>.
  1464. *
  1465. * @param pixels
  1466. * the minimum width for the column
  1467. * @throws IllegalStateException
  1468. * if the column is no longer attached to any grid
  1469. * @see #setExpandRatio(int)
  1470. * @return the column itself
  1471. */
  1472. public Column<T, V> setMinimumWidth(double pixels)
  1473. throws IllegalStateException {
  1474. checkColumnIsAttached();
  1475. final double maxwidth = getMaximumWidth();
  1476. if (pixels >= 0 && pixels > maxwidth && maxwidth >= 0) {
  1477. throw new IllegalArgumentException("New minimum width ("
  1478. + pixels + ") was greater than maximum width ("
  1479. + maxwidth + ")");
  1480. }
  1481. getState().minWidth = pixels;
  1482. getGrid().markAsDirty();
  1483. return this;
  1484. }
  1485. /**
  1486. * Return the minimum width for this column.
  1487. *
  1488. * @return the minimum width for this column
  1489. * @see #setMinimumWidth(double)
  1490. */
  1491. public double getMinimumWidth() {
  1492. return getState(false).minWidth;
  1493. }
  1494. /**
  1495. * Sets whether the width of the contents in the column should be
  1496. * considered minimum width for this column.
  1497. * <p>
  1498. * If this is set to <code>true</code> (default for backwards
  1499. * compatibility), then a column will not shrink to smaller than the
  1500. * width required to show the contents available when calculating the
  1501. * widths (only the widths of the initially rendered rows are
  1502. * considered).
  1503. * <p>
  1504. * If this is set to <code>false</code> and the column has been set to
  1505. * expand using #setExpandRatio(int), then the contents of the column
  1506. * will be ignored when calculating the width, and the column will thus
  1507. * shrink down to the minimum width defined by #setMinimumWidth(double)
  1508. * if necessary.
  1509. *
  1510. * @param minimumWidthFromContent
  1511. * <code>true</code> to reserve space for all contents,
  1512. * <code>false</code> to allow the column to shrink smaller
  1513. * than the contents
  1514. * @return the column itself
  1515. * @throws IllegalStateException
  1516. * if the column is no longer attached to any grid
  1517. * @see #setMinimumWidth(double)
  1518. * @since 8.1
  1519. */
  1520. public Column<T, V> setMinimumWidthFromContent(
  1521. boolean minimumWidthFromContent) throws IllegalStateException {
  1522. checkColumnIsAttached();
  1523. if (isMinimumWidthFromContent() != minimumWidthFromContent) {
  1524. getState().minimumWidthFromContent = minimumWidthFromContent;
  1525. getGrid().markAsDirty();
  1526. }
  1527. return this;
  1528. }
  1529. /**
  1530. * Gets whether the width of the contents in the column should be
  1531. * considered minimum width for this column.
  1532. *
  1533. * @return <code>true</code> to reserve space for all contents,
  1534. * <code>false</code> to allow the column to shrink smaller than
  1535. * the contents
  1536. * @see #setMinimumWidthFromContent(boolean)
  1537. * @since 8.1
  1538. */
  1539. public boolean isMinimumWidthFromContent() {
  1540. return getState(false).minimumWidthFromContent;
  1541. }
  1542. /**
  1543. * Sets the maximum width for this column.
  1544. * <p>
  1545. * This defines the maximum allowed pixel width of the column <em>when
  1546. * it is set to expand</em>.
  1547. *
  1548. * @param pixels
  1549. * the maximum width
  1550. * @throws IllegalStateException
  1551. * if the column is no longer attached to any grid
  1552. * @see #setExpandRatio(int)
  1553. */
  1554. public Column<T, V> setMaximumWidth(double pixels) {
  1555. checkColumnIsAttached();
  1556. final double minwidth = getMinimumWidth();
  1557. if (pixels >= 0 && pixels < minwidth && minwidth >= 0) {
  1558. throw new IllegalArgumentException("New maximum width ("
  1559. + pixels + ") was less than minimum width (" + minwidth
  1560. + ")");
  1561. }
  1562. getState().maxWidth = pixels;
  1563. getGrid().markAsDirty();
  1564. return this;
  1565. }
  1566. /**
  1567. * Returns the maximum width for this column.
  1568. *
  1569. * @return the maximum width for this column
  1570. * @see #setMaximumWidth(double)
  1571. */
  1572. public double getMaximumWidth() {
  1573. return getState(false).maxWidth;
  1574. }
  1575. /**
  1576. * Sets whether this column can be resized by the user.
  1577. *
  1578. * @since 7.6
  1579. * @param resizable
  1580. * {@code true} if this column should be resizable,
  1581. * {@code false} otherwise
  1582. * @throws IllegalStateException
  1583. * if the column is no longer attached to any grid
  1584. */
  1585. public Column<T, V> setResizable(boolean resizable) {
  1586. checkColumnIsAttached();
  1587. if (resizable != isResizable()) {
  1588. getState().resizable = resizable;
  1589. getGrid().markAsDirty();
  1590. }
  1591. return this;
  1592. }
  1593. /**
  1594. * Gets the caption of the hiding toggle for this column.
  1595. *
  1596. * @since 7.5.0
  1597. * @see #setHidingToggleCaption(String)
  1598. * @return the caption for the hiding toggle for this column
  1599. */
  1600. public String getHidingToggleCaption() {
  1601. return getState(false).hidingToggleCaption;
  1602. }
  1603. /**
  1604. * Sets the caption of the hiding toggle for this column. Shown in the
  1605. * toggle for this column in the grid's sidebar when the column is
  1606. * {@link #isHidable() hidable}.
  1607. * <p>
  1608. * The default value is <code>null</code>, and in that case the column's
  1609. * {@link #getCaption() header caption} is used.
  1610. * <p>
  1611. * <em>NOTE:</em> setting this to empty string might cause the hiding
  1612. * toggle to not render correctly.
  1613. *
  1614. * @since 7.5.0
  1615. * @param hidingToggleCaption
  1616. * the text to show in the column hiding toggle
  1617. * @return the column itself
  1618. */
  1619. public Column<T, V> setHidingToggleCaption(String hidingToggleCaption) {
  1620. if (hidingToggleCaption != getHidingToggleCaption()) {
  1621. getState().hidingToggleCaption = hidingToggleCaption;
  1622. }
  1623. return this;
  1624. }
  1625. /**
  1626. * Hides or shows the column. By default columns are visible before
  1627. * explicitly hiding them.
  1628. *
  1629. * @since 7.5.0
  1630. * @param hidden
  1631. * <code>true</code> to hide the column, <code>false</code>
  1632. * to show
  1633. * @return this column
  1634. * @throws IllegalStateException
  1635. * if the column is no longer attached to any grid
  1636. */
  1637. public Column<T, V> setHidden(boolean hidden) {
  1638. checkColumnIsAttached();
  1639. if (hidden != isHidden()) {
  1640. getState().hidden = hidden;
  1641. getGrid().fireColumnVisibilityChangeEvent(this, hidden, false);
  1642. }
  1643. return this;
  1644. }
  1645. /**
  1646. * Returns whether this column is hidden. Default is {@code false}.
  1647. *
  1648. * @since 7.5.0
  1649. * @return <code>true</code> if the column is currently hidden,
  1650. * <code>false</code> otherwise
  1651. */
  1652. public boolean isHidden() {
  1653. return getState(false).hidden;
  1654. }
  1655. /**
  1656. * Sets whether this column can be hidden by the user. Hidable columns
  1657. * can be hidden and shown via the sidebar menu.
  1658. *
  1659. * @since 7.5.0
  1660. * @param hidable
  1661. * <code>true</code> if the column may be hidable by the user
  1662. * via UI interaction
  1663. * @return this column
  1664. */
  1665. public Column<T, V> setHidable(boolean hidable) {
  1666. if (hidable != isHidable()) {
  1667. getState().hidable = hidable;
  1668. }
  1669. return this;
  1670. }
  1671. /**
  1672. * Returns whether this column can be hidden by the user. Default is
  1673. * {@code false}.
  1674. * <p>
  1675. * <em>Note:</em> the column can be programmatically hidden using
  1676. * {@link #setHidden(boolean)} regardless of the returned value.
  1677. *
  1678. * @since 7.5.0
  1679. * @return <code>true</code> if the user can hide the column,
  1680. * <code>false</code> if not
  1681. */
  1682. public boolean isHidable() {
  1683. return getState(false).hidable;
  1684. }
  1685. /**
  1686. * Returns whether this column can be resized by the user. Default is
  1687. * {@code true}.
  1688. * <p>
  1689. * <em>Note:</em> the column can be programmatically resized using
  1690. * {@link #setWidth(double)} and {@link #setWidthUndefined()} regardless
  1691. * of the returned value.
  1692. *
  1693. * @since 7.6
  1694. * @return {@code true} if this column is resizable, {@code false}
  1695. * otherwise
  1696. */
  1697. public boolean isResizable() {
  1698. return getState(false).resizable;
  1699. }
  1700. /**
  1701. * Sets whether this Column has a component displayed in Editor or not.
  1702. * A column can only be editable if an editor component or binding has
  1703. * been set.
  1704. *
  1705. * @param editable
  1706. * {@code true} if column is editable; {@code false} if not
  1707. * @return this column
  1708. *
  1709. * @see #setEditorComponent(HasValue, Setter)
  1710. * @see #setEditorBinding(Binding)
  1711. */
  1712. public Column<T, V> setEditable(boolean editable) {
  1713. Objects.requireNonNull(editorBinding,
  1714. "Column has no editor binding or component defined");
  1715. getState().editable = editable;
  1716. return this;
  1717. }
  1718. /**
  1719. * Gets whether this Column has a component displayed in Editor or not.
  1720. *
  1721. * @return {@code true} if the column displays an editor component;
  1722. * {@code false} if not
  1723. */
  1724. public boolean isEditable() {
  1725. return getState(false).editable;
  1726. }
  1727. /**
  1728. * Sets an editor binding for this column. The {@link Binding} is used
  1729. * when a row is in editor mode to define how to populate an editor
  1730. * component based on the edited row and how to update an item based on
  1731. * the value in the editor component.
  1732. * <p>
  1733. * To create a binding to use with a column, define a binding for the
  1734. * editor binder (<code>grid.getEditor().getBinder()</code>) using e.g.
  1735. * {@link Binder#forField(HasValue)}. You can also use
  1736. * {@link #setEditorComponent(HasValue, Setter)} if no validator or
  1737. * converter is needed for the binding.
  1738. * <p>
  1739. * The {@link HasValue} that the binding is defined to use must be a
  1740. * {@link Component}.
  1741. *
  1742. * @param binding
  1743. * the binding to use for this column
  1744. * @return this column
  1745. *
  1746. * @see #setEditorComponent(HasValue, Setter)
  1747. * @see Binding
  1748. * @see Grid#getEditor()
  1749. * @see Editor#getBinder()
  1750. */
  1751. public Column<T, V> setEditorBinding(Binding<T, ?> binding) {
  1752. Objects.requireNonNull(binding, "null is not a valid editor field");
  1753. if (!(binding.getField() instanceof Component)) {
  1754. throw new IllegalArgumentException(
  1755. "Binding target must be a component.");
  1756. }
  1757. this.editorBinding = binding;
  1758. return setEditable(true);
  1759. }
  1760. /**
  1761. * Gets the binder binding that is currently used for this column.
  1762. *
  1763. * @return the used binder binding, or <code>null</code> if no binding
  1764. * is configured
  1765. *
  1766. * @see #setEditorBinding(Binding)
  1767. */
  1768. public Binding<T, ?> getEditorBinding() {
  1769. return editorBinding;
  1770. }
  1771. /**
  1772. * Sets a component and setter to use for editing values of this column
  1773. * in the editor row. This is a shorthand for use in simple cases where
  1774. * no validator or converter is needed. Use
  1775. * {@link #setEditorBinding(Binding)} to support more complex cases.
  1776. * <p>
  1777. * <strong>Note:</strong> The same component cannot be used for multiple
  1778. * columns.
  1779. *
  1780. * @param editorComponent
  1781. * the editor component
  1782. * @param setter
  1783. * a setter that stores the component value in the row item
  1784. * @return this column
  1785. *
  1786. * @see #setEditorBinding(Binding)
  1787. * @see Grid#getEditor()
  1788. * @see Binder#bind(HasValue, ValueProvider, Setter)
  1789. */
  1790. public <C extends HasValue<V> & Component> Column<T, V> setEditorComponent(
  1791. C editorComponent, Setter<T, V> setter) {
  1792. Objects.requireNonNull(editorComponent,
  1793. "Editor component cannot be null");
  1794. Objects.requireNonNull(setter, "Setter cannot be null");
  1795. Binding<T, V> binding = getGrid().getEditor().getBinder()
  1796. .bind(editorComponent, valueProvider::apply, setter);
  1797. return setEditorBinding(binding);
  1798. }
  1799. /**
  1800. * Sets a component to use for editing values of this columns in the
  1801. * editor row. This method can only be used if the column has an
  1802. * {@link #setId(String) id} and the {@link Grid} has been created using
  1803. * {@link Grid#Grid(Class)} or some other way that allows finding
  1804. * properties based on property names.
  1805. * <p>
  1806. * This is a shorthand for use in simple cases where no validator or
  1807. * converter is needed. Use {@link #setEditorBinding(Binding)} to
  1808. * support more complex cases.
  1809. * <p>
  1810. * <strong>Note:</strong> The same component cannot be used for multiple
  1811. * columns.
  1812. *
  1813. * @param editorComponent
  1814. * the editor component
  1815. * @return this column
  1816. *
  1817. * @see #setEditorBinding(Binding)
  1818. * @see Grid#getEditor()
  1819. * @see Binder#bind(HasValue, String)
  1820. * @see Grid#Grid(Class)
  1821. */
  1822. public <F, C extends HasValue<F> & Component> Column<T, V> setEditorComponent(
  1823. C editorComponent) {
  1824. Objects.requireNonNull(editorComponent,
  1825. "Editor component cannot be null");
  1826. String propertyName = getId();
  1827. if (propertyName == null) {
  1828. throw new IllegalStateException(
  1829. "setEditorComponent without a setter can only be used if the column has an id. "
  1830. + "Use another setEditorComponent(Component, Setter) or setEditorBinding(Binding) instead.");
  1831. }
  1832. Binding<T, F> binding = getGrid().getEditor().getBinder()
  1833. .bind(editorComponent, propertyName);
  1834. return setEditorBinding(binding);
  1835. }
  1836. /**
  1837. * Sets the Renderer for this Column. Setting the renderer will cause
  1838. * all currently available row data to be recreated and sent to the
  1839. * client.
  1840. *
  1841. * @param renderer
  1842. * the new renderer
  1843. * @return this column
  1844. *
  1845. * @since 8.0.3
  1846. */
  1847. public Column<T, V> setRenderer(Renderer<? super V> renderer) {
  1848. return setRenderer(ValueProvider.identity(), renderer);
  1849. }
  1850. /**
  1851. * Sets the Renderer for this Column. Setting the renderer will cause
  1852. * all currently available row data to be recreated and sent to the
  1853. * client.
  1854. * <p>
  1855. * The presentation provider is a method that takes the value of this
  1856. * column on a single row, and maps that to a value that the renderer
  1857. * accepts. This feature can be used for storing a complex value in a
  1858. * column for editing, but providing a simplified presentation for the
  1859. * user when not editing.
  1860. *
  1861. * @param presentationProvider
  1862. * the function to get presentations from the value of this
  1863. * column, not {@code null}
  1864. * @param renderer
  1865. * the new renderer, not {@code null}
  1866. *
  1867. * @param <P>
  1868. * the presentation type
  1869. *
  1870. * @return this column
  1871. *
  1872. * @since 8.1
  1873. */
  1874. public <P> Column<T, V> setRenderer(
  1875. ValueProvider<V, P> presentationProvider,
  1876. Renderer<? super P> renderer) {
  1877. Objects.requireNonNull(renderer, "Renderer can not be null");
  1878. Objects.requireNonNull(presentationProvider,
  1879. "Presentation provider can not be null");
  1880. // Remove old renderer
  1881. Connector oldRenderer = getState().renderer;
  1882. if (oldRenderer instanceof Extension) {
  1883. removeExtension((Extension) oldRenderer);
  1884. }
  1885. // Set new renderer
  1886. getState().renderer = renderer;
  1887. addExtension(renderer);
  1888. this.presentationProvider = presentationProvider;
  1889. // Trigger redraw
  1890. getGrid().getDataCommunicator().reset();
  1891. return this;
  1892. }
  1893. /**
  1894. * Gets the Renderer for this Column.
  1895. *
  1896. * @return the renderer
  1897. * @since 8.1
  1898. */
  1899. public Renderer<?> getRenderer() {
  1900. return (Renderer<?>) getState().renderer;
  1901. }
  1902. /**
  1903. * Sets whether Grid should handle events in this Column from Components
  1904. * and Widgets rendered by certain Renderers. By default the events are
  1905. * not handled.
  1906. * <p>
  1907. * <strong>Note:</strong> Enabling this feature will for example select
  1908. * a row when a component is clicked. For example in the case of a
  1909. * {@link ComboBox} or {@link TextField} it might be problematic as the
  1910. * component gets re-rendered and might lose focus.
  1911. *
  1912. * @param handleWidgetEvents
  1913. * {@code true} to handle events; {@code false} to not
  1914. * @return this column
  1915. * @since 8.3
  1916. */
  1917. public Column<T, V> setHandleWidgetEvents(boolean handleWidgetEvents) {
  1918. getState().handleWidgetEvents = handleWidgetEvents;
  1919. return this;
  1920. }
  1921. /**
  1922. * Gets whether Grid is handling the events in this Column from
  1923. * Component and Widgets.
  1924. *
  1925. * @see #setHandleWidgetEvents(boolean)
  1926. *
  1927. * @return {@code true} if handling events; {@code false} if not
  1928. * @since 8.3
  1929. */
  1930. public boolean isHandleWidgetEvents() {
  1931. return getState(false).handleWidgetEvents;
  1932. }
  1933. /**
  1934. * Gets the grid that this column belongs to.
  1935. *
  1936. * @return the grid that this column belongs to, or <code>null</code> if
  1937. * this column has not yet been associated with any grid
  1938. */
  1939. @SuppressWarnings("unchecked")
  1940. protected Grid<T> getGrid() {
  1941. return (Grid<T>) getParent();
  1942. }
  1943. /**
  1944. * Checks if column is attached and throws an
  1945. * {@link IllegalStateException} if it is not.
  1946. *
  1947. * @throws IllegalStateException
  1948. * if the column is no longer attached to any grid
  1949. */
  1950. protected void checkColumnIsAttached() throws IllegalStateException {
  1951. if (getGrid() == null) {
  1952. throw new IllegalStateException(
  1953. "Column is no longer attached to a grid.");
  1954. }
  1955. }
  1956. /**
  1957. * Writes the design attributes for this column into given element.
  1958. *
  1959. * @since 7.5.0
  1960. *
  1961. * @param element
  1962. * Element to write attributes into
  1963. *
  1964. * @param designContext
  1965. * the design context
  1966. */
  1967. protected void writeDesign(Element element,
  1968. DesignContext designContext) {
  1969. Attributes attributes = element.attributes();
  1970. ColumnState defaultState = new ColumnState();
  1971. if (getId() == null) {
  1972. setId("column" + getGrid().getColumns().indexOf(this));
  1973. }
  1974. DesignAttributeHandler.writeAttribute("column-id", attributes,
  1975. getId(), null, String.class, designContext);
  1976. // Sortable is a special attribute that depends on the data
  1977. // provider.
  1978. DesignAttributeHandler.writeAttribute("sortable", attributes,
  1979. isSortable(), null, boolean.class, designContext);
  1980. DesignAttributeHandler.writeAttribute("editable", attributes,
  1981. isEditable(), defaultState.editable, boolean.class,
  1982. designContext);
  1983. DesignAttributeHandler.writeAttribute("resizable", attributes,
  1984. isResizable(), defaultState.resizable, boolean.class,
  1985. designContext);
  1986. DesignAttributeHandler.writeAttribute("hidable", attributes,
  1987. isHidable(), defaultState.hidable, boolean.class,
  1988. designContext);
  1989. DesignAttributeHandler.writeAttribute("hidden", attributes,
  1990. isHidden(), defaultState.hidden, boolean.class,
  1991. designContext);
  1992. DesignAttributeHandler.writeAttribute("hiding-toggle-caption",
  1993. attributes, getHidingToggleCaption(),
  1994. defaultState.hidingToggleCaption, String.class,
  1995. designContext);
  1996. DesignAttributeHandler.writeAttribute("width", attributes,
  1997. getWidth(), defaultState.width, Double.class,
  1998. designContext);
  1999. DesignAttributeHandler.writeAttribute("min-width", attributes,
  2000. getMinimumWidth(), defaultState.minWidth, Double.class,
  2001. designContext);
  2002. DesignAttributeHandler.writeAttribute("max-width", attributes,
  2003. getMaximumWidth(), defaultState.maxWidth, Double.class,
  2004. designContext);
  2005. DesignAttributeHandler.writeAttribute("expand", attributes,
  2006. getExpandRatio(), defaultState.expandRatio, Integer.class,
  2007. designContext);
  2008. }
  2009. /**
  2010. * Reads the design attributes for this column from given element.
  2011. *
  2012. * @since 7.5.0
  2013. * @param design
  2014. * Element to read attributes from
  2015. * @param designContext
  2016. * the design context
  2017. */
  2018. @SuppressWarnings("unchecked")
  2019. protected void readDesign(Element design, DesignContext designContext) {
  2020. Attributes attributes = design.attributes();
  2021. if (design.hasAttr("sortable")) {
  2022. setSortable(DesignAttributeHandler.readAttribute("sortable",
  2023. attributes, boolean.class));
  2024. } else {
  2025. setSortable(false);
  2026. }
  2027. if (design.hasAttr("editable")) {
  2028. /**
  2029. * This is a fake editor just to have something (otherwise
  2030. * "setEditable" throws an exception.
  2031. *
  2032. * Let's use TextField here because we support only Strings as
  2033. * inline data type. It will work incorrectly for other types
  2034. * but we don't support them anyway.
  2035. */
  2036. setEditorComponent((HasValue<V> & Component) new TextField(),
  2037. (item, value) -> {
  2038. // Ignore user value since we don't know the setter
  2039. });
  2040. setEditable(DesignAttributeHandler.readAttribute("editable",
  2041. attributes, boolean.class));
  2042. }
  2043. if (design.hasAttr("resizable")) {
  2044. setResizable(DesignAttributeHandler.readAttribute("resizable",
  2045. attributes, boolean.class));
  2046. }
  2047. if (design.hasAttr("hidable")) {
  2048. setHidable(DesignAttributeHandler.readAttribute("hidable",
  2049. attributes, boolean.class));
  2050. }
  2051. if (design.hasAttr("hidden")) {
  2052. setHidden(DesignAttributeHandler.readAttribute("hidden",
  2053. attributes, boolean.class));
  2054. }
  2055. if (design.hasAttr("hiding-toggle-caption")) {
  2056. setHidingToggleCaption(DesignAttributeHandler.readAttribute(
  2057. "hiding-toggle-caption", attributes, String.class));
  2058. }
  2059. if (design.hasAttr("assistive-caption")) {
  2060. setAssistiveCaption(DesignAttributeHandler.readAttribute(
  2061. "assistive-caption", attributes, String.class));
  2062. }
  2063. // Read size info where necessary.
  2064. if (design.hasAttr("width")) {
  2065. setWidth(DesignAttributeHandler.readAttribute("width",
  2066. attributes, Double.class));
  2067. }
  2068. if (design.hasAttr("min-width")) {
  2069. setMinimumWidth(DesignAttributeHandler
  2070. .readAttribute("min-width", attributes, Double.class));
  2071. }
  2072. if (design.hasAttr("max-width")) {
  2073. setMaximumWidth(DesignAttributeHandler
  2074. .readAttribute("max-width", attributes, Double.class));
  2075. }
  2076. if (design.hasAttr("expand")) {
  2077. if (design.attr("expand").isEmpty()) {
  2078. setExpandRatio(1);
  2079. } else {
  2080. setExpandRatio(DesignAttributeHandler.readAttribute(
  2081. "expand", attributes, Integer.class));
  2082. }
  2083. }
  2084. }
  2085. /**
  2086. * Gets the DataGenerator for this Column.
  2087. *
  2088. * @return data generator
  2089. */
  2090. private DataGenerator<T> getDataGenerator() {
  2091. return dataGenerator;
  2092. }
  2093. }
  2094. private class HeaderImpl extends Header {
  2095. @Override
  2096. protected Grid<T> getGrid() {
  2097. return Grid.this;
  2098. }
  2099. @Override
  2100. protected SectionState getState(boolean markAsDirty) {
  2101. return Grid.this.getState(markAsDirty).header;
  2102. }
  2103. @Override
  2104. protected Column<?, ?> getColumnByInternalId(String internalId) {
  2105. return getGrid().getColumnByInternalId(internalId);
  2106. }
  2107. @Override
  2108. @SuppressWarnings("unchecked")
  2109. protected String getInternalIdForColumn(Column<?, ?> column) {
  2110. return getGrid().getInternalIdForColumn((Column<T, ?>) column);
  2111. }
  2112. };
  2113. private class FooterImpl extends Footer {
  2114. @Override
  2115. protected Grid<T> getGrid() {
  2116. return Grid.this;
  2117. }
  2118. @Override
  2119. protected SectionState getState(boolean markAsDirty) {
  2120. return Grid.this.getState(markAsDirty).footer;
  2121. }
  2122. @Override
  2123. protected Column<?, ?> getColumnByInternalId(String internalId) {
  2124. return getGrid().getColumnByInternalId(internalId);
  2125. }
  2126. @Override
  2127. @SuppressWarnings("unchecked")
  2128. protected String getInternalIdForColumn(Column<?, ?> column) {
  2129. return getGrid().getInternalIdForColumn((Column<T, ?>) column);
  2130. }
  2131. };
  2132. private final Set<Column<T, ?>> columnSet = new LinkedHashSet<>();
  2133. private final Map<String, Column<T, ?>> columnKeys = new HashMap<>();
  2134. private final Map<String, Column<T, ?>> columnIds = new HashMap<>();
  2135. private final List<GridSortOrder<T>> sortOrder = new ArrayList<>();
  2136. private final DetailsManager<T> detailsManager;
  2137. private final Set<Component> extensionComponents = new HashSet<>();
  2138. private StyleGenerator<T> styleGenerator = item -> null;
  2139. private DescriptionGenerator<T> descriptionGenerator;
  2140. private final Header header = new HeaderImpl();
  2141. private final Footer footer = new FooterImpl();
  2142. private int counter = 0;
  2143. private GridSelectionModel<T> selectionModel;
  2144. private Editor<T> editor;
  2145. private PropertySet<T> propertySet;
  2146. private Class<T> beanType = null;
  2147. /**
  2148. * Creates a new grid without support for creating columns based on property
  2149. * names. Use an alternative constructor, such as {@link Grid#Grid(Class)},
  2150. * to create a grid that automatically sets up columns based on the type of
  2151. * presented data.
  2152. *
  2153. * @see #Grid(Class)
  2154. * @see #withPropertySet(PropertySet)
  2155. */
  2156. public Grid() {
  2157. this(new DataCommunicator<>());
  2158. }
  2159. /**
  2160. * Creates a new grid that uses reflection based on the provided bean type
  2161. * to automatically set up an initial set of columns. All columns will be
  2162. * configured using the same {@link Object#toString()} renderer that is used
  2163. * by {@link #addColumn(ValueProvider)}.
  2164. *
  2165. * @param beanType
  2166. * the bean type to use, not <code>null</code>
  2167. * @see #Grid()
  2168. * @see #withPropertySet(PropertySet)
  2169. */
  2170. public Grid(Class<T> beanType) {
  2171. this(beanType, new DataCommunicator<>());
  2172. }
  2173. /**
  2174. * Creates a new grid that uses custom data communicator and provided bean
  2175. * type
  2176. *
  2177. * It uses reflection of the provided bean type to automatically set up an
  2178. * initial set of columns. All columns will be configured using the same
  2179. * {@link Object#toString()} renderer that is used by
  2180. * {@link #addColumn(ValueProvider)}.
  2181. *
  2182. * @param beanType
  2183. * the bean type to use, not <code>null</code>
  2184. * @param dataCommunicator
  2185. * the data communicator to use, not<code>null</code>
  2186. * @since 8.0.7
  2187. */
  2188. protected Grid(Class<T> beanType, DataCommunicator<T> dataCommunicator) {
  2189. this(BeanPropertySet.get(beanType), dataCommunicator);
  2190. this.beanType = beanType;
  2191. }
  2192. /**
  2193. * Creates a new grid with the given data communicator and without support
  2194. * for creating columns based on property names.
  2195. *
  2196. * @param dataCommunicator
  2197. * the custom data communicator to set
  2198. * @see #Grid()
  2199. * @see #Grid(PropertySet, DataCommunicator)
  2200. * @since 8.0.7
  2201. */
  2202. protected Grid(DataCommunicator<T> dataCommunicator) {
  2203. this(new PropertySet<T>() {
  2204. @Override
  2205. public Stream<PropertyDefinition<T, ?>> getProperties() {
  2206. // No columns configured by default
  2207. return Stream.empty();
  2208. }
  2209. @Override
  2210. public Optional<PropertyDefinition<T, ?>> getProperty(String name) {
  2211. throw new IllegalStateException(
  2212. "A Grid created without a bean type class literal or a custom property set"
  2213. + " doesn't support finding properties by name.");
  2214. }
  2215. }, dataCommunicator);
  2216. }
  2217. /**
  2218. * Creates a grid using a custom {@link PropertySet} implementation for
  2219. * configuring the initial columns and resolving property names for
  2220. * {@link #addColumn(String)} and
  2221. * {@link Column#setEditorComponent(HasValue)}.
  2222. *
  2223. * @see #withPropertySet(PropertySet)
  2224. *
  2225. * @param propertySet
  2226. * the property set implementation to use, not <code>null</code>.
  2227. */
  2228. protected Grid(PropertySet<T> propertySet) {
  2229. this(propertySet, new DataCommunicator<>());
  2230. }
  2231. /**
  2232. * Creates a grid using a custom {@link PropertySet} implementation and
  2233. * custom data communicator.
  2234. * <p>
  2235. * Property set is used for configuring the initial columns and resolving
  2236. * property names for {@link #addColumn(String)} and
  2237. * {@link Column#setEditorComponent(HasValue)}.
  2238. *
  2239. * @see #withPropertySet(PropertySet)
  2240. *
  2241. * @param propertySet
  2242. * the property set implementation to use, not <code>null</code>.
  2243. * @param dataCommunicator
  2244. * the data communicator to use, not<code>null</code>
  2245. * @since 8.0.7
  2246. */
  2247. protected Grid(PropertySet<T> propertySet,
  2248. DataCommunicator<T> dataCommunicator) {
  2249. super(dataCommunicator);
  2250. registerRpc(new GridServerRpcImpl());
  2251. setDefaultHeaderRow(appendHeaderRow());
  2252. setSelectionModel(new SingleSelectionModelImpl<>());
  2253. detailsManager = new DetailsManager<>();
  2254. addExtension(detailsManager);
  2255. addDataGenerator(detailsManager);
  2256. addDataGenerator((item, json) -> {
  2257. String styleName = styleGenerator.apply(item);
  2258. if (styleName != null && !styleName.isEmpty()) {
  2259. json.put(GridState.JSONKEY_ROWSTYLE, styleName);
  2260. }
  2261. if (descriptionGenerator != null) {
  2262. String description = descriptionGenerator.apply(item);
  2263. if (description != null && !description.isEmpty()) {
  2264. json.put(GridState.JSONKEY_ROWDESCRIPTION, description);
  2265. }
  2266. }
  2267. });
  2268. setPropertySet(propertySet);
  2269. // Automatically add columns for all available properties
  2270. propertySet.getProperties().map(PropertyDefinition::getName)
  2271. .forEach(this::addColumn);
  2272. }
  2273. @Override
  2274. public void beforeClientResponse(boolean initial) {
  2275. super.beforeClientResponse(initial);
  2276. if (initial && editor.isOpen()) {
  2277. // Re-attaching grid. Any old editor should be closed.
  2278. editor.cancel();
  2279. }
  2280. }
  2281. /**
  2282. * Sets the property set to use for this grid. Does not create or update
  2283. * columns in any way but will delete and re-create the editor.
  2284. * <p>
  2285. * This is only meant to be called from constructors and readDesign, at a
  2286. * stage where it does not matter if you throw away the editor.
  2287. *
  2288. * @param propertySet
  2289. * the property set to use
  2290. *
  2291. * @since 8.0.3
  2292. */
  2293. protected void setPropertySet(PropertySet<T> propertySet) {
  2294. Objects.requireNonNull(propertySet, "propertySet cannot be null");
  2295. this.propertySet = propertySet;
  2296. if (editor instanceof Extension) {
  2297. removeExtension((Extension) editor);
  2298. }
  2299. editor = createEditor();
  2300. if (editor instanceof Extension) {
  2301. addExtension((Extension) editor);
  2302. }
  2303. }
  2304. /**
  2305. * Returns the property set used by this grid.
  2306. *
  2307. * @return propertySet the property set to return
  2308. * @since 8.4
  2309. */
  2310. protected PropertySet<T> getPropertySet() {
  2311. return propertySet;
  2312. }
  2313. /**
  2314. * Creates a grid using a custom {@link PropertySet} implementation for
  2315. * creating a default set of columns and for resolving property names with
  2316. * {@link #addColumn(String)} and
  2317. * {@link Column#setEditorComponent(HasValue)}.
  2318. * <p>
  2319. * This functionality is provided as static method instead of as a public
  2320. * constructor in order to make it possible to use a custom property set
  2321. * without creating a subclass while still leaving the public constructors
  2322. * focused on the common use cases.
  2323. *
  2324. * @see Grid#Grid()
  2325. * @see Grid#Grid(Class)
  2326. *
  2327. * @param propertySet
  2328. * the property set implementation to use, not <code>null</code>.
  2329. * @return a new grid using the provided property set, not <code>null</code>
  2330. */
  2331. public static <BEAN> Grid<BEAN> withPropertySet(
  2332. PropertySet<BEAN> propertySet) {
  2333. return new Grid<>(propertySet);
  2334. }
  2335. /**
  2336. * Creates a new {@code Grid} using the given caption.
  2337. *
  2338. * @param caption
  2339. * the caption of the grid
  2340. */
  2341. public Grid(String caption) {
  2342. this();
  2343. setCaption(caption);
  2344. }
  2345. /**
  2346. * Creates a new {@code Grid} using the given caption and
  2347. * {@code DataProvider}.
  2348. *
  2349. * @param caption
  2350. * the caption of the grid
  2351. * @param dataProvider
  2352. * the data provider, not {@code null}
  2353. */
  2354. public Grid(String caption, DataProvider<T, ?> dataProvider) {
  2355. this(caption);
  2356. setDataProvider(dataProvider);
  2357. }
  2358. /**
  2359. * Creates a new {@code Grid} using the given {@code DataProvider}.
  2360. *
  2361. * @param dataProvider
  2362. * the data provider, not {@code null}
  2363. */
  2364. public Grid(DataProvider<T, ?> dataProvider) {
  2365. this();
  2366. setDataProvider(dataProvider);
  2367. }
  2368. /**
  2369. * Creates a new {@code Grid} using the given caption and collection of
  2370. * items.
  2371. *
  2372. * @param caption
  2373. * the caption of the grid
  2374. * @param items
  2375. * the data items to use, not {@çode null}
  2376. */
  2377. public Grid(String caption, Collection<T> items) {
  2378. this(caption, DataProvider.ofCollection(items));
  2379. }
  2380. /**
  2381. * Gets the bean type used by this grid.
  2382. * <p>
  2383. * The bean type is used to automatically set up a column added using a
  2384. * property name.
  2385. *
  2386. * @return the used bean type or <code>null</code> if no bean type has been
  2387. * defined
  2388. *
  2389. * @since 8.0.3
  2390. */
  2391. public Class<T> getBeanType() {
  2392. return beanType;
  2393. }
  2394. public <V> void fireColumnVisibilityChangeEvent(Column<T, V> column,
  2395. boolean hidden, boolean userOriginated) {
  2396. fireEvent(new ColumnVisibilityChangeEvent(this, column, hidden,
  2397. userOriginated));
  2398. }
  2399. /**
  2400. * Adds a new column with the given property name. The column will use a
  2401. * {@link TextRenderer}. The value is converted to a String using
  2402. * {@link Object#toString()}. The property name will be used as the
  2403. * {@link Column#getId() column id} and the {@link Column#getCaption()
  2404. * column caption} will be set based on the property definition.
  2405. * <p>
  2406. * This method can only be used for a <code>Grid</code> created using
  2407. * {@link Grid#Grid(Class)} or {@link #withPropertySet(PropertySet)}.
  2408. * <p>
  2409. * You can add columns for nested properties with dot notation, eg.
  2410. * <code>"property.nestedProperty"</code>
  2411. *
  2412. * @param propertyName
  2413. * the property name of the new column, not <code>null</code>
  2414. * @return the newly added column, not <code>null</code>
  2415. */
  2416. public Column<T, ?> addColumn(String propertyName) {
  2417. return addColumn(propertyName, new TextRenderer());
  2418. }
  2419. /**
  2420. * Adds a new column with the given property name and renderer. The property
  2421. * name will be used as the {@link Column#getId() column id} and the
  2422. * {@link Column#getCaption() column caption} will be set based on the
  2423. * property definition.
  2424. * <p>
  2425. * This method can only be used for a <code>Grid</code> created using
  2426. * {@link Grid#Grid(Class)} or {@link #withPropertySet(PropertySet)}.
  2427. * <p>
  2428. * You can add columns for nested properties with dot notation, eg.
  2429. * <code>"property.nestedProperty"</code>
  2430. *
  2431. *
  2432. * @param propertyName
  2433. * the property name of the new column, not <code>null</code>
  2434. * @param renderer
  2435. * the renderer to use, not <code>null</code>
  2436. * @return the newly added column, not <code>null</code>
  2437. */
  2438. public Column<T, ?> addColumn(String propertyName,
  2439. AbstractRenderer<? super T, ?> renderer) {
  2440. Objects.requireNonNull(propertyName, "Property name cannot be null");
  2441. Objects.requireNonNull(renderer, "Renderer cannot be null");
  2442. if (getColumn(propertyName) != null) {
  2443. throw new IllegalStateException(
  2444. "There is already a column for " + propertyName);
  2445. }
  2446. PropertyDefinition<T, ?> definition = propertySet
  2447. .getProperty(propertyName)
  2448. .orElseThrow(() -> new IllegalArgumentException(
  2449. "Could not resolve property name " + propertyName
  2450. + " from " + propertySet));
  2451. if (!renderer.getPresentationType()
  2452. .isAssignableFrom(definition.getType())) {
  2453. throw new IllegalArgumentException(
  2454. renderer + " cannot be used with a property of type "
  2455. + definition.getType().getName());
  2456. }
  2457. @SuppressWarnings({ "unchecked", "rawtypes" })
  2458. Column<T, ?> column = addColumn(definition.getGetter(),
  2459. (AbstractRenderer) renderer).setId(definition.getName())
  2460. .setCaption(definition.getCaption());
  2461. return column;
  2462. }
  2463. /**
  2464. * Adds a new text column to this {@link Grid} with a value provider. The
  2465. * column will use a {@link TextRenderer}. The value is converted to a
  2466. * String using {@link Object#toString()}. In-memory sorting will use the
  2467. * natural ordering of elements if they are mutually comparable and
  2468. * otherwise fall back to comparing the string representations of the
  2469. * values.
  2470. *
  2471. * @param valueProvider
  2472. * the value provider
  2473. *
  2474. * @return the new column
  2475. */
  2476. public <V> Column<T, V> addColumn(ValueProvider<T, V> valueProvider) {
  2477. return addColumn(valueProvider, new TextRenderer());
  2478. }
  2479. /**
  2480. * Adds a new column to this {@link Grid} with typed renderer and value
  2481. * provider.
  2482. *
  2483. * @param valueProvider
  2484. * the value provider
  2485. * @param renderer
  2486. * the column value renderer
  2487. * @param <V>
  2488. * the column value type
  2489. *
  2490. * @return the new column
  2491. *
  2492. * @see AbstractRenderer
  2493. */
  2494. public <V> Column<T, V> addColumn(ValueProvider<T, V> valueProvider,
  2495. AbstractRenderer<? super T, ? super V> renderer) {
  2496. return addColumn(valueProvider, ValueProvider.identity(), renderer);
  2497. }
  2498. /**
  2499. * Adds a new column to this {@link Grid} with value provider and
  2500. * presentation provider.
  2501. * <p>
  2502. * <strong>Note:</strong> The presentation type for this method is set to be
  2503. * String. To use any custom renderer with the presentation provider, use
  2504. * {@link #addColumn(ValueProvider, ValueProvider, AbstractRenderer)}.
  2505. *
  2506. * @param valueProvider
  2507. * the value provider
  2508. * @param presentationProvider
  2509. * the value presentation provider
  2510. * @param <V>
  2511. * the column value type
  2512. *
  2513. * @see #addColumn(ValueProvider, ValueProvider, AbstractRenderer)
  2514. *
  2515. * @return the new column
  2516. * @since 8.1
  2517. */
  2518. public <V> Column<T, V> addColumn(ValueProvider<T, V> valueProvider,
  2519. ValueProvider<V, String> presentationProvider) {
  2520. return addColumn(valueProvider, presentationProvider,
  2521. new TextRenderer());
  2522. }
  2523. /**
  2524. * Adds a new column to this {@link Grid} with value provider, presentation
  2525. * provider and typed renderer.
  2526. *
  2527. * <p>
  2528. * The presentation provider is a method that takes the value from the value
  2529. * provider, and maps that to a value that the renderer accepts. This
  2530. * feature can be used for storing a complex value in a column for editing,
  2531. * but providing a simplified presentation for the user when not editing.
  2532. *
  2533. * @param valueProvider
  2534. * the value provider
  2535. * @param presentationProvider
  2536. * the value presentation provider
  2537. * @param renderer
  2538. * the column value renderer
  2539. * @param <V>
  2540. * the column value type
  2541. * @param <P>
  2542. * the column presentation type
  2543. *
  2544. * @return the new column
  2545. *
  2546. * @see AbstractRenderer
  2547. * @since 8.1
  2548. */
  2549. public <V, P> Column<T, V> addColumn(ValueProvider<T, V> valueProvider,
  2550. ValueProvider<V, P> presentationProvider,
  2551. AbstractRenderer<? super T, ? super P> renderer) {
  2552. String generatedIdentifier = getGeneratedIdentifier();
  2553. Column<T, V> column = createColumn(valueProvider, presentationProvider,
  2554. renderer);
  2555. addColumn(generatedIdentifier, column);
  2556. return column;
  2557. }
  2558. /**
  2559. * Adds a column that shows components.
  2560. * <p>
  2561. * This is a shorthand for {@link #addColum()} with a
  2562. * {@link ComponentRenderer}.
  2563. *
  2564. * @param componentProvider
  2565. * a value provider that will return a component for the given
  2566. * item
  2567. * @return the new column
  2568. * @param <V>
  2569. * the column value type, extends component
  2570. * @since 8.1
  2571. */
  2572. public <V extends Component> Column<T, V> addComponentColumn(
  2573. ValueProvider<T, V> componentProvider) {
  2574. return addColumn(componentProvider, new ComponentRenderer());
  2575. }
  2576. /**
  2577. * Creates a column instance from a value provider, presentation provider
  2578. * and a renderer.
  2579. *
  2580. * @param valueProvider
  2581. * the value provider
  2582. * @param presentationProvider
  2583. * the presentation provider
  2584. * @param renderer
  2585. * the renderer
  2586. * @return a new column instance
  2587. * @param <V>
  2588. * the column value type
  2589. * @param <P>
  2590. * the column presentation type
  2591. *
  2592. * @since 8.1
  2593. */
  2594. protected <V, P> Column<T, V> createColumn(
  2595. ValueProvider<T, V> valueProvider,
  2596. ValueProvider<V, P> presentationProvider,
  2597. AbstractRenderer<? super T, ? super P> renderer) {
  2598. return new Column<>(valueProvider, presentationProvider, renderer);
  2599. }
  2600. private void addColumn(String identifier, Column<T, ?> column) {
  2601. if (getColumns().contains(column)) {
  2602. return;
  2603. }
  2604. column.extend(this);
  2605. columnSet.add(column);
  2606. columnKeys.put(identifier, column);
  2607. column.setInternalId(identifier);
  2608. addDataGenerator(column.getDataGenerator());
  2609. getState().columnOrder.add(identifier);
  2610. getHeader().addColumn(identifier);
  2611. getFooter().addColumn(identifier);
  2612. if (getDefaultHeaderRow() != null) {
  2613. getDefaultHeaderRow().getCell(column).setText(column.getCaption());
  2614. }
  2615. column.updateSortable();
  2616. }
  2617. /**
  2618. * Removes the given column from this {@link Grid}.
  2619. *
  2620. * @param column
  2621. * the column to remove
  2622. *
  2623. * @throws IllegalArgumentException
  2624. * if the column is not a valid one
  2625. */
  2626. public void removeColumn(Column<T, ?> column) {
  2627. if (columnSet.remove(column)) {
  2628. String columnId = column.getInternalId();
  2629. int displayIndex = getState(false).columnOrder.indexOf(columnId);
  2630. assert displayIndex != -1 : "Tried to remove a column which is not included in columnOrder. This should not be possible as all columns should be in columnOrder.";
  2631. columnKeys.remove(columnId);
  2632. columnIds.remove(column.getId());
  2633. column.remove();
  2634. removeDataGenerator(column.getDataGenerator());
  2635. getHeader().removeColumn(columnId);
  2636. getFooter().removeColumn(columnId);
  2637. getState(true).columnOrder.remove(columnId);
  2638. // Remove column from sorted columns.
  2639. List<GridSortOrder<T>> filteredSortOrder = sortOrder.stream()
  2640. .filter(order -> !order.getSorted().equals(column))
  2641. .collect(Collectors.toList());
  2642. if (filteredSortOrder.size() < sortOrder.size()) {
  2643. setSortOrder(filteredSortOrder);
  2644. }
  2645. if (displayIndex < getFrozenColumnCount()) {
  2646. setFrozenColumnCount(getFrozenColumnCount() - 1);
  2647. }
  2648. } else {
  2649. throw new IllegalArgumentException("Column with id "
  2650. + column.getId() + " cannot be removed from the grid");
  2651. }
  2652. }
  2653. /**
  2654. * Removes the column with the given column id.
  2655. *
  2656. * @see #removeColumn(Column)
  2657. * @see Column#setId(String)
  2658. *
  2659. * @param columnId
  2660. * the id of the column to remove, not <code>null</code>
  2661. */
  2662. public void removeColumn(String columnId) {
  2663. removeColumn(getColumnOrThrow(columnId));
  2664. }
  2665. /**
  2666. * Removes all columns from this Grid.
  2667. *
  2668. * @since 8.0.2
  2669. */
  2670. public void removeAllColumns() {
  2671. for (Column<T, ?> column : getColumns()) {
  2672. removeColumn(column);
  2673. }
  2674. }
  2675. /**
  2676. * Requests that the column widths should be recalculated.
  2677. * <p>
  2678. * In most cases Grid will know when column widths need to be recalculated
  2679. * but this method can be used to force recalculation in situations when
  2680. * grid does not recalculate automatically.
  2681. *
  2682. * @since 8.1.1
  2683. */
  2684. public void recalculateColumnWidths() {
  2685. getRpcProxy(GridClientRpc.class).recalculateColumnWidths();
  2686. }
  2687. /**
  2688. * Sets the details component generator.
  2689. *
  2690. * @param generator
  2691. * the generator for details components
  2692. */
  2693. public void setDetailsGenerator(DetailsGenerator<T> generator) {
  2694. this.detailsManager.setDetailsGenerator(generator);
  2695. }
  2696. /**
  2697. * Sets the visibility of details component for given item.
  2698. *
  2699. * @param item
  2700. * the item to show details for
  2701. * @param visible
  2702. * {@code true} if details component should be visible;
  2703. * {@code false} if it should be hidden
  2704. */
  2705. public void setDetailsVisible(T item, boolean visible) {
  2706. detailsManager.setDetailsVisible(item, visible);
  2707. }
  2708. /**
  2709. * Returns the visibility of details component for given item.
  2710. *
  2711. * @param item
  2712. * the item to show details for
  2713. *
  2714. * @return {@code true} if details component should be visible;
  2715. * {@code false} if it should be hidden
  2716. */
  2717. public boolean isDetailsVisible(T item) {
  2718. return detailsManager.isDetailsVisible(item);
  2719. }
  2720. /**
  2721. * Gets an unmodifiable collection of all columns currently in this
  2722. * {@link Grid}.
  2723. *
  2724. * @return unmodifiable collection of columns
  2725. */
  2726. public List<Column<T, ?>> getColumns() {
  2727. return Collections.unmodifiableList(getState(false).columnOrder.stream()
  2728. .map(columnKeys::get).collect(Collectors.toList()));
  2729. }
  2730. /**
  2731. * Gets a {@link Column} of this grid by its identifying string.
  2732. *
  2733. * When you use the Grid constructor with bean class, the columns are
  2734. * initialised with columnId being the property name.
  2735. *
  2736. * @see Column#setId(String)
  2737. *
  2738. * @param columnId
  2739. * the identifier of the column to get
  2740. * @return the column corresponding to the given column identifier, or
  2741. * <code>null</code> if there is no such column
  2742. */
  2743. public Column<T, ?> getColumn(String columnId) {
  2744. return columnIds.get(columnId);
  2745. }
  2746. private Column<T, ?> getColumnOrThrow(String columnId) {
  2747. Objects.requireNonNull(columnId, "Column id cannot be null");
  2748. Column<T, ?> column = getColumn(columnId);
  2749. if (column == null) {
  2750. throw new IllegalStateException(
  2751. "There is no column with the id " + columnId);
  2752. }
  2753. return column;
  2754. }
  2755. /**
  2756. * {@inheritDoc}
  2757. * <p>
  2758. * Note that the order of the returned components it not specified.
  2759. */
  2760. @Override
  2761. public Iterator<Component> iterator() {
  2762. Set<Component> componentSet = new LinkedHashSet<>(extensionComponents);
  2763. Header header = getHeader();
  2764. for (int i = 0; i < header.getRowCount(); ++i) {
  2765. HeaderRow row = header.getRow(i);
  2766. componentSet.addAll(row.getComponents());
  2767. }
  2768. Footer footer = getFooter();
  2769. for (int i = 0; i < footer.getRowCount(); ++i) {
  2770. FooterRow row = footer.getRow(i);
  2771. componentSet.addAll(row.getComponents());
  2772. }
  2773. return Collections.unmodifiableSet(componentSet).iterator();
  2774. }
  2775. /**
  2776. * Sets the number of frozen columns in this grid. Setting the count to 0
  2777. * means that no data columns will be frozen, but the built-in selection
  2778. * checkbox column will still be frozen if it's in use. Setting the count to
  2779. * -1 will also disable the selection column.
  2780. * <p>
  2781. * <em>NOTE:</em> this count includes {@link Column#isHidden() hidden
  2782. * columns} in the count.
  2783. * <p>
  2784. * The default value is 0.
  2785. *
  2786. * @param numberOfColumns
  2787. * the number of columns that should be frozen
  2788. *
  2789. * @throws IllegalArgumentException
  2790. * if the column count is less than -1 or greater than the
  2791. * number of visible columns
  2792. */
  2793. public void setFrozenColumnCount(int numberOfColumns) {
  2794. if (numberOfColumns < -1 || numberOfColumns > columnSet.size()) {
  2795. throw new IllegalArgumentException(
  2796. "count must be between -1 and the current number of columns ("
  2797. + columnSet.size() + "): " + numberOfColumns);
  2798. }
  2799. int currentFrozenColumnState = getState(false).frozenColumnCount;
  2800. /*
  2801. * we remove the current value from the state so that setting frozen
  2802. * columns will always happen after this call. This is so that the value
  2803. * will be set also in the widget even if it happens to seem to be the
  2804. * same as this current value we're setting.
  2805. */
  2806. if (currentFrozenColumnState != numberOfColumns) {
  2807. final String diffStateKey = "frozenColumnCount";
  2808. UI ui = getUI();
  2809. if (ui != null) {
  2810. ui.getConnectorTracker().getDiffState(Grid.this)
  2811. .remove(diffStateKey);
  2812. }
  2813. }
  2814. getState().frozenColumnCount = numberOfColumns;
  2815. }
  2816. /**
  2817. * Gets the number of frozen columns in this grid. 0 means that no data
  2818. * columns will be frozen, but the built-in selection checkbox column will
  2819. * still be frozen if it's in use. -1 means that not even the selection
  2820. * column is frozen.
  2821. * <p>
  2822. * <em>NOTE:</em> this count includes {@link Column#isHidden() hidden
  2823. * columns} in the count.
  2824. *
  2825. * @see #setFrozenColumnCount(int)
  2826. *
  2827. * @return the number of frozen columns
  2828. */
  2829. public int getFrozenColumnCount() {
  2830. return getState(false).frozenColumnCount;
  2831. }
  2832. /**
  2833. * Sets the number of rows that should be visible in Grid's body. This
  2834. * method will set the height mode to be {@link HeightMode#ROW}.
  2835. *
  2836. * @param rows
  2837. * The height in terms of number of rows displayed in Grid's
  2838. * body. If Grid doesn't contain enough rows, white space is
  2839. * displayed instead.
  2840. * @throws IllegalArgumentException
  2841. * if {@code rows} is zero or less
  2842. * @throws IllegalArgumentException
  2843. * if {@code rows} is {@link Double#isInfinite(double) infinite}
  2844. * @throws IllegalArgumentException
  2845. * if {@code rows} is {@link Double#isNaN(double) NaN}
  2846. */
  2847. public void setHeightByRows(double rows) {
  2848. if (rows <= 0.0d) {
  2849. throw new IllegalArgumentException(
  2850. "More than zero rows must be shown.");
  2851. }
  2852. if (Double.isInfinite(rows)) {
  2853. throw new IllegalArgumentException(
  2854. "Grid doesn't support infinite heights");
  2855. }
  2856. if (Double.isNaN(rows)) {
  2857. throw new IllegalArgumentException("NaN is not a valid row count");
  2858. }
  2859. getState().heightMode = HeightMode.ROW;
  2860. getState().heightByRows = rows;
  2861. }
  2862. /**
  2863. * Gets the amount of rows in Grid's body that are shown, while
  2864. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  2865. *
  2866. * @return the amount of rows that are being shown in Grid's body
  2867. * @see #setHeightByRows(double)
  2868. */
  2869. public double getHeightByRows() {
  2870. return getState(false).heightByRows;
  2871. }
  2872. /**
  2873. * {@inheritDoc}
  2874. * <p>
  2875. * <em>Note:</em> This method will set the height mode to be
  2876. * {@link HeightMode#CSS}.
  2877. *
  2878. * @see #setHeightMode(HeightMode)
  2879. */
  2880. @Override
  2881. public void setHeight(float height, Unit unit) {
  2882. getState().heightMode = HeightMode.CSS;
  2883. super.setHeight(height, unit);
  2884. }
  2885. /**
  2886. * Defines the mode in which the Grid widget's height is calculated.
  2887. * <p>
  2888. * If {@link HeightMode#CSS} is given, Grid will respect the values given
  2889. * via a {@code setHeight}-method, and behave as a traditional Component.
  2890. * <p>
  2891. * If {@link HeightMode#ROW} is given, Grid will make sure that the body
  2892. * will display as many rows as {@link #getHeightByRows()} defines.
  2893. * <em>Note:</em> If headers/footers are inserted or removed, the widget
  2894. * will resize itself to still display the required amount of rows in its
  2895. * body. It also takes the horizontal scrollbar into account.
  2896. *
  2897. * @param heightMode
  2898. * the mode in to which Grid should be set
  2899. */
  2900. public void setHeightMode(HeightMode heightMode) {
  2901. /**
  2902. * This method is a workaround for the fact that Vaadin re-applies
  2903. * widget dimensions (height/width) on each state change event. The
  2904. * original design was to have setHeight and setHeightByRow be equals,
  2905. * and whichever was called the latest was considered in effect.
  2906. *
  2907. * But, because of Vaadin always calling setHeight on the widget, this
  2908. * approach doesn't work.
  2909. */
  2910. getState().heightMode = heightMode;
  2911. }
  2912. /**
  2913. * Returns the current {@link HeightMode} the Grid is in.
  2914. * <p>
  2915. * Defaults to {@link HeightMode#CSS}.
  2916. *
  2917. * @return the current HeightMode
  2918. */
  2919. public HeightMode getHeightMode() {
  2920. return getState(false).heightMode;
  2921. }
  2922. /**
  2923. * Sets the height of body, header and footer rows. If -1 (default), the row
  2924. * height is calculated based on the theme for an empty row before the Grid
  2925. * is displayed.
  2926. * <p>
  2927. * Note that all header, body and footer rows get the same height if
  2928. * explicitly set. In automatic mode, each section is calculated separately
  2929. * based on an empty row of that type.
  2930. *
  2931. * @see #setBodyRowHeight(double)
  2932. * @see #setHeaderRowHeight(double)
  2933. * @see #setFooterRowHeight(double)
  2934. *
  2935. * @param rowHeight
  2936. * The height of a row in pixels or -1 for automatic calculation
  2937. */
  2938. public void setRowHeight(double rowHeight) {
  2939. setBodyRowHeight(rowHeight);
  2940. setHeaderRowHeight(rowHeight);
  2941. setFooterRowHeight(rowHeight);
  2942. }
  2943. /**
  2944. * Sets the height of a body row. If -1 (default), the row height is
  2945. * calculated based on the theme for an empty row before the Grid is
  2946. * displayed.
  2947. *
  2948. * @param rowHeight
  2949. * The height of a row in pixels or -1 for automatic calculation
  2950. * @since 8.2
  2951. */
  2952. public void setBodyRowHeight(double rowHeight) {
  2953. getState().bodyRowHeight = rowHeight;
  2954. }
  2955. /**
  2956. * Sets the height of a header row. If -1 (default), the row height is
  2957. * calculated based on the theme for an empty row before the Grid is
  2958. * displayed.
  2959. *
  2960. * @param rowHeight
  2961. * The height of a row in pixels or -1 for automatic calculation
  2962. * @since 8.2
  2963. */
  2964. public void setHeaderRowHeight(double rowHeight) {
  2965. getState().headerRowHeight = rowHeight;
  2966. }
  2967. /**
  2968. * Sets the height of a footer row. If -1 (default), the row height is
  2969. * calculated based on the theme for an empty row before the Grid is
  2970. * displayed.
  2971. *
  2972. * @param rowHeight
  2973. * The height of a row in pixels or -1 for automatic calculation
  2974. * @since 8.2
  2975. */
  2976. public void setFooterRowHeight(double rowHeight) {
  2977. getState().footerRowHeight = rowHeight;
  2978. }
  2979. /**
  2980. * Returns the current body row height.-1 if row height is in automatic
  2981. * calculation mode.
  2982. *
  2983. * @see #getBodyRowHeight()
  2984. * @see #getHeaderRowHeight()
  2985. * @see #getFooterRowHeight()
  2986. *
  2987. * @return body row height
  2988. * @deprecated replaced by three separate row height controls
  2989. */
  2990. @Deprecated
  2991. public double getRowHeight() {
  2992. return getBodyRowHeight();
  2993. }
  2994. /**
  2995. * Returns the current body row height. -1 if row height is in automatic
  2996. * calculation mode.
  2997. *
  2998. * @return body row height
  2999. * @since 8.2
  3000. */
  3001. public double getBodyRowHeight() {
  3002. return getState(false).bodyRowHeight;
  3003. }
  3004. /**
  3005. * Returns the current header row height. -1 if row height is in automatic
  3006. * calculation mode.
  3007. *
  3008. * @return header row height
  3009. * @since 8.2
  3010. */
  3011. public double getHeaderRowHeight() {
  3012. return getState(false).headerRowHeight;
  3013. }
  3014. /**
  3015. * Returns the current footer row height. -1 if row height is in automatic
  3016. * calculation mode.
  3017. *
  3018. * @return footer row height
  3019. * @since 8.2
  3020. */
  3021. public double getFooterRowHeight() {
  3022. return getState(false).footerRowHeight;
  3023. }
  3024. /**
  3025. * Sets the style generator that is used for generating class names for rows
  3026. * in this grid. Returning null from the generator results in no custom
  3027. * style name being set.
  3028. *
  3029. * Note: The style generator is applied only to the body cells, not to the
  3030. * Editor.
  3031. *
  3032. * @see StyleGenerator
  3033. *
  3034. * @param styleGenerator
  3035. * the row style generator to set, not null
  3036. * @throws NullPointerException
  3037. * if {@code styleGenerator} is {@code null}
  3038. */
  3039. public void setStyleGenerator(StyleGenerator<T> styleGenerator) {
  3040. Objects.requireNonNull(styleGenerator,
  3041. "Style generator must not be null");
  3042. this.styleGenerator = styleGenerator;
  3043. getDataCommunicator().reset();
  3044. }
  3045. /**
  3046. * Gets the style generator that is used for generating class names for
  3047. * rows.
  3048. *
  3049. * @see StyleGenerator
  3050. *
  3051. * @return the row style generator
  3052. */
  3053. public StyleGenerator<T> getStyleGenerator() {
  3054. return styleGenerator;
  3055. }
  3056. /**
  3057. * Sets the description generator that is used for generating descriptions
  3058. * for rows. This method uses the {@link ContentMode#PREFORMATTED} content
  3059. * mode.
  3060. *
  3061. * @see #setDescriptionGenerator(DescriptionGenerator, ContentMode)
  3062. *
  3063. * @param descriptionGenerator
  3064. * the row description generator to set, or <code>null</code> to
  3065. * remove a previously set generator
  3066. */
  3067. public void setDescriptionGenerator(
  3068. DescriptionGenerator<T> descriptionGenerator) {
  3069. setDescriptionGenerator(descriptionGenerator, ContentMode.PREFORMATTED);
  3070. }
  3071. /**
  3072. * Sets the description generator that is used for generating descriptions
  3073. * for rows. This method uses the given content mode.
  3074. *
  3075. * @see #setDescriptionGenerator(DescriptionGenerator)
  3076. *
  3077. * @param descriptionGenerator
  3078. * the row description generator to set, or {@code null} to
  3079. * remove a previously set generator
  3080. * @param contentMode
  3081. * the content mode for row tooltips
  3082. *
  3083. * @since 8.2
  3084. */
  3085. public void setDescriptionGenerator(
  3086. DescriptionGenerator<T> descriptionGenerator,
  3087. ContentMode contentMode) {
  3088. Objects.requireNonNull(contentMode, "contentMode cannot be null");
  3089. this.descriptionGenerator = descriptionGenerator;
  3090. getState().rowDescriptionContentMode = contentMode;
  3091. getDataCommunicator().reset();
  3092. }
  3093. /**
  3094. * Gets the description generator that is used for generating descriptions
  3095. * for rows.
  3096. *
  3097. * @return the row description generator, or <code>null</code> if no
  3098. * generator is set
  3099. */
  3100. public DescriptionGenerator<T> getDescriptionGenerator() {
  3101. return descriptionGenerator;
  3102. }
  3103. //
  3104. // HEADER AND FOOTER
  3105. //
  3106. /**
  3107. * Returns the header row at the given index.
  3108. *
  3109. * @param index
  3110. * the index of the row, where the topmost row has index zero
  3111. * @return the header row at the index
  3112. * @throws IndexOutOfBoundsException
  3113. * if {@code rowIndex < 0 || rowIndex >= getHeaderRowCount()}
  3114. */
  3115. public HeaderRow getHeaderRow(int index) {
  3116. return getHeader().getRow(index);
  3117. }
  3118. /**
  3119. * Gets the number of rows in the header section.
  3120. *
  3121. * @return the number of header rows
  3122. */
  3123. public int getHeaderRowCount() {
  3124. return header.getRowCount();
  3125. }
  3126. /**
  3127. * Inserts a new row at the given position to the header section. Shifts the
  3128. * row currently at that position and any subsequent rows down (adds one to
  3129. * their indices). Inserting at {@link #getHeaderRowCount()} appends the row
  3130. * at the bottom of the header.
  3131. *
  3132. * @param index
  3133. * the index at which to insert the row, where the topmost row
  3134. * has index zero
  3135. * @return the inserted header row
  3136. *
  3137. * @throws IndexOutOfBoundsException
  3138. * if {@code rowIndex < 0 || rowIndex > getHeaderRowCount()}
  3139. *
  3140. * @see #appendHeaderRow()
  3141. * @see #prependHeaderRow()
  3142. * @see #removeHeaderRow(HeaderRow)
  3143. * @see #removeHeaderRow(int)
  3144. */
  3145. public HeaderRow addHeaderRowAt(int index) {
  3146. return getHeader().addRowAt(index);
  3147. }
  3148. /**
  3149. * Adds a new row at the bottom of the header section.
  3150. *
  3151. * @return the appended header row
  3152. *
  3153. * @see #prependHeaderRow()
  3154. * @see #addHeaderRowAt(int)
  3155. * @see #removeHeaderRow(HeaderRow)
  3156. * @see #removeHeaderRow(int)
  3157. */
  3158. public HeaderRow appendHeaderRow() {
  3159. return addHeaderRowAt(getHeaderRowCount());
  3160. }
  3161. /**
  3162. * Adds a new row at the top of the header section.
  3163. *
  3164. * @return the prepended header row
  3165. *
  3166. * @see #appendHeaderRow()
  3167. * @see #addHeaderRowAt(int)
  3168. * @see #removeHeaderRow(HeaderRow)
  3169. * @see #removeHeaderRow(int)
  3170. */
  3171. public HeaderRow prependHeaderRow() {
  3172. return addHeaderRowAt(0);
  3173. }
  3174. /**
  3175. * Removes the given row from the header section. Removing a default row
  3176. * sets the Grid to have no default row.
  3177. *
  3178. * @param row
  3179. * the header row to be removed, not null
  3180. *
  3181. * @throws IllegalArgumentException
  3182. * if the header does not contain the row
  3183. *
  3184. * @see #removeHeaderRow(int)
  3185. * @see #addHeaderRowAt(int)
  3186. * @see #appendHeaderRow()
  3187. * @see #prependHeaderRow()
  3188. */
  3189. public void removeHeaderRow(HeaderRow row) {
  3190. getHeader().removeRow(row);
  3191. }
  3192. /**
  3193. * Removes the row at the given position from the header section.
  3194. *
  3195. * @param index
  3196. * the index of the row to remove, where the topmost row has
  3197. * index zero
  3198. *
  3199. * @throws IndexOutOfBoundsException
  3200. * if {@code index < 0 || index >= getHeaderRowCount()}
  3201. *
  3202. * @see #removeHeaderRow(HeaderRow)
  3203. * @see #addHeaderRowAt(int)
  3204. * @see #appendHeaderRow()
  3205. * @see #prependHeaderRow()
  3206. */
  3207. public void removeHeaderRow(int index) {
  3208. getHeader().removeRow(index);
  3209. }
  3210. /**
  3211. * Sets the visibility of the Header in this Grid.
  3212. *
  3213. * @param headerVisible
  3214. * {@code true} if visible; {@code false} if not
  3215. *
  3216. * @since 8.1.1
  3217. */
  3218. public void setHeaderVisible(boolean headerVisible) {
  3219. getHeader().setVisible(headerVisible);
  3220. }
  3221. /**
  3222. * Gets the visibility of the Header in this Grid.
  3223. *
  3224. * @return {@code true} if visible; {@code false} if not
  3225. *
  3226. * @since 8.1.1
  3227. */
  3228. public boolean isHeaderVisible() {
  3229. return getHeader().isVisible();
  3230. }
  3231. /**
  3232. * Returns the current default row of the header.
  3233. *
  3234. * @return the default row or null if no default row set
  3235. *
  3236. * @see #setDefaultHeaderRow(HeaderRow)
  3237. */
  3238. public HeaderRow getDefaultHeaderRow() {
  3239. return header.getDefaultRow();
  3240. }
  3241. /**
  3242. * Sets the default row of the header. The default row is a special header
  3243. * row that displays column captions and sort indicators. By default Grid
  3244. * has a single row which is also the default row. When a header row is set
  3245. * as the default row, any existing cell content is replaced by the column
  3246. * captions.
  3247. *
  3248. * @param row
  3249. * the new default row, or null for no default row
  3250. *
  3251. * @throws IllegalArgumentException
  3252. * if the header does not contain the row
  3253. */
  3254. public void setDefaultHeaderRow(HeaderRow row) {
  3255. header.setDefaultRow((Row) row);
  3256. }
  3257. /**
  3258. * Returns the header section of this grid. The default header contains a
  3259. * single row, set as the {@linkplain #setDefaultHeaderRow(HeaderRow)
  3260. * default row}.
  3261. *
  3262. * @return the header section
  3263. */
  3264. protected Header getHeader() {
  3265. return header;
  3266. }
  3267. /**
  3268. * Returns the footer row at the given index.
  3269. *
  3270. * @param index
  3271. * the index of the row, where the topmost row has index zero
  3272. * @return the footer row at the index
  3273. * @throws IndexOutOfBoundsException
  3274. * if {@code rowIndex < 0 || rowIndex >= getFooterRowCount()}
  3275. */
  3276. public FooterRow getFooterRow(int index) {
  3277. return getFooter().getRow(index);
  3278. }
  3279. /**
  3280. * Gets the number of rows in the footer section.
  3281. *
  3282. * @return the number of footer rows
  3283. */
  3284. public int getFooterRowCount() {
  3285. return getFooter().getRowCount();
  3286. }
  3287. /**
  3288. * Inserts a new row at the given position to the footer section. Shifts the
  3289. * row currently at that position and any subsequent rows down (adds one to
  3290. * their indices). Inserting at {@link #getFooterRowCount()} appends the row
  3291. * at the bottom of the footer.
  3292. *
  3293. * @param index
  3294. * the index at which to insert the row, where the topmost row
  3295. * has index zero
  3296. * @return the inserted footer row
  3297. *
  3298. * @throws IndexOutOfBoundsException
  3299. * if {@code rowIndex < 0 || rowIndex > getFooterRowCount()}
  3300. *
  3301. * @see #appendFooterRow()
  3302. * @see #prependFooterRow()
  3303. * @see #removeFooterRow(FooterRow)
  3304. * @see #removeFooterRow(int)
  3305. */
  3306. public FooterRow addFooterRowAt(int index) {
  3307. return getFooter().addRowAt(index);
  3308. }
  3309. /**
  3310. * Adds a new row at the bottom of the footer section.
  3311. *
  3312. * @return the appended footer row
  3313. *
  3314. * @see #prependFooterRow()
  3315. * @see #addFooterRowAt(int)
  3316. * @see #removeFooterRow(FooterRow)
  3317. * @see #removeFooterRow(int)
  3318. */
  3319. public FooterRow appendFooterRow() {
  3320. return addFooterRowAt(getFooterRowCount());
  3321. }
  3322. /**
  3323. * Adds a new row at the top of the footer section.
  3324. *
  3325. * @return the prepended footer row
  3326. *
  3327. * @see #appendFooterRow()
  3328. * @see #addFooterRowAt(int)
  3329. * @see #removeFooterRow(FooterRow)
  3330. * @see #removeFooterRow(int)
  3331. */
  3332. public FooterRow prependFooterRow() {
  3333. return addFooterRowAt(0);
  3334. }
  3335. /**
  3336. * Removes the given row from the footer section. Removing a default row
  3337. * sets the Grid to have no default row.
  3338. *
  3339. * @param row
  3340. * the footer row to be removed, not null
  3341. *
  3342. * @throws IllegalArgumentException
  3343. * if the footer does not contain the row
  3344. *
  3345. * @see #removeFooterRow(int)
  3346. * @see #addFooterRowAt(int)
  3347. * @see #appendFooterRow()
  3348. * @see #prependFooterRow()
  3349. */
  3350. public void removeFooterRow(FooterRow row) {
  3351. getFooter().removeRow(row);
  3352. }
  3353. /**
  3354. * Removes the row at the given position from the footer section.
  3355. *
  3356. * @param index
  3357. * the index of the row to remove, where the topmost row has
  3358. * index zero
  3359. *
  3360. * @throws IndexOutOfBoundsException
  3361. * if {@code index < 0 || index >= getFooterRowCount()}
  3362. *
  3363. * @see #removeFooterRow(FooterRow)
  3364. * @see #addFooterRowAt(int)
  3365. * @see #appendFooterRow()
  3366. * @see #prependFooterRow()
  3367. */
  3368. public void removeFooterRow(int index) {
  3369. getFooter().removeRow(index);
  3370. }
  3371. /**
  3372. * Sets the visibility of the Footer in this Grid.
  3373. *
  3374. * @param footerVisible
  3375. * {@code true} if visible; {@code false} if not
  3376. *
  3377. * @since 8.1.1
  3378. */
  3379. public void setFooterVisible(boolean footerVisible) {
  3380. getFooter().setVisible(footerVisible);
  3381. }
  3382. /**
  3383. * Gets the visibility of the Footer in this Grid.
  3384. *
  3385. * @return {@code true} if visible; {@code false} if not
  3386. *
  3387. * @since 8.1.1
  3388. */
  3389. public boolean isFooterVisible() {
  3390. return getFooter().isVisible();
  3391. }
  3392. /**
  3393. * Returns the footer section of this grid.
  3394. *
  3395. * @return the footer section
  3396. */
  3397. protected Footer getFooter() {
  3398. return footer;
  3399. }
  3400. /**
  3401. * Registers a new column reorder listener.
  3402. *
  3403. * @param listener
  3404. * the listener to register, not null
  3405. * @return a registration for the listener
  3406. */
  3407. public Registration addColumnReorderListener(
  3408. ColumnReorderListener listener) {
  3409. return addListener(ColumnReorderEvent.class, listener,
  3410. COLUMN_REORDER_METHOD);
  3411. }
  3412. /**
  3413. * Registers a new column resize listener.
  3414. *
  3415. * @param listener
  3416. * the listener to register, not null
  3417. * @return a registration for the listener
  3418. */
  3419. public Registration addColumnResizeListener(ColumnResizeListener listener) {
  3420. return addListener(ColumnResizeEvent.class, listener,
  3421. COLUMN_RESIZE_METHOD);
  3422. }
  3423. /**
  3424. * Adds an item click listener. The listener is called when an item of this
  3425. * {@code Grid} is clicked.
  3426. *
  3427. * @param listener
  3428. * the item click listener, not null
  3429. * @return a registration for the listener
  3430. * @see #addContextClickListener
  3431. */
  3432. public Registration addItemClickListener(
  3433. ItemClickListener<? super T> listener) {
  3434. return addListener(GridConstants.ITEM_CLICK_EVENT_ID, ItemClick.class,
  3435. listener, ITEM_CLICK_METHOD);
  3436. }
  3437. /**
  3438. * Adds a context click listener that gets notified when a context click
  3439. * happens.
  3440. *
  3441. * @param listener
  3442. * the context click listener to add, not null actual event
  3443. * provided to the listener is {@link GridContextClickEvent}
  3444. * @return a registration object for removing the listener
  3445. *
  3446. * @since 8.1
  3447. * @see #addItemClickListener
  3448. * @see Registration
  3449. */
  3450. @Override
  3451. public Registration addContextClickListener(
  3452. ContextClickEvent.ContextClickListener listener) {
  3453. return super.addContextClickListener(listener);
  3454. }
  3455. /**
  3456. * Registers a new column visibility change listener.
  3457. *
  3458. * @param listener
  3459. * the listener to register, not null
  3460. * @return a registration for the listener
  3461. */
  3462. public Registration addColumnVisibilityChangeListener(
  3463. ColumnVisibilityChangeListener listener) {
  3464. return addListener(ColumnVisibilityChangeEvent.class, listener,
  3465. COLUMN_VISIBILITY_METHOD);
  3466. }
  3467. /**
  3468. * Returns whether column reordering is allowed. Default value is
  3469. * <code>false</code>.
  3470. *
  3471. * @return true if reordering is allowed
  3472. */
  3473. public boolean isColumnReorderingAllowed() {
  3474. return getState(false).columnReorderingAllowed;
  3475. }
  3476. /**
  3477. * Sets whether or not column reordering is allowed. Default value is
  3478. * <code>false</code>.
  3479. *
  3480. * @param columnReorderingAllowed
  3481. * specifies whether column reordering is allowed
  3482. */
  3483. public void setColumnReorderingAllowed(boolean columnReorderingAllowed) {
  3484. if (isColumnReorderingAllowed() != columnReorderingAllowed) {
  3485. getState().columnReorderingAllowed = columnReorderingAllowed;
  3486. }
  3487. }
  3488. /**
  3489. * Sets the columns and their order based on their column ids. Columns
  3490. * currently in this grid that are not present in the list of column ids are
  3491. * removed. This includes any column that has no id. Similarly, any new
  3492. * column in columns will be added to this grid. New columns can only be
  3493. * added for a <code>Grid</code> created using {@link Grid#Grid(Class)} or
  3494. * {@link #withPropertySet(PropertySet)}.
  3495. *
  3496. *
  3497. * @param columnIds
  3498. * the column ids to set
  3499. *
  3500. * @see Column#setId(String)
  3501. */
  3502. public void setColumns(String... columnIds) {
  3503. // Must extract to an explicitly typed variable because otherwise javac
  3504. // cannot determine which overload of setColumnOrder to use
  3505. Column<T, ?>[] newColumnOrder = Stream.of(columnIds)
  3506. .map((Function<String, Column<T, ?>>) id -> {
  3507. Column<T, ?> column = getColumn(id);
  3508. if (column == null) {
  3509. column = addColumn(id);
  3510. }
  3511. return column;
  3512. }).toArray(Column[]::new);
  3513. setColumnOrder(newColumnOrder);
  3514. // The columns to remove are now at the end of the column list
  3515. getColumns().stream().skip(columnIds.length)
  3516. .forEach(this::removeColumn);
  3517. }
  3518. private String getGeneratedIdentifier() {
  3519. String columnId = "" + counter;
  3520. counter++;
  3521. return columnId;
  3522. }
  3523. /**
  3524. * Sets a new column order for the grid. All columns which are not ordered
  3525. * here will remain in the order they were before as the last columns of
  3526. * grid.
  3527. *
  3528. * @param columns
  3529. * the columns in the order they should be
  3530. */
  3531. public void setColumnOrder(Column<T, ?>... columns) {
  3532. setColumnOrder(Stream.of(columns));
  3533. }
  3534. private void setColumnOrder(Stream<Column<T, ?>> columns) {
  3535. List<String> columnOrder = new ArrayList<>();
  3536. columns.forEach(column -> {
  3537. if (columnSet.contains(column)) {
  3538. columnOrder.add(column.getInternalId());
  3539. } else {
  3540. throw new IllegalStateException(
  3541. "setColumnOrder should not be called "
  3542. + "with columns that are not in the grid.");
  3543. }
  3544. });
  3545. List<String> stateColumnOrder = getState().columnOrder;
  3546. if (stateColumnOrder.size() != columnOrder.size()) {
  3547. stateColumnOrder.removeAll(columnOrder);
  3548. columnOrder.addAll(stateColumnOrder);
  3549. }
  3550. getState().columnOrder = columnOrder;
  3551. fireColumnReorderEvent(false);
  3552. }
  3553. /**
  3554. * Sets a new column order for the grid based on their column ids. All
  3555. * columns which are not ordered here will remain in the order they were
  3556. * before as the last columns of grid.
  3557. *
  3558. * @param columnIds
  3559. * the column ids in the order they should be
  3560. *
  3561. * @see Column#setId(String)
  3562. */
  3563. public void setColumnOrder(String... columnIds) {
  3564. setColumnOrder(Stream.of(columnIds).map(this::getColumnOrThrow));
  3565. }
  3566. /**
  3567. * Returns the selection model for this grid.
  3568. *
  3569. * @return the selection model, not null
  3570. */
  3571. public GridSelectionModel<T> getSelectionModel() {
  3572. assert selectionModel != null : "No selection model set by "
  3573. + getClass().getName() + " constructor";
  3574. return selectionModel;
  3575. }
  3576. /**
  3577. * Use this grid as a single select in {@link Binder}.
  3578. * <p>
  3579. * Throws {@link IllegalStateException} if the grid is not using a
  3580. * {@link SingleSelectionModel}.
  3581. *
  3582. * @return the single select wrapper that can be used in binder
  3583. * @throws IllegalStateException
  3584. * if not using a single selection model
  3585. */
  3586. public GridSingleSelect<T> asSingleSelect() {
  3587. return new GridSingleSelect<>(this);
  3588. }
  3589. public Editor<T> getEditor() {
  3590. return editor;
  3591. }
  3592. /**
  3593. * User this grid as a multiselect in {@link Binder}.
  3594. * <p>
  3595. * Throws {@link IllegalStateException} if the grid is not using a
  3596. * {@link MultiSelectionModel}.
  3597. *
  3598. * @return the multiselect wrapper that can be used in binder
  3599. * @throws IllegalStateException
  3600. * if not using a multiselection model
  3601. */
  3602. public GridMultiSelect<T> asMultiSelect() {
  3603. return new GridMultiSelect<>(this);
  3604. }
  3605. /**
  3606. * Sets the selection model for the grid.
  3607. * <p>
  3608. * This method is for setting a custom selection model, and is
  3609. * {@code protected} because {@link #setSelectionMode(SelectionMode)} should
  3610. * be used for easy switching between built-in selection models.
  3611. * <p>
  3612. * The default selection model is {@link SingleSelectionModelImpl}.
  3613. * <p>
  3614. * To use a custom selection model, you can e.g. extend the grid call this
  3615. * method with your custom selection model.
  3616. *
  3617. * @param model
  3618. * the selection model to use, not {@code null}
  3619. *
  3620. * @see #setSelectionMode(SelectionMode)
  3621. */
  3622. @SuppressWarnings("unchecked")
  3623. protected void setSelectionModel(GridSelectionModel<T> model) {
  3624. Objects.requireNonNull(model, "selection model cannot be null");
  3625. if (selectionModel != null) { // null when called from constructor
  3626. selectionModel.remove();
  3627. }
  3628. selectionModel = model;
  3629. if (selectionModel instanceof AbstractListingExtension) {
  3630. ((AbstractListingExtension<T>) selectionModel).extend(this);
  3631. } else {
  3632. addExtension(selectionModel);
  3633. }
  3634. }
  3635. /**
  3636. * Sets the grid's selection mode.
  3637. * <p>
  3638. * The built-in selection models are:
  3639. * <ul>
  3640. * <li>{@link SelectionMode#SINGLE} -> {@link SingleSelectionModelImpl},
  3641. * <b>the default model</b></li>
  3642. * <li>{@link SelectionMode#MULTI} -> {@link MultiSelectionModelImpl}, with
  3643. * checkboxes in the first column for selection</li>
  3644. * <li>{@link SelectionMode#NONE} -> {@link NoSelectionModel}, preventing
  3645. * selection</li>
  3646. * </ul>
  3647. * <p>
  3648. * To use your custom selection model, you can use
  3649. * {@link #setSelectionModel(GridSelectionModel)}, see existing selection
  3650. * model implementations for example.
  3651. *
  3652. * @param selectionMode
  3653. * the selection mode to switch to, not {@code null}
  3654. * @return the used selection model
  3655. *
  3656. * @see SelectionMode
  3657. * @see GridSelectionModel
  3658. * @see #setSelectionModel(GridSelectionModel)
  3659. */
  3660. public GridSelectionModel<T> setSelectionMode(SelectionMode selectionMode) {
  3661. Objects.requireNonNull(selectionMode, "Selection mode cannot be null.");
  3662. GridSelectionModel<T> model = selectionMode.createModel();
  3663. setSelectionModel(model);
  3664. return model;
  3665. }
  3666. /**
  3667. * This method is a shorthand that delegates to the currently set selection
  3668. * model.
  3669. *
  3670. * @see #getSelectionModel()
  3671. * @see GridSelectionModel
  3672. */
  3673. public Set<T> getSelectedItems() {
  3674. return getSelectionModel().getSelectedItems();
  3675. }
  3676. /**
  3677. * This method is a shorthand that delegates to the currently set selection
  3678. * model.
  3679. *
  3680. * @see #getSelectionModel()
  3681. * @see GridSelectionModel
  3682. */
  3683. public void select(T item) {
  3684. getSelectionModel().select(item);
  3685. }
  3686. /**
  3687. * This method is a shorthand that delegates to the currently set selection
  3688. * model.
  3689. *
  3690. * @see #getSelectionModel()
  3691. * @see GridSelectionModel
  3692. */
  3693. public void deselect(T item) {
  3694. getSelectionModel().deselect(item);
  3695. }
  3696. /**
  3697. * This method is a shorthand that delegates to the currently set selection
  3698. * model.
  3699. *
  3700. * @see #getSelectionModel()
  3701. * @see GridSelectionModel
  3702. */
  3703. public void deselectAll() {
  3704. getSelectionModel().deselectAll();
  3705. }
  3706. /**
  3707. * Adds a selection listener to the current selection model.
  3708. * <p>
  3709. * <em>NOTE:</em> If selection mode is switched with
  3710. * {@link #setSelectionMode(SelectionMode)}, then this listener is not
  3711. * triggered anymore when selection changes!
  3712. * <p>
  3713. * This is a shorthand for
  3714. * {@code grid.getSelectionModel().addSelectionListener()}. To get more
  3715. * detailed selection events, use {@link #getSelectionModel()} and either
  3716. * {@link SingleSelectionModel#addSingleSelectionListener(SingleSelectionListener)}
  3717. * or
  3718. * {@link MultiSelectionModel#addMultiSelectionListener(MultiSelectionListener)}
  3719. * depending on the used selection mode.
  3720. *
  3721. * @param listener
  3722. * the listener to add
  3723. * @return a registration handle to remove the listener
  3724. * @throws UnsupportedOperationException
  3725. * if selection has been disabled with
  3726. * {@link SelectionMode#NONE}
  3727. */
  3728. public Registration addSelectionListener(SelectionListener<T> listener)
  3729. throws UnsupportedOperationException {
  3730. return getSelectionModel().addSelectionListener(listener);
  3731. }
  3732. /**
  3733. * Sort this Grid in ascending order by a specified column.
  3734. *
  3735. * @param column
  3736. * a column to sort against
  3737. *
  3738. */
  3739. public void sort(Column<T, ?> column) {
  3740. sort(column, SortDirection.ASCENDING);
  3741. }
  3742. /**
  3743. * Sort this Grid in user-specified direction by a column.
  3744. *
  3745. * @param column
  3746. * a column to sort against
  3747. * @param direction
  3748. * a sort order value (ascending/descending)
  3749. *
  3750. */
  3751. public void sort(Column<T, ?> column, SortDirection direction) {
  3752. setSortOrder(Collections
  3753. .singletonList(new GridSortOrder<>(column, direction)));
  3754. }
  3755. /**
  3756. * Sort this Grid in ascending order by a specified column defined by id.
  3757. *
  3758. * @param columnId
  3759. * the id of the column to sort against
  3760. *
  3761. * @see Column#setId(String)
  3762. */
  3763. public void sort(String columnId) {
  3764. sort(columnId, SortDirection.ASCENDING);
  3765. }
  3766. /**
  3767. * Sort this Grid in a user-specified direction by a column defined by id.
  3768. *
  3769. * @param columnId
  3770. * the id of the column to sort against
  3771. * @param direction
  3772. * a sort order value (ascending/descending)
  3773. *
  3774. * @see Column#setId(String)
  3775. */
  3776. public void sort(String columnId, SortDirection direction) {
  3777. sort(getColumnOrThrow(columnId), direction);
  3778. }
  3779. /**
  3780. * Clear the current sort order, and re-sort the grid.
  3781. */
  3782. public void clearSortOrder() {
  3783. setSortOrder(Collections.emptyList());
  3784. }
  3785. /**
  3786. * Sets the sort order to use.
  3787. *
  3788. * @param order
  3789. * a sort order list.
  3790. *
  3791. * @throws IllegalArgumentException
  3792. * if order is null
  3793. */
  3794. public void setSortOrder(List<GridSortOrder<T>> order) {
  3795. setSortOrder(order, false);
  3796. }
  3797. /**
  3798. * Sets the sort order to use, given a {@link GridSortOrderBuilder}.
  3799. * Shorthand for {@code setSortOrder(builder.build())}.
  3800. *
  3801. * @see GridSortOrderBuilder
  3802. *
  3803. * @param builder
  3804. * the sort builder to retrieve the sort order from
  3805. * @throws NullPointerException
  3806. * if builder is null
  3807. */
  3808. public void setSortOrder(GridSortOrderBuilder<T> builder) {
  3809. Objects.requireNonNull(builder, "Sort builder cannot be null");
  3810. setSortOrder(builder.build());
  3811. }
  3812. /**
  3813. * Adds a sort order change listener that gets notified when the sort order
  3814. * changes.
  3815. *
  3816. * @param listener
  3817. * the sort order change listener to add
  3818. */
  3819. @Override
  3820. public Registration addSortListener(
  3821. SortListener<GridSortOrder<T>> listener) {
  3822. return addListener(SortEvent.class, listener, SORT_ORDER_CHANGE_METHOD);
  3823. }
  3824. /**
  3825. * Get the current sort order list.
  3826. *
  3827. * @return a sort order list
  3828. */
  3829. public List<GridSortOrder<T>> getSortOrder() {
  3830. return Collections.unmodifiableList(sortOrder);
  3831. }
  3832. /**
  3833. * Scrolls to a certain item, using {@link ScrollDestination#ANY}.
  3834. * <p>
  3835. * If the item has an open details row, its size will also be taken into
  3836. * account.
  3837. *
  3838. * @param row
  3839. * zero based index of the item to scroll to in the current view.
  3840. * @throws IllegalArgumentException
  3841. * if the provided row is outside the item range
  3842. */
  3843. public void scrollTo(int row) throws IllegalArgumentException {
  3844. scrollTo(row, ScrollDestination.ANY);
  3845. }
  3846. /**
  3847. * Scrolls to a certain item, using user-specified scroll destination.
  3848. * <p>
  3849. * If the item has an open details row, its size will also be taken into
  3850. * account.
  3851. *
  3852. * @param row
  3853. * zero based index of the item to scroll to in the current view.
  3854. * @param destination
  3855. * value specifying desired position of scrolled-to row, not
  3856. * {@code null}
  3857. * @throws IllegalArgumentException
  3858. * if the provided row is outside the item range
  3859. */
  3860. public void scrollTo(int row, ScrollDestination destination) {
  3861. Objects.requireNonNull(destination,
  3862. "ScrollDestination can not be null");
  3863. if (row > getDataCommunicator().getDataProviderSize()) {
  3864. throw new IllegalArgumentException("Row outside dataProvider size");
  3865. }
  3866. getRpcProxy(GridClientRpc.class).scrollToRow(row, destination);
  3867. }
  3868. /**
  3869. * Scrolls to the beginning of the first data row.
  3870. */
  3871. public void scrollToStart() {
  3872. getRpcProxy(GridClientRpc.class).scrollToStart();
  3873. }
  3874. /**
  3875. * Scrolls to the end of the last data row.
  3876. */
  3877. public void scrollToEnd() {
  3878. getRpcProxy(GridClientRpc.class).scrollToEnd();
  3879. }
  3880. @Override
  3881. protected GridState getState() {
  3882. return getState(true);
  3883. }
  3884. @Override
  3885. protected GridState getState(boolean markAsDirty) {
  3886. return (GridState) super.getState(markAsDirty);
  3887. }
  3888. /**
  3889. * Sets the column resize mode to use. The default mode is
  3890. * {@link ColumnResizeMode#ANIMATED}.
  3891. *
  3892. * @param mode
  3893. * a ColumnResizeMode value
  3894. * @since 7.7.5
  3895. */
  3896. public void setColumnResizeMode(ColumnResizeMode mode) {
  3897. getState().columnResizeMode = mode;
  3898. }
  3899. /**
  3900. * Returns the current column resize mode. The default mode is
  3901. * {@link ColumnResizeMode#ANIMATED}.
  3902. *
  3903. * @return a ColumnResizeMode value
  3904. * @since 7.7.5
  3905. */
  3906. public ColumnResizeMode getColumnResizeMode() {
  3907. return getState(false).columnResizeMode;
  3908. }
  3909. /**
  3910. * Creates a new Editor instance. Can be overridden to create a custom
  3911. * Editor. If the Editor is a {@link AbstractGridExtension}, it will be
  3912. * automatically added to {@link DataCommunicator}.
  3913. *
  3914. * @return editor
  3915. */
  3916. protected Editor<T> createEditor() {
  3917. return new EditorImpl<>(propertySet);
  3918. }
  3919. private void addExtensionComponent(Component c) {
  3920. if (extensionComponents.add(c)) {
  3921. c.setParent(this);
  3922. markAsDirty();
  3923. }
  3924. }
  3925. private void removeExtensionComponent(Component c) {
  3926. if (extensionComponents.remove(c)) {
  3927. c.setParent(null);
  3928. markAsDirty();
  3929. }
  3930. }
  3931. private void fireColumnReorderEvent(boolean userOriginated) {
  3932. fireEvent(new ColumnReorderEvent(this, userOriginated));
  3933. }
  3934. private void fireColumnResizeEvent(Column<?, ?> column,
  3935. boolean userOriginated) {
  3936. fireEvent(new ColumnResizeEvent(this, column, userOriginated));
  3937. }
  3938. @Override
  3939. protected void readItems(Element design, DesignContext context) {
  3940. // Grid handles reading of items in Grid#readData
  3941. }
  3942. @Override
  3943. public DataProvider<T, ?> getDataProvider() {
  3944. return internalGetDataProvider();
  3945. }
  3946. @Override
  3947. public void setDataProvider(DataProvider<T, ?> dataProvider) {
  3948. internalSetDataProvider(dataProvider);
  3949. }
  3950. /**
  3951. * Sets a CallbackDataProvider using the given fetch items callback and a
  3952. * size callback.
  3953. * <p>
  3954. * This method is a shorthand for making a {@link CallbackDataProvider} that
  3955. * handles a partial {@link Query} object.
  3956. *
  3957. * @param fetchItems
  3958. * a callback for fetching items
  3959. * @param sizeCallback
  3960. * a callback for getting the count of items
  3961. *
  3962. * @see CallbackDataProvider
  3963. * @see #setDataProvider(DataProvider)
  3964. */
  3965. public void setDataProvider(FetchItemsCallback<T> fetchItems,
  3966. SerializableSupplier<Integer> sizeCallback) {
  3967. internalSetDataProvider(
  3968. new CallbackDataProvider<>(
  3969. q -> fetchItems.fetchItems(q.getSortOrders(),
  3970. q.getOffset(), q.getLimit()),
  3971. q -> sizeCallback.get()));
  3972. }
  3973. @Override
  3974. protected void doReadDesign(Element design, DesignContext context) {
  3975. Attributes attrs = design.attributes();
  3976. if (design.hasAttr(DECLARATIVE_DATA_ITEM_TYPE)) {
  3977. String itemType = design.attr(DECLARATIVE_DATA_ITEM_TYPE);
  3978. setBeanType(itemType);
  3979. }
  3980. if (attrs.hasKey("selection-mode")) {
  3981. setSelectionMode(DesignAttributeHandler.readAttribute(
  3982. "selection-mode", attrs, SelectionMode.class));
  3983. }
  3984. Attributes attr = design.attributes();
  3985. if (attr.hasKey("selection-allowed")) {
  3986. setReadOnly(DesignAttributeHandler
  3987. .readAttribute("selection-allowed", attr, Boolean.class));
  3988. }
  3989. if (attrs.hasKey("rows")) {
  3990. setHeightByRows(DesignAttributeHandler.readAttribute("rows", attrs,
  3991. double.class));
  3992. }
  3993. readStructure(design, context);
  3994. // Read frozen columns after columns are read.
  3995. if (attrs.hasKey("frozen-columns")) {
  3996. setFrozenColumnCount(DesignAttributeHandler
  3997. .readAttribute("frozen-columns", attrs, int.class));
  3998. }
  3999. }
  4000. /**
  4001. * Sets the bean type to use for property mapping.
  4002. * <p>
  4003. * This method is responsible also for setting or updating the property set
  4004. * so that it matches the given bean type.
  4005. * <p>
  4006. * Protected mostly for Designer needs, typically should not be overridden
  4007. * or even called.
  4008. *
  4009. * @param beanTypeClassName
  4010. * the fully qualified class name of the bean type
  4011. *
  4012. * @since 8.0.3
  4013. */
  4014. @SuppressWarnings("unchecked")
  4015. protected void setBeanType(String beanTypeClassName) {
  4016. setBeanType((Class<T>) resolveClass(beanTypeClassName));
  4017. }
  4018. /**
  4019. * Sets the bean type to use for property mapping.
  4020. * <p>
  4021. * This method is responsible also for setting or updating the property set
  4022. * so that it matches the given bean type.
  4023. * <p>
  4024. * Protected mostly for Designer needs, typically should not be overridden
  4025. * or even called.
  4026. *
  4027. * @param beanType
  4028. * the bean type class
  4029. *
  4030. * @since 8.0.3
  4031. */
  4032. protected void setBeanType(Class<T> beanType) {
  4033. this.beanType = beanType;
  4034. setPropertySet(BeanPropertySet.get(beanType));
  4035. }
  4036. private Class<?> resolveClass(String qualifiedClassName) {
  4037. try {
  4038. Class<?> resolvedClass = Class.forName(qualifiedClassName, true,
  4039. VaadinServiceClassLoaderUtil.findDefaultClassLoader());
  4040. return resolvedClass;
  4041. } catch (ClassNotFoundException | SecurityException e) {
  4042. throw new IllegalArgumentException(
  4043. "Unable to find class " + qualifiedClassName, e);
  4044. }
  4045. }
  4046. @Override
  4047. protected void doWriteDesign(Element design, DesignContext designContext) {
  4048. Attributes attr = design.attributes();
  4049. if (this.beanType != null) {
  4050. design.attr(DECLARATIVE_DATA_ITEM_TYPE,
  4051. this.beanType.getCanonicalName());
  4052. }
  4053. DesignAttributeHandler.writeAttribute("selection-allowed", attr,
  4054. isReadOnly(), false, Boolean.class, designContext);
  4055. Attributes attrs = design.attributes();
  4056. Grid<?> defaultInstance = designContext.getDefaultInstance(this);
  4057. DesignAttributeHandler.writeAttribute("frozen-columns", attrs,
  4058. getFrozenColumnCount(), defaultInstance.getFrozenColumnCount(),
  4059. int.class, designContext);
  4060. if (HeightMode.ROW.equals(getHeightMode())) {
  4061. DesignAttributeHandler.writeAttribute("rows", attrs,
  4062. getHeightByRows(), defaultInstance.getHeightByRows(),
  4063. double.class, designContext);
  4064. }
  4065. SelectionMode mode = getSelectionMode();
  4066. if (mode != null) {
  4067. DesignAttributeHandler.writeAttribute("selection-mode", attrs, mode,
  4068. SelectionMode.SINGLE, SelectionMode.class, designContext);
  4069. }
  4070. writeStructure(design, designContext);
  4071. }
  4072. @Override
  4073. protected T deserializeDeclarativeRepresentation(String item) {
  4074. if (item == null) {
  4075. return super.deserializeDeclarativeRepresentation(
  4076. UUID.randomUUID().toString());
  4077. }
  4078. return super.deserializeDeclarativeRepresentation(new String(item));
  4079. }
  4080. @Override
  4081. protected boolean isReadOnly() {
  4082. SelectionMode selectionMode = getSelectionMode();
  4083. if (SelectionMode.SINGLE.equals(selectionMode)) {
  4084. return asSingleSelect().isReadOnly();
  4085. }
  4086. if (SelectionMode.MULTI.equals(selectionMode)) {
  4087. return asMultiSelect().isReadOnly();
  4088. }
  4089. return false;
  4090. }
  4091. @Override
  4092. protected void setReadOnly(boolean readOnly) {
  4093. SelectionMode selectionMode = getSelectionMode();
  4094. if (SelectionMode.SINGLE.equals(selectionMode)) {
  4095. asSingleSelect().setReadOnly(readOnly);
  4096. } else if (SelectionMode.MULTI.equals(selectionMode)) {
  4097. asMultiSelect().setReadOnly(readOnly);
  4098. }
  4099. }
  4100. private void readStructure(Element design, DesignContext context) {
  4101. if (design.children().isEmpty()) {
  4102. return;
  4103. }
  4104. if (design.children().size() > 1
  4105. || !design.child(0).tagName().equals("table")) {
  4106. throw new DesignException(
  4107. "Grid needs to have a table element as its only child");
  4108. }
  4109. Element table = design.child(0);
  4110. Elements colgroups = table.getElementsByTag("colgroup");
  4111. if (colgroups.size() != 1) {
  4112. throw new DesignException(
  4113. "Table element in declarative Grid needs to have a"
  4114. + " colgroup defining the columns used in Grid");
  4115. }
  4116. List<DeclarativeValueProvider<T>> providers = new ArrayList<>();
  4117. for (Element col : colgroups.get(0).getElementsByTag("col")) {
  4118. String id = DesignAttributeHandler.readAttribute("column-id",
  4119. col.attributes(), null, String.class);
  4120. // If there is a property with a matching name available,
  4121. // map to that
  4122. Optional<PropertyDefinition<T, ?>> property = propertySet
  4123. .getProperties().filter(p -> p.getName().equals(id))
  4124. .findFirst();
  4125. Column<T, ?> column;
  4126. if (property.isPresent()) {
  4127. column = addColumn(id);
  4128. } else {
  4129. DeclarativeValueProvider<T> provider = new DeclarativeValueProvider<>();
  4130. column = createColumn(provider, ValueProvider.identity(),
  4131. new HtmlRenderer());
  4132. addColumn(getGeneratedIdentifier(), column);
  4133. if (id != null) {
  4134. column.setId(id);
  4135. }
  4136. providers.add(provider);
  4137. }
  4138. column.readDesign(col, context);
  4139. }
  4140. for (Element child : table.children()) {
  4141. if (child.tagName().equals("thead")) {
  4142. getHeader().readDesign(child, context);
  4143. } else if (child.tagName().equals("tbody")) {
  4144. readData(child, providers);
  4145. } else if (child.tagName().equals("tfoot")) {
  4146. getFooter().readDesign(child, context);
  4147. }
  4148. }
  4149. // Sync default header captions to column captions
  4150. if (getDefaultHeaderRow() != null) {
  4151. for (Column<T, ?> c : getColumns()) {
  4152. HeaderCell headerCell = getDefaultHeaderRow().getCell(c);
  4153. if (headerCell.getCellType() == GridStaticCellType.TEXT) {
  4154. c.setCaption(headerCell.getText());
  4155. }
  4156. }
  4157. }
  4158. }
  4159. /**
  4160. * Reads the declarative representation of a grid's data from the given
  4161. * element and stores it in the given {@link DeclarativeValueProvider}s.
  4162. * Each member in the list of value providers corresponds to a column in the
  4163. * grid.
  4164. *
  4165. * @since 8.1
  4166. *
  4167. * @param body
  4168. * the element to read data from
  4169. * @param providers
  4170. * list of {@link DeclarativeValueProvider}s to store the data of
  4171. * each column to
  4172. */
  4173. protected void readData(Element body,
  4174. List<DeclarativeValueProvider<T>> providers) {
  4175. getSelectionModel().deselectAll();
  4176. List<T> items = new ArrayList<>();
  4177. List<T> selectedItems = new ArrayList<>();
  4178. for (Element row : body.children()) {
  4179. T item = deserializeDeclarativeRepresentation(row.attr("item"));
  4180. items.add(item);
  4181. if (row.hasAttr("selected")) {
  4182. selectedItems.add(item);
  4183. }
  4184. Elements cells = row.children();
  4185. int i = 0;
  4186. for (Element cell : cells) {
  4187. providers.get(i).addValue(item, cell.html());
  4188. i++;
  4189. }
  4190. }
  4191. setItems(items);
  4192. selectedItems.forEach(getSelectionModel()::select);
  4193. }
  4194. private void writeStructure(Element design, DesignContext designContext) {
  4195. if (getColumns().isEmpty()) {
  4196. return;
  4197. }
  4198. Element tableElement = design.appendElement("table");
  4199. Element colGroup = tableElement.appendElement("colgroup");
  4200. getColumns().forEach(column -> column
  4201. .writeDesign(colGroup.appendElement("col"), designContext));
  4202. // Always write thead. Reads correctly when there no header rows
  4203. getHeader().writeDesign(tableElement.appendElement("thead"),
  4204. designContext);
  4205. if (designContext.shouldWriteData(this)) {
  4206. Element bodyElement = tableElement.appendElement("tbody");
  4207. writeData(bodyElement, designContext);
  4208. }
  4209. if (getFooter().getRowCount() > 0) {
  4210. getFooter().writeDesign(tableElement.appendElement("tfoot"),
  4211. designContext);
  4212. }
  4213. }
  4214. /**
  4215. * Writes the data contained in this grid. Used when serializing a grid to
  4216. * its declarative representation, if
  4217. * {@link DesignContext#shouldWriteData(Component)} returns {@code true} for
  4218. * the grid that is being written.
  4219. *
  4220. * @since 8.1
  4221. *
  4222. * @param body
  4223. * the body element to write the declarative representation of
  4224. * data to
  4225. * @param designContext
  4226. * the design context
  4227. *
  4228. * @since 8.1
  4229. */
  4230. protected void writeData(Element body, DesignContext designContext) {
  4231. getDataProvider().fetch(new Query<>())
  4232. .forEach(item -> writeRow(body, item, designContext));
  4233. }
  4234. private void writeRow(Element container, T item, DesignContext context) {
  4235. Element tableRow = container.appendElement("tr");
  4236. tableRow.attr("item", serializeDeclarativeRepresentation(item));
  4237. if (getSelectionModel().isSelected(item)) {
  4238. tableRow.attr("selected", true);
  4239. }
  4240. for (Column<T, ?> column : getColumns()) {
  4241. Object value = column.valueProvider.apply(item);
  4242. tableRow.appendElement("td")
  4243. .append(Optional.ofNullable(value).map(Object::toString)
  4244. .map(DesignFormatter::encodeForTextNode)
  4245. .orElse(""));
  4246. }
  4247. }
  4248. private SelectionMode getSelectionMode() {
  4249. GridSelectionModel<T> selectionModel = getSelectionModel();
  4250. SelectionMode mode = null;
  4251. if (selectionModel.getClass().equals(SingleSelectionModelImpl.class)) {
  4252. mode = SelectionMode.SINGLE;
  4253. } else if (selectionModel.getClass()
  4254. .equals(MultiSelectionModelImpl.class)) {
  4255. mode = SelectionMode.MULTI;
  4256. } else if (selectionModel.getClass().equals(NoSelectionModel.class)) {
  4257. mode = SelectionMode.NONE;
  4258. }
  4259. return mode;
  4260. }
  4261. /**
  4262. * Sets a user-defined identifier for given column.
  4263. *
  4264. * @see Column#setId(String)
  4265. *
  4266. * @param column
  4267. * the column
  4268. * @param id
  4269. * the user-defined identifier
  4270. */
  4271. protected void setColumnId(String id, Column<T, ?> column) {
  4272. if (columnIds.containsKey(id)) {
  4273. throw new IllegalArgumentException("Duplicate ID for columns");
  4274. }
  4275. columnIds.put(id, column);
  4276. }
  4277. @Override
  4278. protected Collection<String> getCustomAttributes() {
  4279. Collection<String> result = super.getCustomAttributes();
  4280. // "rename" for frozen column count
  4281. result.add("frozen-column-count");
  4282. result.add("frozen-columns");
  4283. // "rename" for height-mode
  4284. result.add("height-by-rows");
  4285. result.add("rows");
  4286. // add a selection-mode attribute
  4287. result.add("selection-mode");
  4288. return result;
  4289. }
  4290. /**
  4291. * Returns a column identified by its internal id. This id should not be
  4292. * confused with the user-defined identifier.
  4293. *
  4294. * @param columnId
  4295. * the internal id of column
  4296. * @return column identified by internal id
  4297. */
  4298. protected Column<T, ?> getColumnByInternalId(String columnId) {
  4299. return columnKeys.get(columnId);
  4300. }
  4301. /**
  4302. * Returns the internal id for given column. This id should not be confused
  4303. * with the user-defined identifier.
  4304. *
  4305. * @param column
  4306. * the column
  4307. * @return internal id of given column
  4308. */
  4309. protected String getInternalIdForColumn(Column<T, ?> column) {
  4310. return column.getInternalId();
  4311. }
  4312. private void setSortOrder(List<GridSortOrder<T>> order,
  4313. boolean userOriginated) {
  4314. Objects.requireNonNull(order, "Sort order list cannot be null");
  4315. // Update client state to display sort order.
  4316. List<String> sortColumns = new ArrayList<>();
  4317. List<SortDirection> directions = new ArrayList<>();
  4318. order.stream().forEach(sortOrder -> {
  4319. sortColumns.add(sortOrder.getSorted().getInternalId());
  4320. directions.add(sortOrder.getDirection());
  4321. });
  4322. getState().sortColumns = sortColumns.toArray(new String[0]);
  4323. getState().sortDirs = directions.toArray(new SortDirection[0]);
  4324. sortOrder.clear();
  4325. sortOrder.addAll(order);
  4326. sort(userOriginated);
  4327. }
  4328. private void sort(boolean userOriginated) {
  4329. // Set sort orders
  4330. // In-memory comparator
  4331. getDataCommunicator().setInMemorySorting(createSortingComparator());
  4332. // Back-end sort properties
  4333. List<QuerySortOrder> sortProperties = new ArrayList<>();
  4334. sortOrder.stream().map(
  4335. order -> order.getSorted().getSortOrder(order.getDirection()))
  4336. .forEach(s -> s.forEach(sortProperties::add));
  4337. getDataCommunicator().setBackEndSorting(sortProperties);
  4338. // Close grid editor if it's open.
  4339. if (getEditor().isOpen()) {
  4340. getEditor().cancel();
  4341. }
  4342. fireEvent(new SortEvent<>(this, new ArrayList<>(sortOrder),
  4343. userOriginated));
  4344. }
  4345. /**
  4346. * Creates a comparator for grid to sort rows.
  4347. *
  4348. * @return the comparator based on column sorting information.
  4349. */
  4350. protected SerializableComparator<T> createSortingComparator() {
  4351. /*
  4352. * thenComparing is defined to return a serializable comparator as long
  4353. * as both original comparators are also serializable
  4354. */
  4355. BinaryOperator<SerializableComparator<T>> operator = (comparator1,
  4356. comparator2) -> comparator1.thenComparing(comparator2)::compare;
  4357. return sortOrder.stream().map(
  4358. order -> order.getSorted().getComparator(order.getDirection()))
  4359. .reduce((x, y) -> 0, operator);
  4360. }
  4361. @Override
  4362. protected void internalSetDataProvider(DataProvider<T, ?> dataProvider) {
  4363. super.internalSetDataProvider(dataProvider);
  4364. for (Column<T, ?> column : getColumns()) {
  4365. column.updateSortable();
  4366. }
  4367. }
  4368. }