summaryrefslogtreecommitdiffstats
path: root/src/modules/optional/css.js
blob: 1c5ed40902ffe0df1b7db788169f8840918822ff (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
76
77
78
79
import { isBlank } from '../core/regex.js'
import { registerMethods } from '../../utils/methods.js'

// Dynamic style generator
export function css(style, val) {
  const ret = {}
  if (arguments.length === 0) {
    // get full style as object
    this.node.style.cssText
      .split(/\s*;\s*/)
      .filter(function (el) {
        return !!el.length
      })
      .forEach(function (el) {
        const t = el.split(/\s*:\s*/)
        ret[t[0]] = t[1]
      })
    return ret
  }

  if (arguments.length < 2) {
    // get style properties as array
    if (Array.isArray(style)) {
      for (const name of style) {
        const cased = name
        ret[name] = this.node.style.getPropertyValue(cased)
      }
      return ret
    }

    // get style for property
    if (typeof style === 'string') {
      return this.node.style.getPropertyValue(style)
    }

    // set styles in object
    if (typeof style === 'object') {
      for (const name in style) {
        // set empty string if null/undefined/'' was given
        this.node.style.setProperty(
          name,
          style[name] == null || isBlank.test(style[name]) ? '' : style[name]
        )
      }
    }
  }

  // set style for property
  if (arguments.length === 2) {
    this.node.style.setProperty(
      style,
      val == null || isBlank.test(val) ? '' : val
    )
  }

  return this
}

// Show element
export function show() {
  return this.css('display', '')
}

// Hide element
export function hide() {
  return this.css('display', 'none')
}

// Is element visible?
export function visible() {
  return this.css('display') !== 'none'
}

registerMethods('Dom', {
  css,
  show,
  hide,
  visible
})