import * as d3 from 'd3'; import GraphView from './graph-view'; import SlotView from './slot-view'; import { ICoord, d3Selection, getCurvePoints, getDistance } from './util'; import { SLOT_CONNECT_AVTIVE_DISTANCE } from './constants'; export interface InitialSettings { graphView: GraphView; slotView: SlotView; } export default class TrackerView { public $el: d3Selection; protected $path: d3Selection; protected slotView: SlotView; protected lineGenerator: d3.Line; protected points: [ICoord, ICoord]; constructor (settings: InitialSettings) { const { graphView, slotView } = settings; const slotCoord = slotView.getCoord(); this.$el = graphView.$el.append('g').classed('x-tracker', true); this.points = [this.getCoord(slotCoord), this.getCoord(slotCoord)]; this.lineGenerator = d3.line().x(d => d.x).y(d => d.y).curve(d3.curveBasis); this.$el.append("svg:defs").append("svg:marker") .attr("id", "track_triangle") .attr("viewBox", "5 -5 10 10") .attr("refX", 5) .attr("refY", 0) .attr("markerWidth", 10) .attr("markerHeight", 8) .attr("orient", "auto") .append("path") .attr("d", "M0,-5L10,0L0,5") .style("fill", "#358edf") this.$path = this.$el.append('path') .attr('d', this.lineGenerator(this.points)) .attr("marker-end", "url(#track_triangle)") .attr('stroke-width', 1); } private getCoord (slotCoord: ICoord) { return { x: slotCoord.x, y: slotCoord.y + 1, }; } public render (deltaX: number, deltaY: number) { const endPoint = this.points[1]; endPoint.x += deltaX; endPoint.y += deltaY; this.$path.attr('d', this.lineGenerator(this.points)); } public renderMatched () { const [start, end] = this.points; const curvePoints = getCurvePoints(start, end); this.$path.attr('d', this.lineGenerator(curvePoints)); this.$el.classed('matched', true); } public findConnectActiveSlot (connectable: [SlotView]) { const point = this.points[1]; let minDistance = Number.MAX_VALUE; let minDistanceSlot: SlotView; connectable.forEach((slotView) => { slotView.activeStyle(false); const distance = getDistance(point, slotView.getCoord()); if (distance < minDistance) { minDistance = distance; minDistanceSlot = slotView; } }); if (minDistance <= SLOT_CONNECT_AVTIVE_DISTANCE) { minDistanceSlot.activeStyle(); this.renderMatched(); return minDistanceSlot; } return null; } public destory () { this.$el.remove(); } }