Sean Condon | 0c577f6 | 2018-11-18 22:40:05 +0000 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright 2018-present Open Networking Foundation |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | import { Directive, ElementRef, Input, OnChanges } from '@angular/core'; |
| 17 | import { ForceDirectedGraph, Node } from '../models'; |
| 18 | import * as d3 from 'd3'; |
| 19 | |
| 20 | @Directive({ |
| 21 | selector: '[onosDraggableNode]' |
| 22 | }) |
| 23 | export class DraggableDirective implements OnChanges { |
| 24 | @Input() draggableNode: Node; |
| 25 | @Input() draggableInGraph: ForceDirectedGraph; |
| 26 | |
| 27 | constructor( |
| 28 | private _element: ElementRef |
| 29 | ) { |
| 30 | } |
| 31 | |
| 32 | ngOnChanges() { |
| 33 | this.applyDraggableBehaviour( |
| 34 | this._element.nativeElement, |
| 35 | this.draggableNode, |
| 36 | this.draggableInGraph); |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * A method to bind a draggable behaviour to an svg element |
| 41 | */ |
| 42 | applyDraggableBehaviour(element, node: Node, graph: ForceDirectedGraph) { |
| 43 | const d3element = d3.select(element); |
| 44 | |
| 45 | function started() { |
| 46 | /** Preventing propagation of dragstart to parent elements */ |
| 47 | d3.event.sourceEvent.stopPropagation(); |
| 48 | |
| 49 | if (!d3.event.active) { |
| 50 | graph.simulation.alphaTarget(0.3).restart(); |
| 51 | } |
| 52 | |
| 53 | d3.event.on('drag', dragged).on('end', ended); |
| 54 | |
| 55 | function dragged() { |
| 56 | node.fx = d3.event.x; |
| 57 | node.fy = d3.event.y; |
| 58 | } |
| 59 | |
| 60 | function ended() { |
| 61 | if (!d3.event.active) { |
| 62 | graph.simulation.alphaTarget(0); |
| 63 | } |
| 64 | |
| 65 | node.fx = null; |
| 66 | node.fy = null; |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | d3element.call(d3.drag() |
| 71 | .on('start', started)); |
| 72 | } |
| 73 | } |