summaryrefslogtreecommitdiffstats
path: root/src/elements/Marker.js
blob: 10549878a6d8ce36baf45b5c2380e0d94e1dc9e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import { nodeOrNew, register, wrapWithAttrCheck } from '../utils/adopter.js'
import { registerMethods } from '../utils/methods.js'
import Container from './Container.js'

export default class Marker extends Container {

  // Initialize node
  constructor ( node ) {

    super( nodeOrNew( 'marker', node ), node )

  }

  // Set width of element
  width ( width ) {

    return this.attr( 'markerWidth', width )

  }

  // Set height of element
  height ( height ) {

    return this.attr( 'markerHeight', height )

  }

  // Set marker refX and refY
  ref ( x, y ) {

    return this.attr( 'refX', x ).attr( 'refY', y )

  }

  // Update marker
  update ( block ) {

    // remove all content
    this.clear()

    // invoke passed block
    if ( typeof block === 'function' ) {

      block.call( this, this )

    }

    return this

  }

  // Return the fill id
  toString () {

    return 'url(#' + this.id() + ')'

  }

}

registerMethods( {
  Container: {
    marker ( ...args ) {

      // Create marker element in defs
      return this.defs().marker( ...args )

    }
  },
  Defs: {
    // Create marker
    marker: wrapWithAttrCheck( function ( width, height, block ) {

      // Set default viewbox to match the width and height, set ref to cx and cy and set orient to auto
      return this.put( new Marker() )
        .size( width, height )
        .ref( width / 2, height / 2 )
        .viewbox( 0, 0, width, height )
        .attr( 'orient', 'auto' )
        .update( block )

    } )
  },
  marker: {
    // Create and attach markers
    marker ( marker, width, height, block ) {

      var attr = [ 'marker' ]

      // Build attribute name
      if ( marker !== 'all' ) attr.push( marker )
      attr = attr.join( '-' )

      // Set marker attribute
      marker = arguments[1] instanceof Marker
        ? arguments[1]
        : this.defs().marker( width, height, block )

      return this.attr( attr, marker )

    }
  }
} )

register( Marker )