summaryrefslogtreecommitdiffstats
path: root/src/modules/optional/data.js
blob: a9d7ac784ea2a4c5c506923b6304e6b20c0f8df6 (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
import { registerMethods } from '../../utils/methods.js'
import { filter, map } from '../../utils/utils.js'

// Store data values on svg nodes
export function data(a, v, r) {
  if (a == null) {
    // get an object of attributes
    return this.data(
      map(
        filter(
          this.node.attributes,
          (el) => el.nodeName.indexOf('data-') === 0
        ),
        (el) => el.nodeName.slice(5)
      )
    )
  } else if (a instanceof Array) {
    const data = {}
    for (const key of a) {
      data[key] = this.data(key)
    }
    return data
  } else if (typeof a === 'object') {
    for (v in a) {
      this.data(v, a[v])
    }
  } else if (arguments.length < 2) {
    try {
      return JSON.parse(this.attr('data-' + a))
    } catch (e) {
      return this.attr('data-' + a)
    }
  } else {
    this.attr(
      'data-' + a,
      v === null
        ? null
        : r === true || typeof v === 'string' || typeof v === 'number'
          ? v
          : JSON.stringify(v)
    )
  }

  return this
}

registerMethods('Dom', { data })