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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  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 multi select in {@link Binder}. Throws
  524. * {@link IllegalStateException} if the tree is not using
  525. * {@link SelectionMode#MULTI}.
  526. *
  527. * @return the multi select wrapper that can be used in binder
  528. * @since 8.11
  529. */
  530. public MultiSelect<T> asMultiSelect() {
  531. return treeGrid.asMultiSelect();
  532. }
  533. /**
  534. * Use this tree as a single select in {@link Binder}. Throws
  535. * {@link IllegalStateException} if the tree is not using
  536. * {@link SelectionMode#SINGLE}.
  537. *
  538. * @return the single select wrapper that can be used in binder
  539. */
  540. public SingleSelect<T> asSingleSelect() {
  541. return treeGrid.asSingleSelect();
  542. }
  543. /**
  544. * Returns the selection model for this Tree.
  545. *
  546. * @return the selection model, not <code>null</code>
  547. */
  548. public SelectionModel<T> getSelectionModel() {
  549. return treeGrid.getSelectionModel();
  550. }
  551. /**
  552. * Sets the item caption generator that is used to produce the strings shown
  553. * as the text for each item. By default, {@link String#valueOf(Object)} is
  554. * used.
  555. *
  556. * @param captionGenerator
  557. * the item caption provider to use, not <code>null</code>
  558. */
  559. public void setItemCaptionGenerator(
  560. ItemCaptionGenerator<T> captionGenerator) {
  561. Objects.requireNonNull(captionGenerator,
  562. "Caption generator must not be null");
  563. this.captionGenerator = captionGenerator;
  564. treeGrid.getDataCommunicator().reset();
  565. }
  566. /**
  567. * Sets the item icon generator that is used to produce custom icons for
  568. * items. The generator can return <code>null</code> for items with no icon.
  569. *
  570. * @see IconGenerator
  571. *
  572. * @param iconGenerator
  573. * the item icon generator to set, not <code>null</code>
  574. * @throws NullPointerException
  575. * if {@code itemIconGenerator} is {@code null}
  576. */
  577. public void setItemIconGenerator(IconGenerator<T> iconGenerator) {
  578. Objects.requireNonNull(iconGenerator,
  579. "Item icon generator must not be null");
  580. this.iconProvider = iconGenerator;
  581. treeGrid.getDataCommunicator().reset();
  582. }
  583. /**
  584. * Sets the item collapse allowed provider for this Tree. The provider
  585. * should return {@code true} for any item that the user can collapse.
  586. * <p>
  587. * <strong>Note:</strong> This callback will be accessed often when sending
  588. * data to the client. The callback should not do any costly operations.
  589. *
  590. * @param provider
  591. * the item collapse allowed provider, not {@code null}
  592. */
  593. public void setItemCollapseAllowedProvider(
  594. ItemCollapseAllowedProvider<T> provider) {
  595. treeGrid.setItemCollapseAllowedProvider(provider);
  596. }
  597. /**
  598. * Sets the style generator that is used for generating class names for
  599. * items in this tree. Returning null from the generator results in no
  600. * custom style name being set.
  601. *
  602. * @see StyleGenerator
  603. *
  604. * @param styleGenerator
  605. * the item style generator to set, not {@code null}
  606. * @throws NullPointerException
  607. * if {@code styleGenerator} is {@code null}
  608. */
  609. public void setStyleGenerator(StyleGenerator<T> styleGenerator) {
  610. treeGrid.setStyleGenerator(styleGenerator);
  611. }
  612. /**
  613. * Sets the description generator that is used for generating tooltip
  614. * descriptions for items.
  615. *
  616. * @since 8.2
  617. * @param descriptionGenerator
  618. * the item description generator to set, or <code>null</code> to
  619. * remove a previously set generator
  620. */
  621. public void setItemDescriptionGenerator(
  622. DescriptionGenerator<T> descriptionGenerator) {
  623. treeGrid.setDescriptionGenerator(descriptionGenerator);
  624. }
  625. /**
  626. * Sets the description generator that is used for generating HTML tooltip
  627. * descriptions for items.
  628. *
  629. * @param descriptionGenerator
  630. * the item description generator to set, or <code>null</code> to
  631. * remove a previously set generator
  632. * @param contentMode
  633. * how client should interpret textual values
  634. *
  635. * @since 8.4
  636. */
  637. public void setItemDescriptionGenerator(
  638. DescriptionGenerator<T> descriptionGenerator,
  639. ContentMode contentMode) {
  640. treeGrid.setDescriptionGenerator(descriptionGenerator, contentMode);
  641. }
  642. /**
  643. * Gets the item caption generator.
  644. *
  645. * @return the item caption generator
  646. */
  647. public ItemCaptionGenerator<T> getItemCaptionGenerator() {
  648. return captionGenerator;
  649. }
  650. /**
  651. * Gets the item icon generator.
  652. *
  653. * @see IconGenerator
  654. *
  655. * @return the item icon generator
  656. */
  657. public IconGenerator<T> getItemIconGenerator() {
  658. return iconProvider;
  659. }
  660. /**
  661. * Gets the item collapse allowed provider.
  662. *
  663. * @return the item collapse allowed provider
  664. */
  665. public ItemCollapseAllowedProvider<T> getItemCollapseAllowedProvider() {
  666. return treeGrid.getItemCollapseAllowedProvider();
  667. }
  668. /**
  669. * Gets the style generator.
  670. *
  671. * @see StyleGenerator
  672. *
  673. * @return the item style generator
  674. */
  675. public StyleGenerator<T> getStyleGenerator() {
  676. return treeGrid.getStyleGenerator();
  677. }
  678. /**
  679. * Gets the item description generator.
  680. *
  681. * @since 8.2
  682. * @return the item description generator
  683. */
  684. public DescriptionGenerator<T> getItemDescriptionGenerator() {
  685. return treeGrid.getDescriptionGenerator();
  686. }
  687. /**
  688. * Adds an item click listener. The listener is called when an item of this
  689. * {@code Tree} is clicked.
  690. *
  691. * @param listener
  692. * the item click listener, not null
  693. * @return a registration for the listener
  694. * @see #addContextClickListener
  695. */
  696. public Registration addItemClickListener(ItemClickListener<T> listener) {
  697. return addListener(ItemClick.class, listener, ITEM_CLICK_METHOD);
  698. }
  699. /**
  700. * Sets the tree's selection mode.
  701. * <p>
  702. * The built-in selection modes are:
  703. * <ul>
  704. * <li>{@link SelectionMode#SINGLE} <b>the default model</b></li>
  705. * <li>{@link SelectionMode#MULTI}</li>
  706. * <li>{@link SelectionMode#NONE} preventing selection</li>
  707. * </ul>
  708. *
  709. * @param selectionMode
  710. * the selection mode to switch to, not {@code null}
  711. * @return the used selection model
  712. *
  713. * @see SelectionMode
  714. */
  715. public SelectionModel<T> setSelectionMode(SelectionMode selectionMode) {
  716. Objects.requireNonNull(selectionMode,
  717. "Can not set selection mode to null");
  718. switch (selectionMode) {
  719. case MULTI:
  720. TreeMultiSelectionModel<T> model = new TreeMultiSelectionModel<>();
  721. treeGrid.setSelectionModel(model);
  722. return model;
  723. default:
  724. return treeGrid.setSelectionMode(selectionMode);
  725. }
  726. }
  727. private SelectionMode getSelectionMode() {
  728. SelectionModel<T> selectionModel = getSelectionModel();
  729. SelectionMode mode = null;
  730. if (selectionModel.getClass().equals(SingleSelectionModelImpl.class)) {
  731. mode = SelectionMode.SINGLE;
  732. } else if (selectionModel.getClass()
  733. .equals(TreeMultiSelectionModel.class)) {
  734. mode = SelectionMode.MULTI;
  735. } else if (selectionModel.getClass().equals(NoSelectionModel.class)) {
  736. mode = SelectionMode.NONE;
  737. }
  738. return mode;
  739. }
  740. @Override
  741. public void setCaption(String caption) {
  742. treeGrid.setCaption(caption);
  743. }
  744. @Override
  745. public String getCaption() {
  746. return treeGrid.getCaption();
  747. }
  748. @Override
  749. public void setIcon(Resource icon) {
  750. treeGrid.setIcon(icon);
  751. }
  752. @Override
  753. public Resource getIcon() {
  754. return treeGrid.getIcon();
  755. }
  756. @Override
  757. public String getStyleName() {
  758. return treeGrid.getStyleName();
  759. }
  760. @Override
  761. public void setStyleName(String style) {
  762. treeGrid.setStyleName(style);
  763. }
  764. @Override
  765. public void setStyleName(String style, boolean add) {
  766. treeGrid.setStyleName(style, add);
  767. }
  768. @Override
  769. public void addStyleName(String style) {
  770. treeGrid.addStyleName(style);
  771. }
  772. @Override
  773. public void removeStyleName(String style) {
  774. treeGrid.removeStyleName(style);
  775. }
  776. @Override
  777. public String getPrimaryStyleName() {
  778. return treeGrid.getPrimaryStyleName();
  779. }
  780. @Override
  781. public void setPrimaryStyleName(String style) {
  782. treeGrid.setPrimaryStyleName(style);
  783. }
  784. @Override
  785. public void setId(String id) {
  786. treeGrid.setId(id);
  787. }
  788. @Override
  789. public String getId() {
  790. return treeGrid.getId();
  791. }
  792. @Override
  793. public void setCaptionAsHtml(boolean captionAsHtml) {
  794. treeGrid.setCaptionAsHtml(captionAsHtml);
  795. }
  796. @Override
  797. public boolean isCaptionAsHtml() {
  798. return treeGrid.isCaptionAsHtml();
  799. }
  800. @Override
  801. public void setDescription(String description) {
  802. treeGrid.setDescription(description);
  803. }
  804. @Override
  805. public void setDescription(String description, ContentMode mode) {
  806. treeGrid.setDescription(description, mode);
  807. }
  808. @Override
  809. public ErrorMessage getErrorMessage() {
  810. return treeGrid.getErrorMessage();
  811. }
  812. @Override
  813. public ErrorMessage getComponentError() {
  814. return treeGrid.getComponentError();
  815. }
  816. @Override
  817. public void setComponentError(ErrorMessage componentError) {
  818. treeGrid.setComponentError(componentError);
  819. }
  820. /**
  821. * Sets the height of a row. If -1 (default), the row height is calculated
  822. * based on the theme for an empty row before the Tree is displayed.
  823. *
  824. * @param rowHeight
  825. * The height of a row in pixels or -1 for automatic calculation
  826. */
  827. public void setRowHeight(double rowHeight) {
  828. treeGrid.setRowHeight(rowHeight);
  829. }
  830. /**
  831. * Gets the currently set content mode of the item captions of this Tree.
  832. *
  833. * @since 8.1.3
  834. * @see ContentMode
  835. * @return the content mode of the item captions of this Tree
  836. */
  837. public ContentMode getContentMode() {
  838. return renderer.getState(false).mode;
  839. }
  840. /**
  841. * Sets the content mode of the item caption.
  842. *
  843. * @see ContentMode
  844. * @param contentMode
  845. * the content mode
  846. */
  847. public void setContentMode(ContentMode contentMode) {
  848. renderer.getState().mode = contentMode;
  849. }
  850. /**
  851. * Returns the current state of automatic width recalculation.
  852. *
  853. * @return {@code true} if enabled; {@code false} if disabled
  854. *
  855. * @since 8.1.1
  856. */
  857. public boolean isAutoRecalculateWidth() {
  858. return autoRecalculateWidth;
  859. }
  860. /**
  861. * Sets the automatic width recalculation on or off. This feature is on by
  862. * default.
  863. *
  864. * @param autoRecalculateWidth
  865. * {@code true} to enable recalculation; {@code false} to turn it
  866. * off
  867. *
  868. * @since 8.1.1
  869. */
  870. public void setAutoRecalculateWidth(boolean autoRecalculateWidth) {
  871. this.autoRecalculateWidth = autoRecalculateWidth;
  872. treeGrid.getColumns().get(0)
  873. .setMinimumWidthFromContent(autoRecalculateWidth);
  874. treeGrid.recalculateColumnWidths();
  875. }
  876. /**
  877. * Adds a context click listener that gets notified when a context click
  878. * happens.
  879. *
  880. * @param listener
  881. * the context click listener to add, not null actual event
  882. * provided to the listener is {@link TreeContextClickEvent}
  883. * @return a registration object for removing the listener
  884. *
  885. * @since 8.1
  886. * @see #addItemClickListener
  887. * @see Registration
  888. */
  889. @Override
  890. public Registration addContextClickListener(
  891. ContextClickEvent.ContextClickListener listener) {
  892. Registration registration = addListener(EventId.CONTEXT_CLICK,
  893. ContextClickEvent.class, listener,
  894. ContextClickEvent.CONTEXT_CLICK_METHOD);
  895. setupContextClickListener();
  896. return () -> {
  897. registration.remove();
  898. setupContextClickListener();
  899. };
  900. }
  901. @Override
  902. @Deprecated
  903. public void removeContextClickListener(
  904. ContextClickEvent.ContextClickListener listener) {
  905. super.removeContextClickListener(listener);
  906. setupContextClickListener();
  907. }
  908. @Override
  909. public void writeDesign(Element design, DesignContext designContext) {
  910. super.writeDesign(design, designContext);
  911. Attributes attrs = design.attributes();
  912. SelectionMode mode = getSelectionMode();
  913. if (mode != null) {
  914. DesignAttributeHandler.writeAttribute("selection-mode", attrs, mode,
  915. SelectionMode.SINGLE, SelectionMode.class, designContext);
  916. }
  917. DesignAttributeHandler.writeAttribute("content-mode", attrs,
  918. getContentMode(), ContentMode.TEXT, ContentMode.class,
  919. designContext);
  920. if (designContext.shouldWriteData(this)) {
  921. writeItems(design, designContext);
  922. }
  923. }
  924. private void writeItems(Element design, DesignContext designContext) {
  925. getDataProvider().fetch(new HierarchicalQuery<>(null, null))
  926. .forEach(item -> writeItem(design, designContext, item, null));
  927. }
  928. private void writeItem(Element design, DesignContext designContext, T item,
  929. T parent) {
  930. Element itemElement = design.appendElement("node");
  931. itemElement.attr("item", serializeDeclarativeRepresentation(item));
  932. if (parent != null) {
  933. itemElement.attr("parent",
  934. serializeDeclarativeRepresentation(parent));
  935. }
  936. if (getSelectionModel().isSelected(item)) {
  937. itemElement.attr("selected", true);
  938. }
  939. Resource icon = getItemIconGenerator().apply(item);
  940. DesignAttributeHandler.writeAttribute("icon", itemElement.attributes(),
  941. icon, null, Resource.class, designContext);
  942. String text = getItemCaptionGenerator().apply(item);
  943. itemElement.html(
  944. Optional.ofNullable(text).map(Object::toString).orElse(""));
  945. getDataProvider().fetch(new HierarchicalQuery<>(null, item)).forEach(
  946. childItem -> writeItem(design, designContext, childItem, item));
  947. }
  948. @Override
  949. public void readDesign(Element design, DesignContext designContext) {
  950. super.readDesign(design, designContext);
  951. Attributes attrs = design.attributes();
  952. if (attrs.hasKey("selection-mode")) {
  953. setSelectionMode(DesignAttributeHandler.readAttribute(
  954. "selection-mode", attrs, SelectionMode.class));
  955. }
  956. if (attrs.hasKey("content-mode")) {
  957. setContentMode(DesignAttributeHandler.readAttribute("content-mode",
  958. attrs, ContentMode.class));
  959. }
  960. readItems(design.children());
  961. }
  962. private void readItems(Elements bodyItems) {
  963. if (bodyItems.isEmpty()) {
  964. return;
  965. }
  966. DeclarativeValueProvider<T> valueProvider = new DeclarativeValueProvider<>();
  967. setItemCaptionGenerator(item -> valueProvider.apply(item));
  968. DeclarativeIconGenerator<T> iconGenerator = new DeclarativeIconGenerator<>(
  969. item -> null);
  970. setItemIconGenerator(iconGenerator);
  971. getSelectionModel().deselectAll();
  972. List<T> selectedItems = new ArrayList<>();
  973. TreeData<T> data = new TreeData<T>();
  974. for (Element row : bodyItems) {
  975. T item = deserializeDeclarativeRepresentation(row.attr("item"));
  976. T parent = null;
  977. if (row.hasAttr("parent")) {
  978. parent = deserializeDeclarativeRepresentation(
  979. row.attr("parent"));
  980. }
  981. data.addItem(parent, item);
  982. if (row.hasAttr("selected")) {
  983. selectedItems.add(item);
  984. }
  985. valueProvider.addValue(item, row.html());
  986. iconGenerator.setIcon(item, DesignAttributeHandler
  987. .readAttribute("icon", row.attributes(), Resource.class));
  988. }
  989. setDataProvider(new TreeDataProvider<>(data));
  990. selectedItems.forEach(getSelectionModel()::select);
  991. }
  992. /**
  993. * Deserializes a string to a data item. Used when reading from the
  994. * declarative format of this Tree.
  995. * <p>
  996. * Default implementation is able to handle only {@link String} as an item
  997. * type. There will be a {@link ClassCastException} if {@code T } is not a
  998. * {@link String}.
  999. *
  1000. * @since 8.1.3
  1001. *
  1002. * @see #serializeDeclarativeRepresentation(Object)
  1003. *
  1004. * @param item
  1005. * string to deserialize
  1006. * @throws ClassCastException
  1007. * if type {@code T} is not a {@link String}
  1008. * @return deserialized item
  1009. */
  1010. @SuppressWarnings("unchecked")
  1011. protected T deserializeDeclarativeRepresentation(String item) {
  1012. if (item == null) {
  1013. return (T) new String(UUID.randomUUID().toString());
  1014. }
  1015. return (T) new String(item);
  1016. }
  1017. /**
  1018. * Serializes an {@code item} to a string. Used when saving this Tree to its
  1019. * declarative format.
  1020. * <p>
  1021. * Default implementation delegates a call to {@code item.toString()}.
  1022. *
  1023. * @since 8.1.3
  1024. *
  1025. * @see #deserializeDeclarativeRepresentation(String)
  1026. *
  1027. * @param item
  1028. * a data item
  1029. * @return string representation of the {@code item}.
  1030. */
  1031. protected String serializeDeclarativeRepresentation(T item) {
  1032. return item.toString();
  1033. }
  1034. private void setupContextClickListener() {
  1035. if (hasListeners(ContextClickEvent.class)) {
  1036. if (contextClickRegistration == null) {
  1037. contextClickRegistration = treeGrid
  1038. .addContextClickListener(event -> {
  1039. T item = null;
  1040. if (event instanceof Grid.GridContextClickEvent) {
  1041. item = ((Grid.GridContextClickEvent<T>) event)
  1042. .getItem();
  1043. }
  1044. fireEvent(new TreeContextClickEvent<>(this,
  1045. event.getMouseEventDetails(), item));
  1046. });
  1047. }
  1048. } else if (contextClickRegistration != null) {
  1049. contextClickRegistration.remove();
  1050. contextClickRegistration = null;
  1051. }
  1052. }
  1053. /**
  1054. * ContextClickEvent for the Tree Component.
  1055. * <p>
  1056. * Usage:
  1057. *
  1058. * <pre>
  1059. * tree.addContextClickListener(event -&gt; Notification.show(
  1060. * ((TreeContextClickEvent&lt;Person&gt;) event).getItem() + " Clicked"));
  1061. * </pre>
  1062. *
  1063. * @param <T>
  1064. * the tree bean type
  1065. * @since 8.1
  1066. */
  1067. public static class TreeContextClickEvent<T> extends ContextClickEvent {
  1068. private final T item;
  1069. /**
  1070. * Creates a new context click event.
  1071. *
  1072. * @param source
  1073. * the tree where the context click occurred
  1074. * @param mouseEventDetails
  1075. * details about mouse position
  1076. * @param item
  1077. * the item which was clicked or {@code null} if the click
  1078. * happened outside any item
  1079. */
  1080. public TreeContextClickEvent(Tree<T> source,
  1081. MouseEventDetails mouseEventDetails, T item) {
  1082. super(source, mouseEventDetails);
  1083. this.item = item;
  1084. }
  1085. /**
  1086. * Returns the item of context clicked row.
  1087. *
  1088. * @return clicked item; {@code null} the click happened outside any
  1089. * item
  1090. */
  1091. public T getItem() {
  1092. return item;
  1093. }
  1094. @Override
  1095. public Tree<T> getComponent() {
  1096. return (Tree<T>) super.getComponent();
  1097. }
  1098. }
  1099. /**
  1100. * Scrolls to a certain item, using {@link ScrollDestination#ANY}.
  1101. * <p>
  1102. * If the item has an open details row, its size will also be taken into
  1103. * account.
  1104. *
  1105. * @param row
  1106. * zero based index of the item to scroll to in the current view.
  1107. * @throws IllegalArgumentException
  1108. * if the provided row is outside the item range
  1109. * @since 8.2
  1110. */
  1111. public void scrollTo(int row) throws IllegalArgumentException {
  1112. treeGrid.scrollTo(row, ScrollDestination.ANY);
  1113. }
  1114. /**
  1115. * Scrolls to a certain item, using user-specified scroll destination.
  1116. * <p>
  1117. * If the item has an open details row, its size will also be taken into
  1118. * account.
  1119. *
  1120. * @param row
  1121. * zero based index of the item to scroll to in the current view.
  1122. * @param destination
  1123. * value specifying desired position of scrolled-to row, not
  1124. * {@code null}
  1125. * @throws IllegalArgumentException
  1126. * if the provided row is outside the item range
  1127. * @since 8.2
  1128. */
  1129. public void scrollTo(int row, ScrollDestination destination) {
  1130. treeGrid.scrollTo(row, destination);
  1131. }
  1132. /**
  1133. * Scrolls to the beginning of the first data row.
  1134. *
  1135. * @since 8.2
  1136. */
  1137. public void scrollToStart() {
  1138. treeGrid.scrollToStart();
  1139. }
  1140. /**
  1141. * Scrolls to the end of the last data row.
  1142. *
  1143. * @since 8.2
  1144. */
  1145. public void scrollToEnd() {
  1146. treeGrid.scrollToEnd();
  1147. }
  1148. @Override
  1149. public int getTabIndex() {
  1150. return treeGrid.getTabIndex();
  1151. }
  1152. @Override
  1153. public void setTabIndex(int tabIndex) {
  1154. treeGrid.setTabIndex(tabIndex);
  1155. }
  1156. @Override
  1157. public void focus() {
  1158. treeGrid.focus();
  1159. }
  1160. }