您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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