UNPKG

2.2 kBJavaScriptView Raw
1var inherits = require('inherits')
2var domify = require('domify')
3var insert = require('insert')
4var css = require('dom-css')
5var attr = require('./lib/attr')
6var html = require('./lib/html')
7var classes = require('dom-classes')
8
9module.exports = Elle
10function Elle(element) {
11 if (!(this instanceof Elle))
12 return new Elle(element)
13 this[0] = toElement(element) || document.createElement('div')
14}
15
16//for a jQuery like array dereference we will inherit from Array
17inherits(Elle, Array)
18
19var Proto = Elle.prototype
20
21//getters/setters
22Object.defineProperty(Proto, 'view', {
23 get: function() {
24 return this[0]
25 },
26 enumerable: true,
27 configurable: true
28})
29
30
31//misc utils
32Proto.css = wrap(css)
33Proto.html = property(html)
34Proto.attr = property(attr, 1)
35
36Proto.parent = function() {
37 return Elle(this[0].parentNode)
38}
39
40//class mixins
41Proto.hasClass = function(name) {
42 return classes.has(this[0], name)
43}
44
45;['remove', 'add', 'toggle']
46 .forEach(function(name) {
47 Proto[name+'Class'] = wrap(classes[name])
48 })
49
50//mixin inserts
51;['remove', 'prepend', 'append',
52 'before', 'after', 'replace']
53 .forEach(function(name) {
54 Proto[name] = wrap(insert[name], toElement)
55 })
56
57//mixin inserts with a target
58Proto.appendTo = wrapTarget(insert.append)
59Proto.prependTo = wrapTarget(insert.prepend)
60Proto.insertBefore = wrapTarget(insert.before)
61Proto.insertAfter = wrapTarget(insert.after)
62
63
64//always returns this for chaining
65function wrap(fn, map) {
66 return function(...args) {
67 if (map)
68 args = args.map(map)
69 var a = [this[0], ...args]
70 fn(...a)
71 return this
72 }
73}
74
75//single argument --> return value
76function property(fn, expected) {
77 return function(...args) {
78 var a = [this[0], ...args]
79 var ret = fn(...a)
80 return args.length===(expected|0) ? ret : this
81 }
82}
83
84//for insert/remove/etc
85function wrapTarget(fn) {
86 return function(target) {
87 fn(toElement(target), this[0])
88 return this
89 }
90}
91
92function toElement(e) {
93 if (typeof e === 'string')
94 return domify(e)
95 else if (e && e.view && e.view.nodeType)
96 return e.view
97 return e
98}
\No newline at end of file