aboutsummaryrefslogtreecommitdiffstats
path: root/src/attr.js
blob: 19c7525d4abf1245ba47488a55476842ea782bd3 (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
SVG.extend(SVG.Element, {
  // Set svg element attribute
  attr: function (a, v, n) {
    // act as full getter
    if (a == null) {
      // get an object of attributes
      a = {}
      v = this.node.attributes
      for (n = v.length - 1; n >= 0; n--) {
        a[v[n].nodeName] = SVG.regex.isNumber.test(v[n].nodeValue)
          ? parseFloat(v[n].nodeValue)
          : v[n].nodeValue
      }
      return a
    } else if (typeof a === 'object') {
      // apply every attribute individually if an object is passed
      for (v in a) this.attr(v, a[v])
    } else if (v === null) {
        // remove value
      this.node.removeAttribute(a)
    } else if (v == null) {
      // act as a getter if the first and only argument is not an object
      v = this.node.getAttribute(a)
      return v == null ? SVG.defaults.attrs[a]
        : SVG.regex.isNumber.test(v) ? parseFloat(v)
        : v
    } else {
      // convert image fill and stroke to patterns
      if (a === 'fill' || a === 'stroke') {
        if (SVG.regex.isImage.test(v)) {
          v = this.doc().defs().image(v)
        }

        if (v instanceof SVG.Image) {
          v = this.doc().defs().pattern(0, 0, function () {
            this.add(v)
          })
        }
      }

      // ensure correct numeric values (also accepts NaN and Infinity)
      if (typeof v === 'number') {
        v = new SVG.Number(v)
      } else if (SVG.Color.isColor(v)) {
        // ensure full hex color
        v = new SVG.Color(v)
      } else if (Array.isArray(v)) {
        // parse array values
        v = new SVG.Array(v)
      }

      // if the passed attribute is leading...
      if (a === 'leading') {
        // ... call the leading method instead
        if (this.leading) {
          this.leading(v)
        }
      } else {
        // set given attribute on node
        typeof n === 'string' ? this.node.setAttributeNS(n, a, v.toString())
          : this.node.setAttribute(a, v.toString())
      }

      // rebuild if required
      if (this.rebuild && (a === 'font-size' || a === 'x')) {
        this.rebuild(a, v)
      }
    }

    return this
  }
})