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 163KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783
  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. * @param cellStyleGenerator
  1256. * the cell style generator to set, not null
  1257. * @return this column
  1258. * @throws NullPointerException
  1259. * if {@code cellStyleGenerator} is {@code null}
  1260. */
  1261. public Column<T, V> setStyleGenerator(
  1262. StyleGenerator<T> cellStyleGenerator) {
  1263. Objects.requireNonNull(cellStyleGenerator,
  1264. "Cell style generator must not be null");
  1265. this.styleGenerator = cellStyleGenerator;
  1266. getGrid().getDataCommunicator().reset();
  1267. return this;
  1268. }
  1269. /**
  1270. * Gets the style generator that is used for generating styles for
  1271. * cells.
  1272. *
  1273. * @return the cell style generator
  1274. */
  1275. public StyleGenerator<T> getStyleGenerator() {
  1276. return styleGenerator;
  1277. }
  1278. /**
  1279. * Sets the description generator that is used for generating
  1280. * descriptions for cells in this column. This method uses the
  1281. * {@link ContentMode#PREFORMATTED} content mode.
  1282. *
  1283. * @see #setDescriptionGenerator(DescriptionGenerator, ContentMode)
  1284. *
  1285. * @param cellDescriptionGenerator
  1286. * the cell description generator to set, or {@code null} to
  1287. * remove a previously set generator
  1288. * @return this column
  1289. */
  1290. public Column<T, V> setDescriptionGenerator(
  1291. DescriptionGenerator<T> cellDescriptionGenerator) {
  1292. return setDescriptionGenerator(cellDescriptionGenerator,
  1293. ContentMode.PREFORMATTED);
  1294. }
  1295. /**
  1296. * Sets the description generator that is used for generating
  1297. * descriptions for cells in this column. This method uses the given
  1298. * content mode.
  1299. *
  1300. * @see #setDescriptionGenerator(DescriptionGenerator)
  1301. *
  1302. * @param cellDescriptionGenerator
  1303. * the cell description generator to set, or {@code null} to
  1304. * remove a previously set generator
  1305. * @param tooltipContentMode
  1306. * the content mode for tooltips
  1307. * @return this column
  1308. *
  1309. * @since 8.2
  1310. */
  1311. public Column<T, V> setDescriptionGenerator(
  1312. DescriptionGenerator<T> cellDescriptionGenerator,
  1313. ContentMode tooltipContentMode) {
  1314. this.descriptionGenerator = cellDescriptionGenerator;
  1315. getState().tooltipContentMode = tooltipContentMode;
  1316. getGrid().getDataCommunicator().reset();
  1317. return this;
  1318. }
  1319. /**
  1320. * Gets the description generator that is used for generating
  1321. * descriptions for cells.
  1322. *
  1323. * @return the cell description generator, or <code>null</code> if no
  1324. * generator is set
  1325. */
  1326. public DescriptionGenerator<T> getDescriptionGenerator() {
  1327. return descriptionGenerator;
  1328. }
  1329. /**
  1330. * Sets the ratio with which the column expands.
  1331. * <p>
  1332. * By default, all columns expand equally (treated as if all of them had
  1333. * an expand ratio of 1). Once at least one column gets a defined expand
  1334. * ratio, the implicit expand ratio is removed, and only the defined
  1335. * expand ratios are taken into account.
  1336. * <p>
  1337. * If a column has a defined width ({@link #setWidth(double)}), it
  1338. * overrides this method's effects.
  1339. * <p>
  1340. * <em>Example:</em> A grid with three columns, with expand ratios 0, 1
  1341. * and 2, respectively. The column with a <strong>ratio of 0 is exactly
  1342. * as wide as its contents requires</strong>. The column with a ratio of
  1343. * 1 is as wide as it needs, <strong>plus a third of any excess
  1344. * space</strong>, because we have 3 parts total, and this column
  1345. * reserves only one of those. The column with a ratio of 2, is as wide
  1346. * as it needs to be, <strong>plus two thirds</strong> of the excess
  1347. * width.
  1348. *
  1349. * @param expandRatio
  1350. * the expand ratio of this column. {@code 0} to not have it
  1351. * expand at all. A negative number to clear the expand
  1352. * value.
  1353. * @throws IllegalStateException
  1354. * if the column is no longer attached to any grid
  1355. * @see #setWidth(double)
  1356. */
  1357. public Column<T, V> setExpandRatio(int expandRatio)
  1358. throws IllegalStateException {
  1359. checkColumnIsAttached();
  1360. if (expandRatio != getExpandRatio()) {
  1361. getState().expandRatio = expandRatio;
  1362. getGrid().markAsDirty();
  1363. }
  1364. return this;
  1365. }
  1366. /**
  1367. * Returns the column's expand ratio.
  1368. *
  1369. * @return the column's expand ratio
  1370. * @see #setExpandRatio(int)
  1371. */
  1372. public int getExpandRatio() {
  1373. return getState(false).expandRatio;
  1374. }
  1375. /**
  1376. * Clears the expand ratio for this column.
  1377. * <p>
  1378. * Equal to calling {@link #setExpandRatio(int) setExpandRatio(-1)}
  1379. *
  1380. * @throws IllegalStateException
  1381. * if the column is no longer attached to any grid
  1382. */
  1383. public Column<T, V> clearExpandRatio() throws IllegalStateException {
  1384. return setExpandRatio(-1);
  1385. }
  1386. /**
  1387. * Returns the width (in pixels). By default a column is 100px wide.
  1388. *
  1389. * @return the width in pixels of the column
  1390. * @throws IllegalStateException
  1391. * if the column is no longer attached to any grid
  1392. */
  1393. public double getWidth() throws IllegalStateException {
  1394. checkColumnIsAttached();
  1395. return getState(false).width;
  1396. }
  1397. /**
  1398. * Sets the width (in pixels).
  1399. * <p>
  1400. * This overrides any configuration set by any of
  1401. * {@link #setExpandRatio(int)}, {@link #setMinimumWidth(double)} or
  1402. * {@link #setMaximumWidth(double)}.
  1403. *
  1404. * @param pixelWidth
  1405. * the new pixel width of the column
  1406. * @return the column itself
  1407. *
  1408. * @throws IllegalStateException
  1409. * if the column is no longer attached to any grid
  1410. * @throws IllegalArgumentException
  1411. * thrown if pixel width is less than zero
  1412. */
  1413. public Column<T, V> setWidth(double pixelWidth)
  1414. throws IllegalStateException, IllegalArgumentException {
  1415. checkColumnIsAttached();
  1416. if (pixelWidth < 0) {
  1417. throw new IllegalArgumentException(
  1418. "Pixel width should be greated than 0 (in " + toString()
  1419. + ")");
  1420. }
  1421. if (pixelWidth != getWidth()) {
  1422. getState().width = pixelWidth;
  1423. getGrid().markAsDirty();
  1424. getGrid().fireColumnResizeEvent(this, false);
  1425. }
  1426. return this;
  1427. }
  1428. /**
  1429. * Returns whether this column has an undefined width.
  1430. *
  1431. * @since 7.6
  1432. * @return whether the width is undefined
  1433. * @throws IllegalStateException
  1434. * if the column is no longer attached to any grid
  1435. */
  1436. public boolean isWidthUndefined() {
  1437. checkColumnIsAttached();
  1438. return getState(false).width < 0;
  1439. }
  1440. /**
  1441. * Marks the column width as undefined. An undefined width means the
  1442. * grid is free to resize the column based on the cell contents and
  1443. * available space in the grid.
  1444. *
  1445. * @return the column itself
  1446. */
  1447. public Column<T, V> setWidthUndefined() {
  1448. checkColumnIsAttached();
  1449. if (!isWidthUndefined()) {
  1450. getState().width = -1;
  1451. getGrid().markAsDirty();
  1452. getGrid().fireColumnResizeEvent(this, false);
  1453. }
  1454. return this;
  1455. }
  1456. /**
  1457. * Sets the minimum width for this column.
  1458. * <p>
  1459. * This defines the minimum guaranteed pixel width of the column
  1460. * <em>when it is set to expand</em>.
  1461. *
  1462. * @param pixels
  1463. * the minimum width for the column
  1464. * @throws IllegalStateException
  1465. * if the column is no longer attached to any grid
  1466. * @see #setExpandRatio(int)
  1467. * @return the column itself
  1468. */
  1469. public Column<T, V> setMinimumWidth(double pixels)
  1470. throws IllegalStateException {
  1471. checkColumnIsAttached();
  1472. final double maxwidth = getMaximumWidth();
  1473. if (pixels >= 0 && pixels > maxwidth && maxwidth >= 0) {
  1474. throw new IllegalArgumentException("New minimum width ("
  1475. + pixels + ") was greater than maximum width ("
  1476. + maxwidth + ")");
  1477. }
  1478. getState().minWidth = pixels;
  1479. getGrid().markAsDirty();
  1480. return this;
  1481. }
  1482. /**
  1483. * Return the minimum width for this column.
  1484. *
  1485. * @return the minimum width for this column
  1486. * @see #setMinimumWidth(double)
  1487. */
  1488. public double getMinimumWidth() {
  1489. return getState(false).minWidth;
  1490. }
  1491. /**
  1492. * Sets whether the width of the contents in the column should be
  1493. * considered minimum width for this column.
  1494. * <p>
  1495. * If this is set to <code>true</code> (default for backwards
  1496. * compatibility), then a column will not shrink to smaller than the
  1497. * width required to show the contents available when calculating the
  1498. * widths (only the widths of the initially rendered rows are
  1499. * considered).
  1500. * <p>
  1501. * If this is set to <code>false</code> and the column has been set to
  1502. * expand using #setExpandRatio(int), then the contents of the column
  1503. * will be ignored when calculating the width, and the column will thus
  1504. * shrink down to the minimum width defined by #setMinimumWidth(double)
  1505. * if necessary.
  1506. *
  1507. * @param minimumWidthFromContent
  1508. * <code>true</code> to reserve space for all contents,
  1509. * <code>false</code> to allow the column to shrink smaller
  1510. * than the contents
  1511. * @return the column itself
  1512. * @throws IllegalStateException
  1513. * if the column is no longer attached to any grid
  1514. * @see #setMinimumWidth(double)
  1515. * @since 8.1
  1516. */
  1517. public Column<T, V> setMinimumWidthFromContent(
  1518. boolean minimumWidthFromContent) throws IllegalStateException {
  1519. checkColumnIsAttached();
  1520. if (isMinimumWidthFromContent() != minimumWidthFromContent) {
  1521. getState().minimumWidthFromContent = minimumWidthFromContent;
  1522. getGrid().markAsDirty();
  1523. }
  1524. return this;
  1525. }
  1526. /**
  1527. * Gets whether the width of the contents in the column should be
  1528. * considered minimum width for this column.
  1529. *
  1530. * @return <code>true</code> to reserve space for all contents,
  1531. * <code>false</code> to allow the column to shrink smaller than
  1532. * the contents
  1533. * @see #setMinimumWidthFromContent(boolean)
  1534. * @since 8.1
  1535. */
  1536. public boolean isMinimumWidthFromContent() {
  1537. return getState(false).minimumWidthFromContent;
  1538. }
  1539. /**
  1540. * Sets the maximum width for this column.
  1541. * <p>
  1542. * This defines the maximum allowed pixel width of the column <em>when
  1543. * it is set to expand</em>.
  1544. *
  1545. * @param pixels
  1546. * the maximum width
  1547. * @throws IllegalStateException
  1548. * if the column is no longer attached to any grid
  1549. * @see #setExpandRatio(int)
  1550. */
  1551. public Column<T, V> setMaximumWidth(double pixels) {
  1552. checkColumnIsAttached();
  1553. final double minwidth = getMinimumWidth();
  1554. if (pixels >= 0 && pixels < minwidth && minwidth >= 0) {
  1555. throw new IllegalArgumentException("New maximum width ("
  1556. + pixels + ") was less than minimum width (" + minwidth
  1557. + ")");
  1558. }
  1559. getState().maxWidth = pixels;
  1560. getGrid().markAsDirty();
  1561. return this;
  1562. }
  1563. /**
  1564. * Returns the maximum width for this column.
  1565. *
  1566. * @return the maximum width for this column
  1567. * @see #setMaximumWidth(double)
  1568. */
  1569. public double getMaximumWidth() {
  1570. return getState(false).maxWidth;
  1571. }
  1572. /**
  1573. * Sets whether this column can be resized by the user.
  1574. *
  1575. * @since 7.6
  1576. * @param resizable
  1577. * {@code true} if this column should be resizable,
  1578. * {@code false} otherwise
  1579. * @throws IllegalStateException
  1580. * if the column is no longer attached to any grid
  1581. */
  1582. public Column<T, V> setResizable(boolean resizable) {
  1583. checkColumnIsAttached();
  1584. if (resizable != isResizable()) {
  1585. getState().resizable = resizable;
  1586. getGrid().markAsDirty();
  1587. }
  1588. return this;
  1589. }
  1590. /**
  1591. * Gets the caption of the hiding toggle for this column.
  1592. *
  1593. * @since 7.5.0
  1594. * @see #setHidingToggleCaption(String)
  1595. * @return the caption for the hiding toggle for this column
  1596. */
  1597. public String getHidingToggleCaption() {
  1598. return getState(false).hidingToggleCaption;
  1599. }
  1600. /**
  1601. * Sets the caption of the hiding toggle for this column. Shown in the
  1602. * toggle for this column in the grid's sidebar when the column is
  1603. * {@link #isHidable() hidable}.
  1604. * <p>
  1605. * The default value is <code>null</code>, and in that case the column's
  1606. * {@link #getCaption() header caption} is used.
  1607. * <p>
  1608. * <em>NOTE:</em> setting this to empty string might cause the hiding
  1609. * toggle to not render correctly.
  1610. *
  1611. * @since 7.5.0
  1612. * @param hidingToggleCaption
  1613. * the text to show in the column hiding toggle
  1614. * @return the column itself
  1615. */
  1616. public Column<T, V> setHidingToggleCaption(String hidingToggleCaption) {
  1617. if (hidingToggleCaption != getHidingToggleCaption()) {
  1618. getState().hidingToggleCaption = hidingToggleCaption;
  1619. }
  1620. return this;
  1621. }
  1622. /**
  1623. * Hides or shows the column. By default columns are visible before
  1624. * explicitly hiding them.
  1625. *
  1626. * @since 7.5.0
  1627. * @param hidden
  1628. * <code>true</code> to hide the column, <code>false</code>
  1629. * to show
  1630. * @return this column
  1631. * @throws IllegalStateException
  1632. * if the column is no longer attached to any grid
  1633. */
  1634. public Column<T, V> setHidden(boolean hidden) {
  1635. checkColumnIsAttached();
  1636. if (hidden != isHidden()) {
  1637. getState().hidden = hidden;
  1638. getGrid().fireColumnVisibilityChangeEvent(this, hidden, false);
  1639. }
  1640. return this;
  1641. }
  1642. /**
  1643. * Returns whether this column is hidden. Default is {@code false}.
  1644. *
  1645. * @since 7.5.0
  1646. * @return <code>true</code> if the column is currently hidden,
  1647. * <code>false</code> otherwise
  1648. */
  1649. public boolean isHidden() {
  1650. return getState(false).hidden;
  1651. }
  1652. /**
  1653. * Sets whether this column can be hidden by the user. Hidable columns
  1654. * can be hidden and shown via the sidebar menu.
  1655. *
  1656. * @since 7.5.0
  1657. * @param hidable
  1658. * <code>true</code> if the column may be hidable by the user
  1659. * via UI interaction
  1660. * @return this column
  1661. */
  1662. public Column<T, V> setHidable(boolean hidable) {
  1663. if (hidable != isHidable()) {
  1664. getState().hidable = hidable;
  1665. }
  1666. return this;
  1667. }
  1668. /**
  1669. * Returns whether this column can be hidden by the user. Default is
  1670. * {@code false}.
  1671. * <p>
  1672. * <em>Note:</em> the column can be programmatically hidden using
  1673. * {@link #setHidden(boolean)} regardless of the returned value.
  1674. *
  1675. * @since 7.5.0
  1676. * @return <code>true</code> if the user can hide the column,
  1677. * <code>false</code> if not
  1678. */
  1679. public boolean isHidable() {
  1680. return getState(false).hidable;
  1681. }
  1682. /**
  1683. * Returns whether this column can be resized by the user. Default is
  1684. * {@code true}.
  1685. * <p>
  1686. * <em>Note:</em> the column can be programmatically resized using
  1687. * {@link #setWidth(double)} and {@link #setWidthUndefined()} regardless
  1688. * of the returned value.
  1689. *
  1690. * @since 7.6
  1691. * @return {@code true} if this column is resizable, {@code false}
  1692. * otherwise
  1693. */
  1694. public boolean isResizable() {
  1695. return getState(false).resizable;
  1696. }
  1697. /**
  1698. * Sets whether this Column has a component displayed in Editor or not.
  1699. * A column can only be editable if an editor component or binding has
  1700. * been set.
  1701. *
  1702. * @param editable
  1703. * {@code true} if column is editable; {@code false} if not
  1704. * @return this column
  1705. *
  1706. * @see #setEditorComponent(HasValue, Setter)
  1707. * @see #setEditorBinding(Binding)
  1708. */
  1709. public Column<T, V> setEditable(boolean editable) {
  1710. Objects.requireNonNull(editorBinding,
  1711. "Column has no editor binding or component defined");
  1712. getState().editable = editable;
  1713. return this;
  1714. }
  1715. /**
  1716. * Gets whether this Column has a component displayed in Editor or not.
  1717. *
  1718. * @return {@code true} if the column displays an editor component;
  1719. * {@code false} if not
  1720. */
  1721. public boolean isEditable() {
  1722. return getState(false).editable;
  1723. }
  1724. /**
  1725. * Sets an editor binding for this column. The {@link Binding} is used
  1726. * when a row is in editor mode to define how to populate an editor
  1727. * component based on the edited row and how to update an item based on
  1728. * the value in the editor component.
  1729. * <p>
  1730. * To create a binding to use with a column, define a binding for the
  1731. * editor binder (<code>grid.getEditor().getBinder()</code>) using e.g.
  1732. * {@link Binder#forField(HasValue)}. You can also use
  1733. * {@link #setEditorComponent(HasValue, Setter)} if no validator or
  1734. * converter is needed for the binding.
  1735. * <p>
  1736. * The {@link HasValue} that the binding is defined to use must be a
  1737. * {@link Component}.
  1738. *
  1739. * @param binding
  1740. * the binding to use for this column
  1741. * @return this column
  1742. *
  1743. * @see #setEditorComponent(HasValue, Setter)
  1744. * @see Binding
  1745. * @see Grid#getEditor()
  1746. * @see Editor#getBinder()
  1747. */
  1748. public Column<T, V> setEditorBinding(Binding<T, ?> binding) {
  1749. Objects.requireNonNull(binding, "null is not a valid editor field");
  1750. if (!(binding.getField() instanceof Component)) {
  1751. throw new IllegalArgumentException(
  1752. "Binding target must be a component.");
  1753. }
  1754. this.editorBinding = binding;
  1755. return setEditable(true);
  1756. }
  1757. /**
  1758. * Gets the binder binding that is currently used for this column.
  1759. *
  1760. * @return the used binder binding, or <code>null</code> if no binding
  1761. * is configured
  1762. *
  1763. * @see #setEditorBinding(Binding)
  1764. */
  1765. public Binding<T, ?> getEditorBinding() {
  1766. return editorBinding;
  1767. }
  1768. /**
  1769. * Sets a component and setter to use for editing values of this column
  1770. * in the editor row. This is a shorthand for use in simple cases where
  1771. * no validator or converter is needed. Use
  1772. * {@link #setEditorBinding(Binding)} to support more complex cases.
  1773. * <p>
  1774. * <strong>Note:</strong> The same component cannot be used for multiple
  1775. * columns.
  1776. *
  1777. * @param editorComponent
  1778. * the editor component
  1779. * @param setter
  1780. * a setter that stores the component value in the row item
  1781. * @return this column
  1782. *
  1783. * @see #setEditorBinding(Binding)
  1784. * @see Grid#getEditor()
  1785. * @see Binder#bind(HasValue, ValueProvider, Setter)
  1786. */
  1787. public <C extends HasValue<V> & Component> Column<T, V> setEditorComponent(
  1788. C editorComponent, Setter<T, V> setter) {
  1789. Objects.requireNonNull(editorComponent,
  1790. "Editor component cannot be null");
  1791. Objects.requireNonNull(setter, "Setter cannot be null");
  1792. Binding<T, V> binding = getGrid().getEditor().getBinder()
  1793. .bind(editorComponent, valueProvider::apply, setter);
  1794. return setEditorBinding(binding);
  1795. }
  1796. /**
  1797. * Sets a component to use for editing values of this columns in the
  1798. * editor row. This method can only be used if the column has an
  1799. * {@link #setId(String) id} and the {@link Grid} has been created using
  1800. * {@link Grid#Grid(Class)} or some other way that allows finding
  1801. * properties based on property names.
  1802. * <p>
  1803. * This is a shorthand for use in simple cases where no validator or
  1804. * converter is needed. Use {@link #setEditorBinding(Binding)} to
  1805. * support more complex cases.
  1806. * <p>
  1807. * <strong>Note:</strong> The same component cannot be used for multiple
  1808. * columns.
  1809. *
  1810. * @param editorComponent
  1811. * the editor component
  1812. * @return this column
  1813. *
  1814. * @see #setEditorBinding(Binding)
  1815. * @see Grid#getEditor()
  1816. * @see Binder#bind(HasValue, String)
  1817. * @see Grid#Grid(Class)
  1818. */
  1819. public <F, C extends HasValue<F> & Component> Column<T, V> setEditorComponent(
  1820. C editorComponent) {
  1821. Objects.requireNonNull(editorComponent,
  1822. "Editor component cannot be null");
  1823. String propertyName = getId();
  1824. if (propertyName == null) {
  1825. throw new IllegalStateException(
  1826. "setEditorComponent without a setter can only be used if the column has an id. "
  1827. + "Use another setEditorComponent(Component, Setter) or setEditorBinding(Binding) instead.");
  1828. }
  1829. Binding<T, F> binding = getGrid().getEditor().getBinder()
  1830. .bind(editorComponent, propertyName);
  1831. return setEditorBinding(binding);
  1832. }
  1833. /**
  1834. * Sets the Renderer for this Column. Setting the renderer will cause
  1835. * all currently available row data to be recreated and sent to the
  1836. * client.
  1837. *
  1838. * @param renderer
  1839. * the new renderer
  1840. * @return this column
  1841. *
  1842. * @since 8.0.3
  1843. */
  1844. public Column<T, V> setRenderer(Renderer<? super V> renderer) {
  1845. return setRenderer(ValueProvider.identity(), renderer);
  1846. }
  1847. /**
  1848. * Sets the Renderer for this Column. Setting the renderer will cause
  1849. * all currently available row data to be recreated and sent to the
  1850. * client.
  1851. * <p>
  1852. * The presentation provider is a method that takes the value of this
  1853. * column on a single row, and maps that to a value that the renderer
  1854. * accepts. This feature can be used for storing a complex value in a
  1855. * column for editing, but providing a simplified presentation for the
  1856. * user when not editing.
  1857. *
  1858. * @param presentationProvider
  1859. * the function to get presentations from the value of this
  1860. * column, not {@code null}
  1861. * @param renderer
  1862. * the new renderer, not {@code null}
  1863. *
  1864. * @param <P>
  1865. * the presentation type
  1866. *
  1867. * @return this column
  1868. *
  1869. * @since 8.1
  1870. */
  1871. public <P> Column<T, V> setRenderer(
  1872. ValueProvider<V, P> presentationProvider,
  1873. Renderer<? super P> renderer) {
  1874. Objects.requireNonNull(renderer, "Renderer can not be null");
  1875. Objects.requireNonNull(presentationProvider,
  1876. "Presentation provider can not be null");
  1877. // Remove old renderer
  1878. Connector oldRenderer = getState().renderer;
  1879. if (oldRenderer instanceof Extension) {
  1880. removeExtension((Extension) oldRenderer);
  1881. }
  1882. // Set new renderer
  1883. getState().renderer = renderer;
  1884. addExtension(renderer);
  1885. this.presentationProvider = presentationProvider;
  1886. // Trigger redraw
  1887. getGrid().getDataCommunicator().reset();
  1888. return this;
  1889. }
  1890. /**
  1891. * Gets the Renderer for this Column.
  1892. *
  1893. * @return the renderer
  1894. * @since 8.1
  1895. */
  1896. public Renderer<?> getRenderer() {
  1897. return (Renderer<?>) getState().renderer;
  1898. }
  1899. /**
  1900. * Sets whether Grid should handle events in this Column from Components
  1901. * and Widgets rendered by certain Renderers. By default the events are
  1902. * not handled.
  1903. * <p>
  1904. * <strong>Note:</strong> Enabling this feature will for example select
  1905. * a row when a component is clicked. For example in the case of a
  1906. * {@link ComboBox} or {@link TextField} it might be problematic as the
  1907. * component gets re-rendered and might lose focus.
  1908. *
  1909. * @param handleWidgetEvents
  1910. * {@code true} to handle events; {@code false} to not
  1911. * @return this column
  1912. * @since 8.3
  1913. */
  1914. public Column<T, V> setHandleWidgetEvents(boolean handleWidgetEvents) {
  1915. getState().handleWidgetEvents = handleWidgetEvents;
  1916. return this;
  1917. }
  1918. /**
  1919. * Gets whether Grid is handling the events in this Column from
  1920. * Component and Widgets.
  1921. *
  1922. * @see #setHandleWidgetEvents(boolean)
  1923. *
  1924. * @return {@code true} if handling events; {@code false} if not
  1925. * @since 8.3
  1926. */
  1927. public boolean isHandleWidgetEvents() {
  1928. return getState(false).handleWidgetEvents;
  1929. }
  1930. /**
  1931. * Gets the grid that this column belongs to.
  1932. *
  1933. * @return the grid that this column belongs to, or <code>null</code> if
  1934. * this column has not yet been associated with any grid
  1935. */
  1936. @SuppressWarnings("unchecked")
  1937. protected Grid<T> getGrid() {
  1938. return (Grid<T>) getParent();
  1939. }
  1940. /**
  1941. * Checks if column is attached and throws an
  1942. * {@link IllegalStateException} if it is not.
  1943. *
  1944. * @throws IllegalStateException
  1945. * if the column is no longer attached to any grid
  1946. */
  1947. protected void checkColumnIsAttached() throws IllegalStateException {
  1948. if (getGrid() == null) {
  1949. throw new IllegalStateException(
  1950. "Column is no longer attached to a grid.");
  1951. }
  1952. }
  1953. /**
  1954. * Writes the design attributes for this column into given element.
  1955. *
  1956. * @since 7.5.0
  1957. *
  1958. * @param element
  1959. * Element to write attributes into
  1960. *
  1961. * @param designContext
  1962. * the design context
  1963. */
  1964. protected void writeDesign(Element element,
  1965. DesignContext designContext) {
  1966. Attributes attributes = element.attributes();
  1967. ColumnState defaultState = new ColumnState();
  1968. if (getId() == null) {
  1969. setId("column" + getGrid().getColumns().indexOf(this));
  1970. }
  1971. DesignAttributeHandler.writeAttribute("column-id", attributes,
  1972. getId(), null, String.class, designContext);
  1973. // Sortable is a special attribute that depends on the data
  1974. // provider.
  1975. DesignAttributeHandler.writeAttribute("sortable", attributes,
  1976. isSortable(), null, boolean.class, designContext);
  1977. DesignAttributeHandler.writeAttribute("editable", attributes,
  1978. isEditable(), defaultState.editable, boolean.class,
  1979. designContext);
  1980. DesignAttributeHandler.writeAttribute("resizable", attributes,
  1981. isResizable(), defaultState.resizable, boolean.class,
  1982. designContext);
  1983. DesignAttributeHandler.writeAttribute("hidable", attributes,
  1984. isHidable(), defaultState.hidable, boolean.class,
  1985. designContext);
  1986. DesignAttributeHandler.writeAttribute("hidden", attributes,
  1987. isHidden(), defaultState.hidden, boolean.class,
  1988. designContext);
  1989. DesignAttributeHandler.writeAttribute("hiding-toggle-caption",
  1990. attributes, getHidingToggleCaption(),
  1991. defaultState.hidingToggleCaption, String.class,
  1992. designContext);
  1993. DesignAttributeHandler.writeAttribute("width", attributes,
  1994. getWidth(), defaultState.width, Double.class,
  1995. designContext);
  1996. DesignAttributeHandler.writeAttribute("min-width", attributes,
  1997. getMinimumWidth(), defaultState.minWidth, Double.class,
  1998. designContext);
  1999. DesignAttributeHandler.writeAttribute("max-width", attributes,
  2000. getMaximumWidth(), defaultState.maxWidth, Double.class,
  2001. designContext);
  2002. DesignAttributeHandler.writeAttribute("expand", attributes,
  2003. getExpandRatio(), defaultState.expandRatio, Integer.class,
  2004. designContext);
  2005. }
  2006. /**
  2007. * Reads the design attributes for this column from given element.
  2008. *
  2009. * @since 7.5.0
  2010. * @param design
  2011. * Element to read attributes from
  2012. * @param designContext
  2013. * the design context
  2014. */
  2015. @SuppressWarnings("unchecked")
  2016. protected void readDesign(Element design, DesignContext designContext) {
  2017. Attributes attributes = design.attributes();
  2018. if (design.hasAttr("sortable")) {
  2019. setSortable(DesignAttributeHandler.readAttribute("sortable",
  2020. attributes, boolean.class));
  2021. } else {
  2022. setSortable(false);
  2023. }
  2024. if (design.hasAttr("editable")) {
  2025. /**
  2026. * This is a fake editor just to have something (otherwise
  2027. * "setEditable" throws an exception.
  2028. *
  2029. * Let's use TextField here because we support only Strings as
  2030. * inline data type. It will work incorrectly for other types
  2031. * but we don't support them anyway.
  2032. */
  2033. setEditorComponent((HasValue<V> & Component) new TextField(),
  2034. (item, value) -> {
  2035. // Ignore user value since we don't know the setter
  2036. });
  2037. setEditable(DesignAttributeHandler.readAttribute("editable",
  2038. attributes, boolean.class));
  2039. }
  2040. if (design.hasAttr("resizable")) {
  2041. setResizable(DesignAttributeHandler.readAttribute("resizable",
  2042. attributes, boolean.class));
  2043. }
  2044. if (design.hasAttr("hidable")) {
  2045. setHidable(DesignAttributeHandler.readAttribute("hidable",
  2046. attributes, boolean.class));
  2047. }
  2048. if (design.hasAttr("hidden")) {
  2049. setHidden(DesignAttributeHandler.readAttribute("hidden",
  2050. attributes, boolean.class));
  2051. }
  2052. if (design.hasAttr("hiding-toggle-caption")) {
  2053. setHidingToggleCaption(DesignAttributeHandler.readAttribute(
  2054. "hiding-toggle-caption", attributes, String.class));
  2055. }
  2056. if (design.hasAttr("assistive-caption")) {
  2057. setAssistiveCaption(DesignAttributeHandler.readAttribute(
  2058. "assistive-caption", attributes, String.class));
  2059. }
  2060. // Read size info where necessary.
  2061. if (design.hasAttr("width")) {
  2062. setWidth(DesignAttributeHandler.readAttribute("width",
  2063. attributes, Double.class));
  2064. }
  2065. if (design.hasAttr("min-width")) {
  2066. setMinimumWidth(DesignAttributeHandler
  2067. .readAttribute("min-width", attributes, Double.class));
  2068. }
  2069. if (design.hasAttr("max-width")) {
  2070. setMaximumWidth(DesignAttributeHandler
  2071. .readAttribute("max-width", attributes, Double.class));
  2072. }
  2073. if (design.hasAttr("expand")) {
  2074. if (design.attr("expand").isEmpty()) {
  2075. setExpandRatio(1);
  2076. } else {
  2077. setExpandRatio(DesignAttributeHandler.readAttribute(
  2078. "expand", attributes, Integer.class));
  2079. }
  2080. }
  2081. }
  2082. /**
  2083. * Gets the DataGenerator for this Column.
  2084. *
  2085. * @return data generator
  2086. */
  2087. private DataGenerator<T> getDataGenerator() {
  2088. return dataGenerator;
  2089. }
  2090. }
  2091. private class HeaderImpl extends Header {
  2092. @Override
  2093. protected Grid<T> getGrid() {
  2094. return Grid.this;
  2095. }
  2096. @Override
  2097. protected SectionState getState(boolean markAsDirty) {
  2098. return Grid.this.getState(markAsDirty).header;
  2099. }
  2100. @Override
  2101. protected Column<?, ?> getColumnByInternalId(String internalId) {
  2102. return getGrid().getColumnByInternalId(internalId);
  2103. }
  2104. @Override
  2105. @SuppressWarnings("unchecked")
  2106. protected String getInternalIdForColumn(Column<?, ?> column) {
  2107. return getGrid().getInternalIdForColumn((Column<T, ?>) column);
  2108. }
  2109. };
  2110. private class FooterImpl extends Footer {
  2111. @Override
  2112. protected Grid<T> getGrid() {
  2113. return Grid.this;
  2114. }
  2115. @Override
  2116. protected SectionState getState(boolean markAsDirty) {
  2117. return Grid.this.getState(markAsDirty).footer;
  2118. }
  2119. @Override
  2120. protected Column<?, ?> getColumnByInternalId(String internalId) {
  2121. return getGrid().getColumnByInternalId(internalId);
  2122. }
  2123. @Override
  2124. @SuppressWarnings("unchecked")
  2125. protected String getInternalIdForColumn(Column<?, ?> column) {
  2126. return getGrid().getInternalIdForColumn((Column<T, ?>) column);
  2127. }
  2128. };
  2129. private final Set<Column<T, ?>> columnSet = new LinkedHashSet<>();
  2130. private final Map<String, Column<T, ?>> columnKeys = new HashMap<>();
  2131. private final Map<String, Column<T, ?>> columnIds = new HashMap<>();
  2132. private final List<GridSortOrder<T>> sortOrder = new ArrayList<>();
  2133. private final DetailsManager<T> detailsManager;
  2134. private final Set<Component> extensionComponents = new HashSet<>();
  2135. private StyleGenerator<T> styleGenerator = item -> null;
  2136. private DescriptionGenerator<T> descriptionGenerator;
  2137. private final Header header = new HeaderImpl();
  2138. private final Footer footer = new FooterImpl();
  2139. private int counter = 0;
  2140. private GridSelectionModel<T> selectionModel;
  2141. private Editor<T> editor;
  2142. private PropertySet<T> propertySet;
  2143. private Class<T> beanType = null;
  2144. /**
  2145. * Creates a new grid without support for creating columns based on property
  2146. * names. Use an alternative constructor, such as {@link Grid#Grid(Class)},
  2147. * to create a grid that automatically sets up columns based on the type of
  2148. * presented data.
  2149. *
  2150. * @see #Grid(Class)
  2151. * @see #withPropertySet(PropertySet)
  2152. */
  2153. public Grid() {
  2154. this(new DataCommunicator<>());
  2155. }
  2156. /**
  2157. * Creates a new grid that uses reflection based on the provided bean type
  2158. * to automatically set up an initial set of columns. All columns will be
  2159. * configured using the same {@link Object#toString()} renderer that is used
  2160. * by {@link #addColumn(ValueProvider)}.
  2161. *
  2162. * @param beanType
  2163. * the bean type to use, not <code>null</code>
  2164. * @see #Grid()
  2165. * @see #withPropertySet(PropertySet)
  2166. */
  2167. public Grid(Class<T> beanType) {
  2168. this(beanType, new DataCommunicator<>());
  2169. }
  2170. /**
  2171. * Creates a new grid that uses custom data communicator and provided bean
  2172. * type
  2173. *
  2174. * It uses reflection of the provided bean type to automatically set up an
  2175. * initial set of columns. All columns will be configured using the same
  2176. * {@link Object#toString()} renderer that is used by
  2177. * {@link #addColumn(ValueProvider)}.
  2178. *
  2179. * @param beanType
  2180. * the bean type to use, not <code>null</code>
  2181. * @param dataCommunicator
  2182. * the data communicator to use, not<code>null</code>
  2183. * @since 8.0.7
  2184. */
  2185. protected Grid(Class<T> beanType, DataCommunicator<T> dataCommunicator) {
  2186. this(BeanPropertySet.get(beanType), dataCommunicator);
  2187. this.beanType = beanType;
  2188. }
  2189. /**
  2190. * Creates a new grid with the given data communicator and without support
  2191. * for creating columns based on property names.
  2192. *
  2193. * @param dataCommunicator
  2194. * the custom data communicator to set
  2195. * @see #Grid()
  2196. * @see #Grid(PropertySet, DataCommunicator)
  2197. * @since 8.0.7
  2198. */
  2199. protected Grid(DataCommunicator<T> dataCommunicator) {
  2200. this(new PropertySet<T>() {
  2201. @Override
  2202. public Stream<PropertyDefinition<T, ?>> getProperties() {
  2203. // No columns configured by default
  2204. return Stream.empty();
  2205. }
  2206. @Override
  2207. public Optional<PropertyDefinition<T, ?>> getProperty(String name) {
  2208. throw new IllegalStateException(
  2209. "A Grid created without a bean type class literal or a custom property set"
  2210. + " doesn't support finding properties by name.");
  2211. }
  2212. }, dataCommunicator);
  2213. }
  2214. /**
  2215. * Creates a grid using a custom {@link PropertySet} implementation for
  2216. * configuring the initial columns and resolving property names for
  2217. * {@link #addColumn(String)} and
  2218. * {@link Column#setEditorComponent(HasValue)}.
  2219. *
  2220. * @see #withPropertySet(PropertySet)
  2221. *
  2222. * @param propertySet
  2223. * the property set implementation to use, not <code>null</code>.
  2224. */
  2225. protected Grid(PropertySet<T> propertySet) {
  2226. this(propertySet, new DataCommunicator<>());
  2227. }
  2228. /**
  2229. * Creates a grid using a custom {@link PropertySet} implementation and
  2230. * custom data communicator.
  2231. * <p>
  2232. * Property set is used for configuring the initial columns and resolving
  2233. * property names for {@link #addColumn(String)} and
  2234. * {@link Column#setEditorComponent(HasValue)}.
  2235. *
  2236. * @see #withPropertySet(PropertySet)
  2237. *
  2238. * @param propertySet
  2239. * the property set implementation to use, not <code>null</code>.
  2240. * @param dataCommunicator
  2241. * the data communicator to use, not<code>null</code>
  2242. * @since 8.0.7
  2243. */
  2244. protected Grid(PropertySet<T> propertySet,
  2245. DataCommunicator<T> dataCommunicator) {
  2246. super(dataCommunicator);
  2247. registerRpc(new GridServerRpcImpl());
  2248. setDefaultHeaderRow(appendHeaderRow());
  2249. setSelectionModel(new SingleSelectionModelImpl<>());
  2250. detailsManager = new DetailsManager<>();
  2251. addExtension(detailsManager);
  2252. addDataGenerator(detailsManager);
  2253. addDataGenerator((item, json) -> {
  2254. String styleName = styleGenerator.apply(item);
  2255. if (styleName != null && !styleName.isEmpty()) {
  2256. json.put(GridState.JSONKEY_ROWSTYLE, styleName);
  2257. }
  2258. if (descriptionGenerator != null) {
  2259. String description = descriptionGenerator.apply(item);
  2260. if (description != null && !description.isEmpty()) {
  2261. json.put(GridState.JSONKEY_ROWDESCRIPTION, description);
  2262. }
  2263. }
  2264. });
  2265. setPropertySet(propertySet);
  2266. // Automatically add columns for all available properties
  2267. propertySet.getProperties().map(PropertyDefinition::getName)
  2268. .forEach(this::addColumn);
  2269. }
  2270. @Override
  2271. public void beforeClientResponse(boolean initial) {
  2272. super.beforeClientResponse(initial);
  2273. if (initial && editor.isOpen()) {
  2274. // Re-attaching grid. Any old editor should be closed.
  2275. editor.cancel();
  2276. }
  2277. }
  2278. /**
  2279. * Sets the property set to use for this grid. Does not create or update
  2280. * columns in any way but will delete and re-create the editor.
  2281. * <p>
  2282. * This is only meant to be called from constructors and readDesign, at a
  2283. * stage where it does not matter if you throw away the editor.
  2284. *
  2285. * @param propertySet
  2286. * the property set to use
  2287. *
  2288. * @since 8.0.3
  2289. */
  2290. protected void setPropertySet(PropertySet<T> propertySet) {
  2291. Objects.requireNonNull(propertySet, "propertySet cannot be null");
  2292. this.propertySet = propertySet;
  2293. if (editor instanceof Extension) {
  2294. removeExtension((Extension) editor);
  2295. }
  2296. editor = createEditor();
  2297. if (editor instanceof Extension) {
  2298. addExtension((Extension) editor);
  2299. }
  2300. }
  2301. /**
  2302. * Returns the property set used by this grid.
  2303. *
  2304. * @return propertySet the property set to return
  2305. * @since 8.4
  2306. */
  2307. protected PropertySet<T> getPropertySet() {
  2308. return propertySet;
  2309. }
  2310. /**
  2311. * Creates a grid using a custom {@link PropertySet} implementation for
  2312. * creating a default set of columns and for resolving property names with
  2313. * {@link #addColumn(String)} and
  2314. * {@link Column#setEditorComponent(HasValue)}.
  2315. * <p>
  2316. * This functionality is provided as static method instead of as a public
  2317. * constructor in order to make it possible to use a custom property set
  2318. * without creating a subclass while still leaving the public constructors
  2319. * focused on the common use cases.
  2320. *
  2321. * @see Grid#Grid()
  2322. * @see Grid#Grid(Class)
  2323. *
  2324. * @param propertySet
  2325. * the property set implementation to use, not <code>null</code>.
  2326. * @return a new grid using the provided property set, not <code>null</code>
  2327. */
  2328. public static <BEAN> Grid<BEAN> withPropertySet(
  2329. PropertySet<BEAN> propertySet) {
  2330. return new Grid<>(propertySet);
  2331. }
  2332. /**
  2333. * Creates a new {@code Grid} using the given caption.
  2334. *
  2335. * @param caption
  2336. * the caption of the grid
  2337. */
  2338. public Grid(String caption) {
  2339. this();
  2340. setCaption(caption);
  2341. }
  2342. /**
  2343. * Creates a new {@code Grid} using the given caption and
  2344. * {@code DataProvider}.
  2345. *
  2346. * @param caption
  2347. * the caption of the grid
  2348. * @param dataProvider
  2349. * the data provider, not {@code null}
  2350. */
  2351. public Grid(String caption, DataProvider<T, ?> dataProvider) {
  2352. this(caption);
  2353. setDataProvider(dataProvider);
  2354. }
  2355. /**
  2356. * Creates a new {@code Grid} using the given {@code DataProvider}.
  2357. *
  2358. * @param dataProvider
  2359. * the data provider, not {@code null}
  2360. */
  2361. public Grid(DataProvider<T, ?> dataProvider) {
  2362. this();
  2363. setDataProvider(dataProvider);
  2364. }
  2365. /**
  2366. * Creates a new {@code Grid} using the given caption and collection of
  2367. * items.
  2368. *
  2369. * @param caption
  2370. * the caption of the grid
  2371. * @param items
  2372. * the data items to use, not {@çode null}
  2373. */
  2374. public Grid(String caption, Collection<T> items) {
  2375. this(caption, DataProvider.ofCollection(items));
  2376. }
  2377. /**
  2378. * Gets the bean type used by this grid.
  2379. * <p>
  2380. * The bean type is used to automatically set up a column added using a
  2381. * property name.
  2382. *
  2383. * @return the used bean type or <code>null</code> if no bean type has been
  2384. * defined
  2385. *
  2386. * @since 8.0.3
  2387. */
  2388. public Class<T> getBeanType() {
  2389. return beanType;
  2390. }
  2391. public <V> void fireColumnVisibilityChangeEvent(Column<T, V> column,
  2392. boolean hidden, boolean userOriginated) {
  2393. fireEvent(new ColumnVisibilityChangeEvent(this, column, hidden,
  2394. userOriginated));
  2395. }
  2396. /**
  2397. * Adds a new column with the given property name. The column will use a
  2398. * {@link TextRenderer}. The value is converted to a String using
  2399. * {@link Object#toString()}. The property name will be used as the
  2400. * {@link Column#getId() column id} and the {@link Column#getCaption()
  2401. * column caption} will be set based on the property definition.
  2402. * <p>
  2403. * This method can only be used for a <code>Grid</code> created using
  2404. * {@link Grid#Grid(Class)} or {@link #withPropertySet(PropertySet)}.
  2405. * <p>
  2406. * You can add columns for nested properties with dot notation, eg.
  2407. * <code>"property.nestedProperty"</code>
  2408. *
  2409. * @param propertyName
  2410. * the property name of the new column, not <code>null</code>
  2411. * @return the newly added column, not <code>null</code>
  2412. */
  2413. public Column<T, ?> addColumn(String propertyName) {
  2414. return addColumn(propertyName, new TextRenderer());
  2415. }
  2416. /**
  2417. * Adds a new column with the given property name and renderer. The property
  2418. * name will be used as the {@link Column#getId() column id} and the
  2419. * {@link Column#getCaption() column caption} will be set based on the
  2420. * property definition.
  2421. * <p>
  2422. * This method can only be used for a <code>Grid</code> created using
  2423. * {@link Grid#Grid(Class)} or {@link #withPropertySet(PropertySet)}.
  2424. * <p>
  2425. * You can add columns for nested properties with dot notation, eg.
  2426. * <code>"property.nestedProperty"</code>
  2427. *
  2428. *
  2429. * @param propertyName
  2430. * the property name of the new column, not <code>null</code>
  2431. * @param renderer
  2432. * the renderer to use, not <code>null</code>
  2433. * @return the newly added column, not <code>null</code>
  2434. */
  2435. public Column<T, ?> addColumn(String propertyName,
  2436. AbstractRenderer<? super T, ?> renderer) {
  2437. Objects.requireNonNull(propertyName, "Property name cannot be null");
  2438. Objects.requireNonNull(renderer, "Renderer cannot be null");
  2439. if (getColumn(propertyName) != null) {
  2440. throw new IllegalStateException(
  2441. "There is already a column for " + propertyName);
  2442. }
  2443. PropertyDefinition<T, ?> definition = propertySet
  2444. .getProperty(propertyName)
  2445. .orElseThrow(() -> new IllegalArgumentException(
  2446. "Could not resolve property name " + propertyName
  2447. + " from " + propertySet));
  2448. if (!renderer.getPresentationType()
  2449. .isAssignableFrom(definition.getType())) {
  2450. throw new IllegalArgumentException(
  2451. renderer + " cannot be used with a property of type "
  2452. + definition.getType().getName());
  2453. }
  2454. @SuppressWarnings({ "unchecked", "rawtypes" })
  2455. Column<T, ?> column = addColumn(definition.getGetter(),
  2456. (AbstractRenderer) renderer).setId(definition.getName())
  2457. .setCaption(definition.getCaption());
  2458. return column;
  2459. }
  2460. /**
  2461. * Adds a new text column to this {@link Grid} with a value provider. The
  2462. * column will use a {@link TextRenderer}. The value is converted to a
  2463. * String using {@link Object#toString()}. In-memory sorting will use the
  2464. * natural ordering of elements if they are mutually comparable and
  2465. * otherwise fall back to comparing the string representations of the
  2466. * values.
  2467. *
  2468. * @param valueProvider
  2469. * the value provider
  2470. *
  2471. * @return the new column
  2472. */
  2473. public <V> Column<T, V> addColumn(ValueProvider<T, V> valueProvider) {
  2474. return addColumn(valueProvider, new TextRenderer());
  2475. }
  2476. /**
  2477. * Adds a new column to this {@link Grid} with typed renderer and value
  2478. * provider.
  2479. *
  2480. * @param valueProvider
  2481. * the value provider
  2482. * @param renderer
  2483. * the column value renderer
  2484. * @param <V>
  2485. * the column value type
  2486. *
  2487. * @return the new column
  2488. *
  2489. * @see AbstractRenderer
  2490. */
  2491. public <V> Column<T, V> addColumn(ValueProvider<T, V> valueProvider,
  2492. AbstractRenderer<? super T, ? super V> renderer) {
  2493. return addColumn(valueProvider, ValueProvider.identity(), renderer);
  2494. }
  2495. /**
  2496. * Adds a new column to this {@link Grid} with value provider and
  2497. * presentation provider.
  2498. * <p>
  2499. * <strong>Note:</strong> The presentation type for this method is set to be
  2500. * String. To use any custom renderer with the presentation provider, use
  2501. * {@link #addColumn(ValueProvider, ValueProvider, AbstractRenderer)}.
  2502. *
  2503. * @param valueProvider
  2504. * the value provider
  2505. * @param presentationProvider
  2506. * the value presentation provider
  2507. * @param <V>
  2508. * the column value type
  2509. *
  2510. * @see #addColumn(ValueProvider, ValueProvider, AbstractRenderer)
  2511. *
  2512. * @return the new column
  2513. * @since 8.1
  2514. */
  2515. public <V> Column<T, V> addColumn(ValueProvider<T, V> valueProvider,
  2516. ValueProvider<V, String> presentationProvider) {
  2517. return addColumn(valueProvider, presentationProvider,
  2518. new TextRenderer());
  2519. }
  2520. /**
  2521. * Adds a new column to this {@link Grid} with value provider, presentation
  2522. * provider and typed renderer.
  2523. *
  2524. * <p>
  2525. * The presentation provider is a method that takes the value from the value
  2526. * provider, and maps that to a value that the renderer accepts. This
  2527. * feature can be used for storing a complex value in a column for editing,
  2528. * but providing a simplified presentation for the user when not editing.
  2529. *
  2530. * @param valueProvider
  2531. * the value provider
  2532. * @param presentationProvider
  2533. * the value presentation provider
  2534. * @param renderer
  2535. * the column value renderer
  2536. * @param <V>
  2537. * the column value type
  2538. * @param <P>
  2539. * the column presentation type
  2540. *
  2541. * @return the new column
  2542. *
  2543. * @see AbstractRenderer
  2544. * @since 8.1
  2545. */
  2546. public <V, P> Column<T, V> addColumn(ValueProvider<T, V> valueProvider,
  2547. ValueProvider<V, P> presentationProvider,
  2548. AbstractRenderer<? super T, ? super P> renderer) {
  2549. String generatedIdentifier = getGeneratedIdentifier();
  2550. Column<T, V> column = createColumn(valueProvider, presentationProvider,
  2551. renderer);
  2552. addColumn(generatedIdentifier, column);
  2553. return column;
  2554. }
  2555. /**
  2556. * Adds a column that shows components.
  2557. * <p>
  2558. * This is a shorthand for {@link #addColum()} with a
  2559. * {@link ComponentRenderer}.
  2560. *
  2561. * @param componentProvider
  2562. * a value provider that will return a component for the given
  2563. * item
  2564. * @return the new column
  2565. * @param <V>
  2566. * the column value type, extends component
  2567. * @since 8.1
  2568. */
  2569. public <V extends Component> Column<T, V> addComponentColumn(
  2570. ValueProvider<T, V> componentProvider) {
  2571. return addColumn(componentProvider, new ComponentRenderer());
  2572. }
  2573. /**
  2574. * Creates a column instance from a value provider, presentation provider
  2575. * and a renderer.
  2576. *
  2577. * @param valueProvider
  2578. * the value provider
  2579. * @param presentationProvider
  2580. * the presentation provider
  2581. * @param renderer
  2582. * the renderer
  2583. * @return a new column instance
  2584. * @param <V>
  2585. * the column value type
  2586. * @param <P>
  2587. * the column presentation type
  2588. *
  2589. * @since 8.1
  2590. */
  2591. protected <V, P> Column<T, V> createColumn(
  2592. ValueProvider<T, V> valueProvider,
  2593. ValueProvider<V, P> presentationProvider,
  2594. AbstractRenderer<? super T, ? super P> renderer) {
  2595. return new Column<>(valueProvider, presentationProvider, renderer);
  2596. }
  2597. private void addColumn(String identifier, Column<T, ?> column) {
  2598. if (getColumns().contains(column)) {
  2599. return;
  2600. }
  2601. column.extend(this);
  2602. columnSet.add(column);
  2603. columnKeys.put(identifier, column);
  2604. column.setInternalId(identifier);
  2605. addDataGenerator(column.getDataGenerator());
  2606. getState().columnOrder.add(identifier);
  2607. getHeader().addColumn(identifier);
  2608. getFooter().addColumn(identifier);
  2609. if (getDefaultHeaderRow() != null) {
  2610. getDefaultHeaderRow().getCell(column).setText(column.getCaption());
  2611. }
  2612. column.updateSortable();
  2613. }
  2614. /**
  2615. * Removes the given column from this {@link Grid}.
  2616. *
  2617. * @param column
  2618. * the column to remove
  2619. *
  2620. * @throws IllegalArgumentException
  2621. * if the column is not a valid one
  2622. */
  2623. public void removeColumn(Column<T, ?> column) {
  2624. if (columnSet.remove(column)) {
  2625. String columnId = column.getInternalId();
  2626. int displayIndex = getState(false).columnOrder.indexOf(columnId);
  2627. 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.";
  2628. columnKeys.remove(columnId);
  2629. columnIds.remove(column.getId());
  2630. column.remove();
  2631. removeDataGenerator(column.getDataGenerator());
  2632. getHeader().removeColumn(columnId);
  2633. getFooter().removeColumn(columnId);
  2634. getState(true).columnOrder.remove(columnId);
  2635. // Remove column from sorted columns.
  2636. List<GridSortOrder<T>> filteredSortOrder = sortOrder.stream()
  2637. .filter(order -> !order.getSorted().equals(column))
  2638. .collect(Collectors.toList());
  2639. if (filteredSortOrder.size() < sortOrder.size()) {
  2640. setSortOrder(filteredSortOrder);
  2641. }
  2642. if (displayIndex < getFrozenColumnCount()) {
  2643. setFrozenColumnCount(getFrozenColumnCount() - 1);
  2644. }
  2645. } else {
  2646. throw new IllegalArgumentException("Column with id "
  2647. + column.getId() + " cannot be removed from the grid");
  2648. }
  2649. }
  2650. /**
  2651. * Removes the column with the given column id.
  2652. *
  2653. * @see #removeColumn(Column)
  2654. * @see Column#setId(String)
  2655. *
  2656. * @param columnId
  2657. * the id of the column to remove, not <code>null</code>
  2658. */
  2659. public void removeColumn(String columnId) {
  2660. removeColumn(getColumnOrThrow(columnId));
  2661. }
  2662. /**
  2663. * Removes all columns from this Grid.
  2664. *
  2665. * @since 8.0.2
  2666. */
  2667. public void removeAllColumns() {
  2668. for (Column<T, ?> column : getColumns()) {
  2669. removeColumn(column);
  2670. }
  2671. }
  2672. /**
  2673. * Requests that the column widths should be recalculated.
  2674. * <p>
  2675. * In most cases Grid will know when column widths need to be recalculated
  2676. * but this method can be used to force recalculation in situations when
  2677. * grid does not recalculate automatically.
  2678. *
  2679. * @since 8.1.1
  2680. */
  2681. public void recalculateColumnWidths() {
  2682. getRpcProxy(GridClientRpc.class).recalculateColumnWidths();
  2683. }
  2684. /**
  2685. * Sets the details component generator.
  2686. *
  2687. * @param generator
  2688. * the generator for details components
  2689. */
  2690. public void setDetailsGenerator(DetailsGenerator<T> generator) {
  2691. this.detailsManager.setDetailsGenerator(generator);
  2692. }
  2693. /**
  2694. * Sets the visibility of details component for given item.
  2695. *
  2696. * @param item
  2697. * the item to show details for
  2698. * @param visible
  2699. * {@code true} if details component should be visible;
  2700. * {@code false} if it should be hidden
  2701. */
  2702. public void setDetailsVisible(T item, boolean visible) {
  2703. detailsManager.setDetailsVisible(item, visible);
  2704. }
  2705. /**
  2706. * Returns the visibility of details component for given item.
  2707. *
  2708. * @param item
  2709. * the item to show details for
  2710. *
  2711. * @return {@code true} if details component should be visible;
  2712. * {@code false} if it should be hidden
  2713. */
  2714. public boolean isDetailsVisible(T item) {
  2715. return detailsManager.isDetailsVisible(item);
  2716. }
  2717. /**
  2718. * Gets an unmodifiable collection of all columns currently in this
  2719. * {@link Grid}.
  2720. *
  2721. * @return unmodifiable collection of columns
  2722. */
  2723. public List<Column<T, ?>> getColumns() {
  2724. return Collections.unmodifiableList(getState(false).columnOrder.stream()
  2725. .map(columnKeys::get).collect(Collectors.toList()));
  2726. }
  2727. /**
  2728. * Gets a {@link Column} of this grid by its identifying string.
  2729. *
  2730. * When you use the Grid constructor with bean class, the columns are
  2731. * initialised with columnId being the property name.
  2732. *
  2733. * @see Column#setId(String)
  2734. *
  2735. * @param columnId
  2736. * the identifier of the column to get
  2737. * @return the column corresponding to the given column identifier, or
  2738. * <code>null</code> if there is no such column
  2739. */
  2740. public Column<T, ?> getColumn(String columnId) {
  2741. return columnIds.get(columnId);
  2742. }
  2743. private Column<T, ?> getColumnOrThrow(String columnId) {
  2744. Objects.requireNonNull(columnId, "Column id cannot be null");
  2745. Column<T, ?> column = getColumn(columnId);
  2746. if (column == null) {
  2747. throw new IllegalStateException(
  2748. "There is no column with the id " + columnId);
  2749. }
  2750. return column;
  2751. }
  2752. /**
  2753. * {@inheritDoc}
  2754. * <p>
  2755. * Note that the order of the returned components it not specified.
  2756. */
  2757. @Override
  2758. public Iterator<Component> iterator() {
  2759. Set<Component> componentSet = new LinkedHashSet<>(extensionComponents);
  2760. Header header = getHeader();
  2761. for (int i = 0; i < header.getRowCount(); ++i) {
  2762. HeaderRow row = header.getRow(i);
  2763. componentSet.addAll(row.getComponents());
  2764. }
  2765. Footer footer = getFooter();
  2766. for (int i = 0; i < footer.getRowCount(); ++i) {
  2767. FooterRow row = footer.getRow(i);
  2768. componentSet.addAll(row.getComponents());
  2769. }
  2770. return Collections.unmodifiableSet(componentSet).iterator();
  2771. }
  2772. /**
  2773. * Sets the number of frozen columns in this grid. Setting the count to 0
  2774. * means that no data columns will be frozen, but the built-in selection
  2775. * checkbox column will still be frozen if it's in use. Setting the count to
  2776. * -1 will also disable the selection column.
  2777. * <p>
  2778. * <em>NOTE:</em> this count includes {@link Column#isHidden() hidden
  2779. * columns} in the count.
  2780. * <p>
  2781. * The default value is 0.
  2782. *
  2783. * @param numberOfColumns
  2784. * the number of columns that should be frozen
  2785. *
  2786. * @throws IllegalArgumentException
  2787. * if the column count is less than -1 or greater than the
  2788. * number of visible columns
  2789. */
  2790. public void setFrozenColumnCount(int numberOfColumns) {
  2791. if (numberOfColumns < -1 || numberOfColumns > columnSet.size()) {
  2792. throw new IllegalArgumentException(
  2793. "count must be between -1 and the current number of columns ("
  2794. + columnSet.size() + "): " + numberOfColumns);
  2795. }
  2796. getState().frozenColumnCount = numberOfColumns;
  2797. }
  2798. /**
  2799. * Gets the number of frozen columns in this grid. 0 means that no data
  2800. * columns will be frozen, but the built-in selection checkbox column will
  2801. * still be frozen if it's in use. -1 means that not even the selection
  2802. * column is frozen.
  2803. * <p>
  2804. * <em>NOTE:</em> this count includes {@link Column#isHidden() hidden
  2805. * columns} in the count.
  2806. *
  2807. * @see #setFrozenColumnCount(int)
  2808. *
  2809. * @return the number of frozen columns
  2810. */
  2811. public int getFrozenColumnCount() {
  2812. return getState(false).frozenColumnCount;
  2813. }
  2814. /**
  2815. * Sets the number of rows that should be visible in Grid's body. This
  2816. * method will set the height mode to be {@link HeightMode#ROW}.
  2817. *
  2818. * @param rows
  2819. * The height in terms of number of rows displayed in Grid's
  2820. * body. If Grid doesn't contain enough rows, white space is
  2821. * displayed instead.
  2822. * @throws IllegalArgumentException
  2823. * if {@code rows} is zero or less
  2824. * @throws IllegalArgumentException
  2825. * if {@code rows} is {@link Double#isInfinite(double) infinite}
  2826. * @throws IllegalArgumentException
  2827. * if {@code rows} is {@link Double#isNaN(double) NaN}
  2828. */
  2829. public void setHeightByRows(double rows) {
  2830. if (rows <= 0.0d) {
  2831. throw new IllegalArgumentException(
  2832. "More than zero rows must be shown.");
  2833. }
  2834. if (Double.isInfinite(rows)) {
  2835. throw new IllegalArgumentException(
  2836. "Grid doesn't support infinite heights");
  2837. }
  2838. if (Double.isNaN(rows)) {
  2839. throw new IllegalArgumentException("NaN is not a valid row count");
  2840. }
  2841. getState().heightMode = HeightMode.ROW;
  2842. getState().heightByRows = rows;
  2843. }
  2844. /**
  2845. * Gets the amount of rows in Grid's body that are shown, while
  2846. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  2847. *
  2848. * @return the amount of rows that are being shown in Grid's body
  2849. * @see #setHeightByRows(double)
  2850. */
  2851. public double getHeightByRows() {
  2852. return getState(false).heightByRows;
  2853. }
  2854. /**
  2855. * {@inheritDoc}
  2856. * <p>
  2857. * <em>Note:</em> This method will set the height mode to be
  2858. * {@link HeightMode#CSS}.
  2859. *
  2860. * @see #setHeightMode(HeightMode)
  2861. */
  2862. @Override
  2863. public void setHeight(float height, Unit unit) {
  2864. getState().heightMode = HeightMode.CSS;
  2865. super.setHeight(height, unit);
  2866. }
  2867. /**
  2868. * Defines the mode in which the Grid widget's height is calculated.
  2869. * <p>
  2870. * If {@link HeightMode#CSS} is given, Grid will respect the values given
  2871. * via a {@code setHeight}-method, and behave as a traditional Component.
  2872. * <p>
  2873. * If {@link HeightMode#ROW} is given, Grid will make sure that the body
  2874. * will display as many rows as {@link #getHeightByRows()} defines.
  2875. * <em>Note:</em> If headers/footers are inserted or removed, the widget
  2876. * will resize itself to still display the required amount of rows in its
  2877. * body. It also takes the horizontal scrollbar into account.
  2878. *
  2879. * @param heightMode
  2880. * the mode in to which Grid should be set
  2881. */
  2882. public void setHeightMode(HeightMode heightMode) {
  2883. /**
  2884. * This method is a workaround for the fact that Vaadin re-applies
  2885. * widget dimensions (height/width) on each state change event. The
  2886. * original design was to have setHeight and setHeightByRow be equals,
  2887. * and whichever was called the latest was considered in effect.
  2888. *
  2889. * But, because of Vaadin always calling setHeight on the widget, this
  2890. * approach doesn't work.
  2891. */
  2892. getState().heightMode = heightMode;
  2893. }
  2894. /**
  2895. * Returns the current {@link HeightMode} the Grid is in.
  2896. * <p>
  2897. * Defaults to {@link HeightMode#CSS}.
  2898. *
  2899. * @return the current HeightMode
  2900. */
  2901. public HeightMode getHeightMode() {
  2902. return getState(false).heightMode;
  2903. }
  2904. /**
  2905. * Sets the height of body, header and footer rows. If -1 (default), the row
  2906. * height is calculated based on the theme for an empty row before the Grid
  2907. * is displayed.
  2908. * <p>
  2909. * Note that all header, body and footer rows get the same height if
  2910. * explicitly set. In automatic mode, each section is calculated separately
  2911. * based on an empty row of that type.
  2912. *
  2913. * @see #setBodyRowHeight(double)
  2914. * @see #setHeaderRowHeight(double)
  2915. * @see #setFooterRowHeight(double)
  2916. *
  2917. * @param rowHeight
  2918. * The height of a row in pixels or -1 for automatic calculation
  2919. */
  2920. public void setRowHeight(double rowHeight) {
  2921. setBodyRowHeight(rowHeight);
  2922. setHeaderRowHeight(rowHeight);
  2923. setFooterRowHeight(rowHeight);
  2924. }
  2925. /**
  2926. * Sets the height of a body row. If -1 (default), the row height is
  2927. * calculated based on the theme for an empty row before the Grid is
  2928. * displayed.
  2929. *
  2930. * @param rowHeight
  2931. * The height of a row in pixels or -1 for automatic calculation
  2932. * @since 8.2
  2933. */
  2934. public void setBodyRowHeight(double rowHeight) {
  2935. getState().bodyRowHeight = rowHeight;
  2936. }
  2937. /**
  2938. * Sets the height of a header row. If -1 (default), the row height is
  2939. * calculated based on the theme for an empty row before the Grid is
  2940. * displayed.
  2941. *
  2942. * @param rowHeight
  2943. * The height of a row in pixels or -1 for automatic calculation
  2944. * @since 8.2
  2945. */
  2946. public void setHeaderRowHeight(double rowHeight) {
  2947. getState().headerRowHeight = rowHeight;
  2948. }
  2949. /**
  2950. * Sets the height of a footer row. If -1 (default), the row height is
  2951. * calculated based on the theme for an empty row before the Grid is
  2952. * displayed.
  2953. *
  2954. * @param rowHeight
  2955. * The height of a row in pixels or -1 for automatic calculation
  2956. * @since 8.2
  2957. */
  2958. public void setFooterRowHeight(double rowHeight) {
  2959. getState().footerRowHeight = rowHeight;
  2960. }
  2961. /**
  2962. * Returns the current body row height.-1 if row height is in automatic
  2963. * calculation mode.
  2964. *
  2965. * @see #getBodyRowHeight()
  2966. * @see #getHeaderRowHeight()
  2967. * @see #getFooterRowHeight()
  2968. *
  2969. * @return body row height
  2970. * @deprecated replaced by three separate row height controls
  2971. */
  2972. @Deprecated
  2973. public double getRowHeight() {
  2974. return getBodyRowHeight();
  2975. }
  2976. /**
  2977. * Returns the current body row height. -1 if row height is in automatic
  2978. * calculation mode.
  2979. *
  2980. * @return body row height
  2981. * @since 8.2
  2982. */
  2983. public double getBodyRowHeight() {
  2984. return getState(false).bodyRowHeight;
  2985. }
  2986. /**
  2987. * Returns the current header row height. -1 if row height is in automatic
  2988. * calculation mode.
  2989. *
  2990. * @return header row height
  2991. * @since 8.2
  2992. */
  2993. public double getHeaderRowHeight() {
  2994. return getState(false).headerRowHeight;
  2995. }
  2996. /**
  2997. * Returns the current footer row height. -1 if row height is in automatic
  2998. * calculation mode.
  2999. *
  3000. * @return footer row height
  3001. * @since 8.2
  3002. */
  3003. public double getFooterRowHeight() {
  3004. return getState(false).footerRowHeight;
  3005. }
  3006. /**
  3007. * Sets the style generator that is used for generating class names for rows
  3008. * in this grid. Returning null from the generator results in no custom
  3009. * style name being set.
  3010. *
  3011. * @see StyleGenerator
  3012. *
  3013. * @param styleGenerator
  3014. * the row style generator to set, not null
  3015. * @throws NullPointerException
  3016. * if {@code styleGenerator} is {@code null}
  3017. */
  3018. public void setStyleGenerator(StyleGenerator<T> styleGenerator) {
  3019. Objects.requireNonNull(styleGenerator,
  3020. "Style generator must not be null");
  3021. this.styleGenerator = styleGenerator;
  3022. getDataCommunicator().reset();
  3023. }
  3024. /**
  3025. * Gets the style generator that is used for generating class names for
  3026. * rows.
  3027. *
  3028. * @see StyleGenerator
  3029. *
  3030. * @return the row style generator
  3031. */
  3032. public StyleGenerator<T> getStyleGenerator() {
  3033. return styleGenerator;
  3034. }
  3035. /**
  3036. * Sets the description generator that is used for generating descriptions
  3037. * for rows. This method uses the {@link ContentMode#PREFORMATTED} content
  3038. * mode.
  3039. *
  3040. * @see #setDescriptionGenerator(DescriptionGenerator, ContentMode)
  3041. *
  3042. * @param descriptionGenerator
  3043. * the row description generator to set, or <code>null</code> to
  3044. * remove a previously set generator
  3045. */
  3046. public void setDescriptionGenerator(
  3047. DescriptionGenerator<T> descriptionGenerator) {
  3048. setDescriptionGenerator(descriptionGenerator, ContentMode.PREFORMATTED);
  3049. }
  3050. /**
  3051. * Sets the description generator that is used for generating descriptions
  3052. * for rows. This method uses the given content mode.
  3053. *
  3054. * @see #setDescriptionGenerator(DescriptionGenerator)
  3055. *
  3056. * @param descriptionGenerator
  3057. * the row description generator to set, or {@code null} to
  3058. * remove a previously set generator
  3059. * @param contentMode
  3060. * the content mode for row tooltips
  3061. *
  3062. * @since 8.2
  3063. */
  3064. public void setDescriptionGenerator(
  3065. DescriptionGenerator<T> descriptionGenerator,
  3066. ContentMode contentMode) {
  3067. Objects.requireNonNull(contentMode, "contentMode cannot be null");
  3068. this.descriptionGenerator = descriptionGenerator;
  3069. getState().rowDescriptionContentMode = contentMode;
  3070. getDataCommunicator().reset();
  3071. }
  3072. /**
  3073. * Gets the description generator that is used for generating descriptions
  3074. * for rows.
  3075. *
  3076. * @return the row description generator, or <code>null</code> if no
  3077. * generator is set
  3078. */
  3079. public DescriptionGenerator<T> getDescriptionGenerator() {
  3080. return descriptionGenerator;
  3081. }
  3082. //
  3083. // HEADER AND FOOTER
  3084. //
  3085. /**
  3086. * Returns the header row at the given index.
  3087. *
  3088. * @param index
  3089. * the index of the row, where the topmost row has index zero
  3090. * @return the header row at the index
  3091. * @throws IndexOutOfBoundsException
  3092. * if {@code rowIndex < 0 || rowIndex >= getHeaderRowCount()}
  3093. */
  3094. public HeaderRow getHeaderRow(int index) {
  3095. return getHeader().getRow(index);
  3096. }
  3097. /**
  3098. * Gets the number of rows in the header section.
  3099. *
  3100. * @return the number of header rows
  3101. */
  3102. public int getHeaderRowCount() {
  3103. return header.getRowCount();
  3104. }
  3105. /**
  3106. * Inserts a new row at the given position to the header section. Shifts the
  3107. * row currently at that position and any subsequent rows down (adds one to
  3108. * their indices). Inserting at {@link #getHeaderRowCount()} appends the row
  3109. * at the bottom of the header.
  3110. *
  3111. * @param index
  3112. * the index at which to insert the row, where the topmost row
  3113. * has index zero
  3114. * @return the inserted header row
  3115. *
  3116. * @throws IndexOutOfBoundsException
  3117. * if {@code rowIndex < 0 || rowIndex > getHeaderRowCount()}
  3118. *
  3119. * @see #appendHeaderRow()
  3120. * @see #prependHeaderRow()
  3121. * @see #removeHeaderRow(HeaderRow)
  3122. * @see #removeHeaderRow(int)
  3123. */
  3124. public HeaderRow addHeaderRowAt(int index) {
  3125. return getHeader().addRowAt(index);
  3126. }
  3127. /**
  3128. * Adds a new row at the bottom of the header section.
  3129. *
  3130. * @return the appended header row
  3131. *
  3132. * @see #prependHeaderRow()
  3133. * @see #addHeaderRowAt(int)
  3134. * @see #removeHeaderRow(HeaderRow)
  3135. * @see #removeHeaderRow(int)
  3136. */
  3137. public HeaderRow appendHeaderRow() {
  3138. return addHeaderRowAt(getHeaderRowCount());
  3139. }
  3140. /**
  3141. * Adds a new row at the top of the header section.
  3142. *
  3143. * @return the prepended header row
  3144. *
  3145. * @see #appendHeaderRow()
  3146. * @see #addHeaderRowAt(int)
  3147. * @see #removeHeaderRow(HeaderRow)
  3148. * @see #removeHeaderRow(int)
  3149. */
  3150. public HeaderRow prependHeaderRow() {
  3151. return addHeaderRowAt(0);
  3152. }
  3153. /**
  3154. * Removes the given row from the header section. Removing a default row
  3155. * sets the Grid to have no default row.
  3156. *
  3157. * @param row
  3158. * the header row to be removed, not null
  3159. *
  3160. * @throws IllegalArgumentException
  3161. * if the header does not contain the row
  3162. *
  3163. * @see #removeHeaderRow(int)
  3164. * @see #addHeaderRowAt(int)
  3165. * @see #appendHeaderRow()
  3166. * @see #prependHeaderRow()
  3167. */
  3168. public void removeHeaderRow(HeaderRow row) {
  3169. getHeader().removeRow(row);
  3170. }
  3171. /**
  3172. * Removes the row at the given position from the header section.
  3173. *
  3174. * @param index
  3175. * the index of the row to remove, where the topmost row has
  3176. * index zero
  3177. *
  3178. * @throws IndexOutOfBoundsException
  3179. * if {@code index < 0 || index >= getHeaderRowCount()}
  3180. *
  3181. * @see #removeHeaderRow(HeaderRow)
  3182. * @see #addHeaderRowAt(int)
  3183. * @see #appendHeaderRow()
  3184. * @see #prependHeaderRow()
  3185. */
  3186. public void removeHeaderRow(int index) {
  3187. getHeader().removeRow(index);
  3188. }
  3189. /**
  3190. * Sets the visibility of the Header in this Grid.
  3191. *
  3192. * @param headerVisible
  3193. * {@code true} if visible; {@code false} if not
  3194. *
  3195. * @since 8.1.1
  3196. */
  3197. public void setHeaderVisible(boolean headerVisible) {
  3198. getHeader().setVisible(headerVisible);
  3199. }
  3200. /**
  3201. * Gets the visibility of the Header in this Grid.
  3202. *
  3203. * @return {@code true} if visible; {@code false} if not
  3204. *
  3205. * @since 8.1.1
  3206. */
  3207. public boolean isHeaderVisible() {
  3208. return getHeader().isVisible();
  3209. }
  3210. /**
  3211. * Returns the current default row of the header.
  3212. *
  3213. * @return the default row or null if no default row set
  3214. *
  3215. * @see #setDefaultHeaderRow(HeaderRow)
  3216. */
  3217. public HeaderRow getDefaultHeaderRow() {
  3218. return header.getDefaultRow();
  3219. }
  3220. /**
  3221. * Sets the default row of the header. The default row is a special header
  3222. * row that displays column captions and sort indicators. By default Grid
  3223. * has a single row which is also the default row. When a header row is set
  3224. * as the default row, any existing cell content is replaced by the column
  3225. * captions.
  3226. *
  3227. * @param row
  3228. * the new default row, or null for no default row
  3229. *
  3230. * @throws IllegalArgumentException
  3231. * if the header does not contain the row
  3232. */
  3233. public void setDefaultHeaderRow(HeaderRow row) {
  3234. header.setDefaultRow((Row) row);
  3235. }
  3236. /**
  3237. * Returns the header section of this grid. The default header contains a
  3238. * single row, set as the {@linkplain #setDefaultHeaderRow(HeaderRow)
  3239. * default row}.
  3240. *
  3241. * @return the header section
  3242. */
  3243. protected Header getHeader() {
  3244. return header;
  3245. }
  3246. /**
  3247. * Returns the footer row at the given index.
  3248. *
  3249. * @param index
  3250. * the index of the row, where the topmost row has index zero
  3251. * @return the footer row at the index
  3252. * @throws IndexOutOfBoundsException
  3253. * if {@code rowIndex < 0 || rowIndex >= getFooterRowCount()}
  3254. */
  3255. public FooterRow getFooterRow(int index) {
  3256. return getFooter().getRow(index);
  3257. }
  3258. /**
  3259. * Gets the number of rows in the footer section.
  3260. *
  3261. * @return the number of footer rows
  3262. */
  3263. public int getFooterRowCount() {
  3264. return getFooter().getRowCount();
  3265. }
  3266. /**
  3267. * Inserts a new row at the given position to the footer section. Shifts the
  3268. * row currently at that position and any subsequent rows down (adds one to
  3269. * their indices). Inserting at {@link #getFooterRowCount()} appends the row
  3270. * at the bottom of the footer.
  3271. *
  3272. * @param index
  3273. * the index at which to insert the row, where the topmost row
  3274. * has index zero
  3275. * @return the inserted footer row
  3276. *
  3277. * @throws IndexOutOfBoundsException
  3278. * if {@code rowIndex < 0 || rowIndex > getFooterRowCount()}
  3279. *
  3280. * @see #appendFooterRow()
  3281. * @see #prependFooterRow()
  3282. * @see #removeFooterRow(FooterRow)
  3283. * @see #removeFooterRow(int)
  3284. */
  3285. public FooterRow addFooterRowAt(int index) {
  3286. return getFooter().addRowAt(index);
  3287. }
  3288. /**
  3289. * Adds a new row at the bottom of the footer section.
  3290. *
  3291. * @return the appended footer row
  3292. *
  3293. * @see #prependFooterRow()
  3294. * @see #addFooterRowAt(int)
  3295. * @see #removeFooterRow(FooterRow)
  3296. * @see #removeFooterRow(int)
  3297. */
  3298. public FooterRow appendFooterRow() {
  3299. return addFooterRowAt(getFooterRowCount());
  3300. }
  3301. /**
  3302. * Adds a new row at the top of the footer section.
  3303. *
  3304. * @return the prepended footer row
  3305. *
  3306. * @see #appendFooterRow()
  3307. * @see #addFooterRowAt(int)
  3308. * @see #removeFooterRow(FooterRow)
  3309. * @see #removeFooterRow(int)
  3310. */
  3311. public FooterRow prependFooterRow() {
  3312. return addFooterRowAt(0);
  3313. }
  3314. /**
  3315. * Removes the given row from the footer section. Removing a default row
  3316. * sets the Grid to have no default row.
  3317. *
  3318. * @param row
  3319. * the footer row to be removed, not null
  3320. *
  3321. * @throws IllegalArgumentException
  3322. * if the footer does not contain the row
  3323. *
  3324. * @see #removeFooterRow(int)
  3325. * @see #addFooterRowAt(int)
  3326. * @see #appendFooterRow()
  3327. * @see #prependFooterRow()
  3328. */
  3329. public void removeFooterRow(FooterRow row) {
  3330. getFooter().removeRow(row);
  3331. }
  3332. /**
  3333. * Removes the row at the given position from the footer section.
  3334. *
  3335. * @param index
  3336. * the index of the row to remove, where the topmost row has
  3337. * index zero
  3338. *
  3339. * @throws IndexOutOfBoundsException
  3340. * if {@code index < 0 || index >= getFooterRowCount()}
  3341. *
  3342. * @see #removeFooterRow(FooterRow)
  3343. * @see #addFooterRowAt(int)
  3344. * @see #appendFooterRow()
  3345. * @see #prependFooterRow()
  3346. */
  3347. public void removeFooterRow(int index) {
  3348. getFooter().removeRow(index);
  3349. }
  3350. /**
  3351. * Sets the visibility of the Footer in this Grid.
  3352. *
  3353. * @param footerVisible
  3354. * {@code true} if visible; {@code false} if not
  3355. *
  3356. * @since 8.1.1
  3357. */
  3358. public void setFooterVisible(boolean footerVisible) {
  3359. getFooter().setVisible(footerVisible);
  3360. }
  3361. /**
  3362. * Gets the visibility of the Footer in this Grid.
  3363. *
  3364. * @return {@code true} if visible; {@code false} if not
  3365. *
  3366. * @since 8.1.1
  3367. */
  3368. public boolean isFooterVisible() {
  3369. return getFooter().isVisible();
  3370. }
  3371. /**
  3372. * Returns the footer section of this grid.
  3373. *
  3374. * @return the footer section
  3375. */
  3376. protected Footer getFooter() {
  3377. return footer;
  3378. }
  3379. /**
  3380. * Registers a new column reorder listener.
  3381. *
  3382. * @param listener
  3383. * the listener to register, not null
  3384. * @return a registration for the listener
  3385. */
  3386. public Registration addColumnReorderListener(
  3387. ColumnReorderListener listener) {
  3388. return addListener(ColumnReorderEvent.class, listener,
  3389. COLUMN_REORDER_METHOD);
  3390. }
  3391. /**
  3392. * Registers a new column resize listener.
  3393. *
  3394. * @param listener
  3395. * the listener to register, not null
  3396. * @return a registration for the listener
  3397. */
  3398. public Registration addColumnResizeListener(ColumnResizeListener listener) {
  3399. return addListener(ColumnResizeEvent.class, listener,
  3400. COLUMN_RESIZE_METHOD);
  3401. }
  3402. /**
  3403. * Adds an item click listener. The listener is called when an item of this
  3404. * {@code Grid} is clicked.
  3405. *
  3406. * @param listener
  3407. * the item click listener, not null
  3408. * @return a registration for the listener
  3409. * @see #addContextClickListener
  3410. */
  3411. public Registration addItemClickListener(
  3412. ItemClickListener<? super T> listener) {
  3413. return addListener(GridConstants.ITEM_CLICK_EVENT_ID, ItemClick.class,
  3414. listener, ITEM_CLICK_METHOD);
  3415. }
  3416. /**
  3417. * Adds a context click listener that gets notified when a context click
  3418. * happens.
  3419. *
  3420. * @param listener
  3421. * the context click listener to add, not null actual event
  3422. * provided to the listener is {@link GridContextClickEvent}
  3423. * @return a registration object for removing the listener
  3424. *
  3425. * @since 8.1
  3426. * @see #addItemClickListener
  3427. * @see Registration
  3428. */
  3429. @Override
  3430. public Registration addContextClickListener(
  3431. ContextClickEvent.ContextClickListener listener) {
  3432. return super.addContextClickListener(listener);
  3433. }
  3434. /**
  3435. * Registers a new column visibility change listener.
  3436. *
  3437. * @param listener
  3438. * the listener to register, not null
  3439. * @return a registration for the listener
  3440. */
  3441. public Registration addColumnVisibilityChangeListener(
  3442. ColumnVisibilityChangeListener listener) {
  3443. return addListener(ColumnVisibilityChangeEvent.class, listener,
  3444. COLUMN_VISIBILITY_METHOD);
  3445. }
  3446. /**
  3447. * Returns whether column reordering is allowed. Default value is
  3448. * <code>false</code>.
  3449. *
  3450. * @return true if reordering is allowed
  3451. */
  3452. public boolean isColumnReorderingAllowed() {
  3453. return getState(false).columnReorderingAllowed;
  3454. }
  3455. /**
  3456. * Sets whether or not column reordering is allowed. Default value is
  3457. * <code>false</code>.
  3458. *
  3459. * @param columnReorderingAllowed
  3460. * specifies whether column reordering is allowed
  3461. */
  3462. public void setColumnReorderingAllowed(boolean columnReorderingAllowed) {
  3463. if (isColumnReorderingAllowed() != columnReorderingAllowed) {
  3464. getState().columnReorderingAllowed = columnReorderingAllowed;
  3465. }
  3466. }
  3467. /**
  3468. * Sets the columns and their order based on their column ids. Columns
  3469. * currently in this grid that are not present in the list of column ids are
  3470. * removed. This includes any column that has no id. Similarly, any new
  3471. * column in columns will be added to this grid. New columns can only be
  3472. * added for a <code>Grid</code> created using {@link Grid#Grid(Class)} or
  3473. * {@link #withPropertySet(PropertySet)}.
  3474. *
  3475. *
  3476. * @param columnIds
  3477. * the column ids to set
  3478. *
  3479. * @see Column#setId(String)
  3480. */
  3481. public void setColumns(String... columnIds) {
  3482. // Must extract to an explicitly typed variable because otherwise javac
  3483. // cannot determine which overload of setColumnOrder to use
  3484. Column<T, ?>[] newColumnOrder = Stream.of(columnIds)
  3485. .map((Function<String, Column<T, ?>>) id -> {
  3486. Column<T, ?> column = getColumn(id);
  3487. if (column == null) {
  3488. column = addColumn(id);
  3489. }
  3490. return column;
  3491. }).toArray(Column[]::new);
  3492. setColumnOrder(newColumnOrder);
  3493. // The columns to remove are now at the end of the column list
  3494. getColumns().stream().skip(columnIds.length)
  3495. .forEach(this::removeColumn);
  3496. }
  3497. private String getGeneratedIdentifier() {
  3498. String columnId = "" + counter;
  3499. counter++;
  3500. return columnId;
  3501. }
  3502. /**
  3503. * Sets a new column order for the grid. All columns which are not ordered
  3504. * here will remain in the order they were before as the last columns of
  3505. * grid.
  3506. *
  3507. * @param columns
  3508. * the columns in the order they should be
  3509. */
  3510. public void setColumnOrder(Column<T, ?>... columns) {
  3511. setColumnOrder(Stream.of(columns));
  3512. }
  3513. private void setColumnOrder(Stream<Column<T, ?>> columns) {
  3514. List<String> columnOrder = new ArrayList<>();
  3515. columns.forEach(column -> {
  3516. if (columnSet.contains(column)) {
  3517. columnOrder.add(column.getInternalId());
  3518. } else {
  3519. throw new IllegalStateException(
  3520. "setColumnOrder should not be called "
  3521. + "with columns that are not in the grid.");
  3522. }
  3523. });
  3524. List<String> stateColumnOrder = getState().columnOrder;
  3525. if (stateColumnOrder.size() != columnOrder.size()) {
  3526. stateColumnOrder.removeAll(columnOrder);
  3527. columnOrder.addAll(stateColumnOrder);
  3528. }
  3529. getState().columnOrder = columnOrder;
  3530. fireColumnReorderEvent(false);
  3531. }
  3532. /**
  3533. * Sets a new column order for the grid based on their column ids. All
  3534. * columns which are not ordered here will remain in the order they were
  3535. * before as the last columns of grid.
  3536. *
  3537. * @param columnIds
  3538. * the column ids in the order they should be
  3539. *
  3540. * @see Column#setId(String)
  3541. */
  3542. public void setColumnOrder(String... columnIds) {
  3543. setColumnOrder(Stream.of(columnIds).map(this::getColumnOrThrow));
  3544. }
  3545. /**
  3546. * Returns the selection model for this grid.
  3547. *
  3548. * @return the selection model, not null
  3549. */
  3550. public GridSelectionModel<T> getSelectionModel() {
  3551. assert selectionModel != null : "No selection model set by "
  3552. + getClass().getName() + " constructor";
  3553. return selectionModel;
  3554. }
  3555. /**
  3556. * Use this grid as a single select in {@link Binder}.
  3557. * <p>
  3558. * Throws {@link IllegalStateException} if the grid is not using a
  3559. * {@link SingleSelectionModel}.
  3560. *
  3561. * @return the single select wrapper that can be used in binder
  3562. * @throws IllegalStateException
  3563. * if not using a single selection model
  3564. */
  3565. public GridSingleSelect<T> asSingleSelect() {
  3566. return new GridSingleSelect<>(this);
  3567. }
  3568. public Editor<T> getEditor() {
  3569. return editor;
  3570. }
  3571. /**
  3572. * User this grid as a multiselect in {@link Binder}.
  3573. * <p>
  3574. * Throws {@link IllegalStateException} if the grid is not using a
  3575. * {@link MultiSelectionModel}.
  3576. *
  3577. * @return the multiselect wrapper that can be used in binder
  3578. * @throws IllegalStateException
  3579. * if not using a multiselection model
  3580. */
  3581. public GridMultiSelect<T> asMultiSelect() {
  3582. return new GridMultiSelect<>(this);
  3583. }
  3584. /**
  3585. * Sets the selection model for the grid.
  3586. * <p>
  3587. * This method is for setting a custom selection model, and is
  3588. * {@code protected} because {@link #setSelectionMode(SelectionMode)} should
  3589. * be used for easy switching between built-in selection models.
  3590. * <p>
  3591. * The default selection model is {@link SingleSelectionModelImpl}.
  3592. * <p>
  3593. * To use a custom selection model, you can e.g. extend the grid call this
  3594. * method with your custom selection model.
  3595. *
  3596. * @param model
  3597. * the selection model to use, not {@code null}
  3598. *
  3599. * @see #setSelectionMode(SelectionMode)
  3600. */
  3601. @SuppressWarnings("unchecked")
  3602. protected void setSelectionModel(GridSelectionModel<T> model) {
  3603. Objects.requireNonNull(model, "selection model cannot be null");
  3604. if (selectionModel != null) { // null when called from constructor
  3605. selectionModel.remove();
  3606. }
  3607. selectionModel = model;
  3608. if (selectionModel instanceof AbstractListingExtension) {
  3609. ((AbstractListingExtension<T>) selectionModel).extend(this);
  3610. } else {
  3611. addExtension(selectionModel);
  3612. }
  3613. }
  3614. /**
  3615. * Sets the grid's selection mode.
  3616. * <p>
  3617. * The built-in selection models are:
  3618. * <ul>
  3619. * <li>{@link SelectionMode#SINGLE} -> {@link SingleSelectionModelImpl},
  3620. * <b>the default model</b></li>
  3621. * <li>{@link SelectionMode#MULTI} -> {@link MultiSelectionModelImpl}, with
  3622. * checkboxes in the first column for selection</li>
  3623. * <li>{@link SelectionMode#NONE} -> {@link NoSelectionModel}, preventing
  3624. * selection</li>
  3625. * </ul>
  3626. * <p>
  3627. * To use your custom selection model, you can use
  3628. * {@link #setSelectionModel(GridSelectionModel)}, see existing selection
  3629. * model implementations for example.
  3630. *
  3631. * @param selectionMode
  3632. * the selection mode to switch to, not {@code null}
  3633. * @return the used selection model
  3634. *
  3635. * @see SelectionMode
  3636. * @see GridSelectionModel
  3637. * @see #setSelectionModel(GridSelectionModel)
  3638. */
  3639. public GridSelectionModel<T> setSelectionMode(SelectionMode selectionMode) {
  3640. Objects.requireNonNull(selectionMode, "Selection mode cannot be null.");
  3641. GridSelectionModel<T> model = selectionMode.createModel();
  3642. setSelectionModel(model);
  3643. return model;
  3644. }
  3645. /**
  3646. * This method is a shorthand that delegates to the currently set selection
  3647. * model.
  3648. *
  3649. * @see #getSelectionModel()
  3650. * @see GridSelectionModel
  3651. */
  3652. public Set<T> getSelectedItems() {
  3653. return getSelectionModel().getSelectedItems();
  3654. }
  3655. /**
  3656. * This method is a shorthand that delegates to the currently set selection
  3657. * model.
  3658. *
  3659. * @see #getSelectionModel()
  3660. * @see GridSelectionModel
  3661. */
  3662. public void select(T item) {
  3663. getSelectionModel().select(item);
  3664. }
  3665. /**
  3666. * This method is a shorthand that delegates to the currently set selection
  3667. * model.
  3668. *
  3669. * @see #getSelectionModel()
  3670. * @see GridSelectionModel
  3671. */
  3672. public void deselect(T item) {
  3673. getSelectionModel().deselect(item);
  3674. }
  3675. /**
  3676. * This method is a shorthand that delegates to the currently set selection
  3677. * model.
  3678. *
  3679. * @see #getSelectionModel()
  3680. * @see GridSelectionModel
  3681. */
  3682. public void deselectAll() {
  3683. getSelectionModel().deselectAll();
  3684. }
  3685. /**
  3686. * Adds a selection listener to the current selection model.
  3687. * <p>
  3688. * <em>NOTE:</em> If selection mode is switched with
  3689. * {@link #setSelectionMode(SelectionMode)}, then this listener is not
  3690. * triggered anymore when selection changes!
  3691. * <p>
  3692. * This is a shorthand for
  3693. * {@code grid.getSelectionModel().addSelectionListener()}. To get more
  3694. * detailed selection events, use {@link #getSelectionModel()} and either
  3695. * {@link SingleSelectionModel#addSingleSelectionListener(SingleSelectionListener)}
  3696. * or
  3697. * {@link MultiSelectionModel#addMultiSelectionListener(MultiSelectionListener)}
  3698. * depending on the used selection mode.
  3699. *
  3700. * @param listener
  3701. * the listener to add
  3702. * @return a registration handle to remove the listener
  3703. * @throws UnsupportedOperationException
  3704. * if selection has been disabled with
  3705. * {@link SelectionMode#NONE}
  3706. */
  3707. public Registration addSelectionListener(SelectionListener<T> listener)
  3708. throws UnsupportedOperationException {
  3709. return getSelectionModel().addSelectionListener(listener);
  3710. }
  3711. /**
  3712. * Sort this Grid in ascending order by a specified column.
  3713. *
  3714. * @param column
  3715. * a column to sort against
  3716. *
  3717. */
  3718. public void sort(Column<T, ?> column) {
  3719. sort(column, SortDirection.ASCENDING);
  3720. }
  3721. /**
  3722. * Sort this Grid in user-specified direction by a column.
  3723. *
  3724. * @param column
  3725. * a column to sort against
  3726. * @param direction
  3727. * a sort order value (ascending/descending)
  3728. *
  3729. */
  3730. public void sort(Column<T, ?> column, SortDirection direction) {
  3731. setSortOrder(Collections
  3732. .singletonList(new GridSortOrder<>(column, direction)));
  3733. }
  3734. /**
  3735. * Sort this Grid in ascending order by a specified column defined by id.
  3736. *
  3737. * @param columnId
  3738. * the id of the column to sort against
  3739. *
  3740. * @see Column#setId(String)
  3741. */
  3742. public void sort(String columnId) {
  3743. sort(columnId, SortDirection.ASCENDING);
  3744. }
  3745. /**
  3746. * Sort this Grid in a user-specified direction by a column defined by id.
  3747. *
  3748. * @param columnId
  3749. * the id of the column to sort against
  3750. * @param direction
  3751. * a sort order value (ascending/descending)
  3752. *
  3753. * @see Column#setId(String)
  3754. */
  3755. public void sort(String columnId, SortDirection direction) {
  3756. sort(getColumnOrThrow(columnId), direction);
  3757. }
  3758. /**
  3759. * Clear the current sort order, and re-sort the grid.
  3760. */
  3761. public void clearSortOrder() {
  3762. setSortOrder(Collections.emptyList());
  3763. }
  3764. /**
  3765. * Sets the sort order to use.
  3766. *
  3767. * @param order
  3768. * a sort order list.
  3769. *
  3770. * @throws IllegalArgumentException
  3771. * if order is null
  3772. */
  3773. public void setSortOrder(List<GridSortOrder<T>> order) {
  3774. setSortOrder(order, false);
  3775. }
  3776. /**
  3777. * Sets the sort order to use, given a {@link GridSortOrderBuilder}.
  3778. * Shorthand for {@code setSortOrder(builder.build())}.
  3779. *
  3780. * @see GridSortOrderBuilder
  3781. *
  3782. * @param builder
  3783. * the sort builder to retrieve the sort order from
  3784. * @throws NullPointerException
  3785. * if builder is null
  3786. */
  3787. public void setSortOrder(GridSortOrderBuilder<T> builder) {
  3788. Objects.requireNonNull(builder, "Sort builder cannot be null");
  3789. setSortOrder(builder.build());
  3790. }
  3791. /**
  3792. * Adds a sort order change listener that gets notified when the sort order
  3793. * changes.
  3794. *
  3795. * @param listener
  3796. * the sort order change listener to add
  3797. */
  3798. @Override
  3799. public Registration addSortListener(
  3800. SortListener<GridSortOrder<T>> listener) {
  3801. return addListener(SortEvent.class, listener, SORT_ORDER_CHANGE_METHOD);
  3802. }
  3803. /**
  3804. * Get the current sort order list.
  3805. *
  3806. * @return a sort order list
  3807. */
  3808. public List<GridSortOrder<T>> getSortOrder() {
  3809. return Collections.unmodifiableList(sortOrder);
  3810. }
  3811. /**
  3812. * Scrolls to a certain item, using {@link ScrollDestination#ANY}.
  3813. * <p>
  3814. * If the item has an open details row, its size will also be taken into
  3815. * account.
  3816. *
  3817. * @param row
  3818. * zero based index of the item to scroll to in the current view.
  3819. * @throws IllegalArgumentException
  3820. * if the provided row is outside the item range
  3821. */
  3822. public void scrollTo(int row) throws IllegalArgumentException {
  3823. scrollTo(row, ScrollDestination.ANY);
  3824. }
  3825. /**
  3826. * Scrolls to a certain item, using user-specified scroll destination.
  3827. * <p>
  3828. * If the item has an open details row, its size will also be taken into
  3829. * account.
  3830. *
  3831. * @param row
  3832. * zero based index of the item to scroll to in the current view.
  3833. * @param destination
  3834. * value specifying desired position of scrolled-to row, not
  3835. * {@code null}
  3836. * @throws IllegalArgumentException
  3837. * if the provided row is outside the item range
  3838. */
  3839. public void scrollTo(int row, ScrollDestination destination) {
  3840. Objects.requireNonNull(destination,
  3841. "ScrollDestination can not be null");
  3842. if (row > getDataCommunicator().getDataProviderSize()) {
  3843. throw new IllegalArgumentException("Row outside dataProvider size");
  3844. }
  3845. getRpcProxy(GridClientRpc.class).scrollToRow(row, destination);
  3846. }
  3847. /**
  3848. * Scrolls to the beginning of the first data row.
  3849. */
  3850. public void scrollToStart() {
  3851. getRpcProxy(GridClientRpc.class).scrollToStart();
  3852. }
  3853. /**
  3854. * Scrolls to the end of the last data row.
  3855. */
  3856. public void scrollToEnd() {
  3857. getRpcProxy(GridClientRpc.class).scrollToEnd();
  3858. }
  3859. @Override
  3860. protected GridState getState() {
  3861. return getState(true);
  3862. }
  3863. @Override
  3864. protected GridState getState(boolean markAsDirty) {
  3865. return (GridState) super.getState(markAsDirty);
  3866. }
  3867. /**
  3868. * Sets the column resize mode to use. The default mode is
  3869. * {@link ColumnResizeMode#ANIMATED}.
  3870. *
  3871. * @param mode
  3872. * a ColumnResizeMode value
  3873. * @since 7.7.5
  3874. */
  3875. public void setColumnResizeMode(ColumnResizeMode mode) {
  3876. getState().columnResizeMode = mode;
  3877. }
  3878. /**
  3879. * Returns the current column resize mode. The default mode is
  3880. * {@link ColumnResizeMode#ANIMATED}.
  3881. *
  3882. * @return a ColumnResizeMode value
  3883. * @since 7.7.5
  3884. */
  3885. public ColumnResizeMode getColumnResizeMode() {
  3886. return getState(false).columnResizeMode;
  3887. }
  3888. /**
  3889. * Creates a new Editor instance. Can be overridden to create a custom
  3890. * Editor. If the Editor is a {@link AbstractGridExtension}, it will be
  3891. * automatically added to {@link DataCommunicator}.
  3892. *
  3893. * @return editor
  3894. */
  3895. protected Editor<T> createEditor() {
  3896. return new EditorImpl<>(propertySet);
  3897. }
  3898. private void addExtensionComponent(Component c) {
  3899. if (extensionComponents.add(c)) {
  3900. c.setParent(this);
  3901. markAsDirty();
  3902. }
  3903. }
  3904. private void removeExtensionComponent(Component c) {
  3905. if (extensionComponents.remove(c)) {
  3906. c.setParent(null);
  3907. markAsDirty();
  3908. }
  3909. }
  3910. private void fireColumnReorderEvent(boolean userOriginated) {
  3911. fireEvent(new ColumnReorderEvent(this, userOriginated));
  3912. }
  3913. private void fireColumnResizeEvent(Column<?, ?> column,
  3914. boolean userOriginated) {
  3915. fireEvent(new ColumnResizeEvent(this, column, userOriginated));
  3916. }
  3917. @Override
  3918. protected void readItems(Element design, DesignContext context) {
  3919. // Grid handles reading of items in Grid#readData
  3920. }
  3921. @Override
  3922. public DataProvider<T, ?> getDataProvider() {
  3923. return internalGetDataProvider();
  3924. }
  3925. @Override
  3926. public void setDataProvider(DataProvider<T, ?> dataProvider) {
  3927. internalSetDataProvider(dataProvider);
  3928. }
  3929. /**
  3930. * Sets a CallbackDataProvider using the given fetch items callback and a
  3931. * size callback.
  3932. * <p>
  3933. * This method is a shorthand for making a {@link CallbackDataProvider} that
  3934. * handles a partial {@link Query} object.
  3935. *
  3936. * @param fetchItems
  3937. * a callback for fetching items
  3938. * @param sizeCallback
  3939. * a callback for getting the count of items
  3940. *
  3941. * @see CallbackDataProvider
  3942. * @see #setDataProvider(DataProvider)
  3943. */
  3944. public void setDataProvider(FetchItemsCallback<T> fetchItems,
  3945. SerializableSupplier<Integer> sizeCallback) {
  3946. internalSetDataProvider(
  3947. new CallbackDataProvider<>(
  3948. q -> fetchItems.fetchItems(q.getSortOrders(),
  3949. q.getOffset(), q.getLimit()),
  3950. q -> sizeCallback.get()));
  3951. }
  3952. @Override
  3953. protected void doReadDesign(Element design, DesignContext context) {
  3954. Attributes attrs = design.attributes();
  3955. if (design.hasAttr(DECLARATIVE_DATA_ITEM_TYPE)) {
  3956. String itemType = design.attr(DECLARATIVE_DATA_ITEM_TYPE);
  3957. setBeanType(itemType);
  3958. }
  3959. if (attrs.hasKey("selection-mode")) {
  3960. setSelectionMode(DesignAttributeHandler.readAttribute(
  3961. "selection-mode", attrs, SelectionMode.class));
  3962. }
  3963. Attributes attr = design.attributes();
  3964. if (attr.hasKey("selection-allowed")) {
  3965. setReadOnly(DesignAttributeHandler
  3966. .readAttribute("selection-allowed", attr, Boolean.class));
  3967. }
  3968. if (attrs.hasKey("rows")) {
  3969. setHeightByRows(DesignAttributeHandler.readAttribute("rows", attrs,
  3970. double.class));
  3971. }
  3972. readStructure(design, context);
  3973. // Read frozen columns after columns are read.
  3974. if (attrs.hasKey("frozen-columns")) {
  3975. setFrozenColumnCount(DesignAttributeHandler
  3976. .readAttribute("frozen-columns", attrs, int.class));
  3977. }
  3978. }
  3979. /**
  3980. * Sets the bean type to use for property mapping.
  3981. * <p>
  3982. * This method is responsible also for setting or updating the property set
  3983. * so that it matches the given bean type.
  3984. * <p>
  3985. * Protected mostly for Designer needs, typically should not be overridden
  3986. * or even called.
  3987. *
  3988. * @param beanTypeClassName
  3989. * the fully qualified class name of the bean type
  3990. *
  3991. * @since 8.0.3
  3992. */
  3993. @SuppressWarnings("unchecked")
  3994. protected void setBeanType(String beanTypeClassName) {
  3995. setBeanType((Class<T>) resolveClass(beanTypeClassName));
  3996. }
  3997. /**
  3998. * Sets the bean type to use for property mapping.
  3999. * <p>
  4000. * This method is responsible also for setting or updating the property set
  4001. * so that it matches the given bean type.
  4002. * <p>
  4003. * Protected mostly for Designer needs, typically should not be overridden
  4004. * or even called.
  4005. *
  4006. * @param beanType
  4007. * the bean type class
  4008. *
  4009. * @since 8.0.3
  4010. */
  4011. protected void setBeanType(Class<T> beanType) {
  4012. this.beanType = beanType;
  4013. setPropertySet(BeanPropertySet.get(beanType));
  4014. }
  4015. private Class<?> resolveClass(String qualifiedClassName) {
  4016. try {
  4017. Class<?> resolvedClass = Class.forName(qualifiedClassName, true,
  4018. VaadinServiceClassLoaderUtil.findDefaultClassLoader());
  4019. return resolvedClass;
  4020. } catch (ClassNotFoundException | SecurityException e) {
  4021. throw new IllegalArgumentException(
  4022. "Unable to find class " + qualifiedClassName, e);
  4023. }
  4024. }
  4025. @Override
  4026. protected void doWriteDesign(Element design, DesignContext designContext) {
  4027. Attributes attr = design.attributes();
  4028. if (this.beanType != null) {
  4029. design.attr(DECLARATIVE_DATA_ITEM_TYPE,
  4030. this.beanType.getCanonicalName());
  4031. }
  4032. DesignAttributeHandler.writeAttribute("selection-allowed", attr,
  4033. isReadOnly(), false, Boolean.class, designContext);
  4034. Attributes attrs = design.attributes();
  4035. Grid<?> defaultInstance = designContext.getDefaultInstance(this);
  4036. DesignAttributeHandler.writeAttribute("frozen-columns", attrs,
  4037. getFrozenColumnCount(), defaultInstance.getFrozenColumnCount(),
  4038. int.class, designContext);
  4039. if (HeightMode.ROW.equals(getHeightMode())) {
  4040. DesignAttributeHandler.writeAttribute("rows", attrs,
  4041. getHeightByRows(), defaultInstance.getHeightByRows(),
  4042. double.class, designContext);
  4043. }
  4044. SelectionMode mode = getSelectionMode();
  4045. if (mode != null) {
  4046. DesignAttributeHandler.writeAttribute("selection-mode", attrs, mode,
  4047. SelectionMode.SINGLE, SelectionMode.class, designContext);
  4048. }
  4049. writeStructure(design, designContext);
  4050. }
  4051. @Override
  4052. protected T deserializeDeclarativeRepresentation(String item) {
  4053. if (item == null) {
  4054. return super.deserializeDeclarativeRepresentation(
  4055. UUID.randomUUID().toString());
  4056. }
  4057. return super.deserializeDeclarativeRepresentation(new String(item));
  4058. }
  4059. @Override
  4060. protected boolean isReadOnly() {
  4061. SelectionMode selectionMode = getSelectionMode();
  4062. if (SelectionMode.SINGLE.equals(selectionMode)) {
  4063. return asSingleSelect().isReadOnly();
  4064. }
  4065. if (SelectionMode.MULTI.equals(selectionMode)) {
  4066. return asMultiSelect().isReadOnly();
  4067. }
  4068. return false;
  4069. }
  4070. @Override
  4071. protected void setReadOnly(boolean readOnly) {
  4072. SelectionMode selectionMode = getSelectionMode();
  4073. if (SelectionMode.SINGLE.equals(selectionMode)) {
  4074. asSingleSelect().setReadOnly(readOnly);
  4075. } else if (SelectionMode.MULTI.equals(selectionMode)) {
  4076. asMultiSelect().setReadOnly(readOnly);
  4077. }
  4078. }
  4079. private void readStructure(Element design, DesignContext context) {
  4080. if (design.children().isEmpty()) {
  4081. return;
  4082. }
  4083. if (design.children().size() > 1
  4084. || !design.child(0).tagName().equals("table")) {
  4085. throw new DesignException(
  4086. "Grid needs to have a table element as its only child");
  4087. }
  4088. Element table = design.child(0);
  4089. Elements colgroups = table.getElementsByTag("colgroup");
  4090. if (colgroups.size() != 1) {
  4091. throw new DesignException(
  4092. "Table element in declarative Grid needs to have a"
  4093. + " colgroup defining the columns used in Grid");
  4094. }
  4095. List<DeclarativeValueProvider<T>> providers = new ArrayList<>();
  4096. for (Element col : colgroups.get(0).getElementsByTag("col")) {
  4097. String id = DesignAttributeHandler.readAttribute("column-id",
  4098. col.attributes(), null, String.class);
  4099. // If there is a property with a matching name available,
  4100. // map to that
  4101. Optional<PropertyDefinition<T, ?>> property = propertySet
  4102. .getProperties().filter(p -> p.getName().equals(id))
  4103. .findFirst();
  4104. Column<T, ?> column;
  4105. if (property.isPresent()) {
  4106. column = addColumn(id);
  4107. } else {
  4108. DeclarativeValueProvider<T> provider = new DeclarativeValueProvider<>();
  4109. column = createColumn(provider, ValueProvider.identity(),
  4110. new HtmlRenderer());
  4111. addColumn(getGeneratedIdentifier(), column);
  4112. if (id != null) {
  4113. column.setId(id);
  4114. }
  4115. providers.add(provider);
  4116. }
  4117. column.readDesign(col, context);
  4118. }
  4119. for (Element child : table.children()) {
  4120. if (child.tagName().equals("thead")) {
  4121. getHeader().readDesign(child, context);
  4122. } else if (child.tagName().equals("tbody")) {
  4123. readData(child, providers);
  4124. } else if (child.tagName().equals("tfoot")) {
  4125. getFooter().readDesign(child, context);
  4126. }
  4127. }
  4128. // Sync default header captions to column captions
  4129. if (getDefaultHeaderRow() != null) {
  4130. for (Column<T, ?> c : getColumns()) {
  4131. HeaderCell headerCell = getDefaultHeaderRow().getCell(c);
  4132. if (headerCell.getCellType() == GridStaticCellType.TEXT) {
  4133. c.setCaption(headerCell.getText());
  4134. }
  4135. }
  4136. }
  4137. }
  4138. /**
  4139. * Reads the declarative representation of a grid's data from the given
  4140. * element and stores it in the given {@link DeclarativeValueProvider}s.
  4141. * Each member in the list of value providers corresponds to a column in the
  4142. * grid.
  4143. *
  4144. * @since 8.1
  4145. *
  4146. * @param body
  4147. * the element to read data from
  4148. * @param providers
  4149. * list of {@link DeclarativeValueProvider}s to store the data of
  4150. * each column to
  4151. */
  4152. protected void readData(Element body,
  4153. List<DeclarativeValueProvider<T>> providers) {
  4154. getSelectionModel().deselectAll();
  4155. List<T> items = new ArrayList<>();
  4156. List<T> selectedItems = new ArrayList<>();
  4157. for (Element row : body.children()) {
  4158. T item = deserializeDeclarativeRepresentation(row.attr("item"));
  4159. items.add(item);
  4160. if (row.hasAttr("selected")) {
  4161. selectedItems.add(item);
  4162. }
  4163. Elements cells = row.children();
  4164. int i = 0;
  4165. for (Element cell : cells) {
  4166. providers.get(i).addValue(item, cell.html());
  4167. i++;
  4168. }
  4169. }
  4170. setItems(items);
  4171. selectedItems.forEach(getSelectionModel()::select);
  4172. }
  4173. private void writeStructure(Element design, DesignContext designContext) {
  4174. if (getColumns().isEmpty()) {
  4175. return;
  4176. }
  4177. Element tableElement = design.appendElement("table");
  4178. Element colGroup = tableElement.appendElement("colgroup");
  4179. getColumns().forEach(column -> column
  4180. .writeDesign(colGroup.appendElement("col"), designContext));
  4181. // Always write thead. Reads correctly when there no header rows
  4182. getHeader().writeDesign(tableElement.appendElement("thead"),
  4183. designContext);
  4184. if (designContext.shouldWriteData(this)) {
  4185. Element bodyElement = tableElement.appendElement("tbody");
  4186. writeData(bodyElement, designContext);
  4187. }
  4188. if (getFooter().getRowCount() > 0) {
  4189. getFooter().writeDesign(tableElement.appendElement("tfoot"),
  4190. designContext);
  4191. }
  4192. }
  4193. /**
  4194. * Writes the data contained in this grid. Used when serializing a grid to
  4195. * its declarative representation, if
  4196. * {@link DesignContext#shouldWriteData(Component)} returns {@code true} for
  4197. * the grid that is being written.
  4198. *
  4199. * @since 8.1
  4200. *
  4201. * @param body
  4202. * the body element to write the declarative representation of
  4203. * data to
  4204. * @param designContext
  4205. * the design context
  4206. *
  4207. * @since 8.1
  4208. */
  4209. protected void writeData(Element body, DesignContext designContext) {
  4210. getDataProvider().fetch(new Query<>())
  4211. .forEach(item -> writeRow(body, item, designContext));
  4212. }
  4213. private void writeRow(Element container, T item, DesignContext context) {
  4214. Element tableRow = container.appendElement("tr");
  4215. tableRow.attr("item", serializeDeclarativeRepresentation(item));
  4216. if (getSelectionModel().isSelected(item)) {
  4217. tableRow.attr("selected", true);
  4218. }
  4219. for (Column<T, ?> column : getColumns()) {
  4220. Object value = column.valueProvider.apply(item);
  4221. tableRow.appendElement("td")
  4222. .append(Optional.ofNullable(value).map(Object::toString)
  4223. .map(DesignFormatter::encodeForTextNode)
  4224. .orElse(""));
  4225. }
  4226. }
  4227. private SelectionMode getSelectionMode() {
  4228. GridSelectionModel<T> selectionModel = getSelectionModel();
  4229. SelectionMode mode = null;
  4230. if (selectionModel.getClass().equals(SingleSelectionModelImpl.class)) {
  4231. mode = SelectionMode.SINGLE;
  4232. } else if (selectionModel.getClass()
  4233. .equals(MultiSelectionModelImpl.class)) {
  4234. mode = SelectionMode.MULTI;
  4235. } else if (selectionModel.getClass().equals(NoSelectionModel.class)) {
  4236. mode = SelectionMode.NONE;
  4237. }
  4238. return mode;
  4239. }
  4240. /**
  4241. * Sets a user-defined identifier for given column.
  4242. *
  4243. * @see Column#setId(String)
  4244. *
  4245. * @param column
  4246. * the column
  4247. * @param id
  4248. * the user-defined identifier
  4249. */
  4250. protected void setColumnId(String id, Column<T, ?> column) {
  4251. if (columnIds.containsKey(id)) {
  4252. throw new IllegalArgumentException("Duplicate ID for columns");
  4253. }
  4254. columnIds.put(id, column);
  4255. }
  4256. @Override
  4257. protected Collection<String> getCustomAttributes() {
  4258. Collection<String> result = super.getCustomAttributes();
  4259. // "rename" for frozen column count
  4260. result.add("frozen-column-count");
  4261. result.add("frozen-columns");
  4262. // "rename" for height-mode
  4263. result.add("height-by-rows");
  4264. result.add("rows");
  4265. // add a selection-mode attribute
  4266. result.add("selection-mode");
  4267. return result;
  4268. }
  4269. /**
  4270. * Returns a column identified by its internal id. This id should not be
  4271. * confused with the user-defined identifier.
  4272. *
  4273. * @param columnId
  4274. * the internal id of column
  4275. * @return column identified by internal id
  4276. */
  4277. protected Column<T, ?> getColumnByInternalId(String columnId) {
  4278. return columnKeys.get(columnId);
  4279. }
  4280. /**
  4281. * Returns the internal id for given column. This id should not be confused
  4282. * with the user-defined identifier.
  4283. *
  4284. * @param column
  4285. * the column
  4286. * @return internal id of given column
  4287. */
  4288. protected String getInternalIdForColumn(Column<T, ?> column) {
  4289. return column.getInternalId();
  4290. }
  4291. private void setSortOrder(List<GridSortOrder<T>> order,
  4292. boolean userOriginated) {
  4293. Objects.requireNonNull(order, "Sort order list cannot be null");
  4294. // Update client state to display sort order.
  4295. List<String> sortColumns = new ArrayList<>();
  4296. List<SortDirection> directions = new ArrayList<>();
  4297. order.stream().forEach(sortOrder -> {
  4298. sortColumns.add(sortOrder.getSorted().getInternalId());
  4299. directions.add(sortOrder.getDirection());
  4300. });
  4301. getState().sortColumns = sortColumns.toArray(new String[0]);
  4302. getState().sortDirs = directions.toArray(new SortDirection[0]);
  4303. sortOrder.clear();
  4304. sortOrder.addAll(order);
  4305. sort(userOriginated);
  4306. }
  4307. private void sort(boolean userOriginated) {
  4308. // Set sort orders
  4309. // In-memory comparator
  4310. getDataCommunicator().setInMemorySorting(createSortingComparator());
  4311. // Back-end sort properties
  4312. List<QuerySortOrder> sortProperties = new ArrayList<>();
  4313. sortOrder.stream().map(
  4314. order -> order.getSorted().getSortOrder(order.getDirection()))
  4315. .forEach(s -> s.forEach(sortProperties::add));
  4316. getDataCommunicator().setBackEndSorting(sortProperties);
  4317. // Close grid editor if it's open.
  4318. if (getEditor().isOpen()) {
  4319. getEditor().cancel();
  4320. }
  4321. fireEvent(new SortEvent<>(this, new ArrayList<>(sortOrder),
  4322. userOriginated));
  4323. }
  4324. /**
  4325. * Creates a comparator for grid to sort rows.
  4326. *
  4327. * @return the comparator based on column sorting information.
  4328. */
  4329. protected SerializableComparator<T> createSortingComparator() {
  4330. /*
  4331. * thenComparing is defined to return a serializable comparator as long
  4332. * as both original comparators are also serializable
  4333. */
  4334. BinaryOperator<SerializableComparator<T>> operator = (comparator1,
  4335. comparator2) -> comparator1.thenComparing(comparator2)::compare;
  4336. return sortOrder.stream().map(
  4337. order -> order.getSorted().getComparator(order.getDirection()))
  4338. .reduce((x, y) -> 0, operator);
  4339. }
  4340. @Override
  4341. protected void internalSetDataProvider(DataProvider<T, ?> dataProvider) {
  4342. super.internalSetDataProvider(dataProvider);
  4343. for (Column<T, ?> column : getColumns()) {
  4344. column.updateSortable();
  4345. }
  4346. }
  4347. }