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.

Tree.java 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194
  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.lang.reflect.Method;
  18. import java.util.ArrayList;
  19. import java.util.Collection;
  20. import java.util.HashMap;
  21. import java.util.HashSet;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.Objects;
  25. import java.util.Optional;
  26. import java.util.Set;
  27. import java.util.UUID;
  28. import org.jsoup.nodes.Attributes;
  29. import org.jsoup.nodes.Element;
  30. import org.jsoup.select.Elements;
  31. import com.vaadin.data.Binder;
  32. import com.vaadin.data.HasHierarchicalDataProvider;
  33. import com.vaadin.data.SelectionModel;
  34. import com.vaadin.data.TreeData;
  35. import com.vaadin.data.provider.DataGenerator;
  36. import com.vaadin.data.provider.DataProvider;
  37. import com.vaadin.data.provider.HierarchicalDataProvider;
  38. import com.vaadin.data.provider.HierarchicalQuery;
  39. import com.vaadin.data.provider.TreeDataProvider;
  40. import com.vaadin.event.CollapseEvent;
  41. import com.vaadin.event.CollapseEvent.CollapseListener;
  42. import com.vaadin.event.ConnectorEvent;
  43. import com.vaadin.event.ContextClickEvent;
  44. import com.vaadin.event.ExpandEvent;
  45. import com.vaadin.event.ExpandEvent.ExpandListener;
  46. import com.vaadin.event.SerializableEventListener;
  47. import com.vaadin.event.selection.SelectionListener;
  48. import com.vaadin.server.ErrorMessage;
  49. import com.vaadin.server.Resource;
  50. import com.vaadin.shared.EventId;
  51. import com.vaadin.shared.MouseEventDetails;
  52. import com.vaadin.shared.Registration;
  53. import com.vaadin.shared.ui.ContentMode;
  54. import com.vaadin.shared.ui.grid.HeightMode;
  55. import com.vaadin.shared.ui.grid.ScrollDestination;
  56. import com.vaadin.shared.ui.tree.TreeMultiSelectionModelState;
  57. import com.vaadin.shared.ui.tree.TreeRendererState;
  58. import com.vaadin.ui.Grid.SelectionMode;
  59. import com.vaadin.ui.components.grid.DescriptionGenerator;
  60. import com.vaadin.ui.components.grid.MultiSelectionModelImpl;
  61. import com.vaadin.ui.components.grid.NoSelectionModel;
  62. import com.vaadin.ui.components.grid.SingleSelectionModelImpl;
  63. import com.vaadin.ui.declarative.DesignAttributeHandler;
  64. import com.vaadin.ui.declarative.DesignContext;
  65. import com.vaadin.ui.renderers.AbstractRenderer;
  66. import com.vaadin.util.ReflectTools;
  67. import elemental.json.JsonObject;
  68. /**
  69. * Tree component. A Tree can be used to select an item from a hierarchical set
  70. * of items.
  71. *
  72. * @author Vaadin Ltd
  73. * @since 8.1
  74. *
  75. * @param <T>
  76. * the data type
  77. */
  78. public class Tree<T> extends Composite
  79. implements HasHierarchicalDataProvider<T> {
  80. @Deprecated
  81. private static final Method ITEM_CLICK_METHOD = ReflectTools
  82. .findMethod(ItemClickListener.class, "itemClick", ItemClick.class);
  83. private Registration contextClickRegistration = null;
  84. /**
  85. * A listener for item click events.
  86. *
  87. * @param <T>
  88. * the tree item type
  89. *
  90. * @see ItemClick
  91. * @see Registration
  92. * @since 8.1
  93. */
  94. @FunctionalInterface
  95. public interface ItemClickListener<T> extends SerializableEventListener {
  96. /**
  97. * Invoked when this listener receives a item click event from a Tree to
  98. * which it has been added.
  99. *
  100. * @param event
  101. * the received event, not {@code null}
  102. */
  103. public void itemClick(Tree.ItemClick<T> event);
  104. }
  105. /**
  106. * Tree item click event.
  107. *
  108. * @param <T>
  109. * the data type of tree
  110. * @since 8.1
  111. */
  112. public static class ItemClick<T> extends ConnectorEvent {
  113. private final T item;
  114. private final MouseEventDetails mouseEventDetails;
  115. /**
  116. * Constructs a new item click.
  117. *
  118. * @param source
  119. * the tree component
  120. * @param item
  121. * the clicked item
  122. * @param mouseEventDetails
  123. * information about the original mouse event (mouse button
  124. * clicked, coordinates if available etc.)
  125. */
  126. protected ItemClick(Tree<T> source, T item,
  127. MouseEventDetails mouseEventDetails) {
  128. super(source);
  129. this.item = item;
  130. this.mouseEventDetails = mouseEventDetails;
  131. }
  132. /**
  133. * Returns the clicked item.
  134. *
  135. * @return the clicked item
  136. */
  137. public T getItem() {
  138. return item;
  139. }
  140. @SuppressWarnings("unchecked")
  141. @Override
  142. public Tree<T> getSource() {
  143. return (Tree<T>) super.getSource();
  144. }
  145. /**
  146. * Returns the mouse event details.
  147. *
  148. * @return the mouse event details
  149. */
  150. public MouseEventDetails getMouseEventDetails() {
  151. return mouseEventDetails;
  152. }
  153. }
  154. /**
  155. * String renderer that handles icon resources and stores their identifiers
  156. * into data objects.
  157. *
  158. * @since 8.1
  159. */
  160. public final class TreeRenderer extends AbstractRenderer<T, String>
  161. implements DataGenerator<T> {
  162. /**
  163. * Constructs a new TreeRenderer.
  164. */
  165. protected TreeRenderer() {
  166. super(String.class);
  167. }
  168. private Map<T, String> resourceKeyMap = new HashMap<>();
  169. private int counter = 0;
  170. @Override
  171. public void generateData(T item, JsonObject jsonObject) {
  172. Resource resource = iconProvider.apply(item);
  173. if (resource == null) {
  174. destroyData(item);
  175. return;
  176. }
  177. if (!resourceKeyMap.containsKey(item)) {
  178. resourceKeyMap.put(item, "icon" + (counter++));
  179. }
  180. setResource(resourceKeyMap.get(item), resource);
  181. jsonObject.put("itemIcon", resourceKeyMap.get(item));
  182. }
  183. @Override
  184. public void destroyData(T item) {
  185. if (resourceKeyMap.containsKey(item)) {
  186. setResource(resourceKeyMap.get(item), null);
  187. resourceKeyMap.remove(item);
  188. }
  189. }
  190. @Override
  191. public void destroyAllData() {
  192. Set<T> keys = new HashSet<>(resourceKeyMap.keySet());
  193. for (T key : keys) {
  194. destroyData(key);
  195. }
  196. }
  197. @Override
  198. protected TreeRendererState getState() {
  199. return (TreeRendererState) super.getState();
  200. }
  201. @Override
  202. protected TreeRendererState getState(boolean markAsDirty) {
  203. return (TreeRendererState) super.getState(markAsDirty);
  204. }
  205. }
  206. /**
  207. * Custom MultiSelectionModel for Tree. TreeMultiSelectionModel does not
  208. * show selection column.
  209. *
  210. * @param <T>
  211. * the tree item type
  212. *
  213. * @since 8.1
  214. */
  215. public static final class TreeMultiSelectionModel<T>
  216. extends MultiSelectionModelImpl<T> {
  217. @Override
  218. protected TreeMultiSelectionModelState getState() {
  219. return (TreeMultiSelectionModelState) super.getState();
  220. }
  221. @Override
  222. protected TreeMultiSelectionModelState getState(boolean markAsDirty) {
  223. return (TreeMultiSelectionModelState) super.getState(markAsDirty);
  224. }
  225. }
  226. private TreeGrid<T> treeGrid = new TreeGrid<>();
  227. private ItemCaptionGenerator<T> captionGenerator = String::valueOf;
  228. private IconGenerator<T> iconProvider = t -> null;
  229. private final TreeRenderer renderer;
  230. private boolean autoRecalculateWidth = true;
  231. /**
  232. * Constructs a new Tree Component.
  233. */
  234. public Tree() {
  235. setCompositionRoot(treeGrid);
  236. renderer = new TreeRenderer();
  237. treeGrid.getDataCommunicator().addDataGenerator(renderer);
  238. treeGrid.addColumn(i -> captionGenerator.apply(i), renderer)
  239. .setId("column");
  240. treeGrid.setHierarchyColumn("column");
  241. while (treeGrid.getHeaderRowCount() > 0) {
  242. treeGrid.removeHeaderRow(0);
  243. }
  244. treeGrid.setPrimaryStyleName("v-tree8");
  245. treeGrid.setRowHeight(28);
  246. setWidth("100%");
  247. treeGrid.setHeightUndefined();
  248. treeGrid.setHeightMode(HeightMode.UNDEFINED);
  249. treeGrid.addExpandListener(e -> {
  250. fireExpandEvent(e.getExpandedItem(), e.isUserOriginated());
  251. if (autoRecalculateWidth) {
  252. treeGrid.recalculateColumnWidths();
  253. }
  254. });
  255. treeGrid.addCollapseListener(e -> {
  256. fireCollapseEvent(e.getCollapsedItem(), e.isUserOriginated());
  257. if (autoRecalculateWidth) {
  258. treeGrid.recalculateColumnWidths();
  259. }
  260. });
  261. treeGrid.addItemClickListener(e -> fireEvent(
  262. new ItemClick<>(this, e.getItem(), e.getMouseEventDetails())));
  263. }
  264. /**
  265. * Constructs a new Tree Component with given caption.
  266. *
  267. * @param caption
  268. * the caption for component
  269. */
  270. public Tree(String caption) {
  271. this();
  272. setCaption(caption);
  273. }
  274. /**
  275. * Constructs a new Tree Component with given caption and {@code TreeData}.
  276. *
  277. * @param caption
  278. * the caption for component
  279. * @param treeData
  280. * the tree data for component
  281. */
  282. public Tree(String caption, TreeData<T> treeData) {
  283. this(caption, new TreeDataProvider<>(treeData));
  284. }
  285. /**
  286. * Constructs a new Tree Component with given caption and
  287. * {@code HierarchicalDataProvider}.
  288. *
  289. * @param caption
  290. * the caption for component
  291. * @param dataProvider
  292. * the hierarchical data provider for component
  293. */
  294. public Tree(String caption, HierarchicalDataProvider<T, ?> dataProvider) {
  295. this(caption);
  296. treeGrid.setDataProvider(dataProvider);
  297. }
  298. /**
  299. * Constructs a new Tree Component with given
  300. * {@code HierarchicalDataProvider}.
  301. *
  302. * @param dataProvider
  303. * the hierarchical data provider for component
  304. */
  305. public Tree(HierarchicalDataProvider<T, ?> dataProvider) {
  306. this(null, dataProvider);
  307. }
  308. @Override
  309. public HierarchicalDataProvider<T, ?> getDataProvider() {
  310. return treeGrid.getDataProvider();
  311. }
  312. @Override
  313. public void setDataProvider(DataProvider<T, ?> dataProvider) {
  314. treeGrid.setDataProvider(dataProvider);
  315. }
  316. /**
  317. * Adds an ExpandListener to this Tree.
  318. *
  319. * @see ExpandEvent
  320. *
  321. * @param listener
  322. * the listener to add
  323. * @return a registration for the listener
  324. */
  325. public Registration addExpandListener(ExpandListener<T> listener) {
  326. return addListener(ExpandEvent.class, listener,
  327. ExpandListener.EXPAND_METHOD);
  328. }
  329. /**
  330. * Adds a CollapseListener to this Tree.
  331. *
  332. * @see CollapseEvent
  333. *
  334. * @param listener
  335. * the listener to add
  336. * @return a registration for the listener
  337. */
  338. public Registration addCollapseListener(CollapseListener<T> listener) {
  339. return addListener(CollapseEvent.class, listener,
  340. CollapseListener.COLLAPSE_METHOD);
  341. }
  342. /**
  343. * Fires an expand event with given item.
  344. *
  345. * @param item
  346. * the expanded item
  347. * @param userOriginated
  348. * whether the expand was triggered by a user interaction or the
  349. * server
  350. */
  351. protected void fireExpandEvent(T item, boolean userOriginated) {
  352. fireEvent(new ExpandEvent<>(this, item, userOriginated));
  353. }
  354. /**
  355. * Fires a collapse event with given item.
  356. *
  357. * @param item
  358. * the collapsed item
  359. * @param userOriginated
  360. * whether the collapse was triggered by a user interaction or
  361. * the server
  362. */
  363. protected void fireCollapseEvent(T item, boolean userOriginated) {
  364. fireEvent(new CollapseEvent<>(this, item, userOriginated));
  365. }
  366. /**
  367. * Expands the given items.
  368. * <p>
  369. * If an item is currently expanded, does nothing. If an item does not have
  370. * any children, does nothing.
  371. *
  372. * @param items
  373. * the items to expand
  374. */
  375. public void expand(T... items) {
  376. treeGrid.expand(items);
  377. }
  378. /**
  379. * Expands the given items.
  380. * <p>
  381. * If an item is currently expanded, does nothing. If an item does not have
  382. * any children, does nothing.
  383. *
  384. * @param items
  385. * the items to expand
  386. */
  387. public void expand(Collection<T> items) {
  388. treeGrid.expand(items);
  389. }
  390. /**
  391. * Collapse the given items.
  392. * <p>
  393. * For items that are already collapsed, does nothing.
  394. *
  395. * @param items
  396. * the collection of items to collapse
  397. */
  398. public void collapse(T... items) {
  399. treeGrid.collapse(items);
  400. }
  401. /**
  402. * Collapse the given items.
  403. * <p>
  404. * For items that are already collapsed, does nothing.
  405. *
  406. * @param items
  407. * the collection of items to collapse
  408. */
  409. public void collapse(Collection<T> items) {
  410. treeGrid.collapse(items);
  411. }
  412. /**
  413. * Returns whether a given item is expanded or collapsed.
  414. *
  415. * @param item
  416. * the item to check
  417. * @return true if the item is expanded, false if collapsed
  418. */
  419. public boolean isExpanded(T item) {
  420. return treeGrid.isExpanded(item);
  421. }
  422. /**
  423. * This method is a shorthand that delegates to the currently set selection
  424. * model.
  425. *
  426. * @see #getSelectionModel()
  427. *
  428. * @return set of selected items
  429. */
  430. public Set<T> getSelectedItems() {
  431. return treeGrid.getSelectedItems();
  432. }
  433. /**
  434. * This method is a shorthand that delegates to the currently set selection
  435. * model.
  436. *
  437. * @param item
  438. * item to select
  439. *
  440. * @see SelectionModel#select(Object)
  441. * @see #getSelectionModel()
  442. */
  443. public void select(T item) {
  444. treeGrid.select(item);
  445. }
  446. /**
  447. * This method is a shorthand that delegates to the currently set selection
  448. * model.
  449. *
  450. * @param item
  451. * item to deselect
  452. *
  453. * @see SelectionModel#deselect(Object)
  454. * @see #getSelectionModel()
  455. */
  456. public void deselect(T item) {
  457. treeGrid.deselect(item);
  458. }
  459. /**
  460. * Adds a selection listener to the current selection model.
  461. * <p>
  462. * <strong>NOTE:</strong> If selection mode is switched with
  463. * {@link #setSelectionMode(SelectionMode)}, then this listener is not
  464. * triggered anymore when selection changes!
  465. *
  466. * @param listener
  467. * the listener to add
  468. * @return a registration handle to remove the listener
  469. *
  470. * @throws UnsupportedOperationException
  471. * if selection has been disabled with
  472. * {@link SelectionMode#NONE}
  473. */
  474. public Registration addSelectionListener(SelectionListener<T> listener) {
  475. return treeGrid.addSelectionListener(listener);
  476. }
  477. /**
  478. * Use this tree as a single select in {@link Binder}. Throws
  479. * {@link IllegalStateException} if the tree is not using
  480. * {@link SelectionMode#SINGLE}.
  481. *
  482. * @return the single select wrapper that can be used in binder
  483. */
  484. public SingleSelect<T> asSingleSelect() {
  485. return treeGrid.asSingleSelect();
  486. }
  487. /**
  488. * Returns the selection model for this Tree.
  489. *
  490. * @return the selection model, not <code>null</code>
  491. */
  492. public SelectionModel<T> getSelectionModel() {
  493. return treeGrid.getSelectionModel();
  494. }
  495. /**
  496. * Sets the item caption generator that is used to produce the strings shown
  497. * as the text for each item. By default, {@link String#valueOf(Object)} is
  498. * used.
  499. *
  500. * @param captionGenerator
  501. * the item caption provider to use, not <code>null</code>
  502. */
  503. public void setItemCaptionGenerator(
  504. ItemCaptionGenerator<T> captionGenerator) {
  505. Objects.requireNonNull(captionGenerator,
  506. "Caption generator must not be null");
  507. this.captionGenerator = captionGenerator;
  508. treeGrid.getDataCommunicator().reset();
  509. }
  510. /**
  511. * Sets the item icon generator that is used to produce custom icons for
  512. * items. The generator can return <code>null</code> for items with no icon.
  513. *
  514. * @see IconGenerator
  515. *
  516. * @param iconGenerator
  517. * the item icon generator to set, not <code>null</code>
  518. * @throws NullPointerException
  519. * if {@code itemIconGenerator} is {@code null}
  520. */
  521. public void setItemIconGenerator(IconGenerator<T> iconGenerator) {
  522. Objects.requireNonNull(iconGenerator,
  523. "Item icon generator must not be null");
  524. this.iconProvider = iconGenerator;
  525. treeGrid.getDataCommunicator().reset();
  526. }
  527. /**
  528. * Sets the item collapse allowed provider for this Tree. The provider
  529. * should return {@code true} for any item that the user can collapse.
  530. * <p>
  531. * <strong>Note:</strong> This callback will be accessed often when sending
  532. * data to the client. The callback should not do any costly operations.
  533. *
  534. * @param provider
  535. * the item collapse allowed provider, not {@code null}
  536. */
  537. public void setItemCollapseAllowedProvider(
  538. ItemCollapseAllowedProvider<T> provider) {
  539. treeGrid.setItemCollapseAllowedProvider(provider);
  540. }
  541. /**
  542. * Sets the style generator that is used for generating class names for
  543. * items in this tree. Returning null from the generator results in no
  544. * custom style name being set.
  545. *
  546. * @see StyleGenerator
  547. *
  548. * @param styleGenerator
  549. * the item style generator to set, not {@code null}
  550. * @throws NullPointerException
  551. * if {@code styleGenerator} is {@code null}
  552. */
  553. public void setStyleGenerator(StyleGenerator<T> styleGenerator) {
  554. treeGrid.setStyleGenerator(styleGenerator);
  555. }
  556. /**
  557. * Sets the description generator that is used for generating tooltip
  558. * descriptions for items.
  559. *
  560. * @since 8.2
  561. * @param descriptionGenerator
  562. * the item description generator to set, or <code>null</code> to
  563. * remove a previously set generator
  564. */
  565. public void setItemDescriptionGenerator(
  566. DescriptionGenerator<T> descriptionGenerator) {
  567. treeGrid.setDescriptionGenerator(descriptionGenerator);
  568. }
  569. /**
  570. * Gets the item caption generator.
  571. *
  572. * @return the item caption generator
  573. */
  574. public ItemCaptionGenerator<T> getItemCaptionGenerator() {
  575. return captionGenerator;
  576. }
  577. /**
  578. * Gets the item icon generator.
  579. *
  580. * @see IconGenerator
  581. *
  582. * @return the item icon generator
  583. */
  584. public IconGenerator<T> getItemIconGenerator() {
  585. return iconProvider;
  586. }
  587. /**
  588. * Gets the item collapse allowed provider.
  589. *
  590. * @return the item collapse allowed provider
  591. */
  592. public ItemCollapseAllowedProvider<T> getItemCollapseAllowedProvider() {
  593. return treeGrid.getItemCollapseAllowedProvider();
  594. }
  595. /**
  596. * Gets the style generator.
  597. *
  598. * @see StyleGenerator
  599. *
  600. * @return the item style generator
  601. */
  602. public StyleGenerator<T> getStyleGenerator() {
  603. return treeGrid.getStyleGenerator();
  604. }
  605. /**
  606. * Gets the item description generator.
  607. *
  608. * @since 8.2
  609. * @return the item description generator
  610. */
  611. public DescriptionGenerator<T> getItemDescriptionGenerator() {
  612. return treeGrid.getDescriptionGenerator();
  613. }
  614. /**
  615. * Adds an item click listener. The listener is called when an item of this
  616. * {@code Tree} is clicked.
  617. *
  618. * @param listener
  619. * the item click listener, not null
  620. * @return a registration for the listener
  621. * @see #addContextClickListener
  622. */
  623. public Registration addItemClickListener(ItemClickListener<T> listener) {
  624. return addListener(ItemClick.class, listener, ITEM_CLICK_METHOD);
  625. }
  626. /**
  627. * Sets the tree's selection mode.
  628. * <p>
  629. * The built-in selection modes are:
  630. * <ul>
  631. * <li>{@link SelectionMode#SINGLE} <b>the default model</b></li>
  632. * <li>{@link SelectionMode#MULTI}</li>
  633. * <li>{@link SelectionMode#NONE} preventing selection</li>
  634. * </ul>
  635. *
  636. * @param selectionMode
  637. * the selection mode to switch to, not {@code null}
  638. * @return the used selection model
  639. *
  640. * @see SelectionMode
  641. */
  642. public SelectionModel<T> setSelectionMode(SelectionMode selectionMode) {
  643. Objects.requireNonNull(selectionMode,
  644. "Can not set selection mode to null");
  645. switch (selectionMode) {
  646. case MULTI:
  647. TreeMultiSelectionModel<T> model = new TreeMultiSelectionModel<>();
  648. treeGrid.setSelectionModel(model);
  649. return model;
  650. default:
  651. return treeGrid.setSelectionMode(selectionMode);
  652. }
  653. }
  654. private SelectionMode getSelectionMode() {
  655. SelectionModel<T> selectionModel = getSelectionModel();
  656. SelectionMode mode = null;
  657. if (selectionModel.getClass().equals(SingleSelectionModelImpl.class)) {
  658. mode = SelectionMode.SINGLE;
  659. } else if (selectionModel.getClass()
  660. .equals(TreeMultiSelectionModel.class)) {
  661. mode = SelectionMode.MULTI;
  662. } else if (selectionModel.getClass().equals(NoSelectionModel.class)) {
  663. mode = SelectionMode.NONE;
  664. }
  665. return mode;
  666. }
  667. @Override
  668. public void setCaption(String caption) {
  669. treeGrid.setCaption(caption);
  670. }
  671. @Override
  672. public String getCaption() {
  673. return treeGrid.getCaption();
  674. }
  675. @Override
  676. public void setIcon(Resource icon) {
  677. treeGrid.setIcon(icon);
  678. }
  679. @Override
  680. public Resource getIcon() {
  681. return treeGrid.getIcon();
  682. }
  683. @Override
  684. public String getStyleName() {
  685. return treeGrid.getStyleName();
  686. }
  687. @Override
  688. public void setStyleName(String style) {
  689. treeGrid.setStyleName(style);
  690. }
  691. @Override
  692. public void setStyleName(String style, boolean add) {
  693. treeGrid.setStyleName(style, add);
  694. }
  695. @Override
  696. public void addStyleName(String style) {
  697. treeGrid.addStyleName(style);
  698. }
  699. @Override
  700. public void removeStyleName(String style) {
  701. treeGrid.removeStyleName(style);
  702. }
  703. @Override
  704. public String getPrimaryStyleName() {
  705. return treeGrid.getPrimaryStyleName();
  706. }
  707. @Override
  708. public void setPrimaryStyleName(String style) {
  709. treeGrid.setPrimaryStyleName(style);
  710. }
  711. @Override
  712. public void setId(String id) {
  713. treeGrid.setId(id);
  714. }
  715. @Override
  716. public String getId() {
  717. return treeGrid.getId();
  718. }
  719. @Override
  720. public void setCaptionAsHtml(boolean captionAsHtml) {
  721. treeGrid.setCaptionAsHtml(captionAsHtml);
  722. }
  723. @Override
  724. public boolean isCaptionAsHtml() {
  725. return treeGrid.isCaptionAsHtml();
  726. }
  727. @Override
  728. public void setDescription(String description) {
  729. treeGrid.setDescription(description);
  730. }
  731. @Override
  732. public void setDescription(String description, ContentMode mode) {
  733. treeGrid.setDescription(description, mode);
  734. }
  735. @Override
  736. public ErrorMessage getErrorMessage() {
  737. return treeGrid.getErrorMessage();
  738. }
  739. @Override
  740. public ErrorMessage getComponentError() {
  741. return treeGrid.getComponentError();
  742. }
  743. @Override
  744. public void setComponentError(ErrorMessage componentError) {
  745. treeGrid.setComponentError(componentError);
  746. }
  747. /**
  748. * Sets the height of a row. If -1 (default), the row height is calculated
  749. * based on the theme for an empty row before the Tree is displayed.
  750. *
  751. * @param rowHeight
  752. * The height of a row in pixels or -1 for automatic calculation
  753. */
  754. public void setRowHeight(double rowHeight) {
  755. treeGrid.setRowHeight(rowHeight);
  756. }
  757. /**
  758. * Gets the currently set content mode of the item captions of this Tree.
  759. *
  760. * @since 8.1.3
  761. * @see ContentMode
  762. * @return the content mode of the item captions of this Tree
  763. */
  764. public ContentMode getContentMode() {
  765. return renderer.getState(false).mode;
  766. }
  767. /**
  768. * Sets the content mode of the item caption.
  769. *
  770. * @see ContentMode
  771. * @param contentMode
  772. * the content mode
  773. */
  774. public void setContentMode(ContentMode contentMode) {
  775. renderer.getState().mode = contentMode;
  776. }
  777. /**
  778. * Returns the current state of automatic width recalculation.
  779. *
  780. * @return {@code true} if enabled; {@code false} if disabled
  781. *
  782. * @since 8.1.1
  783. */
  784. public boolean isAutoRecalculateWidth() {
  785. return autoRecalculateWidth;
  786. }
  787. /**
  788. * Sets the automatic width recalculation on or off. This feature is on by
  789. * default.
  790. *
  791. * @param autoRecalculateWidth
  792. * {@code true} to enable recalculation; {@code false} to turn it
  793. * off
  794. *
  795. * @since 8.1.1
  796. */
  797. public void setAutoRecalculateWidth(boolean autoRecalculateWidth) {
  798. this.autoRecalculateWidth = autoRecalculateWidth;
  799. treeGrid.getColumns().get(0)
  800. .setMinimumWidthFromContent(autoRecalculateWidth);
  801. treeGrid.recalculateColumnWidths();
  802. }
  803. /**
  804. * Adds a context click listener that gets notified when a context click
  805. * happens.
  806. *
  807. * @param listener
  808. * the context click listener to add, not null actual event
  809. * provided to the listener is {@link TreeContextClickEvent}
  810. * @return a registration object for removing the listener
  811. *
  812. * @since 8.1
  813. * @see #addItemClickListener
  814. * @see Registration
  815. */
  816. @Override
  817. public Registration addContextClickListener(
  818. ContextClickEvent.ContextClickListener listener) {
  819. Registration registration = addListener(EventId.CONTEXT_CLICK,
  820. ContextClickEvent.class, listener,
  821. ContextClickEvent.CONTEXT_CLICK_METHOD);
  822. setupContextClickListener();
  823. return () -> {
  824. registration.remove();
  825. setupContextClickListener();
  826. };
  827. }
  828. @Override
  829. @Deprecated
  830. public void removeContextClickListener(
  831. ContextClickEvent.ContextClickListener listener) {
  832. super.removeContextClickListener(listener);
  833. setupContextClickListener();
  834. }
  835. @Override
  836. public void writeDesign(Element design, DesignContext designContext) {
  837. super.writeDesign(design, designContext);
  838. Attributes attrs = design.attributes();
  839. SelectionMode mode = getSelectionMode();
  840. if (mode != null) {
  841. DesignAttributeHandler.writeAttribute("selection-mode", attrs, mode,
  842. SelectionMode.SINGLE, SelectionMode.class, designContext);
  843. }
  844. DesignAttributeHandler.writeAttribute("content-mode", attrs,
  845. getContentMode(), ContentMode.TEXT, ContentMode.class,
  846. designContext);
  847. if (designContext.shouldWriteData(this)) {
  848. writeItems(design, designContext);
  849. }
  850. }
  851. private void writeItems(Element design, DesignContext designContext) {
  852. getDataProvider().fetch(new HierarchicalQuery<>(null, null))
  853. .forEach(item -> writeItem(design, designContext, item, null));
  854. }
  855. private void writeItem(Element design, DesignContext designContext, T item,
  856. T parent) {
  857. Element itemElement = design.appendElement("node");
  858. itemElement.attr("item", serializeDeclarativeRepresentation(item));
  859. if (parent != null) {
  860. itemElement.attr("parent",
  861. serializeDeclarativeRepresentation(parent));
  862. }
  863. if (getSelectionModel().isSelected(item)) {
  864. itemElement.attr("selected", "");
  865. }
  866. Resource icon = getItemIconGenerator().apply(item);
  867. DesignAttributeHandler.writeAttribute("icon", itemElement.attributes(),
  868. icon, null, Resource.class, designContext);
  869. String text = getItemCaptionGenerator().apply(item);
  870. itemElement.html(
  871. Optional.ofNullable(text).map(Object::toString).orElse(""));
  872. getDataProvider().fetch(new HierarchicalQuery<>(null, item)).forEach(
  873. childItem -> writeItem(design, designContext, childItem, item));
  874. }
  875. @Override
  876. public void readDesign(Element design, DesignContext designContext) {
  877. super.readDesign(design, designContext);
  878. Attributes attrs = design.attributes();
  879. if (attrs.hasKey("selection-mode")) {
  880. setSelectionMode(DesignAttributeHandler.readAttribute(
  881. "selection-mode", attrs, SelectionMode.class));
  882. }
  883. if (attrs.hasKey("content-mode")) {
  884. setContentMode(DesignAttributeHandler.readAttribute("content-mode",
  885. attrs, ContentMode.class));
  886. }
  887. readItems(design.children());
  888. }
  889. private void readItems(Elements bodyItems) {
  890. if (bodyItems.isEmpty()) {
  891. return;
  892. }
  893. DeclarativeValueProvider<T> valueProvider = new DeclarativeValueProvider<>();
  894. setItemCaptionGenerator(item -> valueProvider.apply(item));
  895. DeclarativeIconGenerator<T> iconGenerator = new DeclarativeIconGenerator<>(
  896. item -> null);
  897. setItemIconGenerator(iconGenerator);
  898. getSelectionModel().deselectAll();
  899. List<T> selectedItems = new ArrayList<>();
  900. TreeData<T> data = new TreeData<T>();
  901. for (Element row : bodyItems) {
  902. T item = deserializeDeclarativeRepresentation(row.attr("item"));
  903. T parent = null;
  904. if (row.hasAttr("parent")) {
  905. parent = deserializeDeclarativeRepresentation(
  906. row.attr("parent"));
  907. }
  908. data.addItem(parent, item);
  909. if (row.hasAttr("selected")) {
  910. selectedItems.add(item);
  911. }
  912. valueProvider.addValue(item, row.html());
  913. iconGenerator.setIcon(item, DesignAttributeHandler
  914. .readAttribute("icon", row.attributes(), Resource.class));
  915. }
  916. setDataProvider(new TreeDataProvider<>(data));
  917. selectedItems.forEach(getSelectionModel()::select);
  918. }
  919. /**
  920. * Deserializes a string to a data item. Used when reading from the
  921. * declarative format of this Tree.
  922. * <p>
  923. * Default implementation is able to handle only {@link String} as an item
  924. * type. There will be a {@link ClassCastException} if {@code T } is not a
  925. * {@link String}.
  926. *
  927. * @since 8.1.3
  928. *
  929. * @see #serializeDeclarativeRepresentation(Object)
  930. *
  931. * @param item
  932. * string to deserialize
  933. * @throws ClassCastException
  934. * if type {@code T} is not a {@link String}
  935. * @return deserialized item
  936. */
  937. @SuppressWarnings("unchecked")
  938. protected T deserializeDeclarativeRepresentation(String item) {
  939. if (item == null) {
  940. return (T) new String(UUID.randomUUID().toString());
  941. }
  942. return (T) new String(item);
  943. }
  944. /**
  945. * Serializes an {@code item} to a string. Used when saving this Tree to its
  946. * declarative format.
  947. * <p>
  948. * Default implementation delegates a call to {@code item.toString()}.
  949. *
  950. * @since 8.1.3
  951. *
  952. * @see #deserializeDeclarativeRepresentation(String)
  953. *
  954. * @param item
  955. * a data item
  956. * @return string representation of the {@code item}.
  957. */
  958. protected String serializeDeclarativeRepresentation(T item) {
  959. return item.toString();
  960. }
  961. private void setupContextClickListener() {
  962. if (hasListeners(ContextClickEvent.class)) {
  963. if (contextClickRegistration == null) {
  964. contextClickRegistration = treeGrid
  965. .addContextClickListener(event -> {
  966. T item = null;
  967. if (event instanceof Grid.GridContextClickEvent) {
  968. item = ((Grid.GridContextClickEvent<T>) event)
  969. .getItem();
  970. }
  971. fireEvent(new TreeContextClickEvent<>(this,
  972. event.getMouseEventDetails(), item));
  973. });
  974. }
  975. } else if (contextClickRegistration != null) {
  976. contextClickRegistration.remove();
  977. contextClickRegistration = null;
  978. }
  979. }
  980. /**
  981. * ContextClickEvent for the Tree Component.
  982. * <p>
  983. * Usage:
  984. *
  985. * <pre>
  986. * tree.addContextClickListener(event -&gt; Notification.show(
  987. * ((TreeContextClickEvent&lt;Person&gt;) event).getItem() + " Clicked"));
  988. * </pre>
  989. *
  990. * @param <T>
  991. * the tree bean type
  992. * @since 8.1
  993. */
  994. public static class TreeContextClickEvent<T> extends ContextClickEvent {
  995. private final T item;
  996. /**
  997. * Creates a new context click event.
  998. *
  999. * @param source
  1000. * the tree where the context click occurred
  1001. * @param mouseEventDetails
  1002. * details about mouse position
  1003. * @param item
  1004. * the item which was clicked or {@code null} if the click
  1005. * happened outside any item
  1006. */
  1007. public TreeContextClickEvent(Tree<T> source,
  1008. MouseEventDetails mouseEventDetails, T item) {
  1009. super(source, mouseEventDetails);
  1010. this.item = item;
  1011. }
  1012. /**
  1013. * Returns the item of context clicked row.
  1014. *
  1015. * @return clicked item; {@code null} the click happened outside any
  1016. * item
  1017. */
  1018. public T getItem() {
  1019. return item;
  1020. }
  1021. @Override
  1022. public Tree<T> getComponent() {
  1023. return (Tree<T>) super.getComponent();
  1024. }
  1025. }
  1026. /**
  1027. * Scrolls to a certain item, using {@link ScrollDestination#ANY}.
  1028. * <p>
  1029. * If the item has an open details row, its size will also be taken into
  1030. * account.
  1031. *
  1032. * @param row
  1033. * zero based index of the item to scroll to in the current view.
  1034. * @throws IllegalArgumentException
  1035. * if the provided row is outside the item range
  1036. */
  1037. public void scrollTo(int row) throws IllegalArgumentException {
  1038. treeGrid.scrollTo(row, ScrollDestination.ANY);
  1039. }
  1040. /**
  1041. * Scrolls to a certain item, using user-specified scroll destination.
  1042. * <p>
  1043. * If the item has an open details row, its size will also be taken into
  1044. * account.
  1045. *
  1046. * @param row
  1047. * zero based index of the item to scroll to in the current view.
  1048. * @param destination
  1049. * value specifying desired position of scrolled-to row, not
  1050. * {@code null}
  1051. * @throws IllegalArgumentException
  1052. * if the provided row is outside the item range
  1053. */
  1054. public void scrollTo(int row, ScrollDestination destination) {
  1055. treeGrid.scrollTo(row, destination);
  1056. }
  1057. /**
  1058. * Scrolls to the beginning of the first data row.
  1059. */
  1060. public void scrollToStart() {
  1061. treeGrid.scrollToStart();
  1062. }
  1063. /**
  1064. * Scrolls to the end of the last data row.
  1065. */
  1066. public void scrollToEnd() {
  1067. treeGrid.scrollToEnd();
  1068. }
  1069. }