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.

GridConnector.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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.grid;
  17. import java.util.ArrayList;
  18. import java.util.Collections;
  19. import java.util.HashMap;
  20. import java.util.HashSet;
  21. import java.util.List;
  22. import java.util.Map;
  23. import java.util.Objects;
  24. import java.util.Set;
  25. import java.util.stream.Collectors;
  26. import com.google.gwt.core.client.Scheduler;
  27. import com.google.gwt.dom.client.Element;
  28. import com.google.gwt.dom.client.EventTarget;
  29. import com.google.gwt.dom.client.NativeEvent;
  30. import com.google.gwt.event.shared.HandlerRegistration;
  31. import com.vaadin.client.ComponentConnector;
  32. import com.vaadin.client.ConnectorHierarchyChangeEvent;
  33. import com.vaadin.client.ConnectorHierarchyChangeEvent.ConnectorHierarchyChangeHandler;
  34. import com.vaadin.client.DeferredWorker;
  35. import com.vaadin.client.HasComponentsConnector;
  36. import com.vaadin.client.MouseEventDetailsBuilder;
  37. import com.vaadin.client.TooltipInfo;
  38. import com.vaadin.client.WidgetUtil;
  39. import com.vaadin.client.annotations.OnStateChange;
  40. import com.vaadin.client.connectors.AbstractListingConnector;
  41. import com.vaadin.client.connectors.grid.ColumnConnector.CustomColumn;
  42. import com.vaadin.client.data.DataSource;
  43. import com.vaadin.client.ui.SimpleManagedLayout;
  44. import com.vaadin.client.widget.grid.CellReference;
  45. import com.vaadin.client.widget.grid.EventCellReference;
  46. import com.vaadin.client.widget.grid.events.BodyClickHandler;
  47. import com.vaadin.client.widget.grid.events.BodyDoubleClickHandler;
  48. import com.vaadin.client.widget.grid.events.GridClickEvent;
  49. import com.vaadin.client.widget.grid.events.GridDoubleClickEvent;
  50. import com.vaadin.client.widget.grid.sort.SortEvent;
  51. import com.vaadin.client.widget.grid.sort.SortOrder;
  52. import com.vaadin.client.widgets.Grid;
  53. import com.vaadin.client.widgets.Grid.Column;
  54. import com.vaadin.client.widgets.Grid.FooterRow;
  55. import com.vaadin.client.widgets.Grid.HeaderRow;
  56. import com.vaadin.shared.MouseEventDetails;
  57. import com.vaadin.shared.data.sort.SortDirection;
  58. import com.vaadin.shared.ui.Connect;
  59. import com.vaadin.shared.ui.grid.GridClientRpc;
  60. import com.vaadin.shared.ui.grid.GridConstants;
  61. import com.vaadin.shared.ui.grid.GridConstants.Section;
  62. import com.vaadin.shared.ui.grid.GridServerRpc;
  63. import com.vaadin.shared.ui.grid.GridState;
  64. import com.vaadin.shared.ui.grid.ScrollDestination;
  65. import com.vaadin.shared.ui.grid.SectionState;
  66. import com.vaadin.shared.ui.grid.SectionState.CellState;
  67. import com.vaadin.shared.ui.grid.SectionState.RowState;
  68. import elemental.json.JsonObject;
  69. /**
  70. * A connector class for the typed Grid component.
  71. *
  72. * @author Vaadin Ltd
  73. * @since 8.0
  74. */
  75. @Connect(com.vaadin.ui.Grid.class)
  76. public class GridConnector extends AbstractListingConnector
  77. implements HasComponentsConnector, SimpleManagedLayout, DeferredWorker {
  78. private Set<Runnable> refreshDetailsCallbacks = new HashSet<>();
  79. private class ItemClickHandler
  80. implements BodyClickHandler, BodyDoubleClickHandler {
  81. @Override
  82. public void onClick(GridClickEvent event) {
  83. if (hasEventListener(GridConstants.ITEM_CLICK_EVENT_ID)) {
  84. fireItemClick(event.getTargetCell(), event.getNativeEvent());
  85. }
  86. }
  87. @Override
  88. public void onDoubleClick(GridDoubleClickEvent event) {
  89. if (hasEventListener(GridConstants.ITEM_CLICK_EVENT_ID)) {
  90. fireItemClick(event.getTargetCell(), event.getNativeEvent());
  91. }
  92. }
  93. private void fireItemClick(CellReference<?> cell,
  94. NativeEvent mouseEvent) {
  95. String rowKey = getRowKey((JsonObject) cell.getRow());
  96. String columnId = columnToIdMap.get(cell.getColumn());
  97. getRpcProxy(GridServerRpc.class).itemClick(rowKey, columnId,
  98. MouseEventDetailsBuilder
  99. .buildMouseEventDetails(mouseEvent));
  100. }
  101. }
  102. /* Map to keep track of all added columns */
  103. private Map<CustomColumn, String> columnToIdMap = new HashMap<>();
  104. private Map<String, CustomColumn> idToColumn = new HashMap<>();
  105. /* Child component list for HasComponentsConnector */
  106. private List<ComponentConnector> childComponents;
  107. private ItemClickHandler itemClickHandler = new ItemClickHandler();
  108. /**
  109. * Gets the string identifier of the given column in this grid.
  110. *
  111. * @param column
  112. * the column whose id to get
  113. * @return the string id of the column
  114. */
  115. public String getColumnId(Column<?, ?> column) {
  116. return columnToIdMap.get(column);
  117. }
  118. /**
  119. * Gets the column corresponding to the given string identifier.
  120. *
  121. * @param columnId
  122. * the id of the column to get
  123. * @return the column with the given id
  124. */
  125. public CustomColumn getColumn(String columnId) {
  126. return idToColumn.get(columnId);
  127. }
  128. @Override
  129. @SuppressWarnings("unchecked")
  130. public Grid<JsonObject> getWidget() {
  131. return (Grid<JsonObject>) super.getWidget();
  132. }
  133. /**
  134. * Method called for a row details refresh. Runs all callbacks if any
  135. * details were shown and clears the callbacks.
  136. *
  137. * @param detailsShown
  138. * True if any details were set visible
  139. */
  140. protected void detailsRefreshed(boolean detailsShown) {
  141. if (detailsShown) {
  142. refreshDetailsCallbacks.forEach(Runnable::run);
  143. }
  144. refreshDetailsCallbacks.clear();
  145. }
  146. /**
  147. * Method target for when one single details has been updated and we might
  148. * need to scroll it into view.
  149. *
  150. * @param rowIndex
  151. * index of updated row
  152. */
  153. protected void singleDetailsOpened(int rowIndex) {
  154. addDetailsRefreshCallback(() -> {
  155. if (rowHasDetails(rowIndex)) {
  156. getWidget().scrollToRow(rowIndex);
  157. }
  158. });
  159. }
  160. /**
  161. * Add a single use details runnable callback for when we get a call to
  162. * {@link #detailsRefreshed(boolean)}.
  163. *
  164. * @param refreshCallback
  165. * Details refreshed callback
  166. */
  167. private void addDetailsRefreshCallback(Runnable refreshCallback) {
  168. refreshDetailsCallbacks.add(refreshCallback);
  169. }
  170. /**
  171. * Check if we have details for given row.
  172. *
  173. * @param rowIndex
  174. * @return
  175. */
  176. private boolean rowHasDetails(int rowIndex) {
  177. JsonObject row = getWidget().getDataSource().getRow(rowIndex);
  178. return row != null && row.hasKey(GridState.JSONKEY_DETAILS_VISIBLE)
  179. && !row.getString(GridState.JSONKEY_DETAILS_VISIBLE).isEmpty();
  180. }
  181. @Override
  182. protected void init() {
  183. super.init();
  184. registerRpc(GridClientRpc.class, new GridClientRpc() {
  185. @Override
  186. public void scrollToRow(int row, ScrollDestination destination) {
  187. Scheduler.get().scheduleFinally(
  188. () -> getWidget().scrollToRow(row, destination));
  189. // Add details refresh listener and handle possible detail for
  190. // scrolled row.
  191. addDetailsRefreshCallback(() -> {
  192. if (rowHasDetails(row)) {
  193. getWidget().scrollToRow(row, destination);
  194. }
  195. });
  196. }
  197. @Override
  198. public void scrollToStart() {
  199. Scheduler.get()
  200. .scheduleFinally(() -> getWidget().scrollToStart());
  201. }
  202. @Override
  203. public void scrollToEnd() {
  204. Scheduler.get()
  205. .scheduleFinally(() -> getWidget().scrollToEnd());
  206. addDetailsRefreshCallback(() -> {
  207. if (rowHasDetails(getWidget().getDataSource().size() - 1)) {
  208. getWidget().scrollToEnd();
  209. }
  210. });
  211. }
  212. });
  213. getWidget().addSortHandler(this::handleSortEvent);
  214. getWidget().setRowStyleGenerator(rowRef -> {
  215. JsonObject json = rowRef.getRow();
  216. return json.hasKey(GridState.JSONKEY_ROWSTYLE)
  217. ? json.getString(GridState.JSONKEY_ROWSTYLE) : null;
  218. });
  219. getWidget().setCellStyleGenerator(cellRef -> {
  220. JsonObject row = cellRef.getRow();
  221. if (!row.hasKey(GridState.JSONKEY_CELLSTYLES)) {
  222. return null;
  223. }
  224. Column<?, JsonObject> column = cellRef.getColumn();
  225. if (column instanceof CustomColumn) {
  226. String id = ((CustomColumn) column).getConnectorId();
  227. JsonObject cellStyles = row
  228. .getObject(GridState.JSONKEY_CELLSTYLES);
  229. if (cellStyles.hasKey(id)) {
  230. return cellStyles.getString(id);
  231. }
  232. }
  233. return null;
  234. });
  235. getWidget().addColumnVisibilityChangeHandler(event -> {
  236. if (event.isUserOriginated()) {
  237. getRpcProxy(GridServerRpc.class).columnVisibilityChanged(
  238. getColumnId(event.getColumn()), event.isHidden());
  239. }
  240. });
  241. getWidget().addColumnReorderHandler(event -> {
  242. if (event.isUserOriginated()) {
  243. List<String> newColumnOrder = mapColumnsToIds(
  244. event.getNewColumnOrder());
  245. List<String> oldColumnOrder = mapColumnsToIds(
  246. event.getOldColumnOrder());
  247. getRpcProxy(GridServerRpc.class)
  248. .columnsReordered(newColumnOrder, oldColumnOrder);
  249. }
  250. });
  251. getWidget().addColumnResizeHandler(event -> {
  252. Column<?, JsonObject> column = event.getColumn();
  253. getRpcProxy(GridServerRpc.class).columnResized(getColumnId(column),
  254. column.getWidthActual());
  255. });
  256. /* Item click events */
  257. getWidget().addBodyClickHandler(itemClickHandler);
  258. getWidget().addBodyDoubleClickHandler(itemClickHandler);
  259. layout();
  260. }
  261. @SuppressWarnings("unchecked")
  262. @OnStateChange("columnOrder")
  263. void updateColumnOrder() {
  264. Scheduler.get()
  265. .scheduleFinally(() -> getWidget().setColumnOrder(
  266. getState().columnOrder.stream().map(this::getColumn)
  267. .toArray(size -> new Column[size])));
  268. }
  269. @OnStateChange("columnResizeMode")
  270. void updateColumnResizeMode() {
  271. getWidget().setColumnResizeMode(getState().columnResizeMode);
  272. }
  273. /**
  274. * Updates the grid header section on state change.
  275. */
  276. @OnStateChange("header")
  277. void updateHeader() {
  278. Scheduler.get().scheduleFinally(() -> {
  279. final Grid<JsonObject> grid = getWidget();
  280. final SectionState state = getState().header;
  281. while (grid.getHeaderRowCount() > 0) {
  282. grid.removeHeaderRow(0);
  283. }
  284. for (RowState rowState : state.rows) {
  285. HeaderRow row = grid.appendHeaderRow();
  286. if (rowState.defaultHeader) {
  287. grid.setDefaultHeaderRow(row);
  288. }
  289. updateStaticRow(rowState, row);
  290. }
  291. });
  292. }
  293. @OnStateChange("rowHeight")
  294. void updateRowHeight() {
  295. double rowHeight = getState().rowHeight;
  296. if (rowHeight >= 0) {
  297. getWidget().getEscalator().getHeader()
  298. .setDefaultRowHeight(rowHeight);
  299. getWidget().getEscalator().getBody().setDefaultRowHeight(rowHeight);
  300. getWidget().getEscalator().getFooter()
  301. .setDefaultRowHeight(rowHeight);
  302. } else if (getWidget().isAttached()) {
  303. // finally to make sure column sizes have been set before this
  304. Scheduler.get()
  305. .scheduleFinally(() -> getWidget().resetSizesFromDom());
  306. }
  307. }
  308. private void updateStaticRow(RowState rowState,
  309. Grid.StaticSection.StaticRow row) {
  310. rowState.cells.forEach((columnId, cellState) -> {
  311. updateStaticCellFromState(row.getCell(getColumn(columnId)),
  312. cellState);
  313. });
  314. for (Map.Entry<CellState, Set<String>> cellGroupEntry : rowState.cellGroups
  315. .entrySet()) {
  316. Set<String> group = cellGroupEntry.getValue();
  317. Grid.Column<?, ?>[] columns = group.stream().map(idToColumn::get)
  318. .toArray(size -> new Grid.Column<?, ?>[size]);
  319. // Set state to be the same as first in group.
  320. updateStaticCellFromState(row.join(columns),
  321. cellGroupEntry.getKey());
  322. }
  323. row.setStyleName(rowState.styleName);
  324. }
  325. private void updateStaticCellFromState(Grid.StaticSection.StaticCell cell,
  326. CellState cellState) {
  327. switch (cellState.type) {
  328. case TEXT:
  329. cell.setText(cellState.text);
  330. break;
  331. case HTML:
  332. cell.setHtml(cellState.html);
  333. break;
  334. case WIDGET:
  335. ComponentConnector connector = (ComponentConnector) cellState.connector;
  336. if (connector != null) {
  337. cell.setWidget(connector.getWidget());
  338. } else {
  339. // This happens if you do setVisible(false) on the component on
  340. // the server side
  341. cell.setWidget(null);
  342. }
  343. break;
  344. default:
  345. throw new IllegalStateException(
  346. "unexpected cell type: " + cellState.type);
  347. }
  348. cell.setStyleName(cellState.styleName);
  349. }
  350. /**
  351. * Updates the grid footer section on state change.
  352. */
  353. @OnStateChange("footer")
  354. void updateFooter() {
  355. final Grid<JsonObject> grid = getWidget();
  356. final SectionState state = getState().footer;
  357. while (grid.getFooterRowCount() > 0) {
  358. grid.removeFooterRow(0);
  359. }
  360. for (RowState rowState : state.rows) {
  361. FooterRow row = grid.appendFooterRow();
  362. updateStaticRow(rowState, row);
  363. }
  364. }
  365. @Override
  366. public void setDataSource(DataSource<JsonObject> dataSource) {
  367. super.setDataSource(dataSource);
  368. getWidget().setDataSource(dataSource);
  369. }
  370. /**
  371. * Adds a column to the Grid widget. For each column a communication id
  372. * stored for client to server communication.
  373. *
  374. * @param column
  375. * column to add
  376. * @param id
  377. * communication id
  378. */
  379. public void addColumn(CustomColumn column, String id) {
  380. assert !columnToIdMap.containsKey(column) && !columnToIdMap
  381. .containsValue(id) : "Column with given id already exists.";
  382. getWidget().addColumn(column);
  383. columnToIdMap.put(column, id);
  384. idToColumn.put(id, column);
  385. }
  386. /**
  387. * Removes a column from Grid widget. This method also removes communication
  388. * id mapping for the column.
  389. *
  390. * @param column
  391. * column to remove
  392. */
  393. public void removeColumn(CustomColumn column) {
  394. assert columnToIdMap
  395. .containsKey(column) : "Given Column does not exist.";
  396. getWidget().removeColumn(column);
  397. String id = columnToIdMap.remove(column);
  398. idToColumn.remove(id);
  399. }
  400. @Override
  401. public void onUnregister() {
  402. super.onUnregister();
  403. }
  404. @Override
  405. public boolean isWorkPending() {
  406. return getWidget().isWorkPending();
  407. }
  408. @Override
  409. public void layout() {
  410. getWidget().onResize();
  411. }
  412. /**
  413. * Sends sort information from an event to the server-side of the Grid.
  414. *
  415. * @param event
  416. * the sort event
  417. */
  418. private void handleSortEvent(SortEvent<JsonObject> event) {
  419. List<String> columnIds = new ArrayList<>();
  420. List<SortDirection> sortDirections = new ArrayList<>();
  421. for (SortOrder so : event.getOrder()) {
  422. if (columnToIdMap.containsKey(so.getColumn())) {
  423. columnIds.add(columnToIdMap.get(so.getColumn()));
  424. sortDirections.add(so.getDirection());
  425. }
  426. }
  427. getRpcProxy(GridServerRpc.class).sort(columnIds.toArray(new String[0]),
  428. sortDirections.toArray(new SortDirection[0]),
  429. event.isUserOriginated());
  430. }
  431. /* HasComponentsConnector */
  432. @Override
  433. public void updateCaption(ComponentConnector connector) {
  434. // Details components don't support captions.
  435. }
  436. @Override
  437. public List<ComponentConnector> getChildComponents() {
  438. if (childComponents == null) {
  439. return Collections.emptyList();
  440. }
  441. return childComponents;
  442. }
  443. @Override
  444. public void setChildComponents(List<ComponentConnector> children) {
  445. childComponents = children;
  446. }
  447. @Override
  448. public HandlerRegistration addConnectorHierarchyChangeHandler(
  449. ConnectorHierarchyChangeHandler handler) {
  450. return ensureHandlerManager()
  451. .addHandler(ConnectorHierarchyChangeEvent.TYPE, handler);
  452. }
  453. @Override
  454. public GridState getState() {
  455. return (GridState) super.getState();
  456. }
  457. @Override
  458. public boolean hasTooltip() {
  459. // Always check for generated descriptions.
  460. return true;
  461. }
  462. @Override
  463. public TooltipInfo getTooltipInfo(Element element) {
  464. CellReference<JsonObject> cell = getWidget().getCellReference(element);
  465. if (cell != null) {
  466. JsonObject row = cell.getRow();
  467. if (row != null && (row.hasKey(GridState.JSONKEY_ROWDESCRIPTION)
  468. || row.hasKey(GridState.JSONKEY_CELLDESCRIPTION))) {
  469. Column<?, JsonObject> column = cell.getColumn();
  470. if (column instanceof CustomColumn) {
  471. JsonObject cellDescriptions = row
  472. .getObject(GridState.JSONKEY_CELLDESCRIPTION);
  473. String id = ((CustomColumn) column).getConnectorId();
  474. if (cellDescriptions != null
  475. && cellDescriptions.hasKey(id)) {
  476. return new TooltipInfo(cellDescriptions.getString(id));
  477. } else if (row.hasKey(GridState.JSONKEY_ROWDESCRIPTION)) {
  478. return new TooltipInfo(row
  479. .getString(GridState.JSONKEY_ROWDESCRIPTION));
  480. }
  481. }
  482. }
  483. }
  484. if (super.hasTooltip()) {
  485. return super.getTooltipInfo(element);
  486. } else {
  487. return null;
  488. }
  489. }
  490. @Override
  491. protected void sendContextClickEvent(MouseEventDetails details,
  492. EventTarget eventTarget) {
  493. // if element is the resize indicator, ignore the event
  494. if (isResizeHandle(eventTarget)) {
  495. WidgetUtil.clearTextSelection();
  496. return;
  497. }
  498. EventCellReference<JsonObject> eventCell = getWidget().getEventCell();
  499. Section section = eventCell.getSection();
  500. String rowKey = null;
  501. if (eventCell.isBody() && eventCell.getRow() != null) {
  502. rowKey = getRowKey(eventCell.getRow());
  503. }
  504. String columnId = getColumnId(eventCell.getColumn());
  505. getRpcProxy(GridServerRpc.class).contextClick(eventCell.getRowIndex(),
  506. rowKey, columnId, section, details);
  507. WidgetUtil.clearTextSelection();
  508. }
  509. private boolean isResizeHandle(EventTarget eventTarget) {
  510. if (Element.is(eventTarget)) {
  511. Element e = Element.as(eventTarget);
  512. if (e.getClassName().contains("-column-resize-handle")) {
  513. return true;
  514. }
  515. }
  516. return false;
  517. }
  518. private List<String> mapColumnsToIds(List<Column<?, JsonObject>> columns) {
  519. return columns.stream().map(this::getColumnId).filter(Objects::nonNull)
  520. .collect(Collectors.toList());
  521. }
  522. }