<commit_before>!(function(window) {
    'use strict';

    // define main constants
    var ROOT       = 'LSP.';
    var STORE      = window.localStorage;
    var EXPIRE_KEY = '--exp';

    /**
     * Util functions
     * @private
     * @type {Object}
     */
    var util = {
        remove: function(key) {
            STORE.removeItem(key.replace(EXPIRE_KEY, ''));
            STORE.removeItem(key);
        },
        flush: function(index) {
            Object.keys(STORE).map(function(key) {
                if (key.indexOf(index) === 0) {
                    util.remove(key);
                }
            });
        },
        flushExpired: function(index) {
            if (Object.keys(STORE).length > 0) {
                Object.keys(STORE).map(function(key) {
                    if (key.indexOf(index) === 0 && key.indexOf(EXPIRE_KEY) !== -1) {
                        if (STORE.getItem(key) < Date.now()) {
                            util.remove(key);
                        }
                    }
                });
            }
        }
    }

    /**
     * Define a new store
     * @class
     * @param  {string} name            The name of the store
     * @param  {boolean} [flushExpired] should the flush expired not run
     * @return {Store}                  The store instance
     */
    var Store = function(name, flushExpired) {
        var storeName;

        function __construct(name) {
            try {
                storeName = validateStoreName(name);

                if (flushExpired === undefined || flushExpired !== false) {
                    flushExpired();
                }
            } catch(error) {
                console.error(error);
            }
        }

        /**
         * Set a defined key with the given value
         * @param  {string} key          The name of the value
         * @param  {mixed}  data         The data to store, can be any datatype
         * @param  {int}    [expiresAt]  When should this value expire
         * @return {void}
         */
        function set(key, data, expiresAt) {
            try {
                if (expiresAt !== undefined && typeof expiresAt === 'number') {
                    STORE.setItem(storeName + key + EXPIRE_KEY, expiresAt.toString());
                }

                STORE.setItem(storeName + key, decodeObjectString(data));

                return true;
            } catch(error) {
                console.error(error);
                return false;
            }
        }

        /**
         * Get the value stored under the given key, or the whole store
         * @param  {string} [key] Index defined in @set
         * @return {mixed}        Stored value
         */
        function get(key) {
            try {
                if (key !== undefined) {
                    var result = encodeObjectString(STORE.getItem(storeName + key));
                    return result !== null ? result : false;
                } else {
                    var resultAll = {};

                    Object.keys(STORE).map(function(key) {
                        if (key.indexOf(storeName) === 0 && key.indexOf(EXPIRE_KEY) === -1) {
                            var varKey = key.replace(storeName, '');
                            resultAll[varKey] = get(varKey);
                        }
                    });

                    return resultAll;
                }
            } catch(error) {
                console.error(error)
                return false;
            }
        }

        /**
         * Check if the given key exists in the store
         * @param  {string}  key  index of the value to test
         * @return {boolean}      Key defined or not
         */
        function isset(key) {
            return get(key) !== false ? true : false;
        }

        /**
         * Flush all values, that are stored in the store instance
         * @return {void}
         */
        function flush() {
            util.flush(storeName);
        }

        /**
         * Remove an item, by the given key and its expire if set
         * @param  {string} key  Index of the value
         * @return {void}
         */
        function remove(key) {
            util.remove(storeName + key);
        }

        /**
         * flush expired values defined in this store
         * @return {void}
         */
        function flushExpired() {
            util.flushExpired(storeName);
        }

        /**
         * generate a store name
         * @param  {string} storeName  The name of the store instance
         * @return {string}            The generated name
         * @throws {TypeError}
         */
        function validateStoreName(storeName) {
            if (storeName === undefined) {
                throw new TypeError('Please provide a storename');
            }

            if (typeof(storeName) !== 'string') {
                throw new TypeError('The storename has to be a string');
            }

            var chargedStoreName = storeName = ROOT + storeName + '-';
            return chargedStoreName;
        }

        /**
         * decode a value if its type is a object
         * @private
         * @param  {mixed}  data  Value to decode
         * @return {mixed}        The decoded value
         */
        function decodeObjectString(data) {
            if (typeof data === 'object') {
                return JSON.stringify(data);
            }

            return data;
        }

        /**
         * encode a value if the value is a object
         * @param  {mixed} data  The value to encode
         * @return {mixed}       The encoded value
         */
        function encodeObjectString(data) {
            if (typeof data === 'string') {
                try {
                    return JSON.parse(data);
                } catch(e) {
                    return data;
                }
            }
        }

        __construct(name);

        // define public interface
        return {
            set    : set,
            get    : get,
            flush  : flush,
            remove : remove,
            isset  : isset
        }
    }

    // static store methods

    /**
     * remove all items from the whole store
     * @return {void}
     */
    Store.flush = function() {
        util.flush(ROOT);
    }

    /**
     * remove all expired items from the whole store
     * @return {void}
     */
    Store.flushExpired = function() {
        util.flushExpired(ROOT);
    }

    // remove the expired values
    Store.flushExpired();

    // export the module
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = Store;
    }

    if (typeof window !== 'undefined' && window) {
        window.Store = Store;
    }
})(window);
<commit_msg>changed the param name<commit_after>!(function(window) {
    'use strict';

    // define main constants
    var ROOT       = 'LSP.';
    var STORE      = window.localStorage;
    var EXPIRE_KEY = '--exp';

    /**
     * Util functions
     * @private
     * @type {Object}
     */
    var util = {
        remove: function(key) {
            STORE.removeItem(key.replace(EXPIRE_KEY, ''));
            STORE.removeItem(key);
        },
        flush: function(index) {
            Object.keys(STORE).map(function(key) {
                if (key.indexOf(index) === 0) {
                    util.remove(key);
                }
            });
        },
        flushExpired: function(index) {
            if (Object.keys(STORE).length > 0) {
                Object.keys(STORE).map(function(key) {
                    if (key.indexOf(index) === 0 && key.indexOf(EXPIRE_KEY) !== -1) {
                        if (STORE.getItem(key) < Date.now()) {
                            util.remove(key);
                        }
                    }
                });
            }
        }
    }

    /**
     * Define a new store
     * @class
     * @param  {string} name            The name of the store
     * @param  {boolean} [flushExpired] should the flush expired not run
     * @return {Store}                  The store instance
     */
    var Store = function(name, autoFlushExpired) {
        var storeName;

        function __construct(name) {
            try {
                storeName = validateStoreName(name);

                if (autoFlushExpired === undefined || autoFlushExpired !== false) {
                    flushExpired();
                }
            } catch(error) {
                console.error(error);
            }
        }

        /**
         * Set a defined key with the given value
         * @param  {string} key          The name of the value
         * @param  {mixed}  data         The data to store, can be any datatype
         * @param  {int}    [expiresAt]  When should this value expire
         * @return {void}
         */
        function set(key, data, expiresAt) {
            try {
                if (expiresAt !== undefined && typeof expiresAt === 'number') {
                    STORE.setItem(storeName + key + EXPIRE_KEY, expiresAt.toString());
                }

                STORE.setItem(storeName + key, decodeObjectString(data));

                return true;
            } catch(error) {
                console.error(error);
                return false;
            }
        }

        /**
         * Get the value stored under the given key, or the whole store
         * @param  {string} [key] Index defined in @set
         * @return {mixed}        Stored value
         */
        function get(key) {
            try {
                if (key !== undefined) {
                    var result = encodeObjectString(STORE.getItem(storeName + key));
                    return result !== null ? result : false;
                } else {
                    var resultAll = {};

                    Object.keys(STORE).map(function(key) {
                        if (key.indexOf(storeName) === 0 && key.indexOf(EXPIRE_KEY) === -1) {
                            var varKey = key.replace(storeName, '');
                            resultAll[varKey] = get(varKey);
                        }
                    });

                    return resultAll;
                }
            } catch(error) {
                console.error(error)
                return false;
            }
        }

        /**
         * Check if the given key exists in the store
         * @param  {string}  key  index of the value to test
         * @return {boolean}      Key defined or not
         */
        function isset(key) {
            return get(key) !== false ? true : false;
        }

        /**
         * Flush all values, that are stored in the store instance
         * @return {void}
         */
        function flush() {
            util.flush(storeName);
        }

        /**
         * Remove an item, by the given key and its expire if set
         * @param  {string} key  Index of the value
         * @return {void}
         */
        function remove(key) {
            util.remove(storeName + key);
        }

        /**
         * flush expired values defined in this store
         * @return {void}
         */
        function flushExpired() {
            util.flushExpired(storeName);
        }

        /**
         * generate a store name
         * @param  {string} storeName  The name of the store instance
         * @return {string}            The generated name
         * @throws {TypeError}
         */
        function validateStoreName(storeName) {
            if (storeName === undefined) {
                throw new TypeError('Please provide a storename');
            }

            if (typeof(storeName) !== 'string') {
                throw new TypeError('The storename has to be a string');
            }

            var chargedStoreName = storeName = ROOT + storeName + '-';
            return chargedStoreName;
        }

        /**
         * decode a value if its type is a object
         * @private
         * @param  {mixed}  data  Value to decode
         * @return {mixed}        The decoded value
         */
        function decodeObjectString(data) {
            if (typeof data === 'object') {
                return JSON.stringify(data);
            }

            return data;
        }

        /**
         * encode a value if the value is a object
         * @param  {mixed} data  The value to encode
         * @return {mixed}       The encoded value
         */
        function encodeObjectString(data) {
            if (typeof data === 'string') {
                try {
                    return JSON.parse(data);
                } catch(e) {
                    return data;
                }
            }
        }

        __construct(name);

        // define public interface
        return {
            set    : set,
            get    : get,
            flush  : flush,
            remove : remove,
            isset  : isset
        }
    }

    // static store methods

    /**
     * remove all items from the whole store
     * @return {void}
     */
    Store.flush = function() {
        util.flush(ROOT);
    }

    /**
     * remove all expired items from the whole store
     * @return {void}
     */
    Store.flushExpired = function() {
        util.flushExpired(ROOT);
    }

    // remove the expired values
    Store.flushExpired();

    // export the module
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = Store;
    }

    if (typeof window !== 'undefined' && window) {
        window.Store = Store;
    }
})(window);
<|endoftext|>


<commit_before>import lowerCaseFirst from 'lower-case-first';
import {handles} from 'marty';

function addHandlers(ResourceStore) {
  const {constantMappings} = this;

  return class ResourceStoreWithHandlers extends ResourceStore {
    @handles(constantMappings.getMany.done)
    receiveMany(args) {
      super.receiveMany(args);
      this.hasChanged();
    }

    @handles(constantMappings.getSingle.done)
    receiveSingle(args) {
      super.receiveSingle(args);
      this.hasChanged();
    }
  };
}

function addFetch(
  ResourceStore,
  {
    actionsKey = `${lowerCaseFirst(this.name)}Actions`
  }
) {
  const {methodNames, name, plural} = this;

  const {getMany, getSingle} = methodNames;
  const refreshMany = `refresh${plural}`;
  const refreshSingle = `refresh${name}`;

  const baseGetMany = ResourceStore.prototype[getMany];
  const baseGetSingle = ResourceStore.prototype[getSingle];

  function fetchMany(options, refresh) {
    return this.fetch({
      id: this.collectionCacheKey(options),
      locally() {
        if (refresh) {
          refresh = false;
          return undefined;
        } else {
          return this::baseGetMany(options);
        }
      },
      remotely() {
        return this.getActions()[getMany](options);
      }
    });
  }

  function fetchSingle(id, options, refresh) {
    return this.fetch({
      id: this.itemCacheKey(id, options),
      locally() {
        if (refresh) {
          refresh = false;
          return undefined;
        } else {
          return this::baseGetSingle(id, options);
        }
      },
      remotely() {
        return this.getActions()[getSingle](id, options);
      }
    });
  }

  return class ResourceStoreWithFetch extends ResourceStore {
    getActions() {
      return this.app[actionsKey];
    }

    [getMany](options) {
      return this::fetchMany(options, false);
    }

    [refreshMany](options) {
      return this::fetchMany(options, true);
    }

    [getSingle](id, options) {
      return this::fetchSingle(id, options, false);
    }

    [refreshSingle](id, options) {
      return this::fetchSingle(id, options, true);
    }
  };
}

export default function extendStore(
  ResourceStore,
  {
    useFetch = true,
    ...options
  }
) {
  ResourceStore = this::addHandlers(ResourceStore, options);

  if (useFetch) {
    ResourceStore = this::addFetch(ResourceStore, options);
  }

  return ResourceStore;
}
<commit_msg>Allow overriding store fetch methods<commit_after>import lowerCaseFirst from 'lower-case-first';
import {handles} from 'marty';

function addHandlers(ResourceStore) {
  const {constantMappings} = this;

  return class ResourceStoreWithHandlers extends ResourceStore {
    @handles(constantMappings.getMany.done)
    receiveMany(args) {
      super.receiveMany(args);
      this.hasChanged();
    }

    @handles(constantMappings.getSingle.done)
    receiveSingle(args) {
      super.receiveSingle(args);
      this.hasChanged();
    }
  };
}

function addFetch(
  ResourceStore,
  {
    actionsKey = `${lowerCaseFirst(this.name)}Actions`
  }
) {
  const {methodNames, name, plural} = this;

  const {getMany, getSingle} = methodNames;
  const refreshMany = `refresh${plural}`;
  const refreshSingle = `refresh${name}`;

  return class ResourceStoreWithFetch extends ResourceStore {
    getActions() {
      return this.app[actionsKey];
    }

    [getMany](options, {refresh} = {}) {
      return this.fetch({
        id: this.collectionKey(options),
        locally: () => this.localGetMany(options),
        remotely: () => this.remoteGetMany(options),
        refresh
      });
    }

    [refreshMany](options) {
      return this[getMany](options, {refresh: true});
    }

    localGetMany(options) {
      return super[getMany](options);
    }

    remoteGetMany(options) {
      return this.getActions()[getMany](options);
    }

    [getSingle](id, options, {refresh} = {}) {
      return this.fetch({
        id: this.itemKey(id, options),
        locally: () => this.localGetSingle(id, options),
        remotely: () => this.remoteGetSingle(id, options),
        refresh
      });
    }

    [refreshSingle](id, options) {
      return this[getSingle](id, options, {refresh: true});
    }

    localGetSingle(id, options) {
      return super[getSingle](id, options);
    }

    remoteGetSingle(id, options) {
      return this.getActions()[getSingle](id, options);
    }

    fetch({refresh, ...options}) {
      if (refresh) {
        const baseLocally = options.locally;
        options.locally = function refreshLocally() {
          if (refresh) {
            refresh = false;
            return undefined;
          } else {
            return this::baseLocally();
          }
        };
      }

      return super.fetch(options);
    }
  };
}

export default function extendStore(
  ResourceStore,
  {
    useFetch = true,
    ...options
  }
) {
  ResourceStore = this::addHandlers(ResourceStore, options);

  if (useFetch) {
    ResourceStore = this::addFetch(ResourceStore, options);
  }

  return ResourceStore;
}
<|endoftext|>


<commit_before>var fs = require("fs");
var file = "./test.db";
var exists = fs.existsSync(file);

if(!exists) {
  console.log("Creating DB file.");
  fs.openSync(file, "w");
}

var sqlite3 = require("sqlite3").verbose();
var db = new sqlite3.Database(file);

db.serialize(function() {
  if(!exists) {
    db.run("CREATE TABLE Stuff (thing TEXT)");

    var stmt = db.prepare("INSERT INTO Stuff VALUES (?)");

    //Insert random data
    var rnd;
    for (var i = 0; i < 10; i++) {
      rnd = Math.floor(Math.random() * 10000000);
      stmt.run("Thing #" + rnd);
    }
    stmt.finalize();
  }

  db.each("SELECT rowid AS id, thing FROM Stuff", function(err, row) {
    console.log(row.id + ": " + row.thing);
  });
});

db.close();
<commit_msg>create user table<commit_after>var fs = require("fs")
var file = "./test.db"
var exists = fs.existsSync(file)

if(!exists) {
  console.log("Creating DB file.")
  fs.openSync(file, "w")
}

var sqlite3 = require("sqlite3").verbose()
var db = new sqlite3.Database(file)

var startup = function() {
  db.serialize(function() {
    if(!exists) {
      db.run("CREATE TABLE user (id INTEGER PRIMARY KEY AUTOINCREMENT, email CHAR(50))")

      var stmt = db.prepare("INSERT INTO user (email) VALUES ('jtms@aol.com')")
      stmt.run()
      stmt.finalize()
    }

    db.each("SELECT u.id, u.email FROM user u", function(err, row) {
      console.log(row.id + ": " + row.email)
    })
  })

  db.close()
}
startup()
<|endoftext|>


<commit_before>import { createStore, applyMiddleware, compose } from 'redux';
import createSagaMiddleware, { END } from 'redux-saga';
import reducer, { initialState } from './reducer';

const configureStore = () => {
  const sagaMiddleware = createSagaMiddleware()
  const store = createStore(
    reducer,
    compose(
      applyMiddleware(sagaMiddleware),
      window.devToolsExtension ? window.devToolsExtension() : f => f
    )
  )

  store.runSaga = sagaMiddleware.run
  store.close = () => store.dispatch(END)

  if (module.hot) {
    module.hot.accept('./reducer', () => {
      store.replaceReducer(require('./reducer').default)
    })
  }

  return store
}

export default configureStore
<commit_msg>Make devtool hook can be remove in production mode<commit_after>import { createStore, applyMiddleware, compose } from 'redux';
import createSagaMiddleware, { END } from 'redux-saga';
import reducer, { initialState } from './reducer';

const getDevtools = () => {
  if (__DEV__) {
    return window.devToolsExtension ? window.devToolsExtension() : (f) => f
  }
  return (f) => f
}

const configureStore = () => {
  const sagaMiddleware = createSagaMiddleware()
  const store = createStore(
    reducer,
    compose(
      applyMiddleware(sagaMiddleware),
      getDevtools()
    )
  )

  store.runSaga = sagaMiddleware.run
  store.close = () => store.dispatch(END)

  if (module.hot) {
    module.hot.accept('./reducer', () => {
      store.replaceReducer(require('./reducer').default)
    })
  }

  return store
}

export default configureStore
<|endoftext|>


<commit_before>(function() {

	var _support = {
		normalizesNewlines: (function () {
			var textarea = document.createElement('textarea');
			var text = 'abc\r\ndef';
			textarea.value = text;
			return textarea.value.length === text.length - 1;
		}())
	};

	/**
	 * Normalizes line endings by removing all \r (carriage return) characters.
	 * In IE, newlines in textareas are stored as \r\n instead of just \n, which screws up length calculations.
	 * All other browsers automatically remove \r characters when you set the value of the textarea.
	 * @returns {string}
	 */
	String.prototype.norm = function() {
		return this.replace(/\r/g, '');
	};

	pavlov.specify.extendAssertions({
		isOneOf: function(actual, expected, message) {
			ok(expected.indexOf(actual) !== -1, message);
		}
	});

	pavlov.specify('jQuery Caret Plugin', function() {

		var $fixture = $('#qunit-fixture');

		var _single = 'abcdefghijklmnop',
			_multi = 'abcdefg\r\nhijklmnop',
			_short = 'abc',
			_long = 'abcdefghijklmnopqrstuvwxyz',
			_empty = '';

		describe('All Plugins', function() {
			var $input, $textarea;

			// befores and afters:

			before(function() {
				$input = $('<input/>').appendTo($fixture);
				$textarea = $('<textarea/>').appendTo($fixture);
			});

			// plugins:

			describe('Caret', function() {
				describe('Get', function() {
					// Note: Every browser handles caret placement a little differently.
					// Chrome always places the caret at the END of an <input>, but at the BEGINNING of a <textarea>;
					//
					// which means our tests need to accommodate both placement strategies.

					describe('<input>', function() {
						it("Returns zero (0) when no value has been set", function() {
							assert($input.caret()).equals(0);
						});
					});

					describe('<textarea>', function() {
						it("Returns zero (0) when no value has been set", function() {
							assert($textarea.caret()).equals(0);
						});
					});

					describe('<input>', function() {
						it("Returns zero (0) or value.length when a value has been set", function() {
							// In IE and FF, the caret remains at index 0 the first time a value is set;
							// the second time a value is set, the caret moves to the end of the input/textarea.
							assert($input.val(_single).caret()).isOneOf([ 0, _single.length ]);
							assert($input.val(_single).caret()).isOneOf([ 0, _single.length ]);
						});
					});

					describe('<textarea>', function() {
						it("Returns zero (0) or value.length when a value has been set", function() {
							// In IE and FF, the caret remains at index 0 the first time a value is set;
							// the second time a value is set, the caret moves to the end of the input/textarea.
							assert($textarea.val(_multi).caret()).isOneOf([ 0, _multi.norm().length ]);
							assert($textarea.val(_multi).caret()).isOneOf([ 0, _multi.norm().length ]);
						});
					});

					describe('<input>', function() {
						it("Returns zero (0) or value.length when the input's value changes", function() {
							assert($input.val(_short).caret()).isOneOf([ 0, _short.length ]);
							assert($input.val(_long).caret()).isOneOf([ 0, _long.length ]);
							assert($input.val(_short).caret()).isOneOf([ 0, _short.length ]);
							assert($input.val(_empty).caret()).isOneOf([ 0, _empty.length ]);
						});
					});

					describe('<textarea>', function() {
						it("Returns zero (0) or value.length when the textarea's value changes", function() {
							assert($textarea.val(_short).caret()).isOneOf([ 0, _short.length ]);
							assert($textarea.val(_long).caret()).isOneOf([ 0, _long.length ]);
							assert($textarea.val(_short).caret()).isOneOf([ 0, _short.length ]);
							assert($textarea.val(_empty).caret()).isOneOf([ 0, _empty.length ]);
						});
					});
				});

				describe('Set', function() {
					describe('<input>', function() {
						var text = _single,
							len = text.length,
							half = Math.floor(len / 2);

						it("Gets the same position that was set", function() {
							assert($input.val(text).caret(0).caret()).equals(0);
							assert($input.val(text).caret(1).caret()).equals(1);
							assert($input.val(text).caret(half - 2).caret()).equals(half - 2);
							assert($input.val(text).caret(half - 1).caret()).equals(half - 1);
							assert($input.val(text).caret(half).caret()).equals(half);
							assert($input.val(text).caret(half + 1).caret()).equals(half + 1);
							assert($input.val(text).caret(half + 2).caret()).equals(half + 2);
							assert($input.val(text).caret(len - 1).caret()).equals(len - 1);
							assert($input.val(text).caret(len).caret()).equals(len);
						});

						it("Enforces start/end boundaries", function() {
							assert($input.val(text).caret(-1).caret()).equals(0);
							assert($input.val(text).caret(len + 1).caret()).equals(len);
						});

						it("Converts floating point values to integers", function() {
							assert($input.val(text).caret(1.5).caret()).equals(1.0);
							assert($input.val(text).caret(2.5).caret()).equals(2.0);
						});
					});

					describe('<textarea>', function() {
						var text = _multi,
							len = text.norm().length,
							half = text.indexOf('\n');

						it("Gets the same position that was set", function() {
							assert($textarea.val(text).caret(0).caret()).equals(0);
							assert($textarea.val(text).caret(1).caret()).equals(1);
							assert($textarea.val(text).caret(half - 2).caret()).equals(half - 2);
							assert($textarea.val(text).caret(half - 1).caret()).equals(half - 1);
							assert($textarea.val(text).caret(half).caret()).equals(half);
							assert($textarea.val(text).caret(half + 1).caret()).equals(half + 1);
							assert($textarea.val(text).caret(half + 2).caret()).equals(half + 2);
							assert($textarea.val(text).caret(len - 1).caret()).equals(len - 1);
							assert($textarea.val(text).caret(len).caret()).equals(len);
						});

						it("Enforces start/end boundaries", function() {
							assert($textarea.val(text).caret(-1).caret()).equals(0);
							assert($textarea.val(text).caret(len + 1).caret()).equals(len);
							assert($textarea.val(text).caret(len + 2).caret()).equals(len);
						});

						it("Converts floating point values to integers", function() {
							assert($textarea.val(text).caret(1.5).caret()).equals(1.0);
							assert($textarea.val(text).caret(2.5).caret()).equals(2.0);
						});
					});
				});
			});
		});

	});

}());<commit_msg>Minor/ignore - Renamed variable<commit_after>(function() {

	var _support = {
		normalizesNewlines: (function () {
			var textarea = document.createElement('textarea');
			var text = 'abc\r\ndef';
			textarea.value = text;
			return textarea.value.length === text.length - 1;
		}())
	};

	/**
	 * Normalizes line endings by removing all \r (carriage return) characters.
	 * In IE, newlines in textareas are stored as \r\n instead of just \n, which screws up length calculations.
	 * All other browsers automatically remove \r characters when you set the value of the textarea.
	 * @returns {string}
	 */
	String.prototype.norm = function() {
		return this.replace(/\r/g, '');
	};

	pavlov.specify.extendAssertions({
		isOneOf: function(actual, expected, message) {
			ok(expected.indexOf(actual) !== -1, message);
		}
	});

	pavlov.specify('jQuery Caret Plugin', function() {

		var $fixture = $('#qunit-fixture');

		var _single = 'abcdefghijklmnop',
			_multi = 'abcdefg\r\nhijklmnop',
			_short = 'abc',
			_long = 'abcdefghijklmnopqrstuvwxyz',
			_empty = '';

		describe('All Plugins', function() {
			var $input, $textarea;

			// befores and afters:

			before(function() {
				$input = $('<input/>').appendTo($fixture);
				$textarea = $('<textarea/>').appendTo($fixture);
			});

			// plugins:

			describe('Caret', function() {
				describe('Get', function() {
					// Note: Every browser handles caret placement a little differently.
					// Chrome always places the caret at the END of an <input>, but at the BEGINNING of a <textarea>;
					//
					// which means our tests need to accommodate both placement strategies.

					describe('<input>', function() {
						it("Returns zero (0) when no value has been set", function() {
							assert($input.caret()).equals(0);
						});
					});

					describe('<textarea>', function() {
						it("Returns zero (0) when no value has been set", function() {
							assert($textarea.caret()).equals(0);
						});
					});

					describe('<input>', function() {
						it("Returns zero (0) or value.length when a value has been set", function() {
							// In IE and FF, the caret remains at index 0 the first time a value is set;
							// the second time a value is set, the caret moves to the end of the input/textarea.
							assert($input.val(_single).caret()).isOneOf([ 0, _single.length ]);
							assert($input.val(_single).caret()).isOneOf([ 0, _single.length ]);
						});
					});

					describe('<textarea>', function() {
						it("Returns zero (0) or value.length when a value has been set", function() {
							// In IE and FF, the caret remains at index 0 the first time a value is set;
							// the second time a value is set, the caret moves to the end of the input/textarea.
							assert($textarea.val(_multi).caret()).isOneOf([ 0, _multi.norm().length ]);
							assert($textarea.val(_multi).caret()).isOneOf([ 0, _multi.norm().length ]);
						});
					});

					describe('<input>', function() {
						it("Returns zero (0) or value.length when the input's value changes", function() {
							assert($input.val(_short).caret()).isOneOf([ 0, _short.length ]);
							assert($input.val(_long).caret()).isOneOf([ 0, _long.length ]);
							assert($input.val(_short).caret()).isOneOf([ 0, _short.length ]);
							assert($input.val(_empty).caret()).isOneOf([ 0, _empty.length ]);
						});
					});

					describe('<textarea>', function() {
						it("Returns zero (0) or value.length when the textarea's value changes", function() {
							assert($textarea.val(_short).caret()).isOneOf([ 0, _short.length ]);
							assert($textarea.val(_long).caret()).isOneOf([ 0, _long.length ]);
							assert($textarea.val(_short).caret()).isOneOf([ 0, _short.length ]);
							assert($textarea.val(_empty).caret()).isOneOf([ 0, _empty.length ]);
						});
					});
				});

				describe('Set', function() {
					describe('<input>', function() {
						var text = _single,
							len = text.length,
							mid = Math.floor(len / 2);

						it("Gets the same position that was set", function() {
							assert($input.val(text).caret(0).caret()).equals(0);
							assert($input.val(text).caret(1).caret()).equals(1);
							assert($input.val(text).caret(mid - 2).caret()).equals(mid - 2);
							assert($input.val(text).caret(mid - 1).caret()).equals(mid - 1);
							assert($input.val(text).caret(mid).caret()).equals(mid);
							assert($input.val(text).caret(mid + 1).caret()).equals(mid + 1);
							assert($input.val(text).caret(mid + 2).caret()).equals(mid + 2);
							assert($input.val(text).caret(len - 1).caret()).equals(len - 1);
							assert($input.val(text).caret(len).caret()).equals(len);
						});

						it("Enforces start/end boundaries", function() {
							assert($input.val(text).caret(-1).caret()).equals(0);
							assert($input.val(text).caret(len + 1).caret()).equals(len);
						});

						it("Converts floating point values to integers", function() {
							assert($input.val(text).caret(1.5).caret()).equals(1.0);
							assert($input.val(text).caret(2.5).caret()).equals(2.0);
						});
					});

					describe('<textarea>', function() {
						var text = _multi,
							len = text.norm().length,
							mid = text.indexOf('\n');

						it("Gets the same position that was set", function() {
							assert($textarea.val(text).caret(0).caret()).equals(0);
							assert($textarea.val(text).caret(1).caret()).equals(1);
							assert($textarea.val(text).caret(mid - 2).caret()).equals(mid - 2);
							assert($textarea.val(text).caret(mid - 1).caret()).equals(mid - 1);
							assert($textarea.val(text).caret(mid).caret()).equals(mid);
							assert($textarea.val(text).caret(mid + 1).caret()).equals(mid + 1);
							assert($textarea.val(text).caret(mid + 2).caret()).equals(mid + 2);
							assert($textarea.val(text).caret(len - 1).caret()).equals(len - 1);
							assert($textarea.val(text).caret(len).caret()).equals(len);
						});

						it("Enforces start/end boundaries", function() {
							assert($textarea.val(text).caret(-1).caret()).equals(0);
							assert($textarea.val(text).caret(len + 1).caret()).equals(len);
							assert($textarea.val(text).caret(len + 2).caret()).equals(len);
						});

						it("Converts floating point values to integers", function() {
							assert($textarea.val(text).caret(1.5).caret()).equals(1.0);
							assert($textarea.val(text).caret(2.5).caret()).equals(2.0);
						});
					});
				});
			});
		});

	});

}());<|endoftext|>


<commit_before>'use strict';

import React from 'react';
import assign from 'object-assign';
import classnames from 'classnames';

var getSlideClasses = (spec) => {
  var slickActive, slickCenter, slickCloned;
  var centerOffset, index;

  if (spec.rtl) {
    index = spec.slideCount - 1 - spec.index;
  } else {
    index = spec.index;
  }
  slickCloned = (index < 0) || (index >= spec.slideCount);
  if (spec.centerMode) {
    centerOffset = Math.floor(spec.slidesToShow / 2);
    slickCenter = (index - spec.currentSlide) % spec.slideCount === 0;
    if ((index > spec.currentSlide - centerOffset - 1) && (index <= spec.currentSlide + centerOffset)) {
      slickActive = true;
    }
  } else {
    slickActive = (spec.currentSlide <= index) && (index < spec.currentSlide + spec.slidesToShow);
  }
  return classnames({
    'slick-slide': true,
    'slick-active': slickActive,
    'slick-center': slickCenter,
    'slick-cloned': slickCloned
  });
};

var getSlideStyle = function (spec) {
  var style = {};

  if (spec.variableWidth === undefined || spec.variableWidth === false) {
    style.width = spec.slideWidth;
  }

  if (spec.fade) {
    style.position = 'relative';
    style.left = -spec.index * spec.slideWidth;
    style.opacity = (spec.currentSlide === spec.index) ? 1 : 0;
    style.transition = 'opacity ' + spec.speed + 'ms ' + spec.cssEase;
    style.WebkitTransition = 'opacity ' + spec.speed + 'ms ' + spec.cssEase;
  }

  return style;
};

var getKey = (child, fallbackKey) => {
    // key could be a zero
    return (child.key === null || child.key === undefined) ? fallbackKey : child.key;
};

var renderSlides = function (spec) {
  var key;
  var slides = [];
  var preCloneSlides = [];
  var postCloneSlides = [];
  var count = React.Children.count(spec.children);

  React.Children.forEach(spec.children, (elem, index) => {
    let child;
    var childOnClickOptions = {
      message: 'children',
      index: index,
      slidesToScroll: spec.slidesToScroll,
      currentSlide: spec.currentSlide
    };

    if (!spec.lazyLoad | (spec.lazyLoad && spec.lazyLoadedList.indexOf(index) >= 0)) {
      child = elem;
    } else {
      child = (

);
    }
    var childStyle = getSlideStyle(assign({}, spec, {index: index}));
    const slideClass = child.props.className || ''

    const onClick = function(e) {
      child.props && child.props.onClick && child.props.onClick(e)
      if (spec.focusOnSelect) {
        spec.focusOnSelect(childOnClickOptions)
      }
    }

    slides.push(React.cloneElement(child, {
      key: 'original' + getKey(child, index),
      'data-index': index,
      className: classnames(getSlideClasses(assign({index: index}, spec)), slideClass),
      tabIndex: '-1',
      style: assign({outline: 'none'}, child.props.style || {}, childStyle),
      onClick
    }));

    // variableWidth doesn't wrap properly.
    if (spec.infinite && spec.fade === false) {
      var infiniteCount = spec.variableWidth ? spec.slidesToShow + 1 : spec.slidesToShow;

      if (index >= (count - infiniteCount)) {
        key = -(count - index);
        preCloneSlides.push(React.cloneElement(child, {
          key: 'precloned' + getKey(child, key),
          'data-index': key,
          className: classnames(getSlideClasses(assign({index: key}, spec)), slideClass),
          style: assign({}, child.props.style || {}, childStyle),
          onClick
        }));
      }

      if (index < infiniteCount) {
        key = count + index;
        postCloneSlides.push(React.cloneElement(child, {
          key: 'postcloned' + getKey(child, key),
          'data-index': key,
          className: classnames(getSlideClasses(assign({index: key}, spec)), slideClass),
          style: assign({}, child.props.style || {}, childStyle),
          onClick
        }));
      }
    }
  });

  if (spec.rtl) {
    return preCloneSlides.concat(slides, postCloneSlides).reverse();
  } else {
    return preCloneSlides.concat(slides, postCloneSlides);
  }

};

export class Track extends React.Component {
  render() {
    var slides = renderSlides.call(this, this.props);
    return (

        { slides }

    );
  }
}
<commit_msg>change bitwise OR to a logical OR<commit_after>'use strict';

import React from 'react';
import assign from 'object-assign';
import classnames from 'classnames';

var getSlideClasses = (spec) => {
  var slickActive, slickCenter, slickCloned;
  var centerOffset, index;

  if (spec.rtl) {
    index = spec.slideCount - 1 - spec.index;
  } else {
    index = spec.index;
  }
  slickCloned = (index < 0) || (index >= spec.slideCount);
  if (spec.centerMode) {
    centerOffset = Math.floor(spec.slidesToShow / 2);
    slickCenter = (index - spec.currentSlide) % spec.slideCount === 0;
    if ((index > spec.currentSlide - centerOffset - 1) && (index <= spec.currentSlide + centerOffset)) {
      slickActive = true;
    }
  } else {
    slickActive = (spec.currentSlide <= index) && (index < spec.currentSlide + spec.slidesToShow);
  }
  return classnames({
    'slick-slide': true,
    'slick-active': slickActive,
    'slick-center': slickCenter,
    'slick-cloned': slickCloned
  });
};

var getSlideStyle = function (spec) {
  var style = {};

  if (spec.variableWidth === undefined || spec.variableWidth === false) {
    style.width = spec.slideWidth;
  }

  if (spec.fade) {
    style.position = 'relative';
    style.left = -spec.index * spec.slideWidth;
    style.opacity = (spec.currentSlide === spec.index) ? 1 : 0;
    style.transition = 'opacity ' + spec.speed + 'ms ' + spec.cssEase;
    style.WebkitTransition = 'opacity ' + spec.speed + 'ms ' + spec.cssEase;
  }

  return style;
};

var getKey = (child, fallbackKey) => {
    // key could be a zero
    return (child.key === null || child.key === undefined) ? fallbackKey : child.key;
};

var renderSlides = function (spec) {
  var key;
  var slides = [];
  var preCloneSlides = [];
  var postCloneSlides = [];
  var count = React.Children.count(spec.children);

  React.Children.forEach(spec.children, (elem, index) => {
    let child;
    var childOnClickOptions = {
      message: 'children',
      index: index,
      slidesToScroll: spec.slidesToScroll,
      currentSlide: spec.currentSlide
    };

    if (!spec.lazyLoad || (spec.lazyLoad && spec.lazyLoadedList.indexOf(index) >= 0)) {
      child = elem;
    } else {
      child = (

);
    }
    var childStyle = getSlideStyle(assign({}, spec, {index: index}));
    const slideClass = child.props.className || ''

    const onClick = function(e) {
      child.props && child.props.onClick && child.props.onClick(e)
      if (spec.focusOnSelect) {
        spec.focusOnSelect(childOnClickOptions)
      }
    }

    slides.push(React.cloneElement(child, {
      key: 'original' + getKey(child, index),
      'data-index': index,
      className: classnames(getSlideClasses(assign({index: index}, spec)), slideClass),
      tabIndex: '-1',
      style: assign({outline: 'none'}, child.props.style || {}, childStyle),
      onClick
    }));

    // variableWidth doesn't wrap properly.
    if (spec.infinite && spec.fade === false) {
      var infiniteCount = spec.variableWidth ? spec.slidesToShow + 1 : spec.slidesToShow;

      if (index >= (count - infiniteCount)) {
        key = -(count - index);
        preCloneSlides.push(React.cloneElement(child, {
          key: 'precloned' + getKey(child, key),
          'data-index': key,
          className: classnames(getSlideClasses(assign({index: key}, spec)), slideClass),
          style: assign({}, child.props.style || {}, childStyle),
          onClick
        }));
      }

      if (index < infiniteCount) {
        key = count + index;
        postCloneSlides.push(React.cloneElement(child, {
          key: 'postcloned' + getKey(child, key),
          'data-index': key,
          className: classnames(getSlideClasses(assign({index: key}, spec)), slideClass),
          style: assign({}, child.props.style || {}, childStyle),
          onClick
        }));
      }
    }
  });

  if (spec.rtl) {
    return preCloneSlides.concat(slides, postCloneSlides).reverse();
  } else {
    return preCloneSlides.concat(slides, postCloneSlides);
  }

};

export class Track extends React.Component {
  render() {
    var slides = renderSlides.call(this, this.props);
    return (

        { slides }

    );
  }
}
<|endoftext|>


<commit_before>define('lyria/tween', ['eventmap', 'mixer', 'jqueryify'], function(EventMap, mixer, $fy) {
  var Tween = (function() {
    var Tween = function(elem) {
      this.$elem = $fy(elem);

      mixer(Tween.prototype, new EventMap());
    };

    return Tween;
  })();

  return Tween;
});<commit_msg>First draft of tweening API<commit_after>define('lyria/tween', ['eventmap', 'mixer', 'options', 'jqueryify'], function(EventMap, mixer, options, $fy) {
  var Tween = (function() {
    var Tween = function(opts) {
      opts = options(opts, {
        elem: null,
        effects: [{
          property: null,
          target: null,
          easing: Tween.defaults.easing,
          duration: Tween.defaults.duration,
          delay: Tween.defaults.delay
        }]
      });

      this.$elem = $fy(opts.elem);
      this.effects = opts.effects;

      this.hwAccelerated = true;

      mixer(Tween.prototype, new EventMap());

      var self = this;

      this.on('start', function() {
        if (self.$elem) {
          return;
        }

        var effects = [];
        var properties = {};

        for (var i = 0, j = self.effects.length; i < j; i++) {
          (function(item) {
            if (item.property == null || item.target == null) {
              return;
            }

            item.duration = item.duration || Tween.defaults.duration;
            item.easing = item.easing || Tween.defaults.easing;
            item.delay = item.delay || Tween.defaults.delay;

            effects.push([item.property, item.duration, item.easing, item.delay].join(' '));
            properties[item.property] = item.target;
          })(self.effects[i]);
        }

        properties['transition'] = effects.join(', ');
        self.$elem.css(properties);

        $(document).one('transitionend', function(e) {
          console.log(e.target);
        });
      });
    };

    Tween.defaults = {
      easing: 'linear',
      duration: '300ms',
      delay: '0ms'
    };

    return Tween;
  })();

  return Tween;
}); <|endoftext|>


<commit_before>udefine(['eventmap', 'gameboard/bezier-easing', 'gameboard/loop'], function(EventMap, BezierEasing, Loop) {

  var Tween = function() {
    EventMap.mixin(this, Tween.prototype);

    this.target = null;
  };

  Tween.prototype.animate = function(property, end, time, easing) {
    var self = this;

    if (this.target && typeof this.target[property] === 'number') {
      var start = this.target[property];

      if (start === end) {
        this.trigger('start');
        this.trigger('end');
        return;
      }

      easing = easing || 'linear';

      var timer = Loop.createTimer();

      timer.interval = time;

      timer.on('start', function() {
        self.trigger('start');
      });

      timer.start();

      timer.on('tick', function(ticks) {
        var multiplicator = BezierEasing.css[easing](ticks / (timer.startTime + timer.interval));
        var points = (end - start) * multiplicator;

        if (points > end) {
          points = end;
        }

        self.target[property] = points;
        self.trigger('animate', points);
      });

      timer.on('interval', function() {
        timer.stop();
        self.target[property] = end;
        self.trigger('end');
      });

    }
  };

  return Tween;

});
<commit_msg>Use relative modules<commit_after>udefine(['eventmap', './bezier-easing', './loop'], function(EventMap, BezierEasing, Loop) {

  var Tween = function() {
    EventMap.mixin(this, Tween.prototype);

    this.target = null;
  };

  Tween.prototype.animate = function(property, end, time, easing) {
    var self = this;

    if (this.target && typeof this.target[property] === 'number') {
      var start = this.target[property];

      if (start === end) {
        this.trigger('start');
        this.trigger('end');
        return;
      }

      easing = easing || 'linear';

      var timer = Loop.createTimer();

      timer.interval = time;

      timer.on('start', function() {
        self.trigger('start');
      });

      timer.start();

      timer.on('tick', function(ticks) {
        var multiplicator = BezierEasing.css[easing](ticks / (timer.startTime + timer.interval));
        var points = (end - start) * multiplicator;

        if (points > end) {
          points = end;
        }

        self.target[property] = points;
        self.trigger('animate', points);
      });

      timer.on('interval', function() {
        timer.stop();
        self.target[property] = end;
        self.trigger('end');
      });

    }
  };

  return Tween;

});
<|endoftext|>


<commit_before>// Copyright (c) 2012 UX Productivity Pty Ltd. All rights reserved.

var CONTAINER_ELEMENTS = {
    "#document": true,
    "HTML": true,
    "BODY": true,
    "UL": true,
    "OL":  true,
    "LI": true,
    "TABLE": true,
    "CAPTION": true,
    "THEAD": true,
    "TFOOT": true,
    "TBODY": true,
    "TR": true,
    "TH": true,
    "TD": true,
    "COL": true,
    "FIGURE": true,
    "FIGCAPTION": true,
    "NAV": true,
};

var PARAGRAPH_ELEMENTS = {
    "P": true,
    "H1": true,
    "H2": true,
    "H3": true,
    "H4": true,
    "H5": true,
    "H6": true,
    "DIV": true,
    "PRE": true,
    "BLOCKQUOTE": true
};

var HEADING_ELEMENTS = {
    "H1": true,
    "H2": true,
    "H3": true,
    "H4": true,
    "H5": true,
    "H6": true
}

var INLINE_ELEMENTS_THAT_CAN_HAVE_CHILDREN = {
    "A": true,
    "B": true,
    "I": true,
    "U": true,
    "SPAN": true,
};

var CONTAINER_ELEMENTS_ALLOWING_CONTENT = {
    "BODY": true,
    "LI": true,
    "CAPTION": true,
    "TH": true,
    "TD": true,
    "FIGURE": true,
    "FIGCAPTION": true,
    "NAV": true,
};

var Keys = {
    HEADING_NUMBER: "uxwrite-heading-number",
    FIGURE_NUMBER: "uxwrite-figure-number",
    TABLE_NUMBER: "uxwrite-table-number",
    SECTION_TOC: "tableofcontents",
    FIGURE_TOC: "listoffigures",
    TABLE_TOC: "listoftables",
    SELECTION_HIGHLIGHT: "uxwrite-selection-highlight",
    AUTOCORRECT_ENTRY: "uxwrite-autocorrect-entry",
    UXWRITE_PREFIX: "uxwrite-",
    NONE_STYLE: "__none",
    AUTOCORRECT_CLASS: "uxwrite-autocorrect",
    SELECTION_CLASS: "uxwrite-selection",
    ABSTRACT_ELEMENT: "uxwrite-abstract",
};

var ITEM_NUMBER_CLASSES = {
    "uxwrite-heading-number": true,
    "uxwrite-figure-number": true,
    "uxwrite-table-number": true,
};

var OPAQUE_NODE_CLASSES = {
    "uxwrite-heading-number": true,
    "uxwrite-figure-number": true,
    "uxwrite-table-number": true,
    "tableofcontents": true,
    "listoffigures": true,
    "listoftables": true,
    "uxwrite-selection-highlight": true,
};

function isContainerNode(node)
{
    return CONTAINER_ELEMENTS[DOM_upperName(node)];
}

function isParagraphNode(node)
{
    return PARAGRAPH_ELEMENTS[DOM_upperName(node)];
}

function isHeadingNode(node)
{
    return HEADING_ELEMENTS[DOM_upperName(node)];
}

function isTableCaptionNode(node)
{
    return (DOM_upperName(node) == "CAPTION");
}

function isFigureCaptionNode(node)
{
    return (DOM_upperName(node) == "FIGCAPTION");
}

function isOutlineItemTitleNode(node)
{
    return (isHeadingNode(node) || isFigureCaptionNode(node) || isTableCaptionNode(node));
}

function isBlockNode(node)
{
    return (isContainerNode(node) || isParagraphNode(node));
}

function isInlineNode(node)
{
    return !isBlockNode(node);
}

function isListNode(node)
{
    return ((DOM_upperName(node) == "UL") || (DOM_upperName(node) == "OL"));
}

function isListItemNode(node)
{
    return (DOM_upperName(node) == "LI");
}

function isTableNode(node)
{
    return (DOM_upperName(node) == "TABLE");
}

function isTableCell(node)
{
    return ((DOM_upperName(node) == "TD") ||
            (DOM_upperName(node) == "TH"));
}

function isFigureNode(node)
{
    return (DOM_upperName(node) == "FIGURE");
}

function isRefNode(node)
{
    return ((DOM_upperName(node) == "A") &&
            node.hasAttribute("href") &&
            node.getAttribute("href").charAt(0) == "#");
}

function isImageNode(node)
{
    return (DOM_upperName(node) == "IMG");
}

function isTextNode(node)
{
    return (node.nodeType == Node.TEXT_NODE);
}

function isItemNumber(node)
{
    if (node.nodeType == Node.TEXT_NODE) {
        return isItemNumber(node.parentNode);
    }
    else if (node.nodeType == Node.ELEMENT_NODE) {
        if ((DOM_upperName(node) == "SPAN") && node.hasAttribute("class")) {
            return ITEM_NUMBER_CLASSES[node.getAttribute("class")];
        }
    }
    return false;
}

function isOpaqueNode(node)
{
    if (node == null)
        return false;
    if (node.nodeType == Node.TEXT_NODE) {
        return isOpaqueNode(node.parentNode);
    }
    else if (node.nodeType == Node.ELEMENT_NODE) {
        if (node.hasAttribute("class") && OPAQUE_NODE_CLASSES[node.getAttribute("class")]) {
            return true;
        }
        else if ((DOM_upperName(node) == "A") && node.hasAttribute("href")) {
            return true;
        }
        else if (isImageNode(node)) {
            return true;
        }
    }
    return isOpaqueNode(node.parentNode);
}

function isAutoCorrectNode(node)
{
    return ((DOM_upperName(node) == "SPAN") &&
            (node.getAttribute("class") == Keys.AUTOCORRECT_CLASS));
}

function isSelectionHighlight(node)
{
    return ((node.nodeType == Node.ELEMENT_NODE) &&
            node.getAttribute("class") == Keys.SELECTION_CLASS);
}

function isTOCNode(node)
{
    if (DOM_upperName(node) == "NAV") {
        var cls = node.getAttribute("class");
        if ((cls == Keys.SECTION_TOC) ||
            (cls == Keys.FIGURE_TOC) ||
            (cls == Keys.TABLE_TOC))
            return true;
    }
    return false;
}

function isInTOC(node)
{
    if (isTOCNode(node))
        return true;
    if (node.parentNode != null)
        return isInTOC(node.parentNode);
    return false;
}

function isSpecialBlockNode(node)
{
    return (isTableNode(node) || isFigureNode(node) || isTOCNode(node));
}

function isContentLeafNode(node)
{
    if (node.nodeType == Node.TEXT_NODE)
        return true;
    if (DOM_upperName(node) == "IMG")
        return true;
    return false;
}

function isAbstractSpan(node)
{
    return ((DOM_upperName(node) == "SPAN") && node.hasAttribute(Keys.ABSTRACT_ELEMENT));
}
<commit_msg>Introduction of type ids part 3: Added a bunch of arrays to types.js to use to check if a particular type id is of a certain kind (container, paragraph, heading etc.). Also modified all of the is* functions to use the numeric type id instead of the name.<commit_after>// Copyright (c) 2012 UX Productivity Pty Ltd. All rights reserved.

var CONTAINER_ELEMENTS = {
    "#document": true,
    "HTML": true,
    "BODY": true,
    "UL": true,
    "OL":  true,
    "LI": true,
    "TABLE": true,
    "CAPTION": true,
    "THEAD": true,
    "TFOOT": true,
    "TBODY": true,
    "TR": true,
    "TH": true,
    "TD": true,
    "COL": true,
    "FIGURE": true,
    "FIGCAPTION": true,
    "NAV": true,
};

var CONTAINER_ELEMENT_TYPES = new Array(HTML_COUNT);
CONTAINER_ELEMENT_TYPES[HTML_DOCUMENT] = true;
CONTAINER_ELEMENT_TYPES[HTML_HTML] = true;
CONTAINER_ELEMENT_TYPES[HTML_BODY] = true;
CONTAINER_ELEMENT_TYPES[HTML_UL] = true;
CONTAINER_ELEMENT_TYPES[HTML_OL] = true,
CONTAINER_ELEMENT_TYPES[HTML_LI] = true;
CONTAINER_ELEMENT_TYPES[HTML_TABLE] = true;
CONTAINER_ELEMENT_TYPES[HTML_CAPTION] = true;
CONTAINER_ELEMENT_TYPES[HTML_THEAD] = true;
CONTAINER_ELEMENT_TYPES[HTML_TFOOT] = true;
CONTAINER_ELEMENT_TYPES[HTML_TBODY] = true;
CONTAINER_ELEMENT_TYPES[HTML_TR] = true;
CONTAINER_ELEMENT_TYPES[HTML_TH] = true;
CONTAINER_ELEMENT_TYPES[HTML_TD] = true;
CONTAINER_ELEMENT_TYPES[HTML_COL] = true;
CONTAINER_ELEMENT_TYPES[HTML_FIGURE] = true;
CONTAINER_ELEMENT_TYPES[HTML_FIGCAPTION] = true;
CONTAINER_ELEMENT_TYPES[HTML_NAV] = true;

var PARAGRAPH_ELEMENTS = {
    "P": true,
    "H1": true,
    "H2": true,
    "H3": true,
    "H4": true,
    "H5": true,
    "H6": true,
    "DIV": true,
    "PRE": true,
    "BLOCKQUOTE": true
};

var PARAGRAPH_ELEMENT_TYPES = new Array(HTML_COUNT);
PARAGRAPH_ELEMENT_TYPES[HTML_P] = true;
PARAGRAPH_ELEMENT_TYPES[HTML_H1] = true;
PARAGRAPH_ELEMENT_TYPES[HTML_H2] = true;
PARAGRAPH_ELEMENT_TYPES[HTML_H3] = true;
PARAGRAPH_ELEMENT_TYPES[HTML_H4] = true;
PARAGRAPH_ELEMENT_TYPES[HTML_H5] = true;
PARAGRAPH_ELEMENT_TYPES[HTML_H6] = true;
PARAGRAPH_ELEMENT_TYPES[HTML_DIV] = true;
PARAGRAPH_ELEMENT_TYPES[HTML_PRE] = true;
PARAGRAPH_ELEMENT_TYPES[HTML_BLOCKQUOTE] = true;

var HEADING_ELEMENTS = {
    "H1": true,
    "H2": true,
    "H3": true,
    "H4": true,
    "H5": true,
    "H6": true
}

var HEADING_ELEMENT_TYPES = new Array(HTML_COUNT);
HEADING_ELEMENT_TYPES[HTML_H1] = true;
HEADING_ELEMENT_TYPES[HTML_H2] = true;
HEADING_ELEMENT_TYPES[HTML_H3] = true;
HEADING_ELEMENT_TYPES[HTML_H4] = true;
HEADING_ELEMENT_TYPES[HTML_H5] = true;
HEADING_ELEMENT_TYPES[HTML_H6] = true;

var INLINE_ELEMENTS_THAT_CAN_HAVE_CHILDREN = {
    "A": true,
    "B": true,
    "I": true,
    "U": true,
    "SPAN": true,
};

var INLINE_ALLOWING_CHILDREN_TYPES = new Array(HTML_COUNT);
INLINE_ALLOWING_CHILDREN_TYPES[HTML_A] = true;
INLINE_ALLOWING_CHILDREN_TYPES[HTML_B] = true;
INLINE_ALLOWING_CHILDREN_TYPES[HTML_I] = true;
INLINE_ALLOWING_CHILDREN_TYPES[HTML_U] = true;
INLINE_ALLOWING_CHILDREN_TYPES[HTML_SPAN] = true;

var CONTAINER_ELEMENTS_ALLOWING_CONTENT = {
    "BODY": true,
    "LI": true,
    "CAPTION": true,
    "TH": true,
    "TD": true,
    "FIGURE": true,
    "FIGCAPTION": true,
    "NAV": true,
};

var CONTAINERS_ALLOWING_CONTENT_TYPES = new Array(HTML_COUNT);
CONTAINERS_ALLOWING_CONTENT_TYPES[HTML_BODY] = true;
CONTAINERS_ALLOWING_CONTENT_TYPES[HTML_LI] = true;
CONTAINERS_ALLOWING_CONTENT_TYPES[HTML_CAPTION] = true;
CONTAINERS_ALLOWING_CONTENT_TYPES[HTML_TH] = true;
CONTAINERS_ALLOWING_CONTENT_TYPES[HTML_TD] = true;
CONTAINERS_ALLOWING_CONTENT_TYPES[HTML_FIGURE] = true;
CONTAINERS_ALLOWING_CONTENT_TYPES[HTML_FIGCAPTION] = true;
CONTAINERS_ALLOWING_CONTENT_TYPES[HTML_NAV] = true;

var Keys = {
    HEADING_NUMBER: "uxwrite-heading-number",
    FIGURE_NUMBER: "uxwrite-figure-number",
    TABLE_NUMBER: "uxwrite-table-number",
    SECTION_TOC: "tableofcontents",
    FIGURE_TOC: "listoffigures",
    TABLE_TOC: "listoftables",
    SELECTION_HIGHLIGHT: "uxwrite-selection-highlight",
    AUTOCORRECT_ENTRY: "uxwrite-autocorrect-entry",
    UXWRITE_PREFIX: "uxwrite-",
    NONE_STYLE: "__none",
    AUTOCORRECT_CLASS: "uxwrite-autocorrect",
    SELECTION_CLASS: "uxwrite-selection",
    ABSTRACT_ELEMENT: "uxwrite-abstract",
};

var ITEM_NUMBER_CLASSES = {
    "uxwrite-heading-number": true,
    "uxwrite-figure-number": true,
    "uxwrite-table-number": true,
};

var OPAQUE_NODE_CLASSES = {
    "uxwrite-heading-number": true,
    "uxwrite-figure-number": true,
    "uxwrite-table-number": true,
    "tableofcontents": true,
    "listoffigures": true,
    "listoftables": true,
    "uxwrite-selection-highlight": true,
};

function isContainerNode(node)
{
    return CONTAINER_ELEMENT_TYPES[node._type];
}

function isParagraphNode(node)
{
    return PARAGRAPH_ELEMENT_TYPES[node._type];
}

function isHeadingNode(node)
{
    return HEADING_ELEMENT_TYPES[node._type];
}

function isTableCaptionNode(node)
{
    return (node._type == HTML_CAPTION);
}

function isFigureCaptionNode(node)
{
    return (node._type == HTML_FIGCAPTION);
}

function isOutlineItemTitleNode(node)
{
    return (isHeadingNode(node) || isFigureCaptionNode(node) || isTableCaptionNode(node));
}

function isBlockNode(node)
{
    return (isContainerNode(node) || isParagraphNode(node));
}

function isInlineNode(node)
{
    return !isBlockNode(node);
}

function isListNode(node)
{
    var type = node._type;
    return ((type == HTML_UL) || (type == HTML_OL));
}

function isListItemNode(node)
{
    return (node._type == HTML_LI);
}

function isTableNode(node)
{
    return (node._type == HTML_TABLE);
}

function isTableCell(node)
{
    var type = node._type;
    return ((type == HTML_TD) || (type == HTML_TH));
}

function isFigureNode(node)
{
    return (node._type == HTML_FIGURE);
}

function isRefNode(node)
{
    return ((node._type == HTML_A) &&
            node.hasAttribute("href") &&
            node.getAttribute("href").charAt(0) == "#");
}

function isImageNode(node)
{
    return (node._type == HTML_IMG);
}

function isTextNode(node)
{
    return (node.nodeType == Node.TEXT_NODE);
}

function isItemNumber(node)
{
    if (node.nodeType == Node.TEXT_NODE) {
        return isItemNumber(node.parentNode);
    }
    else if (node.nodeType == Node.ELEMENT_NODE) {
        if ((node._type == HTML_SPAN) && node.hasAttribute("class")) {
            return ITEM_NUMBER_CLASSES[node.getAttribute("class")];
        }
    }
    return false;
}

function isOpaqueNode(node)
{
    if (node == null)
        return false;
    if (node.nodeType == Node.TEXT_NODE) {
        return isOpaqueNode(node.parentNode);
    }
    else if (node.nodeType == Node.ELEMENT_NODE) {
        if (node.hasAttribute("class") && OPAQUE_NODE_CLASSES[node.getAttribute("class")]) {
            return true;
        }
        else if ((node._type == HTML_A) && node.hasAttribute("href")) {
            return true;
        }
        else if (isImageNode(node)) {
            return true;
        }
    }
    return isOpaqueNode(node.parentNode);
}

function isAutoCorrectNode(node)
{
    return ((node._type == HTML_SPAN) &&
            (node.getAttribute("class") == Keys.AUTOCORRECT_CLASS));
}

function isSelectionHighlight(node)
{
    return ((node.nodeType == Node.ELEMENT_NODE) &&
            node.getAttribute("class") == Keys.SELECTION_CLASS);
}

function isTOCNode(node)
{
    if (node._type == HTML_NAV) {
        var cls = node.getAttribute("class");
        if ((cls == Keys.SECTION_TOC) ||
            (cls == Keys.FIGURE_TOC) ||
            (cls == Keys.TABLE_TOC))
            return true;
    }
    return false;
}

function isInTOC(node)
{
    if (isTOCNode(node))
        return true;
    if (node.parentNode != null)
        return isInTOC(node.parentNode);
    return false;
}

function isSpecialBlockNode(node)
{
    return (isTableNode(node) || isFigureNode(node) || isTOCNode(node));
}

function isContentLeafNode(node)
{
    if (node.nodeType == Node.TEXT_NODE)
        return true;
    if (DOM_upperName(node) == "IMG")
        return true;
    return false;
}

function isAbstractSpan(node)
{
    return ((node._type == HTML_SPAN) && node.hasAttribute(Keys.ABSTRACT_ELEMENT));
}
<|endoftext|>


<commit_before>"use strict";

var primitive = {};

var Nothing = {
    borjes: 'nothing'
};
primitive['nothing'] = true;

var Anything = {
    borjes: 'anything'
};
primitive['anything'] = true;

function Literal ( string ) {
    return {
        borjes: 'literal',
        s: string
    };
};
primitive['literal'] = true;

// LATTICE

var lattice_names = 1;
var lattices = {};
function Lattice (max_elements, name) {
    if (name === undefined) {
        name = lattice_names++;
    }
    var r = {
        borjes: 'lattice',
        n: 0,
        name: name,
        nels: Math.floor((max_elements-1)/32)+1,
        elem: {}, // from bitarray to string
        bits: {}, // from string to bitarray
    };
    lattices[name] = r;
    return r;
}
primitive['lattice'] = true;

function to_bstr ( l, uarray ) {
    var bstr = '';
    for (var j=0; j<l.nels; j++) {
        bstr += uarray[j]+'-';
    }
    return bstr;
}

Lattice.add = function (l, elem, subelems) {
    var bits = new Uint32Array(l.nels);
    var shift = l.n, w = 0;
    for (; shift>=32; shift-=32) { w++; }
    bits[w] |= 1 << shift;
    if ( subelems ) {
        for (var i = 0; i<subelems.length; i++) {
            var toor = l.bits[subelems[i]];
            for (var j=0; j<l.nels; j++) {
                bits[j] |= toor[j];
            }
        }
    }
    l.n++;
    l.bits[elem] = bits;
    l.elem[to_bstr(l, bits)] = elem;
}

Lattice.element = function ( lattice, elem ) {
    if (typeof lattice !== 'object') {
        lattice = lattices[lattice];
    }
    return {
        borjes: 'latticeel',
        l: lattice.name,
        e: elem
    };
}
primitive['latticeel'] = true;

Lattice.meet = function (x, y) {
    if (x.l !== y.l) { return Nothing; }
    var l = lattices[x.l];
    var bits = new Uint32Array(l.nels);
    var xbits = l.bits[x.e];
    var ybits = l.bits[y.e];
    for (var i = 0; i<l.nels; i++) {
        bits[i] = xbits[i] & ybits[i];
    }
    var meet = l.elem[to_bstr(l, bits)];
    if (meet === undefined) { return Nothing; }
    return Lattice.element(l, meet);
}

// FEATURE STRUCTURE

function FStruct ( object, features ) {
    if (object === undefined) {
        features = [];
    }
    if (features === undefined) {
        features = Object.keys(object);
    }
    var r = {
        borjes: 'fstruct',
        f: features,
        v: {}
    };
    for (var i in r.f) {
        var f = r.f[i];
        r.v[f] = copy(object[f]);
    }
    return r;
}

FStruct.set = function ( fs, feat, val ) {
    var i;
    for (i=0; i<fs.f.length; i++) {
        if (fs.f[i] === feat) {
            break;
        }
    }
    if (i==fs.f.length) {
        fs.f.push(feat);
    }
    fs.v[feat] = val;
}

FStruct.get = function ( fs, feat ) {
    return fs.v[feat];
}

function compare_fs ( x, y, wx, wy ) {
    for (var i in x.f) {
        var f = x.f[i];
        if (y.v[f]!==undefined && !compare(x.v[f], y.v[f], wx, wy)) {
            return false;
        }
    }
    return true;
};

function copy_fs ( x, map ) {
    var r = {
        borjes: 'fstruct',
        f: x.f.slice(),
        v: {}
    };
    for (var i in r.f) {
        var f = r.f[i];
        r.v[f] = copy(x.v[f], map);
    }
    return r;
}

// TYPED FEATURE STRUCTURE

function TFS ( type, object, features ) {
    var fs = FStruct(object, features);
    fs.borjes = 'tfstruct';
    fs.type = type;
    return fs;
}

function compare_tfs ( x, y, wx, wy ) {
    if (!eq(x.type, y.type)) { return false; }
    return compare_fs(x, y, wx, wy);
}

function copy_tfs ( x, map ) {
    var r = copy_fs(x, map);
    r.borjes = 'tfstruct';
    r.type = copy(x.type, map);
    return r;
}

// WORLD

function World () {
    return {
        borjes: 'world',
        values: []
    };
}

World.get = function ( world, index ) {
    return world.values[index];
};

World.resolve = function ( world, x ) {
    while (typeof x === 'object' && x.borjes === 'variable') {
        x = world.values[x.index];
    }
    return x;
};

World.bind = function ( world, x ) {
    x.borjes_bound = world;
};

World.put = function ( world, x ) {
    world.values.push(x);
    return world.values.length-1;
};

World.set = function ( world, index, x ) {
    world.values[index] = x;
};

function copy_world ( x, map ) {
    return {
        borjes: 'world',
        values: x.values.map(function(v) {
            return copy(v, map);
        })
    };
}

// VARIABLE

function Variable ( world, value ) {
    return {
        borjes: 'variable',
        index: World.put(world, value)
    };
}

Variable.copy = function ( x, map ) {
    var i;
    if (map) {
        if (map[x.index] !== undefined) {
            i = map[x.index];
        } else {
            i = World.put(map.nw,
                copy(World.get(map.w, x.index),map));
            map[x.index] = i;
        }
    } else {
        i = x.index;
    }
    return {
        borjes: 'variable',
        index: i
    };
}

// PREDICATE

var predicates = {};

function Predicate ( name, params ) {
    return {
        borjes: 'predicate',
        params: params,
        name: name
    };
}

Predicate.create = function ( name, func ) {
    predicates[name] = func;
}

// actually applies it
Predicate.copy = function ( pred, map ) {
    var args = [];
    for (var i=0; i<pred.params.length; i++) {
        var p = pred.params[i];
        if (typeof p !== 'object' || p.borjes !== 'variable') {
            args.push(copy(p, map));
        } else {
            args.push(World.resolve(map.nw, Variable.copy(p, map)));
        }
    }
    return predicates[pred.name].apply(null, args);
}

// FUNCTIONS

function eq ( x, y ) {
    if (x === y) {
        return true;
    }
    if (x.borjes !== y.borjes) {
        return false;
    }
    if (x.borjes === 'nothing' || y.borjes === 'anything') {
        return true;
    }
    if (x.borjes === 'literal') {
        return x.s === y.s;
    }
    if (x.borjes === 'latticeel') {
        return x.l === y.l && x.e === y.e;
    }
    return false;
}

function copy ( x, map ) {
    if (typeof x !== 'object' || primitive[x.borjes]) {
        return x;
    }
    if (x.borjes === 'world') {
        return copy_world(x, map);
    }
    var c = Nothing;
    if (x.borjes === 'fstruct') {
        c = copy_fs(x, map);
    } else if (x.borjes === 'variable') {
        c = Variable.copy(x, map);
    } else if (x.borjes === 'predicate') {
        c = Predicate.copy(x, map);
    }
    if (x.borjes_bound !== undefined) {
        World.bind(map.nw, c);
    }
    return c;
}

function compare ( x, y, worldx, worldy ) {
    if (x.borjes_bound) { worldx = x.borjes_bound; }
    if (y.borjes_bound) { worldy = y.borjes_bound; }
    if (x.borjes === 'variable') {
        return compare(World.get(worldx, x.index), y, worldx, worldy);
    }
    if (y.borjes === 'variable') {
        return compare(x, World.get(worldy, y.index), worldx, worldy);
    }
    if (x.borjes !== y.borjes) {
        return false;
    }
    if (primitive[x.borjes]) {
        return eq(x, y);
    }
    if (x.borjes === 'fstruct') {
        return compare_fs(x, y, worldx, worldy);
    }
    return false;
}

module.exports = {
    Nothing: Nothing,
    Anything: Anything,
    Literal: Literal,
    FStruct: FStruct,
    Variable: Variable,
    World: World,
    Predicate: Predicate,
    Lattice: Lattice,
    eq: eq,
    copy: copy,
    compare: compare
};
<commit_msg>Was missing TFS export<commit_after>"use strict";

var primitive = {};

var Nothing = {
    borjes: 'nothing'
};
primitive['nothing'] = true;

var Anything = {
    borjes: 'anything'
};
primitive['anything'] = true;

function Literal ( string ) {
    return {
        borjes: 'literal',
        s: string
    };
};
primitive['literal'] = true;

// LATTICE

var lattice_names = 1;
var lattices = {};
function Lattice (max_elements, name) {
    if (name === undefined) {
        name = lattice_names++;
    }
    var r = {
        borjes: 'lattice',
        n: 0,
        name: name,
        nels: Math.floor((max_elements-1)/32)+1,
        elem: {}, // from bitarray to string
        bits: {}, // from string to bitarray
    };
    lattices[name] = r;
    return r;
}
primitive['lattice'] = true;

function to_bstr ( l, uarray ) {
    var bstr = '';
    for (var j=0; j<l.nels; j++) {
        bstr += uarray[j]+'-';
    }
    return bstr;
}

Lattice.add = function (l, elem, subelems) {
    var bits = new Uint32Array(l.nels);
    var shift = l.n, w = 0;
    for (; shift>=32; shift-=32) { w++; }
    bits[w] |= 1 << shift;
    if ( subelems ) {
        for (var i = 0; i<subelems.length; i++) {
            var toor = l.bits[subelems[i]];
            for (var j=0; j<l.nels; j++) {
                bits[j] |= toor[j];
            }
        }
    }
    l.n++;
    l.bits[elem] = bits;
    l.elem[to_bstr(l, bits)] = elem;
}

Lattice.element = function ( lattice, elem ) {
    if (typeof lattice !== 'object') {
        lattice = lattices[lattice];
    }
    return {
        borjes: 'latticeel',
        l: lattice.name,
        e: elem
    };
}
primitive['latticeel'] = true;

Lattice.meet = function (x, y) {
    if (x.l !== y.l) { return Nothing; }
    var l = lattices[x.l];
    var bits = new Uint32Array(l.nels);
    var xbits = l.bits[x.e];
    var ybits = l.bits[y.e];
    for (var i = 0; i<l.nels; i++) {
        bits[i] = xbits[i] & ybits[i];
    }
    var meet = l.elem[to_bstr(l, bits)];
    if (meet === undefined) { return Nothing; }
    return Lattice.element(l, meet);
}

// FEATURE STRUCTURE

function FStruct ( object, features ) {
    if (object === undefined) {
        features = [];
    }
    if (features === undefined) {
        features = Object.keys(object);
    }
    var r = {
        borjes: 'fstruct',
        f: features,
        v: {}
    };
    for (var i in r.f) {
        var f = r.f[i];
        r.v[f] = copy(object[f]);
    }
    return r;
}

FStruct.set = function ( fs, feat, val ) {
    var i;
    for (i=0; i<fs.f.length; i++) {
        if (fs.f[i] === feat) {
            break;
        }
    }
    if (i==fs.f.length) {
        fs.f.push(feat);
    }
    fs.v[feat] = val;
}

FStruct.get = function ( fs, feat ) {
    return fs.v[feat];
}

function compare_fs ( x, y, wx, wy ) {
    for (var i in x.f) {
        var f = x.f[i];
        if (y.v[f]!==undefined && !compare(x.v[f], y.v[f], wx, wy)) {
            return false;
        }
    }
    return true;
};

function copy_fs ( x, map ) {
    var r = {
        borjes: 'fstruct',
        f: x.f.slice(),
        v: {}
    };
    for (var i in r.f) {
        var f = r.f[i];
        r.v[f] = copy(x.v[f], map);
    }
    return r;
}

// TYPED FEATURE STRUCTURE

function TFS ( type, object, features ) {
    var fs = FStruct(object, features);
    fs.borjes = 'tfstruct';
    fs.type = type;
    return fs;
}

function compare_tfs ( x, y, wx, wy ) {
    if (!eq(x.type, y.type)) { return false; }
    return compare_fs(x, y, wx, wy);
}

function copy_tfs ( x, map ) {
    var r = copy_fs(x, map);
    r.borjes = 'tfstruct';
    r.type = copy(x.type, map);
    return r;
}

// WORLD

function World () {
    return {
        borjes: 'world',
        values: []
    };
}

World.get = function ( world, index ) {
    return world.values[index];
};

World.resolve = function ( world, x ) {
    while (typeof x === 'object' && x.borjes === 'variable') {
        x = world.values[x.index];
    }
    return x;
};

World.bind = function ( world, x ) {
    x.borjes_bound = world;
};

World.put = function ( world, x ) {
    world.values.push(x);
    return world.values.length-1;
};

World.set = function ( world, index, x ) {
    world.values[index] = x;
};

function copy_world ( x, map ) {
    return {
        borjes: 'world',
        values: x.values.map(function(v) {
            return copy(v, map);
        })
    };
}

// VARIABLE

function Variable ( world, value ) {
    return {
        borjes: 'variable',
        index: World.put(world, value)
    };
}

Variable.copy = function ( x, map ) {
    var i;
    if (map) {
        if (map[x.index] !== undefined) {
            i = map[x.index];
        } else {
            i = World.put(map.nw,
                copy(World.get(map.w, x.index),map));
            map[x.index] = i;
        }
    } else {
        i = x.index;
    }
    return {
        borjes: 'variable',
        index: i
    };
}

// PREDICATE

var predicates = {};

function Predicate ( name, params ) {
    return {
        borjes: 'predicate',
        params: params,
        name: name
    };
}

Predicate.create = function ( name, func ) {
    predicates[name] = func;
}

// actually applies it
Predicate.copy = function ( pred, map ) {
    var args = [];
    for (var i=0; i<pred.params.length; i++) {
        var p = pred.params[i];
        if (typeof p !== 'object' || p.borjes !== 'variable') {
            args.push(copy(p, map));
        } else {
            args.push(World.resolve(map.nw, Variable.copy(p, map)));
        }
    }
    return predicates[pred.name].apply(null, args);
}

// FUNCTIONS

function eq ( x, y ) {
    if (x === y) {
        return true;
    }
    if (x.borjes !== y.borjes) {
        return false;
    }
    if (x.borjes === 'nothing' || y.borjes === 'anything') {
        return true;
    }
    if (x.borjes === 'literal') {
        return x.s === y.s;
    }
    if (x.borjes === 'latticeel') {
        return x.l === y.l && x.e === y.e;
    }
    return false;
}

function copy ( x, map ) {
    if (typeof x !== 'object' || primitive[x.borjes]) {
        return x;
    }
    if (x.borjes === 'world') {
        return copy_world(x, map);
    }
    var c = Nothing;
    if (x.borjes === 'fstruct') {
        c = copy_fs(x, map);
    } else if (x.borjes === 'variable') {
        c = Variable.copy(x, map);
    } else if (x.borjes === 'predicate') {
        c = Predicate.copy(x, map);
    }
    if (x.borjes_bound !== undefined) {
        World.bind(map.nw, c);
    }
    return c;
}

function compare ( x, y, worldx, worldy ) {
    if (x.borjes_bound) { worldx = x.borjes_bound; }
    if (y.borjes_bound) { worldy = y.borjes_bound; }
    if (x.borjes === 'variable') {
        return compare(World.get(worldx, x.index), y, worldx, worldy);
    }
    if (y.borjes === 'variable') {
        return compare(x, World.get(worldy, y.index), worldx, worldy);
    }
    if (x.borjes !== y.borjes) {
        return false;
    }
    if (primitive[x.borjes]) {
        return eq(x, y);
    }
    if (x.borjes === 'fstruct') {
        return compare_fs(x, y, worldx, worldy);
    }
    return false;
}

module.exports = {
    Nothing: Nothing,
    Anything: Anything,
    Literal: Literal,
    Lattice: Lattice,
    FStruct: FStruct,
    TFS: TFS,
    World: World,
    Variable: Variable,
    Predicate: Predicate,
    eq: eq,
    copy: copy,
    compare: compare
};
<|endoftext|>


<commit_before>'use strict';

var promise = require('bluebird'),
    css = require('css'),
    fs = require('fs'),
    glob = require('glob'),
    isHTML = require('is-html'),
    isURL = require('is-absolute-url'),
    phantom = require('./phantom.js'),
    uncss = require('./lib.js'),
    utility = require('./utility.js'),
    _ = require('lodash');

/**
 * Get the contents of HTML pages through PhantomJS.
 * @return {promise}
 */
function getHTML(files, options) {

    if (_.isString(files)) {
        return phantom.fromRaw(files, options.timeout).then(function (pages) {
            return [files, options, [pages]];
        });
    }

    files = _.flatten(files.map(function (file) {
        if (!isURL(file) && !isHTML(file)) {
            return glob.sync(file);
        }
        return file;
    }));

    if (files.length === 0) {
        throw new Error('UnCSS: no HTML files found');
    }

    return promise.map(files, function (filename) {
        if (isURL(filename)) {
            return phantom.fromRemote(filename, options);
        }
        if (fs.existsSync(filename)) {
            return phantom.fromLocal(filename, options);
        }
        // raw html
        return phantom.fromRaw(filename, options);
    }).then(function (pages) {
        return [files, options, pages];
    });
}

/**
 * Get the contents of CSS files.
 * @return {promise}
 */
function getStylesheets(files, options, pages) {
    if (options.stylesheets && options.stylesheets.length > 0) {
        /* Simulate the behavior below */
        return [files, options, pages, [options.stylesheets]];
    }
    /* Extract the stylesheets from the HTML */
    return promise.map(pages, function (page) {
        return phantom.getStylesheets(page, options);
    }).then(function (stylesheets) {
        return [files, options, pages, stylesheets];
    });
}

/**
 * Get the contents of CSS files.
 * @param  {Array}   stylesheets list of stylesheet paths
 * @return {promise}
 */
function getCSS(files, options, pages, stylesheets) {
    /* Ignore specified stylesheets */
    if (options.ignoreSheets.length > 0) {
        stylesheets = stylesheets.map(function (arr) {
            return arr.filter(function (sheet) {
                return _.every(options.ignoreSheets, function (ignore) {
                    if (_.isRegExp(ignore)) {
                        return !ignore.test(sheet);
                    }
                    return sheet !== ignore;
                });
            });
        });
    }

    if (_.flatten(stylesheets).length !== 0) {
        /* Only run this if we found links to stylesheets (there may be none...)
         *  files       = ['some_file.html', 'some_other_file.html']
         *  stylesheets = [['relative_css_path.css', ...],
         *                 ['maybe_a_duplicate.css', ...]]
         * We need to - make the stylesheets' paths relative to the HTML files,
         *            - flatten the array,
         *            - remove duplicates
         */
        stylesheets =
            _.chain(stylesheets)
            .map(function (sheets, i) {
                return utility.parsePaths(files[i], sheets, options);
            })
            .flatten()
            .uniq()
            .value();
    } else {
        /* Reset the array if we didn't find any link tags */
        stylesheets = [];
    }
    return [files, options, pages, utility.readStylesheets(stylesheets)];
}

/**
 * Do the actual work
 * @param  {Array}   stylesheets list of CSS files
 * @return {promise}
 */
function process(files, options, pages, stylesheets) {
    /* If we specified a raw string of CSS, add it to the stylesheets array */
    if (options.raw) {
        if (_.isString(options.raw)) {
            stylesheets.push(options.raw);
        } else {
            throw new Error('UnCSS: options.raw - expected a string');
        }
    }

    /* At this point, there isn't any point in running the rest of the task if:
     * - We didn't specify any stylesheet links in the options object
     * - We couldn't find any stylesheet links in the HTML itself
     * - We weren't passed a string of raw CSS in addition to, or to replace
     *     either of the above
     */
    if (_.flatten(stylesheets).length === 0) {
        throw new Error('UnCSS: no stylesheets found');
    }

    /* OK, so we have some CSS to work with!
     * Three steps:
     * - Parse the CSS
     * - Remove the unused rules
     * - Return the optimized CSS as a string
     */
    var cssStr = stylesheets.join(' \n'),
        parsed, report;

    try {
        parsed = css.parse(cssStr);
    } catch (err) {
        /* Try and construct a helpful error message */
        throw utility.parseErrorMessage(err, cssStr);
    }
    return uncss(pages, parsed.stylesheet, options.ignore).then(function (res) {
        var usedCss = css.stringify(res[0]);
        if (options.report) {
            report = {
                original: cssStr,
                selectors: res[1]
            };
        }
        return new promise(function (resolve) {
            resolve([usedCss + '\n', report]);
        });
    });
}

/**
 * Main exposed function.
 * Here we check the options and callback, then run the files through PhantomJS.
 * @param {Array}    files array of filenames
 * @param {Object}   [options]   options
 * @param {Function} callback(Error, String, Object)
 */
function init(files, options, callback) {

    if (_.isFunction(options)) {
        /* There were no options, this argument is actually the callback */
        callback = options;
        options = {};
    } else if (!_.isFunction(callback)) {
        throw new TypeError('UnCSS: expected a callback');
    }

    /* Try and read options from the specified uncssrc file */
    if (options.uncssrc) {
        try {
            options = utility.parseUncssrc(options.uncssrc);
        } catch (err) {
            if (err instanceof SyntaxError) {
                return callback(new SyntaxError('UnCSS: uncssrc file is invalid JSON.'));
            }
            return callback(err);

        }
    }

    /* Assign default values to options, unless specified */
    options = _.defaults(options, {
        csspath: '',
        ignore: [],
        media: [],
        timeout: 0,
        report: false,
        ignoreSheets: []
    });

    return promise
        .using(phantom.init(options.phantom), function () {
            return getHTML(files, options)
                .spread(getStylesheets)
                .spread(getCSS)
                .spread(process);
        })
        .nodeify(callback, { spread: true });
}

module.exports = init;
<commit_msg>Minor style fixes<commit_after>'use strict';

var promise = require('bluebird'),
    css = require('css'),
    fs = require('fs'),
    glob = require('glob'),
    isHTML = require('is-html'),
    isURL = require('is-absolute-url'),
    phantom = require('./phantom.js'),
    uncss = require('./lib.js'),
    utility = require('./utility.js'),
    _ = require('lodash');

/**
 * Get the contents of HTML pages through PhantomJS.
 * @param  {Array}   files   list of HTML files
 * @param  {Object}  options uncss options
 * @return {promise}
 */
function getHTML(files, options) {

    if (_.isString(files)) {
        return phantom.fromRaw(files, options.timeout).then(function (pages) {
            return [files, options, [pages]];
        });
    }

    files = _.flatten(files.map(function (file) {
        if (!isURL(file) && !isHTML(file)) {
            return glob.sync(file);
        }
        return file;
    }));

    if (files.length === 0) {
        throw new Error('UnCSS: no HTML files found');
    }

    return promise.map(files, function (filename) {
        if (isURL(filename)) {
            return phantom.fromRemote(filename, options);
        }
        if (fs.existsSync(filename)) {
            return phantom.fromLocal(filename, options);
        }
        // raw html
        return phantom.fromRaw(filename, options);
    }).then(function (pages) {
        return [files, options, pages];
    });
}

/**
 * Get the contents of CSS files.
 * @param  {Array}   files   list of HTML files
 * @param  {Object}  options uncss options
 * @param  {Array}   pages   pages opened by phridge
 * @return {promise}
 */
function getStylesheets(files, options, pages) {
    if (options.stylesheets && options.stylesheets.length > 0) {
        /* Simulate the behavior below */
        return [files, options, pages, [options.stylesheets]];
    }
    /* Extract the stylesheets from the HTML */
    return promise.map(pages, function (page) {
        return phantom.getStylesheets(page, options);
    }).then(function (stylesheets) {
        return [files, options, pages, stylesheets];
    });
}

/**
 * Get the contents of CSS files.
 * @param  {Array}   files       list of HTML files
 * @param  {Object}  options     uncss options
 * @param  {Array}   pages       pages opened by phridge
 * @param  {Array}   stylesheets list of CSS files
 * @return {promise}
 */
function getCSS(files, options, pages, stylesheets) {
    /* Ignore specified stylesheets */
    if (options.ignoreSheets.length > 0) {
        stylesheets = stylesheets.map(function (arr) {
            return arr.filter(function (sheet) {
                return _.every(options.ignoreSheets, function (ignore) {
                    if (_.isRegExp(ignore)) {
                        return !ignore.test(sheet);
                    }
                    return sheet !== ignore;
                });
            });
        });
    }

    if (_.flatten(stylesheets).length !== 0) {
        /* Only run this if we found links to stylesheets (there may be none...)
         *  files       = ['some_file.html', 'some_other_file.html']
         *  stylesheets = [['relative_css_path.css', ...],
         *                 ['maybe_a_duplicate.css', ...]]
         * We need to - make the stylesheets' paths relative to the HTML files,
         *            - flatten the array,
         *            - remove duplicates
         */
        stylesheets =
            _.chain(stylesheets)
            .map(function (sheets, i) {
                return utility.parsePaths(files[i], sheets, options);
            })
            .flatten()
            .uniq()
            .value();
    } else {
        /* Reset the array if we didn't find any link tags */
        stylesheets = [];
    }
    return [files, options, pages, utility.readStylesheets(stylesheets)];
}

/**
 * Do the actual work
 * @param  {Array}   files       list of HTML files
 * @param  {Object}  options     uncss options
 * @param  {Array}   pages       pages opened by phridge
 * @param  {Array}   stylesheets list of CSS files
 * @return {promise}
 */
function process(files, options, pages, stylesheets) {
    /* If we specified a raw string of CSS, add it to the stylesheets array */
    if (options.raw) {
        if (_.isString(options.raw)) {
            stylesheets.push(options.raw);
        } else {
            throw new Error('UnCSS: options.raw - expected a string');
        }
    }

    /* At this point, there isn't any point in running the rest of the task if:
     * - We didn't specify any stylesheet links in the options object
     * - We couldn't find any stylesheet links in the HTML itself
     * - We weren't passed a string of raw CSS in addition to, or to replace
     *     either of the above
     */
    if (_.flatten(stylesheets).length === 0) {
        throw new Error('UnCSS: no stylesheets found');
    }

    /* OK, so we have some CSS to work with!
     * Three steps:
     * - Parse the CSS
     * - Remove the unused rules
     * - Return the optimized CSS as a string
     */
    var cssStr = stylesheets.join(' \n'),
        parsed, report;

    try {
        parsed = css.parse(cssStr);
    } catch (err) {
        /* Try and construct a helpful error message */
        throw utility.parseErrorMessage(err, cssStr);
    }
    return uncss(pages, parsed.stylesheet, options.ignore).spread(function (used, rep) {
        var usedCss = css.stringify(used);
        if (options.report) {
            report = {
                original: cssStr,
                selectors: rep
            };
        }
        return new promise(function (resolve) {
            resolve([usedCss + '\n', report]);
        });
    });
}

/**
 * Main exposed function.
 * Here we check the options and callback, then run the files through PhantomJS.
 * @param {Array}    files     array of filenames
 * @param {Object}   [options] options
 * @param {Function} callback(Error, String, Object)
 */
function init(files, options, callback) {

    if (_.isFunction(options)) {
        /* There were no options, this argument is actually the callback */
        callback = options;
        options = {};
    } else if (!_.isFunction(callback)) {
        throw new TypeError('UnCSS: expected a callback');
    }

    /* Try and read options from the specified uncssrc file */
    if (options.uncssrc) {
        try {
            options = utility.parseUncssrc(options.uncssrc);
        } catch (err) {
            if (err instanceof SyntaxError) {
                return callback(new SyntaxError('UnCSS: uncssrc file is invalid JSON.'));
            }
            return callback(err);

        }
    }

    /* Assign default values to options, unless specified */
    options = _.defaults(options, {
        csspath: '',
        ignore: [],
        media: [],
        timeout: 0,
        report: false,
        ignoreSheets: []
    });

    return promise
        .using(phantom.init(options.phantom), function () {
            return getHTML(files, options)
                .spread(getStylesheets)
                .spread(getCSS)
                .spread(process);
        })
        .nodeify(callback, { spread: true });
}

module.exports = init;
<|endoftext|>


<commit_before>function LoadUtils(){
    texty.utils.blockTagNames = ['H1','H2','H3','H4'];
    texty.utils.filterBlockNodes = function(nodes) {
        return nodes.filter(function(node){
            return (node.tagName) && texty.utils.blockTagNames.indexOf(node.tagName) !== -1;
        });
    };
}<commit_msg>nodeName is faster<commit_after>function LoadUtils(){
    texty.utils.blockTagNames = ['H1','H2','H3','H4'];
    texty.utils.filterBlockNodes = function(nodes) {
        return nodes.filter(function(node){
            return texty.utils.blockTagNames.indexOf(node.nodeName) !== -1;
        });
    };
}<|endoftext|>