utils.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. var __rest = (this && this.__rest) || function (s, e) {
  2. var t = {};
  3. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  4. t[p] = s[p];
  5. if (s != null && typeof Object.getOwnPropertySymbols === "function")
  6. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  7. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  8. t[p[i]] = s[p[i]];
  9. }
  10. return t;
  11. };
  12. import { Path } from '@antv/g';
  13. import { path as d3Path } from 'd3-path';
  14. import { sort } from 'd3-array';
  15. import { select } from '../utils/selection';
  16. import { mapObject } from '../utils/array';
  17. import { ELEMENT_CLASS_NAME, PLOT_CLASS_NAME, } from '../runtime';
  18. import { isOrdinalScale } from '../utils/scale';
  19. import { rect } from '../shape/interval/color';
  20. import { isPolar, isTranspose } from '../utils/coordinate';
  21. import { getStyle } from '../utils/style';
  22. import { reorder } from '../shape/utils';
  23. import { angle, angleBetween, sub } from '../utils/vector';
  24. /**
  25. * Given root of chart returns elements to be manipulated
  26. */
  27. export function selectG2Elements(root) {
  28. return select(root)
  29. .selectAll(`.${ELEMENT_CLASS_NAME}`)
  30. .nodes()
  31. .filter((d) => !d.__removed__);
  32. }
  33. export function selectFacetG2Elements(target, viewInstances) {
  34. return selectFacetViews(target, viewInstances).flatMap(({ container }) => selectG2Elements(container));
  35. }
  36. export function selectFacetViews(target, viewInstances) {
  37. return viewInstances.filter((d) => d !== target && d.options.parentKey === target.options.key);
  38. }
  39. export function selectPlotArea(root) {
  40. return select(root).select(`.${PLOT_CLASS_NAME}`).node();
  41. }
  42. export function mousePosition(target, event) {
  43. const { offsetX, offsetY } = event;
  44. const bbox = target.getRenderBounds();
  45. const { min: [x, y], max: [x1, y1], } = bbox;
  46. const isOutX = offsetX < x || offsetX > x1;
  47. const isOutY = offsetY < y || offsetY > y1;
  48. if (isOutX || isOutY)
  49. return null;
  50. return [offsetX - x, offsetY - y];
  51. }
  52. /**
  53. * @todo Pass bbox rather than calc it here.
  54. */
  55. export function brushMousePosition(target, event) {
  56. const { offsetX, offsetY } = event;
  57. const [x, y, x1, y1] = boundsOfBrushArea(target);
  58. return [
  59. Math.min(x1, Math.max(x, offsetX)) - x,
  60. Math.min(y1, Math.max(y, offsetY)) - y,
  61. ];
  62. }
  63. export function boundsOfBrushArea(target) {
  64. // Calc bbox after clipping.
  65. const bbox = target.getRenderBounds();
  66. const { min: [x0, y0], max: [x1, y1], } = bbox;
  67. return [x0, y0, x1, y1];
  68. }
  69. export function createColorKey(view) {
  70. return (element) => element.__data__.color;
  71. }
  72. export function createXKey(view) {
  73. const { x: scaleX } = view.scale;
  74. return (element) => {
  75. const { x } = element.__data__;
  76. return scaleX.invert(x);
  77. };
  78. }
  79. export function createDatumof(view) {
  80. const views = Array.isArray(view) ? view : [view];
  81. const keyData = new Map(views.flatMap((view) => {
  82. const marks = Array.from(view.markState.keys());
  83. return marks.map((mark) => [keyed(view.key, mark.key), mark.data]);
  84. }));
  85. return (element) => {
  86. const { index, markKey, viewKey } = element.__data__;
  87. const data = keyData.get(keyed(viewKey, markKey));
  88. return data[index];
  89. };
  90. }
  91. /**
  92. * A state manager for G2Element.
  93. * The keys for each state's style start with the state name.
  94. * { selectedFill, selectedStroke } is for selected state.
  95. * { unselectedFill, unselectedStroke } is for unselected state.
  96. */
  97. export function useState(style, valueof = (d, element) => d, setAttribute = (element, key, v) => element.setAttribute(key, v)) {
  98. const STATES = '__states__';
  99. const ORIGINAL = '__ordinal__';
  100. // Mix style for each state and apply it to element.
  101. const updateState = (element) => {
  102. const { [STATES]: states = [], [ORIGINAL]: original = {} } = element;
  103. const stateStyle = states.reduce((mixedStyle, state) => (Object.assign(Object.assign({}, mixedStyle), style[state])), original);
  104. if (Object.keys(stateStyle).length === 0)
  105. return;
  106. for (const [key, value] of Object.entries(stateStyle)) {
  107. const currentValue = getStyle(element, key);
  108. const v = valueof(value, element);
  109. setAttribute(element, key, v);
  110. // Store the attribute if it does not exist in original.
  111. if (!(key in original))
  112. original[key] = currentValue;
  113. }
  114. element[ORIGINAL] = original;
  115. };
  116. const initState = (element) => {
  117. if (element[STATES])
  118. return;
  119. element[STATES] = [];
  120. return;
  121. };
  122. /**
  123. * Set the states and update element.
  124. */
  125. const setState = (element, ...states) => {
  126. initState(element);
  127. element[STATES] = [...states];
  128. updateState(element);
  129. };
  130. /**
  131. * Remove the states and update element.
  132. */
  133. const removeState = (element, ...states) => {
  134. initState(element);
  135. for (const state of states) {
  136. const index = element[STATES].indexOf(state);
  137. if (index !== -1) {
  138. element[STATES].splice(index, 1);
  139. }
  140. }
  141. updateState(element);
  142. };
  143. const hasState = (element, state) => {
  144. initState(element);
  145. return element[STATES].indexOf(state) !== -1;
  146. };
  147. return {
  148. setState,
  149. removeState,
  150. hasState,
  151. };
  152. }
  153. function isEmptyObject(obj) {
  154. if (obj === undefined)
  155. return true;
  156. if (typeof obj !== 'object')
  157. return false;
  158. return Object.keys(obj).length === 0;
  159. }
  160. // A function to generate key for mark each view.
  161. function keyed(viewKey, markKey) {
  162. return `${viewKey},${markKey}`;
  163. }
  164. export function mergeState(options, states) {
  165. // Index state by mark key and view key.
  166. const views = Array.isArray(options) ? options : [options];
  167. const markState = views.flatMap((view) => view.marks.map((mark) => [keyed(view.key, mark.key), mark.state]));
  168. const state = {};
  169. // Update each specified state.
  170. for (const descriptor of states) {
  171. const [key, defaults] = Array.isArray(descriptor)
  172. ? descriptor
  173. : [descriptor, {}];
  174. // Update each specified mark state.
  175. state[key] = markState.reduce((merged, mark) => {
  176. // Normalize state.
  177. const [markKey, markState = {}] = mark;
  178. const selectedState = isEmptyObject(markState[key])
  179. ? defaults
  180. : markState[key];
  181. // Update each state attribute.
  182. for (const [attr, value] of Object.entries(selectedState)) {
  183. const oldValue = merged[attr];
  184. const newValue = (data, index, array, element) => {
  185. const k = keyed(element.__data__.viewKey, element.__data__.markKey);
  186. if (markKey !== k)
  187. return oldValue === null || oldValue === void 0 ? void 0 : oldValue(data, index, array, element);
  188. if (typeof value !== 'function')
  189. return value;
  190. return value(data, index, array, element);
  191. };
  192. merged[attr] = newValue;
  193. }
  194. return merged;
  195. }, {});
  196. }
  197. return state;
  198. }
  199. // @todo Support elements from different view.
  200. export function createValueof(elements, datum) {
  201. const elementIndex = new Map(elements.map((d, i) => [d, i]));
  202. const fa = datum ? elements.map(datum) : elements;
  203. return (d, e) => {
  204. if (typeof d !== 'function')
  205. return d;
  206. const i = elementIndex.get(e);
  207. const fe = datum ? datum(e) : e;
  208. return d(fe, i, fa, e);
  209. };
  210. }
  211. export function renderLink(_a) {
  212. var { link = false, valueof = (d, element) => d, coordinate } = _a, style = __rest(_a, ["link", "valueof", "coordinate"]);
  213. const LINK_CLASS_NAME = 'element-link';
  214. if (!link)
  215. return [() => { }, () => { }];
  216. const pointsOf = (element) => element.__data__.points;
  217. const pathPointsOf = (P0, P1) => {
  218. const [, p1, p2] = P0;
  219. const [p0, , , p3] = P1;
  220. const P = [p1, p0, p3, p2];
  221. return P;
  222. };
  223. const append = (elements) => {
  224. var _a;
  225. if (elements.length <= 1)
  226. return;
  227. // Sort elements by normalized x to avoid cross.
  228. const sortedElements = sort(elements, (e0, e1) => {
  229. const { x: x0 } = e0.__data__;
  230. const { x: x1 } = e1.__data__;
  231. const dx = x0 - x1;
  232. return dx;
  233. });
  234. for (let i = 1; i < sortedElements.length; i++) {
  235. const p = d3Path();
  236. const e0 = sortedElements[i - 1];
  237. const e1 = sortedElements[i];
  238. const [p0, p1, p2, p3] = pathPointsOf(pointsOf(e0), pointsOf(e1));
  239. p.moveTo(...p0);
  240. p.lineTo(...p1);
  241. p.lineTo(...p2);
  242. p.lineTo(...p3);
  243. p.closePath();
  244. const _b = mapObject(style, (d) => valueof(d, e0)), { fill = e0.getAttribute('fill') } = _b, rest = __rest(_b, ["fill"]);
  245. const link = new Path({
  246. className: LINK_CLASS_NAME,
  247. style: Object.assign({ d: p.toString(), fill, zIndex: -2 }, rest),
  248. });
  249. // @ts-ignore
  250. (_a = e0.link) === null || _a === void 0 ? void 0 : _a.remove();
  251. e0.parentNode.appendChild(link);
  252. // @ts-ignore
  253. e0.link = link;
  254. }
  255. };
  256. const remove = (element) => {
  257. var _a;
  258. (_a = element.link) === null || _a === void 0 ? void 0 : _a.remove();
  259. element.link = null;
  260. };
  261. return [append, remove];
  262. }
  263. // Apply translate to mock slice out.
  264. export function offsetTransform(element, offset, coordinate) {
  265. const append = (t) => {
  266. const { transform } = element.style;
  267. return transform ? `${transform} ${t}` : t;
  268. };
  269. if (isPolar(coordinate)) {
  270. const { points } = element.__data__;
  271. const [p0, p1] = isTranspose(coordinate) ? reorder(points) : points;
  272. const center = coordinate.getCenter();
  273. const v0 = sub(p0, center);
  274. const v1 = sub(p1, center);
  275. const a0 = angle(v0);
  276. const da = angleBetween(v0, v1);
  277. const amid = a0 + da / 2;
  278. const dx = offset * Math.cos(amid);
  279. const dy = offset * Math.sin(amid);
  280. return append(`translate(${dx}, ${dy})`);
  281. }
  282. if (isTranspose(coordinate))
  283. return append(`translate(${offset}, 0)`);
  284. return append(`translate(0, ${-offset})`);
  285. }
  286. export function renderBackground(_a) {
  287. var { background, scale, coordinate, valueof } = _a, rest = __rest(_a, ["background", "scale", "coordinate", "valueof"]);
  288. const BACKGROUND_CLASS_NAME = 'element-background';
  289. // Don't have background.
  290. if (!background)
  291. return [() => { }, () => { }];
  292. const extentOf = (scale, x, padding) => {
  293. const ax = scale.invert(x);
  294. const mid = x + scale.getBandWidth(ax) / 2;
  295. const half = scale.getStep(ax) / 2;
  296. const offset = half * padding;
  297. return [mid - half + offset, mid + half - offset];
  298. };
  299. const sizeXOf = (element, padding) => {
  300. const { x: scaleX } = scale;
  301. if (!isOrdinalScale(scaleX))
  302. return [0, 1];
  303. const { __data__: data } = element;
  304. const { x } = data;
  305. const [e1, e2] = extentOf(scaleX, x, padding);
  306. return [e1, e2];
  307. };
  308. const sizeYOf = (element, padding) => {
  309. const { y: scaleY } = scale;
  310. if (!isOrdinalScale(scaleY))
  311. return [0, 1];
  312. const { __data__: data } = element;
  313. const { y } = data;
  314. const [e1, e2] = extentOf(scaleY, y, padding);
  315. return [e1, e2];
  316. };
  317. const bandShapeOf = (element, style) => {
  318. const { padding } = style;
  319. const [x1, x2] = sizeXOf(element, padding);
  320. const [y1, y2] = sizeYOf(element, padding);
  321. const points = [
  322. [x1, y1],
  323. [x2, y1],
  324. [x2, y2],
  325. [x1, y2],
  326. ].map((d) => coordinate.map(d));
  327. const { __data__: data } = element;
  328. const { y: dy, y1: dy1 } = data;
  329. return rect(points, { y: dy, y1: dy1 }, coordinate, style);
  330. };
  331. // Shape without ordinal style.
  332. // Clone and scale it.
  333. const cloneShapeOf = (element, style) => {
  334. const { transform = 'scale(1.2, 1.2)', transformOrigin = 'center center', stroke = '' } = style, rest = __rest(style, ["transform", "transformOrigin", "stroke"]);
  335. const finalStyle = Object.assign({ transform, transformOrigin, stroke }, rest);
  336. const shape = element.cloneNode(true);
  337. for (const [key, value] of Object.entries(finalStyle)) {
  338. shape.style[key] = value;
  339. }
  340. return shape;
  341. };
  342. const isOrdinalShape = () => {
  343. const { x, y } = scale;
  344. return [x, y].some(isOrdinalScale);
  345. };
  346. const append = (element) => {
  347. if (element.background)
  348. element.background.remove();
  349. const _a = mapObject(rest, (d) => valueof(d, element)), { fill = '#CCD6EC', fillOpacity = 0.3, zIndex = -2, padding = 0.001, strokeWidth = 0 } = _a, style = __rest(_a, ["fill", "fillOpacity", "zIndex", "padding", "strokeWidth"]);
  350. const finalStyle = Object.assign(Object.assign({}, style), { fill,
  351. fillOpacity,
  352. zIndex,
  353. padding,
  354. strokeWidth });
  355. const shapeOf = isOrdinalShape() ? bandShapeOf : cloneShapeOf;
  356. const shape = shapeOf(element, finalStyle);
  357. shape.className = BACKGROUND_CLASS_NAME;
  358. element.parentNode.appendChild(shape);
  359. element.background = shape;
  360. };
  361. const remove = (element) => {
  362. var _a;
  363. (_a = element.background) === null || _a === void 0 ? void 0 : _a.remove();
  364. element.background = null;
  365. };
  366. const is = (element) => {
  367. return element.className === BACKGROUND_CLASS_NAME;
  368. };
  369. return [append, remove, is];
  370. }
  371. export function setCursor(root, cursor) {
  372. // @ts-ignore
  373. const canvas = root.getRootNode().defaultView;
  374. const dom = canvas.getContextService().getDomElement();
  375. if (dom === null || dom === void 0 ? void 0 : dom.style)
  376. dom.style.cursor = cursor;
  377. }
  378. export function restoreCursor(root) {
  379. setCursor(root, 'default');
  380. }
  381. export function selectElementByData(elements, data, datum) {
  382. return elements.find((d) => Object.entries(data).every(([key, value]) => datum(d)[key] === value));
  383. }
  384. //# sourceMappingURL=utils.js.map