ng-d3-graphs
Version:
<img src="./assets/ng-d3.png" alt="drawing" width="250" height="250"/>
1,110 lines (1,073 loc) • 68.4 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common'), require('d3'), require('rxjs'), require('rxjs/operators')) :
typeof define === 'function' && define.amd ? define('ng-d3-graphs', ['exports', '@angular/core', '@angular/common', 'd3', 'rxjs', 'rxjs/operators'], factory) :
(global = global || self, factory(global['ng-d3-graphs'] = {}, global.ng.core, global.ng.common, global.d3, global.rxjs, global.rxjs.operators));
}(this, (function (exports, core, common, d3, rxjs, operators) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(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;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __exportStar(m, exports) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result.default = mod;
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to get private field on non-instance");
}
return privateMap.get(receiver);
}
function __classPrivateFieldSet(receiver, privateMap, value) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to set private field on non-instance");
}
privateMap.set(receiver, value);
return value;
}
var axisConfig = {
color: 'lightgrey',
opacity: 1,
rendering: 'crispEdges',
strokeWidth: '1px',
xAxisTimeParser: '%Y-%m-%dT%H:%M:%S.%LZ',
xAxisTimeFormat: '%m/%d/%y',
xAxisTicks: 5,
};
var AxisDirection;
(function (AxisDirection) {
AxisDirection["top"] = "top";
AxisDirection["right"] = "right";
AxisDirection["bottom"] = "bottom";
AxisDirection["left"] = "left";
})(AxisDirection || (AxisDirection = {}));
var D3Service = /** @class */ (function () {
function D3Service() {
}
D3Service.prototype.translate = function (x, y) {
return "translate(" + x + ", " + y + ")";
};
D3Service.prototype.factoryAxis = function (scale, direction) {
switch (direction) {
case AxisDirection.top:
return d3.axisTop(scale);
case AxisDirection.right:
return d3.axisRight(scale);
case AxisDirection.bottom:
return d3.axisBottom(scale);
case AxisDirection.left:
return d3.axisLeft(scale);
default:
return new Error('No axis Direction Provided');
}
};
D3Service.prototype.factoryLine = function () {
return d3.line().x(function (d) { return d.x; }).y(function (d) { return d.y; });
};
// ==== Axis =====
D3Service.prototype.scaleLinearX = function (labels, width) {
return d3.scaleLinear()
.domain(d3.extent(labels)) // does the magic for adjustable axis
.range([0, width]);
};
D3Service.prototype.scaleLinearY = function (data, height) {
return d3.scaleLinear()
.domain(d3.extent(data)) // does the magic for adjustable axis
.range([height, 0]);
};
D3Service.prototype.scaleBandX = function (labels, width) {
return d3.scaleBand().domain(labels).rangeRound([0, width]).padding(0.1);
};
D3Service.prototype.scaleLinearYRangeRound = function (data, height) {
return d3.scaleLinear().domain([0, Math.max.apply(Math, __spread(data))]).rangeRound([
height, 0
]);
};
D3Service.prototype.addLabelAxisY = function (svg, height, options) {
svg.append('text')
.attr('transform', 'rotate(-90)')
.attr('y', 0 - options.margin.left)
.attr('x', 0 - height / 2)
.attr('dy', '1em')
.style('text-anchor', 'middle')
.text(options.yAxisLabel);
};
D3Service.prototype.addLabelAxisX = function (svg, width, height, options) {
svg.append('text')
.attr('transform', 'translate(' + width / 2 + ' ,' + (height + options.margin.top) +
')')
.style('text-anchor', 'middle')
.text(options.xAxisLabel);
};
D3Service.prototype.getViewBoxDefault = function (options) {
var res = {
minX: -options.margin.left,
minY: -25,
width: options.width,
height: options.height - options.margin.top,
};
return res;
};
D3Service.prototype.removeAxisTicks = function (axis) {
axis.selectAll('.tick').selectAll('line').remove();
};
D3Service.prototype.changeAxisColor = function (axis, config) {
axis.select('path')
.attr('color', config.color)
.attr('opacity', config.opacity)
.attr('rendering', config.rendering)
.attr('stroke-width', config.strokeWidth);
};
D3Service.prototype.getXaxisTime = function (svg, height, x, timeFormat$1, xAxisTicks) {
return svg.append('g')
.attr('transform', "translate(0," + height + ")")
.call(d3.axisBottom(x)
.tickFormat(d3.timeFormat(timeFormat$1))
.ticks(xAxisTicks));
};
D3Service.prototype.hideTooltip = function (tooltipText, tooltip) {
tooltipText.selectAll('tspan').remove();
tooltip.attr('visibility', 'hidden');
};
D3Service.prototype.showTooltip = function (d, xScale, yScale, tooltip, tooltipRect, tooltipText, formatTime) {
var xPos = xScale(d.x) - 150 / 2;
var yPos = yScale(d.y) + 10;
tooltip.attr('transform', "translate(" + xPos + ", " + yPos + ")")
.attr('is', true)
.attr('visibility', 'visible');
tooltipRect.attr('opacity', 0.7);
tooltipText.attr('tranform', 'translate(75,30)')
.attr('fill', 'white')
.attr('font-size', 10)
.attr('font-family', "'Roboto', 'sans-serif'");
tooltipText.append('tspan')
.attr('text-anchor', 'middle')
.attr('is', true)
.attr('x', 25)
.attr('y', -5)
.text("" + formatTime(d.x));
tooltipText.append('tspan')
.attr('text-anchor', 'middle')
.attr('is', true)
.attr('x', 20)
.attr('dy', 15)
.text("" + d.y);
};
D3Service.prototype.addTooltip = function (container) {
var tooltipConfig = {
width: 100,
height: 40,
fill: '#333',
opacity: 0.7,
rx: 15,
text: {
translateX: 10,
translateY: 20,
},
};
var tooltip = d3.select(container.nativeElement).select('svg').append('g');
var tooltipRect = tooltip.append('rect')
.attr('width', tooltipConfig.width)
.attr('height', tooltipConfig.height)
.attr('fill', tooltipConfig.fill)
.attr('opacity', 0)
.attr('rx', tooltipConfig.rx);
var tooltipText = tooltip.append('text').attr('transform', "translate(\n " + tooltipConfig.text.translateX + ",\n " + tooltipConfig.text.translateY + ")");
return { tooltip: tooltip, tooltipRect: tooltipRect, tooltipText: tooltipText, tooltipConfig: tooltipConfig };
};
D3Service.ngInjectableDef = core.ɵɵdefineInjectable({ factory: function D3Service_Factory() { return new D3Service(); }, token: D3Service, providedIn: "root" });
D3Service = __decorate([
core.Injectable({ providedIn: 'root' })
], D3Service);
return D3Service;
}());
var BandComponent = /** @class */ (function () {
function BandComponent(container, d3Service) {
this.container = container;
this.d3Service = d3Service;
this.data = [];
this.labels = [];
this.options = {};
this.labelsAndData = [];
this.viewBox = {};
this._options = {
width: 879,
height: 804,
margin: { top: 50, right: 50, bottom: 50, left: 50 },
yAxisLabel: '',
gridTicks: 0,
timeParser: axisConfig.xAxisTimeParser,
timeFormat: axisConfig.xAxisTimeFormat,
xAxisTicks: axisConfig.xAxisTicks,
};
this.parseTime = d3.timeParse(this.options.timeParser);
this.formatTime = d3.timeFormat(this.options.timeFormat);
this.onResize$ = new rxjs.Subject();
}
BandComponent.prototype.onResize = function () {
this.onResize$.next();
};
BandComponent.prototype.ngOnInit = function () {
this.options = __assign({}, this._options, this.options);
this.viewBox = {
minX: -this.options.margin.left,
minY: -10,
width: this.options.width + this.options.margin.left +
this.options.margin.right,
height: this.options.height + this.options.margin.top,
};
this.parseTime = d3.timeParse(this.options.timeParser);
this.formatTime = d3.timeFormat(this.options.timeFormat);
this.labels = this.formatLabels();
this.labelsAndData = this.combineLabelsDataToOne();
this.onResizeEvent();
this.render();
};
BandComponent.prototype.formatLabels = function () {
var _this = this;
return this.labels.map(function (d) { return _this.parseTime(d); });
};
BandComponent.prototype.combineLabelsDataToOne = function () {
var N = this.labels.length;
var result = [];
for (var index = 0; index < N; index++) {
result.push({
x: this.labels[index],
low: this.data[index].low,
high: this.data[index].high,
});
}
return result;
};
BandComponent.prototype.render = function () {
var currentWidth = parseInt(d3.select(this.container.nativeElement).select('div').style('width'), 10);
var currentHeight = parseInt(d3.select(this.container.nativeElement).select('div').style('height'), 10);
var width = this.options.width - this.options.margin.left -
this.options.margin.right;
var height = this.options.height - this.options.margin.top -
this.options.margin.bottom;
this.viewBox = {
minX: -this.options.margin.left,
minY: -10,
width: this.options.width,
height: this.options.height - this.options.margin.top,
};
var svg = d3.select(this.container.nativeElement)
.select('div')
.append('svg')
.attr('width', currentWidth)
.attr('height', currentHeight)
.attr('viewBox', this.viewBox.minX + " " + this.viewBox.minY + " " + this.viewBox.width + " " + this.viewBox.height)
.classed('svg-content', true)
.append('g');
var x = d3.scaleTime()
.domain(d3.extent(this.labels, function (d) { return new Date(d); }))
.range([0, width]);
var y = d3.scaleLinear()
.domain([
d3.min(this.data, function (d) { return d.low; }), d3.max(this.data, function (d) { return d.high; })
])
.nice(this.options.gridTicks)
.range([height, 0]);
// add the X gridlines
svg.append('g')
.attr('class', 'grid')
.call(this.make_x_gridlines(x).tickSize(height)
// .tickFormat('')
);
// add the Y gridlines
svg.append('g')
.attr('class', 'grid')
.call(this.make_y_gridlines(y).tickSize(-width)
// .tickFormat('')
);
var xAxis = this.d3Service.getXaxisTime(svg, height, x, this.options.timeFormat, this.options.xAxisTicks);
var yAxis = function (g) {
return g.attr('transform', "translate(" + 0 + ",0)").call(d3.axisLeft(y));
};
var curve = d3.curveStep;
var area$1 = d3.area()
.curve(curve)
.x(function (d) { return x(d.x); })
.y0(function (d) { return y(d.low); })
.y1(function (d) { return y(d.high); });
var _yAxis = svg.append('g').call(yAxis);
// this.d3Service.addLabelAxisX(svg, width, height, this.options);
// text label for the x axis
this.addLabelAxisX(svg, width, height);
// text label for the y axis
this.addLabelAxisY(svg, height);
svg.append('path')
.datum(this.labelsAndData)
.attr('fill', 'steelblue')
.attr('d', area$1);
this.removeAxisTicks(xAxis);
this.removeAxisTicks(_yAxis);
this.changeAxisColor(xAxis, axisConfig);
this.changeAxisColor(_yAxis, axisConfig);
};
BandComponent.prototype.changeAxisColor = function (axis, config) {
this.d3Service.changeAxisColor(axis, config);
};
BandComponent.prototype.removeAxisTicks = function (axis) {
this.d3Service.removeAxisTicks(axis);
};
BandComponent.prototype.addLabelAxisY = function (svg, height) {
svg.append('text')
.attr('transform', 'rotate(0)')
.attr('y', 0 - this.options.margin.top / 2)
.attr('x', 0)
.attr('dy', '1em')
.style('text-anchor', 'start')
.text(this.options.yAxisLabel);
};
BandComponent.prototype.addLabelAxisX = function (svg, width, height) {
svg.append('text')
.attr('transform', 'translate(' + width / 2 + ' ,' +
(height + this.options.margin.top - 15) + ')')
.style('text-anchor', 'middle')
.text(this.options.xAxisLabel);
};
// gridlines in x axis function
BandComponent.prototype.make_x_gridlines = function (x) {
return d3.axisBottom(x).ticks(this.options.gridTicks);
};
// gridlines in y axis function
BandComponent.prototype.make_y_gridlines = function (y) {
return d3.axisLeft(y).ticks(this.options.gridTicks);
};
BandComponent.prototype.onResizeEvent = function () {
var _this = this;
this.onResize$.pipe(operators.debounceTime(200)).subscribe(function () {
var svgExist = d3.select(_this.container.nativeElement).select('svg');
if (svgExist) {
svgExist.remove();
}
_this.render();
});
};
BandComponent.ctorParameters = function () { return [
{ type: core.ElementRef },
{ type: D3Service }
]; };
__decorate([
core.Input()
], BandComponent.prototype, "data", void 0);
__decorate([
core.Input()
], BandComponent.prototype, "labels", void 0);
__decorate([
core.Input()
], BandComponent.prototype, "options", void 0);
__decorate([
core.HostListener('window:resize')
], BandComponent.prototype, "onResize", null);
BandComponent = __decorate([
core.Component({
selector: 'ng-band',
template: "<div class=\"svg-container\"></div>\n",
encapsulation: core.ViewEncapsulation.None,
styles: [".svg-container{display:inline-block;position:relative;width:100%;height:100%;padding-bottom:100%;vertical-align:top;overflow:hidden}.svg-content{display:inline-block;position:absolute;top:0;left:0}.grid line{stroke:#d3d3d3;stroke-opacity:.4;shape-rendering:crispEdges}.grid path{stroke-width:0}.grid text{display:none}.area{fill:#4682b4}"]
})
], BandComponent);
return BandComponent;
}());
var BandModule = /** @class */ (function () {
function BandModule() {
}
BandModule = __decorate([
core.NgModule({
declarations: [BandComponent],
imports: [
common.CommonModule
],
exports: [BandComponent],
})
], BandModule);
return BandModule;
}());
var BarComponent = /** @class */ (function () {
function BarComponent(container, d3Service) {
this.container = container;
this.d3Service = d3Service;
this.data = [];
this.labels = [];
this.options = {};
this.graph = {
xAxis: [],
yAxis: [],
xAxisPath: '',
yAxisPath: '',
rectanglesData: [],
};
this.labelsAndData = [];
this.parseTime = d3.timeParse('%d-%b-%y');
this._options = {
width: 879,
height: 804,
margin: { top: 50, right: 50, bottom: 50, left: 50 },
gridTicks: 0,
};
this.viewBox = {};
this.onResize$ = new rxjs.Subject();
}
BarComponent.prototype.onResize = function () {
this.onResize$.next();
};
BarComponent.prototype.ngOnInit = function () {
this.options = __assign({}, this._options, this.options);
this.viewBox = {
minX: -this.options.margin.left,
minY: -10,
width: this.options.width + this.options.margin.left +
this.options.margin.right,
height: this.options.height + this.options.margin.top,
};
this.labelsAndData = this.combineLabelsDataToOne();
this.onResizeEvent();
this.render();
};
BarComponent.prototype.render = function () {
var currentWidth = parseInt(d3.select(this.container.nativeElement).select('div').style('width'), 10);
var currentHeight = parseInt(d3.select(this.container.nativeElement).select('div').style('height'), 10);
var width = this.options.width - this.options.margin.left -
this.options.margin.right;
var height = this.options.height - this.options.margin.top -
this.options.margin.bottom;
this.viewBox = {
minX: -this.options.margin.left,
minY: -10,
width: this.options.width,
height: this.options.height - this.options.margin.top,
};
var svg = d3.select(this.container.nativeElement)
.select('div')
.append('svg')
.attr('width', currentWidth)
.attr('height', currentHeight)
.attr('viewBox', this.viewBox.minX + " " + this.viewBox.minY + " " + this.viewBox.width + " " + this.viewBox.height)
.classed('svg-content', true)
.append('g');
var x = d3.scaleBand().rangeRound([0, width]).padding(0.1).domain(this.labels);
var y = d3.scaleLinear().rangeRound([height, 0]).domain([
0,
Math.max.apply(Math, __spread(this.data.map(function (d) { return Number(d); })))
]);
var xAxis = function (g) { return g.call(d3.axisBottom(x))
.attr('transform', 'translate(0,' + height + ')'); };
var yAxis = function (g) { return g.call(d3.axisLeft(y)); };
// add the X gridlines
svg.append('g')
.attr('class', 'grid')
.call(this.make_x_gridlines(x).tickSize(height)
// .tickFormat('')
);
// add the Y gridlines
svg.append('g')
.attr('class', 'grid')
.call(this.make_y_gridlines(y).tickSize(-width)
// .tickFormat('')
);
svg.selectAll('.bar')
.data(this.labelsAndData)
.enter()
.append('rect')
.attr('class', 'bar')
.attr('x', function (d) {
return x(d.x);
})
.attr('y', function (d) {
return y(Number(d.y));
})
.attr('width', x.bandwidth())
.attr('height', function (d) {
return height - y(Number(d.y));
});
var _xAxis = svg.append('g').call(xAxis);
// text label for the x axis
this.addLabelAxisX(svg, width, height);
var _yAxis = svg.append('g').call(yAxis);
// text label for the y axis
this.addLabelAxisY(svg, height);
this.removeAxisTicks(_xAxis);
this.removeAxisTicks(_yAxis);
this.changeAxisColor(_xAxis, axisConfig);
this.changeAxisColor(_yAxis, axisConfig);
};
BarComponent.prototype.changeAxisColor = function (axis, config) {
this.d3Service.changeAxisColor(axis, config);
};
BarComponent.prototype.removeAxisTicks = function (axis) {
this.d3Service.removeAxisTicks(axis);
};
BarComponent.prototype.addLabelAxisY = function (svg, height) {
svg.append('text')
.attr('transform', 'rotate(0)')
.attr('y', 0 - this.options.margin.top / 2)
.attr('x', 0)
.attr('dy', '1em')
.style('text-anchor', 'start')
.text(this.options.yAxisLabel);
};
BarComponent.prototype.addLabelAxisX = function (svg, width, height) {
svg.append('text')
.attr('transform', 'translate(' + width / 2 + ' ,' +
(height + this.options.margin.top - 15) + ')')
.style('text-anchor', 'middle')
.text(this.options.xAxisLabel);
};
BarComponent.prototype.combineLabelsDataToOne = function () {
var result = [];
var N = this.data.length;
for (var index = 0; index < N; index++) {
result.push({ x: this.labels[index], y: this.data[index] });
}
return result;
};
// gridlines in x axis function
BarComponent.prototype.make_x_gridlines = function (x) {
return d3.axisBottom(x).ticks(this.options.gridTicks);
};
// gridlines in y axis function
BarComponent.prototype.make_y_gridlines = function (y) {
return d3.axisLeft(y).ticks(this.options.gridTicks);
};
BarComponent.prototype.onResizeEvent = function () {
var _this = this;
this.onResize$.pipe(operators.debounceTime(200)).subscribe(function () {
var svgExist = d3.select(_this.container.nativeElement).select('svg');
if (svgExist) {
svgExist.remove();
}
_this.render();
});
};
BarComponent.ctorParameters = function () { return [
{ type: core.ElementRef },
{ type: D3Service }
]; };
__decorate([
core.Input()
], BarComponent.prototype, "data", void 0);
__decorate([
core.Input()
], BarComponent.prototype, "labels", void 0);
__decorate([
core.Input()
], BarComponent.prototype, "options", void 0);
__decorate([
core.HostListener('window:resize')
], BarComponent.prototype, "onResize", null);
BarComponent = __decorate([
core.Component({
selector: 'ng-bar',
template: "\n<div class=\"svg-container\"></div>\n",
encapsulation: core.ViewEncapsulation.None,
changeDetection: core.ChangeDetectionStrategy.OnPush,
styles: [".svg-container{display:inline-block;position:relative;width:100%;height:100%;padding-bottom:100%;vertical-align:top;overflow:hidden}.svg-content{display:inline-block;position:absolute;top:0;left:0}.grid line{stroke:#d3d3d3;stroke-opacity:.4;shape-rendering:crispEdges}.grid path{stroke-width:0}.grid text{display:none}.bar{fill:#4682b4}.bar:hover{fill:brown}"]
})
], BarComponent);
return BarComponent;
}());
var BarService = /** @class */ (function () {
function BarService() {
}
BarService = __decorate([
core.Injectable()
], BarService);
return BarService;
}());
var BarModule = /** @class */ (function () {
function BarModule() {
}
BarModule = __decorate([
core.NgModule({
declarations: [BarComponent],
imports: [
common.CommonModule
],
providers: [
BarService
],
exports: [BarComponent]
})
], BarModule);
return BarModule;
}());
var LineComponent = /** @class */ (function () {
function LineComponent(container, d3Service) {
this.container = container;
this.d3Service = d3Service;
this.data = [];
this.labels = [];
this.options = {};
this._options = {
width: 879,
height: 804,
margin: { top: 50, right: 50, bottom: 50, left: 50 },
gridTicks: 0,
yAxisLabel: '',
xAxisLabel: '',
timeParser: axisConfig.xAxisTimeParser,
timeFormat: axisConfig.xAxisTimeFormat,
xAxisTicks: axisConfig.xAxisTicks,
};
this.parseTime = d3.timeParse(this.options.timeParser);
this.formatTime = d3.timeFormat(this.options.timeFormat);
this.viewBox = {};
this.labelsAndData = [];
this.AxisDataX = [];
this.onResize$ = new rxjs.Subject();
}
LineComponent.prototype.onResize = function () {
this.onResize$.next();
};
LineComponent.prototype.ngOnInit = function () {
var _this = this;
this.options = __assign({}, this._options, this.options);
this.viewBox = this.d3Service.getViewBoxDefault(this.options);
this.parseTime = d3.timeParse(this.options.timeParser);
this.formatTime = d3.timeFormat(this.options.timeFormat);
this.labels = this.labels.map(function (d) { return _this.parseTime(d); });
this.labelsAndData = this.combineLabelsDataToOne();
this.onResizeEvent();
this.render();
};
LineComponent.prototype.render = function () {
var currentWidth = parseInt(d3.select(this.container.nativeElement).select('div').style('width'), 10);
var currentHeight = parseInt(d3.select(this.container.nativeElement).select('div').style('height'), 10);
var width = this.options.width - this.options.margin.left -
this.options.margin.right;
var height = this.options.height - this.options.margin.top -
this.options.margin.bottom;
this.viewBox = {
minX: -this.options.margin.left,
minY: -10,
width: this.options.width,
height: this.options.height - this.options.margin.top,
};
var svg = d3.select(this.container.nativeElement)
.select('div')
.append('svg')
.attr('width', currentWidth)
.attr('height', currentHeight)
.attr('viewBox', this.viewBox.minX + " " + this.viewBox.minY + " " + this.viewBox.width + " " + this.viewBox.height)
.classed('svg-content', true)
.append('g');
var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]).nice();
var valueline = d3.line().x(function (d) { return x(d.x); }).y(function (d) { return y(d.y); });
x.domain(d3.extent(this.labels, function (d) { return (d); }));
y.domain([0, d3.max(this.data, function (d) { return d; })]);
// add the X gridlines
svg.append('g')
.attr('class', 'grid')
.call(this.make_x_gridlines(x).tickSize(height)
// .tickFormat('')
);
// add the Y gridlines
svg.append('g')
.attr('class', 'grid')
.call(this.make_y_gridlines(y).tickSize(-width)
// .tickFormat('')
);
svg.append('path')
.datum(this.labelsAndData)
.attr('class', 'line')
.attr('d', valueline);
// add the X Axis
var xAxis = this.d3Service.getXaxisTime(svg, height, x, this.options.timeFormat, this.options.xAxisTicks);
// text label for the x axis
this.addLabelAxisX(svg, width, height);
// add the Y Axis
var yAxis = svg.append('g').call(d3.axisLeft(y));
// text label for the y axis
this.addLabelAxisY(svg, height);
this.removeAxisTicks(xAxis);
this.removeAxisTicks(yAxis);
this.changeAxisColor(xAxis, axisConfig);
this.changeAxisColor(yAxis, axisConfig);
this.addDots(svg, x, y);
};
LineComponent.prototype.addDots = function (svg, x, y) {
var _this = this;
var dotRadius = 3;
var dotColor = '#4682b4';
// add tootlip
var _a = this.d3Service.addTooltip(this.container), tooltip = _a.tooltip, tooltipRect = _a.tooltipRect, tooltipText = _a.tooltipText, tooltipConfig = _a.tooltipConfig;
svg.selectAll('dot')
.data(this.labelsAndData)
.enter()
.append('circle')
.attr('r', dotRadius)
.attr('fill', dotColor)
.attr('cx', function (d) {
return x(d.x);
})
.attr('cy', function (d) {
return y(d.y);
})
.on('mouseover', function (d) {
_this.onMouseOver(d, x, y, tooltip, tooltipRect, tooltipText);
})
.on('mouseout', function (d) {
_this.onMouseOut(d, tooltip, tooltipText, tooltipConfig);
});
};
LineComponent.prototype.onMouseOver = function (d, xScale, yScale, tooltip, tooltipRect, tooltipText) {
// show tooltip
if (tooltip) {
this.d3Service.showTooltip(d, xScale, yScale, tooltip, tooltipRect, tooltipText, this.formatTime);
}
};
LineComponent.prototype.onMouseOut = function (d, tooltip, tooltipText, tooltipConfig) {
// hide tooltip
if (tooltip) {
this.d3Service.hideTooltip(tooltipText, tooltip);
}
};
LineComponent.prototype.changeAxisColor = function (axis, config) {
this.d3Service.changeAxisColor(axis, config);
};
LineComponent.prototype.removeAxisTicks = function (axis) {
this.d3Service.removeAxisTicks(axis);
};
LineComponent.prototype.addLabelAxisY = function (svg, height) {
svg.append('text')
.attr('transform', 'rotate(0)')
.attr('y', 0 - this.options.margin.top / 2)
.attr('x', 0)
.attr('dy', '1em')
.style('text-anchor', 'start')
.text(this.options.yAxisLabel);
};
LineComponent.prototype.addLabelAxisX = function (svg, width, height) {
svg.append('text')
.attr('transform', 'translate(' + width / 2 + ' ,' +
(height + this.options.margin.top - 15) + ')')
.style('text-anchor', 'middle')
.text(this.options.xAxisLabel);
};
LineComponent.prototype.combineLabelsDataToOne = function () {
var result = [];
var N = this.data.length;
for (var index = 0; index < N; index++) {
result.push({ x: this.labels[index], y: this.data[index] });
}
return result;
};
// gridlines in x axis function
LineComponent.prototype.make_x_gridlines = function (x) {
return d3.axisBottom(x).ticks(this.options.gridTicks);
};
// gridlines in y axis function
LineComponent.prototype.make_y_gridlines = function (y) {
return d3.axisLeft(y).ticks(this.options.gridTicks);
};
LineComponent.prototype.onResizeEvent = function () {
var _this = this;
this.onResize$.pipe(operators.debounceTime(200)).subscribe(function () {
var svgExist = d3.select(_this.container.nativeElement).select('svg');
if (svgExist) {
svgExist.remove();
}
_this.render();
});
};
LineComponent.ctorParameters = function () { return [
{ type: core.ElementRef },
{ type: D3Service }
]; };
__decorate([
core.Input()
], LineComponent.prototype, "data", void 0);
__decorate([
core.Input()
], LineComponent.prototype, "labels", void 0);
__decorate([
core.Input()
], LineComponent.prototype, "options", void 0);
__decorate([
core.HostListener('window:resize')
], LineComponent.prototype, "onResize", null);
LineComponent = __decorate([
core.Component({
selector: 'ng-line',
template: "<div class=\"svg-container\"></div>\n",
encapsulation: core.ViewEncapsulation.None,
changeDetection: core.ChangeDetectionStrategy.OnPush,
styles: [".svg-container{display:inline-block;position:relative;width:100%;height:100%;padding-bottom:100%;vertical-align:top;overflow:hidden}.svg-content{display:inline-block;position:absolute;top:0;left:0}.grid line{stroke:#d3d3d3;stroke-opacity:.4;shape-rendering:crispEdges}.grid path{stroke-width:0}.grid text{display:none}.line{fill:none;stroke:#4682b4;stroke-width:2px}div.tooltip{position:absolute;text-align:center;min-width:60px;min-height:28px;padding:5px;font:12px sans-serif;background:#b0c4de;border:0;border-radius:5px;pointer-events:none;color:#000}"]
})
], LineComponent);
return LineComponent;
}());
var LineService = /** @class */ (function () {
function LineService(config) {
this.config = config;
}
LineService.prototype.showConfig = function () {
console.log(this.config);
};
LineService.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: core.Inject, args: ['config',] }] }
]; };
LineService = __decorate([
core.Injectable(),
__param(0, core.Inject('config'))
], LineService);
return LineService;
}());
var LineModule = /** @class */ (function () {
function LineModule() {
}
LineModule_1 = LineModule;
LineModule.forRoot = function (config) {
return {
ngModule: LineModule_1,
providers: [
LineService,
{ provide: 'config', useValue: config },
]
};
};
var LineModule_1;
LineModule = LineModule_1 = __decorate([
core.NgModule({
declarations: [LineComponent,],
imports: [
common.CommonModule
],
exports: [LineComponent],
providers: [
LineService
]
})
], LineModule);
return LineModule;
}());
var MultilineComponent = /** @class */ (function () {
function MultilineComponent(container, d3Service) {
this.container = container;
this.d3Service = d3Service;
this.data = [];
this.labels = [];
this.options = {};
this.labelsAndData = [];
this.utcParse = d3.utcParse('%Y-%m');
this.viewBox = {};
this._options = {
width: 879,
height: 804,
yAxisLabel: '',
xAxisLabel: '',
margin: { top: 50, right: 50, bottom: 50, left: 50 },
timeParser: axisConfig.xAxisTimeParser,
timeFormat: axisConfig.xAxisTimeFormat,
xAxisTicks: axisConfig.xAxisTicks,
};
this.parseTime = d3.timeParse(this.options.timeParser);
this.formatTime = d3.timeFormat(this.options.timeFormat);
this.onResize$ = new rxjs.Subject();
}
MultilineComponent.prototype.onResize = function () {
this.onResize$.next();
};
MultilineComponent.prototype.ngOnInit = function () {
this.options = __assign({}, this._options, this.options);
this.viewBox = {
minX: -this.options.margin.left,
minY: -25,
width: this.options.width + this.options.margin.left +
this.options.margin.right,
height: this.options.height + this.options.margin.top,
};
this.parseTime = d3.timeParse(this.options.timeParser);
this.formatTime = d3.timeFormat(this.options.timeFormat);
this.labels = this.formatData();
this.labelsAndData = this.combineLabelsDataToOne();
this.onResizeEvent();
this.render();
};
MultilineComponent.prototype.formatData = function () {
var _this = this;
return this.labels.map(function (d) { return _this.parseTime(d); });
};
MultilineComponent.prototype.combineLabelsDataToOne = function () {
var result = [];
var N = this.data.length;
for (var index = 0; index < N; index++) {
result.push({ x: this.labels, y: this.data[index] });
}
return result;
};
MultilineComponent.prototype.render = function () {
var _this = this;
var currentWidth = parseInt(d3.select(this.container.nativeElement).select('div').style('width'), 10);
var currentHeight = parseInt(d3.select(this.container.nativeElement).select('div').style('height'), 10);
var width = this.options.width - this.options.margin.left