Added logging, changed some directory structure

This commit is contained in:
2018-01-13 21:33:40 -05:00
parent f079a5f067
commit 8e72ffb917
73656 changed files with 35284 additions and 53718 deletions

View File

@@ -0,0 +1,16 @@
*.bat
.htaccess
src/
node_modules
pg
-p
npm-debug.log
!*.gitkeep
xeno
sass
.sass-cache

View File

@@ -0,0 +1,6 @@
language: node_js
node_js:
- 0.10
sudo: false

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.

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

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("Unkown 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;
})();

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();
}

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;
})();

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("Unkown 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("Unkown bg color `" + str + "`");
}
return "\x1B[" + code + "m";
};
styles.none = function(str) {
return "\x1B[" + codes.none + "m";
};

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
};
}

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;
})();

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();
}

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'));

View File

@@ -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;
})();

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'));

View File

@@ -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;
})();

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'));

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;
})();

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("Unkown alignment `" + alignment + "`");
}
}
output = addToLeft + char + addToRight;
} else {
output = self.pad(this._config.amount);
}
return inherited + output;
};
return DefaultLinePrependor;
})(require('./_LinePrependor'));

View File

@@ -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;
})();

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'));

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;
})();

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;
})();

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("Unkown color `" + style.color + "`");
}
tagsToAdd.push(tagName);
}
if (style.background != null) {
tagName = 'bg-' + style.background;
if (AnsiPainter.tags[tagName] == null) {
throw Error("Unkown 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;
}
};

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;
}
}
};

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;
}
};

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;
})();

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;
})();

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("Unkown 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')
};

View File

@@ -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;
})();

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;
})();

View File

@@ -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);

View File

@@ -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);

View File

@@ -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);

View File

@@ -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);

View File

@@ -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);

View File

@@ -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);

View File

@@ -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);

View File

@@ -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);

View File

@@ -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);

View File

@@ -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);

View File

@@ -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);

View File

@@ -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);

View File

@@ -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);

View File

@@ -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);

View File

@@ -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);

View File

@@ -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);

View File

@@ -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);

View File

@@ -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;
})();

View File

@@ -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);

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 && process.stdout.rows) {
return process.stdout.rows;
}
}
} catch (_error) {}
})();
if (typeof cols === 'number' && cols > 30) {
return cols;
} else {
return 80;
}
}
};

View File

@@ -0,0 +1,10 @@
*.bat
.htaccess
xeno/**
node_modules
-p
npm-debug.log
!*.gitkeep

View File

@@ -0,0 +1,86 @@
exec = require('child_process').exec
fs = require 'fs'
sysPath = require 'path'
task 'compile:coffee', ->
unless fs.existsSync './scripts/js'
fs.mkdirSync './scripts/js'
exec 'node ./node_modules/coffee-script/bin/coffee -bco ./scripts/js ./scripts/coffee',
(error) ->
if fs.existsSync '-p'
fs.rmdirSync '-p'
if error?
console.log 'Compile failed: ' + error
return
task 'build', ->
invoke 'compile:coffee'
# This is in place until we replace the test suite runner with popo
task 'test', ->
runTestsIn 'scripts/coffee/test', '_prepare.coffee'
runInCoffee = (path, cb) ->
exec 'node ./node_modules/coffee-script/bin/coffee ' + path, cb
runTestsIn = (shortPath, except) ->
fullPath = sysPath.resolve shortPath
fs.readdir fullPath, (err, files) ->
if err then throw Error err
for file in files
return if file is except
fullFilePath = sysPath.resolve(fullPath, file)
shortFilePath = shortPath + '/' + file
if sysPath.extname(file) is '.coffee'
runAsTest shortFilePath, fullFilePath
else if fs.statSync(fullFilePath).isDirectory()
runTestsIn shortFilePath
return
didBeep = no
runAsTest = (shortPath, fullPath) ->
runInCoffee fullPath, (error, stdout, stderr) ->
output = 'Running ' + shortPath + '\n'
if stderr
unless didBeep
`console.log("\007")`
didBeep = yes
output += 'Error\n' + stdout + stderr + '\n'
else if stdout
output += '\n' + stdout
console.log output

View File

@@ -0,0 +1,7 @@
notareplacementforunderscore
# Installation
**npm**: `npm install utila`
**bower**: available via bower as in `bower install utila`, but you should run `npm install` before you can use it.

View File

@@ -0,0 +1,58 @@
{
"_args": [
[
"utila@0.3.3",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_from": "utila@0.3.3",
"_id": "utila@0.3.3",
"_inBundle": false,
"_integrity": "sha1-1+jn1+MJEHCSsF+NloiCTWM6QiY=",
"_location": "/react-scripts/renderkid/utila",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "utila@0.3.3",
"name": "utila",
"escapedName": "utila",
"rawSpec": "0.3.3",
"saveSpec": null,
"fetchSpec": "0.3.3"
},
"_requiredBy": [
"/react-scripts/renderkid"
],
"_resolved": "https://registry.npmjs.org/utila/-/utila-0.3.3.tgz",
"_spec": "0.3.3",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"author": {
"name": "Aria Minaei"
},
"bugs": {
"url": "https://github.com/AriaMinaei/utila/issues"
},
"dependencies": {},
"description": "notareplacementforunderscore",
"devDependencies": {
"coffee-script": "~1.6.3",
"little-popo": "~0.1"
},
"homepage": "https://github.com/AriaMinaei/utila#readme",
"keywords": [
"utilities"
],
"license": "MIT",
"main": "scripts/js/lib/utila.js",
"name": "utila",
"repository": {
"type": "git",
"url": "git+https://github.com/AriaMinaei/utila.git"
},
"scripts": {
"prepublish": "node ./node_modules/coffee-script/bin/cake build",
"test": "node ./node_modules/coffee-script/bin/cake test"
},
"version": "0.3.3"
}

View File

@@ -0,0 +1,145 @@
array = require './array'
module.exports = class Emitter
constructor: ->
@_listeners = {}
@_listenersForAnyEvent = []
@_disabledEmitters = {}
on: (eventName, listener) ->
unless @_listeners[eventName]?
@_listeners[eventName] = []
@_listeners[eventName].push listener
@
once: (eventName, listener) ->
ran = no
cb = =>
return if ran
ran = yes
do listener
setTimeout =>
@removeEvent eventName, cb
, 0
@on eventName, cb
@
onAnyEvent: (listener) ->
@_listenersForAnyEvent.push listener
@
removeEvent: (eventName, listener) ->
return @ unless @_listeners[eventName]?
array.pluckOneItem @_listeners[eventName], listener
@
removeListeners: (eventName) ->
return @ unless @_listeners[eventName]?
@_listeners[eventName].length = 0
@
removeAllListeners: ->
for name, listeners of @_listeners
listeners.length = 0
@
_emit: (eventName, data) ->
for listener in @_listenersForAnyEvent
listener.call @, data, eventName
return unless @_listeners[eventName]?
for listener in @_listeners[eventName]
listener.call @, data
return
# this makes sure that all the calls to this class's method 'fnName'
# are throttled
_throttleEmitterMethod: (fnName, time = 1000) ->
originalFn = @[fnName]
if typeof originalFn isnt 'function'
throw Error "this class does not have a method called '#{fnName}'"
lastCallArgs = null
pending = no
timer = null
@[fnName] = =>
lastCallArgs = arguments
do pend
pend = =>
if pending
clearTimeout timer
timer = setTimeout runIt, time
pending = yes
runIt = =>
pending = no
originalFn.apply @, lastCallArgs
_disableEmitter: (fnName) ->
if @_disabledEmitters[fnName]?
throw Error "#{fnName} is already a disabled emitter"
@_disabledEmitters[fnName] = @[fnName]
@[fnName] = ->
_enableEmitter: (fnName) ->
fn = @_disabledEmitters[fnName]
unless fn?
throw Error "#{fnName} is not a disabled emitter"
@[fnName] = fn
delete @_disabledEmitters[fnName]

View File

@@ -0,0 +1,99 @@
module.exports = common =
###
Checks to see if o is an object, and it isn't an instance
of some class.
###
isBareObject: (o) ->
if o? and o.constructor is Object
return true
false
###
Returns type of an object, including:
undefined, null, string, number, array,
arguments, element, textnode, whitespace, and object
###
typeOf: (item) ->
return 'null' if item is null
return typeof item if typeof item isnt 'object'
return 'array' if Array.isArray item
# From MooTools
# - do we even need this?
if item.nodeName
if item.nodeType is 1 then return 'element'
if item.nodeType is 3 then return (/\S/).test(item.nodeValue) ? 'textnode' : 'whitespace'
else if typeof item.length is 'number'
if item.callee then return 'arguments'
return typeof item
# Deep clone of any variable.
# From MooTools
clone: (item, includePrototype = false) ->
switch common.typeOf item
when 'array' then return common._cloneArray item, includePrototype
when 'object' then return common._cloneObject item, includePrototype
else return item
###
Deep clone of an object.
From MooTools
###
_cloneObject: (o, includePrototype = false) ->
if common.isBareObject o
clone = {}
for key of o
clone[key] = common.clone o[key], includePrototype
return clone
else
return o unless includePrototype
return o if o instanceof Function
clone = Object.create o.constructor.prototype
for key of o
if o.hasOwnProperty key
clone[key] = common.clone o[key], includePrototype
clone
###
Deep clone of an array.
From MooTools
###
_cloneArray: (a, includePrototype = false) ->
i = a.length
clone = new Array i
while i--
clone[i] = common.clone a[i], includePrototype
clone

View File

@@ -0,0 +1,186 @@
module.exports = array =
###
Tries to turn anything into an array.
###
from: (r) ->
Array::slice.call r
###
Clone of an array. Properties will be shallow copies.
###
simpleClone: (a) ->
a.slice 0
shallowEqual: (a1, a2) ->
return no unless Array.isArray(a1) and Array.isArray(a2) and a1.length is a2.length
for val, i in a1
return no unless a2[i] is val
yes
pluck: (a, i) ->
return a if a.length < 1
for value, index in a
if index > i
a[index - 1] = a[index]
a.length = a.length - 1
a
pluckItem: (a, item) ->
return a if a.length < 1
removed = 0
for value, index in a
if value is item
removed++
continue
if removed isnt 0
a[index - removed] = a[index]
a.length = a.length - removed if removed > 0
a
pluckOneItem: (a, item) ->
return a if a.length < 1
reached = no
for value, index in a
if not reached
if value is item
reached = yes
continue
else
a[index - 1] = a[index]
a.length = a.length - 1 if reached
a
pluckByCallback: (a, cb) ->
return a if a.length < 1
removed = 0
for value, index in a
if cb value, index
removed++
continue
if removed isnt 0
a[index - removed] = a[index]
if removed > 0
a.length = a.length - removed
a
pluckMultiple: (array, indexesToRemove) ->
return array if array.length < 1
removedSoFar = 0
indexesToRemove.sort()
for i in indexesToRemove
@pluck array, i - removedSoFar
removedSoFar++
array
injectByCallback: (a, toInject, shouldInject) ->
valA = null
valB = null
len = a.length
if len < 1
a.push toInject
return a
for val, i in a
valA = valB
valB = val
if shouldInject valA, valB, toInject
return a.splice i, 0, toInject
a.push toInject
a
injectInIndex: (a, index, toInject) ->
len = a.length
i = index
if len < 1
a.push toInject
return a
toPut = toInject
toPutNext = null
`for(; i <= len; i++){
toPutNext = a[i];
a[i] = toPut;
toPut = toPutNext;
}`
# a[i] = toPut
null

View File

@@ -0,0 +1,87 @@
module.exports = classic = {}
# Little helper for mixins from CoffeeScript FAQ,
# courtesy of Sethaurus (http://github.com/sethaurus)
classic.implement = (mixins..., classReference) ->
for mixin in mixins
classProto = classReference::
for member of mixin::
unless Object.getOwnPropertyDescriptor classProto, member
desc = Object.getOwnPropertyDescriptor mixin::, member
Object.defineProperty classProto, member, desc
classReference
classic.mix = (mixins..., classReference) ->
classProto = classReference::
classReference.__mixinCloners = []
classReference.__applyClonersFor = (instance, args = null) ->
for cloner in classReference.__mixinCloners
cloner.apply instance, args
return
classReference.__mixinInitializers = []
classReference.__initMixinsFor = (instance, args = null) ->
for initializer in classReference.__mixinInitializers
initializer.apply instance, args
return
classReference.__mixinQuitters = []
classReference.__applyQuittersFor = (instance, args = null) ->
for quitter in classReference.__mixinQuitters
quitter.apply instance, args
return
for mixin in mixins
unless mixin.constructor instanceof Function
throw Error "Mixin should be a function"
for member of mixin::
if member.substr(0, 11) is '__initMixin'
classReference.__mixinInitializers.push mixin::[member]
continue
else if member.substr(0, 11) is '__clonerFor'
classReference.__mixinCloners.push mixin::[member]
continue
else if member.substr(0, 12) is '__quitterFor'
classReference.__mixinQuitters.push mixin::[member]
continue
unless Object.getOwnPropertyDescriptor classProto, member
desc = Object.getOwnPropertyDescriptor mixin::, member
Object.defineProperty classProto, member, desc
classReference

View File

@@ -0,0 +1,170 @@
_common = require './_common'
module.exports = object =
isBareObject: _common.isBareObject.bind _common
###
if object is an instance of a class
###
isInstance: (what) ->
not @isBareObject what
###
Alias to _common.typeOf
###
typeOf: _common.typeOf.bind _common
###
Alias to _common.clone
###
clone: _common.clone.bind _common
###
Empties an object of its properties.
###
empty: (o) ->
for prop of o
delete o[prop] if o.hasOwnProperty prop
o
###
Empties an object. Doesn't check for hasOwnProperty, so it's a tiny
bit faster. Use it for plain objects.
###
fastEmpty: (o) ->
delete o[property] for property of o
o
###
Overrides values fomr `newValues` on `base`, as long as they
already exist in base.
###
overrideOnto: (base, newValues) ->
return base if not @isBareObject(newValues) or not @isBareObject(base)
for key, oldVal of base
newVal = newValues[key]
continue if newVal is undefined
if typeof newVal isnt 'object' or @isInstance newVal
base[key] = @clone newVal
# newVal is a plain object
else
if typeof oldVal isnt 'object' or @isInstance oldVal
base[key] = @clone newVal
else
@overrideOnto oldVal, newVal
base
###
Takes a clone of 'base' and runs #overrideOnto on it
###
override: (base, newValues) ->
@overrideOnto @clone(base), newValues
append: (base, toAppend) ->
@appendOnto @clone(base), toAppend
# Deep appends values from `toAppend` to `base`
appendOnto: (base, toAppend) ->
return base if not @isBareObject(toAppend) or not @isBareObject(base)
for own key, newVal of toAppend
continue unless newVal isnt undefined
if typeof newVal isnt 'object' or @isInstance newVal
base[key] = newVal
else
# newVal is a bare object
oldVal = base[key]
if typeof oldVal isnt 'object' or @isInstance oldVal
base[key] = @clone newVal
else
@appendOnto oldVal, newVal
base
# Groups
groupProps: (obj, groups) ->
grouped = {}
for name, defs of groups
grouped[name] = {}
grouped['rest'] = {}
`top: //`
for key, val of obj
shouldAdd = no
for name, defs of groups
unless Array.isArray defs
defs = [defs]
for def in defs
if typeof def is 'string'
if key is def
shouldAdd = yes
else if def instanceof RegExp
if def.test key
shouldAdd = yes
else if def instanceof Function
if def key
shouldAdd = yes
else
throw Error 'Group definitions must either
be strings, regexes, or functions.'
if shouldAdd
grouped[name][key] = val
`continue top`
grouped['rest'][key] = val
grouped

View File

@@ -0,0 +1,16 @@
module.exports =
# pads a number with leading zeroes
#
# http://stackoverflow.com/a/10073788/607997
pad: (n, width, z = '0') ->
n = n + ''
if n.length >= width
n
else
new Array(width - n.length + 1).join(z) + n

View File

@@ -0,0 +1,7 @@
module.exports = utila =
array: require './array'
classic: require './classic'
object: require './object'
string: require './string'
Emitter: require './Emitter'

View File

@@ -0,0 +1,5 @@
path = require 'path'
pathToLib = path.resolve __dirname, '../lib'
require('little-popo')(pathToLib)

View File

@@ -0,0 +1,143 @@
require './_prepare'
array = mod 'array'
test 'from', ->
array.from([1]).should.be.an.instanceOf Array
array.from([1])[0].should.equal 1
# test 'clone', ->
# a = [0, 1, 2]
# b = array.clone a
# b[0].should.equal 0
# b[1].should.equal 1
# b[0] = 3
# a[0].should.equal 0
test 'pluck', ->
a = [0, 1, 2, 3]
after = array.pluck a, 1
after.length.should.equal 3
after[0].should.equal 0
after[1].should.equal 2
after[2].should.equal 3
after.should.equal a
test 'pluckMultiple', ->
a = [0, 1, 2, 3, 4, 5, 6]
array.pluckMultiple a, [0, 4, 2, 6]
a.length.should.equal 3
a[0].should.equal 1
a[1].should.equal 3
a[2].should.equal 5
test 'pluckItem', ->
a = [0, 1, 2, 3, 2, 4, 2]
array.pluckItem a, 2
a[0].should.equal 0
a[1].should.equal 1
a[2].should.equal 3
a[3].should.equal 4
array.pluckItem([1], 2).length.should.equal 1
test 'pluckOneItem', ->
a = [0, 1, 2, 3, 2, 4, 2]
array.pluckOneItem a, 2
a[0].should.equal 0
a[1].should.equal 1
a[2].should.equal 3
a[3].should.equal 2
a[4].should.equal 4
a[5].should.equal 2
a = [1, 2]
array.pluckOneItem a, 1
a.length.should.equal 1
a[0].should.equal 2
array.pluckOneItem([], 1).length.should.equal 0
array.pluckOneItem([1], 2).length.should.equal 1
test 'plcukByCallback', ->
a = [0, 1, 2, 3]
array.pluckByCallback a, (val, i) ->
return yes if val is 2
return no
a[0].should.equal 0
a[1].should.equal 1
a[2].should.equal 3
test 'injectByCallback', ->
shouldInject = (valA, valB, toInject) ->
unless valA?
return yes if toInject <= valB
return no
unless valB?
return yes if valA <= toInject
return no
return yes if valA <= toInject <= valB
return no
a = [0.5, 1, 2.5, 2.5, 2.75, 2.75, 3]
array.injectByCallback a, 0, shouldInject
a[0].should.equal 0
a[1].should.equal 0.5
a[7].should.equal 3
a = [0.5, 1, 2.5, 2.5, 2.75, 2.75, 3]
array.injectByCallback a, 2.7, shouldInject
a[0].should.equal 0.5
a[4].should.equal 2.7
a[5].should.equal 2.75
a[7].should.equal 3
a = [0.5, 1, 2.5, 2.5, 2.75, 2.75, 3]
array.injectByCallback a, 3.2, shouldInject
a[0].should.equal 0.5
a[4].should.equal 2.75
a[6].should.equal 3
a[7].should.equal 3.2

View File

@@ -0,0 +1,233 @@
require './_prepare'
object = mod 'object'
test 'isBareObject', ->
object.isBareObject('a').should.equal false
object.isBareObject({'a': 'a'}).should.equal true
test 'typeOf', ->
object.typeOf('s').should.equal 'string'
object.typeOf(0).should.equal 'number'
object.typeOf(false).should.equal 'boolean'
object.typeOf({}).should.equal 'object'
object.typeOf(arguments).should.equal 'arguments'
object.typeOf([]).should.equal 'array'
test 'empty', ->
o =
a: 1
b: 2
object.empty o
o.should.not.have.property 'a'
o.should.not.have.property 'b'
test 'fastEmpty', ->
o =
a: 1
b: 2
object.fastEmpty o
o.should.not.have.property 'a'
o.should.not.have.property 'b'
test 'clone', ->
object.clone([1])[0].should.equal 1
object.clone({a:1}).a.should.equal 1
o = {a: 1}
object.clone(o).should.not.equal o
test 'clone [include prototype]', ->
class C
constructor: (@a) ->
sayA: -> @a + 'a'
a = new C 'a'
a.sayA().should.equal 'aa'
b = object.clone a, yes
b.should.not.equal a
b.constructor.should.equal C
b.a.should.equal 'a'
b.a = 'a2'
b.sayA().should.equal 'a2a'
test 'clone [without prototype]', ->
class C
constructor: (@a) ->
sayA: -> @a + 'a'
a = new C 'a'
a.sayA().should.equal 'aa'
b = object.clone a, no
b.should.equal a
test 'overrideOnto [basic]', ->
onto =
a: 'a'
b:
c: 'c'
d:
e: 'e'
what =
a: 'a2'
b:
c: 'c2'
d:
f: 'f2'
object.overrideOnto onto, what
onto.a.should.equal 'a2'
onto.b.should.have.property 'c'
onto.b.c.should.equal 'c2'
onto.b.d.should.not.have.property 'f'
onto.b.d.e.should.equal 'e'
test 'override', ->
onto =
a: 'a'
b:
c: 'c'
d:
e: 'e'
what =
a: 'a2'
b:
c: 'c2'
d:
f: 'f2'
onto2 = object.override onto, what
onto2.a.should.equal 'a2'
onto2.b.should.have.property 'c'
onto2.b.c.should.equal 'c2'
onto2.b.d.should.not.have.property 'f'
onto2.b.d.e.should.equal 'e'
onto.should.not.equal onto2
do ->
what =
a: 'a2'
c: ->
z: 'z'
y:
a: 'a'
onto =
a: 'a'
b: 'b'
test 'appendOnto [basic]', ->
object.appendOnto onto, what
onto.a.should.equal 'a2'
onto.b.should.equal 'b'
onto.z.should.equal 'z'
test "appendOnto [shallow copies instances]", ->
onto.c.should.be.instanceof Function
onto.c.should.equal what.c
test "appendOnto [clones objects]", ->
onto.should.have.property 'y'
onto.y.a.should.equal 'a'
onto.y.should.not.equal what.y
test 'groupProps', ->
obj =
a1: '1'
a2: '2'
b1: '1'
b2: '2'
c1: '1'
c2: '2'
rest1: '1'
rest2: '2'
groups = object.groupProps obj,
a: ['a1', 'a2']
b: [/^b[0-9]+$/]
c: (key) -> key[0] is 'c'
groups.a.should.have.property 'a1'
groups.a.a1.should.equal '1'
groups.a.should.have.property 'a2'
groups.b.should.have.property 'b1'
groups.b.should.have.property 'b2'
groups.c.should.have.property 'c1'
groups.c.should.have.property 'c2'
groups.rest.should.have.property 'rest1'
groups.rest.should.have.property 'rest1'
groups.rest.should.not.have.property 'c1'

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,74 @@
{
"_args": [
[
"renderkid@2.0.1",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_from": "renderkid@2.0.1",
"_id": "renderkid@2.0.1",
"_inBundle": false,
"_integrity": "sha1-iYyr/Ivt5Le5ETWj/9Mj5YwNsxk=",
"_location": "/react-scripts/renderkid",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "renderkid@2.0.1",
"name": "renderkid",
"escapedName": "renderkid",
"rawSpec": "2.0.1",
"saveSpec": null,
"fetchSpec": "2.0.1"
},
"_requiredBy": [
"/react-scripts/pretty-error"
],
"_resolved": "https://registry.npmjs.org/renderkid/-/renderkid-2.0.1.tgz",
"_spec": "2.0.1",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"author": {
"name": "Aria Minaei"
},
"bugs": {
"url": "https://github.com/AriaMinaei/RenderKid/issues"
},
"dependencies": {
"css-select": "^1.1.0",
"dom-converter": "~0.1",
"htmlparser2": "~3.3.0",
"strip-ansi": "^3.0.0",
"utila": "~0.3"
},
"description": "Stylish console.log for node",
"devDependencies": {
"chai": "^2.2.0",
"chai-changes": "^1.3.4",
"chai-fuzzy": "^1.5.0",
"coffee-script": "^1.9.1",
"jitter": "^1.3.0",
"mocha": "^2.0.1",
"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.1"
}

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 '<>" &'

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

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

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'

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'

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

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'

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'

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: '&<> "'}).should.have.deep
.property '[0].children[0].data', '&amp;&lt;&gt;&sp;&quot;'