@antv/g2
Version:
the Grammar of Graphics in Javascript
459 lines • 18.2 kB
JavaScript
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.maybeRoot = exports.getThetaPath = exports.getElements = exports.getPointsPath = exports.getPointsR = 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.bboxOf = exports.selectPlotArea = exports.selectFacetViews = exports.selectFacetG2Elements = exports.selectG2Elements = void 0;
const g_1 = require("@antv/g");
const d3_path_1 = require("d3-path");
const d3_array_1 = require("d3-array");
const util_1 = require("@antv/util");
const selection_1 = require("../utils/selection");
const array_1 = require("../utils/array");
const runtime_1 = require("../runtime");
const scale_1 = require("../utils/scale");
const color_1 = require("../shape/interval/color");
const coordinate_1 = require("../utils/coordinate");
const style_1 = require("../utils/style");
const utils_1 = require("../shape/utils");
const vector_1 = require("../utils/vector");
/**
* Given root of chart returns elements to be manipulated
*/
function selectG2Elements(root) {
return (0, selection_1.select)(root)
.selectAll(`.${runtime_1.ELEMENT_CLASS_NAME}`)
.nodes()
.filter((d) => !d.__removed__);
}
exports.selectG2Elements = selectG2Elements;
function selectFacetG2Elements(target, viewInstances) {
return selectFacetViews(target, viewInstances).flatMap(({ container }) => selectG2Elements(container));
}
exports.selectFacetG2Elements = selectFacetG2Elements;
function selectFacetViews(target, viewInstances) {
return viewInstances.filter((d) => d !== target && d.options.parentKey === target.options.key);
}
exports.selectFacetViews = selectFacetViews;
function selectPlotArea(root) {
return (0, selection_1.select)(root).select(`.${runtime_1.PLOT_CLASS_NAME}`).node();
}
exports.selectPlotArea = selectPlotArea;
function bboxOf(element) {
// The geometry bounds of a group is empty, so return the render bounds.
if (element.tagName === 'g')
return element.getRenderBounds();
// Compute the geometry bounds related to the parent.
const bounds = element.getGeometryBounds();
const aabb = new g_1.AABB();
aabb.setFromTransformedAABB(bounds, element.getWorldTransform());
return aabb;
}
exports.bboxOf = bboxOf;
function mousePosition(target, event) {
const { offsetX, offsetY } = event;
const bbox = bboxOf(target);
const { min: [x, y], max: [x1, y1], } = bbox;
const isOutX = offsetX < x || offsetX > x1;
const isOutY = offsetY < y || offsetY > y1;
if (isOutX || isOutY)
return null;
return [offsetX - x, offsetY - y];
}
exports.mousePosition = mousePosition;
/**
* @todo Pass bbox rather than calc it here.
*/
function brushMousePosition(target, event) {
const { offsetX, offsetY } = event;
const [x, y, x1, y1] = boundsOfBrushArea(target);
return [
Math.min(x1, Math.max(x, offsetX)) - x,
Math.min(y1, Math.max(y, offsetY)) - y,
];
}
exports.brushMousePosition = brushMousePosition;
function boundsOfBrushArea(target) {
// Calc bbox after clipping.
const bbox = target.getRenderBounds();
const { min: [x0, y0], max: [x1, y1], } = bbox;
return [x0, y0, x1, y1];
}
exports.boundsOfBrushArea = boundsOfBrushArea;
function createColorKey(view) {
return (element) => element.__data__.color;
}
exports.createColorKey = createColorKey;
function createXKey(view) {
return (element) => element.__data__.x;
}
exports.createXKey = createXKey;
function createDatumof(view) {
const views = Array.isArray(view) ? view : [view];
const keyData = new Map(views.flatMap((view) => {
const marks = Array.from(view.markState.keys());
return marks.map((mark) => [keyed(view.key, mark.key), mark.data]);
}));
return (element) => {
const { index, markKey, viewKey } = element.__data__;
const data = keyData.get(keyed(viewKey, markKey));
return data[index];
};
}
exports.createDatumof = createDatumof;
/**
* A state manager for G2Element.
* The keys for each state's style start with the state name.
* { selectedFill, selectedStroke } is for selected state.
* { unselectedFill, unselectedStroke } is for unselected state.
*/
function useState(style, valueof = (d, element) => d, setAttribute = (element, key, v) => element.setAttribute(key, v)) {
const STATES = '__states__';
const ORIGINAL = '__ordinal__';
// Mix style for each state and apply it to element.
const updateState = (element) => {
const { [STATES]: states = [], [ORIGINAL]: original = {} } = element;
const stateStyle = states.reduce((mixedStyle, state) => (Object.assign(Object.assign({}, mixedStyle), style[state])), original);
if (Object.keys(stateStyle).length === 0)
return;
for (const [key, value] of Object.entries(stateStyle)) {
const currentValue = (0, style_1.getStyle)(element, key);
const v = valueof(value, element);
setAttribute(element, key, v);
// Store the attribute if it does not exist in original.
if (!(key in original))
original[key] = currentValue;
}
element[ORIGINAL] = original;
};
const initState = (element) => {
if (element[STATES])
return;
element[STATES] = [];
return;
};
/**
* Set the states and update element.
*/
const setState = (element, ...states) => {
initState(element);
element[STATES] = [...states];
updateState(element);
};
/**
* Remove the states and update element.
*/
const removeState = (element, ...states) => {
initState(element);
for (const state of states) {
const index = element[STATES].indexOf(state);
if (index !== -1) {
element[STATES].splice(index, 1);
}
}
updateState(element);
};
const hasState = (element, state) => {
initState(element);
return element[STATES].indexOf(state) !== -1;
};
return {
setState,
removeState,
hasState,
};
}
exports.useState = useState;
function isEmptyObject(obj) {
if (obj === undefined)
return true;
if (typeof obj !== 'object')
return false;
return Object.keys(obj).length === 0;
}
// A function to generate key for mark each view.
function keyed(viewKey, markKey) {
return `${viewKey},${markKey}`;
}
function mergeState(options, states) {
// Index state by mark key and view key.
const views = Array.isArray(options) ? options : [options];
const markState = views.flatMap((view) => view.marks.map((mark) => [keyed(view.key, mark.key), mark.state]));
const state = {};
// Update each specified state.
for (const descriptor of states) {
const [key, defaults] = Array.isArray(descriptor)
? descriptor
: [descriptor, {}];
// Update each specified mark state.
state[key] = markState.reduce((merged, mark) => {
// Normalize state.
const [markKey, markState = {}] = mark;
const selectedState = isEmptyObject(markState[key])
? defaults
: markState[key];
// Update each state attribute.
for (const [attr, value] of Object.entries(selectedState)) {
const oldValue = merged[attr];
const newValue = (data, index, array, element) => {
const k = keyed(element.__data__.viewKey, element.__data__.markKey);
if (markKey !== k)
return oldValue === null || oldValue === void 0 ? void 0 : oldValue(data, index, array, element);
if (typeof value !== 'function')
return value;
return value(data, index, array, element);
};
merged[attr] = newValue;
}
return merged;
}, {});
}
return state;
}
exports.mergeState = mergeState;
// @todo Support elements from different view.
function createValueof(elements, datum) {
const elementIndex = new Map(elements.map((d, i) => [d, i]));
const fa = datum ? elements.map(datum) : elements;
return (d, e) => {
if (typeof d !== 'function')
return d;
const i = elementIndex.get(e);
const fe = datum ? datum(e) : e;
return d(fe, i, fa, e);
};
}
exports.createValueof = createValueof;
function renderLink(_a) {
var { link = false, valueof = (d, element) => d, coordinate } = _a, style = __rest(_a, ["link", "valueof", "coordinate"]);
const LINK_CLASS_NAME = 'element-link';
if (!link)
return [() => { }, () => { }];
const pointsOf = (element) => element.__data__.points;
const pathPointsOf = (P0, P1) => {
const [, p1, p2] = P0;
const [p0, , , p3] = P1;
const P = [p1, p0, p3, p2];
return P;
};
const append = (elements) => {
var _a;
if (elements.length <= 1)
return;
// Sort elements by normalized x to avoid cross.
const sortedElements = (0, d3_array_1.sort)(elements, (e0, e1) => {
const { x: x0 } = e0.__data__;
const { x: x1 } = e1.__data__;
const dx = x0 - x1;
return dx;
});
for (let i = 1; i < sortedElements.length; i++) {
const p = (0, d3_path_1.path)();
const e0 = sortedElements[i - 1];
const e1 = sortedElements[i];
const [p0, p1, p2, p3] = pathPointsOf(pointsOf(e0), pointsOf(e1));
p.moveTo(...p0);
p.lineTo(...p1);
p.lineTo(...p2);
p.lineTo(...p3);
p.closePath();
const _b = (0, array_1.mapObject)(style, (d) => valueof(d, e0)), { fill = e0.getAttribute('fill') } = _b, rest = __rest(_b, ["fill"]);
const link = new g_1.Path({
className: LINK_CLASS_NAME,
style: Object.assign({ d: p.toString(), fill, zIndex: -2 }, rest),
});
// @ts-ignore
(_a = e0.link) === null || _a === void 0 ? void 0 : _a.remove();
e0.parentNode.appendChild(link);
// @ts-ignore
e0.link = link;
}
};
const remove = (element) => {
var _a;
(_a = element.link) === null || _a === void 0 ? void 0 : _a.remove();
element.link = null;
};
return [append, remove];
}
exports.renderLink = renderLink;
// Apply translate to mock slice out.
function offsetTransform(element, offset, coordinate) {
const append = (t) => {
const { transform } = element.style;
return transform ? `${transform} ${t}` : t;
};
if ((0, coordinate_1.isPolar)(coordinate)) {
const { points } = element.__data__;
const [p0, p1] = (0, coordinate_1.isTranspose)(coordinate) ? (0, utils_1.reorder)(points) : points;
const center = coordinate.getCenter();
const v0 = (0, vector_1.sub)(p0, center);
const v1 = (0, vector_1.sub)(p1, center);
const a0 = (0, vector_1.angle)(v0);
const da = (0, vector_1.angleBetween)(v0, v1);
const amid = a0 + da / 2;
const dx = offset * Math.cos(amid);
const dy = offset * Math.sin(amid);
return append(`translate(${dx}, ${dy})`);
}
if ((0, coordinate_1.isTranspose)(coordinate))
return append(`translate(${offset}, 0)`);
return append(`translate(0, ${-offset})`);
}
exports.offsetTransform = offsetTransform;
function renderBackground(_a) {
var { document, background, scale, coordinate, valueof } = _a, rest = __rest(_a, ["document", "background", "scale", "coordinate", "valueof"]);
const BACKGROUND_CLASS_NAME = 'element-background';
// Don't have background.
if (!background)
return [() => { }, () => { }];
const extentOf = (scale, x, padding) => {
const ax = scale.invert(x);
const mid = x + scale.getBandWidth(ax) / 2;
const half = scale.getStep(ax) / 2;
const offset = half * padding;
return [mid - half + offset, mid + half - offset];
};
const sizeXOf = (element, padding) => {
const { x: scaleX } = scale;
if (!(0, scale_1.isOrdinalScale)(scaleX))
return [0, 1];
const { __data__: data } = element;
const { x } = data;
const [e1, e2] = extentOf(scaleX, x, padding);
return [e1, e2];
};
const sizeYOf = (element, padding) => {
const { y: scaleY } = scale;
if (!(0, scale_1.isOrdinalScale)(scaleY))
return [0, 1];
const { __data__: data } = element;
const { y } = data;
const [e1, e2] = extentOf(scaleY, y, padding);
return [e1, e2];
};
const bandShapeOf = (element, style) => {
const { padding } = style;
const [x1, x2] = sizeXOf(element, padding);
const [y1, y2] = sizeYOf(element, padding);
const points = [
[x1, y1],
[x2, y1],
[x2, y2],
[x1, y2],
].map((d) => coordinate.map(d));
const { __data__: data } = element;
const { y: dy, y1: dy1 } = data;
return (0, color_1.rect)(document, points, { y: dy, y1: dy1 }, coordinate, style);
};
// Shape without ordinal style.
// Clone and scale it.
const cloneShapeOf = (element, style) => {
const { transform = 'scale(1.2, 1.2)', transformOrigin = 'center center', stroke = '' } = style, rest = __rest(style, ["transform", "transformOrigin", "stroke"]);
const finalStyle = Object.assign({ transform, transformOrigin, stroke }, rest);
const shape = element.cloneNode(true);
for (const [key, value] of Object.entries(finalStyle)) {
shape.style[key] = value;
}
return shape;
};
const isOrdinalShape = () => {
const { x, y } = scale;
return [x, y].some(scale_1.isOrdinalScale);
};
const append = (element) => {
if (element.background)
element.background.remove();
const _a = (0, array_1.mapObject)(rest, (d) => valueof(d, element)), { fill = '#CCD6EC', fillOpacity = 0.3, zIndex = -2, padding = 0.001, lineWidth = 0 } = _a, style = __rest(_a, ["fill", "fillOpacity", "zIndex", "padding", "lineWidth"]);
const finalStyle = Object.assign(Object.assign({}, style), { fill,
fillOpacity,
zIndex,
padding,
lineWidth });
const shapeOf = isOrdinalShape() ? bandShapeOf : cloneShapeOf;
const shape = shapeOf(element, finalStyle);
shape.className = BACKGROUND_CLASS_NAME;
element.parentNode.parentNode.appendChild(shape);
element.background = shape;
};
const remove = (element) => {
var _a;
(_a = element.background) === null || _a === void 0 ? void 0 : _a.remove();
element.background = null;
};
const is = (element) => {
return element.className === BACKGROUND_CLASS_NAME;
};
return [append, remove, is];
}
exports.renderBackground = renderBackground;
function setCursor(root, cursor) {
// @ts-ignore
const canvas = root.getRootNode().defaultView;
const dom = canvas.getContextService().getDomElement();
if (dom === null || dom === void 0 ? void 0 : dom.style) {
root.cursor = dom.style.cursor;
dom.style.cursor = cursor;
}
}
exports.setCursor = setCursor;
function restoreCursor(root) {
setCursor(root, root.cursor);
}
exports.restoreCursor = restoreCursor;
function selectElementByData(elements, data, datum) {
return elements.find((d) => Object.entries(data).every(([key, value]) => datum(d)[key] === value));
}
exports.selectElementByData = selectElementByData;
function getPointsR(point, nextPoint) {
return Math.sqrt(Math.pow(point[0] - nextPoint[0], 2) + Math.pow(point[1] - nextPoint[1], 2));
}
exports.getPointsR = getPointsR;
// Points create path.
function getPointsPath(points, isClose = false) {
const path = (0, util_1.filter)(points, (d) => !!d).map((d, i) => {
return [i === 0 ? 'M' : 'L', ...d];
});
if (isClose) {
path.push(['Z']);
}
return path;
}
exports.getPointsPath = getPointsPath;
// Get element.
function getElements(plot) {
return plot.querySelectorAll('.element');
}
exports.getElements = getElements;
// Get Theta coordinate round path.
function getThetaPath(center, points, isBig = 0) {
const path = [['M', ...points[1]]];
const innerRadius = getPointsR(center, points[1]);
const outerRadius = getPointsR(center, points[0]);
if (innerRadius === 0) {
path.push(['L', ...points[3]], ['A', outerRadius, outerRadius, 0, isBig, 1, ...points[0]], ['Z']);
}
else {
path.push(['A', innerRadius, innerRadius, 0, isBig, 0, ...points[2]], ['L', ...points[3]], ['A', outerRadius, outerRadius, 0, isBig, 1, ...points[0]], ['Z']);
}
return path;
}
exports.getThetaPath = getThetaPath;
function maybeRoot(node, rootOf) {
if (rootOf(node))
return node;
let root = node.parent;
while (root && !rootOf(root))
root = root.parent;
return root;
}
exports.maybeRoot = maybeRoot;
//# sourceMappingURL=utils.js.map
;