first commit

This commit is contained in:
DanielRamirezGe
2020-01-14 20:43:08 -06:00
parent 3557894f7f
commit 5eecfbf6cd
26326 changed files with 2434803 additions and 0 deletions
+6
View File
@@ -0,0 +1,6 @@
language: node_js
node_js:
- 8.12.0
sudo: false
+20
View File
@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2015 Aria Minaei
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+189
View File
@@ -0,0 +1,189 @@
# RenderKid
[![Build Status](https://secure.travis-ci.org/AriaMinaei/RenderKid.png)](http://travis-ci.org/AriaMinaei/RenderKid)
RenderKid allows you to use HTML and CSS to style your CLI output, making it easy to create a beautiful, readable, and consistent look for your nodejs tool.
## Installation
Install with npm:
```
$ npm install renderkid
```
## Usage
```coffeescript
RenderKid = require('renderkid')
r = new RenderKid()
r.style({
"ul": {
display: "block"
margin: "2 0 2"
}
"li": {
display: "block"
marginBottom: "1"
}
"key": {
color: "grey"
marginRight: "1"
}
"value": {
color: "bright-white"
}
})
output = r.render("
<ul>
<li>
<key>Name:</key>
<value>RenderKid</value>
</li>
<li>
<key>Version:</key>
<value>0.2</value>
</li>
<li>
<key>Last Update:</key>
<value>Jan 2015</value>
</li>
</ul>
")
console.log(output)
```
![screenshot of usage](https://github.com/AriaMinaei/RenderKid/raw/master/docs/images/usage.png)
## Stylesheet properties
### Display mode
Elements can have a `display` of either `inline`, `block`, or `none`:
```coffeescript
r.style({
"div": {
display: "block"
}
"span": {
display: "inline" # default
}
"hidden": {
display: "none"
}
})
output = r.render("
<div>This will fill one or more rows.</div>
<span>These</span> <span>will</span> <span>be</span> in the same <span>line.</span>
<hidden>This won't be displayed.</hidden>
")
console.log(output)
```
![screenshot of usage](https://github.com/AriaMinaei/RenderKid/raw/master/docs/images/display.png)
### Margin
Margins work just like they do in browsers:
```coffeescript
r.style({
"li": {
display: "block"
marginTop: "1"
marginRight: "2"
marginBottom: "3"
marginLeft: "4"
# or the shorthand version:
"margin": "1 2 3 4"
},
"highlight": {
display: "inline"
marginLeft: "2"
marginRight: "2"
}
})
r.render("
<ul>
<li>Item <highlgiht>1</highlight></li>
<li>Item <highlgiht>2</highlight></li>
<li>Item <highlgiht>3</highlight></li>
</ul>
")
```
### Padding
See margins above. Paddings work the same way, only inward.
### Width and Height
Block elements can have explicit width and height:
```coffeescript
r.style({
"box": {
display: "block"
"width": "4"
"height": "2"
}
})
r.render("<box>This is a box and some of its text will be truncated.</box>")
```
### Colors
You can set a custom color and background color for each element:
```coffeescript
r.style({
"error": {
color: "black"
background: "red"
}
})
```
List of colors currently supported are `black`, `red`, `green`, `yellow`, `blue`, `magenta`, `cyan`, `white`, `grey`, `bright-red`, `bright-green`, `bright-yellow`, `bright-blue`, `bright-magenta`, `bright-cyan`, `bright-white`.
### Bullet points
Block elements can have bullet points on their margins. Let's start with an example:
```coffeescript
r.style({
"li": {
# To add bullet points to an element, first you
# should make some room for the bullet point by
# giving your element some margin to the left:
marginLeft: "4",
# Now we can add a bullet point to our margin:
bullet: '"-"'
}
})
# The four hyphens are there for visual reference
r.render("
----
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
----
")
```
And here is the result:
![screenshot of bullet points, 1](https://github.com/AriaMinaei/RenderKid/raw/master/docs/images/bullets-1.png)
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

+125
View File
@@ -0,0 +1,125 @@
// Generated by CoffeeScript 1.9.3
var AnsiPainter, object, styles, tags, tools,
hasProp = {}.hasOwnProperty,
slice = [].slice;
tools = require('./tools');
tags = require('./ansiPainter/tags');
styles = require('./ansiPainter/styles');
object = require('utila').object;
module.exports = AnsiPainter = (function() {
var self;
function AnsiPainter() {}
AnsiPainter.tags = tags;
AnsiPainter.prototype.paint = function(s) {
return this._replaceSpecialStrings(this._renderDom(this._parse(s)));
};
AnsiPainter.prototype._replaceSpecialStrings = function(str) {
return str.replace(/&sp;/g, ' ').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&amp;/g, '&');
};
AnsiPainter.prototype._parse = function(string, injectFakeRoot) {
if (injectFakeRoot == null) {
injectFakeRoot = true;
}
if (injectFakeRoot) {
string = '<none>' + string + '</none>';
}
return tools.toDom(string);
};
AnsiPainter.prototype._renderDom = function(dom) {
var parentStyles;
parentStyles = {
bg: 'none',
color: 'none'
};
return this._renderChildren(dom, parentStyles);
};
AnsiPainter.prototype._renderChildren = function(children, parentStyles) {
var child, n, ret;
ret = '';
for (n in children) {
if (!hasProp.call(children, n)) continue;
child = children[n];
ret += this._renderNode(child, parentStyles);
}
return ret;
};
AnsiPainter.prototype._renderNode = function(node, parentStyles) {
if (node.type === 'text') {
return this._renderTextNode(node, parentStyles);
} else {
return this._renderTag(node, parentStyles);
}
};
AnsiPainter.prototype._renderTextNode = function(node, parentStyles) {
return this._wrapInStyle(node.data, parentStyles);
};
AnsiPainter.prototype._wrapInStyle = function(str, style) {
return styles.color(style.color) + styles.bg(style.bg) + str + styles.none();
};
AnsiPainter.prototype._renderTag = function(node, parentStyles) {
var currentStyles, tagStyles;
tagStyles = this._getStylesForTagName(node.name);
currentStyles = this._mixStyles(parentStyles, tagStyles);
return this._renderChildren(node.children, currentStyles);
};
AnsiPainter.prototype._mixStyles = function() {
var final, i, key, len, style, styles, val;
styles = 1 <= arguments.length ? slice.call(arguments, 0) : [];
final = {};
for (i = 0, len = styles.length; i < len; i++) {
style = styles[i];
for (key in style) {
if (!hasProp.call(style, key)) continue;
val = style[key];
if ((final[key] == null) || val !== 'inherit') {
final[key] = val;
}
}
}
return final;
};
AnsiPainter.prototype._getStylesForTagName = function(name) {
if (tags[name] == null) {
throw Error("Unknown tag name `" + name + "`");
}
return tags[name];
};
self = AnsiPainter;
AnsiPainter.getInstance = function() {
if (self._instance == null) {
self._instance = new self;
}
return self._instance;
};
AnsiPainter.paint = function(str) {
return self.getInstance().paint(str);
};
AnsiPainter.strip = function(s) {
return s.replace(/\x1b\[[0-9]+m/g, '');
};
return AnsiPainter;
})();
+110
View File
@@ -0,0 +1,110 @@
// Generated by CoffeeScript 1.9.3
var Block, Layout, SpecialString, fn, i, len, object, prop, ref, terminalWidth;
Block = require('./layout/Block');
object = require('utila').object;
SpecialString = require('./layout/SpecialString');
terminalWidth = require('./tools').getCols();
module.exports = Layout = (function() {
var self;
self = Layout;
Layout._rootBlockDefaultConfig = {
linePrependor: {
options: {
amount: 0
}
},
lineAppendor: {
options: {
amount: 0
}
},
blockPrependor: {
options: {
amount: 0
}
},
blockAppendor: {
options: {
amount: 0
}
}
};
Layout._defaultConfig = {
terminalWidth: terminalWidth
};
function Layout(config, rootBlockConfig) {
var rootConfig;
if (config == null) {
config = {};
}
if (rootBlockConfig == null) {
rootBlockConfig = {};
}
this._written = [];
this._activeBlock = null;
this._config = object.append(self._defaultConfig, config);
rootConfig = object.append(self._rootBlockDefaultConfig, rootBlockConfig);
this._root = new Block(this, null, rootConfig, '__root');
this._root._open();
}
Layout.prototype.getRootBlock = function() {
return this._root;
};
Layout.prototype._append = function(text) {
return this._written.push(text);
};
Layout.prototype._appendLine = function(text) {
var s;
this._append(text);
s = SpecialString(text);
if (s.length < this._config.terminalWidth) {
this._append('<none>\n</none>');
}
return this;
};
Layout.prototype.get = function() {
this._ensureClosed();
if (this._written[this._written.length - 1] === '<none>\n</none>') {
this._written.pop();
}
return this._written.join("");
};
Layout.prototype._ensureClosed = function() {
if (this._activeBlock !== this._root) {
throw Error("Not all the blocks have been closed. Please call block.close() on all open blocks.");
}
if (this._root.isOpen()) {
this._root.close();
}
};
return Layout;
})();
ref = ['openBlock', 'write'];
fn = function() {
var method;
method = prop;
return Layout.prototype[method] = function() {
return this._root[method].apply(this._root, arguments);
};
};
for (i = 0, len = ref.length; i < len; i++) {
prop = ref[i];
fn();
}
+197
View File
@@ -0,0 +1,197 @@
// Generated by CoffeeScript 1.9.3
var AnsiPainter, Layout, RenderKid, Styles, blockStyleApplier, inlineStyleApplier, object, stripAnsi, terminalWidth, tools;
inlineStyleApplier = require('./renderKid/styleApplier/inline');
blockStyleApplier = require('./renderKid/styleApplier/block');
AnsiPainter = require('./AnsiPainter');
Styles = require('./renderKid/Styles');
Layout = require('./Layout');
tools = require('./tools');
object = require('utila').object;
stripAnsi = require('strip-ansi');
terminalWidth = require('./tools').getCols();
module.exports = RenderKid = (function() {
var self;
self = RenderKid;
RenderKid.AnsiPainter = AnsiPainter;
RenderKid.Layout = Layout;
RenderKid.quote = tools.quote;
RenderKid.tools = tools;
RenderKid._defaultConfig = {
layout: {
terminalWidth: terminalWidth
}
};
function RenderKid(config) {
if (config == null) {
config = {};
}
this.tools = self.tools;
this._config = object.append(self._defaultConfig, config);
this._initStyles();
}
RenderKid.prototype._initStyles = function() {
return this._styles = new Styles;
};
RenderKid.prototype.style = function() {
return this._styles.setRule.apply(this._styles, arguments);
};
RenderKid.prototype._getStyleFor = function(el) {
return this._styles.getStyleFor(el);
};
RenderKid.prototype.render = function(input, withColors) {
if (withColors == null) {
withColors = true;
}
return this._paint(this._renderDom(this._toDom(input)), withColors);
};
RenderKid.prototype._toDom = function(input) {
if (typeof input === 'string') {
return this._parse(input);
} else if (object.isBareObject(input) || Array.isArray(input)) {
return this._objToDom(input);
} else {
throw Error("Invalid input type. Only strings, arrays and objects are accepted");
}
};
RenderKid.prototype._objToDom = function(o, injectFakeRoot) {
if (injectFakeRoot == null) {
injectFakeRoot = true;
}
if (injectFakeRoot) {
o = {
body: o
};
}
return tools.objectToDom(o);
};
RenderKid.prototype._paint = function(text, withColors) {
var painted;
painted = AnsiPainter.paint(text);
if (withColors) {
return painted;
} else {
return stripAnsi(painted);
}
};
RenderKid.prototype._parse = function(string, injectFakeRoot) {
if (injectFakeRoot == null) {
injectFakeRoot = true;
}
if (injectFakeRoot) {
string = '<body>' + string + '</body>';
}
return tools.stringToDom(string);
};
RenderKid.prototype._renderDom = function(dom) {
var bodyTag, layout, rootBlock;
bodyTag = dom[0];
layout = new Layout(this._config.layout);
rootBlock = layout.getRootBlock();
this._renderBlockNode(bodyTag, null, rootBlock);
return layout.get();
};
RenderKid.prototype._renderChildrenOf = function(parentNode, parentBlock) {
var i, len, node, nodes;
nodes = parentNode.children;
for (i = 0, len = nodes.length; i < len; i++) {
node = nodes[i];
this._renderNode(node, parentNode, parentBlock);
}
};
RenderKid.prototype._renderNode = function(node, parentNode, parentBlock) {
if (node.type === 'text') {
this._renderText(node, parentNode, parentBlock);
} else if (node.name === 'br') {
this._renderBr(node, parentNode, parentBlock);
} else if (this._isBlock(node)) {
this._renderBlockNode(node, parentNode, parentBlock);
} else if (this._isNone(node)) {
return;
} else {
this._renderInlineNode(node, parentNode, parentBlock);
}
};
RenderKid.prototype._renderText = function(node, parentNode, parentBlock) {
var ref, text;
text = node.data;
text = text.replace(/\s+/g, ' ');
if ((parentNode != null ? (ref = parentNode.styles) != null ? ref.display : void 0 : void 0) !== 'inline') {
text = text.trim();
}
if (text.length === 0) {
return;
}
text = text.replace(/&nl;/g, "\n");
return parentBlock.write(text);
};
RenderKid.prototype._renderBlockNode = function(node, parentNode, parentBlock) {
var after, before, block, blockConfig, ref;
ref = blockStyleApplier.applyTo(node, this._getStyleFor(node)), before = ref.before, after = ref.after, blockConfig = ref.blockConfig;
block = parentBlock.openBlock(blockConfig);
if (before !== '') {
block.write(before);
}
this._renderChildrenOf(node, block);
if (after !== '') {
block.write(after);
}
return block.close();
};
RenderKid.prototype._renderInlineNode = function(node, parentNode, parentBlock) {
var after, before, ref;
ref = inlineStyleApplier.applyTo(node, this._getStyleFor(node)), before = ref.before, after = ref.after;
if (before !== '') {
parentBlock.write(before);
}
this._renderChildrenOf(node, parentBlock);
if (after !== '') {
return parentBlock.write(after);
}
};
RenderKid.prototype._renderBr = function(node, parentNode, parentBlock) {
return parentBlock.write("\n");
};
RenderKid.prototype._isBlock = function(node) {
return !(node.type === 'text' || node.name === 'br' || this._getStyleFor(node).display !== 'block');
};
RenderKid.prototype._isNone = function(node) {
return !(node.type === 'text' || node.name === 'br' || this._getStyleFor(node).display !== 'none');
};
return RenderKid;
})();
+68
View File
@@ -0,0 +1,68 @@
// Generated by CoffeeScript 1.9.3
var codes, styles;
module.exports = styles = {};
styles.codes = codes = {
'none': 0,
'black': 30,
'red': 31,
'green': 32,
'yellow': 33,
'blue': 34,
'magenta': 35,
'cyan': 36,
'white': 37,
'grey': 90,
'bright-red': 91,
'bright-green': 92,
'bright-yellow': 93,
'bright-blue': 94,
'bright-magenta': 95,
'bright-cyan': 96,
'bright-white': 97,
'bg-black': 40,
'bg-red': 41,
'bg-green': 42,
'bg-yellow': 43,
'bg-blue': 44,
'bg-magenta': 45,
'bg-cyan': 46,
'bg-white': 47,
'bg-grey': 100,
'bg-bright-red': 101,
'bg-bright-green': 102,
'bg-bright-yellow': 103,
'bg-bright-blue': 104,
'bg-bright-magenta': 105,
'bg-bright-cyan': 106,
'bg-bright-white': 107
};
styles.color = function(str) {
var code;
if (str === 'none') {
return '';
}
code = codes[str];
if (code == null) {
throw Error("Unknown color `" + str + "`");
}
return "\x1b[" + code + "m";
};
styles.bg = function(str) {
var code;
if (str === 'none') {
return '';
}
code = codes['bg-' + str];
if (code == null) {
throw Error("Unknown bg color `" + str + "`");
}
return "\x1B[" + code + "m";
};
styles.none = function(str) {
return "\x1B[" + codes.none + "m";
};
+35
View File
@@ -0,0 +1,35 @@
// Generated by CoffeeScript 1.9.3
var color, colors, i, len, tags;
module.exports = tags = {
'none': {
color: 'none',
bg: 'none'
},
'bg-none': {
color: 'inherit',
bg: 'none'
},
'color-none': {
color: 'none',
bg: 'inherit'
}
};
colors = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'grey', 'bright-red', 'bright-green', 'bright-yellow', 'bright-blue', 'bright-magenta', 'bright-cyan', 'bright-white'];
for (i = 0, len = colors.length; i < len; i++) {
color = colors[i];
tags[color] = {
color: color,
bg: 'inherit'
};
tags["color-" + color] = {
color: color,
bg: 'inherit'
};
tags["bg-" + color] = {
color: 'inherit',
bg: color
};
}
+253
View File
@@ -0,0 +1,253 @@
// Generated by CoffeeScript 1.9.3
var Block, SpecialString, object, terminalWidth;
SpecialString = require('./SpecialString');
object = require('utila').object;
terminalWidth = require('../tools').getCols();
module.exports = Block = (function() {
var self;
self = Block;
Block.defaultConfig = {
blockPrependor: {
fn: require('./block/blockPrependor/Default'),
options: {
amount: 0
}
},
blockAppendor: {
fn: require('./block/blockAppendor/Default'),
options: {
amount: 0
}
},
linePrependor: {
fn: require('./block/linePrependor/Default'),
options: {
amount: 0
}
},
lineAppendor: {
fn: require('./block/lineAppendor/Default'),
options: {
amount: 0
}
},
lineWrapper: {
fn: require('./block/lineWrapper/Default'),
options: {
lineWidth: null
}
},
width: terminalWidth,
prefixRaw: '',
suffixRaw: ''
};
function Block(_layout, _parent, config, _name) {
this._layout = _layout;
this._parent = _parent;
if (config == null) {
config = {};
}
this._name = _name != null ? _name : '';
this._config = object.append(self.defaultConfig, config);
this._closed = false;
this._wasOpenOnce = false;
this._active = false;
this._buffer = '';
this._didSeparateBlock = false;
this._linePrependor = new this._config.linePrependor.fn(this._config.linePrependor.options);
this._lineAppendor = new this._config.lineAppendor.fn(this._config.lineAppendor.options);
this._blockPrependor = new this._config.blockPrependor.fn(this._config.blockPrependor.options);
this._blockAppendor = new this._config.blockAppendor.fn(this._config.blockAppendor.options);
}
Block.prototype._activate = function(deactivateParent) {
if (deactivateParent == null) {
deactivateParent = true;
}
if (this._active) {
throw Error("This block is already active. This is probably a bug in RenderKid itself");
}
if (this._closed) {
throw Error("This block is closed and cannot be activated. This is probably a bug in RenderKid itself");
}
this._active = true;
this._layout._activeBlock = this;
if (deactivateParent) {
if (this._parent != null) {
this._parent._deactivate(false);
}
}
return this;
};
Block.prototype._deactivate = function(activateParent) {
if (activateParent == null) {
activateParent = true;
}
this._ensureActive();
this._flushBuffer();
if (activateParent) {
if (this._parent != null) {
this._parent._activate(false);
}
}
this._active = false;
return this;
};
Block.prototype._ensureActive = function() {
if (!this._wasOpenOnce) {
throw Error("This block has never been open before. This is probably a bug in RenderKid itself.");
}
if (!this._active) {
throw Error("This block is not active. This is probably a bug in RenderKid itself.");
}
if (this._closed) {
throw Error("This block is already closed. This is probably a bug in RenderKid itself.");
}
};
Block.prototype._open = function() {
if (this._wasOpenOnce) {
throw Error("Block._open() has been called twice. This is probably a RenderKid bug.");
}
this._wasOpenOnce = true;
if (this._parent != null) {
this._parent.write(this._whatToPrependToBlock());
}
this._activate();
return this;
};
Block.prototype.close = function() {
this._deactivate();
this._closed = true;
if (this._parent != null) {
this._parent.write(this._whatToAppendToBlock());
}
return this;
};
Block.prototype.isOpen = function() {
return this._wasOpenOnce && !this._closed;
};
Block.prototype.write = function(str) {
this._ensureActive();
if (str === '') {
return;
}
str = String(str);
this._buffer += str;
return this;
};
Block.prototype.openBlock = function(config, name) {
var block;
this._ensureActive();
block = new Block(this._layout, this, config, name);
block._open();
return block;
};
Block.prototype._flushBuffer = function() {
var str;
if (this._buffer === '') {
return;
}
str = this._buffer;
this._buffer = '';
this._writeInline(str);
};
Block.prototype._toPrependToLine = function() {
var fromParent;
fromParent = '';
if (this._parent != null) {
fromParent = this._parent._toPrependToLine();
}
return this._linePrependor.render(fromParent);
};
Block.prototype._toAppendToLine = function() {
var fromParent;
fromParent = '';
if (this._parent != null) {
fromParent = this._parent._toAppendToLine();
}
return this._lineAppendor.render(fromParent);
};
Block.prototype._whatToPrependToBlock = function() {
return this._blockPrependor.render();
};
Block.prototype._whatToAppendToBlock = function() {
return this._blockAppendor.render();
};
Block.prototype._writeInline = function(str) {
var i, j, k, l, lineBreaksToAppend, m, ref, ref1, ref2, remaining;
if (SpecialString(str).isOnlySpecialChars()) {
this._layout._append(str);
return;
}
remaining = str;
lineBreaksToAppend = 0;
if (m = remaining.match(/^\n+/)) {
for (i = j = 1, ref = m[0].length; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) {
this._writeLine('');
}
remaining = remaining.substr(m[0].length, remaining.length);
}
if (m = remaining.match(/\n+$/)) {
lineBreaksToAppend = m[0].length;
remaining = remaining.substr(0, remaining.length - m[0].length);
}
while (remaining.length > 0) {
if (m = remaining.match(/^[^\n]+/)) {
this._writeLine(m[0]);
remaining = remaining.substr(m[0].length, remaining.length);
} else if (m = remaining.match(/^\n+/)) {
for (i = k = 1, ref1 = m[0].length; 1 <= ref1 ? k < ref1 : k > ref1; i = 1 <= ref1 ? ++k : --k) {
this._writeLine('');
}
remaining = remaining.substr(m[0].length, remaining.length);
}
}
if (lineBreaksToAppend > 0) {
for (i = l = 1, ref2 = lineBreaksToAppend; 1 <= ref2 ? l <= ref2 : l >= ref2; i = 1 <= ref2 ? ++l : --l) {
this._writeLine('');
}
}
};
Block.prototype._writeLine = function(str) {
var line, lineContent, lineContentLength, remaining, roomLeft, toAppend, toAppendLength, toPrepend, toPrependLength;
remaining = SpecialString(str);
while (true) {
toPrepend = this._toPrependToLine();
toPrependLength = SpecialString(toPrepend).length;
toAppend = this._toAppendToLine();
toAppendLength = SpecialString(toAppend).length;
roomLeft = this._layout._config.terminalWidth - (toPrependLength + toAppendLength);
lineContentLength = Math.min(this._config.width, roomLeft);
lineContent = remaining.cut(0, lineContentLength, true);
line = toPrepend + lineContent.str + toAppend;
this._layout._appendLine(line);
if (remaining.isEmpty()) {
break;
}
}
};
return Block;
})();
+176
View File
@@ -0,0 +1,176 @@
// Generated by CoffeeScript 1.9.3
var SpecialString, fn, i, len, prop, ref;
module.exports = SpecialString = (function() {
var self;
self = SpecialString;
SpecialString._tabRx = /^\t/;
SpecialString._tagRx = /^<[^>]+>/;
SpecialString._quotedHtmlRx = /^&(gt|lt|quot|amp|apos|sp);/;
function SpecialString(str) {
if (!(this instanceof self)) {
return new self(str);
}
this._str = String(str);
this._len = 0;
}
SpecialString.prototype._getStr = function() {
return this._str;
};
SpecialString.prototype.set = function(str) {
this._str = String(str);
return this;
};
SpecialString.prototype.clone = function() {
return new SpecialString(this._str);
};
SpecialString.prototype.isEmpty = function() {
return this._str === '';
};
SpecialString.prototype.isOnlySpecialChars = function() {
return !this.isEmpty() && this.length === 0;
};
SpecialString.prototype._reset = function() {
return this._len = 0;
};
SpecialString.prototype.splitIn = function(limit, trimLeftEachLine) {
var buffer, bufferLength, justSkippedSkipChar, lines;
if (trimLeftEachLine == null) {
trimLeftEachLine = false;
}
buffer = '';
bufferLength = 0;
lines = [];
justSkippedSkipChar = false;
self._countChars(this._str, function(char, charLength) {
if (bufferLength > limit || bufferLength + charLength > limit) {
lines.push(buffer);
buffer = '';
bufferLength = 0;
}
if (bufferLength === 0 && char === ' ' && !justSkippedSkipChar && trimLeftEachLine) {
return justSkippedSkipChar = true;
} else {
buffer += char;
bufferLength += charLength;
return justSkippedSkipChar = false;
}
});
if (buffer.length > 0) {
lines.push(buffer);
}
return lines;
};
SpecialString.prototype.trim = function() {
return new SpecialString(this.str.trim());
};
SpecialString.prototype.trimLeft = function() {
return new SpecialString(this.str.replace(/^\s+/, ''));
};
SpecialString.prototype.trimRight = function() {
return new SpecialString(this.str.replace(/\s+$/, ''));
};
SpecialString.prototype._getLength = function() {
var sum;
sum = 0;
self._countChars(this._str, function(char, charLength) {
sum += charLength;
});
return sum;
};
SpecialString.prototype.cut = function(from, to, trimLeft) {
var after, before, cur, cut;
if (trimLeft == null) {
trimLeft = false;
}
if (to == null) {
to = this.length;
}
from = parseInt(from);
if (from >= to) {
throw Error("`from` shouldn't be larger than `to`");
}
before = '';
after = '';
cut = '';
cur = 0;
self._countChars(this._str, (function(_this) {
return function(char, charLength) {
if (_this.str === 'ab<tag>') {
console.log(charLength, char);
}
if (cur === from && char.match(/^\s+$/) && trimLeft) {
return;
}
if (cur < from) {
before += char;
} else if (cur < to || cur + charLength <= to) {
cut += char;
} else {
after += char;
}
cur += charLength;
};
})(this));
this._str = before + after;
this._reset();
return SpecialString(cut);
};
SpecialString._countChars = function(text, cb) {
var char, charLength, m;
while (text.length !== 0) {
if (m = text.match(self._tagRx)) {
char = m[0];
charLength = 0;
text = text.substr(char.length, text.length);
} else if (m = text.match(self._quotedHtmlRx)) {
char = m[0];
charLength = 1;
text = text.substr(char.length, text.length);
} else if (text.match(self._tabRx)) {
char = "\t";
charLength = 8;
text = text.substr(1, text.length);
} else {
char = text[0];
charLength = 1;
text = text.substr(1, text.length);
}
cb.call(null, char, charLength);
}
};
return SpecialString;
})();
ref = ['str', 'length'];
fn = function() {
var methodName;
methodName = '_get' + prop[0].toUpperCase() + prop.substr(1, prop.length);
return SpecialString.prototype.__defineGetter__(prop, function() {
return this[methodName]();
});
};
for (i = 0, len = ref.length; i < len; i++) {
prop = ref[i];
fn();
}
+21
View File
@@ -0,0 +1,21 @@
// Generated by CoffeeScript 1.9.3
var DefaultBlockAppendor, tools,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
tools = require('../../../tools');
module.exports = DefaultBlockAppendor = (function(superClass) {
extend(DefaultBlockAppendor, superClass);
function DefaultBlockAppendor() {
return DefaultBlockAppendor.__super__.constructor.apply(this, arguments);
}
DefaultBlockAppendor.prototype._render = function(options) {
return tools.repeatString("\n", this._config.amount);
};
return DefaultBlockAppendor;
})(require('./_BlockAppendor'));
@@ -0,0 +1,15 @@
// Generated by CoffeeScript 1.9.3
var _BlockAppendor;
module.exports = _BlockAppendor = (function() {
function _BlockAppendor(_config) {
this._config = _config;
}
_BlockAppendor.prototype.render = function(options) {
return this._render(options);
};
return _BlockAppendor;
})();
+21
View File
@@ -0,0 +1,21 @@
// Generated by CoffeeScript 1.9.3
var DefaultBlockPrependor, tools,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
tools = require('../../../tools');
module.exports = DefaultBlockPrependor = (function(superClass) {
extend(DefaultBlockPrependor, superClass);
function DefaultBlockPrependor() {
return DefaultBlockPrependor.__super__.constructor.apply(this, arguments);
}
DefaultBlockPrependor.prototype._render = function(options) {
return tools.repeatString("\n", this._config.amount);
};
return DefaultBlockPrependor;
})(require('./_BlockPrependor'));
@@ -0,0 +1,15 @@
// Generated by CoffeeScript 1.9.3
var _BlockPrependor;
module.exports = _BlockPrependor = (function() {
function _BlockPrependor(_config) {
this._config = _config;
}
_BlockPrependor.prototype.render = function(options) {
return this._render(options);
};
return _BlockPrependor;
})();
+21
View File
@@ -0,0 +1,21 @@
// Generated by CoffeeScript 1.9.3
var DefaultLineAppendor, tools,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
tools = require('../../../tools');
module.exports = DefaultLineAppendor = (function(superClass) {
extend(DefaultLineAppendor, superClass);
function DefaultLineAppendor() {
return DefaultLineAppendor.__super__.constructor.apply(this, arguments);
}
DefaultLineAppendor.prototype._render = function(inherited, options) {
return inherited + tools.repeatString(" ", this._config.amount);
};
return DefaultLineAppendor;
})(require('./_LineAppendor'));
+17
View File
@@ -0,0 +1,17 @@
// Generated by CoffeeScript 1.9.3
var _LineAppendor;
module.exports = _LineAppendor = (function() {
function _LineAppendor(_config) {
this._config = _config;
this._lineNo = 0;
}
_LineAppendor.prototype.render = function(inherited, options) {
this._lineNo++;
return '<none>' + this._render(inherited, options) + '</none>';
};
return _LineAppendor;
})();
+58
View File
@@ -0,0 +1,58 @@
// Generated by CoffeeScript 1.9.3
var DefaultLinePrependor, SpecialString, tools,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
tools = require('../../../tools');
SpecialString = require('../../SpecialString');
module.exports = DefaultLinePrependor = (function(superClass) {
var self;
extend(DefaultLinePrependor, superClass);
function DefaultLinePrependor() {
return DefaultLinePrependor.__super__.constructor.apply(this, arguments);
}
self = DefaultLinePrependor;
DefaultLinePrependor.pad = function(howMuch) {
return tools.repeatString(" ", howMuch);
};
DefaultLinePrependor.prototype._render = function(inherited, options) {
var addToLeft, addToRight, alignment, bullet, char, charLen, diff, left, output, space, toWrite;
if (this._lineNo === 0 && (bullet = this._config.bullet)) {
char = bullet.char;
charLen = SpecialString(char).length;
alignment = bullet.alignment;
space = this._config.amount;
toWrite = char;
addToLeft = '';
addToRight = '';
if (space > charLen) {
diff = space - charLen;
if (alignment === 'right') {
addToLeft = self.pad(diff);
} else if (alignment === 'left') {
addToRight = self.pad(diff);
} else if (alignment === 'center') {
left = Math.round(diff / 2);
addToLeft = self.pad(left);
addToRight = self.pad(diff - left);
} else {
throw Error("Unknown alignment `" + alignment + "`");
}
}
output = addToLeft + char + addToRight;
} else {
output = self.pad(this._config.amount);
}
return inherited + output;
};
return DefaultLinePrependor;
})(require('./_LinePrependor'));
@@ -0,0 +1,17 @@
// Generated by CoffeeScript 1.9.3
var _LinePrependor;
module.exports = _LinePrependor = (function() {
function _LinePrependor(_config) {
this._config = _config;
this._lineNo = -1;
}
_LinePrependor.prototype.render = function(inherited, options) {
this._lineNo++;
return '<none>' + this._render(inherited, options) + '</none>';
};
return _LinePrependor;
})();
+17
View File
@@ -0,0 +1,17 @@
// Generated by CoffeeScript 1.9.3
var DefaultLineWrapper,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
module.exports = DefaultLineWrapper = (function(superClass) {
extend(DefaultLineWrapper, superClass);
function DefaultLineWrapper() {
return DefaultLineWrapper.__super__.constructor.apply(this, arguments);
}
DefaultLineWrapper.prototype._render = function() {};
return DefaultLineWrapper;
})(require('./_LineWrapper'));
+13
View File
@@ -0,0 +1,13 @@
// Generated by CoffeeScript 1.9.3
var _LineWrapper;
module.exports = _LineWrapper = (function() {
function _LineWrapper() {}
_LineWrapper.prototype.render = function(str, options) {
return this._render(str, options);
};
return _LineWrapper;
})();
+76
View File
@@ -0,0 +1,76 @@
// Generated by CoffeeScript 1.9.3
var MixedDeclarationSet, StyleSheet, Styles, terminalWidth;
StyleSheet = require('./styles/StyleSheet');
MixedDeclarationSet = require('./styles/rule/MixedDeclarationSet');
terminalWidth = require('../tools').getCols();
module.exports = Styles = (function() {
var self;
self = Styles;
Styles.defaultRules = {
'*': {
display: 'inline'
},
'body': {
background: 'none',
color: 'white',
display: 'block',
width: terminalWidth + ' !important'
}
};
function Styles() {
this._defaultStyles = new StyleSheet;
this._userStyles = new StyleSheet;
this._setDefaultStyles();
}
Styles.prototype._setDefaultStyles = function() {
this._defaultStyles.setRule(self.defaultRules);
};
Styles.prototype.setRule = function(selector, rules) {
this._userStyles.setRule.apply(this._userStyles, arguments);
return this;
};
Styles.prototype.getStyleFor = function(el) {
var styles;
styles = el.styles;
if (styles == null) {
el.styles = styles = this._getComputedStyleFor(el);
}
return styles;
};
Styles.prototype._getRawStyleFor = function(el) {
var def, user;
def = this._defaultStyles.getRulesFor(el);
user = this._userStyles.getRulesFor(el);
return MixedDeclarationSet.mix(def, user).toObject();
};
Styles.prototype._getComputedStyleFor = function(el) {
var decs, parent, prop, ref, val;
decs = {};
parent = el.parent;
ref = this._getRawStyleFor(el);
for (prop in ref) {
val = ref[prop];
if (val !== 'inherit') {
decs[prop] = val;
} else {
throw Error("Inherited styles are not supported yet.");
}
}
return decs;
};
return Styles;
})();
+35
View File
@@ -0,0 +1,35 @@
// Generated by CoffeeScript 1.9.3
var AnsiPainter, _common;
AnsiPainter = require('../../AnsiPainter');
module.exports = _common = {
getStyleTagsFor: function(style) {
var i, len, ret, tag, tagName, tagsToAdd;
tagsToAdd = [];
if (style.color != null) {
tagName = 'color-' + style.color;
if (AnsiPainter.tags[tagName] == null) {
throw Error("Unknown color `" + style.color + "`");
}
tagsToAdd.push(tagName);
}
if (style.background != null) {
tagName = 'bg-' + style.background;
if (AnsiPainter.tags[tagName] == null) {
throw Error("Unknown background `" + style.background + "`");
}
tagsToAdd.push(tagName);
}
ret = {
before: '',
after: ''
};
for (i = 0, len = tagsToAdd.length; i < len; i++) {
tag = tagsToAdd[i];
ret.before = ("<" + tag + ">") + ret.before;
ret.after = ret.after + ("</" + tag + ">");
}
return ret;
}
};
+83
View File
@@ -0,0 +1,83 @@
// Generated by CoffeeScript 1.9.3
var _common, blockStyleApplier, object, self;
_common = require('./_common');
object = require('utila').object;
module.exports = blockStyleApplier = self = {
applyTo: function(el, style) {
var config, ret;
ret = _common.getStyleTagsFor(style);
ret.blockConfig = config = {};
this._margins(style, config);
this._bullet(style, config);
this._dims(style, config);
return ret;
},
_margins: function(style, config) {
if (style.marginLeft != null) {
object.appendOnto(config, {
linePrependor: {
options: {
amount: parseInt(style.marginLeft)
}
}
});
}
if (style.marginRight != null) {
object.appendOnto(config, {
lineAppendor: {
options: {
amount: parseInt(style.marginRight)
}
}
});
}
if (style.marginTop != null) {
object.appendOnto(config, {
blockPrependor: {
options: {
amount: parseInt(style.marginTop)
}
}
});
}
if (style.marginBottom != null) {
object.appendOnto(config, {
blockAppendor: {
options: {
amount: parseInt(style.marginBottom)
}
}
});
}
},
_bullet: function(style, config) {
var after, before, bullet, conf, ref;
if ((style.bullet != null) && style.bullet.enabled) {
bullet = style.bullet;
conf = {};
conf.alignment = style.bullet.alignment;
ref = _common.getStyleTagsFor({
color: bullet.color,
background: bullet.background
}), before = ref.before, after = ref.after;
conf.char = before + bullet.char + after;
object.appendOnto(config, {
linePrependor: {
options: {
bullet: conf
}
}
});
}
},
_dims: function(style, config) {
var w;
if (style.width != null) {
w = parseInt(style.width);
config.width = w;
}
}
};
+26
View File
@@ -0,0 +1,26 @@
// Generated by CoffeeScript 1.9.3
var _common, inlineStyleApplier, self, tools;
tools = require('../../tools');
_common = require('./_common');
module.exports = inlineStyleApplier = self = {
applyTo: function(el, style) {
var ret;
ret = _common.getStyleTagsFor(style);
if (style.marginLeft != null) {
ret.before = (tools.repeatString("&sp;", parseInt(style.marginLeft))) + ret.before;
}
if (style.marginRight != null) {
ret.after += tools.repeatString("&sp;", parseInt(style.marginRight));
}
if (style.paddingLeft != null) {
ret.before += tools.repeatString("&sp;", parseInt(style.paddingLeft));
}
if (style.paddingRight != null) {
ret.after = (tools.repeatString("&sp;", parseInt(style.paddingRight))) + ret.after;
}
return ret;
}
};
+21
View File
@@ -0,0 +1,21 @@
// Generated by CoffeeScript 1.9.3
var DeclarationBlock, Rule, Selector;
Selector = require('./rule/Selector');
DeclarationBlock = require('./rule/DeclarationBlock');
module.exports = Rule = (function() {
function Rule(selector) {
this.selector = new Selector(selector);
this.styles = new DeclarationBlock;
}
Rule.prototype.setStyles = function(styles) {
this.styles.set(styles);
return this;
};
return Rule;
})();
+72
View File
@@ -0,0 +1,72 @@
// Generated by CoffeeScript 1.9.3
var Rule, StyleSheet;
Rule = require('./Rule');
module.exports = StyleSheet = (function() {
var self;
self = StyleSheet;
function StyleSheet() {
this._rulesBySelector = {};
}
StyleSheet.prototype.setRule = function(selector, styles) {
var key, val;
if (typeof selector === 'string') {
this._setRule(selector, styles);
} else if (typeof selector === 'object') {
for (key in selector) {
val = selector[key];
this._setRule(key, val);
}
}
return this;
};
StyleSheet.prototype._setRule = function(s, styles) {
var i, len, ref, selector;
ref = self.splitSelectors(s);
for (i = 0, len = ref.length; i < len; i++) {
selector = ref[i];
this._setSingleRule(selector, styles);
}
return this;
};
StyleSheet.prototype._setSingleRule = function(s, styles) {
var rule, selector;
selector = self.normalizeSelector(s);
if (!(rule = this._rulesBySelector[selector])) {
rule = new Rule(selector);
this._rulesBySelector[selector] = rule;
}
rule.setStyles(styles);
return this;
};
StyleSheet.prototype.getRulesFor = function(el) {
var ref, rule, rules, selector;
rules = [];
ref = this._rulesBySelector;
for (selector in ref) {
rule = ref[selector];
if (rule.selector.matches(el)) {
rules.push(rule);
}
}
return rules;
};
StyleSheet.normalizeSelector = function(selector) {
return selector.replace(/[\s]+/g, ' ').replace(/[\s]*([>\,\+]{1})[\s]*/g, '$1').trim();
};
StyleSheet.splitSelectors = function(s) {
return s.trim().split(',');
};
return StyleSheet;
})();
+65
View File
@@ -0,0 +1,65 @@
// Generated by CoffeeScript 1.9.3
var Arbitrary, DeclarationBlock, declarationClasses;
module.exports = DeclarationBlock = (function() {
var self;
self = DeclarationBlock;
function DeclarationBlock() {
this._declarations = {};
}
DeclarationBlock.prototype.set = function(prop, value) {
var key, val;
if (typeof prop === 'object') {
for (key in prop) {
val = prop[key];
this.set(key, val);
}
return this;
}
prop = self.sanitizeProp(prop);
this._getDeclarationClass(prop).setOnto(this._declarations, prop, value);
return this;
};
DeclarationBlock.prototype._getDeclarationClass = function(prop) {
var cls;
if (prop[0] === '_') {
return Arbitrary;
}
if (!(cls = declarationClasses[prop])) {
throw Error("Unknown property `" + prop + "`. Write it as `_" + prop + "` if you're defining a custom property");
}
return cls;
};
DeclarationBlock.sanitizeProp = function(prop) {
return String(prop).trim();
};
return DeclarationBlock;
})();
Arbitrary = require('./declarationBlock/Arbitrary');
declarationClasses = {
color: require('./declarationBlock/Color'),
background: require('./declarationBlock/Background'),
width: require('./declarationBlock/Width'),
height: require('./declarationBlock/Height'),
bullet: require('./declarationBlock/Bullet'),
display: require('./declarationBlock/Display'),
margin: require('./declarationBlock/Margin'),
marginTop: require('./declarationBlock/MarginTop'),
marginLeft: require('./declarationBlock/MarginLeft'),
marginRight: require('./declarationBlock/MarginRight'),
marginBottom: require('./declarationBlock/MarginBottom'),
padding: require('./declarationBlock/Padding'),
paddingTop: require('./declarationBlock/PaddingTop'),
paddingLeft: require('./declarationBlock/PaddingLeft'),
paddingRight: require('./declarationBlock/PaddingRight'),
paddingBottom: require('./declarationBlock/PaddingBottom')
};
@@ -0,0 +1,78 @@
// Generated by CoffeeScript 1.9.3
var MixedDeclarationSet,
slice = [].slice;
module.exports = MixedDeclarationSet = (function() {
var self;
self = MixedDeclarationSet;
MixedDeclarationSet.mix = function() {
var i, len, mixed, ruleSets, rules;
ruleSets = 1 <= arguments.length ? slice.call(arguments, 0) : [];
mixed = new self;
for (i = 0, len = ruleSets.length; i < len; i++) {
rules = ruleSets[i];
mixed.mixWithList(rules);
}
return mixed;
};
function MixedDeclarationSet() {
this._declarations = {};
}
MixedDeclarationSet.prototype.mixWithList = function(rules) {
var i, len, rule;
rules.sort(function(a, b) {
return a.selector.priority > b.selector.priority;
});
for (i = 0, len = rules.length; i < len; i++) {
rule = rules[i];
this._mixWithRule(rule);
}
return this;
};
MixedDeclarationSet.prototype._mixWithRule = function(rule) {
var dec, prop, ref;
ref = rule.styles._declarations;
for (prop in ref) {
dec = ref[prop];
this._mixWithDeclaration(dec);
}
};
MixedDeclarationSet.prototype._mixWithDeclaration = function(dec) {
var cur;
cur = this._declarations[dec.prop];
if ((cur != null) && cur.important && !dec.important) {
return;
}
this._declarations[dec.prop] = dec;
};
MixedDeclarationSet.prototype.get = function(prop) {
if (prop == null) {
return this._declarations;
}
if (this._declarations[prop] == null) {
return null;
}
return this._declarations[prop].val;
};
MixedDeclarationSet.prototype.toObject = function() {
var dec, obj, prop, ref;
obj = {};
ref = this._declarations;
for (prop in ref) {
dec = ref[prop];
obj[prop] = dec.val;
}
return obj;
};
return MixedDeclarationSet;
})();
+38
View File
@@ -0,0 +1,38 @@
// Generated by CoffeeScript 1.9.3
var CSSSelect, Selector;
CSSSelect = require('css-select');
module.exports = Selector = (function() {
var self;
self = Selector;
function Selector(text1) {
this.text = text1;
this._fn = CSSSelect.compile(this.text);
this.priority = self.calculatePriority(this.text);
}
Selector.prototype.matches = function(elem) {
return CSSSelect.is(elem, this._fn);
};
Selector.calculatePriority = function(text) {
var n, priotrity;
priotrity = 0;
if (n = text.match(/[\#]{1}/g)) {
priotrity += 100 * n.length;
}
if (n = text.match(/[a-zA-Z]+/g)) {
priotrity += 2 * n.length;
}
if (n = text.match(/\*/g)) {
priotrity += 1 * n.length;
}
return priotrity;
};
return Selector;
})();
@@ -0,0 +1,17 @@
// Generated by CoffeeScript 1.9.3
var Arbitrary, _Declaration,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
_Declaration = require('./_Declaration');
module.exports = Arbitrary = (function(superClass) {
extend(Arbitrary, superClass);
function Arbitrary() {
return Arbitrary.__super__.constructor.apply(this, arguments);
}
return Arbitrary;
})(_Declaration);
@@ -0,0 +1,17 @@
// Generated by CoffeeScript 1.9.3
var Background, _Declaration,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
_Declaration = require('./_Declaration');
module.exports = Background = (function(superClass) {
extend(Background, superClass);
function Background() {
return Background.__super__.constructor.apply(this, arguments);
}
return Background;
})(_Declaration);
@@ -0,0 +1,63 @@
// Generated by CoffeeScript 1.9.3
var Bullet, _Declaration,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
_Declaration = require('./_Declaration');
module.exports = Bullet = (function(superClass) {
var self;
extend(Bullet, superClass);
function Bullet() {
return Bullet.__super__.constructor.apply(this, arguments);
}
self = Bullet;
Bullet.prototype._set = function(val) {
var alignment, bg, char, color, enabled, m, original;
val = String(val);
original = val;
char = null;
enabled = false;
color = 'none';
bg = 'none';
if (m = val.match(/\"([^"]+)\"/) || (m = val.match(/\'([^']+)\'/))) {
char = m[1];
val = val.replace(m[0], '');
enabled = true;
}
if (m = val.match(/(none|left|right|center)/)) {
alignment = m[1];
val = val.replace(m[0], '');
} else {
alignment = 'left';
}
if (alignment === 'none') {
enabled = false;
}
if (m = val.match(/color\:([\w\-]+)/)) {
color = m[1];
val = val.replace(m[0], '');
}
if (m = val.match(/bg\:([\w\-]+)/)) {
bg = m[1];
val = val.replace(m[0], '');
}
if (val.trim() !== '') {
throw Error("Unrecognizable value `" + original + "` for `" + this.prop + "`");
}
return this.val = {
enabled: enabled,
char: char,
alignment: alignment,
background: bg,
color: color
};
};
return Bullet;
})(_Declaration);
@@ -0,0 +1,17 @@
// Generated by CoffeeScript 1.9.3
var Color, _Declaration,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
_Declaration = require('./_Declaration');
module.exports = Color = (function(superClass) {
extend(Color, superClass);
function Color() {
return Color.__super__.constructor.apply(this, arguments);
}
return Color;
})(_Declaration);
@@ -0,0 +1,32 @@
// Generated by CoffeeScript 1.9.3
var Display, _Declaration,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty,
indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
_Declaration = require('./_Declaration');
module.exports = Display = (function(superClass) {
var self;
extend(Display, superClass);
function Display() {
return Display.__super__.constructor.apply(this, arguments);
}
self = Display;
Display._allowed = ['inline', 'block', 'none'];
Display.prototype._set = function(val) {
val = String(val).toLowerCase();
if (indexOf.call(self._allowed, val) < 0) {
throw Error("Unrecognizable value `" + val + "` for `" + this.prop + "`");
}
return this.val = val;
};
return Display;
})(_Declaration);
@@ -0,0 +1,17 @@
// Generated by CoffeeScript 1.9.3
var Height, _Length,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
_Length = require('./_Length');
module.exports = Height = (function(superClass) {
extend(Height, superClass);
function Height() {
return Height.__super__.constructor.apply(this, arguments);
}
return Height;
})(_Length);
@@ -0,0 +1,64 @@
// Generated by CoffeeScript 1.9.3
var Margin, MarginBottom, MarginLeft, MarginRight, MarginTop, _Declaration,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
_Declaration = require('./_Declaration');
MarginTop = require('./MarginTop');
MarginLeft = require('./MarginLeft');
MarginRight = require('./MarginRight');
MarginBottom = require('./MarginBottom');
module.exports = Margin = (function(superClass) {
var self;
extend(Margin, superClass);
function Margin() {
return Margin.__super__.constructor.apply(this, arguments);
}
self = Margin;
Margin.setOnto = function(declarations, prop, originalValue) {
var append, val, vals;
append = '';
val = _Declaration.sanitizeValue(originalValue);
if (_Declaration.importantClauseRx.test(String(val))) {
append = ' !important';
val = val.replace(_Declaration.importantClauseRx, '');
}
val = val.trim();
if (val.length === 0) {
return self._setAllDirections(declarations, append, append, append, append);
}
vals = val.split(" ").map(function(val) {
return val + append;
});
if (vals.length === 1) {
return self._setAllDirections(declarations, vals[0], vals[0], vals[0], vals[0]);
} else if (vals.length === 2) {
return self._setAllDirections(declarations, vals[0], vals[1], vals[0], vals[1]);
} else if (vals.length === 3) {
return self._setAllDirections(declarations, vals[0], vals[1], vals[2], vals[1]);
} else if (vals.length === 4) {
return self._setAllDirections(declarations, vals[0], vals[1], vals[2], vals[3]);
} else {
throw Error("Can't understand value for margin: `" + originalValue + "`");
}
};
Margin._setAllDirections = function(declarations, top, right, bottom, left) {
MarginTop.setOnto(declarations, 'marginTop', top);
MarginTop.setOnto(declarations, 'marginRight', right);
MarginTop.setOnto(declarations, 'marginBottom', bottom);
MarginTop.setOnto(declarations, 'marginLeft', left);
};
return Margin;
})(_Declaration);
@@ -0,0 +1,17 @@
// Generated by CoffeeScript 1.9.3
var MarginBottom, _Length,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
_Length = require('./_Length');
module.exports = MarginBottom = (function(superClass) {
extend(MarginBottom, superClass);
function MarginBottom() {
return MarginBottom.__super__.constructor.apply(this, arguments);
}
return MarginBottom;
})(_Length);
@@ -0,0 +1,17 @@
// Generated by CoffeeScript 1.9.3
var MarginLeft, _Length,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
_Length = require('./_Length');
module.exports = MarginLeft = (function(superClass) {
extend(MarginLeft, superClass);
function MarginLeft() {
return MarginLeft.__super__.constructor.apply(this, arguments);
}
return MarginLeft;
})(_Length);
@@ -0,0 +1,17 @@
// Generated by CoffeeScript 1.9.3
var MarginRight, _Length,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
_Length = require('./_Length');
module.exports = MarginRight = (function(superClass) {
extend(MarginRight, superClass);
function MarginRight() {
return MarginRight.__super__.constructor.apply(this, arguments);
}
return MarginRight;
})(_Length);
@@ -0,0 +1,17 @@
// Generated by CoffeeScript 1.9.3
var MarginTop, _Length,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
_Length = require('./_Length');
module.exports = MarginTop = (function(superClass) {
extend(MarginTop, superClass);
function MarginTop() {
return MarginTop.__super__.constructor.apply(this, arguments);
}
return MarginTop;
})(_Length);
@@ -0,0 +1,64 @@
// Generated by CoffeeScript 1.9.3
var Padding, PaddingBottom, PaddingLeft, PaddingRight, PaddingTop, _Declaration,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
_Declaration = require('./_Declaration');
PaddingTop = require('./PaddingTop');
PaddingLeft = require('./PaddingLeft');
PaddingRight = require('./PaddingRight');
PaddingBottom = require('./PaddingBottom');
module.exports = Padding = (function(superClass) {
var self;
extend(Padding, superClass);
function Padding() {
return Padding.__super__.constructor.apply(this, arguments);
}
self = Padding;
Padding.setOnto = function(declarations, prop, originalValue) {
var append, val, vals;
append = '';
val = _Declaration.sanitizeValue(originalValue);
if (_Declaration.importantClauseRx.test(String(val))) {
append = ' !important';
val = val.replace(_Declaration.importantClauseRx, '');
}
val = val.trim();
if (val.length === 0) {
return self._setAllDirections(declarations, append, append, append, append);
}
vals = val.split(" ").map(function(val) {
return val + append;
});
if (vals.length === 1) {
return self._setAllDirections(declarations, vals[0], vals[0], vals[0], vals[0]);
} else if (vals.length === 2) {
return self._setAllDirections(declarations, vals[0], vals[1], vals[0], vals[1]);
} else if (vals.length === 3) {
return self._setAllDirections(declarations, vals[0], vals[1], vals[2], vals[1]);
} else if (vals.length === 4) {
return self._setAllDirections(declarations, vals[0], vals[1], vals[2], vals[3]);
} else {
throw Error("Can't understand value for padding: `" + originalValue + "`");
}
};
Padding._setAllDirections = function(declarations, top, right, bottom, left) {
PaddingTop.setOnto(declarations, 'paddingTop', top);
PaddingTop.setOnto(declarations, 'paddingRight', right);
PaddingTop.setOnto(declarations, 'paddingBottom', bottom);
PaddingTop.setOnto(declarations, 'paddingLeft', left);
};
return Padding;
})(_Declaration);
@@ -0,0 +1,17 @@
// Generated by CoffeeScript 1.9.3
var PaddingBottom, _Length,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
_Length = require('./_Length');
module.exports = PaddingBottom = (function(superClass) {
extend(PaddingBottom, superClass);
function PaddingBottom() {
return PaddingBottom.__super__.constructor.apply(this, arguments);
}
return PaddingBottom;
})(_Length);
@@ -0,0 +1,17 @@
// Generated by CoffeeScript 1.9.3
var PaddingLeft, _Length,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
_Length = require('./_Length');
module.exports = PaddingLeft = (function(superClass) {
extend(PaddingLeft, superClass);
function PaddingLeft() {
return PaddingLeft.__super__.constructor.apply(this, arguments);
}
return PaddingLeft;
})(_Length);
@@ -0,0 +1,17 @@
// Generated by CoffeeScript 1.9.3
var PaddingRight, _Length,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
_Length = require('./_Length');
module.exports = PaddingRight = (function(superClass) {
extend(PaddingRight, superClass);
function PaddingRight() {
return PaddingRight.__super__.constructor.apply(this, arguments);
}
return PaddingRight;
})(_Length);
@@ -0,0 +1,17 @@
// Generated by CoffeeScript 1.9.3
var PaddingTop, _Length,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
_Length = require('./_Length');
module.exports = PaddingTop = (function(superClass) {
extend(PaddingTop, superClass);
function PaddingTop() {
return PaddingTop.__super__.constructor.apply(this, arguments);
}
return PaddingTop;
})(_Length);
@@ -0,0 +1,17 @@
// Generated by CoffeeScript 1.9.3
var Width, _Length,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
_Length = require('./_Length');
module.exports = Width = (function(superClass) {
extend(Width, superClass);
function Width() {
return Width.__super__.constructor.apply(this, arguments);
}
return Width;
})(_Length);
@@ -0,0 +1,84 @@
// Generated by CoffeeScript 1.9.3
var _Declaration;
module.exports = _Declaration = (function() {
var self;
self = _Declaration;
_Declaration.importantClauseRx = /(\s\!important)$/;
_Declaration.setOnto = function(declarations, prop, val) {
var dec;
if (!(dec = declarations[prop])) {
return declarations[prop] = new this(prop, val);
} else {
return dec.set(val);
}
};
_Declaration.sanitizeValue = function(val) {
return String(val).trim().replace(/[\s]+/g, ' ');
};
_Declaration.inheritAllowed = false;
function _Declaration(prop1, val) {
this.prop = prop1;
this.important = false;
this.set(val);
}
_Declaration.prototype.get = function() {
return this._get();
};
_Declaration.prototype._get = function() {
return this.val;
};
_Declaration.prototype._pickImportantClause = function(val) {
if (self.importantClauseRx.test(String(val))) {
this.important = true;
return val.replace(self.importantClauseRx, '');
} else {
this.important = false;
return val;
}
};
_Declaration.prototype.set = function(val) {
val = self.sanitizeValue(val);
val = this._pickImportantClause(val);
val = val.trim();
if (this._handleNullOrInherit(val)) {
return this;
}
this._set(val);
return this;
};
_Declaration.prototype._set = function(val) {
return this.val = val;
};
_Declaration.prototype._handleNullOrInherit = function(val) {
if (val === '') {
this.val = '';
return true;
}
if (val === 'inherit') {
if (this.constructor.inheritAllowed) {
this.val = 'inherit';
} else {
throw Error("Inherit is not allowed for `" + this.prop + "`");
}
return true;
} else {
return false;
}
};
return _Declaration;
})();
@@ -0,0 +1,24 @@
// Generated by CoffeeScript 1.9.3
var _Declaration, _Length,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
_Declaration = require('./_Declaration');
module.exports = _Length = (function(superClass) {
extend(_Length, superClass);
function _Length() {
return _Length.__super__.constructor.apply(this, arguments);
}
_Length.prototype._set = function(val) {
if (!/^[0-9]+$/.test(String(val))) {
throw Error("`" + this.prop + "` only takes an integer for value");
}
return this.val = parseInt(val);
};
return _Length;
})(_Declaration);
+88
View File
@@ -0,0 +1,88 @@
// Generated by CoffeeScript 1.9.3
var htmlparser, object, objectToDom, self;
htmlparser = require('htmlparser2');
object = require('utila').object;
objectToDom = require('dom-converter').objectToDom;
module.exports = self = {
repeatString: function(str, times) {
var i, j, output, ref;
output = '';
for (i = j = 0, ref = times; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
output += str;
}
return output;
},
toDom: function(subject) {
if (typeof subject === 'string') {
return self.stringToDom(subject);
} else if (object.isBareObject(subject)) {
return self._objectToDom(subject);
} else {
throw Error("tools.toDom() only supports strings and objects");
}
},
stringToDom: function(string) {
var handler, parser;
handler = new htmlparser.DomHandler;
parser = new htmlparser.Parser(handler);
parser.write(string);
parser.end();
return handler.dom;
},
_fixQuotesInDom: function(input) {
var j, len, node;
if (Array.isArray(input)) {
for (j = 0, len = input.length; j < len; j++) {
node = input[j];
self._fixQuotesInDom(node);
}
return input;
}
node = input;
if (node.type === 'text') {
return node.data = self._quoteNodeText(node.data);
} else {
return self._fixQuotesInDom(node.children);
}
},
objectToDom: function(o) {
if (!Array.isArray(o)) {
if (!object.isBareObject(o)) {
throw Error("objectToDom() only accepts a bare object or an array");
}
}
return self._fixQuotesInDom(objectToDom(o));
},
quote: function(str) {
return String(str).replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/\ /g, '&sp;').replace(/\n/g, '<br />');
},
_quoteNodeText: function(text) {
return String(text).replace(/\&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/\ /g, '&sp;').replace(/\n/g, "&nl;");
},
getCols: function() {
var cols, tty;
tty = require('tty');
cols = (function() {
try {
if (tty.isatty(1) && tty.isatty(2)) {
if (process.stdout.getWindowSize) {
return process.stdout.getWindowSize(1)[0];
} else if (tty.getWindowSize) {
return tty.getWindowSize()[1];
} else if (process.stdout.columns) {
return process.stdout.columns;
}
}
} catch (_error) {}
})();
if (typeof cols === 'number' && cols > 30) {
return cols;
} else {
return 80;
}
}
};
+4
View File
@@ -0,0 +1,4 @@
'use strict';
module.exports = function () {
return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g;
};
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+108
View File
@@ -0,0 +1,108 @@
{
"_from": "ansi-regex@^2.0.0",
"_id": "ansi-regex@2.1.1",
"_inBundle": false,
"_integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=",
"_location": "/renderkid/ansi-regex",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "ansi-regex@^2.0.0",
"name": "ansi-regex",
"escapedName": "ansi-regex",
"rawSpec": "^2.0.0",
"saveSpec": null,
"fetchSpec": "^2.0.0"
},
"_requiredBy": [
"/renderkid/strip-ansi"
],
"_resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz",
"_shasum": "c3b33ab5ee360d86e0e628f0468ae7ef27d654df",
"_spec": "ansi-regex@^2.0.0",
"_where": "/home/george/citwa/red_de_investigacion_front/first/node_modules/renderkid/node_modules/strip-ansi",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/chalk/ansi-regex/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Regular expression for matching ANSI escape codes",
"devDependencies": {
"ava": "0.17.0",
"xo": "0.16.0"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/chalk/ansi-regex#readme",
"keywords": [
"ansi",
"styles",
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"tty",
"escape",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"command-line",
"text",
"regex",
"regexp",
"re",
"match",
"test",
"find",
"pattern"
],
"license": "MIT",
"maintainers": [
{
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
{
"name": "Joshua Appelman",
"email": "jappelman@xebia.com",
"url": "jbnicolai.com"
},
{
"name": "JD Ballard",
"email": "i.am.qix@gmail.com",
"url": "github.com/qix-"
}
],
"name": "ansi-regex",
"repository": {
"type": "git",
"url": "git+https://github.com/chalk/ansi-regex.git"
},
"scripts": {
"test": "xo && ava --verbose",
"view-supported": "node fixtures/view-codes.js"
},
"version": "2.1.1",
"xo": {
"rules": {
"guard-for-in": 0,
"no-loop-func": 0
}
}
}
+39
View File
@@ -0,0 +1,39 @@
# ansi-regex [![Build Status](https://travis-ci.org/chalk/ansi-regex.svg?branch=master)](https://travis-ci.org/chalk/ansi-regex)
> Regular expression for matching [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code)
## Install
```
$ npm install --save ansi-regex
```
## Usage
```js
const ansiRegex = require('ansi-regex');
ansiRegex().test('\u001b[4mcake\u001b[0m');
//=> true
ansiRegex().test('cake');
//=> false
'\u001b[4mcake\u001b[0m'.match(ansiRegex());
//=> ['\u001b[4m', '\u001b[0m']
```
## FAQ
### Why do you test for codes not in the ECMA 48 standard?
Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. If I recall correctly, we test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them.
On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out.
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)
+11
View File
@@ -0,0 +1,11 @@
Copyright (c) Felix Böhm
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+133
View File
@@ -0,0 +1,133 @@
# css-select [![NPM version](http://img.shields.io/npm/v/css-select.svg)](https://npmjs.org/package/css-select) [![Build Status](https://travis-ci.org/fb55/css-select.svg?branch=master)](http://travis-ci.org/fb55/css-select) [![Downloads](https://img.shields.io/npm/dm/css-select.svg)](https://npmjs.org/package/css-select) [![Coverage](https://coveralls.io/repos/fb55/css-select/badge.svg?branch=master)](https://coveralls.io/r/fb55/css-select)
a CSS selector compiler/engine
## What?
css-select turns CSS selectors into functions that tests if elements match them. When searching for elements, testing is executed "from the top", similar to how browsers execute CSS selectors.
In its default configuration, css-select queries the DOM structure of the [`domhandler`](https://github.com/fb55/domhandler) module (also known as htmlparser2 DOM).
__Features:__
- Full implementation of CSS3 selectors
- Partial implementation of jQuery/Sizzle extensions
- Very high test coverage
- Pretty good performance
## Why?
The traditional approach of executing CSS selectors, named left-to-right execution, is to execute every component of the selector in order, from left to right _(duh)_. The execution of the selector `a b` for example will first query for `a` elements, then search these for `b` elements. (That's the approach of eg. [`Sizzle`](https://github.com/jquery/sizzle), [`nwmatcher`](https://github.com/dperini/nwmatcher/) and [`qwery`](https://github.com/ded/qwery).)
While this works, it has some downsides: Children of `a`s will be checked multiple times; first, to check if they are also `a`s, then, for every superior `a` once, if they are `b`s. Using [Big O notation](http://en.wikipedia.org/wiki/Big_O_notation), that would be `O(n^(k+1))`, where `k` is the number of descendant selectors (that's the space in the example above).
The far more efficient approach is to first look for `b` elements, then check if they have superior `a` elements: Using big O notation again, that would be `O(n)`. That's called right-to-left execution.
And that's what css-select does and why it's quite performant.
## How does it work?
By building a stack of functions.
_Wait, what?_
Okay, so let's suppose we want to compile the selector `a b` again, for right-to-left execution. We start by _parsing_ the selector, which means we turn the selector into an array of the building-blocks of the selector, so we can distinguish them easily. That's what the [`css-what`](https://github.com/fb55/css-what) module is for, if you want to have a look.
Anyway, after parsing, we end up with an array like this one:
```js
[
{ type: 'tag', name: 'a' },
{ type: 'descendant' },
{ type: 'tag', name: 'b' }
]
```
Actually, this array is wrapped in another array, but that's another story (involving commas in selectors).
Now that we know the meaning of every part of the selector, we can compile it. That's where it becomes interesting.
The basic idea is to turn every part of the selector into a function, which takes an element as its only argument. The function checks whether a passed element matches its part of the selector: If it does, the element is passed to the next turned-into-a-function part of the selector, which does the same. If an element is accepted by all parts of the selector, it _matches_ the selector and double rainbow ALL THE WAY.
As said before, we want to do right-to-left execution with all the big O improvements nonsense, so elements are passed from the rightmost part of the selector (`b` in our example) to the leftmost (~~which would be `c`~~ of course `a`).
_//TODO: More in-depth description. Implementation details. Build a spaceship._
## API
```js
var CSSselect = require("css-select");
```
#### `CSSselect(query, elems, options)`
Queries `elems`, returns an array containing all matches.
- `query` can be either a CSS selector or a function.
- `elems` can be either an array of elements, or a single element. If it is an element, its children will be queried.
- `options` is described below.
Aliases: `CSSselect.selectAll(query, elems)`, `CSSselect.iterate(query, elems)`.
#### `CSSselect.compile(query)`
Compiles the query, returns a function.
#### `CSSselect.is(elem, query, options)`
Tests whether or not an element is matched by `query`. `query` can be either a CSS selector or a function.
#### `CSSselect.selectOne(query, elems, options)`
Arguments are the same as for `CSSselect(query, elems)`. Only returns the first match, or `null` if there was no match.
### Options
- `xmlMode`: When enabled, tag names will be case-sensitive. Default: `false`.
- `strict`: Limits the module to only use CSS3 selectors. Default: `false`.
- `rootFunc`: The last function in the stack, will be called with the last element that's looked at. Should return `true`.
## Supported selectors
_As defined by CSS 4 and / or jQuery._
* Universal (`*`)
* Tag (`<tagname>`)
* Descendant (` `)
* Child (`>`)
* Parent (`<`) *
* Sibling (`+`)
* Adjacent (`~`)
* Attribute (`[attr=foo]`), with supported comparisons:
* `[attr]` (existential)
* `=`
* `~=`
* `|=`
* `*=`
* `^=`
* `$=`
* `!=` *
* Also, `i` can be added after the comparison to make the comparison case-insensitive (eg. `[attr=foo i]`) *
* Pseudos:
* `:not`
* `:contains` *
* `:icontains` * (case-insensitive version of `:contains`)
* `:has` *
* `:root`
* `:empty`
* `:parent` *
* `:[first|last]-child[-of-type]`
* `:only-of-type`, `:only-child`
* `:nth-[last-]child[-of-type]`
* `:link`, `:visited` (the latter doesn't match any elements)
* `:selected` *, `:checked`
* `:enabled`, `:disabled`
* `:required`, `:optional`
* `:header`, `:button`, `:input`, `:text`, `:checkbox`, `:file`, `:password`, `:reset`, `:radio` etc. *
* `:matches` *
__*__: Not part of CSS3
---
License: BSD-like
+59
View File
@@ -0,0 +1,59 @@
"use strict";
module.exports = CSSselect;
var Pseudos = require("./lib/pseudos.js"),
DomUtils = require("domutils"),
findOne = DomUtils.findOne,
findAll = DomUtils.findAll,
getChildren = DomUtils.getChildren,
removeSubsets = DomUtils.removeSubsets,
falseFunc = require("boolbase").falseFunc,
compile = require("./lib/compile.js"),
compileUnsafe = compile.compileUnsafe,
compileToken = compile.compileToken;
function getSelectorFunc(searchFunc){
return function select(query, elems, options){
if(typeof query !== "function") query = compileUnsafe(query, options, elems);
if(!Array.isArray(elems)) elems = getChildren(elems);
else elems = removeSubsets(elems);
return searchFunc(query, elems);
};
}
var selectAll = getSelectorFunc(function selectAll(query, elems){
return (query === falseFunc || !elems || elems.length === 0) ? [] : findAll(query, elems);
});
var selectOne = getSelectorFunc(function selectOne(query, elems){
return (query === falseFunc || !elems || elems.length === 0) ? null : findOne(query, elems);
});
function is(elem, query, options){
return (typeof query === "function" ? query : compile(query, options))(elem);
}
/*
the exported interface
*/
function CSSselect(query, elems, options){
return selectAll(query, elems, options);
}
CSSselect.compile = compile;
CSSselect.filters = Pseudos.filters;
CSSselect.pseudos = Pseudos.pseudos;
CSSselect.selectAll = selectAll;
CSSselect.selectOne = selectOne;
CSSselect.is = is;
//legacy methods (might be removed)
CSSselect.parse = compile;
CSSselect.iterate = selectAll;
//hooks
CSSselect._compileUnsafe = compileUnsafe;
CSSselect._compileToken = compileToken;
+181
View File
@@ -0,0 +1,181 @@
var DomUtils = require("domutils"),
hasAttrib = DomUtils.hasAttrib,
getAttributeValue = DomUtils.getAttributeValue,
falseFunc = require("boolbase").falseFunc;
//https://github.com/slevithan/XRegExp/blob/master/src/xregexp.js#L469
var reChars = /[-[\]{}()*+?.,\\^$|#\s]/g;
/*
attribute selectors
*/
var attributeRules = {
__proto__: null,
equals: function(next, data){
var name = data.name,
value = data.value;
if(data.ignoreCase){
value = value.toLowerCase();
return function equalsIC(elem){
var attr = getAttributeValue(elem, name);
return attr != null && attr.toLowerCase() === value && next(elem);
};
}
return function equals(elem){
return getAttributeValue(elem, name) === value && next(elem);
};
},
hyphen: function(next, data){
var name = data.name,
value = data.value,
len = value.length;
if(data.ignoreCase){
value = value.toLowerCase();
return function hyphenIC(elem){
var attr = getAttributeValue(elem, name);
return attr != null &&
(attr.length === len || attr.charAt(len) === "-") &&
attr.substr(0, len).toLowerCase() === value &&
next(elem);
};
}
return function hyphen(elem){
var attr = getAttributeValue(elem, name);
return attr != null &&
attr.substr(0, len) === value &&
(attr.length === len || attr.charAt(len) === "-") &&
next(elem);
};
},
element: function(next, data){
var name = data.name,
value = data.value;
if(/\s/.test(value)){
return falseFunc;
}
value = value.replace(reChars, "\\$&");
var pattern = "(?:^|\\s)" + value + "(?:$|\\s)",
flags = data.ignoreCase ? "i" : "",
regex = new RegExp(pattern, flags);
return function element(elem){
var attr = getAttributeValue(elem, name);
return attr != null && regex.test(attr) && next(elem);
};
},
exists: function(next, data){
var name = data.name;
return function exists(elem){
return hasAttrib(elem, name) && next(elem);
};
},
start: function(next, data){
var name = data.name,
value = data.value,
len = value.length;
if(len === 0){
return falseFunc;
}
if(data.ignoreCase){
value = value.toLowerCase();
return function startIC(elem){
var attr = getAttributeValue(elem, name);
return attr != null && attr.substr(0, len).toLowerCase() === value && next(elem);
};
}
return function start(elem){
var attr = getAttributeValue(elem, name);
return attr != null && attr.substr(0, len) === value && next(elem);
};
},
end: function(next, data){
var name = data.name,
value = data.value,
len = -value.length;
if(len === 0){
return falseFunc;
}
if(data.ignoreCase){
value = value.toLowerCase();
return function endIC(elem){
var attr = getAttributeValue(elem, name);
return attr != null && attr.substr(len).toLowerCase() === value && next(elem);
};
}
return function end(elem){
var attr = getAttributeValue(elem, name);
return attr != null && attr.substr(len) === value && next(elem);
};
},
any: function(next, data){
var name = data.name,
value = data.value;
if(value === ""){
return falseFunc;
}
if(data.ignoreCase){
var regex = new RegExp(value.replace(reChars, "\\$&"), "i");
return function anyIC(elem){
var attr = getAttributeValue(elem, name);
return attr != null && regex.test(attr) && next(elem);
};
}
return function any(elem){
var attr = getAttributeValue(elem, name);
return attr != null && attr.indexOf(value) >= 0 && next(elem);
};
},
not: function(next, data){
var name = data.name,
value = data.value;
if(value === ""){
return function notEmpty(elem){
return !!getAttributeValue(elem, name) && next(elem);
};
} else if(data.ignoreCase){
value = value.toLowerCase();
return function notIC(elem){
var attr = getAttributeValue(elem, name);
return attr != null && attr.toLowerCase() !== value && next(elem);
};
}
return function not(elem){
return getAttributeValue(elem, name) !== value && next(elem);
};
}
};
module.exports = {
compile: function(next, data, options){
if(options && options.strict && (
data.ignoreCase || data.action === "not"
)) throw SyntaxError("Unsupported attribute selector");
return attributeRules[data.action](next, data);
},
rules: attributeRules
};
+192
View File
@@ -0,0 +1,192 @@
/*
compiles a selector to an executable function
*/
module.exports = compile;
module.exports.compileUnsafe = compileUnsafe;
module.exports.compileToken = compileToken;
var parse = require("css-what"),
DomUtils = require("domutils"),
isTag = DomUtils.isTag,
Rules = require("./general.js"),
sortRules = require("./sort.js"),
BaseFuncs = require("boolbase"),
trueFunc = BaseFuncs.trueFunc,
falseFunc = BaseFuncs.falseFunc,
procedure = require("./procedure.json");
function compile(selector, options, context){
var next = compileUnsafe(selector, options, context);
return wrap(next);
}
function wrap(next){
return function base(elem){
return isTag(elem) && next(elem);
};
}
function compileUnsafe(selector, options, context){
var token = parse(selector, options);
return compileToken(token, options, context);
}
function includesScopePseudo(t){
return t.type === "pseudo" && (
t.name === "scope" || (
Array.isArray(t.data) &&
t.data.some(function(data){
return data.some(includesScopePseudo);
})
)
);
}
var DESCENDANT_TOKEN = {type: "descendant"},
SCOPE_TOKEN = {type: "pseudo", name: "scope"},
PLACEHOLDER_ELEMENT = {},
getParent = DomUtils.getParent;
//CSS 4 Spec (Draft): 3.3.1. Absolutizing a Scope-relative Selector
//http://www.w3.org/TR/selectors4/#absolutizing
function absolutize(token, context){
//TODO better check if context is document
var hasContext = !!context && !!context.length && context.every(function(e){
return e === PLACEHOLDER_ELEMENT || !!getParent(e);
});
token.forEach(function(t){
if(t.length > 0 && isTraversal(t[0]) && t[0].type !== "descendant"){
//don't return in else branch
} else if(hasContext && !includesScopePseudo(t)){
t.unshift(DESCENDANT_TOKEN);
} else {
return;
}
t.unshift(SCOPE_TOKEN);
});
}
function compileToken(token, options, context){
token = token.filter(function(t){ return t.length > 0; });
token.forEach(sortRules);
var isArrayContext = Array.isArray(context);
context = (options && options.context) || context;
if(context && !isArrayContext) context = [context];
absolutize(token, context);
return token
.map(function(rules){ return compileRules(rules, options, context, isArrayContext); })
.reduce(reduceRules, falseFunc);
}
function isTraversal(t){
return procedure[t.type] < 0;
}
function compileRules(rules, options, context, isArrayContext){
var acceptSelf = (isArrayContext && rules[0].name === "scope" && rules[1].type === "descendant");
return rules.reduce(function(func, rule, index){
if(func === falseFunc) return func;
return Rules[rule.type](func, rule, options, context, acceptSelf && index === 1);
}, options && options.rootFunc || trueFunc);
}
function reduceRules(a, b){
if(b === falseFunc || a === trueFunc){
return a;
}
if(a === falseFunc || b === trueFunc){
return b;
}
return function combine(elem){
return a(elem) || b(elem);
};
}
//:not, :has and :matches have to compile selectors
//doing this in lib/pseudos.js would lead to circular dependencies,
//so we add them here
var Pseudos = require("./pseudos.js"),
filters = Pseudos.filters,
existsOne = DomUtils.existsOne,
isTag = DomUtils.isTag,
getChildren = DomUtils.getChildren;
function containsTraversal(t){
return t.some(isTraversal);
}
filters.not = function(next, token, options, context){
var opts = {
xmlMode: !!(options && options.xmlMode),
strict: !!(options && options.strict)
};
if(opts.strict){
if(token.length > 1 || token.some(containsTraversal)){
throw new SyntaxError("complex selectors in :not aren't allowed in strict mode");
}
}
var func = compileToken(token, opts, context);
if(func === falseFunc) return next;
if(func === trueFunc) return falseFunc;
return function(elem){
return !func(elem) && next(elem);
};
};
filters.has = function(next, token, options){
var opts = {
xmlMode: !!(options && options.xmlMode),
strict: !!(options && options.strict)
};
//FIXME: Uses an array as a pointer to the current element (side effects)
var context = token.some(containsTraversal) ? [PLACEHOLDER_ELEMENT] : null;
var func = compileToken(token, opts, context);
if(func === falseFunc) return falseFunc;
if(func === trueFunc) return function(elem){
return getChildren(elem).some(isTag) && next(elem);
};
func = wrap(func);
if(context){
return function has(elem){
return next(elem) && (
(context[0] = elem), existsOne(func, getChildren(elem))
);
};
}
return function has(elem){
return next(elem) && existsOne(func, getChildren(elem));
};
};
filters.matches = function(next, token, options, context){
var opts = {
xmlMode: !!(options && options.xmlMode),
strict: !!(options && options.strict),
rootFunc: next
};
return compileToken(token, opts, context);
};
+89
View File
@@ -0,0 +1,89 @@
var DomUtils = require("domutils"),
isTag = DomUtils.isTag,
getParent = DomUtils.getParent,
getChildren = DomUtils.getChildren,
getSiblings = DomUtils.getSiblings,
getName = DomUtils.getName;
/*
all available rules
*/
module.exports = {
__proto__: null,
attribute: require("./attributes.js").compile,
pseudo: require("./pseudos.js").compile,
//tags
tag: function(next, data){
var name = data.name;
return function tag(elem){
return getName(elem) === name && next(elem);
};
},
//traversal
descendant: function(next, rule, options, context, acceptSelf){
return function descendant(elem){
if (acceptSelf && next(elem)) return true;
var found = false;
while(!found && (elem = getParent(elem))){
found = next(elem);
}
return found;
};
},
parent: function(next, data, options){
if(options && options.strict) throw SyntaxError("Parent selector isn't part of CSS3");
return function parent(elem){
return getChildren(elem).some(test);
};
function test(elem){
return isTag(elem) && next(elem);
}
},
child: function(next){
return function child(elem){
var parent = getParent(elem);
return !!parent && next(parent);
};
},
sibling: function(next){
return function sibling(elem){
var siblings = getSiblings(elem);
for(var i = 0; i < siblings.length; i++){
if(isTag(siblings[i])){
if(siblings[i] === elem) break;
if(next(siblings[i])) return true;
}
}
return false;
};
},
adjacent: function(next){
return function adjacent(elem){
var siblings = getSiblings(elem),
lastElement;
for(var i = 0; i < siblings.length; i++){
if(isTag(siblings[i])){
if(siblings[i] === elem) break;
lastElement = siblings[i];
}
}
return !!lastElement && next(lastElement);
};
},
universal: function(next){
return next;
}
};
+11
View File
@@ -0,0 +1,11 @@
{
"universal": 50,
"tag": 30,
"attribute": 1,
"pseudo": 0,
"descendant": -1,
"child": -1,
"parent": -1,
"sibling": -1,
"adjacent": -1
}
+393
View File
@@ -0,0 +1,393 @@
/*
pseudo selectors
---
they are available in two forms:
* filters called when the selector
is compiled and return a function
that needs to return next()
* pseudos get called on execution
they need to return a boolean
*/
var DomUtils = require("domutils"),
isTag = DomUtils.isTag,
getText = DomUtils.getText,
getParent = DomUtils.getParent,
getChildren = DomUtils.getChildren,
getSiblings = DomUtils.getSiblings,
hasAttrib = DomUtils.hasAttrib,
getName = DomUtils.getName,
getAttribute= DomUtils.getAttributeValue,
getNCheck = require("nth-check"),
checkAttrib = require("./attributes.js").rules.equals,
BaseFuncs = require("boolbase"),
trueFunc = BaseFuncs.trueFunc,
falseFunc = BaseFuncs.falseFunc;
//helper methods
function getFirstElement(elems){
for(var i = 0; elems && i < elems.length; i++){
if(isTag(elems[i])) return elems[i];
}
}
function getAttribFunc(name, value){
var data = {name: name, value: value};
return function attribFunc(next){
return checkAttrib(next, data);
};
}
function getChildFunc(next){
return function(elem){
return !!getParent(elem) && next(elem);
};
}
var filters = {
contains: function(next, text){
return function contains(elem){
return next(elem) && getText(elem).indexOf(text) >= 0;
};
},
icontains: function(next, text){
var itext = text.toLowerCase();
return function icontains(elem){
return next(elem) &&
getText(elem).toLowerCase().indexOf(itext) >= 0;
};
},
//location specific methods
"nth-child": function(next, rule){
var func = getNCheck(rule);
if(func === falseFunc) return func;
if(func === trueFunc) return getChildFunc(next);
return function nthChild(elem){
var siblings = getSiblings(elem);
for(var i = 0, pos = 0; i < siblings.length; i++){
if(isTag(siblings[i])){
if(siblings[i] === elem) break;
else pos++;
}
}
return func(pos) && next(elem);
};
},
"nth-last-child": function(next, rule){
var func = getNCheck(rule);
if(func === falseFunc) return func;
if(func === trueFunc) return getChildFunc(next);
return function nthLastChild(elem){
var siblings = getSiblings(elem);
for(var pos = 0, i = siblings.length - 1; i >= 0; i--){
if(isTag(siblings[i])){
if(siblings[i] === elem) break;
else pos++;
}
}
return func(pos) && next(elem);
};
},
"nth-of-type": function(next, rule){
var func = getNCheck(rule);
if(func === falseFunc) return func;
if(func === trueFunc) return getChildFunc(next);
return function nthOfType(elem){
var siblings = getSiblings(elem);
for(var pos = 0, i = 0; i < siblings.length; i++){
if(isTag(siblings[i])){
if(siblings[i] === elem) break;
if(getName(siblings[i]) === getName(elem)) pos++;
}
}
return func(pos) && next(elem);
};
},
"nth-last-of-type": function(next, rule){
var func = getNCheck(rule);
if(func === falseFunc) return func;
if(func === trueFunc) return getChildFunc(next);
return function nthLastOfType(elem){
var siblings = getSiblings(elem);
for(var pos = 0, i = siblings.length - 1; i >= 0; i--){
if(isTag(siblings[i])){
if(siblings[i] === elem) break;
if(getName(siblings[i]) === getName(elem)) pos++;
}
}
return func(pos) && next(elem);
};
},
//TODO determine the actual root element
root: function(next){
return function(elem){
return !getParent(elem) && next(elem);
};
},
scope: function(next, rule, options, context){
if(!context || context.length === 0){
//equivalent to :root
return filters.root(next);
}
if(context.length === 1){
//NOTE: can't be unpacked, as :has uses this for side-effects
return function(elem){
return context[0] === elem && next(elem);
};
}
return function(elem){
return context.indexOf(elem) >= 0 && next(elem);
};
},
//jQuery extensions (others follow as pseudos)
checkbox: getAttribFunc("type", "checkbox"),
file: getAttribFunc("type", "file"),
password: getAttribFunc("type", "password"),
radio: getAttribFunc("type", "radio"),
reset: getAttribFunc("type", "reset"),
image: getAttribFunc("type", "image"),
submit: getAttribFunc("type", "submit")
};
//while filters are precompiled, pseudos get called when they are needed
var pseudos = {
empty: function(elem){
return !getChildren(elem).some(function(elem){
return isTag(elem) || elem.type === "text";
});
},
"first-child": function(elem){
return getFirstElement(getSiblings(elem)) === elem;
},
"last-child": function(elem){
var siblings = getSiblings(elem);
for(var i = siblings.length - 1; i >= 0; i--){
if(siblings[i] === elem) return true;
if(isTag(siblings[i])) break;
}
return false;
},
"first-of-type": function(elem){
var siblings = getSiblings(elem);
for(var i = 0; i < siblings.length; i++){
if(isTag(siblings[i])){
if(siblings[i] === elem) return true;
if(getName(siblings[i]) === getName(elem)) break;
}
}
return false;
},
"last-of-type": function(elem){
var siblings = getSiblings(elem);
for(var i = siblings.length-1; i >= 0; i--){
if(isTag(siblings[i])){
if(siblings[i] === elem) return true;
if(getName(siblings[i]) === getName(elem)) break;
}
}
return false;
},
"only-of-type": function(elem){
var siblings = getSiblings(elem);
for(var i = 0, j = siblings.length; i < j; i++){
if(isTag(siblings[i])){
if(siblings[i] === elem) continue;
if(getName(siblings[i]) === getName(elem)) return false;
}
}
return true;
},
"only-child": function(elem){
var siblings = getSiblings(elem);
for(var i = 0; i < siblings.length; i++){
if(isTag(siblings[i]) && siblings[i] !== elem) return false;
}
return true;
},
//:matches(a, area, link)[href]
link: function(elem){
return hasAttrib(elem, "href");
},
visited: falseFunc, //seems to be a valid implementation
//TODO: :any-link once the name is finalized (as an alias of :link)
//forms
//to consider: :target
//:matches([selected], select:not([multiple]):not(> option[selected]) > option:first-of-type)
selected: function(elem){
if(hasAttrib(elem, "selected")) return true;
else if(getName(elem) !== "option") return false;
//the first <option> in a <select> is also selected
var parent = getParent(elem);
if(
!parent ||
getName(parent) !== "select" ||
hasAttrib(parent, "multiple")
) return false;
var siblings = getChildren(parent),
sawElem = false;
for(var i = 0; i < siblings.length; i++){
if(isTag(siblings[i])){
if(siblings[i] === elem){
sawElem = true;
} else if(!sawElem){
return false;
} else if(hasAttrib(siblings[i], "selected")){
return false;
}
}
}
return sawElem;
},
//https://html.spec.whatwg.org/multipage/scripting.html#disabled-elements
//:matches(
// :matches(button, input, select, textarea, menuitem, optgroup, option)[disabled],
// optgroup[disabled] > option),
// fieldset[disabled] * //TODO not child of first <legend>
//)
disabled: function(elem){
return hasAttrib(elem, "disabled");
},
enabled: function(elem){
return !hasAttrib(elem, "disabled");
},
//:matches(:matches(:radio, :checkbox)[checked], :selected) (TODO menuitem)
checked: function(elem){
return hasAttrib(elem, "checked") || pseudos.selected(elem);
},
//:matches(input, select, textarea)[required]
required: function(elem){
return hasAttrib(elem, "required");
},
//:matches(input, select, textarea):not([required])
optional: function(elem){
return !hasAttrib(elem, "required");
},
//jQuery extensions
//:not(:empty)
parent: function(elem){
return !pseudos.empty(elem);
},
//:matches(h1, h2, h3, h4, h5, h6)
header: function(elem){
var name = getName(elem);
return name === "h1" ||
name === "h2" ||
name === "h3" ||
name === "h4" ||
name === "h5" ||
name === "h6";
},
//:matches(button, input[type=button])
button: function(elem){
var name = getName(elem);
return name === "button" ||
name === "input" &&
getAttribute(elem, "type") === "button";
},
//:matches(input, textarea, select, button)
input: function(elem){
var name = getName(elem);
return name === "input" ||
name === "textarea" ||
name === "select" ||
name === "button";
},
//input:matches(:not([type!='']), [type='text' i])
text: function(elem){
var attr;
return getName(elem) === "input" && (
!(attr = getAttribute(elem, "type")) ||
attr.toLowerCase() === "text"
);
}
};
function verifyArgs(func, name, subselect){
if(subselect === null){
if(func.length > 1 && name !== "scope"){
throw new SyntaxError("pseudo-selector :" + name + " requires an argument");
}
} else {
if(func.length === 1){
throw new SyntaxError("pseudo-selector :" + name + " doesn't have any arguments");
}
}
}
//FIXME this feels hacky
var re_CSS3 = /^(?:(?:nth|last|first|only)-(?:child|of-type)|root|empty|(?:en|dis)abled|checked|not)$/;
module.exports = {
compile: function(next, data, options, context){
var name = data.name,
subselect = data.data;
if(options && options.strict && !re_CSS3.test(name)){
throw SyntaxError(":" + name + " isn't part of CSS3");
}
if(typeof filters[name] === "function"){
verifyArgs(filters[name], name, subselect);
return filters[name](next, subselect, options, context);
} else if(typeof pseudos[name] === "function"){
var func = pseudos[name];
verifyArgs(func, name, subselect);
if(next === trueFunc) return func;
return function pseudoArgs(elem){
return func(elem, subselect) && next(elem);
};
} else {
throw new SyntaxError("unmatched pseudo-class :" + name);
}
},
filters: filters,
pseudos: pseudos
};
+80
View File
@@ -0,0 +1,80 @@
module.exports = sortByProcedure;
/*
sort the parts of the passed selector,
as there is potential for optimization
(some types of selectors are faster than others)
*/
var procedure = require("./procedure.json");
var attributes = {
__proto__: null,
exists: 10,
equals: 8,
not: 7,
start: 6,
end: 6,
any: 5,
hyphen: 4,
element: 4
};
function sortByProcedure(arr){
var procs = arr.map(getProcedure);
for(var i = 1; i < arr.length; i++){
var procNew = procs[i];
if(procNew < 0) continue;
for(var j = i - 1; j >= 0 && procNew < procs[j]; j--){
var token = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = token;
procs[j + 1] = procs[j];
procs[j] = procNew;
}
}
}
function getProcedure(token){
var proc = procedure[token.type];
if(proc === procedure.attribute){
proc = attributes[token.action];
if(proc === attributes.equals && token.name === "id"){
//prefer ID selectors (eg. #ID)
proc = 9;
}
if(token.ignoreCase){
//ignoreCase adds some overhead, prefer "normal" token
//this is a binary operation, to ensure it's still an int
proc >>= 1;
}
} else if(proc === procedure.pseudo){
if(!token.data){
proc = 3;
} else if(token.name === "has" || token.name === "contains"){
proc = 0; //expensive in any case
} else if(token.name === "matches" || token.name === "not"){
proc = 0;
for(var i = 0; i < token.data.length; i++){
//TODO better handling of complex selectors
if(token.data[i].length !== 1) continue;
var cur = getProcedure(token.data[i][0]);
//avoid executing :has or :contains
if(cur === 0){
proc = 0;
break;
}
if(cur > proc) proc = cur;
}
if(token.data.length > 1 && proc > 0) proc -= 1;
} else {
proc = 1;
}
}
return proc;
}
+93
View File
@@ -0,0 +1,93 @@
{
"_from": "css-select@^1.1.0",
"_id": "css-select@1.2.0",
"_inBundle": false,
"_integrity": "sha1-KzoRBTnFNV8c2NMUYj6HCxIeyFg=",
"_location": "/renderkid/css-select",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "css-select@^1.1.0",
"name": "css-select",
"escapedName": "css-select",
"rawSpec": "^1.1.0",
"saveSpec": null,
"fetchSpec": "^1.1.0"
},
"_requiredBy": [
"/renderkid"
],
"_resolved": "https://registry.npmjs.org/css-select/-/css-select-1.2.0.tgz",
"_shasum": "2b3a110539c5355f1cd8d314623e870b121ec858",
"_spec": "css-select@^1.1.0",
"_where": "/home/george/citwa/red_de_investigacion_front/first/node_modules/renderkid",
"author": {
"name": "Felix Boehm",
"email": "me@feedic.com"
},
"bugs": {
"url": "https://github.com/fb55/css-select/issues"
},
"bundleDependencies": false,
"dependencies": {
"boolbase": "~1.0.0",
"css-what": "2.1",
"domutils": "1.5.1",
"nth-check": "~1.0.1"
},
"deprecated": false,
"description": "a CSS selector compiler/engine",
"devDependencies": {
"cheerio-soupselect": "*",
"coveralls": "*",
"expect.js": "*",
"htmlparser2": "*",
"istanbul": "*",
"jshint": "2",
"mocha": "*",
"mocha-lcov-reporter": "*"
},
"files": [
"index.js",
"lib"
],
"homepage": "https://github.com/fb55/css-select#readme",
"jshintConfig": {
"eqeqeq": true,
"freeze": true,
"latedef": "nofunc",
"noarg": true,
"nonbsp": true,
"quotmark": "double",
"undef": true,
"unused": true,
"trailing": true,
"eqnull": true,
"proto": true,
"smarttabs": true,
"node": true,
"globals": {
"describe": true,
"it": true
}
},
"keywords": [
"css",
"selector",
"sizzle"
],
"license": "BSD-like",
"name": "css-select",
"repository": {
"type": "git",
"url": "git://github.com/fb55/css-select.git"
},
"scripts": {
"coveralls": "npm run lint && npm run lcov && (cat coverage/lcov.info | coveralls || exit 0)",
"lcov": "istanbul cover _mocha --report lcovonly -- -R spec",
"lint": "jshint index.js lib/*.js test/*.js",
"test": "mocha && npm run lint"
},
"version": "1.2.0"
}
+11
View File
@@ -0,0 +1,11 @@
Copyright (c) Felix Böhm
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+274
View File
@@ -0,0 +1,274 @@
"use strict";
module.exports = parse;
var re_name = /^(?:\\.|[\w\-\u00b0-\uFFFF])+/,
re_escape = /\\([\da-f]{1,6}\s?|(\s)|.)/ig,
//modified version of https://github.com/jquery/sizzle/blob/master/src/sizzle.js#L87
re_attr = /^\s*((?:\\.|[\w\u00b0-\uFFFF\-])+)\s*(?:(\S?)=\s*(?:(['"])([^]*?)\3|(#?(?:\\.|[\w\u00b0-\uFFFF\-])*)|)|)\s*(i)?\]/;
var actionTypes = {
__proto__: null,
"undefined": "exists",
"": "equals",
"~": "element",
"^": "start",
"$": "end",
"*": "any",
"!": "not",
"|": "hyphen"
};
var simpleSelectors = {
__proto__: null,
">": "child",
"<": "parent",
"~": "sibling",
"+": "adjacent"
};
var attribSelectors = {
__proto__: null,
"#": ["id", "equals"],
".": ["class", "element"]
};
//pseudos, whose data-property is parsed as well
var unpackPseudos = {
__proto__: null,
"has": true,
"not": true,
"matches": true
};
var stripQuotesFromPseudos = {
__proto__: null,
"contains": true,
"icontains": true
};
var quotes = {
__proto__: null,
"\"": true,
"'": true
};
//unescape function taken from https://github.com/jquery/sizzle/blob/master/src/sizzle.js#L139
function funescape( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
}
function unescapeCSS(str){
return str.replace(re_escape, funescape);
}
function isWhitespace(c){
return c === " " || c === "\n" || c === "\t" || c === "\f" || c === "\r";
}
function parse(selector, options){
var subselects = [];
selector = parseSelector(subselects, selector + "", options);
if(selector !== ""){
throw new SyntaxError("Unmatched selector: " + selector);
}
return subselects;
}
function parseSelector(subselects, selector, options){
var tokens = [],
sawWS = false,
data, firstChar, name, quot;
function getName(){
var sub = selector.match(re_name)[0];
selector = selector.substr(sub.length);
return unescapeCSS(sub);
}
function stripWhitespace(start){
while(isWhitespace(selector.charAt(start))) start++;
selector = selector.substr(start);
}
function isEscaped(pos) {
var slashCount = 0;
while (selector.charAt(--pos) === "\\") slashCount++;
return (slashCount & 1) === 1;
}
stripWhitespace(0);
while(selector !== ""){
firstChar = selector.charAt(0);
if(isWhitespace(firstChar)){
sawWS = true;
stripWhitespace(1);
} else if(firstChar in simpleSelectors){
tokens.push({type: simpleSelectors[firstChar]});
sawWS = false;
stripWhitespace(1);
} else if(firstChar === ","){
if(tokens.length === 0){
throw new SyntaxError("empty sub-selector");
}
subselects.push(tokens);
tokens = [];
sawWS = false;
stripWhitespace(1);
} else {
if(sawWS){
if(tokens.length > 0){
tokens.push({type: "descendant"});
}
sawWS = false;
}
if(firstChar === "*"){
selector = selector.substr(1);
tokens.push({type: "universal"});
} else if(firstChar in attribSelectors){
selector = selector.substr(1);
tokens.push({
type: "attribute",
name: attribSelectors[firstChar][0],
action: attribSelectors[firstChar][1],
value: getName(),
ignoreCase: false
});
} else if(firstChar === "["){
selector = selector.substr(1);
data = selector.match(re_attr);
if(!data){
throw new SyntaxError("Malformed attribute selector: " + selector);
}
selector = selector.substr(data[0].length);
name = unescapeCSS(data[1]);
if(
!options || (
"lowerCaseAttributeNames" in options ?
options.lowerCaseAttributeNames :
!options.xmlMode
)
){
name = name.toLowerCase();
}
tokens.push({
type: "attribute",
name: name,
action: actionTypes[data[2]],
value: unescapeCSS(data[4] || data[5] || ""),
ignoreCase: !!data[6]
});
} else if(firstChar === ":"){
if(selector.charAt(1) === ":"){
selector = selector.substr(2);
tokens.push({type: "pseudo-element", name: getName().toLowerCase()});
continue;
}
selector = selector.substr(1);
name = getName().toLowerCase();
data = null;
if(selector.charAt(0) === "("){
if(name in unpackPseudos){
quot = selector.charAt(1);
var quoted = quot in quotes;
selector = selector.substr(quoted + 1);
data = [];
selector = parseSelector(data, selector, options);
if(quoted){
if(selector.charAt(0) !== quot){
throw new SyntaxError("unmatched quotes in :" + name);
} else {
selector = selector.substr(1);
}
}
if(selector.charAt(0) !== ")"){
throw new SyntaxError("missing closing parenthesis in :" + name + " " + selector);
}
selector = selector.substr(1);
} else {
var pos = 1, counter = 1;
for(; counter > 0 && pos < selector.length; pos++){
if(selector.charAt(pos) === "(" && !isEscaped(pos)) counter++;
else if(selector.charAt(pos) === ")" && !isEscaped(pos)) counter--;
}
if(counter){
throw new SyntaxError("parenthesis not matched");
}
data = selector.substr(1, pos - 2);
selector = selector.substr(pos);
if(name in stripQuotesFromPseudos){
quot = data.charAt(0);
if(quot === data.slice(-1) && quot in quotes){
data = data.slice(1, -1);
}
data = unescapeCSS(data);
}
}
}
tokens.push({type: "pseudo", name: name, data: data});
} else if(re_name.test(selector)){
name = getName();
if(!options || ("lowerCaseTags" in options ? options.lowerCaseTags : !options.xmlMode)){
name = name.toLowerCase();
}
tokens.push({type: "tag", name: name});
} else {
if(tokens.length && tokens[tokens.length - 1].type === "descendant"){
tokens.pop();
}
addToken(subselects, tokens);
return selector;
}
}
}
addToken(subselects, tokens);
return selector;
}
function addToken(subselects, tokens){
if(subselects.length > 0 && tokens.length === 0){
throw new SyntaxError("empty sub-selector");
}
subselects.push(tokens);
}
+77
View File
@@ -0,0 +1,77 @@
{
"_from": "css-what@2.1",
"_id": "css-what@2.1.3",
"_inBundle": false,
"_integrity": "sha512-a+EPoD+uZiNfh+5fxw2nO9QwFa6nJe2Or35fGY6Ipw1R3R4AGz1d1TEZrCegvw2YTmZ0jXirGYlzxxpYSHwpEg==",
"_location": "/renderkid/css-what",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "css-what@2.1",
"name": "css-what",
"escapedName": "css-what",
"rawSpec": "2.1",
"saveSpec": null,
"fetchSpec": "2.1"
},
"_requiredBy": [
"/renderkid/css-select"
],
"_resolved": "https://registry.npmjs.org/css-what/-/css-what-2.1.3.tgz",
"_shasum": "a6d7604573365fe74686c3f311c56513d88285f2",
"_spec": "css-what@2.1",
"_where": "/home/george/citwa/red_de_investigacion_front/first/node_modules/renderkid/node_modules/css-select",
"author": {
"name": "Felix Böhm",
"email": "me@feedic.com",
"url": "http://feedic.com"
},
"bugs": {
"url": "https://github.com/fb55/css-what/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": false,
"description": "a CSS selector parser",
"devDependencies": {
"jshint": "2"
},
"engines": {
"node": "*"
},
"files": [
"index.js"
],
"homepage": "https://github.com/fb55/css-what#readme",
"jshintConfig": {
"eqeqeq": true,
"freeze": true,
"latedef": "nofunc",
"noarg": true,
"nonbsp": true,
"undef": true,
"unused": true,
"eqnull": true,
"proto": true,
"node": true,
"globals": {
"describe": true,
"it": true
}
},
"license": "BSD-2-Clause",
"main": "./index.js",
"name": "css-what",
"optionalDependencies": {},
"prettier": {
"tabWidth": 4
},
"repository": {
"url": "git+https://github.com/fb55/css-what.git"
},
"scripts": {
"test": "node tests/test.js && jshint *.js"
},
"version": "2.1.3"
}
+51
View File
@@ -0,0 +1,51 @@
# css-what [![Build Status](https://secure.travis-ci.org/fb55/css-what.svg?branch=master)](http://travis-ci.org/fb55/css-what)
a CSS selector parser
## Example
```js
require('css-what')('foo[bar]:baz')
~> [ [ { type: 'tag', name: 'foo' },
{ type: 'attribute',
name: 'bar',
action: 'exists',
value: '',
ignoreCase: false },
{ type: 'pseudo',
name: 'baz',
data: null } ] ]
```
## API
__`CSSwhat(selector, options)` - Parses `str`, with the passed `options`.__
The function returns a two-dimensional array. The first array represents selectors separated by commas (eg. `sub1, sub2`), the second contains the relevant tokens for that selector. Possible token types are:
name | attributes | example | output
---- | ---------- | ------- | ------
`tag`| `name` | `div` | `{ type: 'tag', name: 'div' }`
`universal`| - | `*` | `{ type: 'universal' }`
`pseudo`| `name`, `data`|`:name(data)`| `{ type: 'pseudo', name: 'name', data: 'data' }`
`pseudo`| `name`, `data`|`:name`| `{ type: 'pseudo', name: 'name', data: null }`
`pseudo-element`| `name` |`::name`| `{ type: 'pseudo-element', name: 'name' }`
`attribute`|`name`, `action`, `value`, `ignoreCase`|`[attr]`|`{ type: 'attribute', name: 'attr', action: 'exists', value: '', ignoreCase: false }`
`attribute`|`name`, `action`, `value`, `ignoreCase`|`[attr=val]`|`{ type: 'attribute', name: 'attr', action: 'equals', value: 'val', ignoreCase: false }`
`attribute`|`name`, `action`, `value`, `ignoreCase`|`[attr^=val]`|`{ type: 'attribute', name: 'attr', action: 'start', value: 'val', ignoreCase: false }`
`attribute`|`name`, `action`, `value`, `ignoreCase`|`[attr$=val]`|`{ type: 'attribute', name: 'attr', action: 'end', value: 'val', ignoreCase: false }`
`child`| - | `>` | `{ type: 'child' }`
`parent`| - | `<` | `{ type: 'parent' }`
`sibling`| - | `~` | `{ type: 'sibling' }`
`adjacent`| - | `+` | `{ type: 'adjacent' }`
`descendant`| - | | `{ type: 'descendant' }`
__Options:__
- `xmlMode`: When enabled, tag names will be case-sensitive (meaning they won't be lowercased).
---
License: BSD-2-Clause
+1
View File
@@ -0,0 +1 @@
node_modules
+11
View File
@@ -0,0 +1,11 @@
Copyright (c) Felix Böhm
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+14
View File
@@ -0,0 +1,14 @@
var DomUtils = module.exports;
[
require("./lib/stringify"),
require("./lib/traversal"),
require("./lib/manipulation"),
require("./lib/querying"),
require("./lib/legacy"),
require("./lib/helpers")
].forEach(function(ext){
Object.keys(ext).forEach(function(key){
DomUtils[key] = ext[key].bind(DomUtils);
});
});
+141
View File
@@ -0,0 +1,141 @@
// removeSubsets
// Given an array of nodes, remove any member that is contained by another.
exports.removeSubsets = function(nodes) {
var idx = nodes.length, node, ancestor, replace;
// Check if each node (or one of its ancestors) is already contained in the
// array.
while (--idx > -1) {
node = ancestor = nodes[idx];
// Temporarily remove the node under consideration
nodes[idx] = null;
replace = true;
while (ancestor) {
if (nodes.indexOf(ancestor) > -1) {
replace = false;
nodes.splice(idx, 1);
break;
}
ancestor = ancestor.parent;
}
// If the node has been found to be unique, re-insert it.
if (replace) {
nodes[idx] = node;
}
}
return nodes;
};
// Source: http://dom.spec.whatwg.org/#dom-node-comparedocumentposition
var POSITION = {
DISCONNECTED: 1,
PRECEDING: 2,
FOLLOWING: 4,
CONTAINS: 8,
CONTAINED_BY: 16
};
// Compare the position of one node against another node in any other document.
// The return value is a bitmask with the following values:
//
// document order:
// > There is an ordering, document order, defined on all the nodes in the
// > document corresponding to the order in which the first character of the
// > XML representation of each node occurs in the XML representation of the
// > document after expansion of general entities. Thus, the document element
// > node will be the first node. Element nodes occur before their children.
// > Thus, document order orders element nodes in order of the occurrence of
// > their start-tag in the XML (after expansion of entities). The attribute
// > nodes of an element occur after the element and before its children. The
// > relative order of attribute nodes is implementation-dependent./
// Source:
// http://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-document-order
//
// @argument {Node} nodaA The first node to use in the comparison
// @argument {Node} nodeB The second node to use in the comparison
//
// @return {Number} A bitmask describing the input nodes' relative position.
// See http://dom.spec.whatwg.org/#dom-node-comparedocumentposition for
// a description of these values.
var comparePos = exports.compareDocumentPosition = function(nodeA, nodeB) {
var aParents = [];
var bParents = [];
var current, sharedParent, siblings, aSibling, bSibling, idx;
if (nodeA === nodeB) {
return 0;
}
current = nodeA;
while (current) {
aParents.unshift(current);
current = current.parent;
}
current = nodeB;
while (current) {
bParents.unshift(current);
current = current.parent;
}
idx = 0;
while (aParents[idx] === bParents[idx]) {
idx++;
}
if (idx === 0) {
return POSITION.DISCONNECTED;
}
sharedParent = aParents[idx - 1];
siblings = sharedParent.children;
aSibling = aParents[idx];
bSibling = bParents[idx];
if (siblings.indexOf(aSibling) > siblings.indexOf(bSibling)) {
if (sharedParent === nodeB) {
return POSITION.FOLLOWING | POSITION.CONTAINED_BY;
}
return POSITION.FOLLOWING;
} else {
if (sharedParent === nodeA) {
return POSITION.PRECEDING | POSITION.CONTAINS;
}
return POSITION.PRECEDING;
}
};
// Sort an array of nodes based on their relative position in the document and
// remove any duplicate nodes. If the array contains nodes that do not belong
// to the same document, sort order is unspecified.
//
// @argument {Array} nodes Array of DOM nodes
//
// @returns {Array} collection of unique nodes, sorted in document order
exports.uniqueSort = function(nodes) {
var idx = nodes.length, node, position;
nodes = nodes.slice();
while (--idx > -1) {
node = nodes[idx];
position = nodes.indexOf(node);
if (position > -1 && position < idx) {
nodes.splice(idx, 1);
}
}
nodes.sort(function(a, b) {
var relative = comparePos(a, b);
if (relative & POSITION.PRECEDING) {
return -1;
} else if (relative & POSITION.FOLLOWING) {
return 1;
}
return 0;
});
return nodes;
};
+87
View File
@@ -0,0 +1,87 @@
var ElementType = require("domelementtype");
var isTag = exports.isTag = ElementType.isTag;
exports.testElement = function(options, element){
for(var key in options){
if(!options.hasOwnProperty(key));
else if(key === "tag_name"){
if(!isTag(element) || !options.tag_name(element.name)){
return false;
}
} else if(key === "tag_type"){
if(!options.tag_type(element.type)) return false;
} else if(key === "tag_contains"){
if(isTag(element) || !options.tag_contains(element.data)){
return false;
}
} else if(!element.attribs || !options[key](element.attribs[key])){
return false;
}
}
return true;
};
var Checks = {
tag_name: function(name){
if(typeof name === "function"){
return function(elem){ return isTag(elem) && name(elem.name); };
} else if(name === "*"){
return isTag;
} else {
return function(elem){ return isTag(elem) && elem.name === name; };
}
},
tag_type: function(type){
if(typeof type === "function"){
return function(elem){ return type(elem.type); };
} else {
return function(elem){ return elem.type === type; };
}
},
tag_contains: function(data){
if(typeof data === "function"){
return function(elem){ return !isTag(elem) && data(elem.data); };
} else {
return function(elem){ return !isTag(elem) && elem.data === data; };
}
}
};
function getAttribCheck(attrib, value){
if(typeof value === "function"){
return function(elem){ return elem.attribs && value(elem.attribs[attrib]); };
} else {
return function(elem){ return elem.attribs && elem.attribs[attrib] === value; };
}
}
function combineFuncs(a, b){
return function(elem){
return a(elem) || b(elem);
};
}
exports.getElements = function(options, element, recurse, limit){
var funcs = Object.keys(options).map(function(key){
var value = options[key];
return key in Checks ? Checks[key](value) : getAttribCheck(key, value);
});
return funcs.length === 0 ? [] : this.filter(
funcs.reduce(combineFuncs),
element, recurse, limit
);
};
exports.getElementById = function(id, element, recurse){
if(!Array.isArray(element)) element = [element];
return this.findOne(getAttribCheck("id", id), element, recurse !== false);
};
exports.getElementsByTagName = function(name, element, recurse, limit){
return this.filter(Checks.tag_name(name), element, recurse, limit);
};
exports.getElementsByTagType = function(type, element, recurse, limit){
return this.filter(Checks.tag_type(type), element, recurse, limit);
};
+77
View File
@@ -0,0 +1,77 @@
exports.removeElement = function(elem){
if(elem.prev) elem.prev.next = elem.next;
if(elem.next) elem.next.prev = elem.prev;
if(elem.parent){
var childs = elem.parent.children;
childs.splice(childs.lastIndexOf(elem), 1);
}
};
exports.replaceElement = function(elem, replacement){
var prev = replacement.prev = elem.prev;
if(prev){
prev.next = replacement;
}
var next = replacement.next = elem.next;
if(next){
next.prev = replacement;
}
var parent = replacement.parent = elem.parent;
if(parent){
var childs = parent.children;
childs[childs.lastIndexOf(elem)] = replacement;
}
};
exports.appendChild = function(elem, child){
child.parent = elem;
if(elem.children.push(child) !== 1){
var sibling = elem.children[elem.children.length - 2];
sibling.next = child;
child.prev = sibling;
child.next = null;
}
};
exports.append = function(elem, next){
var parent = elem.parent,
currNext = elem.next;
next.next = currNext;
next.prev = elem;
elem.next = next;
next.parent = parent;
if(currNext){
currNext.prev = next;
if(parent){
var childs = parent.children;
childs.splice(childs.lastIndexOf(currNext), 0, next);
}
} else if(parent){
parent.children.push(next);
}
};
exports.prepend = function(elem, prev){
var parent = elem.parent;
if(parent){
var childs = parent.children;
childs.splice(childs.lastIndexOf(elem), 0, prev);
}
if(elem.prev){
elem.prev.next = prev;
}
prev.parent = parent;
prev.prev = elem.prev;
prev.next = elem;
elem.prev = prev;
};
+94
View File
@@ -0,0 +1,94 @@
var isTag = require("domelementtype").isTag;
module.exports = {
filter: filter,
find: find,
findOneChild: findOneChild,
findOne: findOne,
existsOne: existsOne,
findAll: findAll
};
function filter(test, element, recurse, limit){
if(!Array.isArray(element)) element = [element];
if(typeof limit !== "number" || !isFinite(limit)){
limit = Infinity;
}
return find(test, element, recurse !== false, limit);
}
function find(test, elems, recurse, limit){
var result = [], childs;
for(var i = 0, j = elems.length; i < j; i++){
if(test(elems[i])){
result.push(elems[i]);
if(--limit <= 0) break;
}
childs = elems[i].children;
if(recurse && childs && childs.length > 0){
childs = find(test, childs, recurse, limit);
result = result.concat(childs);
limit -= childs.length;
if(limit <= 0) break;
}
}
return result;
}
function findOneChild(test, elems){
for(var i = 0, l = elems.length; i < l; i++){
if(test(elems[i])) return elems[i];
}
return null;
}
function findOne(test, elems){
var elem = null;
for(var i = 0, l = elems.length; i < l && !elem; i++){
if(!isTag(elems[i])){
continue;
} else if(test(elems[i])){
elem = elems[i];
} else if(elems[i].children.length > 0){
elem = findOne(test, elems[i].children);
}
}
return elem;
}
function existsOne(test, elems){
for(var i = 0, l = elems.length; i < l; i++){
if(
isTag(elems[i]) && (
test(elems[i]) || (
elems[i].children.length > 0 &&
existsOne(test, elems[i].children)
)
)
){
return true;
}
}
return false;
}
function findAll(test, elems){
var result = [];
for(var i = 0, j = elems.length; i < j; i++){
if(!isTag(elems[i])) continue;
if(test(elems[i])) result.push(elems[i]);
if(elems[i].children.length > 0){
result = result.concat(findAll(test, elems[i].children));
}
}
return result;
}
+22
View File
@@ -0,0 +1,22 @@
var ElementType = require("domelementtype"),
getOuterHTML = require("dom-serializer"),
isTag = ElementType.isTag;
module.exports = {
getInnerHTML: getInnerHTML,
getOuterHTML: getOuterHTML,
getText: getText
};
function getInnerHTML(elem, opts){
return elem.children ? elem.children.map(function(elem){
return getOuterHTML(elem, opts);
}).join("") : "";
}
function getText(elem){
if(Array.isArray(elem)) return elem.map(getText).join("");
if(isTag(elem) || elem.type === ElementType.CDATA) return getText(elem.children);
if(elem.type === ElementType.Text) return elem.data;
return "";
}
+24
View File
@@ -0,0 +1,24 @@
var getChildren = exports.getChildren = function(elem){
return elem.children;
};
var getParent = exports.getParent = function(elem){
return elem.parent;
};
exports.getSiblings = function(elem){
var parent = getParent(elem);
return parent ? getChildren(parent) : [elem];
};
exports.getAttributeValue = function(elem, name){
return elem.attribs && elem.attribs[name];
};
exports.hasAttrib = function(elem, name){
return !!elem.attribs && hasOwnProperty.call(elem.attribs, name);
};
exports.getName = function(elem){
return elem.name;
};
+78
View File
@@ -0,0 +1,78 @@
{
"_from": "domutils@1.5.1",
"_id": "domutils@1.5.1",
"_inBundle": false,
"_integrity": "sha1-3NhIiib1Y9YQeeSMn3t+Mjc2gs8=",
"_location": "/renderkid/domutils",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "domutils@1.5.1",
"name": "domutils",
"escapedName": "domutils",
"rawSpec": "1.5.1",
"saveSpec": null,
"fetchSpec": "1.5.1"
},
"_requiredBy": [
"/renderkid/css-select"
],
"_resolved": "https://registry.npmjs.org/domutils/-/domutils-1.5.1.tgz",
"_shasum": "dcd8488a26f563d61079e48c9f7b7e32373682cf",
"_spec": "domutils@1.5.1",
"_where": "/home/george/citwa/red_de_investigacion_front/first/node_modules/renderkid/node_modules/css-select",
"author": {
"name": "Felix Boehm",
"email": "me@feedic.com"
},
"bugs": {
"url": "https://github.com/FB55/domutils/issues"
},
"bundleDependencies": false,
"dependencies": {
"dom-serializer": "0",
"domelementtype": "1"
},
"deprecated": false,
"description": "utilities for working with htmlparser2's dom",
"devDependencies": {
"domhandler": "2",
"htmlparser2": "~3.3.0",
"jshint": "~2.3.0",
"mocha": "~1.15.1"
},
"directories": {
"test": "tests"
},
"homepage": "https://github.com/FB55/domutils#readme",
"jshintConfig": {
"proto": true,
"unused": true,
"eqnull": true,
"undef": true,
"quotmark": "double",
"eqeqeq": true,
"trailing": true,
"node": true,
"globals": {
"describe": true,
"it": true,
"beforeEach": true
}
},
"keywords": [
"dom",
"htmlparser2"
],
"main": "index.js",
"name": "domutils",
"repository": {
"type": "git",
"url": "git://github.com/FB55/domutils.git"
},
"scripts": {
"test": "mocha test/tests/**.js && jshint index.js test/**/*.js lib/*.js"
},
"version": "1.5.1"
}
+1
View File
@@ -0,0 +1 @@
utilities for working with htmlparser2's dom
+6
View File
@@ -0,0 +1,6 @@
var makeDom = require("./utils").makeDom;
var markup = Array(21).join(
"<?xml><tag1 id='asdf'> <script>text</script> <!-- comment --> <tag2> text </tag1>"
);
module.exports = makeDom(markup);
+89
View File
@@ -0,0 +1,89 @@
var makeDom = require("../utils").makeDom;
var helpers = require("../..");
var assert = require("assert");
describe("helpers", function() {
describe("removeSubsets", function() {
var removeSubsets = helpers.removeSubsets;
var dom = makeDom("<div><p><span></span></p><p></p></div>")[0];
it("removes identical trees", function() {
var matches = removeSubsets([dom, dom]);
assert.equal(matches.length, 1);
});
it("Removes subsets found first", function() {
var matches = removeSubsets([dom, dom.children[0].children[0]]);
assert.equal(matches.length, 1);
});
it("Removes subsets found last", function() {
var matches = removeSubsets([dom.children[0], dom]);
assert.equal(matches.length, 1);
});
it("Does not remove unique trees", function() {
var matches = removeSubsets([dom.children[0], dom.children[1]]);
assert.equal(matches.length, 2);
});
});
describe("compareDocumentPosition", function() {
var compareDocumentPosition = helpers.compareDocumentPosition;
var markup = "<div><p><span></span></p><a></a></div>";
var dom = makeDom(markup)[0];
var p = dom.children[0];
var span = p.children[0];
var a = dom.children[1];
it("reports when the first node occurs before the second indirectly", function() {
assert.equal(compareDocumentPosition(span, a), 2);
});
it("reports when the first node contains the second", function() {
assert.equal(compareDocumentPosition(p, span), 10);
});
it("reports when the first node occurs after the second indirectly", function() {
assert.equal(compareDocumentPosition(a, span), 4);
});
it("reports when the first node is contained by the second", function() {
assert.equal(compareDocumentPosition(span, p), 20);
});
it("reports when the nodes belong to separate documents", function() {
var other = makeDom(markup)[0].children[0].children[0];
assert.equal(compareDocumentPosition(span, other), 1);
});
it("reports when the nodes are identical", function() {
assert.equal(compareDocumentPosition(span, span), 0);
});
});
describe("uniqueSort", function() {
var uniqueSort = helpers.uniqueSort;
var dom, p, span, a;
beforeEach(function() {
dom = makeDom("<div><p><span></span></p><a></a></div>")[0];
p = dom.children[0];
span = p.children[0];
a = dom.children[1];
});
it("leaves unique elements untouched", function() {
assert.deepEqual(uniqueSort([p, a]), [p, a]);
});
it("removes duplicate elements", function() {
assert.deepEqual(uniqueSort([p, a, p]), [p, a]);
});
it("sorts nodes in document order", function() {
assert.deepEqual(uniqueSort([a, dom, span, p]), [dom, p, span, a]);
});
});
});
+119
View File
@@ -0,0 +1,119 @@
var DomUtils = require("../..");
var fixture = require("../fixture");
var assert = require("assert");
// Set up expected structures
var expected = {
idAsdf: fixture[1],
tag2: [],
typeScript: []
};
for (var idx = 0; idx < 20; ++idx) {
expected.tag2.push(fixture[idx*2 + 1].children[5]);
expected.typeScript.push(fixture[idx*2 + 1].children[1]);
}
describe("legacy", function() {
describe("getElements", function() {
var getElements = DomUtils.getElements;
it("returns the node with the specified ID", function() {
assert.deepEqual(
getElements({ id: "asdf" }, fixture, true, 1),
[expected.idAsdf]
);
});
it("returns empty array for unknown IDs", function() {
assert.deepEqual(getElements({ id: "asdfs" }, fixture, true), []);
});
it("returns the nodes with the specified tag name", function() {
assert.deepEqual(
getElements({ tag_name:"tag2" }, fixture, true),
expected.tag2
);
});
it("returns empty array for unknown tag names", function() {
assert.deepEqual(
getElements({ tag_name : "asdfs" }, fixture, true),
[]
);
});
it("returns the nodes with the specified tag type", function() {
assert.deepEqual(
getElements({ tag_type: "script" }, fixture, true),
expected.typeScript
);
});
it("returns empty array for unknown tag types", function() {
assert.deepEqual(
getElements({ tag_type: "video" }, fixture, true),
[]
);
});
});
describe("getElementById", function() {
var getElementById = DomUtils.getElementById;
it("returns the specified node", function() {
assert.equal(
expected.idAsdf,
getElementById("asdf", fixture, true)
);
});
it("returns `null` for unknown IDs", function() {
assert.equal(null, getElementById("asdfs", fixture, true));
});
});
describe("getElementsByTagName", function() {
var getElementsByTagName = DomUtils.getElementsByTagName;
it("returns the specified nodes", function() {
assert.deepEqual(
getElementsByTagName("tag2", fixture, true),
expected.tag2
);
});
it("returns empty array for unknown tag names", function() {
assert.deepEqual(
getElementsByTagName("tag23", fixture, true),
[]
);
});
});
describe("getElementsByTagType", function() {
var getElementsByTagType = DomUtils.getElementsByTagType;
it("returns the specified nodes", function() {
assert.deepEqual(
getElementsByTagType("script", fixture, true),
expected.typeScript
);
});
it("returns empty array for unknown tag types", function() {
assert.deepEqual(
getElementsByTagType("video", fixture, true),
[]
);
});
});
describe("getOuterHTML", function() {
var getOuterHTML = DomUtils.getOuterHTML;
it("Correctly renders the outer HTML", function() {
assert.equal(
getOuterHTML(fixture[1]),
"<tag1 id=\"asdf\"> <script>text</script> <!-- comment --> <tag2> text </tag2></tag1>"
);
});
});
describe("getInnerHTML", function() {
var getInnerHTML = DomUtils.getInnerHTML;
it("Correctly renders the inner HTML", function() {
assert.equal(
getInnerHTML(fixture[1]),
" <script>text</script> <!-- comment --> <tag2> text </tag2>"
);
});
});
});
+17
View File
@@ -0,0 +1,17 @@
var makeDom = require("../utils").makeDom;
var traversal = require("../..");
var assert = require("assert");
describe("traversal", function() {
describe("hasAttrib", function() {
var hasAttrib = traversal.hasAttrib;
it("doesn't throw on text nodes", function() {
var dom = makeDom("textnode");
assert.doesNotThrow(function() {
hasAttrib(dom[0], "some-attrib");
});
});
});
});
+9
View File
@@ -0,0 +1,9 @@
var htmlparser = require("htmlparser2");
exports.makeDom = function(markup) {
var handler = new htmlparser.DomHandler(),
parser = new htmlparser.Parser(handler);
parser.write(markup);
parser.done();
return handler.dom;
};
+6
View File
@@ -0,0 +1,6 @@
'use strict';
var ansiRegex = require('ansi-regex')();
module.exports = function (str) {
return typeof str === 'string' ? str.replace(ansiRegex, '') : str;
};
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+101
View File
@@ -0,0 +1,101 @@
{
"_from": "strip-ansi@^3.0.0",
"_id": "strip-ansi@3.0.1",
"_inBundle": false,
"_integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=",
"_location": "/renderkid/strip-ansi",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "strip-ansi@^3.0.0",
"name": "strip-ansi",
"escapedName": "strip-ansi",
"rawSpec": "^3.0.0",
"saveSpec": null,
"fetchSpec": "^3.0.0"
},
"_requiredBy": [
"/renderkid"
],
"_resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz",
"_shasum": "6a385fb8853d952d5ff05d0e8aaf94278dc63dcf",
"_spec": "strip-ansi@^3.0.0",
"_where": "/home/george/citwa/red_de_investigacion_front/first/node_modules/renderkid",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/chalk/strip-ansi/issues"
},
"bundleDependencies": false,
"dependencies": {
"ansi-regex": "^2.0.0"
},
"deprecated": false,
"description": "Strip ANSI escape codes",
"devDependencies": {
"ava": "*",
"xo": "*"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/chalk/strip-ansi#readme",
"keywords": [
"strip",
"trim",
"remove",
"ansi",
"styles",
"color",
"colour",
"colors",
"terminal",
"console",
"string",
"tty",
"escape",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"license": "MIT",
"maintainers": [
{
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
{
"name": "Joshua Boy Nicolai Appelman",
"email": "joshua@jbna.nl",
"url": "jbna.nl"
},
{
"name": "JD Ballard",
"email": "i.am.qix@gmail.com",
"url": "github.com/qix-"
}
],
"name": "strip-ansi",
"repository": {
"type": "git",
"url": "git+https://github.com/chalk/strip-ansi.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "3.0.1"
}
+33
View File
@@ -0,0 +1,33 @@
# strip-ansi [![Build Status](https://travis-ci.org/chalk/strip-ansi.svg?branch=master)](https://travis-ci.org/chalk/strip-ansi)
> Strip [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code)
## Install
```
$ npm install --save strip-ansi
```
## Usage
```js
var stripAnsi = require('strip-ansi');
stripAnsi('\u001b[4mcake\u001b[0m');
//=> 'cake'
```
## Related
- [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module
- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)
+76
View File
@@ -0,0 +1,76 @@
{
"_from": "renderkid@^2.0.1",
"_id": "renderkid@2.0.3",
"_inBundle": false,
"_integrity": "sha512-z8CLQp7EZBPCwCnncgf9C4XAi3WR0dv+uWu/PjIyhhAb5d6IJ/QZqlHFprHeKT+59//V6BNUsLbvN8+2LarxGA==",
"_location": "/renderkid",
"_phantomChildren": {
"boolbase": "1.0.0",
"dom-serializer": "0.2.2",
"domelementtype": "1.3.1",
"nth-check": "1.0.2"
},
"_requested": {
"type": "range",
"registry": true,
"raw": "renderkid@^2.0.1",
"name": "renderkid",
"escapedName": "renderkid",
"rawSpec": "^2.0.1",
"saveSpec": null,
"fetchSpec": "^2.0.1"
},
"_requiredBy": [
"/pretty-error"
],
"_resolved": "https://registry.npmjs.org/renderkid/-/renderkid-2.0.3.tgz",
"_shasum": "380179c2ff5ae1365c522bf2fcfcff01c5b74149",
"_spec": "renderkid@^2.0.1",
"_where": "/home/george/citwa/red_de_investigacion_front/first/node_modules/pretty-error",
"author": {
"name": "Aria Minaei"
},
"bugs": {
"url": "https://github.com/AriaMinaei/RenderKid/issues"
},
"bundleDependencies": false,
"dependencies": {
"css-select": "^1.1.0",
"dom-converter": "^0.2",
"htmlparser2": "^3.3.0",
"strip-ansi": "^3.0.0",
"utila": "^0.4.0"
},
"deprecated": false,
"description": "Stylish console.log for node",
"devDependencies": {
"chai": "^4.1.2",
"chai-changes": "^1.3.4",
"chai-fuzzy": "^1.5.0",
"coffee-script": "^1.9.1",
"jitter": "^1.3.0",
"mocha": "^5.2.0",
"mocha-pretty-spec-reporter": "0.1.0-beta.2",
"sinon": "^1.14.1",
"sinon-chai": "^2.7.0",
"underscore": "^1.8.3"
},
"homepage": "https://github.com/AriaMinaei/RenderKid#readme",
"license": "MIT",
"main": "lib/RenderKid.js",
"name": "renderkid",
"repository": {
"type": "git",
"url": "git+https://github.com/AriaMinaei/RenderKid.git"
},
"scripts": {
"compile": "coffee --bare --compile --output ./lib ./src",
"compile:watch": "jitter src lib -b",
"prepublish": "npm run compile",
"test": "mocha \"test/**/*.coffee\"",
"test:watch": "mocha \"test/**/*.coffee\" --watch",
"watch": "npm run compile:watch & npm run test:watch",
"winwatch": "start/b npm run compile:watch & npm run test:watch"
},
"version": "2.0.3"
}
+22
View File
@@ -0,0 +1,22 @@
AnsiPainter = require '../src/AnsiPainter'
paint = (t) ->
AnsiPainter.paint(t)
describe "AnsiPainter", ->
describe "paint()", ->
it "should handle basic coloring", ->
t = "<bg-white><black>a</black></bg-white>"
paint(t).should.equal '\u001b[30m\u001b[47ma\u001b[0m'
it "should handle color in color", ->
t = "<red>a<blue>b</blue></red>"
paint(t).should.equal '\u001b[31ma\u001b[0m\u001b[34mb\u001b[0m'
it "should skip empty tags", ->
t = "<blue></blue>a"
paint(t).should.equal 'a\u001b[0m'
describe "_replaceSpecialStrings()", ->
it "should work", ->
AnsiPainter::_replaceSpecialStrings('&lt;&gt;&quot;&sp;&amp;').should.equal '<>" &'
+16
View File
@@ -0,0 +1,16 @@
Layout = require '../src/Layout'
describe "Layout", ->
describe "constructor()", ->
it "should create root block", ->
l = new Layout
expect(l._root).to.exist
l._root._name.should.equal '__root'
describe "get()", ->
it "should not be allowed when any block is open", ->
l = new Layout
l.openBlock()
(->
l.get()
).should.throw Error
+273
View File
@@ -0,0 +1,273 @@
RenderKid = require '../src/RenderKid'
{strip} = require '../src/AnsiPainter'
match = (input, expected, setStuff) ->
r = new RenderKid
r.style
span:
display: 'inline'
div:
display: 'block'
setStuff?(r)
strip(r.render(input)).trim().should.equal expected.trim()
describe "RenderKid", ->
describe "constructor()", ->
it "should work", ->
new RenderKid
describe "whitespace management - inline", ->
it "shouldn't put extra whitespaces", ->
input = """
a<span>b</span>c
"""
expected = """
abc
"""
match input, expected
it "should allow 1 whitespace character on each side", ->
input = """
a<span> b </span>c
"""
expected = """
a b c
"""
match input, expected
it "should eliminate extra whitespaces inside text", ->
input = """
a<span>b1 \n b2</span>c
"""
expected = """
ab1 b2c
"""
match input, expected
it "should allow line breaks with <br />", ->
input = """
a<span>b1<br />b2</span>c
"""
expected = """
ab1\nb2c
"""
match input, expected
it "should allow line breaks with &nl;", ->
input = """
a<span>b1&nl;b2</span>c
"""
expected = """
ab1\nb2c
"""
match input, expected
it "should allow whitespaces with &sp;", ->
input = """
a<span>b1&sp;b2</span>c
"""
expected = """
ab1 b2c
"""
match input, expected
describe "whitespace management - block", ->
it "should add one linebreak between two blocks", ->
input = """
<div>a</div>
<div>b</div>
"""
expected = """
a
b
"""
match input, expected
it "should ignore empty blocks", ->
input = """
<div>a</div>
<div></div>
<div>b</div>
"""
expected = """
a
b
"""
match input, expected
it "should add an extra linebreak between two adjacent blocks inside an inline", ->
input = """
<span>
<div>a</div>
<div>b</div>
</span>
"""
expected = """
a
b
"""
match input, expected
it "example: div(marginBottom:1)+div", ->
input = """
<div class="first">a</div>
<div>b</div>
"""
expected = """
a
b
"""
match input, expected, (r) ->
r.style '.first': marginBottom: 1
it "example: div+div(marginTop:1)", ->
input = """
<div>a</div>
<div class="second">b</div>
"""
expected = """
a
b
"""
match input, expected, (r) ->
r.style '.second': marginTop: 1
it "example: div(marginBottom:1)+div(marginTop:1)", ->
input = """
<div class="first">a</div>
<div class="second">b</div>
"""
expected = """
a
b
"""
match input, expected, (r) ->
r.style
'.first': marginBottom: 1
'.second': marginTop: 1
it "example: div(marginBottom:2)+div(marginTop:1)", ->
input = """
<div class="first">a</div>
<div class="second">b</div>
"""
expected = """
a
b
"""
match input, expected, (r) ->
r.style
'.first': marginBottom: 2
'.second': marginTop: 1
it "example: div(marginBottom:2)+span+div(marginTop:1)", ->
input = """
<div class="first">a</div>
<span>span</span>
<div class="second">b</div>
"""
expected = """
a
span
b
"""
match input, expected, (r) ->
r.style
'.first': marginBottom: 2
'.second': marginTop: 1
+312
View File
@@ -0,0 +1,312 @@
Layout = require '../../src/Layout'
{object} = require 'utila'
{open, get, conf} = do ->
show = (layout) ->
got = layout.get()
got = got.replace /<[^>]+>/g, ''
defaultBlockConfig =
linePrependor: options: amount: 2
c = (add = {}) ->
object.append defaultBlockConfig, add
ret = {}
ret.open = (block, name, top = 0, bottom = 0) ->
config = c
blockPrependor: options: amount: top
blockAppendor: options: amount: bottom
b = block.openBlock config, name
b.write name + ' | top ' + top + ' bottom ' + bottom
b
ret.get = (layout) ->
layout.get().replace(/<[^>]+>/g, '')
ret.conf = (props) ->
config = {}
if props.left?
object.appendOnto config, linePrependor: options: amount: props.left
if props.right?
object.appendOnto config, lineAppendor: options: amount: props.right
if props.top?
object.appendOnto config, blockPrependor: options: amount: props.top
if props.bottom?
object.appendOnto config, blockAppendor: options: amount: props.bottom
if props.width?
object.appendOnto config, width: props.width
if props.bullet is yes
object.appendOnto config, linePrependor: options: bullet: {char: '-', alignment: 'left'}
config
ret
describe "Layout", ->
describe "inline inputs", ->
it "should be merged", ->
l = new Layout
l.write 'a'
l.write 'b'
get(l).should.equal 'ab'
it "should be correctly wrapped", ->
l = new Layout
block = l.openBlock conf width: 20
block.write '123456789012345678901234567890'
block.close()
get(l).should.equal '12345678901234567890\n1234567890'
it "should trim from left when wrapping to a new line", ->
l = new Layout
block = l.openBlock conf width: 20
block.write '12345678901234567890 \t 123456789012345678901'
block.close()
get(l).should.equal '12345678901234567890\n12345678901234567890\n1'
it "should handle line breaks correctly", ->
l = new Layout
block = l.openBlock conf width: 20
block.write '\na\n\nb\n'
block.close()
get(l).should.equal '\na\n\nb\n'
it "should not put extra line breaks when a line is already broken", ->
l = new Layout
block = l.openBlock conf width: 20
block.write '01234567890123456789\n0123456789'
block.close()
get(l).should.equal '01234567890123456789\n0123456789'
describe "horizontal margins", ->
it "should account for left margins", ->
l = new Layout
block = l.openBlock conf width: 20, left: 2
block.write '01'
block.close()
get(l).should.equal ' 01'
it "should account for right margins", ->
l = new Layout
block = l.openBlock conf width: 20, right: 2
block.write '01'
block.close()
get(l).should.equal '01 '
it "should account for both margins", ->
l = new Layout
block = l.openBlock conf width: 20, right: 2, left: 1
block.write '01'
block.close()
get(l).should.equal ' 01 '
it "should break lines according to left margins", ->
l = new Layout
global.tick = yes
block = l.openBlock conf width: 20, left: 2
block.write '01234567890123456789'
block.close()
global.tick = no
get(l).should.equal ' 01234567890123456789'
it "should break lines according to right margins", ->
l = new Layout
block = l.openBlock conf width: 20, right: 2
block.write '01234567890123456789'
block.close()
get(l).should.equal '01234567890123456789 '
it "should break lines according to both margins", ->
l = new Layout
block = l.openBlock conf width: 20, right: 2, left: 1
block.write '01234567890123456789'
block.close()
get(l).should.equal ' 01234567890123456789 '
it "should break lines according to terminal width", ->
l = new Layout terminalWidth: 20
block = l.openBlock conf right: 2, left: 1
block.write '01234567890123456789'
block.close()
# Note: We don't expect ' 01234567890123456 \n 789 ',
# since the first line (' 01234567890123456 ') is a full line
# according to layout.config.terminalWidth and doesn't need
# a break line.
get(l).should.equal ' 01234567890123456 789 '
describe "lines and blocks", ->
it "should put one break line between: line, block", ->
l = new Layout
l.write 'a'
l.openBlock().write('b').close()
get(l).should.equal 'a\nb'
it "should put one break line between: block, line", ->
l = new Layout
l.openBlock().write('a').close()
l.write 'b'
get(l).should.equal 'a\nb'
it "should put one break line between: line, block, line", ->
l = new Layout
l.write 'a'
l.openBlock().write('b').close()
l.write 'c'
get(l).should.equal 'a\nb\nc'
it "margin top should work for: line, block", ->
l = new Layout
l.write 'a'
l.openBlock(conf top: 2).write('b').close()
get(l).should.equal 'a\n\n\nb'
it "margin top should work for: block, line", ->
l = new Layout
l.openBlock(conf top: 1).write('a').close()
l.write 'b'
get(l).should.equal '\na\nb'
it "margin top should work for: block, line, when block starts with a break", ->
l = new Layout
l.openBlock(conf top: 1).write('\na').close()
l.write 'b'
get(l).should.equal '\n\na\nb'
it "margin top should work for: line, block, when line ends with a break", ->
l = new Layout
l.write 'a\n'
l.openBlock(conf top: 1).write('b').close()
get(l).should.equal 'a\n\n\nb'
it "margin top should work for: line, block, when there are two breaks in between", ->
l = new Layout
l.write 'a\n'
l.openBlock(conf top: 1).write('\nb').close()
get(l).should.equal 'a\n\n\n\nb'
it "margin bottom should work for: line, block", ->
l = new Layout
l.write 'a'
l.openBlock(conf bottom: 1).write('b').close()
get(l).should.equal 'a\nb\n'
it "margin bottom should work for: block, line", ->
l = new Layout
l.openBlock(conf bottom: 1).write('a').close()
l.write 'b'
get(l).should.equal 'a\n\nb'
it "margin bottom should work for: block, line, when block ends with a break", ->
l = new Layout
l.openBlock(conf bottom: 1).write('a\n').close()
l.write 'b'
get(l).should.equal 'a\n\n\nb'
it "margin bottom should work for: block, line, when line starts with a break", ->
l = new Layout
l.openBlock(conf bottom: 1).write('a').close()
l.write '\nb'
get(l).should.equal 'a\n\n\nb'
it "margin bottom should work for: block, line, when there are two breaks in between", ->
l = new Layout
l.openBlock(conf bottom: 1).write('a\n').close()
l.write '\nb'
get(l).should.equal 'a\n\n\n\nb'
describe "blocks and blocks", ->
it "should not get extra break lines for full-width lines", ->
l = new Layout
l.openBlock(conf width: 20).write('01234567890123456789').close()
l.openBlock().write('b').close()
get(l).should.equal '01234567890123456789\nb'
it "should not get extra break lines for full-width lines followed by a margin", ->
l = new Layout
l.openBlock(conf width: 20, bottom: 1).write('01234567890123456789').close()
l.openBlock().write('b').close()
get(l).should.equal '01234567890123456789\n\nb'
it "a(top: 0, bottom: 0) b(top: 0, bottom: 0)", ->
l = new Layout
l.openBlock().write('a').close()
l.openBlock().write('b').close()
get(l).should.equal 'a\nb'
it "a(top: 0, bottom: 0) b(top: 1, bottom: 0)", ->
l = new Layout
l.openBlock().write('a').close()
l.openBlock(conf(top: 1)).write('b').close()
get(l).should.equal 'a\n\nb'
it "a(top: 0, bottom: 1) b(top: 0, bottom: 0)", ->
l = new Layout
l.openBlock(conf(bottom: 1)).write('a').close()
l.openBlock().write('b').close()
get(l).should.equal 'a\n\nb'
it "a(top: 0, bottom: 1 ) b( top: 1, bottom: 0)", ->
l = new Layout
l.openBlock(conf(bottom: 1)).write('a').close()
l.openBlock(conf(top: 1)).write('b').close()
get(l).should.equal 'a\n\n\nb'
it "a(top: 0, bottom: 1 br) b(br top: 1, bottom: 0)", ->
l = new Layout
l.openBlock(conf(bottom: 1)).write('a\n').close()
l.openBlock(conf(top: 1)).write('\nb').close()
get(l).should.equal 'a\n\n\n\n\nb'
it "a(top: 2, bottom: 3 a1-br-a2) b(br-b1-br-br-b2-br top: 2, bottom: 3)", ->
l = new Layout
l.openBlock(conf(top: 2, bottom: 3)).write('a1\na2').close()
l.openBlock(conf(top: 2, bottom: 3)).write('\nb1\n\nb2\n').close()
get(l).should.equal '\n\na1\na2\n\n\n\n\n\n\nb1\n\nb2\n\n\n\n'
describe "nesting", ->
it "should break one line for nested blocks", ->
l = new Layout
l.write 'a'
b = l.openBlock()
c = b.openBlock().write('c').close()
b.close()
get(l).should.equal 'a\nc'
it "a(left: 2) > b(top: 2)", ->
l = new Layout
a = l.openBlock(conf(left: 2))
a.openBlock(conf(top: 2)).write('b').close()
a.close()
get(l).should.equal ' \n \n b'
it "a(left: 2) > b(bottom: 2)", ->
l = new Layout
a = l.openBlock(conf(left: 2))
a.openBlock(conf(bottom: 2)).write('b').close()
a.close()
get(l).should.equal ' b\n \n '
describe "bullets", ->
it "basic bullet", ->
l = new Layout
l.openBlock(conf(left: 3, bullet: yes)).write('a').close()
get(l).should.equal '- a'
it "a(left: 3, bullet) > b(top:1)", ->
l = new Layout
a = l.openBlock(conf(left: 3, bullet: yes))
b = a.openBlock(conf(top: 1)).write('b').close()
a.close()
get(l).should.equal '- \n b'
+82
View File
@@ -0,0 +1,82 @@
S = require '../../src/layout/SpecialString'
describe "SpecialString", ->
describe 'SpecialString()', ->
it 'should return instance', ->
S('s').should.be.instanceOf S
describe 'length()', ->
it 'should return correct length for normal text', ->
S('hello').length.should.equal 5
it 'should return correct length for text containing tabs and tags', ->
S('<a>he<you />l\tlo</a>').length.should.equal 13
it "shouldn't count empty tags as tags", ->
S('<>><').length.should.equal 4
it "should count length of single tag as 0", ->
S('<html>').length.should.equal 0
it "should work correctly with html quoted characters", ->
S(' &gt;&lt; &sp;').length.should.equal 5
describe 'splitIn()', ->
it "should work correctly with normal text", ->
S("123456").splitIn(3).should.be.like ['123', '456']
it "should work correctly with normal text containing tabs and tags", ->
S("12\t3<hello>456").splitIn(3).should.be.like ['12', '\t', '3<hello>45', '6']
it "should not trimLeft all lines when trimLeft is no", ->
S('abc def').splitIn(3).should.be.like ['abc', ' de', 'f']
it "should trimLeft all lines when trimLeft is true", ->
S('abc def').splitIn(3, yes).should.be.like ['abc', 'def']
describe 'cut()', ->
it "should work correctly with text containing tabs and tags", ->
original = S("12\t3<hello>456")
cut = original.cut(2, 3)
original.str.should.equal '123<hello>456'
cut.str.should.equal '\t'
it "should trim left when trimLeft is true", ->
original = S ' 132'
cut = original.cut 0, 1, yes
original.str.should.equal '32'
cut.str.should.equal '1'
it "should be greedy", ->
S("ab<tag>a").cut(0, 2).str.should.equal "ab<tag>"
describe 'isOnlySpecialChars()', ->
it "should work", ->
S("12\t3<hello>456").isOnlySpecialChars().should.equal no
S("<hello>").isOnlySpecialChars().should.equal yes
describe 'clone()', ->
it "should return independent instance", ->
a = S('hello')
b = a.clone()
a.str.should.equal b.str
a.should.not.equal b
describe 'trim()', ->
it "should return an independent instance", ->
s = S('')
s.trim().should.not.equal s
it 'should return the same string when trim is not required', ->
S('hello').trim().str.should.equal 'hello'
it 'should return trimmed string', ->
S(' hello').trim().str.should.equal 'hello'
describe 'trimLeft()', ->
it "should only trim on the left", ->
S(' hello ').trimLeft().str.should.equal 'hello '
describe 'trimRight()', ->
it "should only trim on the right", ->
S(' hello ').trimRight().str.should.equal ' hello'
+6
View File
@@ -0,0 +1,6 @@
--compilers coffee:coffee-script/register
--recursive
--reporter mocha-pretty-spec-reporter
--ui bdd
--timeout 20000
--require ./test/mochaHelpers.coffee
+10
View File
@@ -0,0 +1,10 @@
chai = require('chai')
chai
.use(require 'chai-fuzzy')
.use(require 'chai-changes')
.use(require 'sinon-chai')
.should()
global.expect = chai.expect
global.sinon = require 'sinon'
+7
View File
@@ -0,0 +1,7 @@
StyleSheet = require '../../../src/renderKid/styles/StyleSheet'
describe "StyleSheet", ->
describe "normalizeSelector()", ->
it 'should remove unnecessary spaces', ->
StyleSheet.normalizeSelector(' body+a s > a ')
.should.equal 'body+a s>a'
+19
View File
@@ -0,0 +1,19 @@
tools = require '../src/tools'
describe "tools", ->
describe "quote()", ->
it "should convert html special strings to their entities", ->
tools.quote(" abc<>\"\n")
.should.equal '&sp;abc&lt;&gt;&quot;<br />'
describe "stringToDom()", ->
it "should work", ->
tools.stringToDom('<a> text<a1>text</a1> text <a2>text</a2><a3>text</a3>text</a>text')
describe "objectToDom()", ->
it "should work", ->
tools.objectToDom({a: 'text'})
it "should have quoted text nodes", ->
tools.objectToDom({a: '&<> "'})[0].children[0]
.data.should.equal '&amp;&lt;&gt;&sp;&quot;'