├── .gitignore ├── LICENSE ├── README.md ├── assembly ├── MANIFEST.MF └── assembly.xml ├── pom.xml └── src ├── main ├── java │ └── org │ │ └── vaadin │ │ └── gatanaso │ │ ├── MultiselectComboBox.java │ │ └── MultiselectComboBoxDataCommunicator.java └── resources │ └── META-INF │ └── resources │ └── frontend │ └── multiselectComboBoxConnector.js └── test └── java └── org └── vaadin └── gatanaso └── MultiselectComboBoxTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Maven files 2 | target/ 3 | 4 | # Eclipse files 5 | .project 6 | .settings 7 | .classpath 8 | 9 | # IntelliJ IDEA files 10 | .idea/ 11 | *.iml 12 | 13 | # generated/updated by the flow-maven-plugin 14 | node_modules 15 | package*.json 16 | webpack.config.js 17 | webpack.generated.js 18 | tsconfig.json -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Published on Vaadin Directory](https://img.shields.io/badge/Vaadin%20Directory-published-00b4f0.svg)](https://vaadin.com/directory/component/multiselect-combo-box) 2 | [![Build Status](https://travis-ci.org/gatanaso/multiselect-combo-box-flow.svg?branch=master)](https://travis-ci.org/gatanaso/multiselect-combo-box-flow) 3 | [![Version on Vaadin Directory](http://img.shields.io/vaadin-directory/version/multiselect-combo-box.svg)](https://vaadin.com/directory/component/multiselect-combo-box) 4 | [![Stars on vaadin.com/directory](https://img.shields.io/vaadin-directory/star/multiselect-combo-box.svg)](https://vaadin.com/directory/component/multiselect-combo-box) 5 | 6 | # MultiselectComboBox 7 | A multi select combo box component for Vaadin Flow. 8 | 9 | Integration of of the [multiselect-combo-box](https://github.com/gatanaso/multiselect-combo-box) web component. 10 | 11 | #### [Live Demo ↗](https://multiselect-combo-box-flow.herokuapp.com/) 12 | 13 | ## Install 14 | 15 | Add the `multiselect-combo-box-flow dependency` to your `pom.xml`: 16 | ```xml 17 | 18 | org.vaadin.gatanaso 19 | multiselect-combo-box-flow 20 | 4.0.0-rc2 21 | 22 | ``` 23 | 24 | Add the `vaadin-addons` repository: 25 | ```xml 26 | 27 | vaadin-addons 28 | http://maven.vaadin.com/vaadin-addons 29 | 30 | ``` 31 | 32 | ## Basic Usage 33 | 34 | Create a `MultiselectComboBox` and add items 35 | ```java 36 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox(); 37 | 38 | multiselectComboBox.setLabel("Select items"); 39 | 40 | multiselectComboBox.setItems("Item 1", "Item 2", "Item 3", "Item 4"); 41 | ``` 42 | 43 | Add a value change listener (invoked when the selected items/value is changed): 44 | ```java 45 | multiselectComboBox.addValueChangeListener(event -> { 46 | // handle value change 47 | }); 48 | ``` 49 | 50 | Get the selected items/value: 51 | ```java 52 | // set of selected values, or an empty set if none selected 53 | Set value = multiselectComboBox.getValue(); 54 | ``` 55 | 56 | `MultiselectComboBox` also implements the [MultiSelect](https://vaadin.com/api/platform/12.0.3/com/vaadin/flow/data/selection/MultiSelect.html) interface, 57 | which makes it easy to listen for selection changes: 58 | ```java 59 | multiselectComboBox.addSelectionListener(event -> { 60 | event.getAddedSelection(); // get added items 61 | event.getRemovedSelection() // get removed items 62 | }); 63 | ``` 64 | 65 | ## Object items 66 | 67 | The `MultiselectComboBox` supports object items. Given the following `User` class: 68 | ```java 69 | class User { 70 | private String name; 71 | private String username; 72 | private String email; 73 | 74 | public User(String name, String username, String email) { 75 | this.username = username; 76 | this.email = email; 77 | } 78 | 79 | // getters and setters intentionally omitted for brevity 80 | 81 | @Override 82 | public String toString() { 83 | return name; 84 | } 85 | } 86 | ``` 87 | 88 | Create a `MultiselectComboBox` of `User`s: 89 | ```java 90 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox(); 91 | 92 | multiselectComboBox.setLabel("Select users"); 93 | 94 | List users = Arrays.asList( 95 | new User("Leanne Graham","leanne","leanne@demo.dev"), 96 | new User("Ervin Howell","ervin","ervin@demo.dev"), 97 | new User("Samantha Doe","samantha","samantha@demo.dev") 98 | ); 99 | 100 | // by default uses `User.toString()` to generate item labels 101 | multiselectComboBox.setItems(users); 102 | ``` 103 | 104 | The `MultiselectComboBox` uses the `toString()` method to generate the item labels by default. 105 | This can be overridden by setting an item label generator: 106 | ```java 107 | // use the user email as an item label 108 | multiselectComboBox.setItemLabelGenerator(User::getEmail) 109 | ``` 110 | 111 | ## Version information 112 | * 4.x.x - the version for Vaadin 22+ 113 | * 3.x.x - the version for Vaadin 16 and Vaadin 15 114 | * 2.x.x - the version for Vaadin 14 (LTS) 115 | * 1.x.x. - the version for Vaadin 13 and Vaadin 12 116 | 117 | ## Branch information 118 | * `master` the latest version for Vaadin 22+ 119 | * `V14` the version for Vaadin 14 (LTS) 120 | 121 | ## Web Component 122 | The `` web component is available on [npm](https://www.npmjs.com/package/multiselect-combo-box), 123 | the [Vaadin Directory](https://vaadin.com/directory/component/gatanasomultiselect-combo-box) and [GitHub](https://github.com/gatanaso/multiselect-combo-box). 124 | -------------------------------------------------------------------------------- /assembly/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Vaadin-Package-Version: 1 3 | Vaadin-Addon: ${project.build.finalName}.${project.packaging} 4 | Implementation-Vendor: ${organization.name} 5 | Implementation-Title: ${project.name} 6 | Implementation-Version: ${project.version} 7 | -------------------------------------------------------------------------------- /assembly/assembly.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | multiselect-combo-box-flow 7 | 8 | 9 | zip 10 | 11 | 12 | 13 | false 14 | 15 | 16 | 17 | .. 18 | 19 | LICENSE 20 | README.md 21 | 22 | 23 | 24 | target 25 | 26 | 27 | *.jar 28 | *.pdf 29 | 30 | 31 | 32 | 33 | 34 | 36 | 37 | assembly/MANIFEST.MF 38 | META-INF 39 | true 40 | 41 | 42 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | 4 | org.vaadin.gatanaso 5 | multiselect-combo-box-flow 6 | 4.0.0-rc2 7 | Multiselect Combo Box 8 | Integration of multiselect-combo-box for Vaadin platform 9 | 10 | 11 | 22.0.0 12 | 1.8 13 | 1.8 14 | UTF-8 15 | UTF-8 16 | 17 | 18 | Goran Atanasovski 19 | 20 | 21 | 22 | Apache 2 23 | http://www.apache.org/licenses/LICENSE-2.0.txt 24 | repo 25 | 26 | 27 | 28 | 29 | 30 | com.vaadin 31 | vaadin-bom 32 | pom 33 | import 34 | ${vaadin.version} 35 | 36 | 37 | 38 | 39 | 40 | 41 | Vaadin Directory 42 | http://maven.vaadin.com/vaadin-addons 43 | 44 | 45 | 46 | Vaadin prereleases 47 | http://maven.vaadin.com/vaadin-prereleases 48 | 49 | 50 | 51 | vaadin-snapshots 52 | https://oss.sonatype.org/content/repositories/vaadin-snapshots/ 53 | 54 | 55 | 56 | 57 | 58 | 59 | Vaadin prereleases 60 | https://maven.vaadin.com/vaadin-prereleases 61 | 62 | 63 | vaadin-snapshots 64 | https://oss.sonatype.org/content/repositories/vaadin-snapshots/ 65 | false 66 | 67 | 68 | 69 | 70 | 71 | com.vaadin 72 | vaadin-core 73 | 74 | 75 | 76 | org.slf4j 77 | slf4j-simple 78 | test 79 | 80 | 81 | junit 82 | junit 83 | 4.13.1 84 | test 85 | 86 | 87 | org.hamcrest 88 | hamcrest-core 89 | 90 | 91 | 92 | 93 | org.hamcrest 94 | hamcrest-library 95 | 1.3 96 | test 97 | 98 | 99 | 100 | 101 | 102 | 103 | org.apache.maven.plugins 104 | maven-jar-plugin 105 | 3.1.2 106 | 107 | 108 | true 109 | 110 | false 111 | true 112 | 113 | 114 | 1 115 | 116 | 117 | 118 | 119 | META-INF/VAADIN/config/flow-build-info.json 120 | 121 | 122 | 123 | 124 | com.vaadin 125 | vaadin-maven-plugin 126 | ${vaadin.version} 127 | 128 | 129 | 130 | prepare-frontend 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | directory 141 | 142 | 143 | 144 | org.apache.maven.plugins 145 | maven-assembly-plugin 146 | 3.1.0 147 | 148 | false 149 | 150 | assembly/assembly.xml 151 | 152 | 153 | 154 | 155 | 156 | single 157 | 158 | install 159 | 160 | 161 | 162 | 163 | org.apache.maven.plugins 164 | maven-source-plugin 165 | 3.0.1 166 | 167 | 168 | attach-sources 169 | verify 170 | 171 | jar-no-fork 172 | 173 | 174 | 175 | 176 | 177 | org.apache.maven.plugins 178 | maven-javadoc-plugin 179 | 3.0.1 180 | 181 | 182 | attach-javadocs 183 | verify 184 | 185 | jar 186 | 187 | 188 | 189 | 190 | true 191 | -Xdoclint:none 192 | 193 | 194 | 195 | 196 | 197 | 198 | -------------------------------------------------------------------------------- /src/main/java/org/vaadin/gatanaso/MultiselectComboBox.java: -------------------------------------------------------------------------------- 1 | package org.vaadin.gatanaso; 2 | 3 | import java.io.Serializable; 4 | import java.util.ArrayList; 5 | import java.util.Arrays; 6 | import java.util.Collection; 7 | import java.util.Collections; 8 | import java.util.HashSet; 9 | import java.util.List; 10 | import java.util.Objects; 11 | import java.util.Set; 12 | import java.util.function.Function; 13 | import java.util.stream.Stream; 14 | 15 | import com.vaadin.flow.component.AbstractSinglePropertyField; 16 | import com.vaadin.flow.component.ClientCallable; 17 | import com.vaadin.flow.component.ComponentEvent; 18 | import com.vaadin.flow.component.ComponentEventListener; 19 | import com.vaadin.flow.component.DomEvent; 20 | import com.vaadin.flow.component.EventData; 21 | import com.vaadin.flow.component.HasEnabled; 22 | import com.vaadin.flow.component.HasSize; 23 | import com.vaadin.flow.component.HasStyle; 24 | import com.vaadin.flow.component.HasTheme; 25 | import com.vaadin.flow.component.HasValidation; 26 | import com.vaadin.flow.component.ItemLabelGenerator; 27 | import com.vaadin.flow.component.Synchronize; 28 | import com.vaadin.flow.component.Tag; 29 | import com.vaadin.flow.component.UI; 30 | import com.vaadin.flow.component.dependency.JsModule; 31 | import com.vaadin.flow.component.dependency.NpmPackage; 32 | import com.vaadin.flow.data.binder.HasFilterableDataProvider; 33 | import com.vaadin.flow.data.provider.ArrayUpdater; 34 | import com.vaadin.flow.data.provider.CallbackDataProvider; 35 | import com.vaadin.flow.data.provider.CompositeDataGenerator; 36 | import com.vaadin.flow.data.provider.DataChangeEvent; 37 | import com.vaadin.flow.data.provider.DataKeyMapper; 38 | import com.vaadin.flow.data.provider.DataProvider; 39 | import com.vaadin.flow.data.provider.ListDataProvider; 40 | import com.vaadin.flow.data.provider.Query; 41 | import com.vaadin.flow.data.renderer.Renderer; 42 | import com.vaadin.flow.data.renderer.Rendering; 43 | import com.vaadin.flow.data.selection.MultiSelect; 44 | import com.vaadin.flow.data.selection.MultiSelectionEvent; 45 | import com.vaadin.flow.data.selection.MultiSelectionListener; 46 | import com.vaadin.flow.dom.Element; 47 | import com.vaadin.flow.function.SerializableBiPredicate; 48 | import com.vaadin.flow.function.SerializableConsumer; 49 | import com.vaadin.flow.function.SerializableFunction; 50 | import com.vaadin.flow.internal.JsonUtils; 51 | import com.vaadin.flow.shared.Registration; 52 | 53 | import elemental.json.Json; 54 | import elemental.json.JsonArray; 55 | import elemental.json.JsonObject; 56 | import elemental.json.JsonValue; 57 | 58 | /** 59 | * A multiselection component where items are displayed in a drop-down list. 60 | * 61 | *

62 | * This is the server-side component for the `multiselect-combo-box` 63 | * web component. It contains the same features as the web component, such as 64 | * displaying, selection and filtering of multiple items from a drop-down list. 65 | *

66 | * 67 | *

68 | * MultiselectComboBox supports lazy loading. This means that when using large 69 | * data sets, items are requested from the server one "page" at a time when the 70 | * user scrolls down the overlay. The number of items in one page is by default 71 | * 50, and can be changed with {@link #setPageSize(int)}. 72 | *

73 | * MultiselectComboBox can do filtering either in the browser or in the server. 74 | * When MultiselectComboBox has only a relatively small set of items, the 75 | * filtering will happen in the browser, allowing smooth user-experience. When 76 | * the size of the data set is larger than the {@code pageSize}, the 77 | * web component doesn't necessarily have all the data available and it will make 78 | * requests to the server to handle the filtering. Also, if you have defined 79 | * custom filtering logic, with eg. {@link #setItems(ItemFilter, Collection)}, 80 | * filtering will happen in the server. To enable client-side filtering with 81 | * larger data sets, you can override the {@code pageSize} to be bigger than the 82 | * size of your data set. However, then the full data set will be sent to the 83 | * client immediately and you will lose the benefits of lazy loading. 84 | * 85 | * @param 86 | * the type of the items to be inserted in the multiselect combo box 87 | * 88 | * @author gatanaso 89 | */ 90 | @Tag("multiselect-combo-box") 91 | @NpmPackage(value = "multiselect-combo-box", version = "3.0.0-alpha.2") 92 | @JsModule("multiselect-combo-box/src/multiselect-combo-box.js") 93 | @JsModule("./multiselectComboBoxConnector.js") 94 | public class MultiselectComboBox 95 | extends AbstractSinglePropertyField, Set> 96 | implements HasStyle, HasSize, HasValidation, HasEnabled, HasTheme, 97 | MultiSelect, T>, 98 | HasFilterableDataProvider { 99 | 100 | protected static final String ITEM_VALUE_PATH = "key"; 101 | protected static final String ITEM_LABEL_PATH = "label"; 102 | 103 | private final CompositeDataGenerator dataGenerator = new CompositeDataGenerator<>(); 104 | 105 | /** 106 | * Lazy loading updater, used when calling setDataProvider() 107 | */ 108 | private final ArrayUpdater arrayUpdater = new ArrayUpdater() { 109 | @Override 110 | public Update startUpdate(int sizeChange) { 111 | return new UpdateQueue(sizeChange); 112 | } 113 | 114 | @Override 115 | public void initialize() { 116 | // NO-OP 117 | } 118 | }; 119 | 120 | private MultiselectComboBoxDataCommunicator dataCommunicator; 121 | private Function uniqueKeyDataGenerator; 122 | private ItemLabelGenerator itemLabelGenerator = String::valueOf; 123 | private Registration dataGeneratorRegistration; 124 | 125 | private Renderer renderer; 126 | private boolean renderScheduled; 127 | private Element template; 128 | 129 | private int customValuesListenersCount; 130 | 131 | private SerializableConsumer filterSlot = filter -> { 132 | // Just ignore when setDataProvider has not been called 133 | }; 134 | 135 | // Filter set by the client when requesting data. It's sent back to client 136 | // together with the response so client may know for what filter data is 137 | // provided. 138 | private String lastFilter; 139 | 140 | private UserProvidedFilter userProvidedFilter = UserProvidedFilter.UNDECIDED; 141 | 142 | /** 143 | * Default constructor. Creates an empty multiselect combo box. 144 | */ 145 | public MultiselectComboBox() { 146 | this(50); 147 | } 148 | 149 | /** 150 | * Creates an empty multiselect combo box with the defined page size for 151 | * lazy loading. 152 | *

153 | * The default page size is 50. 154 | *

155 | * The page size is also the largest number of items that can support 156 | * client-side filtering. If you provide more items than the page size, the 157 | * component has to fall back to server-side filtering. 158 | * 159 | * @param pageSize 160 | * the amount of items to request at a time for lazy loading 161 | * @see #setPageSize 162 | */ 163 | public MultiselectComboBox(int pageSize) { 164 | super("selectedItems", Collections.emptySet(), JsonArray.class, 165 | MultiselectComboBox::presentationToModel, 166 | MultiselectComboBox::modelToPresentation); 167 | 168 | dataGenerator.addDataGenerator((item, jsonObject) -> jsonObject 169 | .put(ITEM_LABEL_PATH, generateLabel(item))); 170 | 171 | setItemIdPath(ITEM_VALUE_PATH); 172 | setItemValuePath(ITEM_VALUE_PATH); 173 | setItemLabelPath(ITEM_LABEL_PATH); 174 | setPageSize(pageSize); 175 | 176 | addAttachListener(e -> initConnector()); 177 | 178 | runBeforeClientResponse(ui -> { 179 | // If user didn't provide any data, initialize with empty data set. 180 | if (dataCommunicator == null) { 181 | setItems(); 182 | } 183 | }); 184 | } 185 | 186 | /** 187 | * Creates an empty multiselect combo box with the defined label. 188 | * 189 | * @param label 190 | * the label describing the combo box 191 | */ 192 | public MultiselectComboBox(String label) { 193 | this(); 194 | setLabel(label); 195 | } 196 | 197 | /** 198 | * Creates a multiselect combo box with the defined label and populated with 199 | * the items in the collection. 200 | * 201 | * @param label 202 | * the label describing the combo box 203 | * @param items 204 | * the items to be shown in the list of the combo box 205 | * @see #setItems(Collection) 206 | */ 207 | public MultiselectComboBox(String label, Collection items) { 208 | this(); 209 | setLabel(label); 210 | setItems(items); 211 | } 212 | 213 | /** 214 | * Creates a multiselect combo box with the defined label and populated with 215 | * the items in the array. 216 | * 217 | * @param label 218 | * the label describing the combo box 219 | * @param items 220 | * the items to be shown in the list of the combo box 221 | * @see #setItems(Object...) 222 | */ 223 | @SafeVarargs 224 | public MultiselectComboBox(String label, T... items) { 225 | this(); 226 | setLabel(label); 227 | setItems(items); 228 | } 229 | 230 | private static Set presentationToModel( 231 | MultiselectComboBox multiselectComboBox, 232 | JsonArray presentation) { 233 | 234 | if (presentation == null || multiselectComboBox.dataCommunicator == null) { 235 | return multiselectComboBox.getEmptyValue(); 236 | } 237 | 238 | if (multiselectComboBox.getValue() != null) { 239 | // keep existing value items in keyMapper 240 | multiselectComboBox.getValue().forEach(item -> multiselectComboBox.getKeyMapper().key(item)); 241 | } 242 | 243 | Set set = new HashSet<>(); 244 | for (int i = 0; i < presentation.length(); i++) { 245 | String key = presentation.getObject(i).getString(ITEM_VALUE_PATH); 246 | set.add(multiselectComboBox.getKeyMapper().get(key)); 247 | } 248 | return set; 249 | } 250 | 251 | private static JsonArray modelToPresentation( 252 | MultiselectComboBox multiselectComboBox, Set model) { 253 | JsonArray array = Json.createArray(); 254 | if (model == null || model.isEmpty()) { 255 | return array; 256 | } 257 | 258 | model.stream().map(multiselectComboBox::generateJson) 259 | .forEach(jsonObject -> array.set(array.length(), jsonObject)); 260 | 261 | return array; 262 | } 263 | 264 | @Override 265 | public void setValue(Set value) { 266 | if (dataCommunicator == null) { 267 | if (value == null || value.equals(getEmptyValue())) { 268 | return; 269 | } else { 270 | throw new IllegalStateException( 271 | "Cannot set a value for a MultiselectComboBox without items. " 272 | + "Use setItems or setDataProvider to populate " 273 | + "items into the MultiselectComboBox before setting a value."); 274 | } 275 | } 276 | super.setValue(value); 277 | refreshValue(); 278 | } 279 | 280 | private void refreshValue() { 281 | Set value = getValue(); 282 | if (value == null || value.isEmpty()) { 283 | return; 284 | } 285 | JsonArray selectedItems = modelToPresentation(this, value); 286 | getElement().setPropertyJson("selectedItems", selectedItems); 287 | } 288 | 289 | /** 290 | * Sets the TemplateRenderer responsible to render the individual items in 291 | * the list of possible choices of the MultiselectComboBox. It doesn't affect how the 292 | * selected item is rendered - that can be configured by using 293 | * {@link #setItemLabelGenerator(ItemLabelGenerator)}. 294 | * 295 | * @param renderer 296 | * a renderer for the items in the selection list of the 297 | * MultiselectComboBox, not null 298 | * 299 | * Note that filtering of the MultiselectComboBox is not affected by the renderer that 300 | * is set here. Filtering is done on the original values and can be affected 301 | * by {@link #setItemLabelGenerator(ItemLabelGenerator)}. 302 | */ 303 | public void setRenderer(Renderer renderer) { 304 | Objects.requireNonNull(renderer, "The renderer must not be null"); 305 | this.renderer = renderer; 306 | 307 | if (template == null) { 308 | template = new Element("template"); 309 | getElement().appendChild(template); 310 | } 311 | scheduleRender(); 312 | } 313 | 314 | /** 315 | * Gets the label of the multiselect-combo-box. 316 | * 317 | * @return the label property of the multiselect-combo-box. 318 | */ 319 | public String getLabel() { 320 | return getElement().getProperty("label"); 321 | } 322 | 323 | /** 324 | * Sets the label of the multiselect-combo-box. 325 | * 326 | * @param label 327 | * the String value to set. 328 | */ 329 | public void setLabel(String label) { 330 | getElement().setProperty("label", label == null ? "" : label); 331 | } 332 | 333 | /** 334 | * Gets the title of the multiselect-combo-box. 335 | * 336 | * @return the title property of the multiselect-combo-box. 337 | */ 338 | public String getTitle() { 339 | return getElement().getProperty("title"); 340 | } 341 | 342 | /** 343 | * Gets the placeholder of the {@code multiselect-combo-box}. 344 | * 345 | * @return the placeholder property of the multiselect-combo-box. 346 | */ 347 | public String getPlaceholder() { 348 | return getElement().getProperty("placeholder"); 349 | } 350 | 351 | /** 352 | * Sets the placeholder of the multiselect-combo-box. 353 | * 354 | * @param placeholder 355 | * the String value to set. 356 | */ 357 | public void setPlaceholder(String placeholder) { 358 | getElement().setProperty("placeholder", 359 | placeholder == null ? "" : placeholder); 360 | } 361 | 362 | /** 363 | * Gets the required value of the multiselect-combo-box. 364 | * 365 | * @return true if the component is required, false otherwise. 366 | */ 367 | public boolean isRequired() { 368 | return super.isRequiredIndicatorVisible(); 369 | } 370 | 371 | /** 372 | * Sets the required value of the multiselect-combo-box. 373 | * 374 | * @param required 375 | * the boolean value to set 376 | */ 377 | public void setRequired(boolean required) { 378 | super.setRequiredIndicatorVisible(required); 379 | } 380 | 381 | /** 382 | * Gets the 'compact-mode' property value of the multiselect-combo-box. 383 | * 384 | * @return true if the component is in 'compact-mode', false otherwise. 385 | */ 386 | public boolean isCompactMode() { 387 | return getElement().getProperty("compactMode", false); 388 | } 389 | 390 | /** 391 | * Sets the 'compact-mode' property value of the multiselect-combo-box. 392 | *
393 | *

394 | * When set to {@code true}, the component will use the default compact mode label generator. 395 | * To use a customized label generator, use {@link #setCompactModeLabelGenerator}. 396 | *

397 | * 398 | * @param compactMode 399 | * the boolean value to set 400 | */ 401 | public void setCompactMode(boolean compactMode) { 402 | getElement().setProperty("compactMode", compactMode); 403 | } 404 | 405 | /** 406 | * Gets the 'ordered' property value of the multiselect-combo-box. 407 | * 408 | * @return true if the component is ordered, false otherwise. 409 | */ 410 | public boolean isOrdered() { 411 | return getElement().getProperty("ordered", false); 412 | } 413 | 414 | /** 415 | * Sets the 'ordered' property value of the multiselect-combo-box. 416 | * 417 | * This attribute specifies if the list of selected items should be kept 418 | * ordered in ascending lexical order. 419 | * 420 | * @param ordered 421 | * the boolean value to set 422 | */ 423 | public void setOrdered(boolean ordered) { 424 | getElement().setProperty("ordered", ordered); 425 | } 426 | 427 | /** 428 | * Gets the validity of the multiselect-combo-box. 429 | * 430 | * @return true if the component is invalid, false otherwise. 431 | */ 432 | @Override 433 | @Synchronize(property = "invalid", value = "invalid-changed") 434 | public boolean isInvalid() { 435 | return getElement().getProperty("invalid", false); 436 | } 437 | 438 | /** 439 | * Sets the invalid value of the multiselect-combo-box. 440 | * 441 | * @param invalid 442 | * the boolean value to set. 443 | */ 444 | @Override 445 | public void setInvalid(boolean invalid) { 446 | getElement().setProperty("invalid", invalid); 447 | } 448 | 449 | /** 450 | * Gets the current error message of the multiselect-combo-box. 451 | * 452 | * @return the current error message 453 | */ 454 | public String getErrorMessage() { 455 | return getElement().getProperty("errorMessage"); 456 | } 457 | 458 | /** 459 | * Sets the error message of the multiselect-combo-box. 460 | *

461 | * The error message is displayed when the component is invalid. 462 | * 463 | * @param errorMessage 464 | * the String value to set 465 | */ 466 | @Override 467 | public void setErrorMessage(String errorMessage) { 468 | getElement().setProperty("errorMessage", 469 | errorMessage == null ? "" : errorMessage); 470 | } 471 | 472 | /** 473 | *

474 | * Set to true to display the clear icon which clears the input. 475 | *

476 | * This property is not synchronized automatically from the client side, so 477 | * the returned value may not be the same as in client side. 478 | *

479 | * 480 | * @return the {@code clearButtonVisible} property from the web component 481 | */ 482 | public boolean isClearButtonVisible() { 483 | return getElement().getProperty("clearButtonVisible", false); 484 | } 485 | 486 | /** 487 | *

488 | * Set to true to display the clear icon which clears the input. 489 | *

490 | * 491 | * @param clearButtonVisible 492 | * the boolean value to set 493 | */ 494 | public void setClearButtonVisible(boolean clearButtonVisible) { 495 | getElement().setProperty("clearButtonVisible", clearButtonVisible); 496 | } 497 | 498 | /** 499 | * Gets the value of the configured value separator when in read only mode. 500 | * 501 | * @return the read only value separator. 502 | */ 503 | public String getReadOnlyValueSeparator() { 504 | return getElement().getProperty("readonlyValueSeparator"); 505 | } 506 | 507 | /** 508 | * Sets the value separator when in read only mode. 509 | * 510 | * @param readonlyValueSeparator 511 | * the separator value to set 512 | */ 513 | public void setReadOnlyValueSeparator(String readonlyValueSeparator) { 514 | getElement().setProperty("readonlyValueSeparator", readonlyValueSeparator == null ? "" : readonlyValueSeparator); 515 | } 516 | 517 | private void setItemValuePath(String itemValuePath) { 518 | getElement().setProperty("itemValuePath", 519 | itemValuePath == null ? "" : itemValuePath); 520 | } 521 | 522 | private void setItemLabelPath(String itemLabelPath) { 523 | getElement().setProperty("itemLabelPath", 524 | itemLabelPath == null ? "" : itemLabelPath); 525 | } 526 | 527 | private void setItemIdPath(String itemIdPath) { 528 | getElement().setProperty("itemIdPath", 529 | itemIdPath == null ? "" : itemIdPath); 530 | } 531 | 532 | /** 533 | * Gets the item label generator. 534 | * 535 | * By default, {@link String#valueOf(Object)} is used. 536 | * 537 | * @return the item label generator. 538 | */ 539 | public ItemLabelGenerator getItemLabelGenerator() { 540 | return itemLabelGenerator; 541 | } 542 | 543 | /** 544 | * Sets the item label generator that is used to produce the strings shown 545 | * in the multiselect-combo-box for each item. By default, 546 | * {@link String#valueOf(Object)} is used. 547 | * 548 | * @param itemLabelGenerator 549 | * the item label provider to use, not null 550 | */ 551 | public void setItemLabelGenerator( 552 | ItemLabelGenerator itemLabelGenerator) { 553 | Objects.requireNonNull(itemLabelGenerator, 554 | "The item label generator can not be null"); 555 | this.itemLabelGenerator = itemLabelGenerator; 556 | reset(); 557 | if (getValue() != null) { 558 | refreshValue(); 559 | } 560 | } 561 | 562 | /** 563 | * Sets the page size, which is the number of items requested at a time from 564 | * the data provider. This does not guarantee a maximum query size to the 565 | * backend; when the overlay has room to render more new items than the page 566 | * size, multiple "pages" will be requested at once. 567 | *

568 | * The page size is also the largest number of items that can support 569 | * client-side filtering. If you provide more items than the page size, the 570 | * component has to fall back to server-side filtering. 571 | *

572 | * Setting the page size after the MultiselectComboBox has been rendered 573 | * effectively resets the component, and the current page(s) and sent over 574 | * again. 575 | *

576 | * The default page size is 50. 577 | * 578 | * @param pageSize 579 | * the maximum number of items sent per request, should be 580 | * greater than zero 581 | */ 582 | public void setPageSize(int pageSize) { 583 | if (pageSize < 1) { 584 | throw new IllegalArgumentException( 585 | "Page size should be greater than zero."); 586 | } 587 | getElement().setProperty("pageSize", pageSize); 588 | reset(); 589 | } 590 | 591 | /** 592 | * Gets the page size, which is the number of items fetched at a time from 593 | * the data provider. 594 | *

595 | * The page size is also the largest number of items that can support 596 | * client-side filtering. If you provide more items than the page size, the 597 | * component has to fall back to server-side filtering. 598 | *

599 | * The default page size is 50. 600 | * 601 | * @return the maximum number of items sent per request 602 | * @see #setPageSize 603 | */ 604 | public int getPageSize() { 605 | return getElement().getProperty("pageSize", 50); 606 | } 607 | 608 | /** 609 | * Enables or disables the component firing events for custom string input. 610 | *

611 | * When enabled, a {@link CustomValuesSetEvent} will be fired when the user 612 | * inputs a string value that does not match any existing items and commits 613 | * it eg. by blurring or pressing the enter-key. 614 | *

615 | * Note that MultiselectComboBox doesn't do anything with the custom value string 616 | * automatically. Use the 617 | * {@link #addCustomValuesSetListener(ComponentEventListener)} method to 618 | * determine how the custom value should be handled. For example, when the 619 | * MultiselectComboBox has {@code String} as the value type, you can add a listener 620 | * which sets the custom string as on of the values of the MultiselectComboBox. 621 | * 622 | * @param allowCustomValues 623 | * {@code true} to enable custom values set events, {@code false} 624 | * to disable them 625 | * 626 | * @see #addCustomValuesSetListener(ComponentEventListener) 627 | */ 628 | public void setAllowCustomValues(boolean allowCustomValues) { 629 | getElement().setProperty("allowCustomValues", allowCustomValues); 630 | } 631 | 632 | /** 633 | * If {@code true}, the user can input string values that do not match to 634 | * any existing item labels, which will fire a {@link CustomValuesSetEvent}. 635 | * 636 | * @return {@code true} if the component fires custom value set events, 637 | * {@code false} otherwise 638 | * 639 | * @see #setAllowCustomValues(boolean) 640 | * @see #addCustomValuesSetListener(ComponentEventListener) 641 | */ 642 | public boolean isAllowCustomValues() { 643 | return getElement().getProperty("allowCustomValues", false); 644 | } 645 | 646 | /** 647 | * Gets the data provider used by this {@link MultiselectComboBox}. 648 | * 649 | * @return the data provider, not {@code null} 650 | */ 651 | public DataProvider getDataProvider() { 652 | return dataCommunicator.getDataProvider(); 653 | } 654 | 655 | private void reset() { 656 | lastFilter = null; 657 | if (dataCommunicator != null) { 658 | dataCommunicator.setPageSize(getPageSize()); 659 | dataCommunicator.setRequestedRange(0, 0); 660 | dataCommunicator.reset(); 661 | } 662 | runBeforeClientResponse(ui -> ui.getPage().executeJs( 663 | // If-statement is needed because on the first attach this 664 | // JavaScript is called before initializing the connector. 665 | "if($0.$connector) $0.$connector.reset();", getElement())); 666 | } 667 | 668 | private String generateLabel(T item) { 669 | if (item == null) { 670 | return ""; 671 | } 672 | String label = getItemLabelGenerator().apply(item); 673 | if (label == null) { 674 | throw new IllegalStateException(String.format( 675 | "Got 'null' as a label value for the item '%s'. " 676 | + "'%s' instance may not return 'null' values", 677 | item, ItemLabelGenerator.class.getSimpleName())); 678 | } 679 | return label; 680 | } 681 | 682 | private JsonObject generateJson(T item) { 683 | JsonObject jsonObject = Json.createObject(); 684 | jsonObject.put(ITEM_VALUE_PATH, getKeyMapper().key(item)); 685 | dataGenerator.generateData(item, jsonObject); 686 | return jsonObject; 687 | } 688 | 689 | private void initConnector() { 690 | getElement().executeJs( 691 | "window.Vaadin.Flow.multiselectComboBoxConnector.initLazy(this)"); 692 | } 693 | 694 | private void runBeforeClientResponse(SerializableConsumer command) { 695 | getElement().getNode().runWhenAttached(ui -> ui 696 | .beforeClientResponse(this, context -> command.accept(ui))); 697 | } 698 | 699 | @Override 700 | public void updateSelection(Set addedItems, Set removedItems) { 701 | Set value = new HashSet<>(getValue()); 702 | value.addAll(addedItems); 703 | value.removeAll(removedItems); 704 | setValue(value); 705 | } 706 | 707 | @Override 708 | public Set getSelectedItems() { 709 | return getValue(); 710 | } 711 | 712 | @Override 713 | public Registration addSelectionListener( 714 | MultiSelectionListener, T> listener) { 715 | return addValueChangeListener(event -> listener 716 | .selectionChange(new MultiSelectionEvent<>(this, this, 717 | event.getOldValue(), event.isFromClient()))); 718 | } 719 | 720 | /** 721 | * Adds a listener for the event which is fired when user inputs a string 722 | * value that does not match any existing items and commits it eg. by 723 | * blurring or pressing the enter-key. 724 | *

725 | * Note that MultiselectComboBox doesn't do anything with the custom value string 726 | * automatically. Use this method to determine how the custom value should 727 | * be handled. For example, when the MultiselectComboBox has {@code String} as the 728 | * value type, you can add a listener which sets the custom string as on of the 729 | * values of the MultiselectComboBox. 730 | *

731 | * As a side effect, this makes the MultiselectComboBox allow custom values. If you 732 | * want to disable the firing of custom value set events once the listener 733 | * is added, please disable it explicitly via the 734 | * {@link #setAllowCustomValues(boolean)} method. 735 | *

736 | * The custom value becomes disallowed automatically once the last custom 737 | * value set listener is removed. 738 | * 739 | * @param listener 740 | * the listener to be notified when a new value is filled 741 | * @return a {@link Registration} for removing the event listener 742 | * 743 | * @see #setAllowCustomValues(boolean) 744 | */ 745 | public Registration addCustomValuesSetListener(ComponentEventListener>> listener) { 746 | setAllowCustomValues(true); 747 | customValuesListenersCount++; 748 | Registration registration = addListener(CustomValuesSetEvent.class, (ComponentEventListener) listener); 749 | return new CustomValuesRegistration(registration); 750 | } 751 | 752 | private DataKeyMapper getKeyMapper() { 753 | return dataCommunicator.getKeyMapper(); 754 | } 755 | 756 | private void scheduleRender() { 757 | if (renderScheduled || dataCommunicator == null || renderer == null) { 758 | return; 759 | } 760 | renderScheduled = true; 761 | 762 | runBeforeClientResponse(ui -> { 763 | if (dataGeneratorRegistration != null) { 764 | dataGeneratorRegistration.remove(); 765 | dataGeneratorRegistration = null; 766 | } 767 | 768 | Rendering rendering = renderer.render(getElement(), dataCommunicator.getKeyMapper(), template); 769 | 770 | if (rendering.getDataGenerator().isPresent()) { 771 | dataGeneratorRegistration = dataGenerator 772 | .addDataGenerator(rendering.getDataGenerator().get()); 773 | } 774 | 775 | reset(); 776 | }); 777 | } 778 | 779 | @ClientCallable 780 | private void confirmUpdate(int id) { 781 | dataCommunicator.confirmUpdate(id); 782 | } 783 | 784 | @ClientCallable 785 | private void setRequestedRange(int start, int length, String filter) { 786 | dataCommunicator.setRequestedRange(start, length); 787 | filterSlot.accept(filter); 788 | } 789 | 790 | @ClientCallable 791 | private void resetDataCommunicator() { 792 | dataCommunicator.reset(); 793 | } 794 | 795 | @ClientCallable 796 | private void notifyReady() { 797 | // init data connector when shadow-dom is ready 798 | getElement().executeJs("$0.$connector.initDataConnector()"); 799 | } 800 | 801 | /** 802 | * {@inheritDoc} 803 | *

804 | * Filtering will use a case insensitive match to show all items where the 805 | * filter text is a substring of the label displayed for that item, which 806 | * you can configure with 807 | * {@link #setItemLabelGenerator(ItemLabelGenerator)}. 808 | *

809 | * Filtering will be handled in the client-side if the size of the data set 810 | * is less than the page size. To force client-side filtering with a larger 811 | * data set (at the cost of increased network traffic), you can increase the 812 | * page size with {@link #setPageSize(int)}. 813 | *

814 | * Setting the items creates a new DataProvider, which in turn resets the 815 | * multiselect combo box's value to {@code null}. If you want to add and 816 | * remove items to the current item set without resetting the value, you 817 | * should update the previously set item collection and call 818 | * {@code getDataProvider().refreshAll()}. 819 | */ 820 | @Override 821 | public void setItems(Collection items) { 822 | setDataProvider(DataProvider.ofCollection(items)); 823 | } 824 | 825 | /** 826 | * Sets the data items of this multiselect combo box and a filtering 827 | * function for defining which items are displayed when user types into the 828 | * combo box. 829 | *

830 | * Note that defining a custom filter will force the component to make 831 | * server round trips to handle the filtering. Otherwise, it can handle 832 | * filtering in the client-side, if the size of the data set is less than 833 | * the {@link #setPageSize(int) pageSize}. 834 | *

835 | * Setting the items creates a new DataProvider, which in turn resets the 836 | * combo box's value to {@code null}. If you want to add and remove items to 837 | * the current item set without resetting the value, you should update the 838 | * previously set item collection and call 839 | * {@code getDataProvider().refreshAll()}. 840 | * 841 | * @param itemFilter 842 | * filter to check if an item is shown when user typed some text 843 | * into the MultiselectComboBox 844 | * @param items 845 | * the data items to display 846 | */ 847 | public void setItems(ItemFilter itemFilter, Collection items) { 848 | ListDataProvider listDataProvider = DataProvider.ofCollection(items); 849 | 850 | setDataProvider(itemFilter, listDataProvider); 851 | } 852 | 853 | /** 854 | * Sets the data items of this multiselect combo box and a filtering 855 | * function for defining which items are displayed when user types into the 856 | * combo box. 857 | *

858 | * Note that defining a custom filter will force the component to make 859 | * server round trips to handle the filtering. Otherwise it can handle 860 | * filtering in the client-side, if the size of the data set is less than 861 | * the {@link #setPageSize(int) pageSize}. 862 | *

863 | * Setting the items creates a new DataProvider, which in turn resets the 864 | * combo box's value to {@code null}. If you want to add and remove items to 865 | * the current item set without resetting the value, you should update the 866 | * previously set item collection and call 867 | * {@code getDataProvider().refreshAll()}. 868 | * 869 | * @param itemFilter 870 | * filter to check if an item is shown when user typed some text 871 | * into the MultiselectComboBox 872 | * @param items 873 | * the data items to display 874 | */ 875 | public void setItems(ItemFilter itemFilter, T... items) { 876 | setItems(itemFilter, Arrays.asList(items)); 877 | } 878 | 879 | /** 880 | * {@inheritDoc} 881 | *

882 | * The filter-type of the given data provider must be String so that it can 883 | * handle the filters typed into the MultiselectComboBox by users. If your 884 | * data provider uses some other type of filter, you can provide a function 885 | * which converts the MultiselectComboBox's filter-string into that type via 886 | * {@link #setDataProvider(DataProvider, SerializableFunction)}. Another way 887 | * to do the same thing is to use this method with your data provider 888 | * converted with 889 | * {@link DataProvider#withConvertedFilter(SerializableFunction)}. 890 | *

891 | * Changing the multiselect combo box's data provider resets its current 892 | * value to {@code null}. 893 | */ 894 | @Override 895 | public void setDataProvider(DataProvider dataProvider) { 896 | setDataProvider(dataProvider, SerializableFunction.identity()); 897 | } 898 | 899 | /** 900 | * {@inheritDoc} 901 | *

902 | * MultiselectComboBox triggers filtering queries based on the strings users 903 | * type into the field. For this reason you need to provide the second 904 | * parameter, a function which converts the filter-string typed by the user 905 | * into filter-type used by your data provider. If your data provider 906 | * already supports String as the filter-type, it can be used without a 907 | * converter function via {@link #setDataProvider(DataProvider)}. 908 | *

909 | * Using this method provides the same result as using a data provider 910 | * wrapped with 911 | * {@link DataProvider#withConvertedFilter(SerializableFunction)}. 912 | *

913 | * Changing the multiselect combo box's data provider resets its current 914 | * value to {@code null}. 915 | */ 916 | @Override 917 | public void setDataProvider(DataProvider dataProvider, 918 | SerializableFunction filterConverter) { 919 | 920 | Objects.requireNonNull(dataProvider, 921 | "The data provider can not be null"); 922 | Objects.requireNonNull(filterConverter, 923 | "filterConverter cannot be null"); 924 | 925 | if (userProvidedFilter == UserProvidedFilter.UNDECIDED) { 926 | userProvidedFilter = UserProvidedFilter.YES; 927 | } 928 | 929 | if (dataCommunicator == null) { 930 | dataCommunicator = new MultiselectComboBoxDataCommunicator<>(dataGenerator, 931 | arrayUpdater, data -> getElement() 932 | .callJsFunction("$connector.updateData", data), 933 | getElement().getNode()); 934 | if (uniqueKeyDataGenerator != null) { 935 | dataCommunicator.setUniqueKeyDataGenerator(uniqueKeyDataGenerator); 936 | } 937 | } 938 | 939 | scheduleRender(); 940 | setValue(null); 941 | 942 | SerializableFunction convertOrNull = filterText -> { 943 | if (filterText == null) { 944 | return null; 945 | } 946 | 947 | return filterConverter.apply(filterText); 948 | }; 949 | 950 | SerializableConsumer providerFilterSlot = dataCommunicator 951 | .setDataProvider(dataProvider, convertOrNull.apply(null)); 952 | 953 | filterSlot = filter -> { 954 | if (!Objects.equals(filter, lastFilter)) { 955 | providerFilterSlot.accept(convertOrNull.apply(filter)); 956 | lastFilter = filter; 957 | } 958 | }; 959 | 960 | boolean shouldForceServerSideFiltering = userProvidedFilter == UserProvidedFilter.YES; 961 | 962 | dataProvider.addDataProviderListener(e -> { 963 | if (e instanceof DataChangeEvent.DataRefreshEvent) { 964 | dataCommunicator.refresh( 965 | ((DataChangeEvent.DataRefreshEvent) e).getItem()); 966 | } else { 967 | refreshAllData(shouldForceServerSideFiltering); 968 | } 969 | }); 970 | refreshAllData(shouldForceServerSideFiltering); 971 | 972 | userProvidedFilter = UserProvidedFilter.UNDECIDED; 973 | } 974 | 975 | /** 976 | * Sets a list data provider as the data provider of this multiselect combo 977 | * box. 978 | *

979 | * Filtering will use a case insensitive match to show all items where the 980 | * filter text is a substring of the label displayed for that item, which 981 | * you can configure with 982 | * {@link #setItemLabelGenerator(ItemLabelGenerator)}. 983 | *

984 | * Filtering will be handled in the client-side if the size of the data set 985 | * is less than the page size. To force client-side filtering with a larger 986 | * data set (at the cost of increased network traffic), you can increase the 987 | * page size with {@link #setPageSize(int)}. 988 | *

989 | * Changing the multiselect combo box's data provider resets its current 990 | * value to {@code null}. 991 | * 992 | * @param listDataProvider 993 | * the list data provider to use, not null 994 | */ 995 | public void setDataProvider(ListDataProvider listDataProvider) { 996 | if (userProvidedFilter == UserProvidedFilter.UNDECIDED) { 997 | userProvidedFilter = UserProvidedFilter.NO; 998 | } 999 | 1000 | // Cannot use the case insensitive contains shorthand from 1001 | // ListDataProvider since it wouldn't react to locale changes 1002 | ItemFilter defaultItemFilter = (item, 1003 | filterText) -> generateLabel(item).toLowerCase(getLocale()) 1004 | .contains(filterText.toLowerCase(getLocale())); 1005 | 1006 | setDataProvider(defaultItemFilter, listDataProvider); 1007 | } 1008 | 1009 | /** 1010 | * Sets a CallbackDataProvider using the given fetch items callback and a 1011 | * size callback. 1012 | *

1013 | * This method is a shorthand for making a {@link CallbackDataProvider} that 1014 | * handles a partial Query object. 1015 | *

1016 | * Changing the multiselect combo box's data provider resets its current 1017 | * value to {@code null}. 1018 | * 1019 | * @param fetchItems 1020 | * a callback for fetching items 1021 | * @param sizeCallback 1022 | * a callback for getting the count of items 1023 | * 1024 | * @see CallbackDataProvider 1025 | * @see #setDataProvider(DataProvider) 1026 | */ 1027 | public void setDataProvider(FetchItemsCallback fetchItems, 1028 | SerializableFunction sizeCallback) { 1029 | userProvidedFilter = UserProvidedFilter.YES; 1030 | setDataProvider(new CallbackDataProvider<>( 1031 | q -> fetchItems.fetchItems(q.getFilter().orElse(""), 1032 | q.getOffset(), q.getLimit()), 1033 | q -> sizeCallback.apply(q.getFilter().orElse("")))); 1034 | } 1035 | 1036 | /** 1037 | * Sets a list data provider with an item filter as the data provider of 1038 | * this multiselect combo box. The item filter is used to compare each item 1039 | * to the filter text entered by the user. 1040 | *

1041 | * Note that defining a custom filter will force the component to make 1042 | * server round trips to handle the filtering. Otherwise it can handle 1043 | * filtering in the client-side, if the size of the data set is less than 1044 | * the {@link #setPageSize(int) pageSize}. 1045 | *

1046 | * Changing the multiselect combo box's data provider resets its current 1047 | * value to {@code null}. 1048 | * 1049 | * @param itemFilter 1050 | * filter to check if an item is shown when user typed some text 1051 | * into the MultiselectComboBox 1052 | * @param listDataProvider 1053 | * the list data provider to use, not null 1054 | */ 1055 | public void setDataProvider(ItemFilter itemFilter, 1056 | ListDataProvider listDataProvider) { 1057 | 1058 | Objects.requireNonNull(listDataProvider, 1059 | "List data provider cannot be null"); 1060 | setDataProvider(listDataProvider, 1061 | filterText -> item -> itemFilter.test(item, filterText)); 1062 | } 1063 | 1064 | private void refreshAllData(boolean forceServerSideFiltering) { 1065 | setClientSideFilter(!forceServerSideFiltering && getDataProvider() 1066 | .size(new Query<>()) <= getPageSizeDouble()); 1067 | 1068 | reset(); 1069 | } 1070 | 1071 | private double getPageSizeDouble() { 1072 | return getElement().getProperty("pageSize", 0.0); 1073 | } 1074 | 1075 | private void setClientSideFilter(boolean clientSideFilter) { 1076 | getElement().setProperty("_clientSideFilter", clientSideFilter); 1077 | } 1078 | 1079 | private enum UserProvidedFilter { 1080 | UNDECIDED, YES, NO 1081 | } 1082 | 1083 | /** 1084 | * Sets a compact mode label generator. 1085 | *

1086 | * This method is a convenience method for setting a client-side `compactModeLabelGenerator` function. 1087 | * The expression receives as input the array of selected items, named {@code items}, 1088 | * and should return a String value representing the label. For example: 1089 | * {@code return items.length + " " (item.length === 1 ? 'Item' : 'Items');} 1090 | * To set a server-side callback for generating the compact mode label use {@link #setCompactModeLabelGenerator(Function)}. 1091 | *

1092 | * 1093 | * @param expression the JavaScript expression that should return the compact mode label for the given list of selected items, not null. 1094 | */ 1095 | public void setCompactModeLabelGenerator(String expression) { 1096 | Objects.requireNonNull(expression, "The compact mode label generator expression can not be null"); 1097 | 1098 | String wrappedExpression = 1099 | "$0.compactModeLabelGenerator = function(items) { " 1100 | + expression 1101 | + "}"; 1102 | getElement().executeJs(wrappedExpression); 1103 | } 1104 | 1105 | /** 1106 | * Sets a compact mode label generator. 1107 | *

1108 | * This methods sets a 'server-side' compact mode label generator that is invoked every time the value changes. 1109 | *
1110 | * To set a client-side callback for generating the compact mode label user {@link #setCompactModeLabelGenerator(String)}. 1111 | *

1112 | * 1113 | * @param labelGenerator the compact mode label provider to use, not null 1114 | */ 1115 | public void setCompactModeLabelGenerator(Function, String> labelGenerator) { 1116 | Objects.requireNonNull(labelGenerator, "The compact mode label generator can not be null"); 1117 | runBeforeClientResponse(ui -> setCompactModeLabel(labelGenerator.apply(getValue()))); // initial state 1118 | addValueChangeListener(change -> setCompactModeLabel(labelGenerator.apply(getValue()))); 1119 | } 1120 | 1121 | private void setCompactModeLabel(String label) { 1122 | getElement().callJsFunction("$connector.setCompactModeLabel", label); 1123 | } 1124 | 1125 | /** 1126 | * Sets the given {@link Function} as unique key data generator. 1127 | * The default implementation is {@link Object#hashCode()}. 1128 | * 1129 | * @param uniqueKeyDataGenerator {@link Function} to generate unique key data 1130 | */ 1131 | public void setUniqueKeyDataGenerator(Function uniqueKeyDataGenerator) { 1132 | this.uniqueKeyDataGenerator = uniqueKeyDataGenerator; 1133 | if (dataCommunicator != null) { 1134 | dataCommunicator.setUniqueKeyDataGenerator(uniqueKeyDataGenerator); 1135 | } 1136 | } 1137 | 1138 | /** 1139 | * Predicate to check {@link MultiselectComboBox} items against user typed 1140 | * strings. 1141 | */ 1142 | @FunctionalInterface 1143 | public interface ItemFilter extends SerializableBiPredicate { 1144 | @Override 1145 | public boolean test(T item, String filterText); 1146 | } 1147 | 1148 | /** 1149 | * A callback method for fetching items. The callback is provided with a 1150 | * non-null string filter, offset index and limit. 1151 | * 1152 | * @param 1153 | * item (bean) type in MultiselectComboBox 1154 | */ 1155 | @FunctionalInterface 1156 | public interface FetchItemsCallback extends Serializable { 1157 | /** 1158 | * Returns a stream of items that match the given filter, limiting the 1159 | * results with given offset and limit. 1160 | * 1161 | * @param filter 1162 | * a non-null filter string 1163 | * @param offset 1164 | * the first index to fetch 1165 | * @param limit 1166 | * the fetched item count 1167 | * @return stream of items 1168 | */ 1169 | public Stream fetchItems(String filter, int offset, int limit); 1170 | } 1171 | 1172 | @DomEvent("custom-values-set") 1173 | public static class CustomValuesSetEvent extends ComponentEvent> { 1174 | private final String detail; 1175 | 1176 | public CustomValuesSetEvent(MultiselectComboBox source, boolean fromClient, 1177 | @EventData("event.detail") String detail) { 1178 | 1179 | super(source, fromClient); 1180 | this.detail = detail; 1181 | } 1182 | 1183 | public String getDetail() { 1184 | return detail; 1185 | } 1186 | } 1187 | 1188 | private class CustomValuesRegistration implements Registration { 1189 | private Registration delegate; 1190 | 1191 | private CustomValuesRegistration(Registration delegate) { 1192 | this.delegate = delegate; 1193 | } 1194 | 1195 | @Override 1196 | public void remove() { 1197 | if (delegate != null) { 1198 | delegate.remove(); 1199 | customValuesListenersCount--; 1200 | if (customValuesListenersCount == 0) { 1201 | setAllowCustomValues(false); 1202 | } 1203 | delegate = null; 1204 | } 1205 | } 1206 | } 1207 | 1208 | private final class UpdateQueue implements ArrayUpdater.Update { 1209 | private transient List queue = new ArrayList<>(); 1210 | 1211 | private UpdateQueue(int size) { 1212 | enqueue("$connector.updateSize", size); 1213 | } 1214 | 1215 | @Override 1216 | public void set(int start, List items) { 1217 | enqueue("$connector.set", start, 1218 | items.stream().collect(JsonUtils.asArray()), 1219 | MultiselectComboBox.this.lastFilter); 1220 | } 1221 | 1222 | @Override 1223 | public void clear(int start, int length) { 1224 | // NO-OP 1225 | } 1226 | 1227 | @Override 1228 | public void commit(int updateId) { 1229 | enqueue("$connector.confirm", updateId, 1230 | MultiselectComboBox.this.lastFilter); 1231 | queue.forEach(Runnable::run); 1232 | queue.clear(); 1233 | } 1234 | 1235 | private void enqueue(String name, Serializable... arguments) { 1236 | queue.add(() -> getElement().callJsFunction(name, arguments)); 1237 | } 1238 | } 1239 | } 1240 | -------------------------------------------------------------------------------- /src/main/java/org/vaadin/gatanaso/MultiselectComboBoxDataCommunicator.java: -------------------------------------------------------------------------------- 1 | package org.vaadin.gatanaso; 2 | 3 | import java.util.function.Function; 4 | 5 | import com.vaadin.flow.data.provider.ArrayUpdater; 6 | import com.vaadin.flow.data.provider.DataCommunicator; 7 | import com.vaadin.flow.data.provider.DataGenerator; 8 | import com.vaadin.flow.data.provider.KeyMapper; 9 | import com.vaadin.flow.function.SerializableConsumer; 10 | import com.vaadin.flow.internal.StateNode; 11 | 12 | import elemental.json.JsonArray; 13 | 14 | /** 15 | * Data communicator that handles requesting data and sending it to client side. 16 | * 17 | * @param the bean type 18 | */ 19 | public class MultiselectComboBoxDataCommunicator extends DataCommunicator { 20 | 21 | private Function uniqueKeyDataGenerator = Object::hashCode; 22 | 23 | private KeyMapper uniqueKeyMapper = new KeyMapper() { 24 | 25 | private T object; 26 | 27 | @Override 28 | public String key(T o) { 29 | this.object = o; 30 | try { 31 | return super.key(o); 32 | } finally { 33 | this.object = null; 34 | } 35 | } 36 | 37 | @Override 38 | protected String createKey() { 39 | return String.valueOf(uniqueKeyDataGenerator.apply(object)); 40 | } 41 | }; 42 | 43 | /** 44 | * Creates a new instance. 45 | * 46 | * @param dataGenerator 47 | * the data generator function 48 | * @param arrayUpdater 49 | * array updater strategy 50 | * @param dataUpdater 51 | * data updater strategy 52 | * @param stateNode 53 | * the state node used to communicate for 54 | */ 55 | public MultiselectComboBoxDataCommunicator(DataGenerator dataGenerator, ArrayUpdater arrayUpdater, SerializableConsumer dataUpdater, 56 | StateNode stateNode) { 57 | 58 | super(dataGenerator, arrayUpdater, dataUpdater, stateNode); 59 | setKeyMapper(uniqueKeyMapper); 60 | } 61 | 62 | /** 63 | * Sets the given {@link Function} as unique key data generator. 64 | * The default implementation is {@link Object#hashCode()}. 65 | * 66 | * @param uniqueKeyDataGenerator {@link Function} to generate unique key data 67 | */ 68 | public void setUniqueKeyDataGenerator(Function uniqueKeyDataGenerator) { 69 | this.uniqueKeyDataGenerator = uniqueKeyDataGenerator; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/resources/frontend/multiselectComboBoxConnector.js: -------------------------------------------------------------------------------- 1 | // Connector for the MultiselectComboBox (based on the ComboBox connector) 2 | import { Debouncer } from '@polymer/polymer/lib/utils/debounce.js'; 3 | import { timeOut } from '@polymer/polymer/lib/utils/async.js'; 4 | 5 | window.Vaadin.Flow.multiselectComboBoxConnector = { 6 | initLazy: function (multiselectComboBox) { 7 | 8 | // check if already initialized for the MultiselectComboBox 9 | if (multiselectComboBox.$connector) { 10 | return; 11 | } 12 | 13 | multiselectComboBox.$connector = {}; 14 | 15 | let pageCallbacks = {}; 16 | let cache = {}; 17 | let lastFilter = ''; 18 | 19 | multiselectComboBox.$connector.initDataConnector = function() { 20 | if (_hasDataProvider(multiselectComboBox)) { 21 | return; 22 | } 23 | multiselectComboBox.$.comboBox.dataProvider = function (params, callback) { 24 | if (params.pageSize != multiselectComboBox.$.comboBox.pageSize 25 | && multiselectComboBox.pageSize != multiselectComboBox.$.comboBox.pageSize) { 26 | 27 | throw 'Invalid pageSize'; 28 | } 29 | 30 | if (multiselectComboBox._clientSideFilter) { 31 | // For clientside filter we first make sure we have all data which we also 32 | // filter based on comboBox.filter. While later we only filter client side data. 33 | if (cache[0]) { 34 | performClientSideFilter(cache[0], callback); 35 | return; 36 | } else { 37 | // If the client side filter is enabled then we need to first get all data 38 | // and filter it on client side. Otherwise the next time the user 39 | // inputs another filter, eg. continues to type, the local cache will be only 40 | // that which was received for the first filter, which may not be the whole 41 | // data from server (keep in mind that the client side filter is enabled only 42 | // when the items count does not exceed one page). 43 | params.filter = ""; 44 | } 45 | } 46 | 47 | const filterChanged = params.filter !== lastFilter; 48 | if (filterChanged) { 49 | pageCallbacks = {}; 50 | cache = {}; 51 | lastFilter = params.filter; 52 | } 53 | 54 | if (cache[params.page]) { 55 | // This may happen after skipping pages by scrolling fast 56 | commitPage(params.page, callback); 57 | } else { 58 | const upperLimit = params.pageSize * (params.page + 1); 59 | 60 | if (filterChanged) { 61 | this._debouncer = Debouncer.debounce( 62 | this._debouncer, 63 | timeOut.after(500), 64 | () => { 65 | multiselectComboBox.$server.setRequestedRange(0, upperLimit, params.filter); 66 | if (params.filter === '') { 67 | // Fixes the case when the filter changes 68 | // from '' to something else and back to '' 69 | // within debounce timeout, and the 70 | // DataCommunicator thinks it doesn't need to send data 71 | multiselectComboBox.$server.resetDataCommunicator(); 72 | } 73 | }); 74 | } else { 75 | multiselectComboBox.$server.setRequestedRange(0, upperLimit, params.filter); 76 | } 77 | 78 | pageCallbacks[params.page] = callback; 79 | } 80 | }; 81 | }; 82 | 83 | multiselectComboBox.$connector.filter = function (item, filter) { 84 | filter = filter ? filter.toString().toLowerCase() : ''; 85 | return multiselectComboBox.$.comboBox._getItemLabel(item).toString().toLowerCase().indexOf(filter) > -1; 86 | }; 87 | 88 | multiselectComboBox.$connector.set = function (index, items, filter) { 89 | if (filter != lastFilter) { 90 | return; 91 | } 92 | 93 | if (index % multiselectComboBox.$.comboBox.pageSize != 0) { 94 | throw 'Got new data to index ' + index + ' which is not aligned with the page size of ' + multiselectComboBox.$.comboBox.pageSize; 95 | } 96 | 97 | if (index === 0 && items.length === 0 && pageCallbacks[0]) { 98 | // Makes sure that the dataProvider callback is called even when server 99 | // returns empty data set (no items match the filter). 100 | cache[0] = []; 101 | return; 102 | } 103 | 104 | const firstPageToSet = index / multiselectComboBox.$.comboBox.pageSize; 105 | const updatedPageCount = Math.ceil(items.length / multiselectComboBox.$.comboBox.pageSize); 106 | 107 | for (let i = 0; i < updatedPageCount; i++) { 108 | let page = firstPageToSet + i; 109 | let slice = items.slice(i * multiselectComboBox.$.comboBox.pageSize, (i + 1) * multiselectComboBox.$.comboBox.pageSize); 110 | 111 | cache[page] = slice; 112 | } 113 | }; 114 | 115 | multiselectComboBox.$connector.updateData = function (items) { 116 | // IE11 doesn't work with the transpiled version of the forEach. 117 | for (let i = 0; i < items.length; i++) { 118 | let item = items[i]; 119 | 120 | for (let j = 0; j < multiselectComboBox.$.comboBox.filteredItems.length; j++) { 121 | if (multiselectComboBox.$.comboBox.filteredItems[j].key === item.key) { 122 | multiselectComboBox.$.comboBox.set('filteredItems.' + j, item); 123 | break; 124 | } 125 | } 126 | } 127 | }; 128 | 129 | multiselectComboBox.$connector.updateSize = function (newSize) { 130 | if (!multiselectComboBox._clientSideFilter) { 131 | // NOTE: It may be that this set size is unnecessary, since when 132 | // providing data to combobox via callback we may use the data size. 133 | // However, if this size reflects the whole data, including 134 | // data not yet fetched on the client side, and the combobox expects it 135 | // to be set, then at least, we don't need it in case the 136 | // filter is clientSide only (since it'll increase the height of 137 | // the popup at only the first user filter to this size, while the 138 | // filtered items count are less). 139 | customElements.whenDefined('multiselect-combo-box').then(() => { 140 | multiselectComboBox.$.comboBox.size = newSize; 141 | }); 142 | } 143 | }; 144 | 145 | multiselectComboBox.$connector.reset = function () { 146 | pageCallbacks = {}; 147 | cache = {}; 148 | multiselectComboBox.$.comboBox.clearCache(); 149 | }; 150 | 151 | multiselectComboBox.$connector.confirm = function (id, filter) { 152 | 153 | if (filter != lastFilter) { 154 | return; 155 | } 156 | 157 | // We're done applying changes from this batch, 158 | // resolve outstanding callbacks 159 | let outstandingRequests = Object.getOwnPropertyNames(pageCallbacks); 160 | for (let i = 0; i < outstandingRequests.length; i++) { 161 | let page = outstandingRequests[i]; 162 | 163 | if (cache[page]) { 164 | let callback = pageCallbacks[page]; 165 | delete pageCallbacks[page]; 166 | 167 | commitPage(page, callback); 168 | } 169 | } 170 | 171 | // inform the server that we are done 172 | multiselectComboBox.$server.confirmUpdate(id); 173 | }; 174 | 175 | multiselectComboBox.$connector.setCompactModeLabel = function(compactModeLabel) { 176 | multiselectComboBox.compactModeLabelGenerator = () => compactModeLabel; 177 | }; 178 | 179 | const commitPage = function (page, callback) { 180 | let data = cache[page]; 181 | 182 | if (multiselectComboBox._clientSideFilter) { 183 | performClientSideFilter(data, callback) 184 | 185 | } else { 186 | // Remove the data if server-side filtering, 187 | // but keep it for client-side filtering 188 | delete cache[page]; 189 | 190 | // NOTE: It may be that we ought to provide data.length instead of 191 | // comboBox.size and remove the updateSize function. 192 | callback(data, multiselectComboBox.$.comboBox.size); 193 | } 194 | }; 195 | 196 | // Perform filter on client side (here) using the items from specified page 197 | // and submitting the filtered items to specified callback. 198 | // The filter used is the one from combobox, not the lastFilter stored since 199 | // that may not reflect user's input. 200 | const performClientSideFilter = function (page, callback) { 201 | 202 | let filteredItems = page; 203 | 204 | if (multiselectComboBox.$.comboBox.filter) { 205 | filteredItems = page.filter(item => 206 | multiselectComboBox.$connector.filter(item, multiselectComboBox.$.comboBox.filter)); 207 | } 208 | 209 | callback(filteredItems, filteredItems.length); 210 | }; 211 | 212 | const _hasDataProvider = function(multiselectComboBox) { 213 | return multiselectComboBox.$.comboBox.dataProvider && typeof multiselectComboBox.$.comboBox.dataProvider === 'function'; 214 | }; 215 | 216 | } 217 | }; 218 | -------------------------------------------------------------------------------- /src/test/java/org/vaadin/gatanaso/MultiselectComboBoxTest.java: -------------------------------------------------------------------------------- 1 | package org.vaadin.gatanaso; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collection; 5 | import java.util.LinkedHashSet; 6 | import java.util.List; 7 | import java.util.Set; 8 | import java.util.concurrent.atomic.AtomicReference; 9 | import java.util.stream.Collectors; 10 | 11 | import org.junit.Assert; 12 | import org.junit.Test; 13 | 14 | import com.vaadin.flow.data.provider.DataProvider; 15 | import com.vaadin.flow.data.provider.ListDataProvider; 16 | import com.vaadin.flow.data.provider.Query; 17 | import com.vaadin.flow.shared.Registration; 18 | 19 | import static org.hamcrest.MatcherAssert.assertThat; 20 | import static org.hamcrest.Matchers.hasItem; 21 | import static org.hamcrest.Matchers.hasSize; 22 | import static org.hamcrest.Matchers.is; 23 | 24 | /** 25 | * Tests for the {@link MultiselectComboBox}. 26 | */ 27 | public class MultiselectComboBoxTest { 28 | 29 | @Test 30 | public void shouldInstantiateWithLabel() { 31 | // given 32 | MultiselectComboBox multiselectComboBox; 33 | String label = "Label"; 34 | 35 | // when 36 | multiselectComboBox = new MultiselectComboBox<>(label); 37 | 38 | // then 39 | assertThat(multiselectComboBox.getLabel(), is(label)); 40 | } 41 | 42 | @Test 43 | public void shouldInstantiateWithLabelAndCollectionOfItems() { 44 | // given 45 | TestMultiselectComboBox multiselectComboBox; 46 | String label = "Label"; 47 | List items = Arrays.asList("Item 1", "Item 2"); 48 | 49 | // when 50 | multiselectComboBox = new TestMultiselectComboBox(label, items); 51 | 52 | // then 53 | assertThat(multiselectComboBox.getLabel(), is(label)); 54 | assertThat(multiselectComboBox.items, hasSize(2)); 55 | assertThat(multiselectComboBox.items, hasItem("Item 1")); 56 | assertThat(multiselectComboBox.items, hasItem("Item 2")); 57 | } 58 | 59 | @Test 60 | public void shouldInstantiateWithLabelAndItems() { 61 | // given 62 | TestMultiselectComboBox multiselectComboBox; 63 | String label = "Label"; 64 | 65 | // when 66 | multiselectComboBox = new TestMultiselectComboBox(label, "Item 1", "Item 2"); 67 | 68 | // then 69 | assertThat(multiselectComboBox.getLabel(), is(label)); 70 | assertThat(multiselectComboBox.items, hasSize(2)); 71 | assertThat(multiselectComboBox.items, hasItem("Item 1")); 72 | assertThat(multiselectComboBox.items, hasItem("Item 2")); 73 | } 74 | 75 | @Test 76 | public void shouldVerifyItemLabelPath() { 77 | // given 78 | MultiselectComboBox multiselectComboBox; 79 | 80 | // when 81 | multiselectComboBox = new MultiselectComboBox<>(); 82 | 83 | // then 84 | assertThat(multiselectComboBox.getElement().getProperty("itemLabelPath"), is(MultiselectComboBox.ITEM_LABEL_PATH)); 85 | } 86 | 87 | @Test 88 | public void shouldVerifyItemValuePath() { 89 | // given 90 | MultiselectComboBox multiselectComboBox; 91 | 92 | // when 93 | multiselectComboBox = new MultiselectComboBox<>(); 94 | 95 | // then 96 | assertThat(multiselectComboBox.getElement().getProperty("itemValuePath"), is(MultiselectComboBox.ITEM_VALUE_PATH)); 97 | } 98 | 99 | @Test 100 | public void shouldVerifyItemIdPath() { 101 | // given 102 | MultiselectComboBox multiselectComboBox; 103 | 104 | // when 105 | multiselectComboBox = new MultiselectComboBox<>(); 106 | 107 | // then 108 | assertThat(multiselectComboBox.getElement().getProperty("itemIdPath"), is(MultiselectComboBox.ITEM_VALUE_PATH)); 109 | } 110 | 111 | @Test 112 | public void shouldSetLabel() { 113 | // given 114 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 115 | String label = "Multiselect combo box"; 116 | 117 | // when 118 | multiselectComboBox.setLabel(label); 119 | 120 | // then 121 | assertThat(multiselectComboBox.getLabel(), is(label)); 122 | } 123 | 124 | @Test 125 | public void shouldSetPlaceholder() { 126 | // given 127 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 128 | String placeholder = "Add items"; 129 | 130 | // when 131 | multiselectComboBox.setPlaceholder(placeholder); 132 | 133 | // then 134 | assertThat(multiselectComboBox.getPlaceholder(), is(placeholder)); 135 | } 136 | 137 | @Test 138 | public void shouldSetRequired() { 139 | // given 140 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 141 | 142 | Assert.assertFalse(multiselectComboBox.isRequired()); 143 | 144 | // when 145 | multiselectComboBox.setRequired(true); 146 | 147 | // then 148 | assertThat(multiselectComboBox.isRequired(), is(true)); 149 | assertThat(multiselectComboBox.getElement().getProperty("required"), is("true")); 150 | } 151 | 152 | @Test 153 | public void shouldSetReadOnly() { 154 | // given 155 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 156 | 157 | Assert.assertFalse(multiselectComboBox.isReadOnly()); 158 | 159 | // when 160 | multiselectComboBox.setReadOnly(true); 161 | 162 | // then 163 | assertThat(multiselectComboBox.isReadOnly(), is(true)); 164 | assertThat(multiselectComboBox.getElement().getProperty("readonly"), is("true")); 165 | } 166 | 167 | @Test 168 | public void shouldSetCompactMode() { 169 | // given 170 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 171 | 172 | Assert.assertFalse(multiselectComboBox.isCompactMode()); 173 | 174 | // when 175 | multiselectComboBox.setCompactMode(true); 176 | 177 | // then 178 | assertThat(multiselectComboBox.isCompactMode(), is(true)); 179 | assertThat(multiselectComboBox.getElement().getProperty("compactMode"), is("true")); 180 | } 181 | 182 | @Test 183 | public void shouldSetOrdered() { 184 | // given 185 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 186 | 187 | Assert.assertFalse(multiselectComboBox.isOrdered()); 188 | 189 | // when 190 | multiselectComboBox.setOrdered(true); 191 | 192 | // then 193 | assertThat(multiselectComboBox.isOrdered(), is(true)); 194 | assertThat(multiselectComboBox.getElement().getProperty("ordered"), is("true")); 195 | } 196 | 197 | @Test 198 | public void shouldSetInvalid() { 199 | // given 200 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 201 | 202 | Assert.assertFalse(multiselectComboBox.isInvalid()); 203 | 204 | // when 205 | multiselectComboBox.setInvalid(true); 206 | 207 | // then 208 | assertThat(multiselectComboBox.isInvalid(), is(true)); 209 | assertThat(multiselectComboBox.getElement().getProperty("invalid"), is("true")); 210 | } 211 | 212 | @Test 213 | public void shouldSetErrorMessage() { 214 | // given 215 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 216 | String message = "error message"; 217 | 218 | // when 219 | multiselectComboBox.setErrorMessage(message); 220 | 221 | // then 222 | assertThat(multiselectComboBox.getErrorMessage(), is(message)); 223 | } 224 | 225 | @Test 226 | public void shouldSetItems() { 227 | // given 228 | TestMultiselectComboBox multiselectComboBox = new TestMultiselectComboBox(); 229 | 230 | // when 231 | multiselectComboBox.setItems(Arrays.asList("item 1", "item 2", "item 3")); 232 | 233 | // then 234 | assertThat(multiselectComboBox.items, hasSize(3)); 235 | assertThat(multiselectComboBox.items, hasItem("item 1")); 236 | assertThat(multiselectComboBox.items, hasItem("item 2")); 237 | assertThat(multiselectComboBox.items, hasItem("item 3")); 238 | } 239 | 240 | @Test 241 | public void shouldSetPageSize() { 242 | // given 243 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 244 | 245 | assertThat(multiselectComboBox.getPageSize(), is(50)); // default value 246 | 247 | // when 248 | multiselectComboBox.setPageSize(10); 249 | 250 | // then 251 | assertThat(multiselectComboBox.getPageSize(), is(10)); 252 | } 253 | 254 | @Test(expected = IllegalArgumentException.class) 255 | public void shouldThrowExceptionWhenSettingInvalidPageSize() { 256 | // given 257 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 258 | 259 | // when & then 260 | multiselectComboBox.setPageSize(0); 261 | } 262 | 263 | @Test 264 | public void shouldSetClearButtonVisible() { 265 | // given 266 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 267 | 268 | Assert.assertFalse(multiselectComboBox.isClearButtonVisible()); 269 | 270 | // when 271 | multiselectComboBox.setClearButtonVisible(true); 272 | 273 | // then 274 | assertThat(multiselectComboBox.isClearButtonVisible(), is(true)); 275 | assertThat(multiselectComboBox.getElement().getProperty("clearButtonVisible"), is("true")); 276 | } 277 | 278 | @Test 279 | public void shouldSetReadOnlyValueSeparator() { 280 | // given 281 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 282 | 283 | // when 284 | multiselectComboBox.setReadOnlyValueSeparator("***"); 285 | 286 | // then 287 | assertThat(multiselectComboBox.getReadOnlyValueSeparator(), is("***")); 288 | } 289 | 290 | @Test 291 | public void shouldSetAllowCustomValues() { 292 | // given 293 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 294 | 295 | Assert.assertFalse(multiselectComboBox.isAllowCustomValues()); 296 | 297 | // when 298 | multiselectComboBox.setAllowCustomValues(true); 299 | 300 | // then 301 | assertThat(multiselectComboBox.isAllowCustomValues(), is(true)); 302 | assertThat(multiselectComboBox.getElement().getProperty("allowCustomValues"), is("true")); 303 | } 304 | 305 | @Test 306 | public void shouldUpdateDataProviderAndResetValueToEmpty() { 307 | // given 308 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 309 | multiselectComboBox.setItems(Arrays.asList("item 1", "item 2")); // data provider is set 310 | 311 | Set value = new LinkedHashSet<>(Arrays.asList("item 1")); 312 | 313 | // when 314 | multiselectComboBox.setValue(value); 315 | assertThat(multiselectComboBox.getValue(), hasItem("item 1")); // ensure value is set 316 | 317 | multiselectComboBox.setItems(Arrays.asList("foo", "bar")); // update data provider 318 | 319 | // then 320 | assertThat(multiselectComboBox.getValue(), hasSize(0)); // value is reset to empty 321 | } 322 | 323 | @Test(expected = NullPointerException.class) 324 | public void shouldThrowExceptionWhenSettingNullDataProvider() { 325 | // given 326 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 327 | DataProvider dataProvider = null; 328 | 329 | // when 330 | multiselectComboBox.setDataProvider(dataProvider); 331 | 332 | // then, expect exception 333 | } 334 | 335 | @Test(expected = NullPointerException.class) 336 | public void shouldThrowExceptionWhenSettingNullItemLabelGenerator() { 337 | // given 338 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 339 | 340 | // when 341 | multiselectComboBox.setItemLabelGenerator(null); 342 | 343 | // then, expect exception 344 | } 345 | 346 | @Test(expected = NullPointerException.class) 347 | public void shouldThrowExceptionWhenSettingNullRenderer() { 348 | // given 349 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 350 | 351 | // when 352 | multiselectComboBox.setRenderer(null); 353 | 354 | // then, expect exception 355 | } 356 | 357 | @Test 358 | public void shouldNotifyValueChangeListener() { 359 | // given 360 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 361 | multiselectComboBox.setItems("Item 1", "Item 2", "Item 3"); 362 | 363 | AtomicReference> selected = new AtomicReference<>(); 364 | multiselectComboBox.addValueChangeListener(event -> selected.set(multiselectComboBox.getValue())); 365 | 366 | // when 367 | Set value = new LinkedHashSet<>(Arrays.asList("Item 1, Item 2")); 368 | multiselectComboBox.setValue(value); 369 | 370 | // then 371 | assertThat(selected.get(), is(value)); 372 | } 373 | 374 | @Test 375 | public void shouldSetEnabled() { 376 | // given 377 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 378 | 379 | // when & then 380 | multiselectComboBox.setEnabled(true); 381 | assertThat(multiselectComboBox.isEnabled(), is(true)); 382 | 383 | multiselectComboBox.setEnabled(false); 384 | assertThat(multiselectComboBox.isEnabled(), is(false)); 385 | } 386 | 387 | @Test 388 | public void shouldSetCustomValuesAllowedFlagWhenEventListenerIsRegistered() { 389 | // given 390 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 391 | 392 | // when 393 | multiselectComboBox.addCustomValuesSetListener(event -> { 394 | // no op 395 | }); 396 | 397 | // then 398 | assertThat(multiselectComboBox.isAllowCustomValues(), is(true)); 399 | } 400 | 401 | @Test 402 | public void shouldRemoveCustomValuesAllowedFlagWhenEventListenerIsRemoved() { 403 | // given 404 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 405 | 406 | Registration registration = multiselectComboBox.addCustomValuesSetListener(event -> { 407 | // no op 408 | }); 409 | 410 | // when 411 | registration.remove(); 412 | 413 | // then 414 | assertThat(multiselectComboBox.isAllowCustomValues(), is(false)); 415 | } 416 | 417 | @Test 418 | public void shouldRemoveCustomValuesAllowedFlagWhenEventAllListenerAreRemoved() { 419 | // given 420 | MultiselectComboBox multiselectComboBox = new MultiselectComboBox<>(); 421 | 422 | Registration registration1 = multiselectComboBox.addCustomValuesSetListener(event -> { 423 | // no op 424 | }); 425 | Registration registration2 = multiselectComboBox.addCustomValuesSetListener(event -> { 426 | // no op 427 | }); 428 | 429 | assertThat(multiselectComboBox.isAllowCustomValues(), is(true)); 430 | 431 | // when 432 | registration1.remove(); 433 | registration2.remove(); 434 | 435 | // then 436 | assertThat(multiselectComboBox.isAllowCustomValues(), is(false)); 437 | } 438 | 439 | private static class TestMultiselectComboBox extends MultiselectComboBox { 440 | private List items; 441 | 442 | public TestMultiselectComboBox() { 443 | super(); 444 | } 445 | 446 | public TestMultiselectComboBox(String label, Collection items) { 447 | super(label, items); 448 | } 449 | 450 | public TestMultiselectComboBox(String label, T... items) { 451 | super(label, items); 452 | } 453 | 454 | @Override 455 | public void setDataProvider(ListDataProvider listDataProvider) { 456 | super.setDataProvider(listDataProvider); 457 | items = listDataProvider.fetch(new Query<>()) 458 | .collect(Collectors.toList()); 459 | } 460 | } 461 | } 462 | --------------------------------------------------------------------------------