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.

TreeGridConnector.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. /*
  2. * Copyright 2000-2016 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client.connectors.treegrid;
  17. import java.util.Collection;
  18. import java.util.HashSet;
  19. import java.util.Set;
  20. import java.util.logging.Logger;
  21. import com.google.gwt.core.client.Scheduler;
  22. import com.google.gwt.dom.client.BrowserEvents;
  23. import com.google.gwt.dom.client.Element;
  24. import com.google.gwt.event.dom.client.KeyCodes;
  25. import com.google.gwt.user.client.Event;
  26. import com.vaadin.client.annotations.OnStateChange;
  27. import com.vaadin.client.connectors.grid.GridConnector;
  28. import com.vaadin.client.data.AbstractRemoteDataSource;
  29. import com.vaadin.client.data.DataChangeHandler;
  30. import com.vaadin.client.data.DataSource;
  31. import com.vaadin.client.renderers.HierarchyRenderer;
  32. import com.vaadin.client.widget.grid.EventCellReference;
  33. import com.vaadin.client.widget.grid.GridEventHandler;
  34. import com.vaadin.client.widget.grid.events.GridClickEvent;
  35. import com.vaadin.client.widget.treegrid.TreeGrid;
  36. import com.vaadin.client.widget.treegrid.events.TreeGridClickEvent;
  37. import com.vaadin.client.widgets.Grid;
  38. import com.vaadin.shared.Range;
  39. import com.vaadin.shared.data.DataCommunicatorConstants;
  40. import com.vaadin.shared.ui.Connect;
  41. import com.vaadin.shared.ui.treegrid.FocusParentRpc;
  42. import com.vaadin.shared.ui.treegrid.FocusRpc;
  43. import com.vaadin.shared.ui.treegrid.NodeCollapseRpc;
  44. import com.vaadin.shared.ui.treegrid.TreeGridClientRpc;
  45. import com.vaadin.shared.ui.treegrid.TreeGridCommunicationConstants;
  46. import com.vaadin.shared.ui.treegrid.TreeGridState;
  47. import elemental.json.JsonObject;
  48. /**
  49. * A connector class for the TreeGrid component.
  50. *
  51. * @author Vaadin Ltd
  52. * @since 8.1
  53. */
  54. @Connect(com.vaadin.ui.TreeGrid.class)
  55. public class TreeGridConnector extends GridConnector {
  56. public TreeGridConnector() {
  57. registerRpc(FocusRpc.class, (rowIndex, cellIndex) -> {
  58. getWidget().focusCell(rowIndex, cellIndex);
  59. });
  60. }
  61. private String hierarchyColumnId;
  62. private HierarchyRenderer hierarchyRenderer;
  63. private Set<String> rowKeysPendingExpand = new HashSet<>();
  64. @Override
  65. public TreeGrid getWidget() {
  66. return (TreeGrid) super.getWidget();
  67. }
  68. @Override
  69. public TreeGridState getState() {
  70. return (TreeGridState) super.getState();
  71. }
  72. /**
  73. * This method has been scheduled finally to avoid possible race conditions
  74. * between state change handling for the Grid and its columns. The renderer
  75. * of the column is set in a state change handler, and might not be
  76. * available when this method is executed.
  77. * <p>
  78. * TODO: This might need some clean up if we decide to allow setting a new
  79. * renderer for hierarchy columns.
  80. */
  81. @OnStateChange("hierarchyColumnId")
  82. void updateHierarchyColumn() {
  83. Scheduler.get().scheduleFinally(() -> {
  84. // Id of old hierarchy column
  85. String oldHierarchyColumnId = hierarchyColumnId;
  86. // Id of new hierarchy column. Choose first when nothing explicitly
  87. // set
  88. String newHierarchyColumnId = getState().hierarchyColumnId;
  89. if (newHierarchyColumnId == null
  90. && !getState().columnOrder.isEmpty()) {
  91. newHierarchyColumnId = getState().columnOrder.get(0);
  92. }
  93. // Columns
  94. Grid.Column<?, ?> newColumn = getColumn(newHierarchyColumnId);
  95. Grid.Column<?, ?> oldColumn = getColumn(oldHierarchyColumnId);
  96. if (newColumn == null && oldColumn == null) {
  97. // No hierarchy column defined
  98. return;
  99. }
  100. // Unwrap renderer of old column
  101. if (oldColumn != null
  102. && oldColumn.getRenderer() instanceof HierarchyRenderer) {
  103. oldColumn.setRenderer(
  104. ((HierarchyRenderer) oldColumn.getRenderer())
  105. .getInnerRenderer());
  106. }
  107. // Wrap renderer of new column
  108. if (newColumn != null) {
  109. HierarchyRenderer wrapperRenderer = getHierarchyRenderer();
  110. wrapperRenderer.setInnerRenderer(newColumn.getRenderer());
  111. newColumn.setRenderer(wrapperRenderer);
  112. // Set frozen columns again after setting hierarchy column as
  113. // setRenderer() replaces DOM elements
  114. getWidget().setFrozenColumnCount(getState().frozenColumnCount);
  115. hierarchyColumnId = newHierarchyColumnId;
  116. } else {
  117. Logger.getLogger(TreeGridConnector.class.getName()).warning(
  118. "Couldn't find column: " + newHierarchyColumnId);
  119. }
  120. });
  121. }
  122. private HierarchyRenderer getHierarchyRenderer() {
  123. if (hierarchyRenderer == null) {
  124. hierarchyRenderer = new HierarchyRenderer(this::setCollapsed);
  125. }
  126. return hierarchyRenderer;
  127. }
  128. @Override
  129. protected void init() {
  130. super.init();
  131. // Swap Grid's CellFocusEventHandler to this custom one
  132. // The handler is identical to the original one except for the child
  133. // widget check
  134. replaceCellFocusEventHandler(getWidget(), new CellFocusEventHandler());
  135. getWidget().addBrowserEventHandler(5, new NavigationEventHandler());
  136. // Swap Grid#clickEvent field
  137. // The event is identical to the original one except for the child
  138. // widget check
  139. replaceClickEvent(getWidget(),
  140. new TreeGridClickEvent(getWidget(), getEventCell(getWidget())));
  141. registerRpc(TreeGridClientRpc.class, new TreeGridClientRpc() {
  142. @Override
  143. public void setExpanded(String key) {
  144. rowKeysPendingExpand.add(key);
  145. Range cache = ((AbstractRemoteDataSource) getDataSource())
  146. .getCachedRange();
  147. checkExpand(cache.getStart(), cache.length());
  148. }
  149. @Override
  150. public void setCollapsed(String key) {
  151. rowKeysPendingExpand.remove(key);
  152. }
  153. @Override
  154. public void clearPendingExpands() {
  155. rowKeysPendingExpand.clear();
  156. }
  157. });
  158. }
  159. @Override
  160. public void setDataSource(DataSource<JsonObject> dataSource) {
  161. super.setDataSource(dataSource);
  162. dataSource.addDataChangeHandler(new DataChangeHandler() {
  163. @Override
  164. public void dataUpdated(int firstRowIndex, int numberOfRows) {
  165. checkExpand(firstRowIndex, numberOfRows);
  166. }
  167. @Override
  168. public void dataRemoved(int firstRowIndex, int numberOfRows) {
  169. // NO-OP
  170. }
  171. @Override
  172. public void dataAdded(int firstRowIndex, int numberOfRows) {
  173. // NO-OP
  174. }
  175. @Override
  176. public void dataAvailable(int firstRowIndex, int numberOfRows) {
  177. // NO-OP
  178. }
  179. @Override
  180. public void resetDataAndSize(int estimatedNewDataSize) {
  181. // NO-OP
  182. }
  183. });
  184. }
  185. private native void replaceCellFocusEventHandler(Grid<?> grid,
  186. GridEventHandler<?> eventHandler)
  187. /*-{
  188. var browserEventHandlers = grid.@com.vaadin.client.widgets.Grid::browserEventHandlers;
  189. // FocusEventHandler is initially 5th in the list of browser event handlers
  190. browserEventHandlers.@java.util.List::set(*)(5, eventHandler);
  191. }-*/;
  192. private native void replaceClickEvent(Grid<?> grid, GridClickEvent event)
  193. /*-{
  194. grid.@com.vaadin.client.widgets.Grid::clickEvent = event;
  195. }-*/;
  196. private native EventCellReference<?> getEventCell(Grid<?> grid)
  197. /*-{
  198. return grid.@com.vaadin.client.widgets.Grid::eventCell;
  199. }-*/;
  200. private boolean isHierarchyColumn(EventCellReference<JsonObject> cell) {
  201. return cell.getColumn().getRenderer() instanceof HierarchyRenderer;
  202. }
  203. private void setCollapsed(int rowIndex, boolean collapsed) {
  204. String rowKey = getRowKey(getDataSource().getRow(rowIndex));
  205. getRpcProxy(NodeCollapseRpc.class).setNodeCollapsed(rowKey, rowIndex,
  206. collapsed, true);
  207. }
  208. private void setCollapsedServerInitiated(int rowIndex, boolean collapsed) {
  209. String rowKey = getRowKey(getDataSource().getRow(rowIndex));
  210. getRpcProxy(NodeCollapseRpc.class).setNodeCollapsed(rowKey, rowIndex,
  211. collapsed, false);
  212. }
  213. /**
  214. * Class to replace
  215. * {@link com.vaadin.client.widgets.Grid.CellFocusEventHandler}. The only
  216. * difference is that it handles events originated from widgets in hierarchy
  217. * cells.
  218. */
  219. private class CellFocusEventHandler
  220. implements GridEventHandler<JsonObject> {
  221. @Override
  222. public void onEvent(Grid.GridEvent<JsonObject> event) {
  223. Element target = Element.as(event.getDomEvent().getEventTarget());
  224. boolean elementInChildWidget = getWidget()
  225. .isElementInChildWidget(target);
  226. // Ignore if event was handled by keyboard navigation handler
  227. if (event.isHandled() && !elementInChildWidget) {
  228. return;
  229. }
  230. // Ignore target in child widget but handle hierarchy widget
  231. if (elementInChildWidget
  232. && !HierarchyRenderer.isElementInHierarchyWidget(target)) {
  233. return;
  234. }
  235. Collection<String> navigation = getNavigationEvents(getWidget());
  236. if (navigation.contains(event.getDomEvent().getType())) {
  237. handleNavigationEvent(getWidget(), event);
  238. }
  239. }
  240. private native Collection<String> getNavigationEvents(Grid<?> grid)
  241. /*-{
  242. return grid.@com.vaadin.client.widgets.Grid::cellFocusHandler
  243. .@com.vaadin.client.widgets.Grid.CellFocusHandler::getNavigationEvents()();
  244. }-*/;
  245. private native void handleNavigationEvent(Grid<?> grid,
  246. Grid.GridEvent<JsonObject> event)
  247. /*-{
  248. grid.@com.vaadin.client.widgets.Grid::cellFocusHandler
  249. .@com.vaadin.client.widgets.Grid.CellFocusHandler::handleNavigationEvent(*)(
  250. event.@com.vaadin.client.widgets.Grid.GridEvent::getDomEvent()(),
  251. event.@com.vaadin.client.widgets.Grid.GridEvent::getCell()())
  252. }-*/;
  253. }
  254. private class NavigationEventHandler
  255. implements GridEventHandler<JsonObject> {
  256. @Override
  257. public void onEvent(Grid.GridEvent<JsonObject> event) {
  258. if (event.isHandled()) {
  259. return;
  260. }
  261. Event domEvent = event.getDomEvent();
  262. if (!domEvent.getType().equals(BrowserEvents.KEYDOWN)) {
  263. return;
  264. }
  265. // Navigate within hierarchy with ARROW KEYs
  266. if (domEvent.getKeyCode() == KeyCodes.KEY_LEFT
  267. || domEvent.getKeyCode() == KeyCodes.KEY_RIGHT) {
  268. event.setHandled(true);
  269. EventCellReference<JsonObject> cell = event.getCell();
  270. // Hierarchy metadata
  271. JsonObject rowData = cell.getRow();
  272. if (rowData == null) {
  273. // Row data is lost from the cache, i.e. the row is at least outside the visual area,
  274. // let's scroll the row into the view
  275. getWidget().scrollToRow(cell.getRowIndex());
  276. } else if (rowData.hasKey(
  277. TreeGridCommunicationConstants.ROW_HIERARCHY_DESCRIPTION)) {
  278. JsonObject rowDescription = rowData.getObject(
  279. TreeGridCommunicationConstants.ROW_HIERARCHY_DESCRIPTION);
  280. boolean leaf = rowDescription.getBoolean(
  281. TreeGridCommunicationConstants.ROW_LEAF);
  282. boolean collapsed = isCollapsed(rowData);
  283. switch (domEvent.getKeyCode()) {
  284. case KeyCodes.KEY_RIGHT:
  285. if (collapsed && !leaf) {
  286. setCollapsed(cell.getRowIndex(), false);
  287. }
  288. break;
  289. case KeyCodes.KEY_LEFT:
  290. if (collapsed || leaf) {
  291. // navigate up
  292. int columnIndex = cell.getColumnIndex();
  293. getRpcProxy(FocusParentRpc.class).focusParent(
  294. cell.getRowIndex(), columnIndex);
  295. } else if (isCollapseAllowed(rowDescription)) {
  296. setCollapsed(cell.getRowIndex(), true);
  297. }
  298. break;
  299. }
  300. }
  301. }
  302. }
  303. }
  304. private void checkExpand(int firstRowIndex, int numberOfRows) {
  305. if (rowKeysPendingExpand.isEmpty()) {
  306. return;
  307. }
  308. for (int rowIndex = firstRowIndex; rowIndex < firstRowIndex
  309. + numberOfRows; rowIndex++) {
  310. String rowKey = getDataSource().getRow(rowIndex)
  311. .getString(DataCommunicatorConstants.KEY);
  312. if (rowKeysPendingExpand.remove(rowKey)) {
  313. setCollapsedServerInitiated(rowIndex, false);
  314. return;
  315. }
  316. }
  317. }
  318. private static boolean isCollapsed(JsonObject rowData) {
  319. assert rowData
  320. .hasKey(TreeGridCommunicationConstants.ROW_HIERARCHY_DESCRIPTION) : "missing hierarchy data for row "
  321. + rowData.asString();
  322. return rowData
  323. .getObject(
  324. TreeGridCommunicationConstants.ROW_HIERARCHY_DESCRIPTION)
  325. .getBoolean(TreeGridCommunicationConstants.ROW_COLLAPSED);
  326. }
  327. /**
  328. * Checks if the item can be collapsed
  329. *
  330. * @param row the item row
  331. * @return {@code true} if the item is allowed to be collapsed, {@code false} otherwise.
  332. */
  333. public static boolean isCollapseAllowed(JsonObject row) {
  334. return row.getBoolean(
  335. TreeGridCommunicationConstants.ROW_COLLAPSE_ALLOWED);
  336. }
  337. }