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

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