summaryrefslogtreecommitdiffstats
path: root/src/elemnts-svg.js
blob: b5b2542ec53671028787a5ba363eec683f64e3a5 (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
import { ns } from './namespaces.js'

/* eslint no-unused-vars: "off" */
var a = {
  // Import raw svg
  svg (svg, fn = false) {
    var well, len, fragment

    // act as getter if no svg string is given
    if (svg == null || svg === true || typeof svg === 'function') {
      // write svgjs data to the dom
      this.writeDataToDom()
      let current = this

      // An export modifier was passed
      if (typeof svg === 'function') {
        // Juggle arguments
        [fn, svg] = [svg, fn]

        // If the user wants outerHTML we need to process this node, too
        if (!svg) {
          current = fn(current)

          // The user does not want this node? Well, then he gets nothing
          if (current === false) return ''
        }

        // Deep loop through all children and apply modifier
        current.each(function () {
          let result = fn(this)

          // If modifier returns false, discard node
          if (result === false) {
            this.remove()

            // If modifier returns new node, use it
          } else if (result !== this) {
            this.replace(result)
          }
        }, true)
      }

      // Return outer or inner content
      return svg
        ? current.node.innerHTML
        : current.node.outerHTML
    }

    // Act as setter if we got a string

    // Create temporary holder
    well = document.createElementNS(ns, 'svg')
    fragment = document.createDocumentFragment()

    // Dump raw svg
    well.innerHTML = svg

    // Transplant nodes into the fragment
    for (len = well.children.length; len--;) {
      fragment.appendChild(well.firstElementChild)
    }

    // Add the whole fragment at once
    this.node.appendChild(fragment)

    return this
  }
}