utils.js 16 KB

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