summaryrefslogtreecommitdiffstats
path: root/src/Doc.js
blob: e4969965958bcbf6e8ff12ee98cabdc0da1965af (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
import Container from './Container.js'
import Parent from './Parent.js'
import {adopt, extend} from './tools.js'
import {ns, xlink, xmlns, svgjs} from './namespaces.js'

export default class Doc extends Container {
   constructor (node) {
     super(nodeOrNew('svg', node))
     this.namespace()
   }

   isRoot () {
     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 () {
     if (this.isRoot()) return this
     return super.doc()
   }

   // Add namespaces
   namespace () {
     if (!this.isRoot()) return this.doc().namespace()
     return this
       .attr({ xmlns: ns, version: '1.1' })
       .attr('xmlns:xlink', xlink, xmlns)
       .attr('xmlns:svgjs', svgjs, xmlns)
   }

   // Creates and returns defs element
   defs () {
     if (!this.isRoot()) return this.doc().defs()
     return adopt(this.node.getElementsByTagName('defs')[0]) ||
      this.put(new Defs())
   }

   // custom parent method
   parent (type) {
     if (this.isRoot()) {
       return this.node.parentNode.nodeName === '#document' ? null : this.node.parentNode
     }

     return super.parent(type)
   }

   // Removes the doc from the DOM
   remove () {
     if (!this.isRoot()) {
       return super.remove()
     }

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

     return this
   }

   clear () {
     // remove children
     while (this.node.hasChildNodes()) {
       this.node.removeChild(this.node.lastChild)
     }
     return this
   }
}

addFactory(Container, {
  // Create nested svg document
  nested () {
    return this.put(new Doc())
  }
})