summaryrefslogtreecommitdiffstats
path: root/src/Doc.js
blob: 423204fa07bf75e6d71b0987a8f61de1e8ff0c08 (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
SVG.Doc = SVG.invent({
  // Initialize node
  create: function (node) {
    SVG.Element.call(this, node || SVG.create('svg'))

    // set svg element attributes and ensure defs node
    this.namespace()
  },

  // Inherit from
  inherit: SVG.Container,

  // Add class methods
  extend: {
    isRoot: function () {
      return !this.node.parentNode || !(this.node.parentNode instanceof window.SVGElement) || this.node.parentNode.nodeName === '#document'
    },
    // Check if this is a root svg. If not, call docs from this element
    doc: function () {
      if (this.isRoot()) return this
      return SVG.Element.prototype.doc.call(this)
    },
    // Add namespaces
    namespace: function () {
      if (!this.isRoot()) return this.doc().namespace()
      return this
        .attr({ xmlns: SVG.ns, version: '1.1' })
        .attr('xmlns:xlink', SVG.xlink, SVG.xmlns)
        .attr('xmlns:svgjs', SVG.svgjs, SVG.xmlns)
    },
    // Creates and returns defs element
    defs: function () {
      if (!this.isRoot()) return this.doc().defs()
      return SVG.adopt(this.node.getElementsByTagName('defs')[0]) || this.put(new SVG.Defs())
    },
    // custom parent method
    parent: function (type) {
      if (this.isRoot()) {
        return this.node.parentNode.nodeName === '#document' ? null : this.node.parentNode
      }

      return SVG.Element.prototype.parent.call(this, type)
    },
    // Removes the doc from the DOM
    remove: function () {
      if (!this.isRoot()) {
        return SVG.Element.prototype.remove.call(this)
      }

      if (this.parent()) {
        this.parent().removeChild(this.node)
      }

      return this
    },
    clear: function () {
      // remove children
      while (this.node.hasChildNodes()) {
        this.node.removeChild(this.node.lastChild)
      }
      return this
    }
  },
  construct: {
    // Create nested svg document
    nested: function () {
      return this.put(new SVG.Doc())
    }
  }
})