d3plus-shape
Version:
Fancy SVG shapes for visualizations
210 lines (203 loc) • 11.4 kB
JavaScript
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); }
function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
import { extent, sum } from "d3-array";
import { nest } from "d3-collection";
import { interpolatePath } from "d3-interpolate-path";
import { select } from "d3-selection";
import * as paths from "d3-shape";
import { constant, merge } from "d3plus-common";
import Shape from "./Shape.js";
/**
@class Line
@extends Shape
@desc Creates SVG lines based on an array of data.
*/
var Line = /*#__PURE__*/function (_Shape) {
_inherits(Line, _Shape);
var _super = _createSuper(Line);
/**
@memberof Line
@desc Invoked when creating a new class instance, and overrides any default parameters inherited from Shape.
@private
*/
function Line() {
var _this;
_classCallCheck(this, Line);
_this = _super.call(this);
_this._curve = constant("linear");
_this._defined = function (d) {
return d;
};
_this._fill = constant("none");
_this._hitArea = constant({
"d": function d(_d) {
return _this._path(_d.values);
},
"fill": "none",
"stroke-width": 10,
"transform": null
});
_this._name = "Line";
_this._path = paths.line();
_this._stroke = constant("black");
_this._strokeWidth = constant(1);
return _this;
}
/**
@memberof Line
@desc Filters/manipulates the data array before binding each point to an SVG group.
@param {Array} [*data* = the data array to be filtered]
@private
*/
_createClass(Line, [{
key: "_dataFilter",
value: function _dataFilter(data) {
var _this2 = this;
var lines = nest().key(this._id).entries(data).map(function (d) {
d.data = merge(d.values);
d.i = data.indexOf(d.values[0]);
var x = extent(d.values, _this2._x);
d.xR = x;
d.width = x[1] - x[0];
d.x = x[0] + d.width / 2;
var y = extent(d.values, _this2._y);
d.yR = y;
d.height = y[1] - y[0];
d.y = y[0] + d.height / 2;
d.nested = true;
d.translate = [d.x, d.y];
d.__d3plusShape__ = true;
return d;
});
lines.key = function (d) {
return d.key;
};
return lines;
}
/**
@memberof Line
@desc Draws the lines.
@param {Function} [*callback*]
@chainable
*/
}, {
key: "render",
value: function render(callback) {
var _this3 = this;
_get(_getPrototypeOf(Line.prototype), "render", this).call(this, callback);
var that = this;
/**
@desc Calculates the stroke-dasharray used for animations
@param {Object} *d* data point
@private
*/
function calculateStrokeDashArray(d) {
d.initialLength = this.getTotalLength();
var strokeArray = that._strokeDasharray(d.values[0], that._data.indexOf(d.values[0])).split(" ").map(Number);
if (strokeArray.length === 1 && strokeArray[0] === 0) strokeArray = [d.initialLength];else if (strokeArray.length === 1) strokeArray.push(strokeArray[0]);else if (strokeArray.length % 2) strokeArray = strokeArray.concat(strokeArray);
var newStrokeArray = [];
var strokeLength = 0;
while (strokeLength < d.initialLength) {
for (var i = 0; i < strokeArray.length; i++) {
var num = strokeArray[i];
strokeLength += num;
newStrokeArray.push(num);
if (strokeLength >= d.initialLength) break;
}
}
if (newStrokeArray.length > 1 && newStrokeArray.length % 2) newStrokeArray.pop();
newStrokeArray[newStrokeArray.length - 1] += d.initialLength - sum(newStrokeArray);
if (newStrokeArray.length % 2 === 0) newStrokeArray.push(0);
d.initialStrokeArray = newStrokeArray.join(" ");
}
var userCurve = this._curve.bind(this)(this.config());
var curve = paths["curve".concat(userCurve.charAt(0).toUpperCase()).concat(userCurve.slice(1))];
this._path.curve(curve).defined(this._defined).x(this._x).y(this._y);
var enter = this._enter.append("path").attr("transform", function (d) {
return "translate(".concat(-d.xR[0] - d.width / 2, ", ").concat(-d.yR[0] - d.height / 2, ")");
}).attr("d", function (d) {
return _this3._path(d.values);
}).call(this._applyStyle.bind(this));
var update = this._update.select("path").attr("stroke-dasharray", function (d) {
return that._strokeDasharray(d.values[0], that._data.indexOf(d.values[0]));
});
if (this._duration) {
enter.each(calculateStrokeDashArray).attr("stroke-dasharray", function (d) {
return "".concat(d.initialStrokeArray, " ").concat(d.initialLength);
}).attr("stroke-dashoffset", function (d) {
return d.initialLength;
}).transition(this._transition).attr("stroke-dashoffset", 0);
update = update.transition(this._transition).attrTween("d", function (d) {
return interpolatePath(select(this).attr("d"), that._path(d.values));
});
this._exit.selectAll("path").each(calculateStrokeDashArray).attr("stroke-dasharray", function (d) {
return "".concat(d.initialStrokeArray, " ").concat(d.initialLength);
}).transition(this._transition).attr("stroke-dashoffset", function (d) {
return -d.initialLength;
});
} else {
update = update.attr("d", function (d) {
return that._path(d.values);
});
}
update.attr("transform", function (d) {
return "translate(".concat(-d.xR[0] - d.width / 2, ", ").concat(-d.yR[0] - d.height / 2, ")");
}).call(this._applyStyle.bind(this));
return this;
}
/**
@memberof Line
@desc Given a specific data point and index, returns the aesthetic properties of the shape.
@param {Object} *data point*
@param {Number} *index*
@private
*/
}, {
key: "_aes",
value: function _aes(d, i) {
var _this4 = this;
return {
points: d.values.map(function (p) {
return [_this4._x(p, i), _this4._y(p, i)];
})
};
}
/**
@memberof Line
@desc If *value* is specified, sets the area curve to the specified string and returns the current class instance. If *value* is not specified, returns the current area curve.
@param {Function|String} [*value* = "linear"]
@chainable
*/
}, {
key: "curve",
value: function curve(_) {
return arguments.length ? (this._curve = typeof _ === "function" ? _ : constant(_), this) : this._curve;
}
/**
@memberof Line
@desc If *value* is specified, sets the defined accessor to the specified function and returns the current class instance. If *value* is not specified, returns the current defined accessor.
@param {Function} [*value*]
@chainable
*/
}, {
key: "defined",
value: function defined(_) {
return arguments.length ? (this._defined = _, this) : this._defined;
}
}]);
return Line;
}(Shape);
export { Line as default };