zoomable-canvas.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import React from 'react';
  2. import classNames from 'classnames';
  3. import { connect } from 'react-redux';
  4. import { clamp, debounce, pick } from 'lodash';
  5. import { fromJS } from 'immutable';
  6. import stableStringify from 'json-stable-stringify';
  7. import { drag } from 'd3-drag';
  8. import { event as d3Event, select } from 'd3-selection';
  9. import { zoomFactor } from 'weaveworks-ui-components/lib/utils/zooming';
  10. import Logo from './logo';
  11. import ZoomControl from './zoom-control';
  12. import { cacheZoomState } from '../actions/app-actions';
  13. import { applyTransform, inverseTransform } from '../utils/transform-utils';
  14. import { activeTopologyZoomCacheKeyPathSelector } from '../selectors/zooming';
  15. import {
  16. canvasMarginsSelector,
  17. canvasWidthSelector,
  18. canvasHeightSelector,
  19. } from '../selectors/canvas';
  20. import { ZOOM_CACHE_DEBOUNCE_INTERVAL } from '../constants/timer';
  21. import { CONTENT_INCLUDED, CONTENT_COVERING } from '../constants/naming';
  22. class ZoomableCanvas extends React.Component {
  23. constructor(props, context) {
  24. super(props, context);
  25. this.state = {
  26. contentMaxX: 0,
  27. contentMaxY: 0,
  28. contentMinX: 0,
  29. contentMinY: 0,
  30. isPanning: false,
  31. maxScale: 1,
  32. minScale: 1,
  33. scaleX: 1, //默认是1
  34. scaleY: 1,
  35. translateX: 0,
  36. translateY: 0,
  37. };
  38. this.debouncedCacheZoom = debounce(this.cacheZoom.bind(this), ZOOM_CACHE_DEBOUNCE_INTERVAL);
  39. this.handleZoomControlAction = this.handleZoomControlAction.bind(this);
  40. this.canChangeZoom = this.canChangeZoom.bind(this);
  41. this.handleZoom = this.handleZoom.bind(this);
  42. this.handlePanStart = this.handlePanStart.bind(this);
  43. this.handlePanEnd = this.handlePanEnd.bind(this);
  44. this.handlePan = this.handlePan.bind(this);
  45. }
  46. componentDidMount() {
  47. this.svg = select('.zoomable-canvas svg');
  48. this.drag = drag()
  49. .on('start', this.handlePanStart)
  50. .on('end', this.handlePanEnd)
  51. .on('drag', this.handlePan);
  52. this.svg.call(this.drag);
  53. this.zoomRestored = false;
  54. this.updateZoomLimits(this.props);
  55. this.restoreZoomState(this.props);
  56. document
  57. .getElementById('canvas')
  58. .addEventListener('wheel', this.handleZoom, { passive: false });
  59. }
  60. componentWillUnmount() {
  61. this.debouncedCacheZoom.cancel();
  62. document
  63. .getElementById('canvas')
  64. .removeEventListener('wheel', this.handleZoom, { passive: false });
  65. }
  66. componentWillReceiveProps(nextProps) {
  67. const layoutChanged = nextProps.layoutId !== this.props.layoutId;
  68. // If the layout has changed (either active topology or its options) or
  69. // relayouting has been requested, stop pending zoom caching event and
  70. // ask for the new zoom settings to be restored again from the cache.
  71. if (layoutChanged || nextProps.forceRelayout) {
  72. this.debouncedCacheZoom.cancel();
  73. this.zoomRestored = false;
  74. }
  75. this.updateZoomLimits(nextProps);
  76. if (!this.zoomRestored) {
  77. this.restoreZoomState(nextProps);
  78. }
  79. }
  80. handleZoomControlAction(scale) {
  81. // Get the center of the SVG and zoom around it.
  82. const {
  83. top, bottom, left, right
  84. } = this.svg.node().getBoundingClientRect();
  85. const centerOfCanvas = {
  86. x: (left + right) / 2,
  87. y: (top + bottom) / 2,
  88. };
  89. // Zoom factor diff is obtained by dividing the new zoom scale with the old one.
  90. this.zoomAtPositionByFactor(centerOfCanvas, scale / this.state.scaleX);
  91. }
  92. render() {
  93. const className = classNames({ panning: this.state.isPanning });
  94. return (
  95. <div className="zoomable-canvas">
  96. <svg id="canvas" className={className} onClick={this.props.onClick}>
  97. <Logo transform="translate(24,24) scale(0.25)" />
  98. <g className="zoom-content">
  99. {this.props.children(this.state)}
  100. </g>
  101. </svg>
  102. {this.canChangeZoom() && (
  103. <ZoomControl
  104. zoomAction={this.handleZoomControlAction}
  105. minScale={this.state.minScale}
  106. maxScale={this.state.maxScale}
  107. scale={this.state.scaleX}
  108. />
  109. )}
  110. </div>
  111. );
  112. }
  113. // Decides which part of the zoom state is cachable depending
  114. // on the horizontal/vertical degrees of freedom.
  115. cachableState(state = this.state) {
  116. const cachableFields = []
  117. .concat(this.props.fixHorizontal ? [] : ['scaleX', 'translateX'])
  118. .concat(this.props.fixVertical ? [] : ['scaleY', 'translateY']);
  119. return pick(state, cachableFields);
  120. }
  121. cacheZoom() {
  122. this.props.cacheZoomState(fromJS(this.cachableState()));
  123. }
  124. updateZoomLimits(props) {
  125. this.setState(props.layoutLimits.toJS());
  126. }
  127. // Restore the zooming settings
  128. restoreZoomState(props) {
  129. if (!props.layoutZoomState.isEmpty()) {
  130. const zoomState = props.layoutZoomState.toJS();
  131. // Update the state variables.
  132. this.setState(zoomState);
  133. this.zoomRestored = true;
  134. }
  135. }
  136. canChangeZoom() {
  137. const { disabled, layoutLimits } = this.props;
  138. const canvasHasContent = !layoutLimits.isEmpty();
  139. return !disabled && canvasHasContent;
  140. }
  141. handlePanStart() {
  142. this.setState({ isPanning: true });
  143. }
  144. handlePanEnd() {
  145. this.setState({ isPanning: false });
  146. }
  147. handlePan() {
  148. let { state } = this;
  149. // Apply the translation respecting the boundaries.
  150. state = this.clampedTranslation({
  151. ...state,
  152. translateX: this.state.translateX + d3Event.dx,
  153. translateY: this.state.translateY + d3Event.dy,
  154. });
  155. this.updateState(state);
  156. }
  157. handleZoom(ev) {
  158. if (this.canChangeZoom()) {
  159. // Get the exact mouse cursor position in the SVG and zoom around it.
  160. const { top, left } = this.svg.node().getBoundingClientRect();
  161. const mousePosition = {
  162. x: ev.clientX - left,
  163. y: ev.clientY - top,
  164. };
  165. this.zoomAtPositionByFactor(mousePosition, zoomFactor(ev));
  166. }
  167. ev.preventDefault();
  168. }
  169. clampedTranslation(state) {
  170. const {
  171. width, height, canvasMargins, boundContent, layoutLimits
  172. } = this.props;
  173. const {
  174. contentMinX, contentMaxX, contentMinY, contentMaxY
  175. } = layoutLimits.toJS();
  176. if (boundContent) {
  177. // If the content is required to be bounded in any way, the translation will
  178. // be adjusted so that certain constraints between the viewport and displayed
  179. // content bounding box are met.
  180. const viewportMin = { x: canvasMargins.left, y: canvasMargins.top };
  181. const viewportMax = { x: canvasMargins.left + width, y: canvasMargins.top + height };
  182. const contentMin = applyTransform(state, { x: contentMinX, y: contentMinY });
  183. const contentMax = applyTransform(state, { x: contentMaxX, y: contentMaxY });
  184. switch (boundContent) {
  185. case CONTENT_COVERING:
  186. // These lines will adjust the translation by 'minimal effort' in
  187. // such a way that the content always FULLY covers the viewport,
  188. // i.e. that the viewport rectangle is always fully contained in
  189. // the content bounding box rectangle - the assumption made here
  190. // is that that can always be done.
  191. state.translateX += Math.max(0, viewportMax.x - contentMax.x);
  192. state.translateX -= Math.max(0, contentMin.x - viewportMin.x);
  193. state.translateY += Math.max(0, viewportMax.y - contentMax.y);
  194. state.translateY -= Math.max(0, contentMin.y - viewportMin.y);
  195. break;
  196. case CONTENT_INCLUDED:
  197. // These lines will adjust the translation by 'minimal effort' in
  198. // such a way that the content is always at least PARTLY contained
  199. // within the viewport, i.e. that the intersection between the
  200. // viewport and the content bounding box always exists.
  201. state.translateX -= Math.max(0, contentMin.x - viewportMax.x);
  202. state.translateX += Math.max(0, viewportMin.x - contentMax.x);
  203. state.translateY -= Math.max(0, contentMin.y - viewportMax.y);
  204. state.translateY += Math.max(0, viewportMin.y - contentMax.y);
  205. break;
  206. default:
  207. break;
  208. }
  209. }
  210. return state;
  211. }
  212. zoomAtPositionByFactor(position, factor) {
  213. // Update the scales by the given factor, respecting the zoom limits.
  214. const { minScale, maxScale } = this.state;
  215. const scaleX = clamp(this.state.scaleX * factor, minScale, maxScale);
  216. const scaleY = clamp(this.state.scaleY * factor, minScale, maxScale);
  217. let state = { ...this.state, scaleX, scaleY };
  218. // Get the position in the coordinates before the transition and use it
  219. // to adjust the translation part of the new transition (respecting the
  220. // translation limits). Adapted from:
  221. // https://github.com/d3/d3-zoom/blob/807f02c7a5fe496fbd08cc3417b62905a8ce95fa/src/zoom.js#L251
  222. const inversePosition = inverseTransform(this.state, position);
  223. state = this.clampedTranslation({
  224. ...state,
  225. translateX: position.x - (inversePosition.x * scaleX),
  226. translateY: position.y - (inversePosition.y * scaleY),
  227. });
  228. this.updateState(state);
  229. }
  230. updateState(state) {
  231. this.setState(this.cachableState(state));
  232. this.debouncedCacheZoom();
  233. }
  234. }
  235. function mapStateToProps(state, props) {
  236. return {
  237. canvasMargins: canvasMarginsSelector(state),
  238. forceRelayout: state.get('forceRelayout'),
  239. height: canvasHeightSelector(state),
  240. layoutId: stableStringify(activeTopologyZoomCacheKeyPathSelector(state)),
  241. layoutLimits: props.limitsSelector(state),
  242. layoutZoomState: props.zoomStateSelector(state),
  243. width: canvasWidthSelector(state),
  244. };
  245. }
  246. export default connect(
  247. mapStateToProps,
  248. { cacheZoomState }
  249. )(ZoomableCanvas);