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

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