-
Notifications
You must be signed in to change notification settings - Fork 19
/
browser.js
114 lines (97 loc) · 3 KB
/
browser.js
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
var through = require('through');
var hyperglue = require('hyperglue');
var domify = require('domify');
module.exports = function (html, cb) {
var className = classNameOf(html);
var tr = through(function (line) {
var row;
if (isInt8Array(line)) {
var s = '';
for (var i = 0; i < line.length; i++) s += line[i];
line = s;
}
if (typeof line === 'string') {
try { row = JSON.parse(line) }
catch (err) { this.emit('error', err) }
}
else row = line;
var res = cb.call(this, row);
if (res) {
var elem = hyperglue(html, res);
this.emit('element', elem);
this.queue(elem.outerHTML);
}
});
tr.prependTo = function (t) {
var target = getTarget(t);
tr.on('element', function (elem) {
target.insertBefore(elem, target.childNodes[0]);
});
return tr;
};
tr.appendTo = function (t) {
var target = getTarget(t);
tr.on('element', function (elem) {
target.appendChild(elem);
});
return tr;
};
tr.sortTo = function (t, cmp) {
if (typeof cmp !== 'function') {
throw new Error('comparison function not provided');
}
var target = getElem(t);
tr.on('element', function (elem) {
var nodes = target.getElementsByClassName(className);
for (var i = 0; i < nodes.length; i++) {
var n = cmp(elem, nodes[i]);
if (n < 0) {
if (hasChild(target, elem)) {
target.removeChild(elem);
}
target.insertBefore(elem, nodes[i]);
return;
}
}
target.appendChild(elem);
});
getTarget(t, target);
return tr;
};
var emittedElements = false;
return tr;
function getTarget (t, target) {
if (!target) target = getElem(t);
if (!className) return target;
if (emittedElements) return target;
emittedElements = true;
var elems = target.getElementsByClassName(className);
for (var i = 0; i < elems.length; i++) {
tr.emit('element', elems[i]);
}
return target;
}
};
function classNameOf (html) {
var elems = domify(html);
if (elems.length) return elems[0].getAttribute('class');
}
function hasChild (node, child) {
var nodes = node.childNodes;
for (var i = 0; i < nodes.length; i++) {
if (nodes[i] === child) return true;
}
return false;
}
function getElem (target) {
if (typeof target === 'string') {
return document.querySelector(target);
}
return target;
}
function isInt8Array (line) {
return line && typeof line === 'object'
&& line.constructor === 'function'
&& line.constructor.name === 'Int8Array'
;
}