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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  1. /*
  2. * Copyright 2000-2018 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.ui;
  17. import java.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.Component.Focusable;
  59. import com.vaadin.ui.Grid.SelectionMode;
  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>, Focusable {
  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 = createTreeGrid();
  227. /**
  228. * Create inner {@link TreeGrid} object. May be overridden in subclasses.
  229. *
  230. * @return new {@link TreeGrid}
  231. */
  232. protected TreeGrid<T> createTreeGrid() {
  233. return new TreeGrid<>();
  234. }
  235. private ItemCaptionGenerator<T> captionGenerator = String::valueOf;
  236. private IconGenerator<T> iconProvider = t -> null;
  237. private final TreeRenderer renderer;
  238. private boolean autoRecalculateWidth = true;
  239. /**
  240. * Constructs a new Tree Component.
  241. */
  242. public Tree() {
  243. setCompositionRoot(treeGrid);
  244. renderer = new TreeRenderer();
  245. treeGrid.getDataCommunicator().addDataGenerator(renderer);
  246. treeGrid.addColumn(i -> captionGenerator.apply(i), renderer)
  247. .setId("column");
  248. treeGrid.setHierarchyColumn("column");
  249. while (treeGrid.getHeaderRowCount() > 0) {
  250. treeGrid.removeHeaderRow(0);
  251. }
  252. treeGrid.setPrimaryStyleName("v-tree8");
  253. treeGrid.setRowHeight(28);
  254. setWidth("100%");
  255. treeGrid.setHeightUndefined();
  256. treeGrid.setHeightMode(HeightMode.UNDEFINED);
  257. treeGrid.addExpandListener(event -> {
  258. fireExpandEvent(event.getExpandedItem(), event.isUserOriginated());
  259. if (autoRecalculateWidth) {
  260. treeGrid.recalculateColumnWidths();
  261. }
  262. });
  263. treeGrid.addCollapseListener(event -> {
  264. fireCollapseEvent(event.getCollapsedItem(),
  265. event.isUserOriginated());
  266. if (autoRecalculateWidth) {
  267. treeGrid.recalculateColumnWidths();
  268. }
  269. });
  270. treeGrid.addItemClickListener(event -> fireEvent(new ItemClick<>(this,
  271. event.getItem(), event.getMouseEventDetails())));
  272. }
  273. /**
  274. * Constructs a new Tree Component with given caption.
  275. *
  276. * @param caption
  277. * the caption for component
  278. */
  279. public Tree(String caption) {
  280. this();
  281. setCaption(caption);
  282. }
  283. /**
  284. * Constructs a new Tree Component with given caption and {@code TreeData}.
  285. *
  286. * @param caption
  287. * the caption for component
  288. * @param treeData
  289. * the tree data for component
  290. */
  291. public Tree(String caption, TreeData<T> treeData) {
  292. this(caption, new TreeDataProvider<>(treeData));
  293. }
  294. /**
  295. * Constructs a new Tree Component with given caption and
  296. * {@code HierarchicalDataProvider}.
  297. *
  298. * @param caption
  299. * the caption for component
  300. * @param dataProvider
  301. * the hierarchical data provider for component
  302. */
  303. public Tree(String caption, HierarchicalDataProvider<T, ?> dataProvider) {
  304. this(caption);
  305. treeGrid.setDataProvider(dataProvider);
  306. }
  307. /**
  308. * Constructs a new Tree Component with given
  309. * {@code HierarchicalDataProvider}.
  310. *
  311. * @param dataProvider
  312. * the hierarchical data provider for component
  313. */
  314. public Tree(HierarchicalDataProvider<T, ?> dataProvider) {
  315. this(null, dataProvider);
  316. }
  317. @Override
  318. public HierarchicalDataProvider<T, ?> getDataProvider() {
  319. return treeGrid.getDataProvider();
  320. }
  321. @Override
  322. public void setDataProvider(DataProvider<T, ?> dataProvider) {
  323. treeGrid.setDataProvider(dataProvider);
  324. }
  325. /**
  326. * Adds an ExpandListener to this Tree.
  327. *
  328. * @see ExpandEvent
  329. *
  330. * @param listener
  331. * the listener to add
  332. * @return a registration for the listener
  333. */
  334. public Registration addExpandListener(ExpandListener<T> listener) {
  335. return addListener(ExpandEvent.class, listener,
  336. ExpandListener.EXPAND_METHOD);
  337. }
  338. /**
  339. * Adds a CollapseListener to this Tree.
  340. *
  341. * @see CollapseEvent
  342. *
  343. * @param listener
  344. * the listener to add
  345. * @return a registration for the listener
  346. */
  347. public Registration addCollapseListener(CollapseListener<T> listener) {
  348. return addListener(CollapseEvent.class, listener,
  349. CollapseListener.COLLAPSE_METHOD);
  350. }
  351. /**
  352. * Fires an expand event with given item.
  353. *
  354. * @param item
  355. * the expanded item
  356. * @param userOriginated
  357. * whether the expand was triggered by a user interaction or the
  358. * server
  359. */
  360. protected void fireExpandEvent(T item, boolean userOriginated) {
  361. fireEvent(new ExpandEvent<>(this, item, userOriginated));
  362. }
  363. /**
  364. * Fires a collapse event with given item.
  365. *
  366. * @param item
  367. * the collapsed item
  368. * @param userOriginated
  369. * whether the collapse was triggered by a user interaction or
  370. * the server
  371. */
  372. protected void fireCollapseEvent(T item, boolean userOriginated) {
  373. fireEvent(new CollapseEvent<>(this, item, userOriginated));
  374. }
  375. /**
  376. * Expands the given items.
  377. * <p>
  378. * If an item is currently expanded, does nothing. If an item does not have
  379. * any children, does nothing.
  380. *
  381. * @param items
  382. * the items to expand
  383. */
  384. public void expand(T... items) {
  385. treeGrid.expand(items);
  386. }
  387. /**
  388. * Expands the given items.
  389. * <p>
  390. * If an item is currently expanded, does nothing. If an item does not have
  391. * any children, does nothing.
  392. *
  393. * @param items
  394. * the items to expand
  395. */
  396. public void expand(Collection<T> items) {
  397. treeGrid.expand(items);
  398. }
  399. /**
  400. * Expands the given items and their children recursively until the given
  401. * depth.
  402. * <p>
  403. * {@code depth} describes the maximum distance between a given item and its
  404. * descendant, meaning that {@code expandRecursively(items, 0)} expands only
  405. * the given items while {@code expandRecursively(items, 2)} expands the
  406. * given items as well as their children and grandchildren.
  407. *
  408. * @param items
  409. * the items to expand recursively
  410. * @param depth
  411. * the maximum depth of recursion
  412. * @since 8.4
  413. */
  414. public void expandRecursively(Collection<T> items, int depth) {
  415. treeGrid.expandRecursively(items, depth);
  416. }
  417. /**
  418. * Collapse the given items.
  419. * <p>
  420. * For items that are already collapsed, does nothing.
  421. *
  422. * @param items
  423. * the collection of items to collapse
  424. */
  425. public void collapse(T... items) {
  426. treeGrid.collapse(items);
  427. }
  428. /**
  429. * Collapse the given items.
  430. * <p>
  431. * For items that are already collapsed, does nothing.
  432. *
  433. * @param items
  434. * the collection of items to collapse
  435. */
  436. public void collapse(Collection<T> items) {
  437. treeGrid.collapse(items);
  438. }
  439. /**
  440. * Collapse the given items and their children recursively until the given
  441. * depth.
  442. * <p>
  443. * {@code depth} describes the maximum distance between a given item and its
  444. * descendant, meaning that {@code collapseRecursively(items, 0)} collapses
  445. * only the given items while {@code collapseRecursively(items, 2)}
  446. * collapses the given items as well as their children and grandchildren.
  447. *
  448. * @param items
  449. * the items to expand recursively
  450. * @param depth
  451. * the maximum depth of recursion
  452. * @since 8.4
  453. */
  454. public void collapseRecursively(Collection<T> items, int depth) {
  455. treeGrid.collapseRecursively(items, depth);
  456. }
  457. /**
  458. * Returns whether a given item is expanded or collapsed.
  459. *
  460. * @param item
  461. * the item to check
  462. * @return true if the item is expanded, false if collapsed
  463. */
  464. public boolean isExpanded(T item) {
  465. return treeGrid.isExpanded(item);
  466. }
  467. /**
  468. * This method is a shorthand that delegates to the currently set selection
  469. * model.
  470. *
  471. * @see #getSelectionModel()
  472. *
  473. * @return set of selected items
  474. */
  475. public Set<T> getSelectedItems() {
  476. return treeGrid.getSelectedItems();
  477. }
  478. /**
  479. * This method is a shorthand that delegates to the currently set selection
  480. * model.
  481. *
  482. * @param item
  483. * item to select
  484. *
  485. * @see SelectionModel#select(Object)
  486. * @see #getSelectionModel()
  487. */
  488. public void select(T item) {
  489. treeGrid.select(item);
  490. }
  491. /**
  492. * This method is a shorthand that delegates to the currently set selection
  493. * model.
  494. *
  495. * @param item
  496. * item to deselect
  497. *
  498. * @see SelectionModel#deselect(Object)
  499. * @see #getSelectionModel()
  500. */
  501. public void deselect(T item) {
  502. treeGrid.deselect(item);
  503. }
  504. /**
  505. * Adds a selection listener to the current selection model.
  506. * <p>
  507. * <strong>NOTE:</strong> If selection mode is switched with
  508. * {@link #setSelectionMode(SelectionMode)}, then this listener is not
  509. * triggered anymore when selection changes!
  510. *
  511. * @param listener
  512. * the listener to add
  513. * @return a registration handle to remove the listener
  514. *
  515. * @throws UnsupportedOperationException
  516. * if selection has been disabled with
  517. * {@link SelectionMode#NONE}
  518. */
  519. public Registration addSelectionListener(SelectionListener<T> listener) {
  520. return treeGrid.addSelectionListener(listener);
  521. }
  522. /**
  523. * Use this tree as a single select in {@link Binder}. Throws
  524. * {@link IllegalStateException} if the tree is not using
  525. * {@link SelectionMode#SINGLE}.
  526. *
  527. * @return the single select wrapper that can be used in binder
  528. */
  529. public SingleSelect<T> asSingleSelect() {
  530. return treeGrid.asSingleSelect();
  531. }
  532. /**
  533. * Returns the selection model for this Tree.
  534. *
  535. * @return the selection model, not <code>null</code>
  536. */
  537. public SelectionModel<T> getSelectionModel() {
  538. return treeGrid.getSelectionModel();
  539. }
  540. /**
  541. * Sets the item caption generator that is used to produce the strings shown
  542. * as the text for each item. By default, {@link String#valueOf(Object)} is
  543. * used.
  544. *
  545. * @param captionGenerator
  546. * the item caption provider to use, not <code>null</code>
  547. */
  548. public void setItemCaptionGenerator(
  549. ItemCaptionGenerator<T> captionGenerator) {
  550. Objects.requireNonNull(captionGenerator,
  551. "Caption generator must not be null");
  552. this.captionGenerator = captionGenerator;
  553. treeGrid.getDataCommunicator().reset();
  554. }
  555. /**
  556. * Sets the item icon generator that is used to produce custom icons for
  557. * items. The generator can return <code>null</code> for items with no icon.
  558. *
  559. * @see IconGenerator
  560. *
  561. * @param iconGenerator
  562. * the item icon generator to set, not <code>null</code>
  563. * @throws NullPointerException
  564. * if {@code itemIconGenerator} is {@code null}
  565. */
  566. public void setItemIconGenerator(IconGenerator<T> iconGenerator) {
  567. Objects.requireNonNull(iconGenerator,
  568. "Item icon generator must not be null");
  569. this.iconProvider = iconGenerator;
  570. treeGrid.getDataCommunicator().reset();
  571. }
  572. /**
  573. * Sets the item collapse allowed provider for this Tree. The provider
  574. * should return {@code true} for any item that the user can collapse.
  575. * <p>
  576. * <strong>Note:</strong> This callback will be accessed often when sending
  577. * data to the client. The callback should not do any costly operations.
  578. *
  579. * @param provider
  580. * the item collapse allowed provider, not {@code null}
  581. */
  582. public void setItemCollapseAllowedProvider(
  583. ItemCollapseAllowedProvider<T> provider) {
  584. treeGrid.setItemCollapseAllowedProvider(provider);
  585. }
  586. /**
  587. * Sets the style generator that is used for generating class names for
  588. * items in this tree. Returning null from the generator results in no
  589. * custom style name being set.
  590. *
  591. * @see StyleGenerator
  592. *
  593. * @param styleGenerator
  594. * the item style generator to set, not {@code null}
  595. * @throws NullPointerException
  596. * if {@code styleGenerator} is {@code null}
  597. */
  598. public void setStyleGenerator(StyleGenerator<T> styleGenerator) {
  599. treeGrid.setStyleGenerator(styleGenerator);
  600. }
  601. /**
  602. * Sets the description generator that is used for generating tooltip
  603. * descriptions for items.
  604. *
  605. * @since 8.2
  606. * @param descriptionGenerator
  607. * the item description generator to set, or <code>null</code> to
  608. * remove a previously set generator
  609. */
  610. public void setItemDescriptionGenerator(
  611. DescriptionGenerator<T> descriptionGenerator) {
  612. treeGrid.setDescriptionGenerator(descriptionGenerator);
  613. }
  614. /**
  615. * Sets the description generator that is used for generating HTML tooltip
  616. * descriptions for items.
  617. *
  618. * @param descriptionGenerator
  619. * the item description generator to set, or <code>null</code> to
  620. * remove a previously set generator
  621. * @param contentMode
  622. * how client should interpret textual values
  623. *
  624. * @since 8.4
  625. */
  626. public void setItemDescriptionGenerator(
  627. DescriptionGenerator<T> descriptionGenerator,
  628. ContentMode contentMode) {
  629. treeGrid.setDescriptionGenerator(descriptionGenerator, contentMode);
  630. }
  631. /**
  632. * Gets the item caption generator.
  633. *
  634. * @return the item caption generator
  635. */
  636. public ItemCaptionGenerator<T> getItemCaptionGenerator() {
  637. return captionGenerator;
  638. }
  639. /**
  640. * Gets the item icon generator.
  641. *
  642. * @see IconGenerator
  643. *
  644. * @return the item icon generator
  645. */
  646. public IconGenerator<T> getItemIconGenerator() {
  647. return iconProvider;
  648. }
  649. /**
  650. * Gets the item collapse allowed provider.
  651. *
  652. * @return the item collapse allowed provider
  653. */
  654. public ItemCollapseAllowedProvider<T> getItemCollapseAllowedProvider() {
  655. return treeGrid.getItemCollapseAllowedProvider();
  656. }
  657. /**
  658. * Gets the style generator.
  659. *
  660. * @see StyleGenerator
  661. *
  662. * @return the item style generator
  663. */
  664. public StyleGenerator<T> getStyleGenerator() {
  665. return treeGrid.getStyleGenerator();
  666. }
  667. /**
  668. * Gets the item description generator.
  669. *
  670. * @since 8.2
  671. * @return the item description generator
  672. */
  673. public DescriptionGenerator<T> getItemDescriptionGenerator() {
  674. return treeGrid.getDescriptionGenerator();
  675. }
  676. /**
  677. * Adds an item click listener. The listener is called when an item of this
  678. * {@code Tree} is clicked.
  679. *
  680. * @param listener
  681. * the item click listener, not null
  682. * @return a registration for the listener
  683. * @see #addContextClickListener
  684. */
  685. public Registration addItemClickListener(ItemClickListener<T> listener) {
  686. return addListener(ItemClick.class, listener, ITEM_CLICK_METHOD);
  687. }
  688. /**
  689. * Sets the tree's selection mode.
  690. * <p>
  691. * The built-in selection modes are:
  692. * <ul>
  693. * <li>{@link SelectionMode#SINGLE} <b>the default model</b></li>
  694. * <li>{@link SelectionMode#MULTI}</li>
  695. * <li>{@link SelectionMode#NONE} preventing selection</li>
  696. * </ul>
  697. *
  698. * @param selectionMode
  699. * the selection mode to switch to, not {@code null}
  700. * @return the used selection model
  701. *
  702. * @see SelectionMode
  703. */
  704. public SelectionModel<T> setSelectionMode(SelectionMode selectionMode) {
  705. Objects.requireNonNull(selectionMode,
  706. "Can not set selection mode to null");
  707. switch (selectionMode) {
  708. case MULTI:
  709. TreeMultiSelectionModel<T> model = new TreeMultiSelectionModel<>();
  710. treeGrid.setSelectionModel(model);
  711. return model;
  712. default:
  713. return treeGrid.setSelectionMode(selectionMode);
  714. }
  715. }
  716. private SelectionMode getSelectionMode() {
  717. SelectionModel<T> selectionModel = getSelectionModel();
  718. SelectionMode mode = null;
  719. if (selectionModel.getClass().equals(SingleSelectionModelImpl.class)) {
  720. mode = SelectionMode.SINGLE;
  721. } else if (selectionModel.getClass()
  722. .equals(TreeMultiSelectionModel.class)) {
  723. mode = SelectionMode.MULTI;
  724. } else if (selectionModel.getClass().equals(NoSelectionModel.class)) {
  725. mode = SelectionMode.NONE;
  726. }
  727. return mode;
  728. }
  729. @Override
  730. public void setCaption(String caption) {
  731. treeGrid.setCaption(caption);
  732. }
  733. @Override
  734. public String getCaption() {
  735. return treeGrid.getCaption();
  736. }
  737. @Override
  738. public void setIcon(Resource icon) {
  739. treeGrid.setIcon(icon);
  740. }
  741. @Override
  742. public Resource getIcon() {
  743. return treeGrid.getIcon();
  744. }
  745. @Override
  746. public String getStyleName() {
  747. return treeGrid.getStyleName();
  748. }
  749. @Override
  750. public void setStyleName(String style) {
  751. treeGrid.setStyleName(style);
  752. }
  753. @Override
  754. public void setStyleName(String style, boolean add) {
  755. treeGrid.setStyleName(style, add);
  756. }
  757. @Override
  758. public void addStyleName(String style) {
  759. treeGrid.addStyleName(style);
  760. }
  761. @Override
  762. public void removeStyleName(String style) {
  763. treeGrid.removeStyleName(style);
  764. }
  765. @Override
  766. public String getPrimaryStyleName() {
  767. return treeGrid.getPrimaryStyleName();
  768. }
  769. @Override
  770. public void setPrimaryStyleName(String style) {
  771. treeGrid.setPrimaryStyleName(style);
  772. }
  773. @Override
  774. public void setId(String id) {
  775. treeGrid.setId(id);
  776. }
  777. @Override
  778. public String getId() {
  779. return treeGrid.getId();
  780. }
  781. @Override
  782. public void setCaptionAsHtml(boolean captionAsHtml) {
  783. treeGrid.setCaptionAsHtml(captionAsHtml);
  784. }
  785. @Override
  786. public boolean isCaptionAsHtml() {
  787. return treeGrid.isCaptionAsHtml();
  788. }
  789. @Override
  790. public void setDescription(String description) {
  791. treeGrid.setDescription(description);
  792. }
  793. @Override
  794. public void setDescription(String description, ContentMode mode) {
  795. treeGrid.setDescription(description, mode);
  796. }
  797. @Override
  798. public ErrorMessage getErrorMessage() {
  799. return treeGrid.getErrorMessage();
  800. }
  801. @Override
  802. public ErrorMessage getComponentError() {
  803. return treeGrid.getComponentError();
  804. }
  805. @Override
  806. public void setComponentError(ErrorMessage componentError) {
  807. treeGrid.setComponentError(componentError);
  808. }
  809. /**
  810. * Sets the height of a row. If -1 (default), the row height is calculated
  811. * based on the theme for an empty row before the Tree is displayed.
  812. *
  813. * @param rowHeight
  814. * The height of a row in pixels or -1 for automatic calculation
  815. */
  816. public void setRowHeight(double rowHeight) {
  817. treeGrid.setRowHeight(rowHeight);
  818. }
  819. /**
  820. * Gets the currently set content mode of the item captions of this Tree.
  821. *
  822. * @since 8.1.3
  823. * @see ContentMode
  824. * @return the content mode of the item captions of this Tree
  825. */
  826. public ContentMode getContentMode() {
  827. return renderer.getState(false).mode;
  828. }
  829. /**
  830. * Sets the content mode of the item caption.
  831. *
  832. * @see ContentMode
  833. * @param contentMode
  834. * the content mode
  835. */
  836. public void setContentMode(ContentMode contentMode) {
  837. renderer.getState().mode = contentMode;
  838. }
  839. /**
  840. * Returns the current state of automatic width recalculation.
  841. *
  842. * @return {@code true} if enabled; {@code false} if disabled
  843. *
  844. * @since 8.1.1
  845. */
  846. public boolean isAutoRecalculateWidth() {
  847. return autoRecalculateWidth;
  848. }
  849. /**
  850. * Sets the automatic width recalculation on or off. This feature is on by
  851. * default.
  852. *
  853. * @param autoRecalculateWidth
  854. * {@code true} to enable recalculation; {@code false} to turn it
  855. * off
  856. *
  857. * @since 8.1.1
  858. */
  859. public void setAutoRecalculateWidth(boolean autoRecalculateWidth) {
  860. this.autoRecalculateWidth = autoRecalculateWidth;
  861. treeGrid.getColumns().get(0)
  862. .setMinimumWidthFromContent(autoRecalculateWidth);
  863. treeGrid.recalculateColumnWidths();
  864. }
  865. /**
  866. * Adds a context click listener that gets notified when a context click
  867. * happens.
  868. *
  869. * @param listener
  870. * the context click listener to add, not null actual event
  871. * provided to the listener is {@link TreeContextClickEvent}
  872. * @return a registration object for removing the listener
  873. *
  874. * @since 8.1
  875. * @see #addItemClickListener
  876. * @see Registration
  877. */
  878. @Override
  879. public Registration addContextClickListener(
  880. ContextClickEvent.ContextClickListener listener) {
  881. Registration registration = addListener(EventId.CONTEXT_CLICK,
  882. ContextClickEvent.class, listener,
  883. ContextClickEvent.CONTEXT_CLICK_METHOD);
  884. setupContextClickListener();
  885. return () -> {
  886. registration.remove();
  887. setupContextClickListener();
  888. };
  889. }
  890. @Override
  891. @Deprecated
  892. public void removeContextClickListener(
  893. ContextClickEvent.ContextClickListener listener) {
  894. super.removeContextClickListener(listener);
  895. setupContextClickListener();
  896. }
  897. @Override
  898. public void writeDesign(Element design, DesignContext designContext) {
  899. super.writeDesign(design, designContext);
  900. Attributes attrs = design.attributes();
  901. SelectionMode mode = getSelectionMode();
  902. if (mode != null) {
  903. DesignAttributeHandler.writeAttribute("selection-mode", attrs, mode,
  904. SelectionMode.SINGLE, SelectionMode.class, designContext);
  905. }
  906. DesignAttributeHandler.writeAttribute("content-mode", attrs,
  907. getContentMode(), ContentMode.TEXT, ContentMode.class,
  908. designContext);
  909. if (designContext.shouldWriteData(this)) {
  910. writeItems(design, designContext);
  911. }
  912. }
  913. private void writeItems(Element design, DesignContext designContext) {
  914. getDataProvider().fetch(new HierarchicalQuery<>(null, null))
  915. .forEach(item -> writeItem(design, designContext, item, null));
  916. }
  917. private void writeItem(Element design, DesignContext designContext, T item,
  918. T parent) {
  919. Element itemElement = design.appendElement("node");
  920. itemElement.attr("item", serializeDeclarativeRepresentation(item));
  921. if (parent != null) {
  922. itemElement.attr("parent",
  923. serializeDeclarativeRepresentation(parent));
  924. }
  925. if (getSelectionModel().isSelected(item)) {
  926. itemElement.attr("selected", true);
  927. }
  928. Resource icon = getItemIconGenerator().apply(item);
  929. DesignAttributeHandler.writeAttribute("icon", itemElement.attributes(),
  930. icon, null, Resource.class, designContext);
  931. String text = getItemCaptionGenerator().apply(item);
  932. itemElement.html(
  933. Optional.ofNullable(text).map(Object::toString).orElse(""));
  934. getDataProvider().fetch(new HierarchicalQuery<>(null, item)).forEach(
  935. childItem -> writeItem(design, designContext, childItem, item));
  936. }
  937. @Override
  938. public void readDesign(Element design, DesignContext designContext) {
  939. super.readDesign(design, designContext);
  940. Attributes attrs = design.attributes();
  941. if (attrs.hasKey("selection-mode")) {
  942. setSelectionMode(DesignAttributeHandler.readAttribute(
  943. "selection-mode", attrs, SelectionMode.class));
  944. }
  945. if (attrs.hasKey("content-mode")) {
  946. setContentMode(DesignAttributeHandler.readAttribute("content-mode",
  947. attrs, ContentMode.class));
  948. }
  949. readItems(design.children());
  950. }
  951. private void readItems(Elements bodyItems) {
  952. if (bodyItems.isEmpty()) {
  953. return;
  954. }
  955. DeclarativeValueProvider<T> valueProvider = new DeclarativeValueProvider<>();
  956. setItemCaptionGenerator(item -> valueProvider.apply(item));
  957. DeclarativeIconGenerator<T> iconGenerator = new DeclarativeIconGenerator<>(
  958. item -> null);
  959. setItemIconGenerator(iconGenerator);
  960. getSelectionModel().deselectAll();
  961. List<T> selectedItems = new ArrayList<>();
  962. TreeData<T> data = new TreeData<T>();
  963. for (Element row : bodyItems) {
  964. T item = deserializeDeclarativeRepresentation(row.attr("item"));
  965. T parent = null;
  966. if (row.hasAttr("parent")) {
  967. parent = deserializeDeclarativeRepresentation(
  968. row.attr("parent"));
  969. }
  970. data.addItem(parent, item);
  971. if (row.hasAttr("selected")) {
  972. selectedItems.add(item);
  973. }
  974. valueProvider.addValue(item, row.html());
  975. iconGenerator.setIcon(item, DesignAttributeHandler
  976. .readAttribute("icon", row.attributes(), Resource.class));
  977. }
  978. setDataProvider(new TreeDataProvider<>(data));
  979. selectedItems.forEach(getSelectionModel()::select);
  980. }
  981. /**
  982. * Deserializes a string to a data item. Used when reading from the
  983. * declarative format of this Tree.
  984. * <p>
  985. * Default implementation is able to handle only {@link String} as an item
  986. * type. There will be a {@link ClassCastException} if {@code T } is not a
  987. * {@link String}.
  988. *
  989. * @since 8.1.3
  990. *
  991. * @see #serializeDeclarativeRepresentation(Object)
  992. *
  993. * @param item
  994. * string to deserialize
  995. * @throws ClassCastException
  996. * if type {@code T} is not a {@link String}
  997. * @return deserialized item
  998. */
  999. @SuppressWarnings("unchecked")
  1000. protected T deserializeDeclarativeRepresentation(String item) {
  1001. if (item == null) {
  1002. return (T) new String(UUID.randomUUID().toString());
  1003. }
  1004. return (T) new String(item);
  1005. }
  1006. /**
  1007. * Serializes an {@code item} to a string. Used when saving this Tree to its
  1008. * declarative format.
  1009. * <p>
  1010. * Default implementation delegates a call to {@code item.toString()}.
  1011. *
  1012. * @since 8.1.3
  1013. *
  1014. * @see #deserializeDeclarativeRepresentation(String)
  1015. *
  1016. * @param item
  1017. * a data item
  1018. * @return string representation of the {@code item}.
  1019. */
  1020. protected String serializeDeclarativeRepresentation(T item) {
  1021. return item.toString();
  1022. }
  1023. private void setupContextClickListener() {
  1024. if (hasListeners(ContextClickEvent.class)) {
  1025. if (contextClickRegistration == null) {
  1026. contextClickRegistration = treeGrid
  1027. .addContextClickListener(event -> {
  1028. T item = null;
  1029. if (event instanceof Grid.GridContextClickEvent) {
  1030. item = ((Grid.GridContextClickEvent<T>) event)
  1031. .getItem();
  1032. }
  1033. fireEvent(new TreeContextClickEvent<>(this,
  1034. event.getMouseEventDetails(), item));
  1035. });
  1036. }
  1037. } else if (contextClickRegistration != null) {
  1038. contextClickRegistration.remove();
  1039. contextClickRegistration = null;
  1040. }
  1041. }
  1042. /**
  1043. * ContextClickEvent for the Tree Component.
  1044. * <p>
  1045. * Usage:
  1046. *
  1047. * <pre>
  1048. * tree.addContextClickListener(event -&gt; Notification.show(
  1049. * ((TreeContextClickEvent&lt;Person&gt;) event).getItem() + " Clicked"));
  1050. * </pre>
  1051. *
  1052. * @param <T>
  1053. * the tree bean type
  1054. * @since 8.1
  1055. */
  1056. public static class TreeContextClickEvent<T> extends ContextClickEvent {
  1057. private final T item;
  1058. /**
  1059. * Creates a new context click event.
  1060. *
  1061. * @param source
  1062. * the tree where the context click occurred
  1063. * @param mouseEventDetails
  1064. * details about mouse position
  1065. * @param item
  1066. * the item which was clicked or {@code null} if the click
  1067. * happened outside any item
  1068. */
  1069. public TreeContextClickEvent(Tree<T> source,
  1070. MouseEventDetails mouseEventDetails, T item) {
  1071. super(source, mouseEventDetails);
  1072. this.item = item;
  1073. }
  1074. /**
  1075. * Returns the item of context clicked row.
  1076. *
  1077. * @return clicked item; {@code null} the click happened outside any
  1078. * item
  1079. */
  1080. public T getItem() {
  1081. return item;
  1082. }
  1083. @Override
  1084. public Tree<T> getComponent() {
  1085. return (Tree<T>) super.getComponent();
  1086. }
  1087. }
  1088. /**
  1089. * Scrolls to a certain item, using {@link ScrollDestination#ANY}.
  1090. * <p>
  1091. * If the item has an open details row, its size will also be taken into
  1092. * account.
  1093. *
  1094. * @param row
  1095. * zero based index of the item to scroll to in the current view.
  1096. * @throws IllegalArgumentException
  1097. * if the provided row is outside the item range
  1098. * @since 8.2
  1099. */
  1100. public void scrollTo(int row) throws IllegalArgumentException {
  1101. treeGrid.scrollTo(row, ScrollDestination.ANY);
  1102. }
  1103. /**
  1104. * Scrolls to a certain item, using user-specified scroll destination.
  1105. * <p>
  1106. * If the item has an open details row, its size will also be taken into
  1107. * account.
  1108. *
  1109. * @param row
  1110. * zero based index of the item to scroll to in the current view.
  1111. * @param destination
  1112. * value specifying desired position of scrolled-to row, not
  1113. * {@code null}
  1114. * @throws IllegalArgumentException
  1115. * if the provided row is outside the item range
  1116. * @since 8.2
  1117. */
  1118. public void scrollTo(int row, ScrollDestination destination) {
  1119. treeGrid.scrollTo(row, destination);
  1120. }
  1121. /**
  1122. * Scrolls to the beginning of the first data row.
  1123. *
  1124. * @since 8.2
  1125. */
  1126. public void scrollToStart() {
  1127. treeGrid.scrollToStart();
  1128. }
  1129. /**
  1130. * Scrolls to the end of the last data row.
  1131. *
  1132. * @since 8.2
  1133. */
  1134. public void scrollToEnd() {
  1135. treeGrid.scrollToEnd();
  1136. }
  1137. @Override
  1138. public int getTabIndex() {
  1139. return treeGrid.getTabIndex();
  1140. }
  1141. @Override
  1142. public void setTabIndex(int tabIndex) {
  1143. treeGrid.setTabIndex(tabIndex);
  1144. }
  1145. @Override
  1146. public void focus() {
  1147. treeGrid.focus();
  1148. }
  1149. }