<commit_before>var api = exports;

function nodeType(v){
	if(v.nodeType) return v.nodeType();
	if(typeof v=='string') return (v.substr(0,2)=='_:')?'BlankNode':'IRI';
	return 'TypedLiteral';
}
api.nodeType = nodeType;

function RDFNodeEquals(other) {
	if(nodeType(this)!=nodeType(other)) return false;
	switch(nodeType(this)) {
		case "IRI":
		case "BlankNode":
			return this.toString()==other.toString();
		case "PlainLiteral":
			return this.language==other.language && this.nominalValue==other.nominalValue;
		case "TypedLiteral":
			return this.type==other.type && this.nominalValue==other.nominalValue;
	}
	return this.toNT() == other.toNT();
}
api.RDFNodeEquals = RDFNodeEquals;

/**
* Implements Triple http://www.w3.org/TR/2011/WD-rdf-interfaces-20110510/#idl-def-Triple
*/
api.Triple = function Triple(s, p, o) { this.subject = s; this.predicate = p; this.object = o; };
api.Triple.prototype.size = 3;
api.Triple.prototype.length = 3;
api.Triple.prototype.toString = function() { return this.subject.toNT() + " " + this.predicate.toNT() + " " + this.object.toNT() + " ." }
api.Triple.prototype.equals = function(t) { return RDFNodeEquals.call(this.subject,t.subject) && RDFNodeEquals.call(this.predicate,t.predicate) && RDFNodeEquals.call(this.object,t.object) }

/**
 * Implements RDFNode http://www.w3.org/TR/2011/WD-rdf-interfaces-20110510/#idl-def-RDFNode
 */
api.RDFNode = function RDFNode() {};
api.RDFNode.prototype.equals = api.RDFNodeEquals = RDFNodeEquals;
api.RDFNode.prototype.nodeType = function() { return "RDFNode"; }
api.RDFNode.prototype.toNT = function() { return ""; }
api.RDFNode.prototype.toCanonical = function() { return this.toNT(); }
api.RDFNode.prototype.toString = function() { return this.nominalValue; }
api.RDFNode.prototype.valueOf = function() { return this.nominalValue; }
api.encodeString = function(s) {
	var out = "";
	var skip = false;
	var _g1 = 0, _g = s.length;
	while(_g1 < _g) {
		var i = _g1++;
		if(!skip) {
			var code = s.charCodeAt(i);
			if(55296 <= code && code <= 56319) {
				var low = s.charCodeAt(i + 1);
				code = (code - 55296) * 1024 + (low - 56320) + 65536;
				skip = true;
			}
			if(code > 1114111) { throw new Error("Char out of range"); }
			var hex = "00000000".concat((new Number(code)).toString(16).toUpperCase());
			if(code >= 65536) {
				out += "\\U" + hex.slice(-8);
			} else {
				if(code >= 127 || code <= 31) {
					switch(code) {
						case 9:	out += "\\t"; break;
						case 10: out += "\\n"; break;
						case 13: out += "\\r"; break;
						default: out += "\\u" + hex.slice(-4); break;
					}
				} else {
					switch(code) {
						case 34: out += '\\"'; break;
						case 92: out += "\\\\"; break;
						default: out += s.charAt(i); break;
					}
				}
			}
		} else {
			skip = !skip;
		}
	}
	return out;
}

/**
 * BlankNode
 */
api.BlankNode = function BlankNode(id) {
	if(typeof id=='string' && id.substr(0,2)=='_:') this.nominalValue=id.substr(2);
	else if(id) this.nominalValue=id;
	else this.nominalValue = 'b'+(++api.BlankNode.NextId).toString();
}
api.BlankNode.NextId = 0;
// Or maybe: Object.create(api.RDFNode.prototype, {constructor: {value: api.NamedNode, enumerable:false}});
api.BlankNode.prototype = new api.RDFNode;
api.BlankNode.prototype.nodeType = function() { return "BlankNode"; }
api.BlankNode.prototype.toNT = function() { return "_:"+this.nominalValue; }
api.BlankNode.prototype.n3 = function() { return this.toNT(); }
api.BlankNode.prototype.toString =  function() { return "_:"+this.nominalValue; }

/**
 * Implements Literal http://www.w3.org/TR/2011/WD-rdf-interfaces-20110510/#idl-def-Literal
 */
api.Literal = function Literal(value, language) {
	this.nominalValue = value;
	if(typeof language=="string" && language[0]=="@") this.language = language.slice(1);
	else if(typeof language=="string") this.datatype = language;
};
api.Literal.prototype = new api.RDFNode;
api.Literal.prototype.nodeType = function() {
	if(this.datatype) return "TypedLiteral";
	return "PlainLiteral";
}
api.Literal.prototype.toNT = function() {
	var string = '"'+api.encodeString(this.nominalValue)+'"';
	if(this.datatype) return string+'^^<'+this.datatype+">";
	if(this.language) return string+"@"+this.language;
	return string;
}
api.Literal.prototype.n3 = function() {
	return this.toNT();
}
api.Literal.prototype.valueOf = function() {
	if(this.datatype && typeof api.Literal.typeValueOf[this.datatype]=="function"){
		return api.Literal.typeValueOf[this.datatype](this.nominalValue, this.datatype);
	}
	return this.nominalValue;
}
api.Literal.typeValueOf = {};
api.Literal.registerTypeConversion = function(datatype, f){
	api.Literal.typeValueOf[datatype] = f;
}
require('./Default.js').loadDefaultTypeConverters(api.Literal);

/**
 * NamedNode
 */
api.NamedNode = function NamedNode(iri) { this.nominalValue = iri };
api.NamedNode.SCHEME_MATCH = new RegExp("^[a-z0-9-.+]+:", "i");
api.NamedNode.prototype = new api.RDFNode;
api.NamedNode.prototype.nodeType = function nodeType() { return "IRI" };
api.NamedNode.prototype.toNT = function toNT() { return "<" + api.encodeString(this.nominalValue) + ">"; };
api.NamedNode.prototype.n3 = function n3() { return this.toNT(); }
<commit_msg>Add comment to Literal#valueOf<commit_after>var api = exports;

function nodeType(v){
	if(v.nodeType) return v.nodeType();
	if(typeof v=='string') return (v.substr(0,2)=='_:')?'BlankNode':'IRI';
	return 'TypedLiteral';
}
api.nodeType = nodeType;

function RDFNodeEquals(other) {
	if(nodeType(this)!=nodeType(other)) return false;
	switch(nodeType(this)) {
		case "IRI":
		case "BlankNode":
			return this.toString()==other.toString();
		case "PlainLiteral":
			return this.language==other.language && this.nominalValue==other.nominalValue;
		case "TypedLiteral":
			return this.type==other.type && this.nominalValue==other.nominalValue;
	}
	return this.toNT() == other.toNT();
}
api.RDFNodeEquals = RDFNodeEquals;

/**
* Implements Triple http://www.w3.org/TR/2011/WD-rdf-interfaces-20110510/#idl-def-Triple
*/
api.Triple = function Triple(s, p, o) { this.subject = s; this.predicate = p; this.object = o; };
api.Triple.prototype.size = 3;
api.Triple.prototype.length = 3;
api.Triple.prototype.toString = function() { return this.subject.toNT() + " " + this.predicate.toNT() + " " + this.object.toNT() + " ." }
api.Triple.prototype.equals = function(t) { return RDFNodeEquals.call(this.subject,t.subject) && RDFNodeEquals.call(this.predicate,t.predicate) && RDFNodeEquals.call(this.object,t.object) }

/**
 * Implements RDFNode http://www.w3.org/TR/2011/WD-rdf-interfaces-20110510/#idl-def-RDFNode
 */
api.RDFNode = function RDFNode() {};
api.RDFNode.prototype.equals = api.RDFNodeEquals = RDFNodeEquals;
api.RDFNode.prototype.nodeType = function() { return "RDFNode"; }
api.RDFNode.prototype.toNT = function() { return ""; }
api.RDFNode.prototype.toCanonical = function() { return this.toNT(); }
api.RDFNode.prototype.toString = function() { return this.nominalValue; }
api.RDFNode.prototype.valueOf = function() { return this.nominalValue; }
api.encodeString = function(s) {
	var out = "";
	var skip = false;
	var _g1 = 0, _g = s.length;
	while(_g1 < _g) {
		var i = _g1++;
		if(!skip) {
			var code = s.charCodeAt(i);
			if(55296 <= code && code <= 56319) {
				var low = s.charCodeAt(i + 1);
				code = (code - 55296) * 1024 + (low - 56320) + 65536;
				skip = true;
			}
			if(code > 1114111) { throw new Error("Char out of range"); }
			var hex = "00000000".concat((new Number(code)).toString(16).toUpperCase());
			if(code >= 65536) {
				out += "\\U" + hex.slice(-8);
			} else {
				if(code >= 127 || code <= 31) {
					switch(code) {
						case 9:	out += "\\t"; break;
						case 10: out += "\\n"; break;
						case 13: out += "\\r"; break;
						default: out += "\\u" + hex.slice(-4); break;
					}
				} else {
					switch(code) {
						case 34: out += '\\"'; break;
						case 92: out += "\\\\"; break;
						default: out += s.charAt(i); break;
					}
				}
			}
		} else {
			skip = !skip;
		}
	}
	return out;
}

/**
 * BlankNode
 */
api.BlankNode = function BlankNode(id) {
	if(typeof id=='string' && id.substr(0,2)=='_:') this.nominalValue=id.substr(2);
	else if(id) this.nominalValue=id;
	else this.nominalValue = 'b'+(++api.BlankNode.NextId).toString();
}
api.BlankNode.NextId = 0;
// Or maybe: Object.create(api.RDFNode.prototype, {constructor: {value: api.NamedNode, enumerable:false}});
api.BlankNode.prototype = new api.RDFNode;
api.BlankNode.prototype.nodeType = function() { return "BlankNode"; }
api.BlankNode.prototype.toNT = function() { return "_:"+this.nominalValue; }
api.BlankNode.prototype.n3 = function() { return this.toNT(); }
api.BlankNode.prototype.toString =  function() { return "_:"+this.nominalValue; }

/**
 * Implements Literal http://www.w3.org/TR/2011/WD-rdf-interfaces-20110510/#idl-def-Literal
 */
api.Literal = function Literal(value, language) {
	this.nominalValue = value;
	if(typeof language=="string" && language[0]=="@") this.language = language.slice(1);
	else if(typeof language=="string") this.datatype = language;
};
api.Literal.prototype = new api.RDFNode;
api.Literal.prototype.nodeType = function() {
	if(this.datatype) return "TypedLiteral";
	return "PlainLiteral";
}
api.Literal.prototype.toNT = function() {
	var string = '"'+api.encodeString(this.nominalValue)+'"';
	if(this.datatype) return string+'^^<'+this.datatype+">";
	if(this.language) return string+"@"+this.language;
	return string;
}
api.Literal.prototype.n3 = function() {
	return this.toNT();
}
/**
 * Literal#valueOf returns a language-native value - e.g. a number, boolean, or Date where possible
 */
api.Literal.prototype.valueOf = function() {
	if(this.datatype && typeof api.Literal.typeValueOf[this.datatype]=="function"){
		return api.Literal.typeValueOf[this.datatype](this.nominalValue, this.datatype);
	}
	return this.nominalValue;
}
api.Literal.typeValueOf = {};
api.Literal.registerTypeConversion = function(datatype, f){
	api.Literal.typeValueOf[datatype] = f;
}
require('./Default.js').loadDefaultTypeConverters(api.Literal);

/**
 * NamedNode
 */
api.NamedNode = function NamedNode(iri) { this.nominalValue = iri };
api.NamedNode.SCHEME_MATCH = new RegExp("^[a-z0-9-.+]+:", "i");
api.NamedNode.prototype = new api.RDFNode;
api.NamedNode.prototype.nodeType = function nodeType() { return "IRI" };
api.NamedNode.prototype.toNT = function toNT() { return "<" + api.encodeString(this.nominalValue) + ">"; };
api.NamedNode.prototype.n3 = function n3() { return this.toNT(); }
<|endoftext|>


<commit_before>'use strict';

const StumbleCore = require('stumble-core');
const dequire = StumbleCore.dequire;
const Mumble = require('mumble');

const IO = require('./IO');
const isstdlib = require('./stdlibs');

module.exports = class Stumble extends StumbleCore {
  constructor (config) {
    super();

    this.client = null;
    this.config = config;
    this.io = new IO();
    this.space = new Map();

    let extensions = Object.keys(config.extensions || { system: true })
                            .filter(isstdlib);

    if (extensions.length) {
      extensions = extensions.map(extension => dequire(`./ext/${extension}`));
      if (extensions.length) this.use(extensions);
    }
  }

  observe (message, user) {
    this.emit('message', message, user);

    const operator = this.config.operator;

    if (operator && message.startsWith(operator)) {
      const pieces = message.substring(operator.length).split(' ');
      const handle = pieces.shift();

      if (this.commands.has(handle)) {
        const data = { user, message: pieces.join(' ') };
        this.invoke(handle, data);
      }
    }
  }

  connect () {
    const conf = this.config.mumble;
    const addr = `mumble://${conf.server}:${conf.port}`;

    Mumble.connect(addr, {}, (error, client) => {
      if (error) console.error(error);
      else {
        client.authenticate(conf.username, conf.password);
        client.on('ready', () => this.emit('ready'));
        client.on('message', (message, user) => this.observe(message, user));
        client.once('disconnect', () => this.disconnect(true));

        this.client = client;

        this.emit('connect');
      }
    });

    return this;
  }

  disconnect (evented) {
    if (this.client) {
      this.io.nullify('io');
      if (!evented) this.client.disconnect();
      this.client = null;
      this.emit('disconnect');
    }

    return this;
  }
};
<commit_msg>reordered client assignment, changed events<commit_after>'use strict';

const StumbleCore = require('stumble-core');
const dequire = StumbleCore.dequire;
const Mumble = require('mumble');

const IO = require('./IO');
const isstdlib = require('./stdlibs');

module.exports = class Stumble extends StumbleCore {
  constructor (config) {
    super();

    this.client = null;
    this.config = config;
    this.io = new IO();
    this.space = new Map();

    let extensions = Object.keys(config.extensions || { system: true })
                            .filter(isstdlib);

    if (extensions.length) {
      extensions = extensions.map(extension => dequire(`./ext/${extension}`));
      if (extensions.length) this.use(extensions);
    }
  }

  observe (message, user) {
    this.emit('message', message, user);

    const operator = this.config.operator;

    if (operator && message.startsWith(operator)) {
      const pieces = message.substring(operator.length).split(' ');
      const handle = pieces.shift();

      if (this.commands.has(handle)) {
        const data = { user, message: pieces.join(' ') };
        this.invoke(handle, data);
      }
    }
  }

  connect () {
    const conf = this.config.mumble;
    const addr = `mumble://${conf.server}:${conf.port}`;

    Mumble.connect(addr, {}, (error, client) => {
      if (error)
        this.emit('connect-error', error);
      else {
        this.client = client;

        client.authenticate(conf.username, conf.password);

        client.on('ready', () => this.emit('ready'));
        client.on('message', (message, user) => this.observe(message, user));
        client.once('disconnect', () => this.disconnect(true));

        this.emit('connect', client);
      }
    });

    return this;
  }

  disconnect (evented) {
    if (this.client) {
      this.io.nullify('io');
      if (!evented) this.client.disconnect();
      this.client = null;
      this.emit('disconnect');
    }

    return this;
  }
};
<|endoftext|>


<commit_before>(function ($) {
    var Module = core.wirings.Module,
        __super__ = Module.prototype;
    /**
     * The main class that implements offline webapp functionalities using application cache and local storage.
     * Extends core.wirings.Module to have the ability to be instantiated in the same fashion.
     *
     * @class OfflineModule
     * @module addons
     * @namespace core.wirings
     * @extends core.wirings.Module
     * @constructor
     * @param {Object} opts An object containing configurations required by the Core derived class.
     * @param {HTMLElement} opts.el The node element included in the class composition.
     *
     */
    function OfflineModule(opts) {
        if (opts && opts.__inheriting__) return;
        __super__.constructor.call(this, opts);

    }
    OfflineModule.inherits(Module);
    var proto = OfflineModule.prototype;
    proto.dispose = function () {
        //clear
        __super__.dispose.call(this);
        clearInterval(this.cacheStatusTimer);
    };
    proto.construct = function(opts){
        this.cacheUpdateInterval = 3000;
		__super__.construct.call(this, opts);
        prepare.call(this);
    };
    proto.initialized = function(opts){
        console.warn("OfflineModule subclass requires initialized method.");
    };
    /**
     * The main method handler for checking the application status. Also determines if a web application has gone offline/online
     *
     * @method onApplicationCacheStatus
     * @param {Object} event Contains the information about the current application cache status.
     */
    proto.onApplicationCacheStatus = function(evt){

        switch(evt.type){
            case "error":
                if(this.currentOnlineStatus !== false){
                    this.currentOnlineStatus = false;
                    this.onlineStatus(false);
                }

                break;
            case "cached":
                if(this.currentOnlineStatus !== true){
                    this.currentOnlineStatus = true;
                    this.onlineStatus(true);
                }
                this.cacheStatus("cached");
                break;
            case "checking":
                break;
            case "downloading":
                break;
            case "noupdate":

                if(this.currentOnlineStatus !== true){
                    this.currentOnlineStatus = true;
                    this.onlineStatus(true);
                }
                break;
            case "obsolete":
                if(this.currentOnlineStatus !== true){
                    this.currentOnlineStatus = true;
                    this.onlineStatus(true);
                }
                this.cacheStatus("updateAvailable");
                break;
            case "progress":
                break;
            case "ready":
                if(this.currentOnlineStatus !== true){
                    this.currentOnlineStatus = true;
                    this.onlineStatus(true);
                }
                break;
            default:
                if(this.currentOnlineStatus !== true){
                    this.currentOnlineStatus = true;
                    this.onlineStatus(true);
                }
                break;
        }
    };
    /**
     * Virtual protected function. Should be overridden on subclasses. Called automatically when the cache status has changed.
     *
     * @method cacheStatus
     * @param {String} status The status of the application cache.
     */
    proto.cacheStatus = function(status){

    };
    /**
     * Virtual protected function. Should be overridden on subclasses. Called automatically when the online/offline state of the application changes.
     *
     * @method onlineStatus
     * @param {Boolean} isonline True/false depending on the applications online/offline state.
     */
    proto.onlineStatus = function(isonline){

    };
    var prepare = function(){
        this.currentOnlineStatus = -1;
        if("applicationCache" in window){
            var ac = window.applicationCache;
            ac.addEventListener("error", this._("onApplicationCacheStatus"));
            ac.addEventListener("cached", this._("onApplicationCacheStatus"));
            ac.addEventListener("checking", this._("onApplicationCacheStatus"));
            ac.addEventListener("downloading", this._("onApplicationCacheStatus"));
            ac.addEventListener("noupdate", this._("onApplicationCacheStatus"));
            ac.addEventListener("obsolete", this._("onApplicationCacheStatus"));
            ac.addEventListener("progress", this._("onApplicationCacheStatus"));
            ac.addEventListener("ready", this._("onApplicationCacheStatus"));
            var ref = this;
            this.cacheStatusTimer = setInterval(function(){
                try{
                    window.applicationCache.update();
                }catch(err){
                    console.warn("Using application cache without a manifest. Cache update check and online status check will not work.");
                    clearInterval(ref.cacheStatusTimer);

                }

            }, this.cacheUpdateInterval);
        }
        this.localStorage = core.addons.webapp.LocalStorage.init();

    };
    core.registerNamespace("core.wirings.OfflineModule", OfflineModule);

})(core.selector);<commit_msg>supply default value to cacheUpdateInterval<commit_after>(function ($) {
    var Module = core.wirings.Module,
        __super__ = Module.prototype;
    /**
     * The main class that implements offline webapp functionalities using application cache and local storage.
     * Extends core.wirings.Module to have the ability to be instantiated in the same fashion.
     *
     * @class OfflineModule
     * @module addons
     * @namespace core.wirings
     * @extends core.wirings.Module
     * @constructor
     * @param {Object} opts An object containing configurations required by the Core derived class.
     * @param {HTMLElement} opts.el The node element included in the class composition.
     *
     */
    function OfflineModule(opts) {
        if (opts && opts.__inheriting__) return;
        __super__.constructor.call(this, opts);

    }
    OfflineModule.inherits(Module);
    var proto = OfflineModule.prototype;
    proto.dispose = function () {
        //clear
        __super__.dispose.call(this);
        clearInterval(this.cacheStatusTimer);
    };
    proto.construct = function(opts){
        //if cacheUpdateInterval is not overridden from outside, then assign a default value which is 3000
        if (!this.cacheUpdateInterval)
            this.cacheUpdateInterval = 3000;

		__super__.construct.call(this, opts);
        prepare.call(this);
    };
    proto.initialized = function(opts){
        console.warn("OfflineModule subclass requires initialized method.");
    };
    /**
     * The main method handler for checking the application status. Also determines if a web application has gone offline/online
     *
     * @method onApplicationCacheStatus
     * @param {Object} event Contains the information about the current application cache status.
     */
    proto.onApplicationCacheStatus = function(evt){

        switch(evt.type){
            case "error":
                if(this.currentOnlineStatus !== false){
                    this.currentOnlineStatus = false;
                    this.onlineStatus(false);
                }

                break;
            case "cached":
                if(this.currentOnlineStatus !== true){
                    this.currentOnlineStatus = true;
                    this.onlineStatus(true);
                }
                this.cacheStatus("cached");
                break;
            case "checking":
                break;
            case "downloading":
                break;
            case "noupdate":

                if(this.currentOnlineStatus !== true){
                    this.currentOnlineStatus = true;
                    this.onlineStatus(true);
                }
                break;
            case "obsolete":
                if(this.currentOnlineStatus !== true){
                    this.currentOnlineStatus = true;
                    this.onlineStatus(true);
                }
                this.cacheStatus("updateAvailable");
                break;
            case "progress":
                break;
            case "ready":
                if(this.currentOnlineStatus !== true){
                    this.currentOnlineStatus = true;
                    this.onlineStatus(true);
                }
                break;
            default:
                if(this.currentOnlineStatus !== true){
                    this.currentOnlineStatus = true;
                    this.onlineStatus(true);
                }
                break;
        }
    };
    /**
     * Virtual protected function. Should be overridden on subclasses. Called automatically when the cache status has changed.
     *
     * @method cacheStatus
     * @param {String} status The status of the application cache.
     */
    proto.cacheStatus = function(status){

    };
    /**
     * Virtual protected function. Should be overridden on subclasses. Called automatically when the online/offline state of the application changes.
     *
     * @method onlineStatus
     * @param {Boolean} isonline True/false depending on the applications online/offline state.
     */
    proto.onlineStatus = function(isonline){

    };
    var prepare = function(){
        this.currentOnlineStatus = -1;
        if("applicationCache" in window){
            var ac = window.applicationCache;
            ac.addEventListener("error", this._("onApplicationCacheStatus"));
            ac.addEventListener("cached", this._("onApplicationCacheStatus"));
            ac.addEventListener("checking", this._("onApplicationCacheStatus"));
            ac.addEventListener("downloading", this._("onApplicationCacheStatus"));
            ac.addEventListener("noupdate", this._("onApplicationCacheStatus"));
            ac.addEventListener("obsolete", this._("onApplicationCacheStatus"));
            ac.addEventListener("progress", this._("onApplicationCacheStatus"));
            ac.addEventListener("ready", this._("onApplicationCacheStatus"));
            var ref = this;
            this.cacheStatusTimer = setInterval(function(){
                try{
                    window.applicationCache.update();
                }catch(err){
                    console.warn("Using application cache without a manifest. Cache update check and online status check will not work.");
                    clearInterval(ref.cacheStatusTimer);

                }

            }, this.cacheUpdateInterval);
        }
        this.localStorage = core.addons.webapp.LocalStorage.init();

    };
    core.registerNamespace("core.wirings.OfflineModule", OfflineModule);

})(core.selector);<|endoftext|>


<commit_before>window.PNGDrive = function(image, bitsPerColorComponent) {

	this.VERSION_MAJOR = 1;
	this.VERSION_MINOR = 0;

	this.files = [];
	this.raw = new Uint8Array(0);

	if(typeof image !== "undefined") {
		this.decode(image, bitsPerColorComponent);
	}
};

window.PNGDrive.prototype = {

	addFile: function(file) {
		this.files.push({ name: file.name, type: file.type, fileRef: file });
	},

	addTextFile: function(text, name, type) {
		this.files.push({ name: name, type: type, content: this.utf8Encode(text) });
	},

	addBinaryFile: function(uint8Array, name, type) {
		this.files.push({ name: name, type: type, content: uint8Array });
	},

	removeAll: function() {
		this.files = [];
	},

	removeFileAt: function(index) {
		if(index >= 0 && index < this.files.length) {
			this.files.splice(index, 1);
		}
	},

	removeFileByName: function(name) {
		for(var i = 0; i < this.files.length; i++) {
			if(this.files[i].name == name) {
				this.files.splice(i, 1);
				break;
			}
		}
	},

	getFileCount: function() {
		return this.files.length;
	},

	getFileAt: function(index) {
		return (index >= 0 && index < this.files.length) ? this.files[index] : null;
	},

	getFileByName: function(name) {
		for(var i = 0; i < this.files.length; i++) {
			if(this.files[i].name == name) {
				return this.files[i];
			}
		}
		return null;
	},

	decode: function(image, bitsPerColorComponent) {
		if (typeof bitsPerColorComponent == "undefined") { bitsPerColorComponent = 8; }
		var canvas = document.createElement('canvas');
		var ctx = canvas.getContext('2d');
		canvas.width = image.width;
		canvas.height = image.height;
		ctx.drawImage(image, 0, 0);
		var img = ctx.getImageData(0, 0, image.width, image.height);
		var imgData = img.data;
		var length = imgData.length;
		var buf = this.raw = new Uint8Array(image.width * image.height * 3);
		var i = 0;
		if(bitsPerColorComponent == 8) {
			var j = 0;
			while(i < length) {
				if(imgData[i + 3] == 0xff) {
					buf[j++] = imgData[i++];
					buf[j++] = imgData[i++];
					buf[j++] = imgData[i++];
					i++;
				} else {
					i += 4;
				}
			}
		} else {
			var bitStream = new PNGDriveBitStream(buf);
			while(i < length) {
				if(imgData[i + 3] == 0xff) {
					bitStream.writeBits(bitsPerColorComponent, imgData[i++]);
					bitStream.writeBits(bitsPerColorComponent, imgData[i++]);
					bitStream.writeBits(bitsPerColorComponent, imgData[i++]);
					i++;
				} else {
					i += 4;
				}
			}
		}
		if(buf[0] == 0xda && buf[1] == 0xda) {
			var dirSize = buf[4] | buf[5] << 8 | buf[6] << 16 | buf[7] << 24;
			var dirBuf = buf.subarray(8, 8 + dirSize);
			var dir = JSON.parse(this.utf8Decode(dirBuf));
			var pos = 8 + dirSize;
			this.files = [];
			for(i = 0; i < dir.files.length; i++) {
				var file = dir.files[i];
				var fileBuf = new Uint8Array(file.size);
				fileBuf.set(buf.subarray(pos, pos + file.size));
				pos += file.size;
				this.files.push({ name: file.name, type: file.type, content: fileBuf });
			}
		}
		return this;
	},

	encode: function(callback) {
		var that = this;
		(function(serialize) {
			var numFilesToLoad = 0;
			var fileCount = that.getFileCount();
			for(var i = 0; i < fileCount; i++) {
				var file = that.files[i];
				if(file.fileRef) {
					numFilesToLoad++;
					var reader = new FileReader();
					reader.onload = (function(f) {
						return function(event) {
							f.content = new Uint8Array(event.target.result);
							delete f.fileRef;
							if(--numFilesToLoad == 0 && i == fileCount) {
								numFilesToLoad = -1;
								serialize.call(that);;
							}
						};
					})(file);
					reader.readAsArrayBuffer(file.fileRef);
				}
			}
			if(numFilesToLoad == 0) {
				serialize.call(that);;
			}
		})(function() {
			var fileCount = this.getFileCount();
			if(fileCount > 0) {
				var j, pos, file;
				var dir = { files: [] };
				var payLoadSize = 0;
				for(j = 0; j < fileCount; j++) {
					file = this.files[j];
					payLoadSize += file.content.byteLength;
					dir.files.push({ name: file.name, size: file.content.byteLength, type: file.type });
				}
				var dirBuf = this.utf8Encode(JSON.stringify(dir));
				var dirSize = dirBuf.byteLength;
				var totalSize = 8 + dirSize + payLoadSize;
				var buf = this.raw = new Uint8Array(totalSize);
				// intro, 0xDADA
				buf[0] = buf[1] = 0xda;
				// version, major/minor
				buf[2] = this.VERSION_MAJOR;
				buf[3] = this.VERSION_MINOR;
				// directory size, 32 bit little endian
				buf[4] = dirSize & 0xff;
				buf[5] = (dirSize >> 8) & 0xff;
				buf[6] = (dirSize >> 16) & 0xff;
				buf[7] = (dirSize >> 24) & 0xff;
				// write directory
				buf.set(dirBuf, 8);
				// write files
				for(j = 0, pos = 8 + dirBuf.byteLength; j < fileCount; j++) {
					file = this.files[j];
					buf.set(file.content, pos);
					pos += file.content.byteLength;
				}
			} else {
				this.raw = new Uint8Array(0);
			}
			if(callback) {
				callback.call(this);
			}
		});
	},

	createImage: function(targetImage, bitsPerColorComponent) {
		var canvas = document.createElement('canvas');
		var ctx = canvas.getContext('2d');
		if(typeof targetImage == "undefined") {
			bitsPerColorComponent = 8;
			var px = Math.ceil(Math.sqrt(this.raw.byteLength / 3));
			canvas.width = px;
			canvas.height = px;
			ctx.fillRect(0, 0, px, px);
		} else {
			if(typeof bitsPerColorComponent == "undefined") { bitsPerColorComponent = 8; }
			canvas.width = targetImage.width;
			canvas.height = targetImage.height;
			ctx.drawImage(targetImage, 0, 0);
		}
		var img = ctx.getImageData(0, 0, canvas.width, canvas.height);
		var imgData = img.data;
		var imgLength = imgData.length;
		var i = 0;
		if(bitsPerColorComponent == 8) {
			var j = 0;
			while(i < imgLength) {
				if(imgData[i + 3] == 0xff) {
					imgData[i++] = this.raw[j++];
					imgData[i++] = this.raw[j++];
					imgData[i++] = this.raw[j++];
					i++;
				} else {
					i += 4;
				}
			}
		} else {
			var bitStream = new PNGDriveBitStream(this.raw);
			var bitMask = 0xff ^ (0xff >>> (8 - bitsPerColorComponent));
			while(i < imgLength) {
				if(imgData[i + 3] == 0xff) {
					imgData[i] = (imgData[i++] & bitMask) | bitStream.readBits(bitsPerColorComponent);
					imgData[i] = (imgData[i++] & bitMask) | bitStream.readBits(bitsPerColorComponent);
					imgData[i] = (imgData[i++] & bitMask) | bitStream.readBits(bitsPerColorComponent);
					i++;
				} else {
					i += 4;
				}
			}
		}
		ctx.putImageData(img, 0, 0);
		return canvas;
	},

	computeImageCapacity: function(targetImage, bitsPerColorComponent) {
		if(typeof bitsPerColorComponent == "undefined") { bitsPerColorComponent = 8; }
		var canvas = document.createElement('canvas');
		var ctx = canvas.getContext('2d');
		canvas.width = targetImage.width;
		canvas.height = targetImage.height;
		ctx.drawImage(targetImage, 0, 0);
		var img = ctx.getImageData(0, 0, canvas.width, canvas.height);
		var imgData = img.data;
		var imgLength = imgData.length;
		var i = 0;
		var numBits = 0;
		var numBitsPerPixel = bitsPerColorComponent * 3;
		while(i < imgLength) {
			if(imgData[i + 3] == 0xff) {
				numBits += numBitsPerPixel;
			}
			i += 4;
		}
		return numBits;
	},

	utf8Encode: function(string) {
		var tmparr = [];
		var len = string.length;
		for (var n = 0; n < len; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				tmparr.push(c);
			} else if((c > 127) && (c < 2048)) {
				tmparr.push((c >> 6) | 192);
				tmparr.push((c & 63) | 128);
			} else {
				tmparr.push((c >> 12) | 224);
				tmparr.push(((c >> 6) & 63) | 128);
				tmparr.push((c & 63) | 128);
			}
		}
		return new Uint8Array(tmparr);
	},

	utf8Decode: function(uint8array) {
		var len = uint8array.byteLength;
		var string = "";
		var i = 0;
		while (i < len) {
			var c = uint8array[i];
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			} else if((c > 191) && (c < 224) && (i + 1 < len)) {
				string += String.fromCharCode(((c & 31) << 6) | (uint8array[i + 1] & 63));
				i += 2;
			} else if(i + 2 < len) {
				string += String.fromCharCode(((c & 15) << 12) | ((uint8array[i + 1] & 63) << 6) | (uint8array[i + 2] & 63));
				i += 3;
			}
		}
		return string;
	}

};

window.PNGDriveBitStream = function(uint8array) {

	this.a = uint8array;
	this.position = 0;
	this.bitsPending = 0;

};

window.PNGDriveBitStream.prototype = {

	writeBits: function(bits, value) {
		if (bits == 0) { return; }
		value &= (0xffffffff >>> (32 - bits));
		var bitsConsumed;
		if (this.bitsPending > 0) {
			if (this.bitsPending > bits) {
				this.a[this.position - 1] |= value << (this.bitsPending - bits);
				bitsConsumed = bits;
				this.bitsPending -= bits;
			} else if (this.bitsPending == bits) {
				this.a[this.position - 1] |= value;
				bitsConsumed = bits;
				this.bitsPending = 0;
			} else {
				this.a[this.position - 1] |= value >> (bits - this.bitsPending);
				bitsConsumed = this.bitsPending;
				this.bitsPending = 0;
			}
		} else {
			bitsConsumed = Math.min(8, bits);
			this.bitsPending = 8 - bitsConsumed;
			this.a[this.position++] = (value >> (bits - bitsConsumed)) << this.bitsPending;
		}
		bits -= bitsConsumed;
		if (bits > 0) {
			this.writeBits(bits, value);
		}
	},

	readBits: function(bits, bitBuffer) {
		if (typeof bitBuffer == "undefined") { bitBuffer = 0; }
		if (bits == 0) { return bitBuffer; }
		var partial;
		var bitsConsumed;
		if (this.bitsPending > 0) {
			var b = this.a[this.position - 1] & (0xff >> (8 - this.bitsPending));
			bitsConsumed = Math.min(this.bitsPending, bits);
			this.bitsPending -= bitsConsumed;
			partial = b >> this.bitsPending;
		} else {
			bitsConsumed = Math.min(8, bits);
			this.bitsPending = 8 - bitsConsumed;
			partial = this.a[this.position++] >> this.bitsPending;
		}
		bits -= bitsConsumed;
		bitBuffer = (bitBuffer << bitsConsumed) | partial;
		return (bits > 0) ? this.readBits(bits, bitBuffer) : bitBuffer;
	},

	seekTo: function(bitPos) {
		this.position = (bitPos / 8) | 0;
		this.bitsPending = bitPos % 8;
		if(this.bitsPending > 0) {
			this.bitsPending = 8 - this.bitsPending;
			this.position++;
		}
	}

};
<commit_msg>Credits for new utf-8 en/decoder<commit_after>window.PNGDrive = function(image, bitsPerColorComponent) {

	this.VERSION_MAJOR = 1;
	this.VERSION_MINOR = 0;

	this.files = [];
	this.raw = new Uint8Array(0);

	if(typeof image !== "undefined") {
		this.decode(image, bitsPerColorComponent);
	}
};

window.PNGDrive.prototype = {

	addFile: function(file) {
		this.files.push({ name: file.name, type: file.type, fileRef: file });
	},

	addTextFile: function(text, name, type) {
		this.files.push({ name: name, type: type, content: this.utf8Encode(text) });
	},

	addBinaryFile: function(uint8Array, name, type) {
		this.files.push({ name: name, type: type, content: uint8Array });
	},

	removeAll: function() {
		this.files = [];
	},

	removeFileAt: function(index) {
		if(index >= 0 && index < this.files.length) {
			this.files.splice(index, 1);
		}
	},

	removeFileByName: function(name) {
		for(var i = 0; i < this.files.length; i++) {
			if(this.files[i].name == name) {
				this.files.splice(i, 1);
				break;
			}
		}
	},

	getFileCount: function() {
		return this.files.length;
	},

	getFileAt: function(index) {
		return (index >= 0 && index < this.files.length) ? this.files[index] : null;
	},

	getFileByName: function(name) {
		for(var i = 0; i < this.files.length; i++) {
			if(this.files[i].name == name) {
				return this.files[i];
			}
		}
		return null;
	},

	decode: function(image, bitsPerColorComponent) {
		if (typeof bitsPerColorComponent == "undefined") { bitsPerColorComponent = 8; }
		var canvas = document.createElement('canvas');
		var ctx = canvas.getContext('2d');
		canvas.width = image.width;
		canvas.height = image.height;
		ctx.drawImage(image, 0, 0);
		var img = ctx.getImageData(0, 0, image.width, image.height);
		var imgData = img.data;
		var length = imgData.length;
		var buf = this.raw = new Uint8Array(image.width * image.height * 3);
		var i = 0;
		if(bitsPerColorComponent == 8) {
			var j = 0;
			while(i < length) {
				if(imgData[i + 3] == 0xff) {
					buf[j++] = imgData[i++];
					buf[j++] = imgData[i++];
					buf[j++] = imgData[i++];
					i++;
				} else {
					i += 4;
				}
			}
		} else {
			var bitStream = new PNGDriveBitStream(buf);
			while(i < length) {
				if(imgData[i + 3] == 0xff) {
					bitStream.writeBits(bitsPerColorComponent, imgData[i++]);
					bitStream.writeBits(bitsPerColorComponent, imgData[i++]);
					bitStream.writeBits(bitsPerColorComponent, imgData[i++]);
					i++;
				} else {
					i += 4;
				}
			}
		}
		if(buf[0] == 0xda && buf[1] == 0xda) {
			var dirSize = buf[4] | buf[5] << 8 | buf[6] << 16 | buf[7] << 24;
			var dirBuf = buf.subarray(8, 8 + dirSize);
			var dir = JSON.parse(this.utf8Decode(dirBuf));
			var pos = 8 + dirSize;
			this.files = [];
			for(i = 0; i < dir.files.length; i++) {
				var file = dir.files[i];
				var fileBuf = new Uint8Array(file.size);
				fileBuf.set(buf.subarray(pos, pos + file.size));
				pos += file.size;
				this.files.push({ name: file.name, type: file.type, content: fileBuf });
			}
		}
		return this;
	},

	encode: function(callback) {
		var that = this;
		(function(serialize) {
			var numFilesToLoad = 0;
			var fileCount = that.getFileCount();
			for(var i = 0; i < fileCount; i++) {
				var file = that.files[i];
				if(file.fileRef) {
					numFilesToLoad++;
					var reader = new FileReader();
					reader.onload = (function(f) {
						return function(event) {
							f.content = new Uint8Array(event.target.result);
							delete f.fileRef;
							if(--numFilesToLoad == 0 && i == fileCount) {
								numFilesToLoad = -1;
								serialize.call(that);;
							}
						};
					})(file);
					reader.readAsArrayBuffer(file.fileRef);
				}
			}
			if(numFilesToLoad == 0) {
				serialize.call(that);;
			}
		})(function() {
			var fileCount = this.getFileCount();
			if(fileCount > 0) {
				var j, pos, file;
				var dir = { files: [] };
				var payLoadSize = 0;
				for(j = 0; j < fileCount; j++) {
					file = this.files[j];
					payLoadSize += file.content.byteLength;
					dir.files.push({ name: file.name, size: file.content.byteLength, type: file.type });
				}
				var dirBuf = this.utf8Encode(JSON.stringify(dir));
				var dirSize = dirBuf.byteLength;
				var totalSize = 8 + dirSize + payLoadSize;
				var buf = this.raw = new Uint8Array(totalSize);
				// intro, 0xDADA
				buf[0] = buf[1] = 0xda;
				// version, major/minor
				buf[2] = this.VERSION_MAJOR;
				buf[3] = this.VERSION_MINOR;
				// directory size, 32 bit little endian
				buf[4] = dirSize & 0xff;
				buf[5] = (dirSize >> 8) & 0xff;
				buf[6] = (dirSize >> 16) & 0xff;
				buf[7] = (dirSize >> 24) & 0xff;
				// write directory
				buf.set(dirBuf, 8);
				// write files
				for(j = 0, pos = 8 + dirBuf.byteLength; j < fileCount; j++) {
					file = this.files[j];
					buf.set(file.content, pos);
					pos += file.content.byteLength;
				}
			} else {
				this.raw = new Uint8Array(0);
			}
			if(callback) {
				callback.call(this);
			}
		});
	},

	createImage: function(targetImage, bitsPerColorComponent) {
		var canvas = document.createElement('canvas');
		var ctx = canvas.getContext('2d');
		if(typeof targetImage == "undefined") {
			bitsPerColorComponent = 8;
			var px = Math.ceil(Math.sqrt(this.raw.byteLength / 3));
			canvas.width = px;
			canvas.height = px;
			ctx.fillRect(0, 0, px, px);
		} else {
			if(typeof bitsPerColorComponent == "undefined") { bitsPerColorComponent = 8; }
			canvas.width = targetImage.width;
			canvas.height = targetImage.height;
			ctx.drawImage(targetImage, 0, 0);
		}
		var img = ctx.getImageData(0, 0, canvas.width, canvas.height);
		var imgData = img.data;
		var imgLength = imgData.length;
		var i = 0;
		if(bitsPerColorComponent == 8) {
			var j = 0;
			while(i < imgLength) {
				if(imgData[i + 3] == 0xff) {
					imgData[i++] = this.raw[j++];
					imgData[i++] = this.raw[j++];
					imgData[i++] = this.raw[j++];
					i++;
				} else {
					i += 4;
				}
			}
		} else {
			var bitStream = new PNGDriveBitStream(this.raw);
			var bitMask = 0xff ^ (0xff >>> (8 - bitsPerColorComponent));
			while(i < imgLength) {
				if(imgData[i + 3] == 0xff) {
					imgData[i] = (imgData[i++] & bitMask) | bitStream.readBits(bitsPerColorComponent);
					imgData[i] = (imgData[i++] & bitMask) | bitStream.readBits(bitsPerColorComponent);
					imgData[i] = (imgData[i++] & bitMask) | bitStream.readBits(bitsPerColorComponent);
					i++;
				} else {
					i += 4;
				}
			}
		}
		ctx.putImageData(img, 0, 0);
		return canvas;
	},

	computeImageCapacity: function(targetImage, bitsPerColorComponent) {
		if(typeof bitsPerColorComponent == "undefined") { bitsPerColorComponent = 8; }
		var canvas = document.createElement('canvas');
		var ctx = canvas.getContext('2d');
		canvas.width = targetImage.width;
		canvas.height = targetImage.height;
		ctx.drawImage(targetImage, 0, 0);
		var img = ctx.getImageData(0, 0, canvas.width, canvas.height);
		var imgData = img.data;
		var imgLength = imgData.length;
		var i = 0;
		var numBits = 0;
		var numBitsPerPixel = bitsPerColorComponent * 3;
		while(i < imgLength) {
			if(imgData[i + 3] == 0xff) {
				numBits += numBitsPerPixel;
			}
			i += 4;
		}
		return numBits;
	},

	// http://www.webtoolkit.info/javascript-base64.html
	// http://stackoverflow.com/questions/246801/how-can-you-encode-to-base64-using-javascript/6836708
	// (modified to use typed arrays)
	utf8Encode: function(string) {
		var tmparr = [];
		var len = string.length;
		for (var n = 0; n < len; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				tmparr.push(c);
			} else if((c > 127) && (c < 2048)) {
				tmparr.push((c >> 6) | 192);
				tmparr.push((c & 63) | 128);
			} else {
				tmparr.push((c >> 12) | 224);
				tmparr.push(((c >> 6) & 63) | 128);
				tmparr.push((c & 63) | 128);
			}
		}
		return new Uint8Array(tmparr);
	},

	// http://www.webtoolkit.info/javascript-base64.html
	// http://stackoverflow.com/questions/246801/how-can-you-encode-to-base64-using-javascript/6836708
	// (modified to use typed arrays)
	utf8Decode: function(uint8array) {
		var len = uint8array.byteLength;
		var string = "";
		var i = 0;
		while (i < len) {
			var c = uint8array[i];
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			} else if((c > 191) && (c < 224) && (i + 1 < len)) {
				string += String.fromCharCode(((c & 31) << 6) | (uint8array[i + 1] & 63));
				i += 2;
			} else if(i + 2 < len) {
				string += String.fromCharCode(((c & 15) << 12) | ((uint8array[i + 1] & 63) << 6) | (uint8array[i + 2] & 63));
				i += 3;
			}
		}
		return string;
	}

};

window.PNGDriveBitStream = function(uint8array) {

	this.a = uint8array;
	this.position = 0;
	this.bitsPending = 0;

};

window.PNGDriveBitStream.prototype = {

	writeBits: function(bits, value) {
		if (bits == 0) { return; }
		value &= (0xffffffff >>> (32 - bits));
		var bitsConsumed;
		if (this.bitsPending > 0) {
			if (this.bitsPending > bits) {
				this.a[this.position - 1] |= value << (this.bitsPending - bits);
				bitsConsumed = bits;
				this.bitsPending -= bits;
			} else if (this.bitsPending == bits) {
				this.a[this.position - 1] |= value;
				bitsConsumed = bits;
				this.bitsPending = 0;
			} else {
				this.a[this.position - 1] |= value >> (bits - this.bitsPending);
				bitsConsumed = this.bitsPending;
				this.bitsPending = 0;
			}
		} else {
			bitsConsumed = Math.min(8, bits);
			this.bitsPending = 8 - bitsConsumed;
			this.a[this.position++] = (value >> (bits - bitsConsumed)) << this.bitsPending;
		}
		bits -= bitsConsumed;
		if (bits > 0) {
			this.writeBits(bits, value);
		}
	},

	readBits: function(bits, bitBuffer) {
		if (typeof bitBuffer == "undefined") { bitBuffer = 0; }
		if (bits == 0) { return bitBuffer; }
		var partial;
		var bitsConsumed;
		if (this.bitsPending > 0) {
			var b = this.a[this.position - 1] & (0xff >> (8 - this.bitsPending));
			bitsConsumed = Math.min(this.bitsPending, bits);
			this.bitsPending -= bitsConsumed;
			partial = b >> this.bitsPending;
		} else {
			bitsConsumed = Math.min(8, bits);
			this.bitsPending = 8 - bitsConsumed;
			partial = this.a[this.position++] >> this.bitsPending;
		}
		bits -= bitsConsumed;
		bitBuffer = (bitBuffer << bitsConsumed) | partial;
		return (bits > 0) ? this.readBits(bits, bitBuffer) : bitBuffer;
	},

	seekTo: function(bitPos) {
		this.position = (bitPos / 8) | 0;
		this.bitsPending = bitPos % 8;
		if(this.bitsPending > 0) {
			this.bitsPending = 8 - this.bitsPending;
			this.position++;
		}
	}

};
<|endoftext|>


<commit_before>'use strict';

var doc = global.document;
var ui = require('./ui');
var util = require('./util');
var configure = require('./configure');
var Editor = require('./Editor');
var nextId = 0;

function convertTabs () {
  util.addEventDelegate(doc, 'pmk-input', 'keydown', ui.convertTabs);
}

function ponymark (containers) {
  var postfix = nextId++;
  var editor;

  if (Object.prototype.toString.call(containers) !== '[object Object]') {
    containers = {
      buttons: containers,
      input: containers,
      preview: containers
    };
  }

  markup(containers, postfix);

  editor = new Editor(postfix);
  editor.run();
}

function markup (containers, postfix) {
  var buttonBar = doc.createElement('div');
  var preview = doc.createElement('div');
  var input = doc.createElement('textarea');

  buttonBar.id = 'pmk-buttons-' + postfix;
  buttonBar.className = 'pmk-buttons';
  preview.id = 'pmk-preview-' + postfix;
  preview.className = 'pmk-preview';
  input.id = 'pmk-input-' + postfix;
  input.className = 'pmk-input';
  input.placeholder = containers.input.getAttribute('placeholder');

  containers.buttons.appendChild(buttonBar);
  containers.input.appendChild(input);
  containers.preview.appendChild(preview);
}

module.exports = ponymark;

ponymark.Editor = Editor;
ponymark.convertTabs = convertTabs;
ponymark.configure = configure;
<commit_msg>or default to empty<commit_after>'use strict';

var doc = global.document;
var ui = require('./ui');
var util = require('./util');
var configure = require('./configure');
var Editor = require('./Editor');
var nextId = 0;

function convertTabs () {
  util.addEventDelegate(doc, 'pmk-input', 'keydown', ui.convertTabs);
}

function ponymark (containers) {
  var postfix = nextId++;
  var editor;

  if (Object.prototype.toString.call(containers) !== '[object Object]') {
    containers = {
      buttons: containers,
      input: containers,
      preview: containers
    };
  }

  markup(containers, postfix);

  editor = new Editor(postfix);
  editor.run();
}

function markup (containers, postfix) {
  var buttonBar = doc.createElement('div');
  var preview = doc.createElement('div');
  var input = doc.createElement('textarea');

  buttonBar.id = 'pmk-buttons-' + postfix;
  buttonBar.className = 'pmk-buttons';
  preview.id = 'pmk-preview-' + postfix;
  preview.className = 'pmk-preview';
  input.id = 'pmk-input-' + postfix;
  input.className = 'pmk-input';
  input.placeholder = containers.input.getAttribute('placeholder') || '';

  containers.buttons.appendChild(buttonBar);
  containers.input.appendChild(input);
  containers.preview.appendChild(preview);
}

module.exports = ponymark;

ponymark.Editor = Editor;
ponymark.convertTabs = convertTabs;
ponymark.configure = configure;
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var _ = require('lodash');
var webpack = require('webpack');
var chokidar = require('chokidar');
var Watcher = require('./Watcher');
var options = require('./options');
var hmr = require('./hmr');
var builds = require('./builds');

var Wrapper = function Wrapper(opts, config, cache) {
  this.opts = options.generate(opts);

  // TODO: remove this, should simply pass the config obj as `opts.config`
  // Convenience hook to pass an object in. You can also define
  // `opts.config` as a path to a file
  this.config = config;

  this.cache = cache;

  // State
  this.watcher = null;
  this.watching = false;
  this.watchingConfig = false;

  // Callbacks
  this._onceDone = [];
};

Wrapper.prototype.invalidate = function invalidate() {
  if (this.watching) {
    this.watcher.invalidate();
  }
};

Wrapper.prototype.invalidateConfig = function invalidateConfig() {
  if (this.opts.logger) {
    this.opts.logger.info('Webpack: invalidating config file require cache for ' + this.getIdentifier());
  }

  this.config = null;

  if (_.isString(this.opts.config)) {
    delete require.cache[this.opts.config];
  }

  if (this.watching) {
    this.watcher.close();
    this.watcher = null;
    this.watching = false;

    if (this.opts.logger) {
      this.opts.logger.info('Webpack: closed watcher for ' + this.getIdentifier());
    }
  }

  this.invalidate();
};

Wrapper.prototype.getConfig = function getConfig(cb) {
  if (this.config) {
    return cb(null, this.config);
  }

  if (!this.opts.config) {
    return cb(new Error('Wrapper options missing `config` value'));
  }

  this.config = this.opts.config;

  if (_.isString(this.config)) {
    try {
      this.config = require(this.config);
    } catch(err) {
      this.config = null;
      return cb(err);
    }

    if (this.opts.watchConfig && !this.watchingConfig) {
      this.watchingConfig = true;
      if (this.opts.logger) {
        this.opts.logger.info('Webpack: watching config file ' + this.opts.config);
      }
      this.watchFile(this.opts.config, function() {
        if (this.opts.logger) {
          this.opts.logger.info('Webpack: change detected in config file ' + this.opts.config);
        }
        this.invalidateConfig();
      }.bind(this));
    }
  }

  if (this.config && this.opts.hmr) {
    try {
      this.config = builds.hmr(this.config, this.opts);
    } catch(err) {
      return cb(err);
    }
  }

  if (this.config && this.opts.build) {
    if (!this.config.builds) {
      return cb(new Error('No builds property has been defined on ' + this.opts.config));
    }

    if (this.opts.build in this.config.builds) {
      if (this.opts.logger) {
        this.opts.logger.info('Webpack: applying build "' + this.opts.build + '" to ' + this.opts.config);
      }

      try {
        this.config = this.config.builds[this.opts.build](this.config, this.opts);
      } catch(err) {
        return cb(err);
      }
    } else {
      return cb(new Error(
        'Unknown build "' + this.opts.build + '". ' +
        'Available builds: ' + Object.keys(this.config.builds).join(', ')
      ));
    }
  }

  if (this.opts.outputPath && this.config.output) {
    this.config.output.path = this.opts.outputPath;
  }

  cb(null, this.config)
};

Wrapper.prototype.getCompiler = function getCompiler(cb) {
  this.getConfig(function(err, config) {
    if (err) return cb(err);

    var compiler = webpack(config);

    if (this.opts.logger) {
      compiler.plugin('done', function(stats) {
        if (stats.hasErrors()) {
          this.opts.logger.error('Webpack: build error', stats.compilation.errors[0].stack);
        } else {
          this.opts.logger.info('Webpack: build completed for ' + this.getIdentifier());
        }
      }.bind(this));
    }

    if (this.opts.config && this.cache && this.opts.cacheKey) {
      compiler.plugin('compilation', function(compilation) {
        compilation.__startTime = +new Date();
      });

      compiler.plugin('done', function(stats) {
        if (stats.hasErrors()) {
          this.cache.set(this.opts.cacheKey, undefined);
        } else {
          var entry = {
            startTime: stats.compilation.__startTime,
            fileDependencies: stats.compilation.fileDependencies,
            stats: this.processStats(stats),
            config: this.opts.config,
            optsHash: this.opts.hash
          };

          if (this.opts.watch && !this._onceDone.length) {
            this.onceWatcherDone(function(err) {
              if (err) {
                if (this.opts.logger) {
                  this.opts.logger.error('Webpack: cache population error for ' + this.getIdentifier(), err.stack);
                }
                return;
              }

              this.cache.set(this.opts.cacheKey, entry, true);
            }.bind(this));
          } else {
            this.cache.set(this.opts.cacheKey, entry, this.opts.watch);
          }
        }
      }.bind(this));
    }

    if (this.opts.watch && this.opts.hmrRoot) {
      hmr.bindCompiler(compiler, this.opts);
    }

    cb(null, compiler);
  }.bind(this));
};

Wrapper.prototype.compile = function compile(cb) {
  this.getCompiler(function(err, compiler) {
    if (err) return cb(err);

    compiler.run(function(err, stats) {
      if (!err && stats.hasErrors()) {
        err = _.first(stats.compilation.errors);
      }

      if (this.opts.logger) {
        this.opts.logger.info('Webpack: compiler built ' + this.getIdentifier());
      }

      this.handleErrAndStats(err, stats, cb);
    }.bind(this));
  }.bind(this));
};

Wrapper.prototype.processStats = function(stats) {
  if (!stats) return null;

  var processed = stats.toJson({
    modules: false,
    source: false
  });

  if (stats.compilation) {
    processed.pathsToAssets = _.transform(stats.compilation.assets, function(result, obj, asset) {
      result[asset] = obj.existsAt;
    }, {});

    processed.urlsToAssets = {};
    processed.rendered = {
      scripts: [],
      styleSheets: []
    };
    if (this.opts.staticRoot && this.opts.staticUrl) {
      _.forEach(processed.pathsToAssets, function(absPath, asset) {
        var rel = absPath.replace(this.opts.staticRoot, '');

        var parts = rel.split(path.sep);

        var relUrl = parts.join('/');

        if (_.startsWith(relUrl, '/')) {
          relUrl = relUrl.slice(1);
        }

        var url = this.opts.staticUrl + relUrl;

        processed.urlsToAssets[asset] = url;

        if (path.extname(rel) === '.css') {
          processed.rendered.styleSheets.push(
            '<link rel="stylesheet" href="' + url + '">'
          );
        }

        if (path.extname(rel) === '.js') {
          processed.rendered.scripts.push(
            '<script src="' + url + '"></script>'
          );
        }
      }, this);
    }
  }

  if (this.config) {
    processed.webpackConfig = this.config;
  } else if (this.opts.config) {
    try {
      processed.webpackConfig = require(this.opts.config);
    } catch(err) {}
  }

  return processed
};

Wrapper.prototype.handleErrAndStats = function(err, stats, cb) {
  if (!stats) {
    return cb(err, stats);
  }

  if (!err && stats && stats.compilation && stats.compilation.errors.length) {
    err = _.first(stats.compilation.errors);
  }

  cb(err, this.processStats(stats));
};

Wrapper.prototype.getWatcher = function getWatcher(cb) {
  if (this.watcher) {
    return cb(null, this.watcher);
  }

  this.getCompiler(function(err, compiler) {
    if (err) return cb(err);

    try {
      this.watcher = new Watcher(compiler, {
        aggregateTimeout: this.opts.aggregateTimeout,
        poll: this.opts.poll
      });
    } catch(err) {
      return cb(err);
    }

    if (this.opts.logger) {
      if (this.opts.config) {
        this.watcher.onInvalid(function() {
          this.opts.logger.info('Webpack: watcher detected a change and has invalidated ' + this.getIdentifier());
        }.bind(this));
      }

      this.watcher.onFailure(function(err) {
        this.opts.logger.error('Webpack: watcher failure', err.stack);
      }.bind(this));
    }

    cb(null, this.watcher);
  }.bind(this));
};

Wrapper.prototype.onceWatcherDone = function(cb) {
  this.getWatcher(function(err, watcher) {
    if (err) return cb(err);

    var currentStats = watcher.stats;

    watcher.onceDone(function(err, stats) {
      if (err) return cb(err, stats);

      if (this.opts.logger) {
        if (this.cache || (stats && currentStats === stats)) {
          this.opts.logger.info('Webpack: watcher provided current build output for ' + this.getIdentifier());
        } else {
          this.opts.logger.info('Webpack: watcher built ' + this.getIdentifier());
        }
      }

      this.handleErrAndStats(err, stats, cb);
    }.bind(this));

    this.watching = true;
  }.bind(this));
};

Wrapper.prototype.onceDone = function onceDone(cb) {
  this._onceDone.push(cb);

  if (this.opts.logger) {
    this.opts.logger.info('Webpack: requesting build of ' + this.getIdentifier());
  }

  if (this.opts.watch) {
    if (this._onceDone.length === 1) {
      this.onceWatcherDone(this.callDone.bind(this));
    }
  } else {
    this.compile(this.callDone.bind(this));
  }
};

Wrapper.prototype.callDone = function callDone(err, stats) {
  var _onceDone = this._onceDone;
  this._onceDone = [];

  _onceDone.forEach(function(cb) {
    cb(err, stats);
  }, this);
};

Wrapper.prototype.getIdentifier = function getIdentifier() {
  if (this.opts.cacheKey) {
    return this.opts.cacheKey;
  }
  if (this.opts.config) {
    return this.opts.config
  }
  return this.config;
};

Wrapper.prototype.watchFile = function watchFile(filename, cb) {
  if (Wrapper._watchedFiles[filename]) {
    Wrapper._watchedFiles[filename].push(cb);
  } else {
    Wrapper._watchedFiles[filename] = [cb];
    Wrapper._fileWatcher.add(filename);
  }
};

var _getFileWatcher = function() {
  var fileWatcher = new chokidar.FSWatcher();
  fileWatcher.on('change', Wrapper._onFileChange);
  return fileWatcher;
};

Wrapper._watchedFiles = {};

Wrapper._resetFileWatcher = function _resetFileWatcher() {
  if (Wrapper._fileWatcher) {
    Wrapper._fileWatcher.close();
    Wrapper._fileWatcher = _getFileWatcher();
  }
  Wrapper._watchedFiles = {};
};

Wrapper._onFileChange = function _onFileChange(filename) {
  var callbacks = Wrapper._watchedFiles[filename];
  if (callbacks && callbacks.length) {
    callbacks.forEach(function(cb) {
      cb();
    });
  }
};

Wrapper._fileWatcher = _getFileWatcher();

module.exports = Wrapper;<commit_msg>Bug fix for an uncaught exception triggered by certain option combinations<commit_after>'use strict';

var path = require('path');
var _ = require('lodash');
var webpack = require('webpack');
var chokidar = require('chokidar');
var Watcher = require('./Watcher');
var options = require('./options');
var hmr = require('./hmr');
var builds = require('./builds');

var Wrapper = function Wrapper(opts, config, cache) {
  this.opts = options.generate(opts);

  // TODO: remove this, should simply pass the config obj as `opts.config`
  // Convenience hook to pass an object in. You can also define
  // `opts.config` as a path to a file
  this.config = config;

  this.cache = cache;

  // State
  this.watcher = null;
  this.watching = false;
  this.watchingConfig = false;

  // Callbacks
  this._onceDone = [];
};

Wrapper.prototype.invalidate = function invalidate() {
  if (this.watching) {
    this.watcher.invalidate();
  }
};

Wrapper.prototype.invalidateConfig = function invalidateConfig() {
  if (this.opts.logger) {
    this.opts.logger.info('Webpack: invalidating config file require cache for ' + this.getIdentifier());
  }

  this.config = null;

  if (_.isString(this.opts.config)) {
    delete require.cache[this.opts.config];
  }

  if (this.watching) {
    this.watcher.close();
    this.watcher = null;
    this.watching = false;

    if (this.opts.logger) {
      this.opts.logger.info('Webpack: closed watcher for ' + this.getIdentifier());
    }
  }

  this.invalidate();
};

Wrapper.prototype.getConfig = function getConfig(cb) {
  if (this.config) {
    return cb(null, this.config);
  }

  if (!this.opts.config) {
    return cb(new Error('Wrapper options missing `config` value'));
  }

  this.config = this.opts.config;

  if (_.isString(this.config)) {
    try {
      this.config = require(this.config);
    } catch(err) {
      this.config = null;
      return cb(err);
    }

    if (this.opts.watchConfig && !this.watchingConfig) {
      this.watchingConfig = true;
      if (this.opts.logger) {
        this.opts.logger.info('Webpack: watching config file ' + this.opts.config);
      }
      this.watchFile(this.opts.config, function() {
        if (this.opts.logger) {
          this.opts.logger.info('Webpack: change detected in config file ' + this.opts.config);
        }
        this.invalidateConfig();
      }.bind(this));
    }
  }

  if (this.config && this.opts.hmr) {
    try {
      this.config = builds.hmr(this.config, this.opts);
    } catch(err) {
      return cb(err);
    }
  }

  if (this.config && this.opts.build) {
    if (!this.config.builds) {
      return cb(new Error('No builds property has been defined on ' + this.opts.config));
    }

    if (this.opts.build in this.config.builds) {
      if (this.opts.logger) {
        this.opts.logger.info('Webpack: applying build "' + this.opts.build + '" to ' + this.opts.config);
      }

      try {
        this.config = this.config.builds[this.opts.build](this.config, this.opts);
      } catch(err) {
        return cb(err);
      }
    } else {
      return cb(new Error(
        'Unknown build "' + this.opts.build + '". ' +
        'Available builds: ' + Object.keys(this.config.builds).join(', ')
      ));
    }
  }

  if (this.opts.outputPath && this.config.output) {
    this.config.output.path = this.opts.outputPath;
  }

  cb(null, this.config)
};

Wrapper.prototype.getCompiler = function getCompiler(cb) {
  this.getConfig(function(err, config) {
    if (err) return cb(err);

    var compiler = webpack(config);

    if (this.opts.logger) {
      compiler.plugin('done', function(stats) {
        if (stats.hasErrors()) {
          this.opts.logger.error('Webpack: build error', stats.compilation.errors[0].stack);
        } else {
          this.opts.logger.info('Webpack: build completed for ' + this.getIdentifier());
        }
      }.bind(this));
    }

    if (this.opts.config && this.cache && this.opts.cacheKey) {
      compiler.plugin('compilation', function(compilation) {
        compilation.__startTime = +new Date();
      });

      compiler.plugin('done', function(stats) {
        if (stats.hasErrors()) {
          this.cache.set(this.opts.cacheKey, undefined);
        } else {
          var entry = {
            startTime: stats.compilation.__startTime,
            fileDependencies: stats.compilation.fileDependencies,
            stats: this.processStats(stats),
            config: this.opts.config,
            optsHash: this.opts.hash
          };

          if (this.opts.watch && !this._onceDone.length) {
            this.onceWatcherDone(function(err) {
              if (err) {
                if (this.opts.logger) {
                  this.opts.logger.error('Webpack: cache population error for ' + this.getIdentifier(), err.stack);
                }
                return;
              }

              this.cache.set(this.opts.cacheKey, entry, true);
            }.bind(this));
          } else {
            this.cache.set(this.opts.cacheKey, entry, this.opts.watch);
          }
        }
      }.bind(this));
    }

    if (this.opts.watch && this.opts.hmr && this.opts.hmrRoot) {
      hmr.bindCompiler(compiler, this.opts);
    }

    cb(null, compiler);
  }.bind(this));
};

Wrapper.prototype.compile = function compile(cb) {
  this.getCompiler(function(err, compiler) {
    if (err) return cb(err);

    compiler.run(function(err, stats) {
      if (!err && stats.hasErrors()) {
        err = _.first(stats.compilation.errors);
      }

      if (this.opts.logger) {
        this.opts.logger.info('Webpack: compiler built ' + this.getIdentifier());
      }

      this.handleErrAndStats(err, stats, cb);
    }.bind(this));
  }.bind(this));
};

Wrapper.prototype.processStats = function(stats) {
  if (!stats) return null;

  var processed = stats.toJson({
    modules: false,
    source: false
  });

  if (stats.compilation) {
    processed.pathsToAssets = _.transform(stats.compilation.assets, function(result, obj, asset) {
      result[asset] = obj.existsAt;
    }, {});

    processed.urlsToAssets = {};
    processed.rendered = {
      scripts: [],
      styleSheets: []
    };
    if (this.opts.staticRoot && this.opts.staticUrl) {
      _.forEach(processed.pathsToAssets, function(absPath, asset) {
        var rel = absPath.replace(this.opts.staticRoot, '');

        var parts = rel.split(path.sep);

        var relUrl = parts.join('/');

        if (_.startsWith(relUrl, '/')) {
          relUrl = relUrl.slice(1);
        }

        var url = this.opts.staticUrl + relUrl;

        processed.urlsToAssets[asset] = url;

        if (path.extname(rel) === '.css') {
          processed.rendered.styleSheets.push(
            '<link rel="stylesheet" href="' + url + '">'
          );
        }

        if (path.extname(rel) === '.js') {
          processed.rendered.scripts.push(
            '<script src="' + url + '"></script>'
          );
        }
      }, this);
    }
  }

  if (this.config) {
    processed.webpackConfig = this.config;
  } else if (this.opts.config) {
    try {
      processed.webpackConfig = require(this.opts.config);
    } catch(err) {}
  }

  return processed
};

Wrapper.prototype.handleErrAndStats = function(err, stats, cb) {
  if (!stats) {
    return cb(err, stats);
  }

  if (!err && stats && stats.compilation && stats.compilation.errors.length) {
    err = _.first(stats.compilation.errors);
  }

  cb(err, this.processStats(stats));
};

Wrapper.prototype.getWatcher = function getWatcher(cb) {
  if (this.watcher) {
    return cb(null, this.watcher);
  }

  this.getCompiler(function(err, compiler) {
    if (err) return cb(err);

    try {
      this.watcher = new Watcher(compiler, {
        aggregateTimeout: this.opts.aggregateTimeout,
        poll: this.opts.poll
      });
    } catch(err) {
      return cb(err);
    }

    if (this.opts.logger) {
      if (this.opts.config) {
        this.watcher.onInvalid(function() {
          this.opts.logger.info('Webpack: watcher detected a change and has invalidated ' + this.getIdentifier());
        }.bind(this));
      }

      this.watcher.onFailure(function(err) {
        this.opts.logger.error('Webpack: watcher failure', err.stack);
      }.bind(this));
    }

    cb(null, this.watcher);
  }.bind(this));
};

Wrapper.prototype.onceWatcherDone = function(cb) {
  this.getWatcher(function(err, watcher) {
    if (err) return cb(err);

    var currentStats = watcher.stats;

    watcher.onceDone(function(err, stats) {
      if (err) return cb(err, stats);

      if (this.opts.logger) {
        if (this.cache || (stats && currentStats === stats)) {
          this.opts.logger.info('Webpack: watcher provided current build output for ' + this.getIdentifier());
        } else {
          this.opts.logger.info('Webpack: watcher built ' + this.getIdentifier());
        }
      }

      this.handleErrAndStats(err, stats, cb);
    }.bind(this));

    this.watching = true;
  }.bind(this));
};

Wrapper.prototype.onceDone = function onceDone(cb) {
  this._onceDone.push(cb);

  if (this.opts.logger) {
    this.opts.logger.info('Webpack: requesting build of ' + this.getIdentifier());
  }

  if (this.opts.watch) {
    if (this._onceDone.length === 1) {
      this.onceWatcherDone(this.callDone.bind(this));
    }
  } else {
    this.compile(this.callDone.bind(this));
  }
};

Wrapper.prototype.callDone = function callDone(err, stats) {
  var _onceDone = this._onceDone;
  this._onceDone = [];

  _onceDone.forEach(function(cb) {
    cb(err, stats);
  }, this);
};

Wrapper.prototype.getIdentifier = function getIdentifier() {
  if (this.opts.cacheKey) {
    return this.opts.cacheKey;
  }
  if (this.opts.config) {
    return this.opts.config
  }
  return this.config;
};

Wrapper.prototype.watchFile = function watchFile(filename, cb) {
  if (Wrapper._watchedFiles[filename]) {
    Wrapper._watchedFiles[filename].push(cb);
  } else {
    Wrapper._watchedFiles[filename] = [cb];
    Wrapper._fileWatcher.add(filename);
  }
};

var _getFileWatcher = function() {
  var fileWatcher = new chokidar.FSWatcher();
  fileWatcher.on('change', Wrapper._onFileChange);
  return fileWatcher;
};

Wrapper._watchedFiles = {};

Wrapper._resetFileWatcher = function _resetFileWatcher() {
  if (Wrapper._fileWatcher) {
    Wrapper._fileWatcher.close();
    Wrapper._fileWatcher = _getFileWatcher();
  }
  Wrapper._watchedFiles = {};
};

Wrapper._onFileChange = function _onFileChange(filename) {
  var callbacks = Wrapper._watchedFiles[filename];
  if (callbacks && callbacks.length) {
    callbacks.forEach(function(cb) {
      cb();
    });
  }
};

Wrapper._fileWatcher = _getFileWatcher();

module.exports = Wrapper;<|endoftext|>


<commit_before>// LICENSE : MIT
"use strict";
import {RuleHelper} from "textlint-rule-helper";
import StructuredSource from "structured-source";
import prh from "prh";
import path from "path";
export default function (context, options) {
    if (typeof options === "undefined" || typeof options.rulePaths === "undefined") {
        throw new Error(`textlint-rule-prh require Rule Options.
Please set .textlinrc:
{
    "rules": {
        "prh": {
            "rulePaths" :["path/to/rule.yaml"]
        }
    }
}
`);
    }
    var configFilePath = context.config ? context.config.configFile : null;
    // .textlinrc directory
    var textlintRCDir = configFilePath ? path.dirname(configFilePath) : process.cwd();
    let helper = new RuleHelper(context);
    let {Syntax, getSource, report, RuleError} = context;
    var rulePaths = options.rulePaths;
    var config = prh.fromYAMLFilePath(path.resolve(textlintRCDir, rulePaths[0]));
    rulePaths.splice(1).forEach(function (rulePath) {
        var c = prh.fromYAMLFilePath(path.resolve(textlintRCDir, rulePath));
        config.merge(c);
    });
    return {
        [Syntax.Str](node){
            if (helper.isChildNode(node, [Syntax.Link, Syntax.Image, Syntax.BlockQuote, Syntax.Emphasis])) {
                return;
            }
            let text = getSource(node);
            // to get position from index
            let src = new StructuredSource(text);
            let makeChangeSet = config.makeChangeSet(null, text);
            makeChangeSet.diffs.forEach(function (changeSet) {
                // | ----[match]------
                var slicedText = text.slice(changeSet.index);
                // | ----[match------|
                var matchedText = slicedText.slice(0, changeSet.matches[0].length);
                var expected = matchedText.replace(changeSet.pattern, changeSet.expected);
                // Avoid accidental match(ignore case, expected contain actual pattern)
                if (slicedText.indexOf(expected) === 0) {
                    return;
                }
                /*
                line start with 1
                column start with 0

                adjust position => line -1, column +0
                 */
                var position = src.indexToPosition(changeSet.index);

                // line, column
                context.report(node, new RuleError(changeSet.matches[0] + " => " + expected, {
                    line: position.line - 1,
                    column: position.column
                }));
            });
        }
    }
}<commit_msg>fix(src): fix to break rulePaths<commit_after>// LICENSE : MIT
"use strict";
import {RuleHelper} from "textlint-rule-helper";
import StructuredSource from "structured-source";
import prh from "prh";
import path from "path";
export default function (context, options) {
    if (typeof options === "undefined" || typeof options.rulePaths === "undefined") {
        throw new Error(`textlint-rule-prh require Rule Options.
Please set .textlinrc:
{
    "rules": {
        "prh": {
            "rulePaths" :["path/to/rule.yaml"]
        }
    }
}
`);
    }
    var configFilePath = context.config ? context.config.configFile : null;
    // .textlinrc directory
    var textlintRCDir = configFilePath ? path.dirname(configFilePath) : process.cwd();
    let helper = new RuleHelper(context);
    let {Syntax, getSource, report, RuleError} = context;
    var rulePaths = options.rulePaths.slice();
    var config = prh.fromYAMLFilePath(path.resolve(textlintRCDir, rulePaths[0]));
    rulePaths.slice(1).forEach(function (rulePath) {
        var c = prh.fromYAMLFilePath(path.resolve(textlintRCDir, rulePath));
        config.merge(c);
    });
    return {
        [Syntax.Str](node){
            if (helper.isChildNode(node, [Syntax.Link, Syntax.Image, Syntax.BlockQuote, Syntax.Emphasis])) {
                return;
            }
            let text = getSource(node);
            // to get position from index
            let src = new StructuredSource(text);
            let makeChangeSet = config.makeChangeSet(null, text);
            makeChangeSet.diffs.forEach(function (changeSet) {
                // | ----[match]------
                var slicedText = text.slice(changeSet.index);
                // | ----[match------|
                var matchedText = slicedText.slice(0, changeSet.matches[0].length);
                var expected = matchedText.replace(changeSet.pattern, changeSet.expected);
                // Avoid accidental match(ignore case, expected contain actual pattern)
                if (slicedText.indexOf(expected) === 0) {
                    return;
                }
                /*
                line start with 1
                column start with 0

                adjust position => line -1, column +0
                 */
                var position = src.indexToPosition(changeSet.index);

                // line, column
                report(node, new RuleError(changeSet.matches[0] + " => " + expected, {
                    line: position.line - 1,
                    column: position.column
                }));
            });
        }
    }
}<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import {
  View,
  StyleSheet,
  TouchableHighlight,
  Image,
  Platform,
  Switch,
  TextInput,
} from 'react-native';
import Badge from '../badge/badge';
import Icon from '../icons/Icon';
import Text from '../text/Text';
import colors from '../config/colors';
import fonts from '../config/fonts';
import normalize from '../helpers/normalizeText';

const ListItem = props => {
  const {
    onPress,
    title,
    leftIcon,
    rightIcon,
    leftIconContainerStyle,
    avatarStyle,
    underlayColor,
    subtitle,
    subtitleStyle,
    containerStyle,
    wrapperStyle,
    titleStyle,
    titleContainerStyle,
    hideChevron,
    chevronColor,
    roundAvatar,
    component,
    fontFamily,
    rightTitle,
    rightTitleContainerStyle,
    rightTitleStyle,
    subtitleContainerStyle,
    badge,
    label,
    onLongPress,
    switchButton,
    onSwitch,
    switchDisabled,
    switchOnTintColor,
    switchThumbTintColor,
    switchTintColor,
    switched,
    textInput,
    textInputAutoCapitalize,
    textInputAutoCorrect,
    textInputAutoFocus,
    textInputEditable,
    textInputKeyboardType,
    textInputMaxLength,
    textInputMultiline,
    textInputOnChangeText,
    textInputOnFocus,
    textInputOnBlur,
    textInputSelectTextOnFocus,
    textInputReturnKeyType,
    textInputValue,
    textInputSecure,
    textInputStyle,
    textInputContainerStyle,
    ...attributes
  } = props;

  let { avatar } = props;

  let Component = onPress || onLongPress ? TouchableHighlight : View;
  if (component) {
    Component = component;
  }
  if (typeof avatar === 'string') {
    avatar = { uri: avatar };
  }
  return (
    <Component
      onLongPress={onLongPress}
      onPress={onPress}
      underlayColor={underlayColor}
      style={[styles.container, containerStyle && containerStyle]}
      {...attributes}
    >
      <View style={[styles.wrapper, wrapperStyle && wrapperStyle]}>
        {React.isValidElement(leftIcon)
          ? leftIcon
          : leftIcon &&
              leftIcon.name &&
              <View
                style={[
                  styles.iconStyle,
                  leftIconContainerStyle && leftIconContainerStyle,
                ]}
              >
                <Icon
                  type={leftIcon.type}
                  iconStyle={[styles.icon, leftIcon.style && leftIcon.style]}
                  name={leftIcon.name}
                  color={leftIcon.color || colors.grey4}
                  size={leftIcon.size || 24}
                />
              </View>}
        {avatar &&
          <Image
            style={[
              styles.avatar,
              roundAvatar && { borderRadius: 17 },
              avatarStyle && avatarStyle,
            ]}
            source={avatar}
          />}
        <View style={styles.titleSubtitleContainer}>
          <View style={titleContainerStyle}>
            {title && (typeof title === 'string' || typeof title === 'number')
              ? <Text
                  style={[
                    styles.title,
                    !leftIcon && { marginLeft: 10 },
                    titleStyle && titleStyle,
                    fontFamily && { fontFamily },
                  ]}
                >
                  {title}
                </Text>
              : <View>
                  {title}
                </View>}
          </View>
          <View style={subtitleContainerStyle}>
            {subtitle &&
              (typeof subtitle === 'string' || typeof subtitle === 'number')
              ? <Text
                  style={[
                    styles.subtitle,
                    !leftIcon && { marginLeft: 10 },
                    subtitleStyle && subtitleStyle,
                    fontFamily && { fontFamily },
                  ]}
                >
                  {subtitle}
                </Text>
              : <View>
                  {subtitle}
                </View>}
          </View>
        </View>
        {rightTitle &&
          rightTitle !== '' &&
          !textInput &&
          <View style={[styles.rightTitleContainer, rightTitleContainerStyle]}>
            <Text style={[styles.rightTitleStyle, rightTitleStyle]}>
              {rightTitle}
            </Text>
          </View>}
        {textInput &&
          <View style={[styles.rightTitleContainer, textInputContainerStyle]}>
            <TextInput
              style={[styles.textInputStyle, textInputStyle]}
              defaultValue={rightTitle}
              value={textInputValue}
              autoCapitalize={textInputAutoCapitalize}
              autoCorrect={textInputAutoCorrect}
              autoFocus={textInputAutoFocus}
              editable={textInputEditable}
              keyboardType={textInputKeyboardType}
              maxLength={textInputMaxLength}
              multiline={textInputMultiline}
              onChangeText={textInputOnChangeText}
              onFocus={textInputOnFocus}
              onBlur={textInputOnBlur}
              secureTextEntry={textInputSecure}
              selectTextOnFocus={textInputSelectTextOnFocus}
              returnKeyType={textInputReturnKeyType}
            />
          </View>}
        {!hideChevron &&
          (React.isValidElement(rightIcon)
            ? rightIcon
            : <View style={styles.chevronContainer}>
                <Icon
                  type={rightIcon.type}
                  iconStyle={rightIcon.style}
                  size={28}
                  name={rightIcon.name || 'chevron-right'}
                  color={rightIcon.color || chevronColor}
                />
              </View>)}
        {switchButton &&
          hideChevron &&
          <View style={styles.switchContainer}>
            <Switch
              onValueChange={onSwitch}
              disabled={switchDisabled}
              onTintColor={switchOnTintColor}
              thumbTintColor={switchThumbTintColor}
              tintColor={switchTintColor}
              value={switched}
            />
          </View>}
        {badge && !rightTitle && <Badge {...badge} />}
        {label && label}
      </View>
    </Component>
  );
};

ListItem.defaultProps = {
  underlayColor: 'white',
  chevronColor: colors.grey4,
  rightIcon: { name: 'chevron-right' },
  hideChevron: false,
  roundAvatar: false,
  switchButton: false,
  textInputEditable: true,
};

ListItem.propTypes = {
  title: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.object,
  ]),
  avatar: PropTypes.any,
  icon: PropTypes.any,
  onPress: PropTypes.func,
  rightIcon: PropTypes.oneOfType([PropTypes.element, PropTypes.object]),
  underlayColor: PropTypes.string,
  subtitle: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.object,
  ]),
  subtitleStyle: PropTypes.any,
  containerStyle: PropTypes.any,
  wrapperStyle: PropTypes.any,
  titleStyle: PropTypes.any,
  titleContainerStyle: PropTypes.any,
  hideChevron: PropTypes.bool,
  chevronColor: PropTypes.string,
  roundAvatar: PropTypes.bool,
  badge: PropTypes.any,
  switchButton: PropTypes.bool,
  onSwitch: PropTypes.func,
  switchDisabled: PropTypes.bool,
  switchOnTintColor: PropTypes.string,
  switchThumbTintColor: PropTypes.string,
  switchTintColor: PropTypes.string,
  switched: PropTypes.bool,
  textInput: PropTypes.bool,
  textInputAutoCapitalize: PropTypes.bool,
  textInputAutoCorrect: PropTypes.bool,
  textInputAutoFocus: PropTypes.bool,
  textInputEditable: PropTypes.bool,
  textInputKeyboardType: PropTypes.oneOf([
    'default',
    'email-address',
    'numeric',
    'phone-pad',
    'ascii-capable',
    'numbers-and-punctuation',
    'url',
    'number-pad',
    'name-phone-pad',
    'decimal-pad',
    'twitter',
    'web-search',
  ]),
  textInputMaxLength: PropTypes.number,
  textInputMultiline: PropTypes.bool,
  textInputOnChangeText: PropTypes.func,
  textInputOnFocus: PropTypes.func,
  textInputOnBlur: PropTypes.func,
  textInputSelectTextOnFocus: PropTypes.bool,
  textInputReturnKeyType: PropTypes.string,
  textInputValue: PropTypes.string,
  textInputSecure: PropTypes.bool,
  textInputStyle: PropTypes.any,
  textInputContainerStyle: PropTypes.any,
  component: PropTypes.any,
  fontFamily: PropTypes.string,
  rightTitle: PropTypes.string,
  rightTitleContainerStyle: View.propTypes.style,
  rightTitleStyle: Text.propTypes.style,
  subtitleContainerStyle: View.propTypes.style,
  label: PropTypes.any,
  onLongPress: PropTypes.func,
  leftIcon: PropTypes.oneOfType([PropTypes.element, PropTypes.object]),
  leftIconContainerStyle: View.propTypes.style,
  avatarStyle: View.propTypes.style,
};

const styles = StyleSheet.create({
  avatar: {
    width: 34,
    height: 34,
  },
  container: {
    paddingTop: 10,
    paddingRight: 10,
    paddingBottom: 10,
    borderBottomColor: '#ededed',
    borderBottomWidth: 1,
    backgroundColor: 'transparent',
  },
  wrapper: {
    flexDirection: 'row',
    marginLeft: 10,
  },
  iconStyle: {
    flex: 0.15,
    justifyContent: 'center',
    alignItems: 'center',
  },
  icon: {
    marginRight: 8,
  },
  title: {
    fontSize: normalize(14),
    color: colors.grey1,
  },
  subtitle: {
    color: colors.grey3,
    fontSize: normalize(12),
    marginTop: 1,
    ...Platform.select({
      ios: {
        fontWeight: '600',
      },
      android: {
        ...fonts.android.bold,
      },
    }),
  },
  titleSubtitleContainer: {
    justifyContent: 'center',
    flex: 1,
  },
  chevronContainer: {
    flex: 0.15,
    alignItems: 'flex-end',
    justifyContent: 'center',
  },
  switchContainer: {
    flex: 0.15,
    alignItems: 'flex-end',
    justifyContent: 'center',
    marginRight: 5,
  },
  rightTitleContainer: {
    flex: 1,
    alignItems: 'flex-end',
    justifyContent: 'center',
  },
  rightTitleStyle: {
    marginRight: 5,
    color: colors.grey4,
  },
  textInputStyle: {
    height: 20,
    textAlign: 'right',
  },
});

export default ListItem;
<commit_msg>Fix #352<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import {
  View,
  StyleSheet,
  TouchableHighlight,
  Image,
  Platform,
  Switch,
  TextInput,
} from 'react-native';
import Badge from '../badge/badge';
import Icon from '../icons/Icon';
import Text from '../text/Text';
import colors from '../config/colors';
import fonts from '../config/fonts';
import normalize from '../helpers/normalizeText';

const ListItem = props => {
  const {
    onPress,
    title,
    leftIcon,
    rightIcon,
    leftIconContainerStyle,
    avatarStyle,
    underlayColor,
    subtitle,
    subtitleStyle,
    containerStyle,
    wrapperStyle,
    titleStyle,
    titleContainerStyle,
    hideChevron,
    chevronColor,
    roundAvatar,
    component,
    fontFamily,
    rightTitle,
    rightTitleContainerStyle,
    rightTitleStyle,
    subtitleContainerStyle,
    badge,
    label,
    onLongPress,
    switchButton,
    onSwitch,
    switchDisabled,
    switchOnTintColor,
    switchThumbTintColor,
    switchTintColor,
    switched,
    textInput,
    textInputAutoCapitalize,
    textInputAutoCorrect,
    textInputAutoFocus,
    textInputEditable,
    textInputKeyboardType,
    textInputMaxLength,
    textInputMultiline,
    textInputOnChangeText,
    textInputOnFocus,
    textInputOnBlur,
    textInputSelectTextOnFocus,
    textInputReturnKeyType,
    textInputValue,
    textInputSecure,
    textInputStyle,
    textInputContainerStyle,
    ...attributes
  } = props;

  let { avatar } = props;

  let Component = onPress || onLongPress ? TouchableHighlight : View;
  if (component) {
    Component = component;
  }
  if (typeof avatar === 'string') {
    avatar = { uri: avatar };
  }
  return (
    <Component
      onLongPress={onLongPress}
      onPress={onPress}
      underlayColor={underlayColor}
      style={[styles.container, containerStyle && containerStyle]}
      {...attributes}
    >
      <View style={[styles.wrapper, wrapperStyle && wrapperStyle]}>
        {React.isValidElement(leftIcon)
          ? leftIcon
          : leftIcon &&
              leftIcon.name &&
              <View
                style={[
                  styles.iconStyle,
                  leftIconContainerStyle && leftIconContainerStyle,
                ]}
              >
                <Icon
                  type={leftIcon.type}
                  iconStyle={[styles.icon, leftIcon.style && leftIcon.style]}
                  name={leftIcon.name}
                  color={leftIcon.color || colors.grey4}
                  size={leftIcon.size || 24}
                />
              </View>}
        {avatar &&
          <Image
            style={[
              styles.avatar,
              roundAvatar && { borderRadius: 17 },
              avatarStyle && avatarStyle,
            ]}
            source={avatar}
          />}
        <View style={styles.titleSubtitleContainer}>
          <View style={titleContainerStyle}>
            {title && (typeof title === 'string' || typeof title === 'number')
              ? <Text
                  style={[
                    styles.title,
                    !leftIcon && { marginLeft: 10 },
                    titleStyle && titleStyle,
                    fontFamily && { fontFamily },
                  ]}
                >
                  {title}
                </Text>
              : <View>
                  {title}
                </View>}
          </View>
          <View style={subtitleContainerStyle}>
            {subtitle &&
              (typeof subtitle === 'string' || typeof subtitle === 'number')
              ? <Text
                  style={[
                    styles.subtitle,
                    !leftIcon && { marginLeft: 10 },
                    subtitleStyle && subtitleStyle,
                    fontFamily && { fontFamily },
                  ]}
                >
                  {subtitle}
                </Text>
              : <View>
                  {subtitle}
                </View>}
          </View>
        </View>
        {rightTitle &&
          rightTitle !== '' &&
          !textInput &&
          <View style={[styles.rightTitleContainer, rightTitleContainerStyle]}>
            <Text style={[styles.rightTitleStyle, rightTitleStyle]}>
              {rightTitle}
            </Text>
          </View>}
        {textInput &&
          <View style={[styles.rightTitleContainer, textInputContainerStyle]}>
            <TextInput
              style={[styles.textInputStyle, textInputStyle]}
              defaultValue={rightTitle}
              value={textInputValue}
              autoCapitalize={textInputAutoCapitalize}
              autoCorrect={textInputAutoCorrect}
              autoFocus={textInputAutoFocus}
              editable={textInputEditable}
              keyboardType={textInputKeyboardType}
              maxLength={textInputMaxLength}
              multiline={textInputMultiline}
              onChangeText={textInputOnChangeText}
              onFocus={textInputOnFocus}
              onBlur={textInputOnBlur}
              secureTextEntry={textInputSecure}
              selectTextOnFocus={textInputSelectTextOnFocus}
              returnKeyType={textInputReturnKeyType}
            />
          </View>}
        {badge && !rightTitle && <Badge {...badge} />}
        {!hideChevron &&
          (React.isValidElement(rightIcon)
            ? rightIcon
            : <View style={styles.chevronContainer}>
                <Icon
                  type={rightIcon.type}
                  iconStyle={rightIcon.style}
                  size={28}
                  name={rightIcon.name || 'chevron-right'}
                  color={rightIcon.color || chevronColor}
                />
              </View>)}
        {switchButton &&
          hideChevron &&
          <View style={styles.switchContainer}>
            <Switch
              onValueChange={onSwitch}
              disabled={switchDisabled}
              onTintColor={switchOnTintColor}
              thumbTintColor={switchThumbTintColor}
              tintColor={switchTintColor}
              value={switched}
            />
          </View>}
        {label && label}
      </View>
    </Component>
  );
};

ListItem.defaultProps = {
  underlayColor: 'white',
  chevronColor: colors.grey4,
  rightIcon: { name: 'chevron-right' },
  hideChevron: false,
  roundAvatar: false,
  switchButton: false,
  textInputEditable: true,
};

ListItem.propTypes = {
  title: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.object,
  ]),
  avatar: PropTypes.any,
  icon: PropTypes.any,
  onPress: PropTypes.func,
  rightIcon: PropTypes.oneOfType([PropTypes.element, PropTypes.object]),
  underlayColor: PropTypes.string,
  subtitle: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.object,
  ]),
  subtitleStyle: PropTypes.any,
  containerStyle: PropTypes.any,
  wrapperStyle: PropTypes.any,
  titleStyle: PropTypes.any,
  titleContainerStyle: PropTypes.any,
  hideChevron: PropTypes.bool,
  chevronColor: PropTypes.string,
  roundAvatar: PropTypes.bool,
  badge: PropTypes.any,
  switchButton: PropTypes.bool,
  onSwitch: PropTypes.func,
  switchDisabled: PropTypes.bool,
  switchOnTintColor: PropTypes.string,
  switchThumbTintColor: PropTypes.string,
  switchTintColor: PropTypes.string,
  switched: PropTypes.bool,
  textInput: PropTypes.bool,
  textInputAutoCapitalize: PropTypes.bool,
  textInputAutoCorrect: PropTypes.bool,
  textInputAutoFocus: PropTypes.bool,
  textInputEditable: PropTypes.bool,
  textInputKeyboardType: PropTypes.oneOf([
    'default',
    'email-address',
    'numeric',
    'phone-pad',
    'ascii-capable',
    'numbers-and-punctuation',
    'url',
    'number-pad',
    'name-phone-pad',
    'decimal-pad',
    'twitter',
    'web-search',
  ]),
  textInputMaxLength: PropTypes.number,
  textInputMultiline: PropTypes.bool,
  textInputOnChangeText: PropTypes.func,
  textInputOnFocus: PropTypes.func,
  textInputOnBlur: PropTypes.func,
  textInputSelectTextOnFocus: PropTypes.bool,
  textInputReturnKeyType: PropTypes.string,
  textInputValue: PropTypes.string,
  textInputSecure: PropTypes.bool,
  textInputStyle: PropTypes.any,
  textInputContainerStyle: PropTypes.any,
  component: PropTypes.any,
  fontFamily: PropTypes.string,
  rightTitle: PropTypes.string,
  rightTitleContainerStyle: View.propTypes.style,
  rightTitleStyle: Text.propTypes.style,
  subtitleContainerStyle: View.propTypes.style,
  label: PropTypes.any,
  onLongPress: PropTypes.func,
  leftIcon: PropTypes.oneOfType([PropTypes.element, PropTypes.object]),
  leftIconContainerStyle: View.propTypes.style,
  avatarStyle: View.propTypes.style,
};

const styles = StyleSheet.create({
  avatar: {
    width: 34,
    height: 34,
  },
  container: {
    paddingTop: 10,
    paddingRight: 10,
    paddingBottom: 10,
    borderBottomColor: '#ededed',
    borderBottomWidth: 1,
    backgroundColor: 'transparent',
  },
  wrapper: {
    flexDirection: 'row',
    marginLeft: 10,
  },
  iconStyle: {
    flex: 0.15,
    justifyContent: 'center',
    alignItems: 'center',
  },
  icon: {
    marginRight: 8,
  },
  title: {
    fontSize: normalize(14),
    color: colors.grey1,
  },
  subtitle: {
    color: colors.grey3,
    fontSize: normalize(12),
    marginTop: 1,
    ...Platform.select({
      ios: {
        fontWeight: '600',
      },
      android: {
        ...fonts.android.bold,
      },
    }),
  },
  titleSubtitleContainer: {
    justifyContent: 'center',
    flex: 1,
  },
  chevronContainer: {
    flex: 0.15,
    alignItems: 'flex-end',
    justifyContent: 'center',
  },
  switchContainer: {
    flex: 0.15,
    alignItems: 'flex-end',
    justifyContent: 'center',
    marginRight: 5,
  },
  rightTitleContainer: {
    flex: 1,
    alignItems: 'flex-end',
    justifyContent: 'center',
  },
  rightTitleStyle: {
    marginRight: 5,
    color: colors.grey4,
  },
  textInputStyle: {
    height: 20,
    textAlign: 'right',
  },
});

export default ListItem;
<|endoftext|>


<commit_before>'use strict'

class PriorityNode {
  constructor(data, priority) {
    this.data = data;
    this.next = null;
    this.priority = priority;
  }
}

export default class Priority {

  constructor(data) {
    this.head = null
    this.tail = null
    this.size = 0
  }

  enqueue( data, priority ) {
    const newPriorityNode = new PriorityNode( data, priority ) //{ data: 'foo', next: null}
    if( this.size === 0 ) {
      this.head = newPriorityNode
      this.tail = newPriorityNode
      this.size++
    } else {
      newPriorityNode.next = this.tail // newPriorityNode = { data: 'foo', next:{data: 'roo', next: null}}
      //this.tail = {{data: 'roo', next: null}
      this.tail = newPriorityNode
      this.size++
    }
  }

  dequeue() {
    if( this.size === 0 ) {
      return null
    } else {
      let removedNode = this.head
      this.head = this.next;
      this.size--;
      return removedNode
    }
  }

  front() {
    if(this.head) {
      return this.head;
    } else {
      return null;
    }
  }

  back(){
    if(this.tail) {
      return this.tail;
    } else {
      return null;
    }

  }

  isEmpty(){
    if () {
      return true
    } else {
      return false
    }
  }

  length(){
    return this.size
  }
}

const queue = new Queue()

queue.enqueue('foo')
// bayarea.push('fred')
// bayarea.push('BMW')
<commit_msg>Competed Priority Queue<commit_after>'use strict'

class PriorityNode {
  constructor(data, priority) {
    this.data = data;
    this.next = null;
    this.priority = priority;
  }
}

export default class Priority {

  constructor(data) {
    this.head = null
    this.tail = null
    this.size = 0
  }

  enqueue( data, priority ) {
    const newPriorityNode = new PriorityNode( data, priority ) //{ data: 'foo', next: null}
    if( this.size === 0 ) {
      this.head = newPriorityNode
      this.tail = newPriorityNode
      this.size++
    } else {
      newPriorityNode.next = this.tail // newPriorityNode = { data: 'foo', next:{data: 'roo', next: null}}
      //this.tail = {{data: 'roo', next: null}
      this.tail = newPriorityNode
      this.size++
    }
  }

  dequeue() {
    if( this.size === 0 ) {
      return null
    } else {
      let removedNode = this.head
      this.head = this.next;
      this.size--;
      return removedNode
    }
  }

  front() {
    if(this.head) {
      return this.head;
    } else {
      return null;
    }
  }

  back(){
    if(this.tail) {
      return this.tail;
    } else {
      return null;
    }

  }

  isEmpty(){
    if () {
      return true
    } else {
      return false
    }
  }

  length(){
    return this.size
  }
}

const queue = new Queue()

queue.enqueue('foo')
// bayarea.push('fred')
// bayarea.push('BMW')
<|endoftext|>