+
+
+
+
+
diff --git a/test/usage/leia.jpeg b/__test__/usage/leia.jpeg
similarity index 100%
rename from test/usage/leia.jpeg
rename to __test__/usage/leia.jpeg
diff --git a/test/usage/luke.jpeg b/__test__/usage/luke.jpeg
similarity index 100%
rename from test/usage/luke.jpeg
rename to __test__/usage/luke.jpeg
diff --git a/__test__/usage/main.js b/__test__/usage/main.js
new file mode 100644
index 00000000..5ff9002e
--- /dev/null
+++ b/__test__/usage/main.js
@@ -0,0 +1,6 @@
+require(['../../dist/list', '../../dist/list.min'], function (List, ListMin) {
+ var options = {
+ valueNames: ['name', 'born'],
+ }
+ var userList = new List('users', options)
+})
diff --git a/__test__/usage/require.js b/__test__/usage/require.js
new file mode 100644
index 00000000..7360434e
--- /dev/null
+++ b/__test__/usage/require.js
@@ -0,0 +1,2142 @@
+/** vim: et:ts=4:sw=4:sts=4
+ * @license RequireJS 2.1.17 Copyright (c) 2010-2015, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+//Not using strict: uneven strict support in browsers, #392, and causes
+//problems with requirejs.exec()/transpiler plugins that may not be strict.
+/*jslint regexp: true, nomen: true, sloppy: true */
+/*global window, navigator, document, importScripts, setTimeout, opera */
+
+var requirejs, require, define
+;(function (global) {
+ var req,
+ s,
+ head,
+ baseElement,
+ dataMain,
+ src,
+ interactiveScript,
+ currentlyAddingScript,
+ mainScript,
+ subPath,
+ version = '2.1.17',
+ commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/gm,
+ cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
+ jsSuffixRegExp = /\.js$/,
+ currDirRegExp = /^\.\//,
+ op = Object.prototype,
+ ostring = op.toString,
+ hasOwn = op.hasOwnProperty,
+ ap = Array.prototype,
+ apsp = ap.splice,
+ isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document),
+ isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
+ //PS3 indicates loaded and complete, but need to wait for complete
+ //specifically. Sequence is 'loading', 'loaded', execution,
+ // then 'complete'. The UA check is unfortunate, but not sure how
+ //to feature test w/o causing perf issues.
+ readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ? /^complete$/ : /^(complete|loaded)$/,
+ defContextName = '_',
+ //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
+ isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
+ contexts = {},
+ cfg = {},
+ globalDefQueue = [],
+ useInteractive = false
+
+ function isFunction(it) {
+ return ostring.call(it) === '[object Function]'
+ }
+
+ function isArray(it) {
+ return ostring.call(it) === '[object Array]'
+ }
+
+ /**
+ * Helper function for iterating over an array. If the func returns
+ * a true value, it will break out of the loop.
+ */
+ function each(ary, func) {
+ if (ary) {
+ var i
+ for (i = 0; i < ary.length; i += 1) {
+ if (ary[i] && func(ary[i], i, ary)) {
+ break
+ }
+ }
+ }
+ }
+
+ /**
+ * Helper function for iterating over an array backwards. If the func
+ * returns a true value, it will break out of the loop.
+ */
+ function eachReverse(ary, func) {
+ if (ary) {
+ var i
+ for (i = ary.length - 1; i > -1; i -= 1) {
+ if (ary[i] && func(ary[i], i, ary)) {
+ break
+ }
+ }
+ }
+ }
+
+ function hasProp(obj, prop) {
+ return hasOwn.call(obj, prop)
+ }
+
+ function getOwn(obj, prop) {
+ return hasProp(obj, prop) && obj[prop]
+ }
+
+ /**
+ * Cycles over properties in an object and calls a function for each
+ * property value. If the function returns a truthy value, then the
+ * iteration is stopped.
+ */
+ function eachProp(obj, func) {
+ var prop
+ for (prop in obj) {
+ if (hasProp(obj, prop)) {
+ if (func(obj[prop], prop)) {
+ break
+ }
+ }
+ }
+ }
+
+ /**
+ * Simple function to mix in properties from source into target,
+ * but only if target does not already have a property of the same name.
+ */
+ function mixin(target, source, force, deepStringMixin) {
+ if (source) {
+ eachProp(source, function (value, prop) {
+ if (force || !hasProp(target, prop)) {
+ if (
+ deepStringMixin &&
+ typeof value === 'object' &&
+ value &&
+ !isArray(value) &&
+ !isFunction(value) &&
+ !(value instanceof RegExp)
+ ) {
+ if (!target[prop]) {
+ target[prop] = {}
+ }
+ mixin(target[prop], value, force, deepStringMixin)
+ } else {
+ target[prop] = value
+ }
+ }
+ })
+ }
+ return target
+ }
+
+ //Similar to Function.prototype.bind, but the 'this' object is specified
+ //first, since it is easier to read/figure out what 'this' will be.
+ function bind(obj, fn) {
+ return function () {
+ return fn.apply(obj, arguments)
+ }
+ }
+
+ function scripts() {
+ return document.getElementsByTagName('script')
+ }
+
+ function defaultOnError(err) {
+ throw err
+ }
+
+ //Allow getting a global that is expressed in
+ //dot notation, like 'a.b.c'.
+ function getGlobal(value) {
+ if (!value) {
+ return value
+ }
+ var g = global
+ each(value.split('.'), function (part) {
+ g = g[part]
+ })
+ return g
+ }
+
+ /**
+ * Constructs an error with a pointer to an URL with more information.
+ * @param {String} id the error ID that maps to an ID on a web page.
+ * @param {String} message human readable error.
+ * @param {Error} [err] the original error, if there is one.
+ *
+ * @returns {Error}
+ */
+ function makeError(id, msg, err, requireModules) {
+ var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id)
+ e.requireType = id
+ e.requireModules = requireModules
+ if (err) {
+ e.originalError = err
+ }
+ return e
+ }
+
+ if (typeof define !== 'undefined') {
+ //If a define is already in play via another AMD loader,
+ //do not overwrite.
+ return
+ }
+
+ if (typeof requirejs !== 'undefined') {
+ if (isFunction(requirejs)) {
+ //Do not overwrite an existing requirejs instance.
+ return
+ }
+ cfg = requirejs
+ requirejs = undefined
+ }
+
+ //Allow for a require config object
+ if (typeof require !== 'undefined' && !isFunction(require)) {
+ //assume it is a config object.
+ cfg = require
+ require = undefined
+ }
+
+ function newContext(contextName) {
+ var inCheckLoaded,
+ Module,
+ context,
+ handlers,
+ checkLoadedTimeoutId,
+ config = {
+ //Defaults. Do not set a default for map
+ //config to speed up normalize(), which
+ //will run faster if there is no default.
+ waitSeconds: 7,
+ baseUrl: './',
+ paths: {},
+ bundles: {},
+ pkgs: {},
+ shim: {},
+ config: {},
+ },
+ registry = {},
+ //registry of just enabled modules, to speed
+ //cycle breaking code when lots of modules
+ //are registered, but not activated.
+ enabledRegistry = {},
+ undefEvents = {},
+ defQueue = [],
+ defined = {},
+ urlFetched = {},
+ bundlesMap = {},
+ requireCounter = 1,
+ unnormalizedCounter = 1
+
+ /**
+ * Trims the . and .. from an array of path segments.
+ * It will keep a leading path segment if a .. will become
+ * the first path segment, to help with module name lookups,
+ * which act like paths, but can be remapped. But the end result,
+ * all paths that use this function should look normalized.
+ * NOTE: this method MODIFIES the input array.
+ * @param {Array} ary the array of path segments.
+ */
+ function trimDots(ary) {
+ var i, part
+ for (i = 0; i < ary.length; i++) {
+ part = ary[i]
+ if (part === '.') {
+ ary.splice(i, 1)
+ i -= 1
+ } else if (part === '..') {
+ // If at the start, or previous value is still ..,
+ // keep them so that when converted to a path it may
+ // still work when converted to a path, even though
+ // as an ID it is less than ideal. In larger point
+ // releases, may be better to just kick out an error.
+ if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') {
+ continue
+ } else if (i > 0) {
+ ary.splice(i - 1, 2)
+ i -= 2
+ }
+ }
+ }
+ }
+
+ /**
+ * Given a relative module name, like ./something, normalize it to
+ * a real name that can be mapped to a path.
+ * @param {String} name the relative name
+ * @param {String} baseName a real name that the name arg is relative
+ * to.
+ * @param {Boolean} applyMap apply the map config to the value. Should
+ * only be done if this normalization is for a dependency ID.
+ * @returns {String} normalized name
+ */
+ function normalize(name, baseName, applyMap) {
+ var pkgMain,
+ mapValue,
+ nameParts,
+ i,
+ j,
+ nameSegment,
+ lastIndex,
+ foundMap,
+ foundI,
+ foundStarMap,
+ starI,
+ normalizedBaseParts,
+ baseParts = baseName && baseName.split('/'),
+ map = config.map,
+ starMap = map && map['*']
+
+ //Adjust any relative paths.
+ if (name) {
+ name = name.split('/')
+ lastIndex = name.length - 1
+
+ // If wanting node ID compatibility, strip .js from end
+ // of IDs. Have to do this here, and not in nameToUrl
+ // because node allows either .js or non .js to map
+ // to same file.
+ if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
+ name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '')
+ }
+
+ // Starts with a '.' so need the baseName
+ if (name[0].charAt(0) === '.' && baseParts) {
+ //Convert baseName to array, and lop off the last part,
+ //so that . matches that 'directory' and not name of the baseName's
+ //module. For instance, baseName of 'one/two/three', maps to
+ //'one/two/three.js', but we want the directory, 'one/two' for
+ //this normalization.
+ normalizedBaseParts = baseParts.slice(0, baseParts.length - 1)
+ name = normalizedBaseParts.concat(name)
+ }
+
+ trimDots(name)
+ name = name.join('/')
+ }
+
+ //Apply map config if available.
+ if (applyMap && map && (baseParts || starMap)) {
+ nameParts = name.split('/')
+
+ outerLoop: for (i = nameParts.length; i > 0; i -= 1) {
+ nameSegment = nameParts.slice(0, i).join('/')
+
+ if (baseParts) {
+ //Find the longest baseName segment match in the config.
+ //So, do joins on the biggest to smallest lengths of baseParts.
+ for (j = baseParts.length; j > 0; j -= 1) {
+ mapValue = getOwn(map, baseParts.slice(0, j).join('/'))
+
+ //baseName segment has config, find if it has one for
+ //this name.
+ if (mapValue) {
+ mapValue = getOwn(mapValue, nameSegment)
+ if (mapValue) {
+ //Match, update name to the new value.
+ foundMap = mapValue
+ foundI = i
+ break outerLoop
+ }
+ }
+ }
+ }
+
+ //Check for a star map match, but just hold on to it,
+ //if there is a shorter segment match later in a matching
+ //config, then favor over this star map.
+ if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
+ foundStarMap = getOwn(starMap, nameSegment)
+ starI = i
+ }
+ }
+
+ if (!foundMap && foundStarMap) {
+ foundMap = foundStarMap
+ foundI = starI
+ }
+
+ if (foundMap) {
+ nameParts.splice(0, foundI, foundMap)
+ name = nameParts.join('/')
+ }
+ }
+
+ // If the name points to a package's name, use
+ // the package main instead.
+ pkgMain = getOwn(config.pkgs, name)
+
+ return pkgMain ? pkgMain : name
+ }
+
+ function removeScript(name) {
+ if (isBrowser) {
+ each(scripts(), function (scriptNode) {
+ if (
+ scriptNode.getAttribute('data-requiremodule') === name &&
+ scriptNode.getAttribute('data-requirecontext') === context.contextName
+ ) {
+ scriptNode.parentNode.removeChild(scriptNode)
+ return true
+ }
+ })
+ }
+ }
+
+ function hasPathFallback(id) {
+ var pathConfig = getOwn(config.paths, id)
+ if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
+ //Pop off the first array value, since it failed, and
+ //retry
+ pathConfig.shift()
+ context.require.undef(id)
+
+ //Custom require that does not do map translation, since
+ //ID is "absolute", already mapped/resolved.
+ context.makeRequire(null, {
+ skipMap: true,
+ })([id])
+
+ return true
+ }
+ }
+
+ //Turns a plugin!resource to [plugin, resource]
+ //with the plugin being undefined if the name
+ //did not have a plugin prefix.
+ function splitPrefix(name) {
+ var prefix,
+ index = name ? name.indexOf('!') : -1
+ if (index > -1) {
+ prefix = name.substring(0, index)
+ name = name.substring(index + 1, name.length)
+ }
+ return [prefix, name]
+ }
+
+ /**
+ * Creates a module mapping that includes plugin prefix, module
+ * name, and path. If parentModuleMap is provided it will
+ * also normalize the name via require.normalize()
+ *
+ * @param {String} name the module name
+ * @param {String} [parentModuleMap] parent module map
+ * for the module name, used to resolve relative names.
+ * @param {Boolean} isNormalized: is the ID already normalized.
+ * This is true if this call is done for a define() module ID.
+ * @param {Boolean} applyMap: apply the map config to the ID.
+ * Should only be true if this map is for a dependency.
+ *
+ * @returns {Object}
+ */
+ function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
+ var url,
+ pluginModule,
+ suffix,
+ nameParts,
+ prefix = null,
+ parentName = parentModuleMap ? parentModuleMap.name : null,
+ originalName = name,
+ isDefine = true,
+ normalizedName = ''
+
+ //If no name, then it means it is a require call, generate an
+ //internal name.
+ if (!name) {
+ isDefine = false
+ name = '_@r' + (requireCounter += 1)
+ }
+
+ nameParts = splitPrefix(name)
+ prefix = nameParts[0]
+ name = nameParts[1]
+
+ if (prefix) {
+ prefix = normalize(prefix, parentName, applyMap)
+ pluginModule = getOwn(defined, prefix)
+ }
+
+ //Account for relative paths if there is a base name.
+ if (name) {
+ if (prefix) {
+ if (pluginModule && pluginModule.normalize) {
+ //Plugin is loaded, use its normalize method.
+ normalizedName = pluginModule.normalize(name, function (name) {
+ return normalize(name, parentName, applyMap)
+ })
+ } else {
+ // If nested plugin references, then do not try to
+ // normalize, as it will not normalize correctly. This
+ // places a restriction on resourceIds, and the longer
+ // term solution is not to normalize until plugins are
+ // loaded and all normalizations to allow for async
+ // loading of a loader plugin. But for now, fixes the
+ // common uses. Details in #1131
+ normalizedName = name.indexOf('!') === -1 ? normalize(name, parentName, applyMap) : name
+ }
+ } else {
+ //A regular module.
+ normalizedName = normalize(name, parentName, applyMap)
+
+ //Normalized name may be a plugin ID due to map config
+ //application in normalize. The map config values must
+ //already be normalized, so do not need to redo that part.
+ nameParts = splitPrefix(normalizedName)
+ prefix = nameParts[0]
+ normalizedName = nameParts[1]
+ isNormalized = true
+
+ url = context.nameToUrl(normalizedName)
+ }
+ }
+
+ //If the id is a plugin id that cannot be determined if it needs
+ //normalization, stamp it with a unique ID so two matching relative
+ //ids that may conflict can be separate.
+ suffix = prefix && !pluginModule && !isNormalized ? '_unnormalized' + (unnormalizedCounter += 1) : ''
+
+ return {
+ prefix: prefix,
+ name: normalizedName,
+ parentMap: parentModuleMap,
+ unnormalized: !!suffix,
+ url: url,
+ originalName: originalName,
+ isDefine: isDefine,
+ id: (prefix ? prefix + '!' + normalizedName : normalizedName) + suffix,
+ }
+ }
+
+ function getModule(depMap) {
+ var id = depMap.id,
+ mod = getOwn(registry, id)
+
+ if (!mod) {
+ mod = registry[id] = new context.Module(depMap)
+ }
+
+ return mod
+ }
+
+ function on(depMap, name, fn) {
+ var id = depMap.id,
+ mod = getOwn(registry, id)
+
+ if (hasProp(defined, id) && (!mod || mod.defineEmitComplete)) {
+ if (name === 'defined') {
+ fn(defined[id])
+ }
+ } else {
+ mod = getModule(depMap)
+ if (mod.error && name === 'error') {
+ fn(mod.error)
+ } else {
+ mod.on(name, fn)
+ }
+ }
+ }
+
+ function onError(err, errback) {
+ var ids = err.requireModules,
+ notified = false
+
+ if (errback) {
+ errback(err)
+ } else {
+ each(ids, function (id) {
+ var mod = getOwn(registry, id)
+ if (mod) {
+ //Set error on module, so it skips timeout checks.
+ mod.error = err
+ if (mod.events.error) {
+ notified = true
+ mod.emit('error', err)
+ }
+ }
+ })
+
+ if (!notified) {
+ req.onError(err)
+ }
+ }
+ }
+
+ /**
+ * Internal method to transfer globalQueue items to this context's
+ * defQueue.
+ */
+ function takeGlobalQueue() {
+ //Push all the globalDefQueue items into the context's defQueue
+ if (globalDefQueue.length) {
+ //Array splice in the values since the context code has a
+ //local var ref to defQueue, so cannot just reassign the one
+ //on context.
+ apsp.apply(defQueue, [defQueue.length, 0].concat(globalDefQueue))
+ globalDefQueue = []
+ }
+ }
+
+ handlers = {
+ require: function (mod) {
+ if (mod.require) {
+ return mod.require
+ } else {
+ return (mod.require = context.makeRequire(mod.map))
+ }
+ },
+ exports: function (mod) {
+ mod.usingExports = true
+ if (mod.map.isDefine) {
+ if (mod.exports) {
+ return (defined[mod.map.id] = mod.exports)
+ } else {
+ return (mod.exports = defined[mod.map.id] = {})
+ }
+ }
+ },
+ module: function (mod) {
+ if (mod.module) {
+ return mod.module
+ } else {
+ return (mod.module = {
+ id: mod.map.id,
+ uri: mod.map.url,
+ config: function () {
+ return getOwn(config.config, mod.map.id) || {}
+ },
+ exports: mod.exports || (mod.exports = {}),
+ })
+ }
+ },
+ }
+
+ function cleanRegistry(id) {
+ //Clean up machinery used for waiting modules.
+ delete registry[id]
+ delete enabledRegistry[id]
+ }
+
+ function breakCycle(mod, traced, processed) {
+ var id = mod.map.id
+
+ if (mod.error) {
+ mod.emit('error', mod.error)
+ } else {
+ traced[id] = true
+ each(mod.depMaps, function (depMap, i) {
+ var depId = depMap.id,
+ dep = getOwn(registry, depId)
+
+ //Only force things that have not completed
+ //being defined, so still in the registry,
+ //and only if it has not been matched up
+ //in the module already.
+ if (dep && !mod.depMatched[i] && !processed[depId]) {
+ if (getOwn(traced, depId)) {
+ mod.defineDep(i, defined[depId])
+ mod.check() //pass false?
+ } else {
+ breakCycle(dep, traced, processed)
+ }
+ }
+ })
+ processed[id] = true
+ }
+ }
+
+ function checkLoaded() {
+ var err,
+ usingPathFallback,
+ waitInterval = config.waitSeconds * 1000,
+ //It is possible to disable the wait interval by using waitSeconds of 0.
+ expired = waitInterval && context.startTime + waitInterval < new Date().getTime(),
+ noLoads = [],
+ reqCalls = [],
+ stillLoading = false,
+ needCycleCheck = true
+
+ //Do not bother if this call was a result of a cycle break.
+ if (inCheckLoaded) {
+ return
+ }
+
+ inCheckLoaded = true
+
+ //Figure out the state of all the modules.
+ eachProp(enabledRegistry, function (mod) {
+ var map = mod.map,
+ modId = map.id
+
+ //Skip things that are not enabled or in error state.
+ if (!mod.enabled) {
+ return
+ }
+
+ if (!map.isDefine) {
+ reqCalls.push(mod)
+ }
+
+ if (!mod.error) {
+ //If the module should be executed, and it has not
+ //been inited and time is up, remember it.
+ if (!mod.inited && expired) {
+ if (hasPathFallback(modId)) {
+ usingPathFallback = true
+ stillLoading = true
+ } else {
+ noLoads.push(modId)
+ removeScript(modId)
+ }
+ } else if (!mod.inited && mod.fetched && map.isDefine) {
+ stillLoading = true
+ if (!map.prefix) {
+ //No reason to keep looking for unfinished
+ //loading. If the only stillLoading is a
+ //plugin resource though, keep going,
+ //because it may be that a plugin resource
+ //is waiting on a non-plugin cycle.
+ return (needCycleCheck = false)
+ }
+ }
+ }
+ })
+
+ if (expired && noLoads.length) {
+ //If wait time expired, throw error of unloaded modules.
+ err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads)
+ err.contextName = context.contextName
+ return onError(err)
+ }
+
+ //Not expired, check for a cycle.
+ if (needCycleCheck) {
+ each(reqCalls, function (mod) {
+ breakCycle(mod, {}, {})
+ })
+ }
+
+ //If still waiting on loads, and the waiting load is something
+ //other than a plugin resource, or there are still outstanding
+ //scripts, then just try back later.
+ if ((!expired || usingPathFallback) && stillLoading) {
+ //Something is still waiting to load. Wait for it, but only
+ //if a timeout is not already in effect.
+ if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
+ checkLoadedTimeoutId = setTimeout(function () {
+ checkLoadedTimeoutId = 0
+ checkLoaded()
+ }, 50)
+ }
+ }
+
+ inCheckLoaded = false
+ }
+
+ Module = function (map) {
+ this.events = getOwn(undefEvents, map.id) || {}
+ this.map = map
+ this.shim = getOwn(config.shim, map.id)
+ this.depExports = []
+ this.depMaps = []
+ this.depMatched = []
+ this.pluginMaps = {}
+ this.depCount = 0
+
+ /* this.exports this.factory
+ this.depMaps = [],
+ this.enabled, this.fetched
+ */
+ }
+
+ Module.prototype = {
+ init: function (depMaps, factory, errback, options) {
+ options = options || {}
+
+ //Do not do more inits if already done. Can happen if there
+ //are multiple define calls for the same module. That is not
+ //a normal, common case, but it is also not unexpected.
+ if (this.inited) {
+ return
+ }
+
+ this.factory = factory
+
+ if (errback) {
+ //Register for errors on this module.
+ this.on('error', errback)
+ } else if (this.events.error) {
+ //If no errback already, but there are error listeners
+ //on this module, set up an errback to pass to the deps.
+ errback = bind(this, function (err) {
+ this.emit('error', err)
+ })
+ }
+
+ //Do a copy of the dependency array, so that
+ //source inputs are not modified. For example
+ //"shim" deps are passed in here directly, and
+ //doing a direct modification of the depMaps array
+ //would affect that config.
+ this.depMaps = depMaps && depMaps.slice(0)
+
+ this.errback = errback
+
+ //Indicate this module has be initialized
+ this.inited = true
+
+ this.ignore = options.ignore
+
+ //Could have option to init this module in enabled mode,
+ //or could have been previously marked as enabled. However,
+ //the dependencies are not known until init is called. So
+ //if enabled previously, now trigger dependencies as enabled.
+ if (options.enabled || this.enabled) {
+ //Enable this module and dependencies.
+ //Will call this.check()
+ this.enable()
+ } else {
+ this.check()
+ }
+ },
+
+ defineDep: function (i, depExports) {
+ //Because of cycles, defined callback for a given
+ //export can be called more than once.
+ if (!this.depMatched[i]) {
+ this.depMatched[i] = true
+ this.depCount -= 1
+ this.depExports[i] = depExports
+ }
+ },
+
+ fetch: function () {
+ if (this.fetched) {
+ return
+ }
+ this.fetched = true
+
+ context.startTime = new Date().getTime()
+
+ var map = this.map
+
+ //If the manager is for a plugin managed resource,
+ //ask the plugin to load it now.
+ if (this.shim) {
+ context.makeRequire(this.map, {
+ enableBuildCallback: true,
+ })(
+ this.shim.deps || [],
+ bind(this, function () {
+ return map.prefix ? this.callPlugin() : this.load()
+ })
+ )
+ } else {
+ //Regular dependency.
+ return map.prefix ? this.callPlugin() : this.load()
+ }
+ },
+
+ load: function () {
+ var url = this.map.url
+
+ //Regular dependency.
+ if (!urlFetched[url]) {
+ urlFetched[url] = true
+ context.load(this.map.id, url)
+ }
+ },
+
+ /**
+ * Checks if the module is ready to define itself, and if so,
+ * define it.
+ */
+ check: function () {
+ if (!this.enabled || this.enabling) {
+ return
+ }
+
+ var err,
+ cjsModule,
+ id = this.map.id,
+ depExports = this.depExports,
+ exports = this.exports,
+ factory = this.factory
+
+ if (!this.inited) {
+ this.fetch()
+ } else if (this.error) {
+ this.emit('error', this.error)
+ } else if (!this.defining) {
+ //The factory could trigger another require call
+ //that would result in checking this module to
+ //define itself again. If already in the process
+ //of doing that, skip this work.
+ this.defining = true
+
+ if (this.depCount < 1 && !this.defined) {
+ if (isFunction(factory)) {
+ //If there is an error listener, favor passing
+ //to that instead of throwing an error. However,
+ //only do it for define()'d modules. require
+ //errbacks should not be called for failures in
+ //their callbacks (#699). However if a global
+ //onError is set, use that.
+ if ((this.events.error && this.map.isDefine) || req.onError !== defaultOnError) {
+ try {
+ exports = context.execCb(id, factory, depExports, exports)
+ } catch (e) {
+ err = e
+ }
+ } else {
+ exports = context.execCb(id, factory, depExports, exports)
+ }
+
+ // Favor return value over exports. If node/cjs in play,
+ // then will not have a return value anyway. Favor
+ // module.exports assignment over exports object.
+ if (this.map.isDefine && exports === undefined) {
+ cjsModule = this.module
+ if (cjsModule) {
+ exports = cjsModule.exports
+ } else if (this.usingExports) {
+ //exports already set the defined value.
+ exports = this.exports
+ }
+ }
+
+ if (err) {
+ err.requireMap = this.map
+ err.requireModules = this.map.isDefine ? [this.map.id] : null
+ err.requireType = this.map.isDefine ? 'define' : 'require'
+ return onError((this.error = err))
+ }
+ } else {
+ //Just a literal value
+ exports = factory
+ }
+
+ this.exports = exports
+
+ if (this.map.isDefine && !this.ignore) {
+ defined[id] = exports
+
+ if (req.onResourceLoad) {
+ req.onResourceLoad(context, this.map, this.depMaps)
+ }
+ }
+
+ //Clean up
+ cleanRegistry(id)
+
+ this.defined = true
+ }
+
+ //Finished the define stage. Allow calling check again
+ //to allow define notifications below in the case of a
+ //cycle.
+ this.defining = false
+
+ if (this.defined && !this.defineEmitted) {
+ this.defineEmitted = true
+ this.emit('defined', this.exports)
+ this.defineEmitComplete = true
+ }
+ }
+ },
+
+ callPlugin: function () {
+ var map = this.map,
+ id = map.id,
+ //Map already normalized the prefix.
+ pluginMap = makeModuleMap(map.prefix)
+
+ //Mark this as a dependency for this plugin, so it
+ //can be traced for cycles.
+ this.depMaps.push(pluginMap)
+
+ on(
+ pluginMap,
+ 'defined',
+ bind(this, function (plugin) {
+ var load,
+ normalizedMap,
+ normalizedMod,
+ bundleId = getOwn(bundlesMap, this.map.id),
+ name = this.map.name,
+ parentName = this.map.parentMap ? this.map.parentMap.name : null,
+ localRequire = context.makeRequire(map.parentMap, {
+ enableBuildCallback: true,
+ })
+
+ //If current map is not normalized, wait for that
+ //normalized name to load instead of continuing.
+ if (this.map.unnormalized) {
+ //Normalize the ID if the plugin allows it.
+ if (plugin.normalize) {
+ name =
+ plugin.normalize(name, function (name) {
+ return normalize(name, parentName, true)
+ }) || ''
+ }
+
+ //prefix and name should already be normalized, no need
+ //for applying map config again either.
+ normalizedMap = makeModuleMap(map.prefix + '!' + name, this.map.parentMap)
+ on(
+ normalizedMap,
+ 'defined',
+ bind(this, function (value) {
+ this.init(
+ [],
+ function () {
+ return value
+ },
+ null,
+ {
+ enabled: true,
+ ignore: true,
+ }
+ )
+ })
+ )
+
+ normalizedMod = getOwn(registry, normalizedMap.id)
+ if (normalizedMod) {
+ //Mark this as a dependency for this plugin, so it
+ //can be traced for cycles.
+ this.depMaps.push(normalizedMap)
+
+ if (this.events.error) {
+ normalizedMod.on(
+ 'error',
+ bind(this, function (err) {
+ this.emit('error', err)
+ })
+ )
+ }
+ normalizedMod.enable()
+ }
+
+ return
+ }
+
+ //If a paths config, then just load that file instead to
+ //resolve the plugin, as it is built into that paths layer.
+ if (bundleId) {
+ this.map.url = context.nameToUrl(bundleId)
+ this.load()
+ return
+ }
+
+ load = bind(this, function (value) {
+ this.init(
+ [],
+ function () {
+ return value
+ },
+ null,
+ {
+ enabled: true,
+ }
+ )
+ })
+
+ load.error = bind(this, function (err) {
+ this.inited = true
+ this.error = err
+ err.requireModules = [id]
+
+ //Remove temp unnormalized modules for this module,
+ //since they will never be resolved otherwise now.
+ eachProp(registry, function (mod) {
+ if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
+ cleanRegistry(mod.map.id)
+ }
+ })
+
+ onError(err)
+ })
+
+ //Allow plugins to load other code without having to know the
+ //context or how to 'complete' the load.
+ load.fromText = bind(this, function (text, textAlt) {
+ /*jslint evil: true */
+ var moduleName = map.name,
+ moduleMap = makeModuleMap(moduleName),
+ hasInteractive = useInteractive
+
+ //As of 2.1.0, support just passing the text, to reinforce
+ //fromText only being called once per resource. Still
+ //support old style of passing moduleName but discard
+ //that moduleName in favor of the internal ref.
+ if (textAlt) {
+ text = textAlt
+ }
+
+ //Turn off interactive script matching for IE for any define
+ //calls in the text, then turn it back on at the end.
+ if (hasInteractive) {
+ useInteractive = false
+ }
+
+ //Prime the system by creating a module instance for
+ //it.
+ getModule(moduleMap)
+
+ //Transfer any config to this other module.
+ if (hasProp(config.config, id)) {
+ config.config[moduleName] = config.config[id]
+ }
+
+ try {
+ req.exec(text)
+ } catch (e) {
+ return onError(makeError('fromtexteval', 'fromText eval for ' + id + ' failed: ' + e, e, [id]))
+ }
+
+ if (hasInteractive) {
+ useInteractive = true
+ }
+
+ //Mark this as a dependency for the plugin
+ //resource
+ this.depMaps.push(moduleMap)
+
+ //Support anonymous modules.
+ context.completeLoad(moduleName)
+
+ //Bind the value of that module to the value for this
+ //resource ID.
+ localRequire([moduleName], load)
+ })
+
+ //Use parentName here since the plugin's name is not reliable,
+ //could be some weird string with no path that actually wants to
+ //reference the parentName's path.
+ plugin.load(map.name, localRequire, load, config)
+ })
+ )
+
+ context.enable(pluginMap, this)
+ this.pluginMaps[pluginMap.id] = pluginMap
+ },
+
+ enable: function () {
+ enabledRegistry[this.map.id] = this
+ this.enabled = true
+
+ //Set flag mentioning that the module is enabling,
+ //so that immediate calls to the defined callbacks
+ //for dependencies do not trigger inadvertent load
+ //with the depCount still being zero.
+ this.enabling = true
+
+ //Enable each dependency
+ each(
+ this.depMaps,
+ bind(this, function (depMap, i) {
+ var id, mod, handler
+
+ if (typeof depMap === 'string') {
+ //Dependency needs to be converted to a depMap
+ //and wired up to this module.
+ depMap = makeModuleMap(depMap, this.map.isDefine ? this.map : this.map.parentMap, false, !this.skipMap)
+ this.depMaps[i] = depMap
+
+ handler = getOwn(handlers, depMap.id)
+
+ if (handler) {
+ this.depExports[i] = handler(this)
+ return
+ }
+
+ this.depCount += 1
+
+ on(
+ depMap,
+ 'defined',
+ bind(this, function (depExports) {
+ this.defineDep(i, depExports)
+ this.check()
+ })
+ )
+
+ if (this.errback) {
+ on(depMap, 'error', bind(this, this.errback))
+ } else if (this.events.error) {
+ // No direct errback on this module, but something
+ // else is listening for errors, so be sure to
+ // propagate the error correctly.
+ on(
+ depMap,
+ 'error',
+ bind(this, function (err) {
+ this.emit('error', err)
+ })
+ )
+ }
+ }
+
+ id = depMap.id
+ mod = registry[id]
+
+ //Skip special modules like 'require', 'exports', 'module'
+ //Also, don't call enable if it is already enabled,
+ //important in circular dependency cases.
+ if (!hasProp(handlers, id) && mod && !mod.enabled) {
+ context.enable(depMap, this)
+ }
+ })
+ )
+
+ //Enable each plugin that is used in
+ //a dependency
+ eachProp(
+ this.pluginMaps,
+ bind(this, function (pluginMap) {
+ var mod = getOwn(registry, pluginMap.id)
+ if (mod && !mod.enabled) {
+ context.enable(pluginMap, this)
+ }
+ })
+ )
+
+ this.enabling = false
+
+ this.check()
+ },
+
+ on: function (name, cb) {
+ var cbs = this.events[name]
+ if (!cbs) {
+ cbs = this.events[name] = []
+ }
+ cbs.push(cb)
+ },
+
+ emit: function (name, evt) {
+ each(this.events[name], function (cb) {
+ cb(evt)
+ })
+ if (name === 'error') {
+ //Now that the error handler was triggered, remove
+ //the listeners, since this broken Module instance
+ //can stay around for a while in the registry.
+ delete this.events[name]
+ }
+ },
+ }
+
+ function callGetModule(args) {
+ //Skip modules already defined.
+ if (!hasProp(defined, args[0])) {
+ getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2])
+ }
+ }
+
+ function removeListener(node, func, name, ieName) {
+ //Favor detachEvent because of IE9
+ //issue, see attachEvent/addEventListener comment elsewhere
+ //in this file.
+ if (node.detachEvent && !isOpera) {
+ //Probably IE. If not it will throw an error, which will be
+ //useful to know.
+ if (ieName) {
+ node.detachEvent(ieName, func)
+ }
+ } else {
+ node.removeEventListener(name, func, false)
+ }
+ }
+
+ /**
+ * Given an event from a script node, get the requirejs info from it,
+ * and then removes the event listeners on the node.
+ * @param {Event} evt
+ * @returns {Object}
+ */
+ function getScriptData(evt) {
+ //Using currentTarget instead of target for Firefox 2.0's sake. Not
+ //all old browsers will be supported, but this one was easy enough
+ //to support and still makes sense.
+ var node = evt.currentTarget || evt.srcElement
+
+ //Remove the listeners once here.
+ removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange')
+ removeListener(node, context.onScriptError, 'error')
+
+ return {
+ node: node,
+ id: node && node.getAttribute('data-requiremodule'),
+ }
+ }
+
+ function intakeDefines() {
+ var args
+
+ //Any defined modules in the global queue, intake them now.
+ takeGlobalQueue()
+
+ //Make sure any remaining defQueue items get properly processed.
+ while (defQueue.length) {
+ args = defQueue.shift()
+ if (args[0] === null) {
+ return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]))
+ } else {
+ //args are id, deps, factory. Should be normalized by the
+ //define() function.
+ callGetModule(args)
+ }
+ }
+ }
+
+ context = {
+ config: config,
+ contextName: contextName,
+ registry: registry,
+ defined: defined,
+ urlFetched: urlFetched,
+ defQueue: defQueue,
+ Module: Module,
+ makeModuleMap: makeModuleMap,
+ nextTick: req.nextTick,
+ onError: onError,
+
+ /**
+ * Set a configuration for the context.
+ * @param {Object} cfg config object to integrate.
+ */
+ configure: function (cfg) {
+ //Make sure the baseUrl ends in a slash.
+ if (cfg.baseUrl) {
+ if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
+ cfg.baseUrl += '/'
+ }
+ }
+
+ //Save off the paths since they require special processing,
+ //they are additive.
+ var shim = config.shim,
+ objs = {
+ paths: true,
+ bundles: true,
+ config: true,
+ map: true,
+ }
+
+ eachProp(cfg, function (value, prop) {
+ if (objs[prop]) {
+ if (!config[prop]) {
+ config[prop] = {}
+ }
+ mixin(config[prop], value, true, true)
+ } else {
+ config[prop] = value
+ }
+ })
+
+ //Reverse map the bundles
+ if (cfg.bundles) {
+ eachProp(cfg.bundles, function (value, prop) {
+ each(value, function (v) {
+ if (v !== prop) {
+ bundlesMap[v] = prop
+ }
+ })
+ })
+ }
+
+ //Merge shim
+ if (cfg.shim) {
+ eachProp(cfg.shim, function (value, id) {
+ //Normalize the structure
+ if (isArray(value)) {
+ value = {
+ deps: value,
+ }
+ }
+ if ((value.exports || value.init) && !value.exportsFn) {
+ value.exportsFn = context.makeShimExports(value)
+ }
+ shim[id] = value
+ })
+ config.shim = shim
+ }
+
+ //Adjust packages if necessary.
+ if (cfg.packages) {
+ each(cfg.packages, function (pkgObj) {
+ var location, name
+
+ pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj
+
+ name = pkgObj.name
+ location = pkgObj.location
+ if (location) {
+ config.paths[name] = pkgObj.location
+ }
+
+ //Save pointer to main module ID for pkg name.
+ //Remove leading dot in main, so main paths are normalized,
+ //and remove any trailing .js, since different package
+ //envs have different conventions: some use a module name,
+ //some use a file name.
+ config.pkgs[name] =
+ pkgObj.name + '/' + (pkgObj.main || 'main').replace(currDirRegExp, '').replace(jsSuffixRegExp, '')
+ })
+ }
+
+ //If there are any "waiting to execute" modules in the registry,
+ //update the maps for them, since their info, like URLs to load,
+ //may have changed.
+ eachProp(registry, function (mod, id) {
+ //If module already has init called, since it is too
+ //late to modify them, and ignore unnormalized ones
+ //since they are transient.
+ if (!mod.inited && !mod.map.unnormalized) {
+ mod.map = makeModuleMap(id)
+ }
+ })
+
+ //If a deps array or a config callback is specified, then call
+ //require with those args. This is useful when require is defined as a
+ //config object before require.js is loaded.
+ if (cfg.deps || cfg.callback) {
+ context.require(cfg.deps || [], cfg.callback)
+ }
+ },
+
+ makeShimExports: function (value) {
+ function fn() {
+ var ret
+ if (value.init) {
+ ret = value.init.apply(global, arguments)
+ }
+ return ret || (value.exports && getGlobal(value.exports))
+ }
+ return fn
+ },
+
+ makeRequire: function (relMap, options) {
+ options = options || {}
+
+ function localRequire(deps, callback, errback) {
+ var id, map, requireMod
+
+ if (options.enableBuildCallback && callback && isFunction(callback)) {
+ callback.__requireJsBuild = true
+ }
+
+ if (typeof deps === 'string') {
+ if (isFunction(callback)) {
+ //Invalid call
+ return onError(makeError('requireargs', 'Invalid require call'), errback)
+ }
+
+ //If require|exports|module are requested, get the
+ //value for them from the special handlers. Caveat:
+ //this only works while module is being defined.
+ if (relMap && hasProp(handlers, deps)) {
+ return handlers[deps](registry[relMap.id])
+ }
+
+ //Synchronous access to one module. If require.get is
+ //available (as in the Node adapter), prefer that.
+ if (req.get) {
+ return req.get(context, deps, relMap, localRequire)
+ }
+
+ //Normalize module name, if it contains . or ..
+ map = makeModuleMap(deps, relMap, false, true)
+ id = map.id
+
+ if (!hasProp(defined, id)) {
+ return onError(
+ makeError(
+ 'notloaded',
+ 'Module name "' +
+ id +
+ '" has not been loaded yet for context: ' +
+ contextName +
+ (relMap ? '' : '. Use require([])')
+ )
+ )
+ }
+ return defined[id]
+ }
+
+ //Grab defines waiting in the global queue.
+ intakeDefines()
+
+ //Mark all the dependencies as needing to be loaded.
+ context.nextTick(function () {
+ //Some defines could have been added since the
+ //require call, collect them.
+ intakeDefines()
+
+ requireMod = getModule(makeModuleMap(null, relMap))
+
+ //Store if map config should be applied to this require
+ //call for dependencies.
+ requireMod.skipMap = options.skipMap
+
+ requireMod.init(deps, callback, errback, {
+ enabled: true,
+ })
+
+ checkLoaded()
+ })
+
+ return localRequire
+ }
+
+ mixin(localRequire, {
+ isBrowser: isBrowser,
+
+ /**
+ * Converts a module name + .extension into an URL path.
+ * *Requires* the use of a module name. It does not support using
+ * plain URLs like nameToUrl.
+ */
+ toUrl: function (moduleNamePlusExt) {
+ var ext,
+ index = moduleNamePlusExt.lastIndexOf('.'),
+ segment = moduleNamePlusExt.split('/')[0],
+ isRelative = segment === '.' || segment === '..'
+
+ //Have a file extension alias, and it is not the
+ //dots from a relative path.
+ if (index !== -1 && (!isRelative || index > 1)) {
+ ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length)
+ moduleNamePlusExt = moduleNamePlusExt.substring(0, index)
+ }
+
+ return context.nameToUrl(normalize(moduleNamePlusExt, relMap && relMap.id, true), ext, true)
+ },
+
+ defined: function (id) {
+ return hasProp(defined, makeModuleMap(id, relMap, false, true).id)
+ },
+
+ specified: function (id) {
+ id = makeModuleMap(id, relMap, false, true).id
+ return hasProp(defined, id) || hasProp(registry, id)
+ },
+ })
+
+ //Only allow undef on top level require calls
+ if (!relMap) {
+ localRequire.undef = function (id) {
+ //Bind any waiting define() calls to this context,
+ //fix for #408
+ takeGlobalQueue()
+
+ var map = makeModuleMap(id, relMap, true),
+ mod = getOwn(registry, id)
+
+ removeScript(id)
+
+ delete defined[id]
+ delete urlFetched[map.url]
+ delete undefEvents[id]
+
+ //Clean queued defines too. Go backwards
+ //in array so that the splices do not
+ //mess up the iteration.
+ eachReverse(defQueue, function (args, i) {
+ if (args[0] === id) {
+ defQueue.splice(i, 1)
+ }
+ })
+
+ if (mod) {
+ //Hold on to listeners in case the
+ //module will be attempted to be reloaded
+ //using a different config.
+ if (mod.events.defined) {
+ undefEvents[id] = mod.events
+ }
+
+ cleanRegistry(id)
+ }
+ }
+ }
+
+ return localRequire
+ },
+
+ /**
+ * Called to enable a module if it is still in the registry
+ * awaiting enablement. A second arg, parent, the parent module,
+ * is passed in for context, when this method is overridden by
+ * the optimizer. Not shown here to keep code compact.
+ */
+ enable: function (depMap) {
+ var mod = getOwn(registry, depMap.id)
+ if (mod) {
+ getModule(depMap).enable()
+ }
+ },
+
+ /**
+ * Internal method used by environment adapters to complete a load event.
+ * A load event could be a script load or just a load pass from a synchronous
+ * load call.
+ * @param {String} moduleName the name of the module to potentially complete.
+ */
+ completeLoad: function (moduleName) {
+ var found,
+ args,
+ mod,
+ shim = getOwn(config.shim, moduleName) || {},
+ shExports = shim.exports
+
+ takeGlobalQueue()
+
+ while (defQueue.length) {
+ args = defQueue.shift()
+ if (args[0] === null) {
+ args[0] = moduleName
+ //If already found an anonymous module and bound it
+ //to this name, then this is some other anon module
+ //waiting for its completeLoad to fire.
+ if (found) {
+ break
+ }
+ found = true
+ } else if (args[0] === moduleName) {
+ //Found matching define call for this script!
+ found = true
+ }
+
+ callGetModule(args)
+ }
+
+ //Do this after the cycle of callGetModule in case the result
+ //of those calls/init calls changes the registry.
+ mod = getOwn(registry, moduleName)
+
+ if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
+ if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
+ if (hasPathFallback(moduleName)) {
+ return
+ } else {
+ return onError(makeError('nodefine', 'No define call for ' + moduleName, null, [moduleName]))
+ }
+ } else {
+ //A script that does not call define(), so just simulate
+ //the call for it.
+ callGetModule([moduleName, shim.deps || [], shim.exportsFn])
+ }
+ }
+
+ checkLoaded()
+ },
+
+ /**
+ * Converts a module name to a file path. Supports cases where
+ * moduleName may actually be just an URL.
+ * Note that it **does not** call normalize on the moduleName,
+ * it is assumed to have already been normalized. This is an
+ * internal API, not a public one. Use toUrl for the public API.
+ */
+ nameToUrl: function (moduleName, ext, skipExt) {
+ var paths,
+ syms,
+ i,
+ parentModule,
+ url,
+ parentPath,
+ bundleId,
+ pkgMain = getOwn(config.pkgs, moduleName)
+
+ if (pkgMain) {
+ moduleName = pkgMain
+ }
+
+ bundleId = getOwn(bundlesMap, moduleName)
+
+ if (bundleId) {
+ return context.nameToUrl(bundleId, ext, skipExt)
+ }
+
+ //If a colon is in the URL, it indicates a protocol is used and it is just
+ //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
+ //or ends with .js, then assume the user meant to use an url and not a module id.
+ //The slash is important for protocol-less URLs as well as full paths.
+ if (req.jsExtRegExp.test(moduleName)) {
+ //Just a plain path, not module name lookup, so just return it.
+ //Add extension if it is included. This is a bit wonky, only non-.js things pass
+ //an extension, this method probably needs to be reworked.
+ url = moduleName + (ext || '')
+ } else {
+ //A module that needs to be converted to a path.
+ paths = config.paths
+
+ syms = moduleName.split('/')
+ //For each module name segment, see if there is a path
+ //registered for it. Start with most specific name
+ //and work up from it.
+ for (i = syms.length; i > 0; i -= 1) {
+ parentModule = syms.slice(0, i).join('/')
+
+ parentPath = getOwn(paths, parentModule)
+ if (parentPath) {
+ //If an array, it means there are a few choices,
+ //Choose the one that is desired
+ if (isArray(parentPath)) {
+ parentPath = parentPath[0]
+ }
+ syms.splice(0, i, parentPath)
+ break
+ }
+ }
+
+ //Join the path parts together, then figure out if baseUrl is needed.
+ url = syms.join('/')
+ url += ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js')
+ url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url
+ }
+
+ return config.urlArgs ? url + ((url.indexOf('?') === -1 ? '?' : '&') + config.urlArgs) : url
+ },
+
+ //Delegates to req.load. Broken out as a separate function to
+ //allow overriding in the optimizer.
+ load: function (id, url) {
+ req.load(context, id, url)
+ },
+
+ /**
+ * Executes a module callback function. Broken out as a separate function
+ * solely to allow the build system to sequence the files in the built
+ * layer in the right sequence.
+ *
+ * @private
+ */
+ execCb: function (name, callback, args, exports) {
+ return callback.apply(exports, args)
+ },
+
+ /**
+ * callback for script loads, used to check status of loading.
+ *
+ * @param {Event} evt the event from the browser for the script
+ * that was loaded.
+ */
+ onScriptLoad: function (evt) {
+ //Using currentTarget instead of target for Firefox 2.0's sake. Not
+ //all old browsers will be supported, but this one was easy enough
+ //to support and still makes sense.
+ if (evt.type === 'load' || readyRegExp.test((evt.currentTarget || evt.srcElement).readyState)) {
+ //Reset interactive script so a script node is not held onto for
+ //to long.
+ interactiveScript = null
+
+ //Pull out the name of the module and the context.
+ var data = getScriptData(evt)
+ context.completeLoad(data.id)
+ }
+ },
+
+ /**
+ * Callback for script errors.
+ */
+ onScriptError: function (evt) {
+ var data = getScriptData(evt)
+ if (!hasPathFallback(data.id)) {
+ return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id]))
+ }
+ },
+ }
+
+ context.require = context.makeRequire()
+ return context
+ }
+
+ /**
+ * Main entry point.
+ *
+ * If the only argument to require is a string, then the module that
+ * is represented by that string is fetched for the appropriate context.
+ *
+ * If the first argument is an array, then it will be treated as an array
+ * of dependency string names to fetch. An optional function callback can
+ * be specified to execute when all of those dependencies are available.
+ *
+ * Make a local req variable to help Caja compliance (it assumes things
+ * on a require that are not standardized), and to give a short
+ * name for minification/local scope use.
+ */
+ req = requirejs = function (deps, callback, errback, optional) {
+ //Find the right context, use default
+ var context,
+ config,
+ contextName = defContextName
+
+ // Determine if have config object in the call.
+ if (!isArray(deps) && typeof deps !== 'string') {
+ // deps is a config object
+ config = deps
+ if (isArray(callback)) {
+ // Adjust args if there are dependencies
+ deps = callback
+ callback = errback
+ errback = optional
+ } else {
+ deps = []
+ }
+ }
+
+ if (config && config.context) {
+ contextName = config.context
+ }
+
+ context = getOwn(contexts, contextName)
+ if (!context) {
+ context = contexts[contextName] = req.s.newContext(contextName)
+ }
+
+ if (config) {
+ context.configure(config)
+ }
+
+ return context.require(deps, callback, errback)
+ }
+
+ /**
+ * Support require.config() to make it easier to cooperate with other
+ * AMD loaders on globally agreed names.
+ */
+ req.config = function (config) {
+ return req(config)
+ }
+
+ /**
+ * Execute something after the current tick
+ * of the event loop. Override for other envs
+ * that have a better solution than setTimeout.
+ * @param {Function} fn function to execute later.
+ */
+ req.nextTick =
+ typeof setTimeout !== 'undefined'
+ ? function (fn) {
+ setTimeout(fn, 4)
+ }
+ : function (fn) {
+ fn()
+ }
+
+ /**
+ * Export require as a global, but only if it does not already exist.
+ */
+ if (!require) {
+ require = req
+ }
+
+ req.version = version
+
+ //Used to filter out dependencies that are already paths.
+ req.jsExtRegExp = /^\/|:|\?|\.js$/
+ req.isBrowser = isBrowser
+ s = req.s = {
+ contexts: contexts,
+ newContext: newContext,
+ }
+
+ //Create default context.
+ req({})
+
+ //Exports some context-sensitive methods on global require.
+ each(['toUrl', 'undef', 'defined', 'specified'], function (prop) {
+ //Reference from contexts instead of early binding to default context,
+ //so that during builds, the latest instance of the default context
+ //with its config gets used.
+ req[prop] = function () {
+ var ctx = contexts[defContextName]
+ return ctx.require[prop].apply(ctx, arguments)
+ }
+ })
+
+ if (isBrowser) {
+ head = s.head = document.getElementsByTagName('head')[0]
+ //If BASE tag is in play, using appendChild is a problem for IE6.
+ //When that browser dies, this can be removed. Details in this jQuery bug:
+ //http://dev.jquery.com/ticket/2709
+ baseElement = document.getElementsByTagName('base')[0]
+ if (baseElement) {
+ head = s.head = baseElement.parentNode
+ }
+ }
+
+ /**
+ * Any errors that require explicitly generates will be passed to this
+ * function. Intercept/override it if you want custom error handling.
+ * @param {Error} err the error object.
+ */
+ req.onError = defaultOnError
+
+ /**
+ * Creates the node for the load command. Only used in browser envs.
+ */
+ req.createNode = function (config, moduleName, url) {
+ var node = config.xhtml
+ ? document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script')
+ : document.createElement('script')
+ node.type = config.scriptType || 'text/javascript'
+ node.charset = 'utf-8'
+ node.async = true
+ return node
+ }
+
+ /**
+ * Does the request to load a module for the browser case.
+ * Make this a separate function to allow other environments
+ * to override it.
+ *
+ * @param {Object} context the require context to find state.
+ * @param {String} moduleName the name of the module.
+ * @param {Object} url the URL to the module.
+ */
+ req.load = function (context, moduleName, url) {
+ var config = (context && context.config) || {},
+ node
+ if (isBrowser) {
+ //In the browser so use a script tag
+ node = req.createNode(config, moduleName, url)
+
+ node.setAttribute('data-requirecontext', context.contextName)
+ node.setAttribute('data-requiremodule', moduleName)
+
+ //Set up load listener. Test attachEvent first because IE9 has
+ //a subtle issue in its addEventListener and script onload firings
+ //that do not match the behavior of all other browsers with
+ //addEventListener support, which fire the onload event for a
+ //script right after the script execution. See:
+ //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
+ //UNFORTUNATELY Opera implements attachEvent but does not follow the script
+ //script execution mode.
+ if (
+ node.attachEvent &&
+ //Check if node.attachEvent is artificially added by custom script or
+ //natively supported by browser
+ //read https://github.com/jrburke/requirejs/issues/187
+ //if we can NOT find [native code] then it must NOT natively supported.
+ //in IE8, node.attachEvent does not have toString()
+ //Note the test for "[native code" with no closing brace, see:
+ //https://github.com/jrburke/requirejs/issues/273
+ !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
+ !isOpera
+ ) {
+ //Probably IE. IE (at least 6-8) do not fire
+ //script onload right after executing the script, so
+ //we cannot tie the anonymous define call to a name.
+ //However, IE reports the script as being in 'interactive'
+ //readyState at the time of the define call.
+ useInteractive = true
+
+ node.attachEvent('onreadystatechange', context.onScriptLoad)
+ //It would be great to add an error handler here to catch
+ //404s in IE9+. However, onreadystatechange will fire before
+ //the error handler, so that does not help. If addEventListener
+ //is used, then IE will fire error before load, but we cannot
+ //use that pathway given the connect.microsoft.com issue
+ //mentioned above about not doing the 'script execute,
+ //then fire the script load event listener before execute
+ //next script' that other browsers do.
+ //Best hope: IE10 fixes the issues,
+ //and then destroys all installs of IE 6-9.
+ //node.attachEvent('onerror', context.onScriptError);
+ } else {
+ node.addEventListener('load', context.onScriptLoad, false)
+ node.addEventListener('error', context.onScriptError, false)
+ }
+ node.src = url
+
+ //For some cache cases in IE 6-8, the script executes before the end
+ //of the appendChild execution, so to tie an anonymous define
+ //call to the module name (which is stored on the node), hold on
+ //to a reference to this node, but clear after the DOM insertion.
+ currentlyAddingScript = node
+ if (baseElement) {
+ head.insertbeforeAll(node, baseElement)
+ } else {
+ head.appendChild(node)
+ }
+ currentlyAddingScript = null
+
+ return node
+ } else if (isWebWorker) {
+ try {
+ //In a web worker, use importScripts. This is not a very
+ //efficient use of importScripts, importScripts will block until
+ //its script is downloaded and evaluated. However, if web workers
+ //are in play, the expectation that a build has been done so that
+ //only one script needs to be loaded anyway. This may need to be
+ //reevaluated if other use cases become common.
+ importScripts(url)
+
+ //Account for anonymous modules
+ context.completeLoad(moduleName)
+ } catch (e) {
+ context.onError(
+ makeError('importscripts', 'importScripts failed for ' + moduleName + ' at ' + url, e, [moduleName])
+ )
+ }
+ }
+ }
+
+ function getInteractiveScript() {
+ if (interactiveScript && interactiveScript.readyState === 'interactive') {
+ return interactiveScript
+ }
+
+ eachReverse(scripts(), function (script) {
+ if (script.readyState === 'interactive') {
+ return (interactiveScript = script)
+ }
+ })
+ return interactiveScript
+ }
+
+ //Look for a data-main script attribute, which could also adjust the baseUrl.
+ if (isBrowser && !cfg.skipDataMain) {
+ //Figure out baseUrl. Get it from the script tag with require.js in it.
+ eachReverse(scripts(), function (script) {
+ //Set the 'head' where we can append children by
+ //using the script's parent.
+ if (!head) {
+ head = script.parentNode
+ }
+
+ //Look for a data-main attribute to set main script for the page
+ //to load. If it is there, the path to data main becomes the
+ //baseUrl, if it is not already set.
+ dataMain = script.getAttribute('data-main')
+ if (dataMain) {
+ //Preserve dataMain in case it is a path (i.e. contains '?')
+ mainScript = dataMain
+
+ //Set final baseUrl if there is not already an explicit one.
+ if (!cfg.baseUrl) {
+ //Pull off the directory of data-main for use as the
+ //baseUrl.
+ src = mainScript.split('/')
+ mainScript = src.pop()
+ subPath = src.length ? src.join('/') + '/' : './'
+
+ cfg.baseUrl = subPath
+ }
+
+ //Strip off any trailing .js since mainScript is now
+ //like a module name.
+ mainScript = mainScript.replace(jsSuffixRegExp, '')
+
+ //If mainScript is still a path, fall back to dataMain
+ if (req.jsExtRegExp.test(mainScript)) {
+ mainScript = dataMain
+ }
+
+ //Put the data-main script in the files to load.
+ cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript]
+
+ return true
+ }
+ })
+ }
+
+ /**
+ * The function that handles definitions of modules. Differs from
+ * require() in that a string for the module should be the first argument,
+ * and the function to execute after dependencies are loaded should
+ * return a value to define the module corresponding to the first argument's
+ * name.
+ */
+ define = function (name, deps, callback) {
+ var node, context
+
+ //Allow for anonymous modules
+ if (typeof name !== 'string') {
+ //Adjust args appropriately
+ callback = deps
+ deps = name
+ name = null
+ }
+
+ //This module may not have dependencies
+ if (!isArray(deps)) {
+ callback = deps
+ deps = null
+ }
+
+ //If no name, and callback is a function, then figure out if it a
+ //CommonJS thing with dependencies.
+ if (!deps && isFunction(callback)) {
+ deps = []
+ //Remove comments from the callback string,
+ //look for require calls, and pull them into the dependencies,
+ //but only if there are function args.
+ if (callback.length) {
+ callback
+ .toString()
+ .replace(commentRegExp, '')
+ .replace(cjsRequireRegExp, function (match, dep) {
+ deps.push(dep)
+ })
+
+ //May be a CommonJS thing even without require calls, but still
+ //could use exports, and module. Avoid doing exports and module
+ //work though if it just needs require.
+ //REQUIRES the function to expect the CommonJS variables in the
+ //order listed below.
+ deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps)
+ }
+ }
+
+ //If in IE 6-8 and hit an anonymous define() call, do the interactive
+ //work.
+ if (useInteractive) {
+ node = currentlyAddingScript || getInteractiveScript()
+ if (node) {
+ if (!name) {
+ name = node.getAttribute('data-requiremodule')
+ }
+ context = contexts[node.getAttribute('data-requirecontext')]
+ }
+ }
+
+ //Always save off evaluating the def call until the script onload handler.
+ //This allows multiple modules to be in a file without prematurely
+ //tracing dependencies, and allows for anonymous module support,
+ //where the module name is not known until the script onload event
+ //occurs. If no context, use the global queue, and get it processed
+ //in the onscript load callback.
+ ;(context ? context.defQueue : globalDefQueue).push([name, deps, callback])
+ }
+
+ define.amd = {
+ jQuery: true,
+ }
+
+ /**
+ * Executes the text. Normally just uses eval, but can be modified
+ * to use a better, environment-specific call. Only used for transpiling
+ * loader plugins, not for plain JS modules.
+ * @param {String} text the text to execute/evaluate.
+ */
+ req.exec = function (text) {
+ /*jslint evil: true */
+ return eval(text)
+ }
+
+ //Set up with config info.
+ req(cfg)
+})(this)
diff --git a/test/usage/rey.jpeg b/__test__/usage/rey.jpeg
similarity index 100%
rename from test/usage/rey.jpeg
rename to __test__/usage/rey.jpeg
diff --git a/test/usage/style.css b/__test__/usage/style.css
similarity index 100%
rename from test/usage/style.css
rename to __test__/usage/style.css
diff --git a/__test__/utils.classes.test.js b/__test__/utils.classes.test.js
new file mode 100644
index 00000000..e2ad006f
--- /dev/null
+++ b/__test__/utils.classes.test.js
@@ -0,0 +1,45 @@
+const classes = require('../src/utils/classes')
+
+describe('Classes', function () {
+ var el
+
+ beforeEach(function () {
+ el = document.createElement('div')
+ document.body.appendChild(el)
+ })
+
+ afterEach(function () {
+ document.body.removeChild(el)
+ })
+
+ it('should add', function () {
+ classes(el).add('show')
+ expect(el.getAttribute('class')).toBe('show')
+ })
+ it('should remove', function () {
+ el.setAttribute('class', 'show')
+ expect(el.getAttribute('class')).toBe('show')
+ classes(el).remove('show')
+ expect(el.getAttribute('class')).toBe('')
+ })
+ it('should toggle', function () {
+ classes(el).toggle('show')
+ expect(el.getAttribute('class')).toBe('show')
+ classes(el).toggle('show')
+ expect(el.getAttribute('class')).toBe('')
+ })
+ it('should array', function () {
+ el.setAttribute('class', 'foo bar')
+ expect(classes(el).array()).toEqual(['foo', 'bar'])
+ })
+ it('should has', function () {
+ expect(classes(el).has('show')).toBe(false)
+ el.setAttribute('class', 'show')
+ expect(classes(el).has('show')).toBe(true)
+ })
+ it('should contains', function () {
+ expect(classes(el).contains('show')).toBe(false)
+ el.setAttribute('class', 'show')
+ expect(classes(el).contains('show')).toBe(true)
+ })
+})
diff --git a/__test__/utils.get-by-class.test.js b/__test__/utils.get-by-class.test.js
new file mode 100644
index 00000000..b524b544
--- /dev/null
+++ b/__test__/utils.get-by-class.test.js
@@ -0,0 +1,25 @@
+const getByClass = require('../src/utils/get-by-class')
+
+describe('GetByClass', function () {
+ var el
+
+ beforeEach(function () {
+ el = document.createElement('div')
+ el.setAttribute('class', 'foo')
+ document.body.appendChild(el)
+ })
+
+ afterEach(function () {
+ document.body.removeChild(el)
+ })
+
+ it('should use getElementsByClassName', function () {
+ expect(getByClass(document.body, 'foo', false, { test: true, getElementsByClassName: true }).length).toBe(1)
+ })
+ it('should use getElementsByClassName', function () {
+ expect(getByClass(document.body, 'foo', false, { test: true, querySelector: true }).length).toBe(1)
+ })
+ it('should toggle', function () {
+ expect(getByClass(document.body, 'foo', false, { test: true, polyfill: true }).length).toBe(1)
+ })
+})
diff --git a/bower.json b/bower.json
index 8794778d..aea09c3c 100644
--- a/bower.json
+++ b/bower.json
@@ -1,11 +1,11 @@
{
"name": "list.js",
"main": "dist/list.js",
- "homepage": "http://listjs.com",
+ "homepage": "https://listjs.com",
"authors": [
"Jonny Strömberg "
],
- "description": "The perfect library for adding search, sort, filters and flexibility to tables, lists and various HTML elements. Built to be invisible and work on existing HTML",
+ "description": "The perfect library for lists. Supports search, sort, filters and flexibility. Built to be invisible and work on existing HTML",
"keywords": [
"list",
"search",
@@ -19,9 +19,7 @@
"ignore": [
"**/.*",
"node_modules",
- "bower_components",
- "components",
- "test",
- "tests"
+ "__test__",
+ "docs"
]
}
diff --git a/dist/list.js b/dist/list.js
index 38ddeca4..640deceb 100644
--- a/dist/list.js
+++ b/dist/list.js
@@ -1,46 +1,203 @@
-(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0) {
+ setTimeout(function () {
+ addAsync(values, callback, items);
+ }, 1);
+ } else {
+ list.update();
+ callback(items);
+ }
+ };
+
+ return addAsync;
+};
+
+/***/ }),
+
+/***/ "./src/filter.js":
+/*!***********************!*\
+ !*** ./src/filter.js ***!
+ \***********************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: module */
+/*! CommonJS bailout: module.exports is used directly at 1:0-14 */
+/***/ (function(module) {
+
+module.exports = function (list) {
+ // Add handlers
+ list.handlers.filterStart = list.handlers.filterStart || [];
+ list.handlers.filterComplete = list.handlers.filterComplete || [];
+ return function (filterFunction) {
+ list.trigger('filterStart');
+ list.i = 1; // Reset paging
+
+ list.reset.filter();
+
+ if (filterFunction === undefined) {
+ list.filtered = false;
+ } else {
+ list.filtered = true;
+ var is = list.items;
+
+ for (var i = 0, il = is.length; i < il; i++) {
+ var item = is[i];
+
+ if (filterFunction(item)) {
+ item.filtered = true;
+ } else {
+ item.filtered = false;
+ }
+ }
+ }
+
+ list.update();
+ list.trigger('filterComplete');
+ return list.visibleItems;
+ };
+};
+
+/***/ }),
+
+/***/ "./src/fuzzy-search.js":
+/*!*****************************!*\
+ !*** ./src/fuzzy-search.js ***!
+ \*****************************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: module, __webpack_require__ */
+/*! CommonJS bailout: module.exports is used directly at 8:0-14 */
+/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
+
+var classes = __webpack_require__(/*! ./utils/classes */ "./src/utils/classes.js"),
+ events = __webpack_require__(/*! ./utils/events */ "./src/utils/events.js"),
+ extend = __webpack_require__(/*! ./utils/extend */ "./src/utils/extend.js"),
+ toString = __webpack_require__(/*! ./utils/to-string */ "./src/utils/to-string.js"),
+ getByClass = __webpack_require__(/*! ./utils/get-by-class */ "./src/utils/get-by-class.js"),
+ fuzzy = __webpack_require__(/*! ./utils/fuzzy */ "./src/utils/fuzzy.js");
+
+module.exports = function (list, options) {
+ options = options || {};
+ options = extend({
+ location: 0,
+ distance: 100,
+ threshold: 0.4,
+ multiSearch: true,
+ searchClass: 'fuzzy-search'
+ }, options);
+ var fuzzySearch = {
+ search: function search(searchString, columns) {
+ // Substract arguments from the searchString or put searchString as only argument
+ var searchArguments = options.multiSearch ? searchString.replace(/ +$/, '').split(/ +/) : [searchString];
+
+ for (var k = 0, kl = list.items.length; k < kl; k++) {
+ fuzzySearch.item(list.items[k], columns, searchArguments);
+ }
+ },
+ item: function item(_item, columns, searchArguments) {
+ var found = true;
+
+ for (var i = 0; i < searchArguments.length; i++) {
+ var foundArgument = false;
+
+ for (var j = 0, jl = columns.length; j < jl; j++) {
+ if (fuzzySearch.values(_item.values(), columns[j], searchArguments[i])) {
+ foundArgument = true;
+ }
+ }
+
+ if (!foundArgument) {
+ found = false;
+ }
+ }
+
+ _item.found = found;
+ },
+ values: function values(_values, value, searchArgument) {
+ if (_values.hasOwnProperty(value)) {
+ var text = toString(_values[value]).toLowerCase();
-var document = window.document,
- getByClass = require('./src/utils/get-by-class'),
- extend = require('./src/utils/extend'),
- indexOf = require('./src/utils/index-of'),
- events = require('./src/utils/events'),
- toString = require('./src/utils/to-string'),
- naturalSort = require('./src/utils/natural-sort'),
- classes = require('./src/utils/classes'),
- getAttribute = require('./src/utils/get-attribute'),
- toArray = require('./src/utils/to-array');
+ if (fuzzy(text, searchArgument, options)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+ };
+ events.bind(getByClass(list.listContainer, options.searchClass), 'keyup', list.utils.events.debounce(function (e) {
+ var target = e.target || e.srcElement; // IE have srcElement
-var List = function(id, options, values) {
+ list.search(target.value, fuzzySearch.search);
+ }, list.searchDelay));
+ return function (str, columns) {
+ list.search(str, columns, fuzzySearch.search);
+ };
+};
+/***/ }),
+
+/***/ "./src/index.js":
+/*!**********************!*\
+ !*** ./src/index.js ***!
+ \**********************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: module, __webpack_require__ */
+/*! CommonJS bailout: module.exports is used directly at 11:0-14 */
+/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
+
+var naturalSort = __webpack_require__(/*! string-natural-compare */ "./node_modules/string-natural-compare/natural-compare.js"),
+ getByClass = __webpack_require__(/*! ./utils/get-by-class */ "./src/utils/get-by-class.js"),
+ extend = __webpack_require__(/*! ./utils/extend */ "./src/utils/extend.js"),
+ indexOf = __webpack_require__(/*! ./utils/index-of */ "./src/utils/index-of.js"),
+ events = __webpack_require__(/*! ./utils/events */ "./src/utils/events.js"),
+ toString = __webpack_require__(/*! ./utils/to-string */ "./src/utils/to-string.js"),
+ classes = __webpack_require__(/*! ./utils/classes */ "./src/utils/classes.js"),
+ getAttribute = __webpack_require__(/*! ./utils/get-attribute */ "./src/utils/get-attribute.js"),
+ toArray = __webpack_require__(/*! ./utils/to-array */ "./src/utils/to-array.js");
+
+module.exports = function (id, options, values) {
var self = this,
- init,
- Item = require('./src/item')(self),
- addAsync = require('./src/add-async')(self);
+ init,
+ Item = __webpack_require__(/*! ./item */ "./src/item.js")(self),
+ addAsync = __webpack_require__(/*! ./add-async */ "./src/add-async.js")(self),
+ initPagination = __webpack_require__(/*! ./pagination */ "./src/pagination.js")(self);
init = {
- start: function() {
- self.listClass = "list";
- self.searchClass = "search";
- self.sortClass = "sort";
- self.page = 10000;
- self.i = 1;
- self.items = [];
- self.visibleItems = [];
- self.matchingItems = [];
- self.searched = false;
- self.filtered = false;
- self.searchColumns = undefined;
- self.handlers = { 'updated': [] };
- self.plugins = {};
- self.valueNames = [];
- self.utils = {
+ start: function start() {
+ self.listClass = 'list';
+ self.searchClass = 'search';
+ self.sortClass = 'sort';
+ self.page = 10000;
+ self.i = 1;
+ self.items = [];
+ self.visibleItems = [];
+ self.matchingItems = [];
+ self.searched = false;
+ self.filtered = false;
+ self.searchColumns = undefined;
+ self.searchDelay = 0;
+ self.handlers = {
+ updated: []
+ };
+ self.valueNames = [];
+ self.utils = {
getByClass: getByClass,
extend: extend,
indexOf: indexOf,
@@ -51,200 +208,234 @@ var List = function(id, options, values) {
getAttribute: getAttribute,
toArray: toArray
};
-
self.utils.extend(self, options);
+ self.listContainer = typeof id === 'string' ? document.getElementById(id) : id;
- self.listContainer = (typeof(id) === 'string') ? document.getElementById(id) : id;
- if (!self.listContainer) { return; }
- self.list = getByClass(self.listContainer, self.listClass, true);
-
- self.parse = require('./src/parse')(self);
- self.templater = require('./src/templater')(self);
- self.search = require('./src/search')(self);
- self.filter = require('./src/filter')(self);
- self.sort = require('./src/sort')(self);
+ if (!self.listContainer) {
+ return;
+ }
+ self.list = getByClass(self.listContainer, self.listClass, true);
+ self.parse = __webpack_require__(/*! ./parse */ "./src/parse.js")(self);
+ self.templater = __webpack_require__(/*! ./templater */ "./src/templater.js")(self);
+ self.search = __webpack_require__(/*! ./search */ "./src/search.js")(self);
+ self.filter = __webpack_require__(/*! ./filter */ "./src/filter.js")(self);
+ self.sort = __webpack_require__(/*! ./sort */ "./src/sort.js")(self);
+ self.fuzzySearch = __webpack_require__(/*! ./fuzzy-search */ "./src/fuzzy-search.js")(self, options.fuzzySearch);
this.handlers();
this.items();
+ this.pagination();
self.update();
- this.plugins();
},
- handlers: function() {
+ handlers: function handlers() {
for (var handler in self.handlers) {
- if (self[handler]) {
+ if (self[handler] && self.handlers.hasOwnProperty(handler)) {
self.on(handler, self[handler]);
}
}
},
- items: function() {
+ items: function items() {
self.parse(self.list);
+
if (values !== undefined) {
self.add(values);
}
},
- plugins: function() {
- for (var i = 0; i < self.plugins.length; i++) {
- var plugin = self.plugins[i];
- self[plugin.name] = plugin;
- plugin.init(self, List);
+ pagination: function pagination() {
+ if (options.pagination !== undefined) {
+ if (options.pagination === true) {
+ options.pagination = [{}];
+ }
+
+ if (options.pagination[0] === undefined) {
+ options.pagination = [options.pagination];
+ }
+
+ for (var i = 0, il = options.pagination.length; i < il; i++) {
+ initPagination(options.pagination[i]);
+ }
}
}
};
-
/*
- * Re-parse the List, use if html have changed
- */
- this.reIndex = function() {
- self.items = [];
- self.visibleItems = [];
- self.matchingItems = [];
- self.searched = false;
- self.filtered = false;
+ * Re-parse the List, use if html have changed
+ */
+
+ this.reIndex = function () {
+ self.items = [];
+ self.visibleItems = [];
+ self.matchingItems = [];
+ self.searched = false;
+ self.filtered = false;
self.parse(self.list);
};
- this.toJSON = function() {
+ this.toJSON = function () {
var json = [];
+
for (var i = 0, il = self.items.length; i < il; i++) {
json.push(self.items[i].values());
}
+
return json;
};
+ /*
+ * Add object to list
+ */
- /*
- * Add object to list
- */
- this.add = function(values, callback) {
+ this.add = function (values, callback) {
if (values.length === 0) {
return;
}
+
if (callback) {
- addAsync(values, callback);
+ addAsync(values.slice(0), callback);
return;
}
+
var added = [],
- notCreate = false;
- if (values[0] === undefined){
+ notCreate = false;
+
+ if (values[0] === undefined) {
values = [values];
}
+
for (var i = 0, il = values.length; i < il; i++) {
var item = null;
- notCreate = (self.items.length > self.page) ? true : false;
+ notCreate = self.items.length > self.page ? true : false;
item = new Item(values[i], undefined, notCreate);
self.items.push(item);
added.push(item);
}
+
self.update();
return added;
};
- this.show = function(i, page) {
- this.i = i;
- this.page = page;
- self.update();
+ this.show = function (i, page) {
+ this.i = i;
+ this.page = page;
+ self.update();
return self;
- };
-
+ };
/* Removes object from list.
- * Loops through the list and removes objects where
- * property "valuename" === value
- */
- this.remove = function(valueName, value, options) {
+ * Loops through the list and removes objects where
+ * property "valuename" === value
+ */
+
+
+ this.remove = function (valueName, value, options) {
var found = 0;
+
for (var i = 0, il = self.items.length; i < il; i++) {
if (self.items[i].values()[valueName] == value) {
self.templater.remove(self.items[i], options);
- self.items.splice(i,1);
+ self.items.splice(i, 1);
il--;
i--;
found++;
}
}
+
self.update();
return found;
};
-
/* Gets the objects in the list which
- * property "valueName" === value
- */
- this.get = function(valueName, value) {
+ * property "valueName" === value
+ */
+
+
+ this.get = function (valueName, value) {
var matchedItems = [];
+
for (var i = 0, il = self.items.length; i < il; i++) {
var item = self.items[i];
+
if (item.values()[valueName] == value) {
matchedItems.push(item);
}
}
+
return matchedItems;
};
-
/*
- * Get size of the list
- */
- this.size = function() {
+ * Get size of the list
+ */
+
+
+ this.size = function () {
return self.items.length;
};
-
/*
- * Removes all items from the list
- */
- this.clear = function() {
+ * Removes all items from the list
+ */
+
+
+ this.clear = function () {
self.templater.clear();
self.items = [];
return self;
};
- this.on = function(event, callback) {
+ this.on = function (event, callback) {
self.handlers[event].push(callback);
return self;
};
- this.off = function(event, callback) {
+ this.off = function (event, callback) {
var e = self.handlers[event];
var index = indexOf(e, callback);
+
if (index > -1) {
e.splice(index, 1);
}
+
return self;
};
- this.trigger = function(event) {
+ this.trigger = function (event) {
var i = self.handlers[event].length;
- while(i--) {
+
+ while (i--) {
self.handlers[event][i](self);
}
+
return self;
};
this.reset = {
- filter: function() {
+ filter: function filter() {
var is = self.items,
- il = is.length;
+ il = is.length;
+
while (il--) {
is[il].filtered = false;
}
+
return self;
},
- search: function() {
+ search: function search() {
var is = self.items,
- il = is.length;
+ il = is.length;
+
while (il--) {
is[il].found = false;
}
+
return self;
}
};
- this.update = function() {
+ this.update = function () {
var is = self.items,
- il = is.length;
-
+ il = is.length;
self.visibleItems = [];
self.matchingItems = [];
self.templater.clear();
+
for (var i = 0; i < il; i++) {
- if (is[i].matching() && ((self.matchingItems.length+1) >= self.i && self.visibleItems.length < self.page)) {
+ if (is[i].matching() && self.matchingItems.length + 1 >= self.i && self.visibleItems.length < self.page) {
is[i].show();
self.visibleItems.push(is[i]);
self.matchingItems.push(is[i]);
@@ -255,6 +446,7 @@ var List = function(id, options, values) {
is[i].hide();
}
}
+
self.trigger('updated');
return self;
};
@@ -262,76 +454,26 @@ var List = function(id, options, values) {
init.start();
};
+/***/ }),
-// AMD support
-if (typeof define === 'function' && define.amd) {
- define(function () { return List; });
-}
-module.exports = List;
-window.List = List;
-
-})(window);
-
-},{"./src/add-async":2,"./src/filter":3,"./src/item":4,"./src/parse":5,"./src/search":6,"./src/sort":7,"./src/templater":8,"./src/utils/classes":9,"./src/utils/events":10,"./src/utils/extend":11,"./src/utils/get-attribute":12,"./src/utils/get-by-class":13,"./src/utils/index-of":14,"./src/utils/natural-sort":15,"./src/utils/to-array":16,"./src/utils/to-string":17}],2:[function(require,module,exports){
-module.exports = function(list) {
- var addAsync = function(values, callback, items) {
- var valuesToAdd = values.splice(0, 50);
- items = items || [];
- items = items.concat(list.add(valuesToAdd));
- if (values.length > 0) {
- setTimeout(function() {
- addAsync(values, callback, items);
- }, 1);
- } else {
- list.update();
- callback(items);
- }
- };
- return addAsync;
-};
-
-},{}],3:[function(require,module,exports){
-module.exports = function(list) {
-
- // Add handlers
- list.handlers.filterStart = list.handlers.filterStart || [];
- list.handlers.filterComplete = list.handlers.filterComplete || [];
-
- return function(filterFunction) {
- list.trigger('filterStart');
- list.i = 1; // Reset paging
- list.reset.filter();
- if (filterFunction === undefined) {
- list.filtered = false;
- } else {
- list.filtered = true;
- var is = list.items;
- for (var i = 0, il = is.length; i < il; i++) {
- var item = is[i];
- if (filterFunction(item)) {
- item.filtered = true;
- } else {
- item.filtered = false;
- }
- }
- }
- list.update();
- list.trigger('filterComplete');
- return list.visibleItems;
- };
-};
+/***/ "./src/item.js":
+/*!*********************!*\
+ !*** ./src/item.js ***!
+ \*********************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: module */
+/*! CommonJS bailout: module.exports is used directly at 1:0-14 */
+/***/ (function(module) {
-},{}],4:[function(require,module,exports){
-module.exports = function(list) {
- return function(initValues, element, notCreate) {
+module.exports = function (list) {
+ return function (initValues, element, notCreate) {
var item = this;
-
this._values = {};
-
this.found = false; // Show if list.searched == true and this.found == true
- this.filtered = false;// Show if list.filtered == true and this.filtered == true
- var init = function(initValues, element, notCreate) {
+ this.filtered = false; // Show if list.filtered == true and this.filtered == true
+
+ var init = function init(initValues, element, notCreate) {
if (element === undefined) {
if (notCreate) {
item.values(initValues, notCreate);
@@ -345,11 +487,12 @@ module.exports = function(list) {
}
};
- this.values = function(newValues, notCreate) {
+ this.values = function (newValues, notCreate) {
if (newValues !== undefined) {
- for(var name in newValues) {
+ for (var name in newValues) {
item._values[name] = newValues[name];
}
+
if (notCreate !== true) {
list.templater.set(item, item.values());
}
@@ -358,58 +501,182 @@ module.exports = function(list) {
}
};
- this.show = function() {
+ this.show = function () {
list.templater.show(item);
};
- this.hide = function() {
+ this.hide = function () {
list.templater.hide(item);
};
- this.matching = function() {
- return (
- (list.filtered && list.searched && item.found && item.filtered) ||
- (list.filtered && !list.searched && item.filtered) ||
- (!list.filtered && list.searched && item.found) ||
- (!list.filtered && !list.searched)
- );
+ this.matching = function () {
+ return list.filtered && list.searched && item.found && item.filtered || list.filtered && !list.searched && item.filtered || !list.filtered && list.searched && item.found || !list.filtered && !list.searched;
};
- this.visible = function() {
- return (item.elm && (item.elm.parentNode == list.list)) ? true : false;
+ this.visible = function () {
+ return item.elm && item.elm.parentNode == list.list ? true : false;
};
init(initValues, element, notCreate);
};
};
-},{}],5:[function(require,module,exports){
-module.exports = function(list) {
+/***/ }),
+
+/***/ "./src/pagination.js":
+/*!***************************!*\
+ !*** ./src/pagination.js ***!
+ \***************************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: module, __webpack_require__ */
+/*! CommonJS bailout: module.exports is used directly at 5:0-14 */
+/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
+
+var classes = __webpack_require__(/*! ./utils/classes */ "./src/utils/classes.js"),
+ events = __webpack_require__(/*! ./utils/events */ "./src/utils/events.js"),
+ List = __webpack_require__(/*! ./index */ "./src/index.js");
+
+module.exports = function (list) {
+ var isHidden = false;
+
+ var refresh = function refresh(pagingList, options) {
+ if (list.page < 1) {
+ list.listContainer.style.display = 'none';
+ isHidden = true;
+ return;
+ } else if (isHidden) {
+ list.listContainer.style.display = 'block';
+ }
+
+ var item,
+ l = list.matchingItems.length,
+ index = list.i,
+ page = list.page,
+ pages = Math.ceil(l / page),
+ currentPage = Math.ceil(index / page),
+ innerWindow = options.innerWindow || 2,
+ left = options.left || options.outerWindow || 0,
+ right = options.right || options.outerWindow || 0;
+ right = pages - right;
+ pagingList.clear();
+
+ for (var i = 1; i <= pages; i++) {
+ var className = currentPage === i ? 'active' : ''; //console.log(i, left, right, currentPage, (currentPage - innerWindow), (currentPage + innerWindow), className);
+
+ if (is.number(i, left, right, currentPage, innerWindow)) {
+ item = pagingList.add({
+ page: i,
+ dotted: false
+ })[0];
+
+ if (className) {
+ classes(item.elm).add(className);
+ }
+
+ item.elm.firstChild.setAttribute('data-i', i);
+ item.elm.firstChild.setAttribute('data-page', page);
+ } else if (is.dotted(pagingList, i, left, right, currentPage, innerWindow, pagingList.size())) {
+ item = pagingList.add({
+ page: '...',
+ dotted: true
+ })[0];
+ classes(item.elm).add('disabled');
+ }
+ }
+ };
+
+ var is = {
+ number: function number(i, left, right, currentPage, innerWindow) {
+ return this.left(i, left) || this.right(i, right) || this.innerWindow(i, currentPage, innerWindow);
+ },
+ left: function left(i, _left) {
+ return i <= _left;
+ },
+ right: function right(i, _right) {
+ return i > _right;
+ },
+ innerWindow: function innerWindow(i, currentPage, _innerWindow) {
+ return i >= currentPage - _innerWindow && i <= currentPage + _innerWindow;
+ },
+ dotted: function dotted(pagingList, i, left, right, currentPage, innerWindow, currentPageItem) {
+ return this.dottedLeft(pagingList, i, left, right, currentPage, innerWindow) || this.dottedRight(pagingList, i, left, right, currentPage, innerWindow, currentPageItem);
+ },
+ dottedLeft: function dottedLeft(pagingList, i, left, right, currentPage, innerWindow) {
+ return i == left + 1 && !this.innerWindow(i, currentPage, innerWindow) && !this.right(i, right);
+ },
+ dottedRight: function dottedRight(pagingList, i, left, right, currentPage, innerWindow, currentPageItem) {
+ if (pagingList.items[currentPageItem - 1].values().dotted) {
+ return false;
+ } else {
+ return i == right && !this.innerWindow(i, currentPage, innerWindow) && !this.right(i, right);
+ }
+ }
+ };
+ return function (options) {
+ var pagingList = new List(list.listContainer.id, {
+ listClass: options.paginationClass || 'pagination',
+ item: options.item || "
",
+ valueNames: ['page', 'dotted'],
+ searchClass: 'pagination-search-that-is-not-supposed-to-exist',
+ sortClass: 'pagination-sort-that-is-not-supposed-to-exist'
+ });
+ events.bind(pagingList.listContainer, 'click', function (e) {
+ var target = e.target || e.srcElement,
+ page = list.utils.getAttribute(target, 'data-page'),
+ i = list.utils.getAttribute(target, 'data-i');
+
+ if (i) {
+ list.show((i - 1) * page + 1, page);
+ }
+ });
+ list.on('updated', function () {
+ refresh(pagingList, options);
+ });
+ refresh(pagingList, options);
+ };
+};
+
+/***/ }),
- var Item = require('./item')(list);
+/***/ "./src/parse.js":
+/*!**********************!*\
+ !*** ./src/parse.js ***!
+ \**********************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: module, __webpack_require__ */
+/*! CommonJS bailout: module.exports is used directly at 1:0-14 */
+/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
- var getChildren = function(parent) {
+module.exports = function (list) {
+ var Item = __webpack_require__(/*! ./item */ "./src/item.js")(list);
+
+ var getChildren = function getChildren(parent) {
var nodes = parent.childNodes,
- items = [];
+ items = [];
+
for (var i = 0, il = nodes.length; i < il; i++) {
// Only textnodes have a data attribute
if (nodes[i].data === undefined) {
items.push(nodes[i]);
}
}
+
return items;
};
- var parse = function(itemElements, valueNames) {
+ var parse = function parse(itemElements, valueNames) {
for (var i = 0, il = itemElements.length; i < il; i++) {
list.items.push(new Item(valueNames, itemElements[i]));
}
};
- var parseAsync = function(itemElements, valueNames) {
+
+ var parseAsync = function parseAsync(itemElements, valueNames) {
var itemsToIndex = itemElements.splice(0, 50); // TODO: If < 100 items, what happens in IE etc?
+
parse(itemsToIndex, valueNames);
+
if (itemElements.length > 0) {
- setTimeout(function() {
+ setTimeout(function () {
parseAsync(itemElements, valueNames);
}, 1);
} else {
@@ -419,10 +686,9 @@ module.exports = function(list) {
};
list.handlers.parseComplete = list.handlers.parseComplete || [];
-
- return function() {
+ return function () {
var itemsToIndex = getChildren(list.list),
- valueNames = list.valueNames;
+ valueNames = list.valueNames;
if (list.indexAsync) {
parseAsync(itemsToIndex, valueNames);
@@ -432,91 +698,132 @@ module.exports = function(list) {
};
};
-},{"./item":4}],6:[function(require,module,exports){
-module.exports = function(list) {
- var item,
- text,
- columns,
- searchString,
- customSearch;
+/***/ }),
+/***/ "./src/search.js":
+/*!***********************!*\
+ !*** ./src/search.js ***!
+ \***********************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: module */
+/*! CommonJS bailout: module.exports is used directly at 1:0-14 */
+/***/ (function(module) {
+
+module.exports = function (_list) {
+ var item, text, columns, searchString, customSearch;
var prepare = {
- resetList: function() {
- list.i = 1;
- list.templater.clear();
+ resetList: function resetList() {
+ _list.i = 1;
+
+ _list.templater.clear();
+
customSearch = undefined;
},
- setOptions: function(args) {
+ setOptions: function setOptions(args) {
if (args.length == 2 && args[1] instanceof Array) {
columns = args[1];
- } else if (args.length == 2 && typeof(args[1]) == "function") {
+ } else if (args.length == 2 && typeof args[1] == 'function') {
+ columns = undefined;
customSearch = args[1];
} else if (args.length == 3) {
columns = args[1];
customSearch = args[2];
+ } else {
+ columns = undefined;
}
},
- setColumns: function() {
- if (list.items.length === 0) return;
+ setColumns: function setColumns() {
+ if (_list.items.length === 0) return;
+
if (columns === undefined) {
- columns = (list.searchColumns === undefined) ? prepare.toArray(list.items[0].values()) : list.searchColumns;
+ columns = _list.searchColumns === undefined ? prepare.toArray(_list.items[0].values()) : _list.searchColumns;
}
},
- setSearchString: function(s) {
- s = list.utils.toString(s).toLowerCase();
- s = s.replace(/[-[\]{}()*+?.,\\^$|#]/g, "\\$&"); // Escape regular expression characters
+ setSearchString: function setSearchString(s) {
+ s = _list.utils.toString(s).toLowerCase();
+ s = s.replace(/[-[\]{}()*+?.,\\^$|#]/g, '\\$&'); // Escape regular expression characters
+
searchString = s;
},
- toArray: function(values) {
+ toArray: function toArray(values) {
var tmpColumn = [];
+
for (var name in values) {
tmpColumn.push(name);
}
+
return tmpColumn;
}
};
var search = {
- list: function() {
- for (var k = 0, kl = list.items.length; k < kl; k++) {
- search.item(list.items[k]);
- }
- },
- item: function(item) {
- item.found = false;
- for (var j = 0, jl = columns.length; j < jl; j++) {
- if (search.values(item.values(), columns[j])) {
- item.found = true;
- return;
- }
- }
- },
- values: function(values, column) {
- if (values.hasOwnProperty(column)) {
- text = list.utils.toString(values[column]).toLowerCase();
- if ((searchString !== "") && (text.search(searchString) > -1)) {
- return true;
+ list: function list() {
+ // Extract quoted phrases "word1 word2" from original searchString
+ // searchString is converted to lowercase by List.js
+ var words = [],
+ phrase,
+ ss = searchString;
+
+ while ((phrase = ss.match(/"([^"]+)"/)) !== null) {
+ words.push(phrase[1]);
+ ss = ss.substring(0, phrase.index) + ss.substring(phrase.index + phrase[0].length);
+ } // Get remaining space-separated words (if any)
+
+
+ ss = ss.trim();
+ if (ss.length) words = words.concat(ss.split(/\s+/));
+
+ for (var k = 0, kl = _list.items.length; k < kl; k++) {
+ var item = _list.items[k];
+ item.found = false;
+ if (!words.length) continue;
+
+ for (var i = 0, il = words.length; i < il; i++) {
+ var word_found = false;
+
+ for (var j = 0, jl = columns.length; j < jl; j++) {
+ var values = item.values(),
+ column = columns[j];
+
+ if (values.hasOwnProperty(column) && values[column] !== undefined && values[column] !== null) {
+ var text = typeof values[column] !== 'string' ? values[column].toString() : values[column];
+
+ if (text.toLowerCase().indexOf(words[i]) !== -1) {
+ // word found, so no need to check it against any other columns
+ word_found = true;
+ break;
+ }
+ }
+ } // this word not found? no need to check any other words, the item cannot match
+
+
+ if (!word_found) break;
}
+
+ item.found = word_found;
}
- return false;
},
- reset: function() {
- list.reset.search();
- list.searched = false;
+ // Removed search.item() and search.values()
+ reset: function reset() {
+ _list.reset.search();
+
+ _list.searched = false;
}
};
- var searchMethod = function(str) {
- list.trigger('searchStart');
+ var searchMethod = function searchMethod(str) {
+ _list.trigger('searchStart');
prepare.resetList();
prepare.setSearchString(str);
prepare.setOptions(arguments); // str, cols|searchFunction, searchFunction
+
prepare.setColumns();
- if (searchString === "" ) {
+ if (searchString === '') {
search.reset();
} else {
- list.searched = true;
+ _list.searched = true;
+
if (customSearch) {
customSearch(searchString, columns);
} else {
@@ -524,26 +831,32 @@ module.exports = function(list) {
}
}
- list.update();
- list.trigger('searchComplete');
- return list.visibleItems;
+ _list.update();
+
+ _list.trigger('searchComplete');
+
+ return _list.visibleItems;
};
- list.handlers.searchStart = list.handlers.searchStart || [];
- list.handlers.searchComplete = list.handlers.searchComplete || [];
+ _list.handlers.searchStart = _list.handlers.searchStart || [];
+ _list.handlers.searchComplete = _list.handlers.searchComplete || [];
+
+ _list.utils.events.bind(_list.utils.getByClass(_list.listContainer, _list.searchClass), 'keyup', _list.utils.events.debounce(function (e) {
+ var target = e.target || e.srcElement,
+ // IE have srcElement
+ alreadyCleared = target.value === '' && !_list.searched;
- list.utils.events.bind(list.utils.getByClass(list.listContainer, list.searchClass), 'keyup', function(e) {
- var target = e.target || e.srcElement, // IE have srcElement
- alreadyCleared = (target.value === "" && !list.searched);
- if (!alreadyCleared) { // If oninput already have resetted the list, do nothing
+ if (!alreadyCleared) {
+ // If oninput already have resetted the list, do nothing
searchMethod(target.value);
}
- });
+ }, _list.searchDelay)); // Used to detect click on HTML5 clear button
+
- // Used to detect click on HTML5 clear button
- list.utils.events.bind(list.utils.getByClass(list.listContainer, list.searchClass), 'input', function(e) {
+ _list.utils.events.bind(_list.utils.getByClass(_list.listContainer, _list.searchClass), 'input', function (e) {
var target = e.target || e.srcElement;
- if (target.value === "") {
+
+ if (target.value === '') {
searchMethod('');
}
});
@@ -551,49 +864,59 @@ module.exports = function(list) {
return searchMethod;
};
-},{}],7:[function(require,module,exports){
-module.exports = function(list) {
- list.sortFunction = list.sortFunction || function(itemA, itemB, options) {
- options.desc = options.order == "desc" ? true : false; // Natural sort uses this format
- return list.utils.naturalSort(itemA.values()[options.valueName], itemB.values()[options.valueName], options);
- };
+/***/ }),
+/***/ "./src/sort.js":
+/*!*********************!*\
+ !*** ./src/sort.js ***!
+ \*********************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: module */
+/*! CommonJS bailout: module.exports is used directly at 1:0-14 */
+/***/ (function(module) {
+
+module.exports = function (list) {
var buttons = {
els: undefined,
- clear: function() {
+ clear: function clear() {
for (var i = 0, il = buttons.els.length; i < il; i++) {
list.utils.classes(buttons.els[i]).remove('asc');
list.utils.classes(buttons.els[i]).remove('desc');
}
},
- getOrder: function(btn) {
+ getOrder: function getOrder(btn) {
var predefinedOrder = list.utils.getAttribute(btn, 'data-order');
- if (predefinedOrder == "asc" || predefinedOrder == "desc") {
+
+ if (predefinedOrder == 'asc' || predefinedOrder == 'desc') {
return predefinedOrder;
} else if (list.utils.classes(btn).has('desc')) {
- return "asc";
+ return 'asc';
} else if (list.utils.classes(btn).has('asc')) {
- return "desc";
+ return 'desc';
} else {
- return "asc";
+ return 'asc';
}
},
- getInSensitive: function(btn, options) {
+ getInSensitive: function getInSensitive(btn, options) {
var insensitive = list.utils.getAttribute(btn, 'data-insensitive');
- if (insensitive === "false") {
+
+ if (insensitive === 'false') {
options.insensitive = false;
} else {
options.insensitive = true;
}
},
- setOrder: function(options) {
+ setOrder: function setOrder(options) {
for (var i = 0, il = buttons.els.length; i < il; i++) {
var btn = buttons.els[i];
+
if (list.utils.getAttribute(btn, 'data-sort') !== options.valueName) {
continue;
}
+
var predefinedOrder = list.utils.getAttribute(btn, 'data-order');
- if (predefinedOrder == "asc" || predefinedOrder == "desc") {
+
+ if (predefinedOrder == 'asc' || predefinedOrder == 'desc') {
if (predefinedOrder == options.order) {
list.utils.classes(btn).add(options.order);
}
@@ -603,10 +926,10 @@ module.exports = function(list) {
}
}
};
- var sort = function() {
+
+ var sort = function sort() {
list.trigger('sortStart');
var options = {};
-
var target = arguments[0].currentTarget || arguments[0].srcElement || undefined;
if (target) {
@@ -616,192 +939,268 @@ module.exports = function(list) {
} else {
options = arguments[1] || options;
options.valueName = arguments[0];
- options.order = options.order || "asc";
- options.insensitive = (typeof options.insensitive == "undefined") ? true : options.insensitive;
+ options.order = options.order || 'asc';
+ options.insensitive = typeof options.insensitive == 'undefined' ? true : options.insensitive;
}
+
buttons.clear();
- buttons.setOrder(options);
+ buttons.setOrder(options); // caseInsensitive
+ // alphabet
- options.sortFunction = options.sortFunction || list.sortFunction;
- list.items.sort(function(a, b) {
- var mult = (options.order === 'desc') ? -1 : 1;
- return (options.sortFunction(a, b, options) * mult);
- });
+ var customSortFunction = options.sortFunction || list.sortFunction || null,
+ multi = options.order === 'desc' ? -1 : 1,
+ sortFunction;
+
+ if (customSortFunction) {
+ sortFunction = function sortFunction(itemA, itemB) {
+ return customSortFunction(itemA, itemB, options) * multi;
+ };
+ } else {
+ sortFunction = function sortFunction(itemA, itemB) {
+ var sort = list.utils.naturalSort;
+ sort.alphabet = list.alphabet || options.alphabet || undefined;
+
+ if (!sort.alphabet && options.insensitive) {
+ sort = list.utils.naturalSort.caseInsensitive;
+ }
+
+ return sort(itemA.values()[options.valueName], itemB.values()[options.valueName]) * multi;
+ };
+ }
+
+ list.items.sort(sortFunction);
list.update();
list.trigger('sortComplete');
- };
+ }; // Add handlers
+
- // Add handlers
list.handlers.sortStart = list.handlers.sortStart || [];
list.handlers.sortComplete = list.handlers.sortComplete || [];
-
buttons.els = list.utils.getByClass(list.listContainer, list.sortClass);
list.utils.events.bind(buttons.els, 'click', sort);
list.on('searchStart', buttons.clear);
list.on('filterStart', buttons.clear);
-
return sort;
};
-},{}],8:[function(require,module,exports){
-var Templater = function(list) {
- var itemSource,
- templater = this;
+/***/ }),
+
+/***/ "./src/templater.js":
+/*!**************************!*\
+ !*** ./src/templater.js ***!
+ \**************************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: module */
+/*! CommonJS bailout: module.exports is used directly at 216:0-14 */
+/***/ (function(module) {
+
+var Templater = function Templater(list) {
+ var createItem,
+ templater = this;
- var init = function() {
- itemSource = templater.getItemSource(list.item);
- itemSource = templater.clearSourceItem(itemSource, list.valueNames);
+ var init = function init() {
+ var itemSource;
+
+ if (typeof list.item === 'function') {
+ createItem = function createItem(values) {
+ var item = list.item(values);
+ return getItemSource(item);
+ };
+
+ return;
+ }
+
+ if (typeof list.item === 'string') {
+ if (list.item.indexOf('<') === -1) {
+ itemSource = document.getElementById(list.item);
+ } else {
+ itemSource = getItemSource(list.item);
+ }
+ } else {
+ /* If item source does not exists, use the first item in list as
+ source for new items */
+ itemSource = getFirstListItem();
+ }
+
+ if (!itemSource) {
+ throw new Error("The list needs to have at least one item on init otherwise you'll have to add a template.");
+ }
+
+ itemSource = createCleanTemplateItem(itemSource, list.valueNames);
+
+ createItem = function createItem() {
+ return itemSource.cloneNode(true);
+ };
};
- this.clearSourceItem = function(el, valueNames) {
- for(var i = 0, il = valueNames.length; i < il; i++) {
- var elm;
- if (valueNames[i].data) {
- for (var j = 0, jl = valueNames[i].data.length; j < jl; j++) {
- el.setAttribute('data-'+valueNames[i].data[j], '');
+ var createCleanTemplateItem = function createCleanTemplateItem(templateNode, valueNames) {
+ var el = templateNode.cloneNode(true);
+ el.removeAttribute('id');
+
+ for (var i = 0, il = valueNames.length; i < il; i++) {
+ var elm = undefined,
+ valueName = valueNames[i];
+
+ if (valueName.data) {
+ for (var j = 0, jl = valueName.data.length; j < jl; j++) {
+ el.setAttribute('data-' + valueName.data[j], '');
}
- } else if (valueNames[i].attr && valueNames[i].name) {
- elm = list.utils.getByClass(el, valueNames[i].name, true);
+ } else if (valueName.attr && valueName.name) {
+ elm = list.utils.getByClass(el, valueName.name, true);
+
if (elm) {
- elm.setAttribute(valueNames[i].attr, "");
+ elm.setAttribute(valueName.attr, '');
}
} else {
- elm = list.utils.getByClass(el, valueNames[i], true);
+ elm = list.utils.getByClass(el, valueName, true);
+
if (elm) {
- elm.innerHTML = "";
+ elm.innerHTML = '';
}
}
- elm = undefined;
}
+
return el;
};
- this.getItemSource = function(item) {
- if (item === undefined) {
- var nodes = list.list.childNodes,
- items = [];
+ var getFirstListItem = function getFirstListItem() {
+ var nodes = list.list.childNodes;
- for (var i = 0, il = nodes.length; i < il; i++) {
- // Only textnodes have a data attribute
- if (nodes[i].data === undefined) {
- return nodes[i].cloneNode(true);
- }
+ for (var i = 0, il = nodes.length; i < il; i++) {
+ // Only textnodes have a data attribute
+ if (nodes[i].data === undefined) {
+ return nodes[i].cloneNode(true);
}
- } else if (/^tr[\s>]/.exec(item)) {
- var table = document.createElement('table');
- table.innerHTML = item;
- return table.firstChild;
- } else if (item.indexOf("<") !== -1) {
+ }
+
+ return undefined;
+ };
+
+ var getItemSource = function getItemSource(itemHTML) {
+ if (typeof itemHTML !== 'string') return undefined;
+
+ if (/
]/g.exec(itemHTML)) {
+ var tbody = document.createElement('tbody');
+ tbody.innerHTML = itemHTML;
+ return tbody.firstElementChild;
+ } else if (itemHTML.indexOf('<') !== -1) {
var div = document.createElement('div');
- div.innerHTML = item;
- return div.firstChild;
- } else {
- var source = document.getElementById(list.item);
- if (source) {
- return source;
- }
+ div.innerHTML = itemHTML;
+ return div.firstElementChild;
}
- throw new Error("The list need to have at list one item on init otherwise you'll have to add a template.");
+
+ return undefined;
};
- this.get = function(item, valueNames) {
- templater.create(item);
- var values = {};
- for(var i = 0, il = valueNames.length; i < il; i++) {
- var elm;
- if (valueNames[i].data) {
- for (var j = 0, jl = valueNames[i].data.length; j < jl; j++) {
- values[valueNames[i].data[j]] = list.utils.getAttribute(item.elm, 'data-'+valueNames[i].data[j]);
+ var getValueName = function getValueName(name) {
+ for (var i = 0, il = list.valueNames.length; i < il; i++) {
+ var valueName = list.valueNames[i];
+
+ if (valueName.data) {
+ var data = valueName.data;
+
+ for (var j = 0, jl = data.length; j < jl; j++) {
+ if (data[j] === name) {
+ return {
+ data: name
+ };
+ }
}
- } else if (valueNames[i].attr && valueNames[i].name) {
- elm = list.utils.getByClass(item.elm, valueNames[i].name, true);
- values[valueNames[i].name] = elm ? list.utils.getAttribute(elm, valueNames[i].attr) : "";
- } else {
- elm = list.utils.getByClass(item.elm, valueNames[i], true);
- values[valueNames[i]] = elm ? elm.innerHTML : "";
+ } else if (valueName.attr && valueName.name && valueName.name == name) {
+ return valueName;
+ } else if (valueName === name) {
+ return name;
}
- elm = undefined;
}
- return values;
};
- this.set = function(item, values) {
- var getValueName = function(name) {
- for (var i = 0, il = list.valueNames.length; i < il; i++) {
- if (list.valueNames[i].data) {
- var data = list.valueNames[i].data;
- for (var j = 0, jl = data.length; j < jl; j++) {
- if (data[j] === name) {
- return { data: name };
- }
- }
- } else if (list.valueNames[i].attr && list.valueNames[i].name && list.valueNames[i].name == name) {
- return list.valueNames[i];
- } else if (list.valueNames[i] === name) {
- return name;
- }
+ var setValue = function setValue(item, name, value) {
+ var elm = undefined,
+ valueName = getValueName(name);
+ if (!valueName) return;
+
+ if (valueName.data) {
+ item.elm.setAttribute('data-' + valueName.data, value);
+ } else if (valueName.attr && valueName.name) {
+ elm = list.utils.getByClass(item.elm, valueName.name, true);
+
+ if (elm) {
+ elm.setAttribute(valueName.attr, value);
}
- };
- var setValue = function(name, value) {
- var elm;
- var valueName = getValueName(name);
- if (!valueName)
- return;
+ } else {
+ elm = list.utils.getByClass(item.elm, valueName, true);
+
+ if (elm) {
+ elm.innerHTML = value;
+ }
+ }
+ };
+
+ this.get = function (item, valueNames) {
+ templater.create(item);
+ var values = {};
+
+ for (var i = 0, il = valueNames.length; i < il; i++) {
+ var elm = undefined,
+ valueName = valueNames[i];
+
if (valueName.data) {
- item.elm.setAttribute('data-'+valueName.data, value);
+ for (var j = 0, jl = valueName.data.length; j < jl; j++) {
+ values[valueName.data[j]] = list.utils.getAttribute(item.elm, 'data-' + valueName.data[j]);
+ }
} else if (valueName.attr && valueName.name) {
elm = list.utils.getByClass(item.elm, valueName.name, true);
- if (elm) {
- elm.setAttribute(valueName.attr, value);
- }
+ values[valueName.name] = elm ? list.utils.getAttribute(elm, valueName.attr) : '';
} else {
elm = list.utils.getByClass(item.elm, valueName, true);
- if (elm) {
- elm.innerHTML = value;
- }
+ values[valueName] = elm ? elm.innerHTML : '';
}
- elm = undefined;
- };
+ }
+
+ return values;
+ };
+
+ this.set = function (item, values) {
if (!templater.create(item)) {
- for(var v in values) {
+ for (var v in values) {
if (values.hasOwnProperty(v)) {
- setValue(v, values[v]);
+ setValue(item, v, values[v]);
}
}
}
};
- this.create = function(item) {
+ this.create = function (item) {
if (item.elm !== undefined) {
return false;
}
- /* If item source does not exists, use the first item in list as
- source for new items */
- var newItem = itemSource.cloneNode(true);
- newItem.removeAttribute('id');
- item.elm = newItem;
+
+ item.elm = createItem(item.values());
templater.set(item, item.values());
return true;
};
- this.remove = function(item) {
+
+ this.remove = function (item) {
if (item.elm.parentNode === list.list) {
list.list.removeChild(item.elm);
}
};
- this.show = function(item) {
+
+ this.show = function (item) {
templater.create(item);
list.list.appendChild(item.elm);
};
- this.hide = function(item) {
+
+ this.hide = function (item) {
if (item.elm !== undefined && item.elm.parentNode === list.list) {
list.list.removeChild(item.elm);
}
};
- this.clear = function() {
+
+ this.clear = function () {
/* .innerHTML = ''; fucks up IE */
if (list.list.hasChildNodes()) {
- while (list.list.childNodes.length >= 1)
- {
+ while (list.list.childNodes.length >= 1) {
list.list.removeChild(list.list.firstChild);
}
}
@@ -810,29 +1209,36 @@ var Templater = function(list) {
init();
};
-module.exports = function(list) {
+module.exports = function (list) {
return new Templater(list);
};
-},{}],9:[function(require,module,exports){
+/***/ }),
+
+/***/ "./src/utils/classes.js":
+/*!******************************!*\
+ !*** ./src/utils/classes.js ***!
+ \******************************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: module, __webpack_require__ */
+/*! CommonJS bailout: module.exports is used directly at 24:0-14 */
+/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
+
/**
* Module dependencies.
*/
-
-var index = require('./index-of');
-
+var index = __webpack_require__(/*! ./index-of */ "./src/utils/index-of.js");
/**
* Whitespace regexp.
*/
-var re = /\s+/;
+var re = /\s+/;
/**
* toString reference.
*/
var toString = Object.prototype.toString;
-
/**
* Wrap `el` in a `ClassList`.
*
@@ -841,10 +1247,9 @@ var toString = Object.prototype.toString;
* @api public
*/
-module.exports = function(el){
+module.exports = function (el) {
return new ClassList(el);
};
-
/**
* Initialize a new ClassList for `el`.
*
@@ -852,14 +1257,15 @@ module.exports = function(el){
* @api private
*/
+
function ClassList(el) {
if (!el || !el.nodeType) {
throw new Error('A DOM element reference is required');
}
+
this.el = el;
this.list = el.classList;
}
-
/**
* Add class `name` if not already present.
*
@@ -868,21 +1274,21 @@ function ClassList(el) {
* @api public
*/
-ClassList.prototype.add = function(name){
+
+ClassList.prototype.add = function (name) {
// classList
if (this.list) {
this.list.add(name);
return this;
- }
+ } // fallback
+
- // fallback
var arr = this.array();
var i = index(arr, name);
if (!~i) arr.push(name);
this.el.className = arr.join(' ');
return this;
};
-
/**
* Remove class `name` when present, or
* pass a regular expression to remove
@@ -893,43 +1299,21 @@ ClassList.prototype.add = function(name){
* @api public
*/
-ClassList.prototype.remove = function(name){
- if ('[object RegExp]' == toString.call(name)) {
- return this.removeMatching(name);
- }
+ClassList.prototype.remove = function (name) {
// classList
if (this.list) {
this.list.remove(name);
return this;
- }
+ } // fallback
+
- // fallback
var arr = this.array();
var i = index(arr, name);
if (~i) arr.splice(i, 1);
this.el.className = arr.join(' ');
return this;
};
-
-/**
- * Remove all classes matching `re`.
- *
- * @param {RegExp} re
- * @return {ClassList}
- * @api private
- */
-
-ClassList.prototype.removeMatching = function(re){
- var arr = this.array();
- for (var i = 0; i < arr.length; i++) {
- if (re.test(arr[i])) {
- this.remove(arr[i]);
- }
- }
- return this;
-};
-
/**
* Toggle class `name`, can force state via `force`.
*
@@ -942,21 +1326,23 @@ ClassList.prototype.removeMatching = function(re){
* @api public
*/
-ClassList.prototype.toggle = function(name, force){
+
+ClassList.prototype.toggle = function (name, force) {
// classList
if (this.list) {
- if ("undefined" !== typeof force) {
+ if ('undefined' !== typeof force) {
if (force !== this.list.toggle(name, force)) {
this.list.toggle(name); // toggle again to correct
}
} else {
this.list.toggle(name);
}
+
return this;
- }
+ } // fallback
- // fallback
- if ("undefined" !== typeof force) {
+
+ if ('undefined' !== typeof force) {
if (!force) {
this.remove(name);
} else {
@@ -972,7 +1358,6 @@ ClassList.prototype.toggle = function(name, force){
return this;
};
-
/**
* Return an array of classes.
*
@@ -980,14 +1365,14 @@ ClassList.prototype.toggle = function(name, force){
* @api public
*/
-ClassList.prototype.array = function(){
+
+ClassList.prototype.array = function () {
var className = this.el.getAttribute('class') || '';
var str = className.replace(/^\s+|\s+$/g, '');
var arr = str.split(re);
if ('' === arr[0]) arr.shift();
return arr;
};
-
/**
* Check if class `name` is present.
*
@@ -996,17 +1381,29 @@ ClassList.prototype.array = function(){
* @api public
*/
-ClassList.prototype.has =
-ClassList.prototype.contains = function(name){
- return this.list ? this.list.contains(name) : !! ~index(this.array(), name);
+
+ClassList.prototype.has = ClassList.prototype.contains = function (name) {
+ return this.list ? this.list.contains(name) : !!~index(this.array(), name);
};
-},{"./index-of":14}],10:[function(require,module,exports){
+/***/ }),
+
+/***/ "./src/utils/events.js":
+/*!*****************************!*\
+ !*** ./src/utils/events.js ***!
+ \*****************************/
+/*! default exports */
+/*! export bind [provided] [no usage info] [missing usage info prevents renaming] */
+/*! export debounce [provided] [no usage info] [missing usage info prevents renaming] */
+/*! export unbind [provided] [no usage info] [missing usage info prevents renaming] */
+/*! other exports [not provided] [no usage info] */
+/*! runtime requirements: __webpack_exports__, __webpack_require__ */
+/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
+
var bind = window.addEventListener ? 'addEventListener' : 'attachEvent',
unbind = window.removeEventListener ? 'removeEventListener' : 'detachEvent',
prefix = bind !== 'addEventListener' ? 'on' : '',
- toArray = require('./to-array');
-
+ toArray = __webpack_require__(/*! ./to-array */ "./src/utils/to-array.js");
/**
* Bind `el` event `type` to `fn`.
*
@@ -1017,13 +1414,14 @@ var bind = window.addEventListener ? 'addEventListener' : 'attachEvent',
* @api public
*/
-exports.bind = function(el, type, fn, capture){
+
+exports.bind = function (el, type, fn, capture) {
el = toArray(el);
- for ( var i = 0; i < el.length; i++ ) {
+
+ for (var i = 0, il = el.length; i < il; i++) {
el[i][bind](prefix + type, fn, capture || false);
}
};
-
/**
* Unbind `el` event `type`'s callback `fn`.
*
@@ -1034,34 +1432,227 @@ exports.bind = function(el, type, fn, capture){
* @api public
*/
-exports.unbind = function(el, type, fn, capture){
+
+exports.unbind = function (el, type, fn, capture) {
el = toArray(el);
- for ( var i = 0; i < el.length; i++ ) {
+
+ for (var i = 0, il = el.length; i < il; i++) {
el[i][unbind](prefix + type, fn, capture || false);
}
};
+/**
+ * Returns a function, that, as long as it continues to be invoked, will not
+ * be triggered. The function will be called after it stops being called for
+ * `wait` milliseconds. If `immediate` is true, trigger the function on the
+ * leading edge, instead of the trailing.
+ *
+ * @param {Function} fn
+ * @param {Integer} wait
+ * @param {Boolean} immediate
+ * @api public
+ */
+
+
+exports.debounce = function (fn, wait, immediate) {
+ var timeout;
+ return wait ? function () {
+ var context = this,
+ args = arguments;
+
+ var later = function later() {
+ timeout = null;
+ if (!immediate) fn.apply(context, args);
+ };
+
+ var callNow = immediate && !timeout;
+ clearTimeout(timeout);
+ timeout = setTimeout(later, wait);
+ if (callNow) fn.apply(context, args);
+ } : fn;
+};
+
+/***/ }),
+
+/***/ "./src/utils/extend.js":
+/*!*****************************!*\
+ !*** ./src/utils/extend.js ***!
+ \*****************************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: module */
+/*! CommonJS bailout: module.exports is used directly at 4:0-14 */
+/***/ (function(module) {
-},{"./to-array":16}],11:[function(require,module,exports){
/*
* Source: https://github.com/segmentio/extend
*/
+module.exports = function extend(object) {
+ // Takes an unlimited number of extenders.
+ var args = Array.prototype.slice.call(arguments, 1); // For each extender, copy their properties on our object.
+
+ for (var i = 0, source; source = args[i]; i++) {
+ if (!source) continue;
+
+ for (var property in source) {
+ object[property] = source[property];
+ }
+ }
+
+ return object;
+};
+
+/***/ }),
+
+/***/ "./src/utils/fuzzy.js":
+/*!****************************!*\
+ !*** ./src/utils/fuzzy.js ***!
+ \****************************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: module */
+/*! CommonJS bailout: module.exports is used directly at 1:0-14 */
+/***/ (function(module) {
+
+module.exports = function (text, pattern, options) {
+ // Aproximately where in the text is the pattern expected to be found?
+ var Match_Location = options.location || 0; //Determines how close the match must be to the fuzzy location (specified above). An exact letter match which is 'distance' characters away from the fuzzy location would score as a complete mismatch. A distance of '0' requires the match be at the exact location specified, a threshold of '1000' would require a perfect match to be within 800 characters of the fuzzy location to be found using a 0.8 threshold.
+
+ var Match_Distance = options.distance || 100; // At what point does the match algorithm give up. A threshold of '0.0' requires a perfect match (of both letters and location), a threshold of '1.0' would match anything.
+
+ var Match_Threshold = options.threshold || 0.4;
+ if (pattern === text) return true; // Exact match
+
+ if (pattern.length > 32) return false; // This algorithm cannot be used
+ // Set starting location at beginning text and initialise the alphabet.
+
+ var loc = Match_Location,
+ s = function () {
+ var q = {},
+ i;
+
+ for (i = 0; i < pattern.length; i++) {
+ q[pattern.charAt(i)] = 0;
+ }
+
+ for (i = 0; i < pattern.length; i++) {
+ q[pattern.charAt(i)] |= 1 << pattern.length - i - 1;
+ }
+
+ return q;
+ }(); // Compute and return the score for a match with e errors and x location.
+ // Accesses loc and pattern through being a closure.
+
+
+ function match_bitapScore_(e, x) {
+ var accuracy = e / pattern.length,
+ proximity = Math.abs(loc - x);
+
+ if (!Match_Distance) {
+ // Dodge divide by zero error.
+ return proximity ? 1.0 : accuracy;
+ }
+
+ return accuracy + proximity / Match_Distance;
+ }
+
+ var score_threshold = Match_Threshold,
+ // Highest score beyond which we give up.
+ best_loc = text.indexOf(pattern, loc); // Is there a nearby exact match? (speedup)
+
+ if (best_loc != -1) {
+ score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold); // What about in the other direction? (speedup)
+
+ best_loc = text.lastIndexOf(pattern, loc + pattern.length);
+
+ if (best_loc != -1) {
+ score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold);
+ }
+ } // Initialise the bit arrays.
+
+
+ var matchmask = 1 << pattern.length - 1;
+ best_loc = -1;
+ var bin_min, bin_mid;
+ var bin_max = pattern.length + text.length;
+ var last_rd;
+
+ for (var d = 0; d < pattern.length; d++) {
+ // Scan for the best match; each iteration allows for one more error.
+ // Run a binary search to determine how far from 'loc' we can stray at this
+ // error level.
+ bin_min = 0;
+ bin_mid = bin_max;
+
+ while (bin_min < bin_mid) {
+ if (match_bitapScore_(d, loc + bin_mid) <= score_threshold) {
+ bin_min = bin_mid;
+ } else {
+ bin_max = bin_mid;
+ }
+
+ bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min);
+ } // Use the result from this iteration as the maximum for the next.
+
+
+ bin_max = bin_mid;
+ var start = Math.max(1, loc - bin_mid + 1);
+ var finish = Math.min(loc + bin_mid, text.length) + pattern.length;
+ var rd = Array(finish + 2);
+ rd[finish + 1] = (1 << d) - 1;
-module.exports = function extend (object) {
- // Takes an unlimited number of extenders.
- var args = Array.prototype.slice.call(arguments, 1);
+ for (var j = finish; j >= start; j--) {
+ // The alphabet (s) is a sparse hash, so the following line generates
+ // warnings.
+ var charMatch = s[text.charAt(j - 1)];
- // For each extender, copy their properties on our object.
- for (var i = 0, source; source = args[i]; i++) {
- if (!source) continue;
- for (var property in source) {
- object[property] = source[property];
+ if (d === 0) {
+ // First pass: exact match.
+ rd[j] = (rd[j + 1] << 1 | 1) & charMatch;
+ } else {
+ // Subsequent passes: fuzzy match.
+ rd[j] = (rd[j + 1] << 1 | 1) & charMatch | ((last_rd[j + 1] | last_rd[j]) << 1 | 1) | last_rd[j + 1];
+ }
+
+ if (rd[j] & matchmask) {
+ var score = match_bitapScore_(d, j - 1); // This match will almost certainly be better than any existing match.
+ // But check anyway.
+
+ if (score <= score_threshold) {
+ // Told you so.
+ score_threshold = score;
+ best_loc = j - 1;
+
+ if (best_loc > loc) {
+ // When passing loc, don't exceed our current distance from loc.
+ start = Math.max(1, 2 * loc - best_loc);
+ } else {
+ // Already passed loc, downhill from here on in.
+ break;
+ }
}
+ }
+ } // No hope for a (better) match at greater error levels.
+
+
+ if (match_bitapScore_(d + 1, loc) > score_threshold) {
+ break;
}
- return object;
+ last_rd = rd;
+ }
+
+ return best_loc < 0 ? false : true;
};
-},{}],12:[function(require,module,exports){
+/***/ }),
+
+/***/ "./src/utils/get-attribute.js":
+/*!************************************!*\
+ !*** ./src/utils/get-attribute.js ***!
+ \************************************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: module */
+/*! CommonJS bailout: module.exports is used directly at 11:0-14 */
+/***/ (function(module) {
+
/**
* A cross-browser implementation of getAttribute.
* Source found here: http://stackoverflow.com/a/3755343/361337 written by Vivin Paliath
@@ -1072,24 +1663,36 @@ module.exports = function extend (object) {
* @param {String} attr
* @api public
*/
+module.exports = function (el, attr) {
+ var result = el.getAttribute && el.getAttribute(attr) || null;
-module.exports = function(el, attr) {
- var result = (el.getAttribute && el.getAttribute(attr)) || null;
- if( !result ) {
+ if (!result) {
var attrs = el.attributes;
var length = attrs.length;
- for(var i = 0; i < length; i++) {
- if (attr[i] !== undefined) {
- if(attr[i].nodeName === attr) {
- result = attr[i].nodeValue;
+
+ for (var i = 0; i < length; i++) {
+ if (attrs[i] !== undefined) {
+ if (attrs[i].nodeName === attr) {
+ result = attrs[i].nodeValue;
}
}
}
}
+
return result;
};
-},{}],13:[function(require,module,exports){
+/***/ }),
+
+/***/ "./src/utils/get-by-class.js":
+/*!***********************************!*\
+ !*** ./src/utils/get-by-class.js ***!
+ \***********************************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: module */
+/*! CommonJS bailout: module.exports is used directly at 53:0-14 */
+/***/ (function(module) {
+
/**
* A cross-browser implementation of getElementsByClass.
* Heavily based on Dustin Diaz's function: http://dustindiaz.com/getelementsbyclass.
@@ -1103,112 +1706,93 @@ module.exports = function(el, attr) {
* @param {Boolean} single
* @api public
*/
+var getElementsByClassName = function getElementsByClassName(container, className, single) {
+ if (single) {
+ return container.getElementsByClassName(className)[0];
+ } else {
+ return container.getElementsByClassName(className);
+ }
+};
-module.exports = (function() {
- if (document.getElementsByClassName) {
- return function(container, className, single) {
- if (single) {
- return container.getElementsByClassName(className)[0];
- } else {
- return container.getElementsByClassName(className);
- }
- };
- } else if (document.querySelector) {
- return function(container, className, single) {
- className = '.' + className;
+var querySelector = function querySelector(container, className, single) {
+ className = '.' + className;
+
+ if (single) {
+ return container.querySelector(className);
+ } else {
+ return container.querySelectorAll(className);
+ }
+};
+
+var polyfill = function polyfill(container, className, single) {
+ var classElements = [],
+ tag = '*';
+ var els = container.getElementsByTagName(tag);
+ var elsLen = els.length;
+ var pattern = new RegExp('(^|\\s)' + className + '(\\s|$)');
+
+ for (var i = 0, j = 0; i < elsLen; i++) {
+ if (pattern.test(els[i].className)) {
if (single) {
- return container.querySelector(className);
+ return els[i];
} else {
- return container.querySelectorAll(className);
+ classElements[j] = els[i];
+ j++;
}
- };
- } else {
- return function(container, className, single) {
- var classElements = [],
- tag = '*';
- if (container === null) {
- container = document;
- }
- var els = container.getElementsByTagName(tag);
- var elsLen = els.length;
- var pattern = new RegExp("(^|\\s)"+className+"(\\s|$)");
- for (var i = 0, j = 0; i < elsLen; i++) {
- if ( pattern.test(els[i].className) ) {
- if (single) {
- return els[i];
- } else {
- classElements[j] = els[i];
- j++;
- }
- }
- }
- return classElements;
- };
+ }
}
-})();
-},{}],14:[function(require,module,exports){
+ return classElements;
+};
+
+module.exports = function () {
+ return function (container, className, single, options) {
+ options = options || {};
+
+ if (options.test && options.getElementsByClassName || !options.test && document.getElementsByClassName) {
+ return getElementsByClassName(container, className, single);
+ } else if (options.test && options.querySelector || !options.test && document.querySelector) {
+ return querySelector(container, className, single);
+ } else {
+ return polyfill(container, className, single);
+ }
+ };
+}();
+
+/***/ }),
+
+/***/ "./src/utils/index-of.js":
+/*!*******************************!*\
+ !*** ./src/utils/index-of.js ***!
+ \*******************************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: module */
+/*! CommonJS bailout: module.exports is used directly at 3:0-14 */
+/***/ (function(module) {
+
var indexOf = [].indexOf;
-module.exports = function(arr, obj){
+module.exports = function (arr, obj) {
if (indexOf) return arr.indexOf(obj);
- for (var i = 0; i < arr.length; ++i) {
+
+ for (var i = 0, il = arr.length; i < il; ++i) {
if (arr[i] === obj) return i;
}
+
return -1;
};
-},{}],15:[function(require,module,exports){
-/*
- * Natural Sort algorithm for Javascript - Version 0.8 - Released under MIT license
- * Author: Jim Palmer (based on chunking idea from Dave Koelle)
- */
-module.exports = function(a, b, opts) {
- var re = /(^([+\-]?(?:\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[\da-fA-F]+$|\d+)/g,
- sre = /^\s+|\s+$/g, // trim pre-post whitespace
- snre = /\s+/g, // normalize all whitespace to single ' ' character
- dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
- hre = /^0x[0-9a-f]+$/i,
- ore = /^0/,
- options = opts || {},
- i = function(s) { return options.insensitive && (''+s).toLowerCase() || ''+s; },
- // convert all to strings strip whitespace
- x = i(a) || '',
- y = i(b) || '',
- // chunk/tokenize
- xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
- yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
- // numeric, hex or date detection
- xD = parseInt(x.match(hre), 16) || (xN.length !== 1 && Date.parse(x)),
- yD = parseInt(y.match(hre), 16) || xD && y.match(dre) && Date.parse(y) || null,
- normChunk = function(s, l) {
- // normalize spaces; find floats not starting with '0', string or 0 if not defined (Clint Priest)
- return (!s.match(ore) || l == 1) && parseFloat(s) || s.replace(snre, ' ').replace(sre, '') || 0;
- },
- oFxNcL, oFyNcL;
- // first try and sort Hex codes or Dates
- if (yD) {
- if ( xD < yD ) { return -1; }
- else if ( xD > yD ) { return 1; }
- }
- // natural sorting through split numeric strings and default strings
- for(var cLoc=0, xNl = xN.length, yNl = yN.length, numS=Math.max(xNl, yNl); cLoc < numS; cLoc++) {
- oFxNcL = normChunk(xN[cLoc], xNl);
- oFyNcL = normChunk(yN[cLoc], yNl);
- // handle numeric vs string comparison - number < string - (Kyle Adams)
- if (isNaN(oFxNcL) !== isNaN(oFyNcL)) { return (isNaN(oFxNcL)) ? 1 : -1; }
- // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
- else if (typeof oFxNcL !== typeof oFyNcL) {
- oFxNcL += '';
- oFyNcL += '';
- }
- if (oFxNcL < oFyNcL) { return -1; }
- if (oFxNcL > oFyNcL) { return 1; }
- }
- return 0;
-};
+/***/ }),
+
+/***/ "./src/utils/to-array.js":
+/*!*******************************!*\
+ !*** ./src/utils/to-array.js ***!
+ \*******************************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: module */
+/*! CommonJS bailout: module.exports is used directly at 11:0-14 */
+/***/ (function(module) {
-},{}],16:[function(require,module,exports){
/**
* Source: https://github.com/timoxley/to-array
*
@@ -1219,7 +1803,6 @@ module.exports = function(a, b, opts) {
* @return {Array} Naive conversion of `collection` to a new `Array`.
* @api public
*/
-
module.exports = function toArray(collection) {
if (typeof collection === 'undefined') return [];
if (collection === null) return [null];
@@ -1228,27 +1811,210 @@ module.exports = function toArray(collection) {
if (isArray(collection)) return collection;
if (typeof collection.length != 'number') return [collection];
if (typeof collection === 'function' && collection instanceof Function) return [collection];
-
var arr = [];
- for (var i = 0; i < collection.length; i++) {
+
+ for (var i = 0, il = collection.length; i < il; i++) {
if (Object.prototype.hasOwnProperty.call(collection, i) || i in collection) {
arr.push(collection[i]);
}
}
+
if (!arr.length) return [];
return arr;
};
function isArray(arr) {
- return Object.prototype.toString.call(arr) === "[object Array]";
+ return Object.prototype.toString.call(arr) === '[object Array]';
}
-},{}],17:[function(require,module,exports){
-module.exports = function(s) {
- s = (s === undefined) ? "" : s;
- s = (s === null) ? "" : s;
+/***/ }),
+
+/***/ "./src/utils/to-string.js":
+/*!********************************!*\
+ !*** ./src/utils/to-string.js ***!
+ \********************************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: module */
+/*! CommonJS bailout: module.exports is used directly at 1:0-14 */
+/***/ (function(module) {
+
+module.exports = function (s) {
+ s = s === undefined ? '' : s;
+ s = s === null ? '' : s;
s = s.toString();
return s;
};
-},{}]},{},[1]);
+/***/ }),
+
+/***/ "./node_modules/string-natural-compare/natural-compare.js":
+/*!****************************************************************!*\
+ !*** ./node_modules/string-natural-compare/natural-compare.js ***!
+ \****************************************************************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: module */
+/*! CommonJS bailout: module.exports is used directly at 124:0-14 */
+/***/ (function(module) {
+
+"use strict";
+
+
+var alphabet;
+var alphabetIndexMap;
+var alphabetIndexMapLength = 0;
+
+function isNumberCode(code) {
+ return code >= 48 && code <= 57;
+}
+
+function naturalCompare(a, b) {
+ var lengthA = (a += '').length;
+ var lengthB = (b += '').length;
+ var aIndex = 0;
+ var bIndex = 0;
+
+ while (aIndex < lengthA && bIndex < lengthB) {
+ var charCodeA = a.charCodeAt(aIndex);
+ var charCodeB = b.charCodeAt(bIndex);
+
+ if (isNumberCode(charCodeA)) {
+ if (!isNumberCode(charCodeB)) {
+ return charCodeA - charCodeB;
+ }
+
+ var numStartA = aIndex;
+ var numStartB = bIndex;
+
+ while (charCodeA === 48 && ++numStartA < lengthA) {
+ charCodeA = a.charCodeAt(numStartA);
+ }
+ while (charCodeB === 48 && ++numStartB < lengthB) {
+ charCodeB = b.charCodeAt(numStartB);
+ }
+
+ var numEndA = numStartA;
+ var numEndB = numStartB;
+
+ while (numEndA < lengthA && isNumberCode(a.charCodeAt(numEndA))) {
+ ++numEndA;
+ }
+ while (numEndB < lengthB && isNumberCode(b.charCodeAt(numEndB))) {
+ ++numEndB;
+ }
+
+ var difference = numEndA - numStartA - numEndB + numStartB; // numA length - numB length
+ if (difference) {
+ return difference;
+ }
+
+ while (numStartA < numEndA) {
+ difference = a.charCodeAt(numStartA++) - b.charCodeAt(numStartB++);
+ if (difference) {
+ return difference;
+ }
+ }
+
+ aIndex = numEndA;
+ bIndex = numEndB;
+ continue;
+ }
+
+ if (charCodeA !== charCodeB) {
+ if (
+ charCodeA < alphabetIndexMapLength &&
+ charCodeB < alphabetIndexMapLength &&
+ alphabetIndexMap[charCodeA] !== -1 &&
+ alphabetIndexMap[charCodeB] !== -1
+ ) {
+ return alphabetIndexMap[charCodeA] - alphabetIndexMap[charCodeB];
+ }
+
+ return charCodeA - charCodeB;
+ }
+
+ ++aIndex;
+ ++bIndex;
+ }
+
+ if (aIndex >= lengthA && bIndex < lengthB && lengthA >= lengthB) {
+ return -1;
+ }
+
+ if (bIndex >= lengthB && aIndex < lengthA && lengthB >= lengthA) {
+ return 1;
+ }
+
+ return lengthA - lengthB;
+}
+
+naturalCompare.caseInsensitive = naturalCompare.i = function(a, b) {
+ return naturalCompare(('' + a).toLowerCase(), ('' + b).toLowerCase());
+};
+
+Object.defineProperties(naturalCompare, {
+ alphabet: {
+ get: function() {
+ return alphabet;
+ },
+
+ set: function(value) {
+ alphabet = value;
+ alphabetIndexMap = [];
+
+ var i = 0;
+
+ if (alphabet) {
+ for (; i < alphabet.length; i++) {
+ alphabetIndexMap[alphabet.charCodeAt(i)] = i;
+ }
+ }
+
+ alphabetIndexMapLength = alphabetIndexMap.length;
+
+ for (i = 0; i < alphabetIndexMapLength; i++) {
+ if (alphabetIndexMap[i] === undefined) {
+ alphabetIndexMap[i] = -1;
+ }
+ }
+ },
+ },
+});
+
+module.exports = naturalCompare;
+
+
+/***/ })
+
+/******/ });
+/************************************************************************/
+/******/ // The module cache
+/******/ var __webpack_module_cache__ = {};
+/******/
+/******/ // The require function
+/******/ function __webpack_require__(moduleId) {
+/******/ // Check if module is in cache
+/******/ if(__webpack_module_cache__[moduleId]) {
+/******/ return __webpack_module_cache__[moduleId].exports;
+/******/ }
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = __webpack_module_cache__[moduleId] = {
+/******/ // no module.id needed
+/******/ // no module.loaded needed
+/******/ exports: {}
+/******/ };
+/******/
+/******/ // Execute the module function
+/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
+/******/
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+/******/
+/************************************************************************/
+/******/ // module exports must be returned from runtime so entry inlining is disabled
+/******/ // startup
+/******/ // Load entry module and return exports
+/******/ return __webpack_require__("./src/index.js");
+/******/ })()
+;
+//# sourceMappingURL=list.js.map
\ No newline at end of file
diff --git a/dist/list.js.map b/dist/list.js.map
new file mode 100644
index 00000000..0583dbe3
--- /dev/null
+++ b/dist/list.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"list.js","sources":["webpack://List/./src/add-async.js","webpack://List/./src/filter.js","webpack://List/./src/fuzzy-search.js","webpack://List/./src/index.js","webpack://List/./src/item.js","webpack://List/./src/pagination.js","webpack://List/./src/parse.js","webpack://List/./src/search.js","webpack://List/./src/sort.js","webpack://List/./src/templater.js","webpack://List/./src/utils/classes.js","webpack://List/./src/utils/events.js","webpack://List/./src/utils/extend.js","webpack://List/./src/utils/fuzzy.js","webpack://List/./src/utils/get-attribute.js","webpack://List/./src/utils/get-by-class.js","webpack://List/./src/utils/index-of.js","webpack://List/./src/utils/to-array.js","webpack://List/./src/utils/to-string.js","webpack://List/./node_modules/string-natural-compare/natural-compare.js","webpack://List/webpack/bootstrap","webpack://List/webpack/startup"],"sourcesContent":["module.exports = function (list) {\n var addAsync = function (values, callback, items) {\n var valuesToAdd = values.splice(0, 50)\n items = items || []\n items = items.concat(list.add(valuesToAdd))\n if (values.length > 0) {\n setTimeout(function () {\n addAsync(values, callback, items)\n }, 1)\n } else {\n list.update()\n callback(items)\n }\n }\n return addAsync\n}\n","module.exports = function (list) {\n // Add handlers\n list.handlers.filterStart = list.handlers.filterStart || []\n list.handlers.filterComplete = list.handlers.filterComplete || []\n\n return function (filterFunction) {\n list.trigger('filterStart')\n list.i = 1 // Reset paging\n list.reset.filter()\n if (filterFunction === undefined) {\n list.filtered = false\n } else {\n list.filtered = true\n var is = list.items\n for (var i = 0, il = is.length; i < il; i++) {\n var item = is[i]\n if (filterFunction(item)) {\n item.filtered = true\n } else {\n item.filtered = false\n }\n }\n }\n list.update()\n list.trigger('filterComplete')\n return list.visibleItems\n }\n}\n","var classes = require('./utils/classes'),\n events = require('./utils/events'),\n extend = require('./utils/extend'),\n toString = require('./utils/to-string'),\n getByClass = require('./utils/get-by-class'),\n fuzzy = require('./utils/fuzzy')\n\nmodule.exports = function (list, options) {\n options = options || {}\n\n options = extend(\n {\n location: 0,\n distance: 100,\n threshold: 0.4,\n multiSearch: true,\n searchClass: 'fuzzy-search',\n },\n options\n )\n\n var fuzzySearch = {\n search: function (searchString, columns) {\n // Substract arguments from the searchString or put searchString as only argument\n var searchArguments = options.multiSearch ? searchString.replace(/ +$/, '').split(/ +/) : [searchString]\n\n for (var k = 0, kl = list.items.length; k < kl; k++) {\n fuzzySearch.item(list.items[k], columns, searchArguments)\n }\n },\n item: function (item, columns, searchArguments) {\n var found = true\n for (var i = 0; i < searchArguments.length; i++) {\n var foundArgument = false\n for (var j = 0, jl = columns.length; j < jl; j++) {\n if (fuzzySearch.values(item.values(), columns[j], searchArguments[i])) {\n foundArgument = true\n }\n }\n if (!foundArgument) {\n found = false\n }\n }\n item.found = found\n },\n values: function (values, value, searchArgument) {\n if (values.hasOwnProperty(value)) {\n var text = toString(values[value]).toLowerCase()\n\n if (fuzzy(text, searchArgument, options)) {\n return true\n }\n }\n return false\n },\n }\n\n events.bind(\n getByClass(list.listContainer, options.searchClass),\n 'keyup',\n list.utils.events.debounce(function (e) {\n var target = e.target || e.srcElement // IE have srcElement\n list.search(target.value, fuzzySearch.search)\n }, list.searchDelay)\n )\n\n return function (str, columns) {\n list.search(str, columns, fuzzySearch.search)\n }\n}\n","var naturalSort = require('string-natural-compare'),\n getByClass = require('./utils/get-by-class'),\n extend = require('./utils/extend'),\n indexOf = require('./utils/index-of'),\n events = require('./utils/events'),\n toString = require('./utils/to-string'),\n classes = require('./utils/classes'),\n getAttribute = require('./utils/get-attribute'),\n toArray = require('./utils/to-array')\n\nmodule.exports = function (id, options, values) {\n var self = this,\n init,\n Item = require('./item')(self),\n addAsync = require('./add-async')(self),\n initPagination = require('./pagination')(self)\n\n init = {\n start: function () {\n self.listClass = 'list'\n self.searchClass = 'search'\n self.sortClass = 'sort'\n self.page = 10000\n self.i = 1\n self.items = []\n self.visibleItems = []\n self.matchingItems = []\n self.searched = false\n self.filtered = false\n self.searchColumns = undefined\n self.searchDelay = 0\n self.handlers = { updated: [] }\n self.valueNames = []\n self.utils = {\n getByClass: getByClass,\n extend: extend,\n indexOf: indexOf,\n events: events,\n toString: toString,\n naturalSort: naturalSort,\n classes: classes,\n getAttribute: getAttribute,\n toArray: toArray,\n }\n\n self.utils.extend(self, options)\n\n self.listContainer = typeof id === 'string' ? document.getElementById(id) : id\n if (!self.listContainer) {\n return\n }\n self.list = getByClass(self.listContainer, self.listClass, true)\n\n self.parse = require('./parse')(self)\n self.templater = require('./templater')(self)\n self.search = require('./search')(self)\n self.filter = require('./filter')(self)\n self.sort = require('./sort')(self)\n self.fuzzySearch = require('./fuzzy-search')(self, options.fuzzySearch)\n\n this.handlers()\n this.items()\n this.pagination()\n\n self.update()\n },\n handlers: function () {\n for (var handler in self.handlers) {\n if (self[handler] && self.handlers.hasOwnProperty(handler)) {\n self.on(handler, self[handler])\n }\n }\n },\n items: function () {\n self.parse(self.list)\n if (values !== undefined) {\n self.add(values)\n }\n },\n pagination: function () {\n if (options.pagination !== undefined) {\n if (options.pagination === true) {\n options.pagination = [{}]\n }\n if (options.pagination[0] === undefined) {\n options.pagination = [options.pagination]\n }\n for (var i = 0, il = options.pagination.length; i < il; i++) {\n initPagination(options.pagination[i])\n }\n }\n },\n }\n\n /*\n * Re-parse the List, use if html have changed\n */\n this.reIndex = function () {\n self.items = []\n self.visibleItems = []\n self.matchingItems = []\n self.searched = false\n self.filtered = false\n self.parse(self.list)\n }\n\n this.toJSON = function () {\n var json = []\n for (var i = 0, il = self.items.length; i < il; i++) {\n json.push(self.items[i].values())\n }\n return json\n }\n\n /*\n * Add object to list\n */\n this.add = function (values, callback) {\n if (values.length === 0) {\n return\n }\n if (callback) {\n addAsync(values.slice(0), callback)\n return\n }\n var added = [],\n notCreate = false\n if (values[0] === undefined) {\n values = [values]\n }\n for (var i = 0, il = values.length; i < il; i++) {\n var item = null\n notCreate = self.items.length > self.page ? true : false\n item = new Item(values[i], undefined, notCreate)\n self.items.push(item)\n added.push(item)\n }\n self.update()\n return added\n }\n\n this.show = function (i, page) {\n this.i = i\n this.page = page\n self.update()\n return self\n }\n\n /* Removes object from list.\n * Loops through the list and removes objects where\n * property \"valuename\" === value\n */\n this.remove = function (valueName, value, options) {\n var found = 0\n for (var i = 0, il = self.items.length; i < il; i++) {\n if (self.items[i].values()[valueName] == value) {\n self.templater.remove(self.items[i], options)\n self.items.splice(i, 1)\n il--\n i--\n found++\n }\n }\n self.update()\n return found\n }\n\n /* Gets the objects in the list which\n * property \"valueName\" === value\n */\n this.get = function (valueName, value) {\n var matchedItems = []\n for (var i = 0, il = self.items.length; i < il; i++) {\n var item = self.items[i]\n if (item.values()[valueName] == value) {\n matchedItems.push(item)\n }\n }\n return matchedItems\n }\n\n /*\n * Get size of the list\n */\n this.size = function () {\n return self.items.length\n }\n\n /*\n * Removes all items from the list\n */\n this.clear = function () {\n self.templater.clear()\n self.items = []\n return self\n }\n\n this.on = function (event, callback) {\n self.handlers[event].push(callback)\n return self\n }\n\n this.off = function (event, callback) {\n var e = self.handlers[event]\n var index = indexOf(e, callback)\n if (index > -1) {\n e.splice(index, 1)\n }\n return self\n }\n\n this.trigger = function (event) {\n var i = self.handlers[event].length\n while (i--) {\n self.handlers[event][i](self)\n }\n return self\n }\n\n this.reset = {\n filter: function () {\n var is = self.items,\n il = is.length\n while (il--) {\n is[il].filtered = false\n }\n return self\n },\n search: function () {\n var is = self.items,\n il = is.length\n while (il--) {\n is[il].found = false\n }\n return self\n },\n }\n\n this.update = function () {\n var is = self.items,\n il = is.length\n\n self.visibleItems = []\n self.matchingItems = []\n self.templater.clear()\n for (var i = 0; i < il; i++) {\n if (is[i].matching() && self.matchingItems.length + 1 >= self.i && self.visibleItems.length < self.page) {\n is[i].show()\n self.visibleItems.push(is[i])\n self.matchingItems.push(is[i])\n } else if (is[i].matching()) {\n self.matchingItems.push(is[i])\n is[i].hide()\n } else {\n is[i].hide()\n }\n }\n self.trigger('updated')\n return self\n }\n\n init.start()\n}\n","module.exports = function (list) {\n return function (initValues, element, notCreate) {\n var item = this\n\n this._values = {}\n\n this.found = false // Show if list.searched == true and this.found == true\n this.filtered = false // Show if list.filtered == true and this.filtered == true\n\n var init = function (initValues, element, notCreate) {\n if (element === undefined) {\n if (notCreate) {\n item.values(initValues, notCreate)\n } else {\n item.values(initValues)\n }\n } else {\n item.elm = element\n var values = list.templater.get(item, initValues)\n item.values(values)\n }\n }\n\n this.values = function (newValues, notCreate) {\n if (newValues !== undefined) {\n for (var name in newValues) {\n item._values[name] = newValues[name]\n }\n if (notCreate !== true) {\n list.templater.set(item, item.values())\n }\n } else {\n return item._values\n }\n }\n\n this.show = function () {\n list.templater.show(item)\n }\n\n this.hide = function () {\n list.templater.hide(item)\n }\n\n this.matching = function () {\n return (\n (list.filtered && list.searched && item.found && item.filtered) ||\n (list.filtered && !list.searched && item.filtered) ||\n (!list.filtered && list.searched && item.found) ||\n (!list.filtered && !list.searched)\n )\n }\n\n this.visible = function () {\n return item.elm && item.elm.parentNode == list.list ? true : false\n }\n\n init(initValues, element, notCreate)\n }\n}\n","var classes = require('./utils/classes'),\n events = require('./utils/events'),\n List = require('./index')\n\nmodule.exports = function (list) {\n var isHidden = false\n\n var refresh = function (pagingList, options) {\n if (list.page < 1) {\n list.listContainer.style.display = 'none'\n isHidden = true\n return\n } else if (isHidden) {\n list.listContainer.style.display = 'block'\n }\n\n var item,\n l = list.matchingItems.length,\n index = list.i,\n page = list.page,\n pages = Math.ceil(l / page),\n currentPage = Math.ceil(index / page),\n innerWindow = options.innerWindow || 2,\n left = options.left || options.outerWindow || 0,\n right = options.right || options.outerWindow || 0\n\n right = pages - right\n pagingList.clear()\n for (var i = 1; i <= pages; i++) {\n var className = currentPage === i ? 'active' : ''\n\n //console.log(i, left, right, currentPage, (currentPage - innerWindow), (currentPage + innerWindow), className);\n\n if (is.number(i, left, right, currentPage, innerWindow)) {\n item = pagingList.add({\n page: i,\n dotted: false,\n })[0]\n if (className) {\n classes(item.elm).add(className)\n }\n item.elm.firstChild.setAttribute('data-i', i)\n item.elm.firstChild.setAttribute('data-page', page)\n } else if (is.dotted(pagingList, i, left, right, currentPage, innerWindow, pagingList.size())) {\n item = pagingList.add({\n page: '...',\n dotted: true,\n })[0]\n classes(item.elm).add('disabled')\n }\n }\n }\n\n var is = {\n number: function (i, left, right, currentPage, innerWindow) {\n return this.left(i, left) || this.right(i, right) || this.innerWindow(i, currentPage, innerWindow)\n },\n left: function (i, left) {\n return i <= left\n },\n right: function (i, right) {\n return i > right\n },\n innerWindow: function (i, currentPage, innerWindow) {\n return i >= currentPage - innerWindow && i <= currentPage + innerWindow\n },\n dotted: function (pagingList, i, left, right, currentPage, innerWindow, currentPageItem) {\n return (\n this.dottedLeft(pagingList, i, left, right, currentPage, innerWindow) ||\n this.dottedRight(pagingList, i, left, right, currentPage, innerWindow, currentPageItem)\n )\n },\n dottedLeft: function (pagingList, i, left, right, currentPage, innerWindow) {\n return i == left + 1 && !this.innerWindow(i, currentPage, innerWindow) && !this.right(i, right)\n },\n dottedRight: function (pagingList, i, left, right, currentPage, innerWindow, currentPageItem) {\n if (pagingList.items[currentPageItem - 1].values().dotted) {\n return false\n } else {\n return i == right && !this.innerWindow(i, currentPage, innerWindow) && !this.right(i, right)\n }\n },\n }\n\n return function (options) {\n var pagingList = new List(list.listContainer.id, {\n listClass: options.paginationClass || 'pagination',\n item: options.item || \"
\",\n valueNames: ['page', 'dotted'],\n searchClass: 'pagination-search-that-is-not-supposed-to-exist',\n sortClass: 'pagination-sort-that-is-not-supposed-to-exist',\n })\n\n events.bind(pagingList.listContainer, 'click', function (e) {\n var target = e.target || e.srcElement,\n page = list.utils.getAttribute(target, 'data-page'),\n i = list.utils.getAttribute(target, 'data-i')\n if (i) {\n list.show((i - 1) * page + 1, page)\n }\n })\n\n list.on('updated', function () {\n refresh(pagingList, options)\n })\n refresh(pagingList, options)\n }\n}\n","module.exports = function (list) {\n var Item = require('./item')(list)\n\n var getChildren = function (parent) {\n var nodes = parent.childNodes,\n items = []\n for (var i = 0, il = nodes.length; i < il; i++) {\n // Only textnodes have a data attribute\n if (nodes[i].data === undefined) {\n items.push(nodes[i])\n }\n }\n return items\n }\n\n var parse = function (itemElements, valueNames) {\n for (var i = 0, il = itemElements.length; i < il; i++) {\n list.items.push(new Item(valueNames, itemElements[i]))\n }\n }\n var parseAsync = function (itemElements, valueNames) {\n var itemsToIndex = itemElements.splice(0, 50) // TODO: If < 100 items, what happens in IE etc?\n parse(itemsToIndex, valueNames)\n if (itemElements.length > 0) {\n setTimeout(function () {\n parseAsync(itemElements, valueNames)\n }, 1)\n } else {\n list.update()\n list.trigger('parseComplete')\n }\n }\n\n list.handlers.parseComplete = list.handlers.parseComplete || []\n\n return function () {\n var itemsToIndex = getChildren(list.list),\n valueNames = list.valueNames\n\n if (list.indexAsync) {\n parseAsync(itemsToIndex, valueNames)\n } else {\n parse(itemsToIndex, valueNames)\n }\n }\n}\n","module.exports = function (list) {\n var item, text, columns, searchString, customSearch\n\n var prepare = {\n resetList: function () {\n list.i = 1\n list.templater.clear()\n customSearch = undefined\n },\n setOptions: function (args) {\n if (args.length == 2 && args[1] instanceof Array) {\n columns = args[1]\n } else if (args.length == 2 && typeof args[1] == 'function') {\n columns = undefined\n customSearch = args[1]\n } else if (args.length == 3) {\n columns = args[1]\n customSearch = args[2]\n } else {\n columns = undefined\n }\n },\n setColumns: function () {\n if (list.items.length === 0) return\n if (columns === undefined) {\n columns = list.searchColumns === undefined ? prepare.toArray(list.items[0].values()) : list.searchColumns\n }\n },\n setSearchString: function (s) {\n s = list.utils.toString(s).toLowerCase()\n s = s.replace(/[-[\\]{}()*+?.,\\\\^$|#]/g, '\\\\$&') // Escape regular expression characters\n searchString = s\n },\n toArray: function (values) {\n var tmpColumn = []\n for (var name in values) {\n tmpColumn.push(name)\n }\n return tmpColumn\n },\n }\n var search = {\n list: function () {\n // Extract quoted phrases \"word1 word2\" from original searchString\n // searchString is converted to lowercase by List.js\n var words = [],\n phrase,\n ss = searchString\n while ((phrase = ss.match(/\"([^\"]+)\"/)) !== null) {\n words.push(phrase[1])\n ss = ss.substring(0, phrase.index) + ss.substring(phrase.index + phrase[0].length)\n }\n // Get remaining space-separated words (if any)\n ss = ss.trim()\n if (ss.length) words = words.concat(ss.split(/\\s+/))\n for (var k = 0, kl = list.items.length; k < kl; k++) {\n var item = list.items[k]\n item.found = false\n if (!words.length) continue\n for (var i = 0, il = words.length; i < il; i++) {\n var word_found = false\n for (var j = 0, jl = columns.length; j < jl; j++) {\n var values = item.values(),\n column = columns[j]\n if (values.hasOwnProperty(column) && values[column] !== undefined && values[column] !== null) {\n var text = typeof values[column] !== 'string' ? values[column].toString() : values[column]\n if (text.toLowerCase().indexOf(words[i]) !== -1) {\n // word found, so no need to check it against any other columns\n word_found = true\n break\n }\n }\n }\n // this word not found? no need to check any other words, the item cannot match\n if (!word_found) break\n }\n item.found = word_found\n }\n },\n // Removed search.item() and search.values()\n reset: function () {\n list.reset.search()\n list.searched = false\n },\n }\n\n var searchMethod = function (str) {\n list.trigger('searchStart')\n\n prepare.resetList()\n prepare.setSearchString(str)\n prepare.setOptions(arguments) // str, cols|searchFunction, searchFunction\n prepare.setColumns()\n\n if (searchString === '') {\n search.reset()\n } else {\n list.searched = true\n if (customSearch) {\n customSearch(searchString, columns)\n } else {\n search.list()\n }\n }\n\n list.update()\n list.trigger('searchComplete')\n return list.visibleItems\n }\n\n list.handlers.searchStart = list.handlers.searchStart || []\n list.handlers.searchComplete = list.handlers.searchComplete || []\n\n list.utils.events.bind(\n list.utils.getByClass(list.listContainer, list.searchClass),\n 'keyup',\n list.utils.events.debounce(function (e) {\n var target = e.target || e.srcElement, // IE have srcElement\n alreadyCleared = target.value === '' && !list.searched\n if (!alreadyCleared) {\n // If oninput already have resetted the list, do nothing\n searchMethod(target.value)\n }\n }, list.searchDelay)\n )\n\n // Used to detect click on HTML5 clear button\n list.utils.events.bind(list.utils.getByClass(list.listContainer, list.searchClass), 'input', function (e) {\n var target = e.target || e.srcElement\n if (target.value === '') {\n searchMethod('')\n }\n })\n\n return searchMethod\n}\n","module.exports = function (list) {\n var buttons = {\n els: undefined,\n clear: function () {\n for (var i = 0, il = buttons.els.length; i < il; i++) {\n list.utils.classes(buttons.els[i]).remove('asc')\n list.utils.classes(buttons.els[i]).remove('desc')\n }\n },\n getOrder: function (btn) {\n var predefinedOrder = list.utils.getAttribute(btn, 'data-order')\n if (predefinedOrder == 'asc' || predefinedOrder == 'desc') {\n return predefinedOrder\n } else if (list.utils.classes(btn).has('desc')) {\n return 'asc'\n } else if (list.utils.classes(btn).has('asc')) {\n return 'desc'\n } else {\n return 'asc'\n }\n },\n getInSensitive: function (btn, options) {\n var insensitive = list.utils.getAttribute(btn, 'data-insensitive')\n if (insensitive === 'false') {\n options.insensitive = false\n } else {\n options.insensitive = true\n }\n },\n setOrder: function (options) {\n for (var i = 0, il = buttons.els.length; i < il; i++) {\n var btn = buttons.els[i]\n if (list.utils.getAttribute(btn, 'data-sort') !== options.valueName) {\n continue\n }\n var predefinedOrder = list.utils.getAttribute(btn, 'data-order')\n if (predefinedOrder == 'asc' || predefinedOrder == 'desc') {\n if (predefinedOrder == options.order) {\n list.utils.classes(btn).add(options.order)\n }\n } else {\n list.utils.classes(btn).add(options.order)\n }\n }\n },\n }\n\n var sort = function () {\n list.trigger('sortStart')\n var options = {}\n\n var target = arguments[0].currentTarget || arguments[0].srcElement || undefined\n\n if (target) {\n options.valueName = list.utils.getAttribute(target, 'data-sort')\n buttons.getInSensitive(target, options)\n options.order = buttons.getOrder(target)\n } else {\n options = arguments[1] || options\n options.valueName = arguments[0]\n options.order = options.order || 'asc'\n options.insensitive = typeof options.insensitive == 'undefined' ? true : options.insensitive\n }\n\n buttons.clear()\n buttons.setOrder(options)\n\n // caseInsensitive\n // alphabet\n var customSortFunction = options.sortFunction || list.sortFunction || null,\n multi = options.order === 'desc' ? -1 : 1,\n sortFunction\n\n if (customSortFunction) {\n sortFunction = function (itemA, itemB) {\n return customSortFunction(itemA, itemB, options) * multi\n }\n } else {\n sortFunction = function (itemA, itemB) {\n var sort = list.utils.naturalSort\n sort.alphabet = list.alphabet || options.alphabet || undefined\n if (!sort.alphabet && options.insensitive) {\n sort = list.utils.naturalSort.caseInsensitive\n }\n return sort(itemA.values()[options.valueName], itemB.values()[options.valueName]) * multi\n }\n }\n\n list.items.sort(sortFunction)\n list.update()\n list.trigger('sortComplete')\n }\n\n // Add handlers\n list.handlers.sortStart = list.handlers.sortStart || []\n list.handlers.sortComplete = list.handlers.sortComplete || []\n\n buttons.els = list.utils.getByClass(list.listContainer, list.sortClass)\n list.utils.events.bind(buttons.els, 'click', sort)\n list.on('searchStart', buttons.clear)\n list.on('filterStart', buttons.clear)\n\n return sort\n}\n","var Templater = function (list) {\n var createItem,\n templater = this\n\n var init = function () {\n var itemSource\n\n if (typeof list.item === 'function') {\n createItem = function (values) {\n var item = list.item(values)\n return getItemSource(item)\n }\n return\n }\n\n if (typeof list.item === 'string') {\n if (list.item.indexOf('<') === -1) {\n itemSource = document.getElementById(list.item)\n } else {\n itemSource = getItemSource(list.item)\n }\n } else {\n /* If item source does not exists, use the first item in list as\n source for new items */\n itemSource = getFirstListItem()\n }\n\n if (!itemSource) {\n throw new Error(\"The list needs to have at least one item on init otherwise you'll have to add a template.\")\n }\n\n itemSource = createCleanTemplateItem(itemSource, list.valueNames)\n\n createItem = function () {\n return itemSource.cloneNode(true)\n }\n }\n\n var createCleanTemplateItem = function (templateNode, valueNames) {\n var el = templateNode.cloneNode(true)\n el.removeAttribute('id')\n\n for (var i = 0, il = valueNames.length; i < il; i++) {\n var elm = undefined,\n valueName = valueNames[i]\n if (valueName.data) {\n for (var j = 0, jl = valueName.data.length; j < jl; j++) {\n el.setAttribute('data-' + valueName.data[j], '')\n }\n } else if (valueName.attr && valueName.name) {\n elm = list.utils.getByClass(el, valueName.name, true)\n if (elm) {\n elm.setAttribute(valueName.attr, '')\n }\n } else {\n elm = list.utils.getByClass(el, valueName, true)\n if (elm) {\n elm.innerHTML = ''\n }\n }\n }\n return el\n }\n\n var getFirstListItem = function () {\n var nodes = list.list.childNodes\n\n for (var i = 0, il = nodes.length; i < il; i++) {\n // Only textnodes have a data attribute\n if (nodes[i].data === undefined) {\n return nodes[i].cloneNode(true)\n }\n }\n return undefined\n }\n\n var getItemSource = function (itemHTML) {\n if (typeof itemHTML !== 'string') return undefined\n if (/
]/g.exec(itemHTML)) {\n var tbody = document.createElement('tbody')\n tbody.innerHTML = itemHTML\n return tbody.firstElementChild\n } else if (itemHTML.indexOf('<') !== -1) {\n var div = document.createElement('div')\n div.innerHTML = itemHTML\n return div.firstElementChild\n }\n return undefined\n }\n\n var getValueName = function (name) {\n for (var i = 0, il = list.valueNames.length; i < il; i++) {\n var valueName = list.valueNames[i]\n if (valueName.data) {\n var data = valueName.data\n for (var j = 0, jl = data.length; j < jl; j++) {\n if (data[j] === name) {\n return { data: name }\n }\n }\n } else if (valueName.attr && valueName.name && valueName.name == name) {\n return valueName\n } else if (valueName === name) {\n return name\n }\n }\n }\n\n var setValue = function (item, name, value) {\n var elm = undefined,\n valueName = getValueName(name)\n if (!valueName) return\n if (valueName.data) {\n item.elm.setAttribute('data-' + valueName.data, value)\n } else if (valueName.attr && valueName.name) {\n elm = list.utils.getByClass(item.elm, valueName.name, true)\n if (elm) {\n elm.setAttribute(valueName.attr, value)\n }\n } else {\n elm = list.utils.getByClass(item.elm, valueName, true)\n if (elm) {\n elm.innerHTML = value\n }\n }\n }\n\n this.get = function (item, valueNames) {\n templater.create(item)\n var values = {}\n for (var i = 0, il = valueNames.length; i < il; i++) {\n var elm = undefined,\n valueName = valueNames[i]\n if (valueName.data) {\n for (var j = 0, jl = valueName.data.length; j < jl; j++) {\n values[valueName.data[j]] = list.utils.getAttribute(item.elm, 'data-' + valueName.data[j])\n }\n } else if (valueName.attr && valueName.name) {\n elm = list.utils.getByClass(item.elm, valueName.name, true)\n values[valueName.name] = elm ? list.utils.getAttribute(elm, valueName.attr) : ''\n } else {\n elm = list.utils.getByClass(item.elm, valueName, true)\n values[valueName] = elm ? elm.innerHTML : ''\n }\n }\n return values\n }\n\n this.set = function (item, values) {\n if (!templater.create(item)) {\n for (var v in values) {\n if (values.hasOwnProperty(v)) {\n setValue(item, v, values[v])\n }\n }\n }\n }\n\n this.create = function (item) {\n if (item.elm !== undefined) {\n return false\n }\n item.elm = createItem(item.values())\n templater.set(item, item.values())\n return true\n }\n this.remove = function (item) {\n if (item.elm.parentNode === list.list) {\n list.list.removeChild(item.elm)\n }\n }\n this.show = function (item) {\n templater.create(item)\n list.list.appendChild(item.elm)\n }\n this.hide = function (item) {\n if (item.elm !== undefined && item.elm.parentNode === list.list) {\n list.list.removeChild(item.elm)\n }\n }\n this.clear = function () {\n /* .innerHTML = ''; fucks up IE */\n if (list.list.hasChildNodes()) {\n while (list.list.childNodes.length >= 1) {\n list.list.removeChild(list.list.firstChild)\n }\n }\n }\n\n init()\n}\n\nmodule.exports = function (list) {\n return new Templater(list)\n}\n","/**\n * Module dependencies.\n */\n\nvar index = require('./index-of')\n\n/**\n * Whitespace regexp.\n */\n\nvar re = /\\s+/\n\n/**\n * toString reference.\n */\n\nvar toString = Object.prototype.toString\n\n/**\n * Wrap `el` in a `ClassList`.\n *\n * @param {Element} el\n * @return {ClassList}\n * @api public\n */\n\nmodule.exports = function (el) {\n return new ClassList(el)\n}\n\n/**\n * Initialize a new ClassList for `el`.\n *\n * @param {Element} el\n * @api private\n */\n\nfunction ClassList(el) {\n if (!el || !el.nodeType) {\n throw new Error('A DOM element reference is required')\n }\n this.el = el\n this.list = el.classList\n}\n\n/**\n * Add class `name` if not already present.\n *\n * @param {String} name\n * @return {ClassList}\n * @api public\n */\n\nClassList.prototype.add = function (name) {\n // classList\n if (this.list) {\n this.list.add(name)\n return this\n }\n\n // fallback\n var arr = this.array()\n var i = index(arr, name)\n if (!~i) arr.push(name)\n this.el.className = arr.join(' ')\n return this\n}\n\n/**\n * Remove class `name` when present, or\n * pass a regular expression to remove\n * any which match.\n *\n * @param {String|RegExp} name\n * @return {ClassList}\n * @api public\n */\n\nClassList.prototype.remove = function (name) {\n // classList\n if (this.list) {\n this.list.remove(name)\n return this\n }\n\n // fallback\n var arr = this.array()\n var i = index(arr, name)\n if (~i) arr.splice(i, 1)\n this.el.className = arr.join(' ')\n return this\n}\n\n/**\n * Toggle class `name`, can force state via `force`.\n *\n * For browsers that support classList, but do not support `force` yet,\n * the mistake will be detected and corrected.\n *\n * @param {String} name\n * @param {Boolean} force\n * @return {ClassList}\n * @api public\n */\n\nClassList.prototype.toggle = function (name, force) {\n // classList\n if (this.list) {\n if ('undefined' !== typeof force) {\n if (force !== this.list.toggle(name, force)) {\n this.list.toggle(name) // toggle again to correct\n }\n } else {\n this.list.toggle(name)\n }\n return this\n }\n\n // fallback\n if ('undefined' !== typeof force) {\n if (!force) {\n this.remove(name)\n } else {\n this.add(name)\n }\n } else {\n if (this.has(name)) {\n this.remove(name)\n } else {\n this.add(name)\n }\n }\n\n return this\n}\n\n/**\n * Return an array of classes.\n *\n * @return {Array}\n * @api public\n */\n\nClassList.prototype.array = function () {\n var className = this.el.getAttribute('class') || ''\n var str = className.replace(/^\\s+|\\s+$/g, '')\n var arr = str.split(re)\n if ('' === arr[0]) arr.shift()\n return arr\n}\n\n/**\n * Check if class `name` is present.\n *\n * @param {String} name\n * @return {ClassList}\n * @api public\n */\n\nClassList.prototype.has = ClassList.prototype.contains = function (name) {\n return this.list ? this.list.contains(name) : !!~index(this.array(), name)\n}\n","var bind = window.addEventListener ? 'addEventListener' : 'attachEvent',\n unbind = window.removeEventListener ? 'removeEventListener' : 'detachEvent',\n prefix = bind !== 'addEventListener' ? 'on' : '',\n toArray = require('./to-array')\n\n/**\n * Bind `el` event `type` to `fn`.\n *\n * @param {Element} el, NodeList, HTMLCollection or Array\n * @param {String} type\n * @param {Function} fn\n * @param {Boolean} capture\n * @api public\n */\n\nexports.bind = function (el, type, fn, capture) {\n el = toArray(el)\n for (var i = 0, il = el.length; i < il; i++) {\n el[i][bind](prefix + type, fn, capture || false)\n }\n}\n\n/**\n * Unbind `el` event `type`'s callback `fn`.\n *\n * @param {Element} el, NodeList, HTMLCollection or Array\n * @param {String} type\n * @param {Function} fn\n * @param {Boolean} capture\n * @api public\n */\n\nexports.unbind = function (el, type, fn, capture) {\n el = toArray(el)\n for (var i = 0, il = el.length; i < il; i++) {\n el[i][unbind](prefix + type, fn, capture || false)\n }\n}\n\n/**\n * Returns a function, that, as long as it continues to be invoked, will not\n * be triggered. The function will be called after it stops being called for\n * `wait` milliseconds. If `immediate` is true, trigger the function on the\n * leading edge, instead of the trailing.\n *\n * @param {Function} fn\n * @param {Integer} wait\n * @param {Boolean} immediate\n * @api public\n */\n\nexports.debounce = function (fn, wait, immediate) {\n var timeout\n return wait\n ? function () {\n var context = this,\n args = arguments\n var later = function () {\n timeout = null\n if (!immediate) fn.apply(context, args)\n }\n var callNow = immediate && !timeout\n clearTimeout(timeout)\n timeout = setTimeout(later, wait)\n if (callNow) fn.apply(context, args)\n }\n : fn\n}\n","/*\n * Source: https://github.com/segmentio/extend\n */\n\nmodule.exports = function extend(object) {\n // Takes an unlimited number of extenders.\n var args = Array.prototype.slice.call(arguments, 1)\n\n // For each extender, copy their properties on our object.\n for (var i = 0, source; (source = args[i]); i++) {\n if (!source) continue\n for (var property in source) {\n object[property] = source[property]\n }\n }\n\n return object\n}\n","module.exports = function (text, pattern, options) {\n // Aproximately where in the text is the pattern expected to be found?\n var Match_Location = options.location || 0\n\n //Determines how close the match must be to the fuzzy location (specified above). An exact letter match which is 'distance' characters away from the fuzzy location would score as a complete mismatch. A distance of '0' requires the match be at the exact location specified, a threshold of '1000' would require a perfect match to be within 800 characters of the fuzzy location to be found using a 0.8 threshold.\n var Match_Distance = options.distance || 100\n\n // At what point does the match algorithm give up. A threshold of '0.0' requires a perfect match (of both letters and location), a threshold of '1.0' would match anything.\n var Match_Threshold = options.threshold || 0.4\n\n if (pattern === text) return true // Exact match\n if (pattern.length > 32) return false // This algorithm cannot be used\n\n // Set starting location at beginning text and initialise the alphabet.\n var loc = Match_Location,\n s = (function () {\n var q = {},\n i\n\n for (i = 0; i < pattern.length; i++) {\n q[pattern.charAt(i)] = 0\n }\n\n for (i = 0; i < pattern.length; i++) {\n q[pattern.charAt(i)] |= 1 << (pattern.length - i - 1)\n }\n\n return q\n })()\n\n // Compute and return the score for a match with e errors and x location.\n // Accesses loc and pattern through being a closure.\n\n function match_bitapScore_(e, x) {\n var accuracy = e / pattern.length,\n proximity = Math.abs(loc - x)\n\n if (!Match_Distance) {\n // Dodge divide by zero error.\n return proximity ? 1.0 : accuracy\n }\n return accuracy + proximity / Match_Distance\n }\n\n var score_threshold = Match_Threshold, // Highest score beyond which we give up.\n best_loc = text.indexOf(pattern, loc) // Is there a nearby exact match? (speedup)\n\n if (best_loc != -1) {\n score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold)\n // What about in the other direction? (speedup)\n best_loc = text.lastIndexOf(pattern, loc + pattern.length)\n\n if (best_loc != -1) {\n score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold)\n }\n }\n\n // Initialise the bit arrays.\n var matchmask = 1 << (pattern.length - 1)\n best_loc = -1\n\n var bin_min, bin_mid\n var bin_max = pattern.length + text.length\n var last_rd\n for (var d = 0; d < pattern.length; d++) {\n // Scan for the best match; each iteration allows for one more error.\n // Run a binary search to determine how far from 'loc' we can stray at this\n // error level.\n bin_min = 0\n bin_mid = bin_max\n while (bin_min < bin_mid) {\n if (match_bitapScore_(d, loc + bin_mid) <= score_threshold) {\n bin_min = bin_mid\n } else {\n bin_max = bin_mid\n }\n bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min)\n }\n // Use the result from this iteration as the maximum for the next.\n bin_max = bin_mid\n var start = Math.max(1, loc - bin_mid + 1)\n var finish = Math.min(loc + bin_mid, text.length) + pattern.length\n\n var rd = Array(finish + 2)\n rd[finish + 1] = (1 << d) - 1\n for (var j = finish; j >= start; j--) {\n // The alphabet (s) is a sparse hash, so the following line generates\n // warnings.\n var charMatch = s[text.charAt(j - 1)]\n if (d === 0) {\n // First pass: exact match.\n rd[j] = ((rd[j + 1] << 1) | 1) & charMatch\n } else {\n // Subsequent passes: fuzzy match.\n rd[j] = (((rd[j + 1] << 1) | 1) & charMatch) | (((last_rd[j + 1] | last_rd[j]) << 1) | 1) | last_rd[j + 1]\n }\n if (rd[j] & matchmask) {\n var score = match_bitapScore_(d, j - 1)\n // This match will almost certainly be better than any existing match.\n // But check anyway.\n if (score <= score_threshold) {\n // Told you so.\n score_threshold = score\n best_loc = j - 1\n if (best_loc > loc) {\n // When passing loc, don't exceed our current distance from loc.\n start = Math.max(1, 2 * loc - best_loc)\n } else {\n // Already passed loc, downhill from here on in.\n break\n }\n }\n }\n }\n // No hope for a (better) match at greater error levels.\n if (match_bitapScore_(d + 1, loc) > score_threshold) {\n break\n }\n last_rd = rd\n }\n\n return best_loc < 0 ? false : true\n}\n","/**\n * A cross-browser implementation of getAttribute.\n * Source found here: http://stackoverflow.com/a/3755343/361337 written by Vivin Paliath\n *\n * Return the value for `attr` at `element`.\n *\n * @param {Element} el\n * @param {String} attr\n * @api public\n */\n\nmodule.exports = function (el, attr) {\n var result = (el.getAttribute && el.getAttribute(attr)) || null\n if (!result) {\n var attrs = el.attributes\n var length = attrs.length\n for (var i = 0; i < length; i++) {\n if (attrs[i] !== undefined) {\n if (attrs[i].nodeName === attr) {\n result = attrs[i].nodeValue\n }\n }\n }\n }\n return result\n}\n","/**\n * A cross-browser implementation of getElementsByClass.\n * Heavily based on Dustin Diaz's function: http://dustindiaz.com/getelementsbyclass.\n *\n * Find all elements with class `className` inside `container`.\n * Use `single = true` to increase performance in older browsers\n * when only one element is needed.\n *\n * @param {String} className\n * @param {Element} container\n * @param {Boolean} single\n * @api public\n */\n\nvar getElementsByClassName = function (container, className, single) {\n if (single) {\n return container.getElementsByClassName(className)[0]\n } else {\n return container.getElementsByClassName(className)\n }\n}\n\nvar querySelector = function (container, className, single) {\n className = '.' + className\n if (single) {\n return container.querySelector(className)\n } else {\n return container.querySelectorAll(className)\n }\n}\n\nvar polyfill = function (container, className, single) {\n var classElements = [],\n tag = '*'\n\n var els = container.getElementsByTagName(tag)\n var elsLen = els.length\n var pattern = new RegExp('(^|\\\\s)' + className + '(\\\\s|$)')\n for (var i = 0, j = 0; i < elsLen; i++) {\n if (pattern.test(els[i].className)) {\n if (single) {\n return els[i]\n } else {\n classElements[j] = els[i]\n j++\n }\n }\n }\n return classElements\n}\n\nmodule.exports = (function () {\n return function (container, className, single, options) {\n options = options || {}\n if ((options.test && options.getElementsByClassName) || (!options.test && document.getElementsByClassName)) {\n return getElementsByClassName(container, className, single)\n } else if ((options.test && options.querySelector) || (!options.test && document.querySelector)) {\n return querySelector(container, className, single)\n } else {\n return polyfill(container, className, single)\n }\n }\n})()\n","var indexOf = [].indexOf\n\nmodule.exports = function(arr, obj){\n if (indexOf) return arr.indexOf(obj);\n for (var i = 0, il = arr.length; i < il; ++i) {\n if (arr[i] === obj) return i;\n }\n return -1\n}\n","/**\n * Source: https://github.com/timoxley/to-array\n *\n * Convert an array-like object into an `Array`.\n * If `collection` is already an `Array`, then will return a clone of `collection`.\n *\n * @param {Array | Mixed} collection An `Array` or array-like object to convert e.g. `arguments` or `NodeList`\n * @return {Array} Naive conversion of `collection` to a new `Array`.\n * @api public\n */\n\nmodule.exports = function toArray(collection) {\n if (typeof collection === 'undefined') return []\n if (collection === null) return [null]\n if (collection === window) return [window]\n if (typeof collection === 'string') return [collection]\n if (isArray(collection)) return collection\n if (typeof collection.length != 'number') return [collection]\n if (typeof collection === 'function' && collection instanceof Function) return [collection]\n\n var arr = [];\n for (var i = 0, il = collection.length; i < il; i++) {\n if (Object.prototype.hasOwnProperty.call(collection, i) || i in collection) {\n arr.push(collection[i])\n }\n }\n if (!arr.length) return []\n return arr\n}\n\nfunction isArray(arr) {\n return Object.prototype.toString.call(arr) === '[object Array]'\n}\n","module.exports = function (s) {\n s = s === undefined ? '' : s\n s = s === null ? '' : s\n s = s.toString()\n return s\n}\n","'use strict';\n\nvar alphabet;\nvar alphabetIndexMap;\nvar alphabetIndexMapLength = 0;\n\nfunction isNumberCode(code) {\n return code >= 48 && code <= 57;\n}\n\nfunction naturalCompare(a, b) {\n var lengthA = (a += '').length;\n var lengthB = (b += '').length;\n var aIndex = 0;\n var bIndex = 0;\n\n while (aIndex < lengthA && bIndex < lengthB) {\n var charCodeA = a.charCodeAt(aIndex);\n var charCodeB = b.charCodeAt(bIndex);\n\n if (isNumberCode(charCodeA)) {\n if (!isNumberCode(charCodeB)) {\n return charCodeA - charCodeB;\n }\n\n var numStartA = aIndex;\n var numStartB = bIndex;\n\n while (charCodeA === 48 && ++numStartA < lengthA) {\n charCodeA = a.charCodeAt(numStartA);\n }\n while (charCodeB === 48 && ++numStartB < lengthB) {\n charCodeB = b.charCodeAt(numStartB);\n }\n\n var numEndA = numStartA;\n var numEndB = numStartB;\n\n while (numEndA < lengthA && isNumberCode(a.charCodeAt(numEndA))) {\n ++numEndA;\n }\n while (numEndB < lengthB && isNumberCode(b.charCodeAt(numEndB))) {\n ++numEndB;\n }\n\n var difference = numEndA - numStartA - numEndB + numStartB; // numA length - numB length\n if (difference) {\n return difference;\n }\n\n while (numStartA < numEndA) {\n difference = a.charCodeAt(numStartA++) - b.charCodeAt(numStartB++);\n if (difference) {\n return difference;\n }\n }\n\n aIndex = numEndA;\n bIndex = numEndB;\n continue;\n }\n\n if (charCodeA !== charCodeB) {\n if (\n charCodeA < alphabetIndexMapLength &&\n charCodeB < alphabetIndexMapLength &&\n alphabetIndexMap[charCodeA] !== -1 &&\n alphabetIndexMap[charCodeB] !== -1\n ) {\n return alphabetIndexMap[charCodeA] - alphabetIndexMap[charCodeB];\n }\n\n return charCodeA - charCodeB;\n }\n\n ++aIndex;\n ++bIndex;\n }\n\n if (aIndex >= lengthA && bIndex < lengthB && lengthA >= lengthB) {\n return -1;\n }\n\n if (bIndex >= lengthB && aIndex < lengthA && lengthB >= lengthA) {\n return 1;\n }\n\n return lengthA - lengthB;\n}\n\nnaturalCompare.caseInsensitive = naturalCompare.i = function(a, b) {\n return naturalCompare(('' + a).toLowerCase(), ('' + b).toLowerCase());\n};\n\nObject.defineProperties(naturalCompare, {\n alphabet: {\n get: function() {\n return alphabet;\n },\n\n set: function(value) {\n alphabet = value;\n alphabetIndexMap = [];\n\n var i = 0;\n\n if (alphabet) {\n for (; i < alphabet.length; i++) {\n alphabetIndexMap[alphabet.charCodeAt(i)] = i;\n }\n }\n\n alphabetIndexMapLength = alphabetIndexMap.length;\n\n for (i = 0; i < alphabetIndexMapLength; i++) {\n if (alphabetIndexMap[i] === undefined) {\n alphabetIndexMap[i] = -1;\n }\n }\n },\n },\n});\n\nmodule.exports = naturalCompare;\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tif(__webpack_module_cache__[moduleId]) {\n\t\treturn __webpack_module_cache__[moduleId].exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// module exports must be returned from runtime so entry inlining is disabled\n// startup\n// Load entry module and return exports\nreturn __webpack_require__(\"./src/index.js\");\n"],"mappings":";;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;A;;;;;;;;;;;AChBA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAAA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;A;;;;;;;;;;;AC5BA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA;AAMA;AACA;AAEA;AAEA;AACA;AACA;AACA;AACA;AALA;AAUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AAjCA;AAoCA;AAIA;AACA;AAAA;AACA;AAGA;AACA;AACA;AACA;AACA;A;;;;;;;;;;;ACtEA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA;AASA;AACA;AAAA;AAAA;AAAA;AAAA;AACA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AATA;AAYA;AAEA;AACA;AAAA;AACA;AACA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AA1EA;AA6EA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AAEA;AACA;AACA;AACA;AACA;AADA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AAAA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AADA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AADA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AAEA;AACA;AACA;AACA;AACA;AADA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AADA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AAhBA;AACA;AAkBA;AACA;AAAA;AAGA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;;;;;;ACvQA;AACA;AACA;AAEA;AAEA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;;;;;;AC5DA;AAAA;AAAA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUA;AACA;AACA;AAAA;AACA;AACA;AAGA;AACA;AACA;AACA;AAFA;AACA;AAGA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAFA;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AA5BA;AA+BA;AACA;AACA;AACA;AACA;AACA;AACA;AALA;AAQA;AACA;AAAA;AAAA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;;;;;;AC5GA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;;;;;;AC9CA;AACA;AAEA;AACA;AACA;AACA;AAAA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AApCA;AAsCA;AACA;AACA;AACA;AACA;AAAA;AAAA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AA1CA;AACA;AA4CA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAIA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;;;;;;ACxIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AA3CA;AACA;AA6CA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AAAA;AAAA;AAAA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;A;;;;;;;;;;;ACxGA;AACA;AAAA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AAAA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AAEA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;;;;;;ACnMA;AACA;AACA;AAEA;AAEA;AACA;AACA;AACA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;A;;;;;;;;;;;;;;AClKA;AAAA;AAAA;AAAA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAEA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;AACA;A;;;;;;;;;;;ACpEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;;;;;;AClBA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAEA;AACA;AAAA;AAEA;AACA;AAAA;AAAA;AAEA;AAAA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AAAA;AACA;AAAA;AACA;AAEA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AAEA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;A;;;;;;;;;;;AC3HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;A;;;;;;;;;;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AAGA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;;;;;;AC/DA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AACA;A;;;;;;;;;;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;;;;;;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;;;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;AC7HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtBA;AACA;AACA;AACA;;A","sourceRoot":""}
\ No newline at end of file
diff --git a/dist/list.min.js b/dist/list.min.js
index ff939b4b..81318815 100644
--- a/dist/list.min.js
+++ b/dist/list.min.js
@@ -1 +1,2 @@
-!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;gb;b++)a.push(r.items[b].values());return a},this.add=function(a,b){if(0!==a.length){if(b)return void t(a,b);var c=[],e=!1;a[0]===d&&(a=[a]);for(var f=0,g=a.length;g>f;f++){var h=null;e=r.items.length>r.page?!0:!1,h=new s(a[f],d,e),r.items.push(h),c.push(h)}return r.update(),c}},this.show=function(a,b){return this.i=a,this.page=b,r.update(),r},this.remove=function(a,b,c){for(var d=0,e=0,f=r.items.length;f>e;e++)r.items[e].values()[a]==b&&(r.templater.remove(r.items[e],c),r.items.splice(e,1),f--,e--,d++);return r.update(),d},this.get=function(a,b){for(var c=[],d=0,e=r.items.length;e>d;d++){var f=r.items[d];f.values()[a]==b&&c.push(f)}return c},this.size=function(){return r.items.length},this.clear=function(){return r.templater.clear(),r.items=[],r},this.on=function(a,b){return r.handlers[a].push(b),r},this.off=function(a,b){var c=r.handlers[a],d=h(c,b);return d>-1&&c.splice(d,1),r},this.trigger=function(a){for(var b=r.handlers[a].length;b--;)r.handlers[a][b](r);return r},this.reset={filter:function(){for(var a=r.items,b=a.length;b--;)a[b].filtered=!1;return r},search:function(){for(var a=r.items,b=a.length;b--;)a[b].found=!1;return r}},this.update=function(){var a=r.items,b=a.length;r.visibleItems=[],r.matchingItems=[],r.templater.clear();for(var c=0;b>c;c++)a[c].matching()&&r.matchingItems.length+1>=r.i&&r.visibleItems.length0?setTimeout(function(){b(c,d,e)},1):(a.update(),d(e))};return b}},{}],3:[function(a,b,c){b.exports=function(a){return a.handlers.filterStart=a.handlers.filterStart||[],a.handlers.filterComplete=a.handlers.filterComplete||[],function(b){if(a.trigger("filterStart"),a.i=1,a.reset.filter(),void 0===b)a.filtered=!1;else{a.filtered=!0;for(var c=a.items,d=0,e=c.length;e>d;d++){var f=c[d];b(f)?f.filtered=!0:f.filtered=!1}}return a.update(),a.trigger("filterComplete"),a.visibleItems}}},{}],4:[function(a,b,c){b.exports=function(a){return function(b,c,d){var e=this;this._values={},this.found=!1,this.filtered=!1;var f=function(b,c,d){if(void 0===c)d?e.values(b,d):e.values(b);else{e.elm=c;var f=a.templater.get(e,b);e.values(f)}};this.values=function(b,c){if(void 0===b)return e._values;for(var d in b)e._values[d]=b[d];c!==!0&&a.templater.set(e,e.values())},this.show=function(){a.templater.show(e)},this.hide=function(){a.templater.hide(e)},this.matching=function(){return a.filtered&&a.searched&&e.found&&e.filtered||a.filtered&&!a.searched&&e.filtered||!a.filtered&&a.searched&&e.found||!a.filtered&&!a.searched},this.visible=function(){return e.elm&&e.elm.parentNode==a.list?!0:!1},f(b,c,d)}}},{}],5:[function(a,b,c){b.exports=function(b){var c=a("./item")(b),d=function(a){for(var b=a.childNodes,c=[],d=0,e=b.length;e>d;d++)void 0===b[d].data&&c.push(b[d]);return c},e=function(a,d){for(var e=0,f=a.length;f>e;e++)b.items.push(new c(d,a[e]))},f=function(a,c){var d=a.splice(0,50);e(d,c),a.length>0?setTimeout(function(){f(a,c)},1):(b.update(),b.trigger("parseComplete"))};return b.handlers.parseComplete=b.handlers.parseComplete||[],function(){var a=d(b.list),c=b.valueNames;b.indexAsync?f(a,c):e(a,c)}}},{"./item":4}],6:[function(a,b,c){b.exports=function(a){var b,c,d,e,f={resetList:function(){a.i=1,a.templater.clear(),e=void 0},setOptions:function(a){2==a.length&&a[1]instanceof Array?c=a[1]:2==a.length&&"function"==typeof a[1]?e=a[1]:3==a.length&&(c=a[1],e=a[2])},setColumns:function(){0!==a.items.length&&void 0===c&&(c=void 0===a.searchColumns?f.toArray(a.items[0].values()):a.searchColumns)},setSearchString:function(b){b=a.utils.toString(b).toLowerCase(),b=b.replace(/[-[\]{}()*+?.,\\^$|#]/g,"\\$&"),d=b},toArray:function(a){var b=[];for(var c in a)b.push(c);return b}},g={list:function(){for(var b=0,c=a.items.length;c>b;b++)g.item(a.items[b])},item:function(a){a.found=!1;for(var b=0,d=c.length;d>b;b++)if(g.values(a.values(),c[b]))return void(a.found=!0)},values:function(c,e){return c.hasOwnProperty(e)&&(b=a.utils.toString(c[e]).toLowerCase(),""!==d&&b.search(d)>-1)?!0:!1},reset:function(){a.reset.search(),a.searched=!1}},h=function(b){return a.trigger("searchStart"),f.resetList(),f.setSearchString(b),f.setOptions(arguments),f.setColumns(),""===d?g.reset():(a.searched=!0,e?e(d,c):g.list()),a.update(),a.trigger("searchComplete"),a.visibleItems};return a.handlers.searchStart=a.handlers.searchStart||[],a.handlers.searchComplete=a.handlers.searchComplete||[],a.utils.events.bind(a.utils.getByClass(a.listContainer,a.searchClass),"keyup",function(b){var c=b.target||b.srcElement,d=""===c.value&&!a.searched;d||h(c.value)}),a.utils.events.bind(a.utils.getByClass(a.listContainer,a.searchClass),"input",function(a){var b=a.target||a.srcElement;""===b.value&&h("")}),h}},{}],7:[function(a,b,c){b.exports=function(a){a.sortFunction=a.sortFunction||function(b,c,d){return d.desc="desc"==d.order?!0:!1,a.utils.naturalSort(b.values()[d.valueName],c.values()[d.valueName],d)};var b={els:void 0,clear:function(){for(var c=0,d=b.els.length;d>c;c++)a.utils.classes(b.els[c]).remove("asc"),a.utils.classes(b.els[c]).remove("desc")},getOrder:function(b){var c=a.utils.getAttribute(b,"data-order");return"asc"==c||"desc"==c?c:a.utils.classes(b).has("desc")?"asc":a.utils.classes(b).has("asc")?"desc":"asc"},getInSensitive:function(b,c){var d=a.utils.getAttribute(b,"data-insensitive");"false"===d?c.insensitive=!1:c.insensitive=!0},setOrder:function(c){for(var d=0,e=b.els.length;e>d;d++){var f=b.els[d];if(a.utils.getAttribute(f,"data-sort")===c.valueName){var g=a.utils.getAttribute(f,"data-order");"asc"==g||"desc"==g?g==c.order&&a.utils.classes(f).add(c.order):a.utils.classes(f).add(c.order)}}}},c=function(){a.trigger("sortStart");var c={},d=arguments[0].currentTarget||arguments[0].srcElement||void 0;d?(c.valueName=a.utils.getAttribute(d,"data-sort"),b.getInSensitive(d,c),c.order=b.getOrder(d)):(c=arguments[1]||c,c.valueName=arguments[0],c.order=c.order||"asc",c.insensitive="undefined"==typeof c.insensitive?!0:c.insensitive),b.clear(),b.setOrder(c),c.sortFunction=c.sortFunction||a.sortFunction,a.items.sort(function(a,b){var d="desc"===c.order?-1:1;return c.sortFunction(a,b,c)*d}),a.update(),a.trigger("sortComplete")};return a.handlers.sortStart=a.handlers.sortStart||[],a.handlers.sortComplete=a.handlers.sortComplete||[],b.els=a.utils.getByClass(a.listContainer,a.sortClass),a.utils.events.bind(b.els,"click",c),a.on("searchStart",b.clear),a.on("filterStart",b.clear),c}},{}],8:[function(a,b,c){var d=function(a){var b,c=this,d=function(){b=c.getItemSource(a.item),b=c.clearSourceItem(b,a.valueNames)};this.clearSourceItem=function(b,c){for(var d=0,e=c.length;e>d;d++){var f;if(c[d].data)for(var g=0,h=c[d].data.length;h>g;g++)b.setAttribute("data-"+c[d].data[g],"");else c[d].attr&&c[d].name?(f=a.utils.getByClass(b,c[d].name,!0),f&&f.setAttribute(c[d].attr,"")):(f=a.utils.getByClass(b,c[d],!0),f&&(f.innerHTML=""));f=void 0}return b},this.getItemSource=function(b){if(void 0===b){for(var c=a.list.childNodes,d=0,e=c.length;e>d;d++)if(void 0===c[d].data)return c[d].cloneNode(!0)}else{if(/^tr[\s>]/.exec(b)){var f=document.createElement("table");return f.innerHTML=b,f.firstChild}if(-1!==b.indexOf("<")){var g=document.createElement("div");return g.innerHTML=b,g.firstChild}var h=document.getElementById(a.item);if(h)return h}throw new Error("The list need to have at list one item on init otherwise you'll have to add a template.")},this.get=function(b,d){c.create(b);for(var e={},f=0,g=d.length;g>f;f++){var h;if(d[f].data)for(var i=0,j=d[f].data.length;j>i;i++)e[d[f].data[i]]=a.utils.getAttribute(b.elm,"data-"+d[f].data[i]);else d[f].attr&&d[f].name?(h=a.utils.getByClass(b.elm,d[f].name,!0),e[d[f].name]=h?a.utils.getAttribute(h,d[f].attr):""):(h=a.utils.getByClass(b.elm,d[f],!0),e[d[f]]=h?h.innerHTML:"");h=void 0}return e},this.set=function(b,d){var e=function(b){for(var c=0,d=a.valueNames.length;d>c;c++)if(a.valueNames[c].data){for(var e=a.valueNames[c].data,f=0,g=e.length;g>f;f++)if(e[f]===b)return{data:b}}else{if(a.valueNames[c].attr&&a.valueNames[c].name&&a.valueNames[c].name==b)return a.valueNames[c];if(a.valueNames[c]===b)return b}},f=function(c,d){var f,g=e(c);g&&(g.data?b.elm.setAttribute("data-"+g.data,d):g.attr&&g.name?(f=a.utils.getByClass(b.elm,g.name,!0),f&&f.setAttribute(g.attr,d)):(f=a.utils.getByClass(b.elm,g,!0),f&&(f.innerHTML=d)),f=void 0)};if(!c.create(b))for(var g in d)d.hasOwnProperty(g)&&f(g,d[g])},this.create=function(a){if(void 0!==a.elm)return!1;var d=b.cloneNode(!0);return d.removeAttribute("id"),a.elm=d,c.set(a,a.values()),!0},this.remove=function(b){b.elm.parentNode===a.list&&a.list.removeChild(b.elm)},this.show=function(b){c.create(b),a.list.appendChild(b.elm)},this.hide=function(b){void 0!==b.elm&&b.elm.parentNode===a.list&&a.list.removeChild(b.elm)},this.clear=function(){if(a.list.hasChildNodes())for(;a.list.childNodes.length>=1;)a.list.removeChild(a.list.firstChild)},d()};b.exports=function(a){return new d(a)}},{}],9:[function(a,b,c){function d(a){if(!a||!a.nodeType)throw new Error("A DOM element reference is required");this.el=a,this.list=a.classList}var e=a("./index-of"),f=/\s+/,g=Object.prototype.toString;b.exports=function(a){return new d(a)},d.prototype.add=function(a){if(this.list)return this.list.add(a),this;var b=this.array(),c=e(b,a);return~c||b.push(a),this.el.className=b.join(" "),this},d.prototype.remove=function(a){if("[object RegExp]"==g.call(a))return this.removeMatching(a);if(this.list)return this.list.remove(a),this;var b=this.array(),c=e(b,a);return~c&&b.splice(c,1),this.el.className=b.join(" "),this},d.prototype.removeMatching=function(a){for(var b=this.array(),c=0;cf;f++)void 0!==b[f]&&b[f].nodeName===b&&(c=b[f].nodeValue);return c}},{}],13:[function(a,b,c){b.exports=function(){return document.getElementsByClassName?function(a,b,c){return c?a.getElementsByClassName(b)[0]:a.getElementsByClassName(b)}:document.querySelector?function(a,b,c){return b="."+b,c?a.querySelector(b):a.querySelectorAll(b)}:function(a,b,c){var d=[],e="*";null===a&&(a=document);for(var f=a.getElementsByTagName(e),g=f.length,h=new RegExp("(^|\\s)"+b+"(\\s|$)"),i=0,j=0;g>i;i++)if(h.test(f[i].className)){if(c)return f[i];d[j]=f[i],j++}return d}}()},{}],14:[function(a,b,c){var d=[].indexOf;b.exports=function(a,b){if(d)return a.indexOf(b);for(var c=0;cr)return-1;if(r>s)return 1}for(var u=0,v=p.length,w=q.length,x=Math.max(v,w);x>u;u++){if(d=t(p[u],v),e=t(q[u],w),isNaN(d)!==isNaN(e))return isNaN(d)?1:-1;if(typeof d!=typeof e&&(d+="",e+=""),e>d)return-1;if(d>e)return 1}return 0}},{}],16:[function(a,b,c){function d(a){return"[object Array]"===Object.prototype.toString.call(a)}b.exports=function(a){if("undefined"==typeof a)return[];if(null===a)return[null];if(a===window)return[window];if("string"==typeof a)return[a];if(d(a))return a;if("number"!=typeof a.length)return[a];if("function"==typeof a&&a instanceof Function)return[a];for(var b=[],c=0;c0?setTimeout((function(){e(r,n,s)}),1):(t.update(),n(s))}}},"./src/filter.js":function(t){t.exports=function(t){return t.handlers.filterStart=t.handlers.filterStart||[],t.handlers.filterComplete=t.handlers.filterComplete||[],function(e){if(t.trigger("filterStart"),t.i=1,t.reset.filter(),void 0===e)t.filtered=!1;else{t.filtered=!0;for(var r=t.items,n=0,s=r.length;nv.page,a=new g(t[s],void 0,n),v.items.push(a),r.push(a)}return v.update(),r}m(t.slice(0),e)}},this.show=function(t,e){return this.i=t,this.page=e,v.update(),v},this.remove=function(t,e,r){for(var n=0,s=0,i=v.items.length;s-1&&r.splice(n,1),v},this.trigger=function(t){for(var e=v.handlers[t].length;e--;)v.handlers[t][e](v);return v},this.reset={filter:function(){for(var t=v.items,e=t.length;e--;)t[e].filtered=!1;return v},search:function(){for(var t=v.items,e=t.length;e--;)t[e].found=!1;return v}},this.update=function(){var t=v.items,e=t.length;v.visibleItems=[],v.matchingItems=[],v.templater.clear();for(var r=0;r=v.i&&v.visibleItems.lengthe},innerWindow:function(t,e,r){return t>=e-r&&t<=e+r},dotted:function(t,e,r,n,s,i,a){return this.dottedLeft(t,e,r,n,s,i)||this.dottedRight(t,e,r,n,s,i,a)},dottedLeft:function(t,e,r,n,s,i){return e==r+1&&!this.innerWindow(e,s,i)&&!this.right(e,n)},dottedRight:function(t,e,r,n,s,i,a){return!t.items[a-1].values().dotted&&(e==n&&!this.innerWindow(e,s,i)&&!this.right(e,n))}};return function(e){var n=new i(t.listContainer.id,{listClass:e.paginationClass||"pagination",item:e.item||"
+
\ No newline at end of file
diff --git a/docs/_includes/examples/annotated-example.html b/docs/_includes/examples/annotated-example.html
new file mode 100644
index 00000000..3c0b72e8
--- /dev/null
+++ b/docs/_includes/examples/annotated-example.html
@@ -0,0 +1,171 @@
+
+
Basic examples
+
+ Here is an example of a list with List.js applied. List.js can be used in
+ three different ways. It can be on existing HTML, it can create it's own
+ HTML or a combination of both methods.
+
+
+
+
+
+
+
+
Jonny Strömberg
+
1990
+
+
+
Jonas Arnklint
+
1985
+
+
+
Martina Elm
+
1986
+
+
+
Gustaf Lindqvist
+
1983
+
+
+
+
+
Apply List.js on existing HTML
+
+
+
<div id="users">
+
+<!-- class="search" automagically makes an input a search field. -->
+ <input class="search" placeholder="Search" />
+<!-- class="sort" automagically makes an element a sort buttons. The date-sort value decides what to sort by. -->
+ <button class="sort" data-sort="name">
+ Sort
+ </button>
+
+<!-- Child elements of container with class="list" becomes list items -->
+ <ul class="list">
+ <li>
+<!-- The innerHTML of children with class="name" becomes this items "name" value -->
+ <h3 class="name">Jonny Stromberg</h3>
+ <p class="born">1986</p>
+ </li>
+ <li>
+ <h3 class="name">Jonas Arnklint</h3>
+ <p class="born">1985</p>
+ </li>
+ <li>
+ <h3 class="name">Martina Elm</h3>
+ <p class="born">1986</p>
+ </li>
+ <li>
+ <h3 class="name">Gustaf Lindqvist</h3>
+ <p class="born">1983</p>
+ </li>
+ </ul>
+
+</div>
+
+
+
var options = {
+ valueNames: [ 'name', 'born' ]
+};
+
+var userList = new List('users', options);
+
+
+
+
Apply List.js on existing HTML and then add items
+
+
+
<div id="users">
+
+ <input class="search" placeholder="Search" />
+ <button class="sort" data-sort="name">
+ Sort
+ </button>
+
+ <ul class="list">
+<!-- This, the first element in the list, will be used as template for new items. -->
+ <li>
+ <h3 class="name">Jonny Stromberg</h3>
+ <p class="born">1986</p>
+ </li>
+ </ul>
+
+</div>
+
+
+
+
var options = {
+ valueNames: [ 'name', 'born' ]
+};
+
+// These items will be added to the list on initialization.
+var values = [
+ {
+ name: 'Jonas Arnklint',
+ born: 1985
+ },
+ {
+ name: 'Martina Elm',
+ born: 1986
+ }
+];
+
+var userList = new List('users', options, values);
+
+// It's possible to add items after list been initiated
+userList.add({
+ name: 'Gustaf Lindqvist',
+ born: 1983
+});
Using List.js is pretty much plug and play, but you can change some options if you feel like it.
+
new List(id/element, options, values);
+
+
+
+ id or element*required
+ Id the element in which the list area should be initialized. OR the actual element itself.
+
+
+
optionsObject, default: undefined
+Some of the option parameters are required at some times
+
+
+
+
valueNamesArray, default: null. *required
+If the list contains items on initialization, then this array
+has to contain the value names (class names) for the different values of
+each list item.
itemString, default: undefined
+ID to item template element or a string of HTML. Can also be a function which receives a values object and which must return the complete item's HTML as a string.
listClassString, default: "list"
+What is the class of the list-container?
+
searchClassString, default: "search"
+What is the class of the search field?
+
searchColumnsArray of strings, default: undefined
+Restrict searching to just these column names? Default is to search all columns.
+
searchDelayInt default: 0
+Delay in milliseconds after last keypress in search field before search starts. 250→750 is good for very large lists.
+
sortClassString, default: "sort"
+What is the class of the sort buttons?
+
indexAsyncBoolean, default: false
+If there are already items in the list to which the
+List.js-script is added, then should the indexing be done
+in a asynchronous way? Good for large lists (> 500 items).
+
pageInt, default: 200
+Defines how many items that should be visible at the same time. This affects
+performance.
+
iInt, default: 1
+Which item should be shown as the first one.
+
paginationBoolean, default: undefined
+Read more here.
+
+
+
valuesArray of objects, default: undefined
+Values to add to the list on initialization.
+
+
+
+
Properties
+
+
+
+
+ listContainer
+ Element
+ The element node that contains the entire list area.
+
+
+
+
+ list
+ Element
+ The element containing all items.
+
+
+
+
+ items
+ Array
+ An Array of all Item-objects in the list.
+
+
+
+
+ visibleItems
+ Array
+ The currently visible items in the list
+
+
+
+
+ matchingItems
+ Array
+ The items matching the currently active filter and search.
+
+
+
+
+ searched
+ Boolean
+ Returns true if the list is searched.
+
+
+
+
+ filtered
+ Boolean
+ Returns true if there is an active filter.
+
+
+
+
+
Methods
+
+
+
+
add(values, callback)
+ Adds one or more items to the list.
If callback is set then items are added to the list in a asynchronous way, and the
+ callback is called when all items are added. This is especially useful
+ when adding very many items (200+ or something), or if you just like the
+ asynchronous coding style.
remove(valueName, value)
+ Removes items from the list where the value named valueName has value value.
+ Returns the number of items that where removed.
sort(valueName, {
+ order: 'desc',
+ alphabet: undefined,
+ insensitive: true,
+ sortFunction: undefined
+ })
+ Sorts the list based on values the in the column named valueName.
+ The alphabet option is used when you have non-english alphabet
+ where which JavaScript don't know how to sort some characters by default.
listObj.sort('name', { order: "asc" }); // Sorts the list in abc-order based on names
+listObj.sort('name', { order: "desc" }); // Sorts the list in zxy-order based on names
+
+// Sort swedish characters correcly, case-insensitive.
+listObj.sort('name', { alphabet: "ABCDEFGHIJKLMNOPQRSTUVXYZÅÄÖabcdefghijklmnopqrstuvxyzåäö" });
+
+// Sort swedish characters correcly, case-sensitive.
+listObj.sort('name', { alphabet: "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvXxYyZzÅåÄäÖö" });
+
+// Alphabet could also be on the actual listObj via
+listObj.alphabet = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvXxYyZzÅåÄäÖö";
+
+
+
+
+
search(searchString, columns, searchFunction)
+ Searches the list
+
+
itemsInList = [
+{ id: 1, name: "Jonny Stromberg", born: 1986 }
+, { id: 2, name "Jonas Arnklint", born: 1985 }
+, { id: 3, name "Martina Elm", born: 1986 }
+, { id: 4, name "Gustaf Lindqvist", born: 1983 }
+, { id: 5, name "Jonny Strandberg", born: 1990 }
+];
+
+listObj.search('Jonny'); // Only items with name Jonny are shown (also returns these items)
+
+listObj.search(); // Show all items in list
+
+listObj.search('Jonny', ['name']); // Only search in the 'name' column
+
+
Space-separated words match in any order using logical AND. Surround a phrase in quotes for exact matches:
+
+
listObj.search('Jon 198'); // Items that match Jon AND 198
+
+listObj.search('"Jonny S" 1990'); // Items that match "Jonny S" AND 1990
+
+
Optionally your own search function can be used:
+
+
listObj.search('Jonny', searchFunction); // Custom search for Jonny
+
+listObj.search('Jonny', ['name'], searchFunction); // Custom search in the 'name' column
+
+function searchFunction(searchString, columns) {
+ for (var k = 0, kl = listObj.items.length; k < kl; k++) {
+ listObj.items[k].found = false;
+ // Insert your custom search logic here, set found = true
+
+ }
+};
+
+
+
+
clear()
+ Removes all items from the list
+
+
+
filter(filterFunction)
+
+
itemsInList = [
+{ id: 1, name: "Jonny" }
+, { id: 2, name "Gustaf" }
+, { id: 3, name "Jonas" }
+];
+
+listObj.filter(function(item) {
+if (item.values().id > 1) {
+ return true;
+} else {
+ return false;
+}
+}); // Only items with id > 1 are shown in list
+
+listObj.filter(); // Remove all filters
+
+
+
+
size()
+ Returns the size of the list.
+
+
+
show(i, page)
+ Shows page number of items from i. Use for paging etc.
update()
+ Updates the current state of the list. Meaning that if you for instance
+ hides some items with the itemObj.hide() method then you have to call listObj.update()
+ if you want the paging to update.
+
+
+
reIndex()
+ Re-index list from HTML. Good to use if the HTML has been changed by something
+ else than List.js.
on(event, callback)
+ Execute callback when list have been updated (triggered by update(), which is used by a lot of methods). Use updated as the event.
",valueNames:["page","dotted"],searchClass:"pagination-search-that-is-not-supposed-to-exist",sortClass:"pagination-sort-that-is-not-supposed-to-exist"});s.bind(n.listContainer,"click",(function(e){var r=e.target||e.srcElement,n=t.utils.getAttribute(r,"data-page"),s=t.utils.getAttribute(r,"data-i");s&&t.show((s-1)*n+1,n)})),t.on("updated",(function(){r(n,e)})),r(n,e)}}},"./src/parse.js":function(t,e,r){t.exports=function(t){var e=r("./src/item.js")(t),n=function(r,n){for(var s=0,i=r.length;s0?setTimeout((function(){e(r,s)}),1):(t.update(),t.trigger("parseComplete"))};return t.handlers.parseComplete=t.handlers.parseComplete||[],function(){var e=function(t){for(var e=t.childNodes,r=[],n=0,s=e.length;n]/g.exec(t)){var e=document.createElement("tbody");return e.innerHTML=t,e.firstElementChild}if(-1!==t.indexOf("<")){var r=document.createElement("div");return r.innerHTML=t,r.firstElementChild}}},a=function(e,r,n){var s=void 0,i=function(e){for(var r=0,n=t.valueNames.length;r=1;)t.list.removeChild(t.list.firstChild)},function(){var r;if("function"!=typeof t.item){if(!(r="string"==typeof t.item?-1===t.item.indexOf("<")?document.getElementById(t.item):i(t.item):s()))throw new Error("The list needs to have at least one item on init otherwise you'll have to add a template.");r=n(r,t.valueNames),e=function(){return r.cloneNode(!0)}}else e=function(e){var r=t.item(e);return i(r)}}()};t.exports=function(t){return new e(t)}},"./src/utils/classes.js":function(t,e,r){var n=r("./src/utils/index-of.js"),s=/\s+/;Object.prototype.toString;function i(t){if(!t||!t.nodeType)throw new Error("A DOM element reference is required");this.el=t,this.list=t.classList}t.exports=function(t){return new i(t)},i.prototype.add=function(t){if(this.list)return this.list.add(t),this;var e=this.array();return~n(e,t)||e.push(t),this.el.className=e.join(" "),this},i.prototype.remove=function(t){if(this.list)return this.list.remove(t),this;var e=this.array(),r=n(e,t);return~r&&e.splice(r,1),this.el.className=e.join(" "),this},i.prototype.toggle=function(t,e){return this.list?(void 0!==e?e!==this.list.toggle(t,e)&&this.list.toggle(t):this.list.toggle(t),this):(void 0!==e?e?this.add(t):this.remove(t):this.has(t)?this.remove(t):this.add(t),this)},i.prototype.array=function(){var t=(this.el.getAttribute("class")||"").replace(/^\s+|\s+$/g,"").split(s);return""===t[0]&&t.shift(),t},i.prototype.has=i.prototype.contains=function(t){return this.list?this.list.contains(t):!!~n(this.array(),t)}},"./src/utils/events.js":function(t,e,r){var n=window.addEventListener?"addEventListener":"attachEvent",s=window.removeEventListener?"removeEventListener":"detachEvent",i="addEventListener"!==n?"on":"",a=r("./src/utils/to-array.js");e.bind=function(t,e,r,s){for(var o=0,l=(t=a(t)).length;o32)return!1;var a=n,o=function(){var t,r={};for(t=0;t=p;b--){var j=o[t.charAt(b-1)];if(C[b]=0===m?(C[b+1]<<1|1)&j:(C[b+1]<<1|1)&j|(v[b+1]|v[b])<<1|1|v[b+1],C[b]&d){var x=l(m,b-1);if(x<=u){if(u=x,!((c=b-1)>a))break;p=Math.max(1,2*a-c)}}}if(l(m+1,a)>u)break;v=C}return!(c<0)}},"./src/utils/get-attribute.js":function(t){t.exports=function(t,e){var r=t.getAttribute&&t.getAttribute(e)||null;if(!r)for(var n=t.attributes,s=n.length,i=0;i=48&&t<=57}function i(t,e){for(var i=(t+="").length,a=(e+="").length,o=0,l=0;o=i&&l=a?-1:l>=a&&o=i?1:i-a}i.caseInsensitive=i.i=function(t,e){return i((""+t).toLowerCase(),(""+e).toLowerCase())},Object.defineProperties(i,{alphabet:{get:function(){return e},set:function(t){r=[];var s=0;if(e=t)for(;sFuzzy search
+
+
The difference between Fuzzy Search and List.js default search
+
+
The default search will conduct a time efficient search for an exact match in the content searched, while the fuzzy search will render results depending on if they are included anywhere in the content.
All options are optional. Simplest implementation is:
+
new List(id, { fuzzySearch: options });
+
+
+ searchClassString, default: fuzzy-search
+ What is the class of the search field?
+
+
+ locationInt, default: 0
+ Approximately where in the text is the pattern expected to be found?
+
+
+ distanceInt, default: 100
+ Determines how close the match must be to the fuzzy location (specified above). An exact letter match which is ‘distance’ characters away from the fuzzy location would score as a complete mismatch. A distance of 0 requires the match be at the exact location specified, a threshold of 1000 would require a perfect match to be within 800 characters of the fuzzy location to be found using a 0.8 threshold.
+
+
+ thresholdInt, default: 0.4
+ At what point does the match algorithm give up. A threshold of 0.0 requires a perfect match (of both letters and location), a threshold of 1.0 would match anything.
+
+
+ multiSearchBoolean, default: true
+ Subtract arguments from the searchString or put searchString as only argument
+
diff --git a/docs/docs/item-api.html b/docs/docs/item-api.html
new file mode 100644
index 00000000..2cadf428
--- /dev/null
+++ b/docs/docs/item-api.html
@@ -0,0 +1,77 @@
+---
+layout: default
+title: Item API
+---
+
+
+Item API
+
+
These methods are available for all Items that are returned by
+the list.
+
+
+Properties
+
+
+
+ elmElement
+ The actual item DOM element
+
+
+ _valuesArray
+ Direct access to the item's values. Simplifies debugging. Note: Always use item.values() when interacting with the values.
+
+
+
+
Methods
+
+
+
+
values(newValues)
+
+
+
+ newValuesoptional
+ If variable newValues are present the new values replaces the current item values
+ and updates the list.
+ If newValues are not present, the function returns the current values.
+
+ hide()
+ Hides the item (removes the element from the list, and then when its shown it's appended again. The element will thereby change position in the list. A bug, but a good solution is yet to be found.)
+
+
+
+
+ matching()Boolean
+ Returns boolean. True if the item matches the current filter and search. Visible items
+ always matches, but matching items are not always visible.
+
+
+
+
+ visible()Boolean
+ Returns boolean. True if the item is visible. Visible items
+ always matches, but matching items are not always visible.
+
+ Note: The pagination plugin is
+ deprecated since v1.5.0, it's now bundled into List.js. Read the
+ old docs here.
+
+
+
Basic example
+
<div id="listId">
+ <ul class="list">
+ // A bunch of items
+ </ul>
+ <ul class="pagination"></ul>
+</div>
+
+<script>
+ var options = {
+ valueNames: [ 'name', 'category' ],
+ page: 3,
+ pagination: true
+ };
+
+ var listObj = new List('listId', options);
+</script>
+
+
+
+
+
Options
+
+
+ paginationClassString, default: “pagination”
+ The class that defines which ul that should contain the pagination (must be inside the list container)
+
+
+ innerWindowInt, default: 2
+ How many pages should be visible on each side of the current page.
+ innerWindow: 2 … 3 4 5 6 7 …
+ innerWindow: 1 … 4 5 6 …
+
+
+ outerWindowInt, default: 0
+ How many pages should be visible on from the beginning and from the end of the pagination.
+ outerWindow: 0 … 3 4 5 6 7…
+ outerWindow: 2 1 2 … 4 5 6 7 8 … 11 12
+
+
+ leftInt, default: 0
+ Same as outerWindow but only from left.
+ outerWindow: 2 and left: 11 … 4 5 6 7 8 … 11 12
+
+
+ rightInt, default: 0
+ Same as left but from right.
+
+
+ itemString, default <li><a class='page' href='#'></a></li>
+ Template for the pagination items.
+
+
+
+
Notice
+
The number of items at each page are decided by the List.js own property page. To set this just add page: Number to the option object sent into the List.js constructor (as been done in both of the examples at this page).
+ A plugin namned Awesome Thing have to be in a JavaScript file namned list.awesomething.js(no dash, camelcase or anything)
+ and the function/class have to be namned ListAwesomeThing(camelcase but no dash anything else).
+
+
The plugin object must contain an init method.
+
The plugin object must contain an name attribute that defaults to the plugin name.
The difference between Fuzzy Search and List.js default search
+
+
The default search will conduct a time efficient search for an exact match in the content searched, while the fuzzy search will render results depending on if they are included anywhere in the content.
All options are optional. Simplest implementation is:
+
plugins: [ ListFuzzySearch() ]
+
+
+ locationInt, default: 0
+ Approximately where in the text is the pattern expected to be found?
+
+
+ distanceInt, default: 100
+ Determines how close the match must be to the fuzzy location (specified above). An exact letter match which is ‘distance’ characters away from the fuzzy location would score as a complete mismatch. A distance of 0 requires the match be at the exact location specified, a threshold of 1000 would require a perfect match to be within 800 characters of the fuzzy location to be found using a 0.8 threshold.
+
+
+ thresholdInt, default: 0.4
+ At what point does the match algorithm give up. A threshold of 0.0 requires a perfect match (of both letters and location), a threshold of 1.0 would match anything.
+
+
+ multiSearchBoolean, default: true
+ Subtract arguments from the searchString or put searchString as only argument
+
+
+
+
A big thanks to LuukvE who made a commit from which I could create this Fuzzy Search plugin.
diff --git a/docs/docs/plugins/index.html b/docs/docs/plugins/index.html
new file mode 100755
index 00000000..4e8c8910
--- /dev/null
+++ b/docs/docs/plugins/index.html
@@ -0,0 +1,38 @@
+---
+layout: default
+title: Using Plugins
+---
+
+
Using plugins
+
+
Getting started
+
To use a plugin you need two things:
+
+
Include the plugins .js-file at the page.
+
+
Include it when you instantiate List.js
+
new List('list-id', {
+ plugins: [ ListPagination(), NameOfOtherPlugin(options) ]
+});
+
+
+
+
Naming and accessing plugins
+
It is also possible to add options and load multiple instances of the same plugins (if the plugin itself allows it).
+
+ If the property name is added in the plugin option parameter does the plugin become
+ accessible through listObj.namePropertyValue.This is useful when having multiple instances of the same plugin.
+
+ nameString, default: “pagination”
+ Default option for all plugins. Defines how to access the plugin from the list object listObj.pluginName.
+
+
+ paginationClassString, default: “pagination”
+ The class that defines which ul that should contain the pagination (must be inside the list container)
+
+
+ innerWindowInt, default: 2
+ How many pages should be visible on each side of the current page.
+ innerWindow: 2 … 3 4 5 6 7 …
+ innerWindow: 1 … 4 5 6 …
+
+
+ outerWindowInt, default: 0
+ How many pages should be visible on from the beginning and from the end of the pagination.
+ outerWindow: 0 … 3 4 5 6 7…
+ outerWindow: 2 1 2 … 4 5 6 7 8 … 11 12
+
+
+ leftInt, default: 0
+ Same as outerWindow but only from left.
+ outerWindow: 2 and left: 11 … 4 5 6 7 8 … 11 12
+
+
+ rightInt, default: 0
+ Same as left but from right.
+
+
+
+
Notice
+
The number of items at each page are decided by the List.js own property page. To set this just add page: Number to the option object sent into the List.js constructor (as been done in both of the examples at this page).
It is easy to add search input and sort buttons with just a few classes and attributes in your HTML. ‘Automagical’ because List.js registers the event handlers, searches/sorts and updates the list for you:
+
+
+Searching
+
+
+
+
+ classString. *required
+ The default class search is how List.js finds your writable search field. If you change it also set options.searchClass.
+
+ Alternatively, using fuzzy-search here will switch to the Fuzzy Search function.
+
+
+
+
+ typeString. *required
+ The default input type search is similar to using text, but web browsers may render it slightly differently: see https://developer.mozilla.org/.../input/search. Either type will work with List.js.
+
classString. *required
+ The default class sort is how List.js finds clickable sort buttons. If you change it also set options.sortClass.
+
+
+
+
+ data-sortString. *required
+ This attribute on a clickable sort button should match the column name passed to List.js in options.valueNames.
+
+
+
+
+ data-orderString
+ Set to asc or desc to enforce that sorting order for a column. The user won't be able to change the order, and any data-default-order attribute is ignored.
+
+
+
+
+ data-default-orderString, default: "asc"
+ Set to desc to change the initial sorting order for a column. Subsequent clicks will toggle the sorting order between ascending/descending, as usual.
+
+
+
+
+ data-insensitiveBoolean, default: true
+ Set to false for case-sensitive sorting of that column.
+
+
+
+
+
+Sort by:
+<span class='sort' data-sort='name'>Name</span> or
+<span class='sort' data-sort='born' data-default-order='desc'>Born in Year</span> or
+<span class='sort' data-sort='city'>City</span>
+
+
+
The CSS classes asc and desc are added when a sort button is clicked on, so List.js can show which column is currently sorted. For example, using this CSS sets a yellow background with ⬆ or ⬇ added after the button text:
+ Tiny, invisible and simple, yet powerful and incredibly fast vanilla JavaScript
+ that adds search, sort, filters and flexibility
+ to plain HTML lists, tables, or anything.
+
+
+
+
+{% include author.html %}
+
+{% include examples/annotated-example.html %}
+
+
diff --git a/docs/overview/index.html b/docs/overview/index.html
new file mode 100644
index 00000000..8c9f161b
--- /dev/null
+++ b/docs/overview/index.html
@@ -0,0 +1,36 @@
+---
+layout: default
+title: TL;DR / Features
+---
+
+
TL;DR
+
+
Perfect library for adding search, sort, filters and flexibility to tables, lists and various HTML elements. Built to be invisible and work on existing HTML.
+
+
Core idea
+
+
Simple and invisible
+
Easy to apply to existing HTML
+
No dependencies
+
Fast
+
Tiny (5KB minified&gzip)
+
Handle thousands of items
+
+
+
Features
+
+
Works both lists, tables and almost anything else. E.g. <div>,<ul>,<table>, etc.
Anna3043'
- $(list.list).html(newHtml);
- list.reIndex();
- expect(list.toJSON()).to.eql([
- { name: "Sven", born: '2013' },
- { name: "Anna", born: '3043' }
- ]);
- });
-});
diff --git a/test/test.search-filter.js b/test/test.search-filter.js
deleted file mode 100644
index 3b9af3ed..00000000
--- a/test/test.search-filter.js
+++ /dev/null
@@ -1,66 +0,0 @@
-describe('Search and filter', function() {
-
- var list, jonny, martina, angelica, sebastian, imma, hasse;
-
- before(function() {
- list = fixture.list(['name', 'born'], fixture.all);
-
- jonny = list.get('name', 'Jonny Strömberg')[0];
- martina = list.get('name', 'Martina Elm')[0];
- angelica = list.get('name', 'Angelica Abraham')[0];
- sebastian = list.get('name', 'Sebastian Höglund')[0];
- imma = list.get('name', 'Imma Grafström')[0];
- hasse = list.get('name', 'Hasse Strömberg')[0];
- });
-
- after(function() {
- fixture.removeList();
- });
-
- afterEach(function() {
- list.search();
- list.filter();
- });
-
- describe('Search with filter', function() {
- it('should find everyone born 1986', function() {
- list.filter(function(item) {
- return (item.values().born == '1986');
- });
- expect(list.matchingItems.length).to.equal(3);
- expect(jonny.matching()).to.be(true);
- expect(martina.matching()).to.be(true);
- expect(angelica.matching()).to.be(true);
- expect(sebastian.matching()).to.be(false);
- expect(imma.matching()).to.be(false);
- expect(hasse.matching()).to.be(false);
- });
- it('should find everyone born 1986 and containes "ö"', function() {
- list.filter(function(item) {
- return (item.values().born == '1986');
- });
- list.search('ö');
- expect(list.matchingItems.length).to.equal(1);
- expect(jonny.matching()).to.be(true);
- expect(martina.matching()).to.be(false);
- expect(angelica.matching()).to.be(false);
- expect(sebastian.matching()).to.be(false);
- expect(imma.matching()).to.be(false);
- expect(hasse.matching()).to.be(false);
- });
- it('should find everyone with a "ö"', function() {
- list.filter(function(item) {
- return (item.values().born == '1986');
- });
- list.search('ö');
- list.filter();
- expect(list.matchingItems.length).to.equal(4);
- expect(jonny.matching()).to.be(true);
- expect(martina.matching()).to.be(false);
- expect(angelica.matching()).to.be(false);
- expect(sebastian.matching()).to.be(true);
- expect(imma.matching()).to.be(true);
- expect(hasse.matching()).to.be(true);
- });
- });
-});
diff --git a/test/test.search.js b/test/test.search.js
deleted file mode 100644
index c98fc530..00000000
--- a/test/test.search.js
+++ /dev/null
@@ -1,148 +0,0 @@
-describe('Search', function() {
-
- var list, jonny, martina, angelica, sebastian, imma, hasse;
-
- beforeEach(function() {
- list = fixture.list(['name', 'born'], fixture.all);
-
- jonny = list.get('name', 'Jonny Strömberg')[0];
- martina = list.get('name', 'Martina Elm')[0];
- angelica = list.get('name', 'Angelica Abraham')[0];
- sebastian = list.get('name', 'Sebastian Höglund')[0];
- imma = list.get('name', 'Imma Grafström')[0];
- hasse = list.get('name', 'Hasse Strömberg')[0];
- });
-
- afterEach(function() {
- fixture.removeList();
- });
-
- describe('Case-sensitive', function() {
- it('should not be case-sensitive', function() {
- var result = list.search('jonny');
- expect(result.length).to.equal(1);
- expect(result[0]).to.eql(jonny);
- });
- });
-
- describe('Number of results', function() {
- it('should find jonny, martina, angelice', function() {
- var result = list.search('1986');
- expect(result.length).to.equal(3); // 3!!
- expect(jonny.matching()).to.be(true);
- expect(martina.matching()).to.be(true);
- expect(angelica.matching()).to.be(true);
- expect(sebastian.matching()).to.be(false);
- expect(imma.matching()).to.be(false);
- expect(hasse.matching()).to.be(false);
- });
- it('should find all with utf-8 char ö', function() {
- var result = list.search('ö');
- expect(result.length).to.equal(4); // 4!!
- expect(jonny.matching()).to.be(true);
- expect(martina.matching()).to.be(false);
- expect(angelica.matching()).to.be(false);
- expect(sebastian.matching()).to.be(true);
- expect(imma.matching()).to.be(true);
- expect(hasse.matching()).to.be(true);
- });
- it('should not break with weird searches', function() {
- expect(list.search).withArgs(undefined).to.not.throwException();
- expect(list.search).withArgs(null).to.not.throwException();
- expect(list.search).withArgs(0).to.not.throwException();
- expect(list.search).withArgs(function() {}).to.not.throwException();
- expect(list.search).withArgs({ foo: "bar" }).to.not.throwException();
- });
- it('should not break with weird values', function() {
- jonny.values({ name: undefined });
- martina.values({ name: null });
- angelica.values({ name: 0 });
- sebastian.values({ name: function() {} });
- imma.values({ name: { foo: "bar" } });
-
- expect(list.search).withArgs("jonny").to.not.throwException();
- expect(list.search).withArgs(undefined).to.not.throwException();
- expect(list.search).withArgs(null).to.not.throwException();
- expect(list.search).withArgs(0).to.not.throwException();
- expect(list.search).withArgs(function() {}).to.not.throwException();
- expect(list.search).withArgs({ foo: "bar" }).to.not.throwException();
- });
- });
-
-
- describe('Default search columns', function() {
- it('should find in the default match column', function() {
- list.searchColumns = ['name'];
- var result = list.search('jonny');
- expect(result.length).to.equal(1);
- expect(result[0]).to.eql(jonny);
- });
- it('should not find in the default match column', function() {
- list.searchColumns = ['born'];
- var result = list.search('jonny');
- expect(result.length).to.equal(0);
- });
- });
-
-
- describe('Specfic columns', function() {
- it('should find match in column', function() {
- var result = list.search('jonny', [ 'name' ]);
- expect(result.length).to.equal(1);
- expect(result[0]).to.eql(jonny);
- });
- it('should not find match in column', function() {
- var result = list.search('jonny', [ 'born' ]);
- expect(result.length).to.equal(0);
- });
- it('should find match in column', function() {
- var result = list.search('jonny', [ 'name' ]);
- expect(result.length).to.equal(1);
- expect(result[0]).to.eql(jonny);
- });
- it('should not find match in column', function() {
- var result = list.search('jonny', [ 'born' ]);
- expect(result.length).to.equal(0);
- });
- it('should work with columns that does not exist', function() {
- var result = list.search('jonny', [ 'pet' ]);
- expect(result.length).to.equal(0);
- });
- });
-
- describe('Custom search function', function() {
- var customSearchFunction = function(searchString, columns) {
- for (var k = 0, kl = list.items.length; k < kl; k++) {
- if (list.items[k].values().born > 1985) {
- list.items[k].found = true;
- }
- }
- };
- it('should use custom function in third argument', function() {
- var result = list.search('jonny', [ 'name' ], customSearchFunction);
- expect(result.length).to.equal(4);
- });
- it('should use custom function in second argument', function() {
- var result = list.search('jonny', customSearchFunction);
- expect(result.length).to.equal(4);
- });
- });
- //
- // describe('Special characters', function() {
- // it('should escape and handle special characters', function() {
- // list.add([
- // { name: 'Jonny&Jabba' },
- // { name: 'Luke' },
- // { name: '"Chewie"' },
- // { name: "'Ewok'" }
- // ]);
- // var result = list.search('Leia');
- // console.log(result);
- // expect(result.length).to.equal(1);
- // var result = list.search('<');
- // console.log(result);
- // expect(result.length).to.equal(1);
- // });
- // });
-});
diff --git a/test/test.show.js b/test/test.show.js
deleted file mode 100644
index eb42ddb0..00000000
--- a/test/test.show.js
+++ /dev/null
@@ -1,208 +0,0 @@
-describe('Show', function() {
-
- var list, a, b, c, d, e, f;
-
- before(function() {
- list = fixture.list(['id', 'id2'], [
- { id: "1", id2: "a" },
- { id: "2", id2: "a" },
- { id: "3", id2: "b" },
- { id: "4", id2: "b" },
- { id: "5", id2: "bc" },
- { id: "6", id2: "bc" }
- ]);
- a = list.get('id', '1')[0];
- b = list.get('id', '2')[0];
- c = list.get('id', '3')[0];
- d = list.get('id', '4')[0];
- e = list.get('id', '5')[0];
- f = list.get('id', '6')[0];
- });
-
- after(function() {
- fixture.removeList();
- });
-
- afterEach(function() {
- list.filter();
- list.show(1, 200);
- });
-
- describe('Basics', function() {
- it('should be 1, 2', function() {
- list.show(1,2);
- expect(list.visibleItems.length).to.equal(2);
- expect(a.visible()).to.be(true);
- expect(b.visible()).to.be(true);
- expect(c.visible()).to.be(false);
- expect(d.visible()).to.be(false);
- expect(e.visible()).to.be(false);
- expect(f.visible()).to.be(false);
- });
- it('should show item 6', function() {
- list.show(6,2);
- expect(list.visibleItems.length).to.equal(1);
- expect(a.visible()).to.be(false);
- expect(b.visible()).to.be(false);
- expect(c.visible()).to.be(false);
- expect(d.visible()).to.be(false);
- expect(e.visible()).to.be(false);
- expect(f.visible()).to.be(true);
- });
- it('should show item 1, 2, 3, 4, 5, 6', function() {
- list.show(1,200);
- expect(list.visibleItems.length).to.equal(6);
- expect(a.visible()).to.be(true);
- expect(b.visible()).to.be(true);
- expect(c.visible()).to.be(true);
- expect(d.visible()).to.be(true);
- expect(e.visible()).to.be(true);
- expect(f.visible()).to.be(true);
- });
- it('should show item 3, 4, 5', function() {
- list.show(3,3);
- expect(list.visibleItems.length).to.equal(3);
- expect(a.visible()).to.be(false);
- expect(b.visible()).to.be(false);
- expect(c.visible()).to.be(true);
- expect(d.visible()).to.be(true);
- expect(e.visible()).to.be(true);
- expect(f.visible()).to.be(false);
- });
- it('should show item 5, 6', function() {
- list.show(5,3);
- expect(list.visibleItems.length).to.equal(2);
- expect(a.visible()).to.be(false);
- expect(b.visible()).to.be(false);
- expect(c.visible()).to.be(false);
- expect(d.visible()).to.be(false);
- expect(e.visible()).to.be(true);
- expect(f.visible()).to.be(true);
- });
- });
-
- describe('Search', function() {
- afterEach(function() {
- list.search();
- });
- it('should show 3, 4', function() {
- list.search('b');
- list.show(1,2);
- expect(list.visibleItems.length).to.equal(2);
- expect(a.visible()).to.be(false);
- expect(b.visible()).to.be(false);
- expect(c.visible()).to.be(true);
- expect(d.visible()).to.be(true);
- expect(e.visible()).to.be(false);
- expect(f.visible()).to.be(false);
- });
- it('should show item 3,4,5,6', function() {
- list.search('b');
- list.show(1,4);
- expect(list.visibleItems.length).to.equal(4);
- expect(a.visible()).to.be(false);
- expect(b.visible()).to.be(false);
- expect(c.visible()).to.be(true);
- expect(d.visible()).to.be(true);
- expect(e.visible()).to.be(true);
- expect(f.visible()).to.be(true);
- });
- it('should not show any items but match two', function() {
- list.search('a');
- list.show(3,2);
- expect(list.visibleItems.length).to.equal(0);
- expect(list.matchingItems.length).to.equal(2);
- expect(a.visible()).to.be(false);
- expect(b.visible()).to.be(false);
- expect(c.visible()).to.be(false);
- expect(d.visible()).to.be(false);
- expect(e.visible()).to.be(false);
- expect(f.visible()).to.be(false);
- });
- });
-
- describe('Filter', function() {
- afterEach(function() {
- list.filter();
- });
- it('should show 3, 4', function() {
- list.filter(function(item) {
- return (item.values().id2 == 'b');
- });
- list.show(1,2);
- expect(list.visibleItems.length).to.equal(2);
- expect(list.matchingItems.length).to.equal(2);
- expect(a.visible()).to.be(false);
- expect(b.visible()).to.be(false);
- expect(c.visible()).to.be(true);
- expect(d.visible()).to.be(true);
- expect(e.visible()).to.be(false);
- expect(f.visible()).to.be(false);
- });
- it('should show item 3,4,5,6', function() {
- list.filter(function(item) {
- return (item.values().id2 == 'bc');
- });
- list.show(1,4);
- expect(list.visibleItems.length).to.equal(2);
- expect(list.matchingItems.length).to.equal(2);
- expect(a.visible()).to.be(false);
- expect(b.visible()).to.be(false);
- expect(c.visible()).to.be(false);
- expect(d.visible()).to.be(false);
- expect(e.visible()).to.be(true);
- expect(f.visible()).to.be(true);
- });
- it('should not show any items but match two', function() {
- list.filter(function(item) {
- return (item.values().id2 == 'b');
- });
- list.show(3,2);
- expect(list.visibleItems.length).to.equal(0);
- expect(list.matchingItems.length).to.equal(2);
- expect(a.visible()).to.be(false);
- expect(b.visible()).to.be(false);
- expect(c.visible()).to.be(false);
- expect(d.visible()).to.be(false);
- expect(e.visible()).to.be(false);
- expect(f.visible()).to.be(false);
- });
- });
-
- describe('Filter and search', function() {
- afterEach(function() {
- list.filter();
- });
- it('should show 4, 5', function() {
- list.show(1,2);
- list.filter(function(item) {
- return (item.values().id > '3');
- });
- list.search('b');
- expect(list.visibleItems.length).to.equal(2);
- expect(list.matchingItems.length).to.equal(3);
- expect(a.visible()).to.be(false);
- expect(b.visible()).to.be(false);
- expect(c.visible()).to.be(false);
- expect(d.visible()).to.be(true);
- expect(e.visible()).to.be(true);
- expect(f.visible()).to.be(false);
- });
- it('should show 5, 6', function() {
- list.show(1,2);
- list.filter(function(item) {
- return (item.values().id > '3');
- });
- list.search('b');
- list.show(2,2);
- expect(list.visibleItems.length).to.equal(2);
- expect(list.matchingItems.length).to.equal(3);
- expect(a.visible()).to.be(false);
- expect(b.visible()).to.be(false);
- expect(c.visible()).to.be(false);
- expect(d.visible()).to.be(false);
- expect(e.visible()).to.be(true);
- expect(f.visible()).to.be(true);
- });
- });
-});
diff --git a/test/test.sort.js b/test/test.sort.js
deleted file mode 100644
index 0e9ca9c6..00000000
--- a/test/test.sort.js
+++ /dev/null
@@ -1,320 +0,0 @@
-describe('Sort', function() {
-
- var list, i1, i2, i3, i4, i5, i6;
-
- beforeEach(function() {
- list = fixture.list(['id'], [
- { id: "1", val: "" },
- { id: "2", val: "" },
- { id: "3", val: "" },
- { id: "4", val: "" },
- { id: "5", val: "" },
- { id: "6", val: "" }
- ]);
- i1 = list.get('id', '1')[0];
- i2 = list.get('id', '2')[0];
- i3 = list.get('id', '3')[0];
- i4 = list.get('id', '4')[0];
- i5 = list.get('id', '5')[0];
- i6 = list.get('id', '6')[0];
- });
-
- afterEach(function() {
- fixture.removeList();
- });
-
- describe('Basics', function() {
- it('should sort letters asc', function() {
- i1.values({ val: "b" });
- i2.values({ val: "a" });
- i3.values({ val: "c" });
- i4.values({ val: "z" });
- i5.values({ val: "s" });
- i6.values({ val: "y" });
- list.sort('val');
- expect(list.items[0].values().val).to.be.equal("a");
- expect(list.items[1].values().val).to.be.equal("b");
- expect(list.items[2].values().val).to.be.equal("c");
- expect(list.items[3].values().val).to.be.equal("s");
- expect(list.items[4].values().val).to.be.equal("y");
- expect(list.items[5].values().val).to.be.equal("z");
- });
- it('should sort letters desc', function() {
- i1.values({ val: "b" });
- i2.values({ val: "a" });
- i3.values({ val: "c" });
- i4.values({ val: "z" });
- i5.values({ val: "s" });
- i6.values({ val: "y" });
- list.sort('val', { order: "desc" });
- expect(list.items[0].values().val).to.be.equal("z");
- expect(list.items[1].values().val).to.be.equal("y");
- expect(list.items[2].values().val).to.be.equal("s");
- expect(list.items[3].values().val).to.be.equal("c");
- expect(list.items[4].values().val).to.be.equal("b");
- expect(list.items[5].values().val).to.be.equal("a");
- });
- it('should fail to sort åäö desc (becomes äåö)', function() {
- i1.values({ val: "a" });
- i2.values({ val: "å" });
- i3.values({ val: "ä" });
- i4.values({ val: "ö" });
- i5.values({ val: "o" });
- i6.values({ val: "s" });
- list.sort('val');
- expect(list.items[0].values().val).to.be.equal("a");
- expect(list.items[1].values().val).to.be.equal("o");
- expect(list.items[2].values().val).to.be.equal("s");
- expect(list.items[3].values().val).to.be.equal("ä");
- expect(list.items[4].values().val).to.be.equal("å");
- expect(list.items[5].values().val).to.be.equal("ö");
- });
- it('should fail to sort åäö asc (becomes öåä)', function() {
- i1.values({ val: "a" });
- i2.values({ val: "å" });
- i3.values({ val: "ä" });
- i4.values({ val: "ö" });
- i5.values({ val: "o" });
- i6.values({ val: "s" });
- list.sort('val', { order: "desc" });
- expect(list.items[0].values().val).to.be.equal("ö");
- expect(list.items[1].values().val).to.be.equal("å");
- expect(list.items[2].values().val).to.be.equal("ä");
- expect(list.items[3].values().val).to.be.equal("s");
- expect(list.items[4].values().val).to.be.equal("o");
- expect(list.items[5].values().val).to.be.equal("a");
- });
- it('should handle case-insensitive by default', function() {
- i1.values({ val: "e" });
- i2.values({ val: "b" });
- i4.values({ val: "F" });
- i3.values({ val: "D" });
- i5.values({ val: "A" });
- i6.values({ val: "C" });
- list.sort('val');
- expect(list.items[0].values().val).to.be.equal("A");
- expect(list.items[1].values().val).to.be.equal("b");
- expect(list.items[2].values().val).to.be.equal("C");
- expect(list.items[3].values().val).to.be.equal("D");
- expect(list.items[4].values().val).to.be.equal("e");
- expect(list.items[5].values().val).to.be.equal("F");
- });
- it('should disable insensitive', function() {
- i1.values({ val: "e" });
- i2.values({ val: "b" });
- i4.values({ val: "F" });
- i3.values({ val: "D" });
- i5.values({ val: "A" });
- i6.values({ val: "C" });
- list.sort('val', { insensitive: false });
- expect(list.items[0].values().val).to.be.equal("A");
- expect(list.items[1].values().val).to.be.equal("C");
- expect(list.items[2].values().val).to.be.equal("D");
- expect(list.items[3].values().val).to.be.equal("F");
- expect(list.items[4].values().val).to.be.equal("b");
- expect(list.items[5].values().val).to.be.equal("e");
- });
- it('should sort dates', function() {
- i1.values({ val: "10/12/2008" });
- i2.values({ val: "10/11/2008" });
- i3.values({ val: "10/11/2007" });
- i4.values({ val: "10/12/2009" });
- i5.values({ val: "4/01/2007" });
- i6.values({ val: "10/12/2006" });
- list.sort('val', { order: "asc" });
- expect(list.items[0].values().val).to.be.equal("10/12/2006");
- expect(list.items[1].values().val).to.be.equal("4/01/2007");
- expect(list.items[2].values().val).to.be.equal("10/11/2007");
- expect(list.items[3].values().val).to.be.equal("10/11/2008");
- expect(list.items[4].values().val).to.be.equal("10/12/2008");
- expect(list.items[5].values().val).to.be.equal("10/12/2009");
- });
- it('should sort file names', function() {
- i1.values({ val: "car.mov" });
- i2.values({ val: "01alpha.sgi" });
- i3.values({ val: "001alpha.sgi" });
- i4.values({ val: "my.string_41299.tif" });
- i5.values({ val: "0003.zip" });
- i6.values({ val: "0002.asp" });
- list.sort('val', { order: "asc" });
- expect(list.items[0].values().val).to.be.equal("0002.asp");
- expect(list.items[1].values().val).to.be.equal("0003.zip");
- expect(list.items[2].values().val).to.be.equal("001alpha.sgi");
- expect(list.items[3].values().val).to.be.equal("01alpha.sgi");
- expect(list.items[4].values().val).to.be.equal("car.mov");
- expect(list.items[5].values().val).to.be.equal("my.string_41299.tif");
- });
- it('should sort floates', function() {
- i1.values({ val: "10.0401" });
- i2.values({ val: "10.022" });
- i3.values({ val: "10.021999" });
- i4.values({ val: "11.231" });
- i5.values({ val: "0003.123" });
- i6.values({ val: "09.2123" });
- list.sort('val', { order: "asc" });
- expect(list.items[0].values().val).to.be.equal("0003.123");
- expect(list.items[1].values().val).to.be.equal("09.2123");
- expect(list.items[2].values().val).to.be.equal("10.021999");
- expect(list.items[3].values().val).to.be.equal("10.022");
- expect(list.items[4].values().val).to.be.equal("10.0401");
- expect(list.items[5].values().val).to.be.equal("11.231");
- });
- it('should sort IP addresses', function() {
- i1.values({ val: "192.168.1.1" });
- i2.values({ val: "192.168.0.100" });
- i3.values({ val: "192.168.0.1" });
- i4.values({ val: "192.168.1.3" });
- i5.values({ val: "127.0.0.1" });
- i6.values({ val: "192.168.1.2" });
- list.sort('val', { order: "asc" });
- expect(list.items[0].values().val).to.be.equal("127.0.0.1");
- expect(list.items[1].values().val).to.be.equal("192.168.0.1");
- expect(list.items[2].values().val).to.be.equal("192.168.0.100");
- expect(list.items[3].values().val).to.be.equal("192.168.1.1");
- expect(list.items[4].values().val).to.be.equal("192.168.1.2");
- expect(list.items[5].values().val).to.be.equal("192.168.1.3");
- });
- it('should not break with weird values', function() {
- i1.values({ val: undefined });
- i2.values({ val: null });
- i3.values({ val: 0 });
- i4.values({ val: function() {} });
- i5.values({ val: { foo: "bar" } });
-
- expect(list.sort).withArgs('val').to.not.throwException();
- expect(list.sort).withArgs('val').to.not.throwException();
- expect(list.sort).withArgs('val').to.not.throwException();
- expect(list.sort).withArgs('val').to.not.throwException();
- expect(list.sort).withArgs('val').to.not.throwException();
- expect(list.sort).withArgs('val').to.not.throwException();
- });
- /*
- it('should show how random values are sorted', function() {
- list.add({ id: '7', val: "" });
- list.add({ id: '8', val: "" });
- list.add({ id: '9', val: "" });
- list.add({ id: '10', val: "" });
- list.add({ id: '11', val: "" });
- list.add({ id: '12', val: "" });
-
- var i7 = list.get('id', '7')[0],
- i8 = list.get('id', '8')[0],
- i9 = list.get('id', '9')[0],
- i10 = list.get('id', '10')[0],
- i11 = list.get('id', '11')[0],
- i12 = list.get('id', '12')[0];
-
- i1.values({ val: undefined });
- i2.values({ val: "" });
- i3.values({ val: null });
- i4.values({ val: "a" });
- i5.values({ val: "0" });
- i6.values({ val: true });
- i7.values({ val: 0 });
- i8.values({ val: "z" });
- i9.values({ val: "!" });
- i10.values({ val: "?" });
- i11.values({ val: 100 });
- i12.values({ val: false });
-
- list.sort('val', { order: "asc" });
- list.sort('val', { order: "desc" });
- list.sort('val', { order: "asc" });
-
- expect(list.items[0].values().val).to.be.equal("");
- expect(list.items[1].values().val).to.be.equal("0");
- expect(list.items[2].values().val).to.be.equal(0);
- expect(list.items[3].values().val).to.be.equal(100);
- expect(list.items[4].values().val).to.be.equal("!");
- expect(list.items[5].values().val).to.be.equal("?");
- expect(list.items[6].values().val).to.be.equal("a");
- expect(list.items[7].values().val).to.be.equal(false);
- expect(list.items[8].values().val).to.be.equal(null);
- expect(list.items[9].values().val).to.be.equal(true);
- expect(list.items[10].values().val).to.be.equal(undefined);
- expect(list.items[11].values().val).to.be.equal("z");
- });
-
- it('should handle space and zero the same for desc and asc (random)', function() {
- list.clear();
- list.add({ val: "" });
- list.add({ val: "0" });
- list.add({ val: 0 });
-
- list.sort('val', { order: "asc" });
- expect(list.items[0].values().val).to.be.equal("");
- expect(list.items[1].values().val).to.be.equal("0");
- expect(list.items[2].values().val).to.be.equal(0);
- list.sort('val', { order: "desc" });
- expect(list.items[0].values().val).to.be.equal("");
- expect(list.items[1].values().val).to.be.equal("0");
- expect(list.items[2].values().val).to.be.equal(0);
- list.sort('val', { order: "asc" });
- expect(list.items[0].values().val).to.be.equal("");
- expect(list.items[1].values().val).to.be.equal("0");
- expect(list.items[2].values().val).to.be.equal(0);
- });
- */
- });
-
- describe('Custom sort function', function() {
- it('should use custom sort option', function() {
- i1.values({ val: "" });
- i2.values({ val: "" });
- i3.values({ val: "" });
- i4.values({ val: "" });
- i5.values({ val: "" });
- i6.values({ val: "" });
- list.sort('val', {
- sortFunction: function(itemA, itemB, options) {
- options.desc = false;
- return list.utils.naturalSort($(itemA.values()[options.valueName]).val(), $(itemB.values()[options.valueName]).val(), options);
- }
- });
- expect(list.items[0].values().val).to.be.equal("");
- expect(list.items[1].values().val).to.be.equal("");
- expect(list.items[2].values().val).to.be.equal("");
- expect(list.items[3].values().val).to.be.equal("");
- expect(list.items[4].values().val).to.be.equal("");
- expect(list.items[5].values().val).to.be.equal("");
- });
- it('should use default custom sort function', function() {
- list.sortFunction = function(itemA, itemB, options) {
- options.desc = false;
- return list.utils.naturalSort($(itemA.values()[options.valueName]).val(), $(itemB.values()[options.valueName]).val(), options);
- };
- i1.values({ val: "" });
- i2.values({ val: "" });
- i3.values({ val: "" });
- i4.values({ val: "" });
- i5.values({ val: "" });
- i6.values({ val: "" });
- list.sort('val');
- expect(list.items[0].values().val).to.be.equal("");
- expect(list.items[1].values().val).to.be.equal("");
- expect(list.items[2].values().val).to.be.equal("");
- expect(list.items[3].values().val).to.be.equal("");
- expect(list.items[4].values().val).to.be.equal("");
- expect(list.items[5].values().val).to.be.equal("");
- });
- it('should use default custom sort function with options', function() {
- list.sortFunction = function(itemA, itemB, options) {
- options.desc = true;
- return list.utils.naturalSort($(itemA.values()[options.valueName]).val(), $(itemB.values()[options.valueName]).val(), options);
- };
- i1.values({ val: "" });
- i2.values({ val: "" });
- i3.values({ val: "" });
- i4.values({ val: "" });
- i5.values({ val: "" });
- i6.values({ val: "" });
- list.sort('val', { order: "desc"});
- expect(list.items[0].values().val).to.be.equal("");
- expect(list.items[1].values().val).to.be.equal("");
- expect(list.items[2].values().val).to.be.equal("");
- expect(list.items[3].values().val).to.be.equal("");
- expect(list.items[4].values().val).to.be.equal("");
- expect(list.items[5].values().val).to.be.equal("");
- });
- });
-});
diff --git a/test/test.trigger.js b/test/test.trigger.js
deleted file mode 100644
index 12ad8890..00000000
--- a/test/test.trigger.js
+++ /dev/null
@@ -1,21 +0,0 @@
-describe('Trigger', function() {
-
- var list;
-
- before(function() {
- list = fixture.list(['name', 'born'], fixture.all);
- });
-
- after(function() {
- fixture.removeList();
- });
-
- describe('General', function() {
- it('should be triggered by searchComplete', function(done) {
- list.on('searchComplete', function() {
- done();
- });
- list.trigger('searchComplete');
- });
- });
-});
\ No newline at end of file
diff --git a/test/usage/main.js b/test/usage/main.js
deleted file mode 100644
index 63cc377b..00000000
--- a/test/usage/main.js
+++ /dev/null
@@ -1,6 +0,0 @@
-require(['../../dist/list', '../../dist/list.min'], function(List, ListMin) {
- var options = {
- valueNames: [ 'name', 'born' ]
- };
- var userList = new List('users', options);
-});
diff --git a/test/usage/require.js b/test/usage/require.js
deleted file mode 100644
index babfa9ad..00000000
--- a/test/usage/require.js
+++ /dev/null
@@ -1,2083 +0,0 @@
-/** vim: et:ts=4:sw=4:sts=4
- * @license RequireJS 2.1.17 Copyright (c) 2010-2015, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/requirejs for details
- */
-//Not using strict: uneven strict support in browsers, #392, and causes
-//problems with requirejs.exec()/transpiler plugins that may not be strict.
-/*jslint regexp: true, nomen: true, sloppy: true */
-/*global window, navigator, document, importScripts, setTimeout, opera */
-
-var requirejs, require, define;
-(function (global) {
- var req, s, head, baseElement, dataMain, src,
- interactiveScript, currentlyAddingScript, mainScript, subPath,
- version = '2.1.17',
- commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
- cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
- jsSuffixRegExp = /\.js$/,
- currDirRegExp = /^\.\//,
- op = Object.prototype,
- ostring = op.toString,
- hasOwn = op.hasOwnProperty,
- ap = Array.prototype,
- apsp = ap.splice,
- isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document),
- isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
- //PS3 indicates loaded and complete, but need to wait for complete
- //specifically. Sequence is 'loading', 'loaded', execution,
- // then 'complete'. The UA check is unfortunate, but not sure how
- //to feature test w/o causing perf issues.
- readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
- /^complete$/ : /^(complete|loaded)$/,
- defContextName = '_',
- //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
- isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
- contexts = {},
- cfg = {},
- globalDefQueue = [],
- useInteractive = false;
-
- function isFunction(it) {
- return ostring.call(it) === '[object Function]';
- }
-
- function isArray(it) {
- return ostring.call(it) === '[object Array]';
- }
-
- /**
- * Helper function for iterating over an array. If the func returns
- * a true value, it will break out of the loop.
- */
- function each(ary, func) {
- if (ary) {
- var i;
- for (i = 0; i < ary.length; i += 1) {
- if (ary[i] && func(ary[i], i, ary)) {
- break;
- }
- }
- }
- }
-
- /**
- * Helper function for iterating over an array backwards. If the func
- * returns a true value, it will break out of the loop.
- */
- function eachReverse(ary, func) {
- if (ary) {
- var i;
- for (i = ary.length - 1; i > -1; i -= 1) {
- if (ary[i] && func(ary[i], i, ary)) {
- break;
- }
- }
- }
- }
-
- function hasProp(obj, prop) {
- return hasOwn.call(obj, prop);
- }
-
- function getOwn(obj, prop) {
- return hasProp(obj, prop) && obj[prop];
- }
-
- /**
- * Cycles over properties in an object and calls a function for each
- * property value. If the function returns a truthy value, then the
- * iteration is stopped.
- */
- function eachProp(obj, func) {
- var prop;
- for (prop in obj) {
- if (hasProp(obj, prop)) {
- if (func(obj[prop], prop)) {
- break;
- }
- }
- }
- }
-
- /**
- * Simple function to mix in properties from source into target,
- * but only if target does not already have a property of the same name.
- */
- function mixin(target, source, force, deepStringMixin) {
- if (source) {
- eachProp(source, function (value, prop) {
- if (force || !hasProp(target, prop)) {
- if (deepStringMixin && typeof value === 'object' && value &&
- !isArray(value) && !isFunction(value) &&
- !(value instanceof RegExp)) {
-
- if (!target[prop]) {
- target[prop] = {};
- }
- mixin(target[prop], value, force, deepStringMixin);
- } else {
- target[prop] = value;
- }
- }
- });
- }
- return target;
- }
-
- //Similar to Function.prototype.bind, but the 'this' object is specified
- //first, since it is easier to read/figure out what 'this' will be.
- function bind(obj, fn) {
- return function () {
- return fn.apply(obj, arguments);
- };
- }
-
- function scripts() {
- return document.getElementsByTagName('script');
- }
-
- function defaultOnError(err) {
- throw err;
- }
-
- //Allow getting a global that is expressed in
- //dot notation, like 'a.b.c'.
- function getGlobal(value) {
- if (!value) {
- return value;
- }
- var g = global;
- each(value.split('.'), function (part) {
- g = g[part];
- });
- return g;
- }
-
- /**
- * Constructs an error with a pointer to an URL with more information.
- * @param {String} id the error ID that maps to an ID on a web page.
- * @param {String} message human readable error.
- * @param {Error} [err] the original error, if there is one.
- *
- * @returns {Error}
- */
- function makeError(id, msg, err, requireModules) {
- var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
- e.requireType = id;
- e.requireModules = requireModules;
- if (err) {
- e.originalError = err;
- }
- return e;
- }
-
- if (typeof define !== 'undefined') {
- //If a define is already in play via another AMD loader,
- //do not overwrite.
- return;
- }
-
- if (typeof requirejs !== 'undefined') {
- if (isFunction(requirejs)) {
- //Do not overwrite an existing requirejs instance.
- return;
- }
- cfg = requirejs;
- requirejs = undefined;
- }
-
- //Allow for a require config object
- if (typeof require !== 'undefined' && !isFunction(require)) {
- //assume it is a config object.
- cfg = require;
- require = undefined;
- }
-
- function newContext(contextName) {
- var inCheckLoaded, Module, context, handlers,
- checkLoadedTimeoutId,
- config = {
- //Defaults. Do not set a default for map
- //config to speed up normalize(), which
- //will run faster if there is no default.
- waitSeconds: 7,
- baseUrl: './',
- paths: {},
- bundles: {},
- pkgs: {},
- shim: {},
- config: {}
- },
- registry = {},
- //registry of just enabled modules, to speed
- //cycle breaking code when lots of modules
- //are registered, but not activated.
- enabledRegistry = {},
- undefEvents = {},
- defQueue = [],
- defined = {},
- urlFetched = {},
- bundlesMap = {},
- requireCounter = 1,
- unnormalizedCounter = 1;
-
- /**
- * Trims the . and .. from an array of path segments.
- * It will keep a leading path segment if a .. will become
- * the first path segment, to help with module name lookups,
- * which act like paths, but can be remapped. But the end result,
- * all paths that use this function should look normalized.
- * NOTE: this method MODIFIES the input array.
- * @param {Array} ary the array of path segments.
- */
- function trimDots(ary) {
- var i, part;
- for (i = 0; i < ary.length; i++) {
- part = ary[i];
- if (part === '.') {
- ary.splice(i, 1);
- i -= 1;
- } else if (part === '..') {
- // If at the start, or previous value is still ..,
- // keep them so that when converted to a path it may
- // still work when converted to a path, even though
- // as an ID it is less than ideal. In larger point
- // releases, may be better to just kick out an error.
- if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') {
- continue;
- } else if (i > 0) {
- ary.splice(i - 1, 2);
- i -= 2;
- }
- }
- }
- }
-
- /**
- * Given a relative module name, like ./something, normalize it to
- * a real name that can be mapped to a path.
- * @param {String} name the relative name
- * @param {String} baseName a real name that the name arg is relative
- * to.
- * @param {Boolean} applyMap apply the map config to the value. Should
- * only be done if this normalization is for a dependency ID.
- * @returns {String} normalized name
- */
- function normalize(name, baseName, applyMap) {
- var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex,
- foundMap, foundI, foundStarMap, starI, normalizedBaseParts,
- baseParts = (baseName && baseName.split('/')),
- map = config.map,
- starMap = map && map['*'];
-
- //Adjust any relative paths.
- if (name) {
- name = name.split('/');
- lastIndex = name.length - 1;
-
- // If wanting node ID compatibility, strip .js from end
- // of IDs. Have to do this here, and not in nameToUrl
- // because node allows either .js or non .js to map
- // to same file.
- if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
- name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
- }
-
- // Starts with a '.' so need the baseName
- if (name[0].charAt(0) === '.' && baseParts) {
- //Convert baseName to array, and lop off the last part,
- //so that . matches that 'directory' and not name of the baseName's
- //module. For instance, baseName of 'one/two/three', maps to
- //'one/two/three.js', but we want the directory, 'one/two' for
- //this normalization.
- normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
- name = normalizedBaseParts.concat(name);
- }
-
- trimDots(name);
- name = name.join('/');
- }
-
- //Apply map config if available.
- if (applyMap && map && (baseParts || starMap)) {
- nameParts = name.split('/');
-
- outerLoop: for (i = nameParts.length; i > 0; i -= 1) {
- nameSegment = nameParts.slice(0, i).join('/');
-
- if (baseParts) {
- //Find the longest baseName segment match in the config.
- //So, do joins on the biggest to smallest lengths of baseParts.
- for (j = baseParts.length; j > 0; j -= 1) {
- mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
-
- //baseName segment has config, find if it has one for
- //this name.
- if (mapValue) {
- mapValue = getOwn(mapValue, nameSegment);
- if (mapValue) {
- //Match, update name to the new value.
- foundMap = mapValue;
- foundI = i;
- break outerLoop;
- }
- }
- }
- }
-
- //Check for a star map match, but just hold on to it,
- //if there is a shorter segment match later in a matching
- //config, then favor over this star map.
- if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
- foundStarMap = getOwn(starMap, nameSegment);
- starI = i;
- }
- }
-
- if (!foundMap && foundStarMap) {
- foundMap = foundStarMap;
- foundI = starI;
- }
-
- if (foundMap) {
- nameParts.splice(0, foundI, foundMap);
- name = nameParts.join('/');
- }
- }
-
- // If the name points to a package's name, use
- // the package main instead.
- pkgMain = getOwn(config.pkgs, name);
-
- return pkgMain ? pkgMain : name;
- }
-
- function removeScript(name) {
- if (isBrowser) {
- each(scripts(), function (scriptNode) {
- if (scriptNode.getAttribute('data-requiremodule') === name &&
- scriptNode.getAttribute('data-requirecontext') === context.contextName) {
- scriptNode.parentNode.removeChild(scriptNode);
- return true;
- }
- });
- }
- }
-
- function hasPathFallback(id) {
- var pathConfig = getOwn(config.paths, id);
- if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
- //Pop off the first array value, since it failed, and
- //retry
- pathConfig.shift();
- context.require.undef(id);
-
- //Custom require that does not do map translation, since
- //ID is "absolute", already mapped/resolved.
- context.makeRequire(null, {
- skipMap: true
- })([id]);
-
- return true;
- }
- }
-
- //Turns a plugin!resource to [plugin, resource]
- //with the plugin being undefined if the name
- //did not have a plugin prefix.
- function splitPrefix(name) {
- var prefix,
- index = name ? name.indexOf('!') : -1;
- if (index > -1) {
- prefix = name.substring(0, index);
- name = name.substring(index + 1, name.length);
- }
- return [prefix, name];
- }
-
- /**
- * Creates a module mapping that includes plugin prefix, module
- * name, and path. If parentModuleMap is provided it will
- * also normalize the name via require.normalize()
- *
- * @param {String} name the module name
- * @param {String} [parentModuleMap] parent module map
- * for the module name, used to resolve relative names.
- * @param {Boolean} isNormalized: is the ID already normalized.
- * This is true if this call is done for a define() module ID.
- * @param {Boolean} applyMap: apply the map config to the ID.
- * Should only be true if this map is for a dependency.
- *
- * @returns {Object}
- */
- function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
- var url, pluginModule, suffix, nameParts,
- prefix = null,
- parentName = parentModuleMap ? parentModuleMap.name : null,
- originalName = name,
- isDefine = true,
- normalizedName = '';
-
- //If no name, then it means it is a require call, generate an
- //internal name.
- if (!name) {
- isDefine = false;
- name = '_@r' + (requireCounter += 1);
- }
-
- nameParts = splitPrefix(name);
- prefix = nameParts[0];
- name = nameParts[1];
-
- if (prefix) {
- prefix = normalize(prefix, parentName, applyMap);
- pluginModule = getOwn(defined, prefix);
- }
-
- //Account for relative paths if there is a base name.
- if (name) {
- if (prefix) {
- if (pluginModule && pluginModule.normalize) {
- //Plugin is loaded, use its normalize method.
- normalizedName = pluginModule.normalize(name, function (name) {
- return normalize(name, parentName, applyMap);
- });
- } else {
- // If nested plugin references, then do not try to
- // normalize, as it will not normalize correctly. This
- // places a restriction on resourceIds, and the longer
- // term solution is not to normalize until plugins are
- // loaded and all normalizations to allow for async
- // loading of a loader plugin. But for now, fixes the
- // common uses. Details in #1131
- normalizedName = name.indexOf('!') === -1 ?
- normalize(name, parentName, applyMap) :
- name;
- }
- } else {
- //A regular module.
- normalizedName = normalize(name, parentName, applyMap);
-
- //Normalized name may be a plugin ID due to map config
- //application in normalize. The map config values must
- //already be normalized, so do not need to redo that part.
- nameParts = splitPrefix(normalizedName);
- prefix = nameParts[0];
- normalizedName = nameParts[1];
- isNormalized = true;
-
- url = context.nameToUrl(normalizedName);
- }
- }
-
- //If the id is a plugin id that cannot be determined if it needs
- //normalization, stamp it with a unique ID so two matching relative
- //ids that may conflict can be separate.
- suffix = prefix && !pluginModule && !isNormalized ?
- '_unnormalized' + (unnormalizedCounter += 1) :
- '';
-
- return {
- prefix: prefix,
- name: normalizedName,
- parentMap: parentModuleMap,
- unnormalized: !!suffix,
- url: url,
- originalName: originalName,
- isDefine: isDefine,
- id: (prefix ?
- prefix + '!' + normalizedName :
- normalizedName) + suffix
- };
- }
-
- function getModule(depMap) {
- var id = depMap.id,
- mod = getOwn(registry, id);
-
- if (!mod) {
- mod = registry[id] = new context.Module(depMap);
- }
-
- return mod;
- }
-
- function on(depMap, name, fn) {
- var id = depMap.id,
- mod = getOwn(registry, id);
-
- if (hasProp(defined, id) &&
- (!mod || mod.defineEmitComplete)) {
- if (name === 'defined') {
- fn(defined[id]);
- }
- } else {
- mod = getModule(depMap);
- if (mod.error && name === 'error') {
- fn(mod.error);
- } else {
- mod.on(name, fn);
- }
- }
- }
-
- function onError(err, errback) {
- var ids = err.requireModules,
- notified = false;
-
- if (errback) {
- errback(err);
- } else {
- each(ids, function (id) {
- var mod = getOwn(registry, id);
- if (mod) {
- //Set error on module, so it skips timeout checks.
- mod.error = err;
- if (mod.events.error) {
- notified = true;
- mod.emit('error', err);
- }
- }
- });
-
- if (!notified) {
- req.onError(err);
- }
- }
- }
-
- /**
- * Internal method to transfer globalQueue items to this context's
- * defQueue.
- */
- function takeGlobalQueue() {
- //Push all the globalDefQueue items into the context's defQueue
- if (globalDefQueue.length) {
- //Array splice in the values since the context code has a
- //local var ref to defQueue, so cannot just reassign the one
- //on context.
- apsp.apply(defQueue,
- [defQueue.length, 0].concat(globalDefQueue));
- globalDefQueue = [];
- }
- }
-
- handlers = {
- 'require': function (mod) {
- if (mod.require) {
- return mod.require;
- } else {
- return (mod.require = context.makeRequire(mod.map));
- }
- },
- 'exports': function (mod) {
- mod.usingExports = true;
- if (mod.map.isDefine) {
- if (mod.exports) {
- return (defined[mod.map.id] = mod.exports);
- } else {
- return (mod.exports = defined[mod.map.id] = {});
- }
- }
- },
- 'module': function (mod) {
- if (mod.module) {
- return mod.module;
- } else {
- return (mod.module = {
- id: mod.map.id,
- uri: mod.map.url,
- config: function () {
- return getOwn(config.config, mod.map.id) || {};
- },
- exports: mod.exports || (mod.exports = {})
- });
- }
- }
- };
-
- function cleanRegistry(id) {
- //Clean up machinery used for waiting modules.
- delete registry[id];
- delete enabledRegistry[id];
- }
-
- function breakCycle(mod, traced, processed) {
- var id = mod.map.id;
-
- if (mod.error) {
- mod.emit('error', mod.error);
- } else {
- traced[id] = true;
- each(mod.depMaps, function (depMap, i) {
- var depId = depMap.id,
- dep = getOwn(registry, depId);
-
- //Only force things that have not completed
- //being defined, so still in the registry,
- //and only if it has not been matched up
- //in the module already.
- if (dep && !mod.depMatched[i] && !processed[depId]) {
- if (getOwn(traced, depId)) {
- mod.defineDep(i, defined[depId]);
- mod.check(); //pass false?
- } else {
- breakCycle(dep, traced, processed);
- }
- }
- });
- processed[id] = true;
- }
- }
-
- function checkLoaded() {
- var err, usingPathFallback,
- waitInterval = config.waitSeconds * 1000,
- //It is possible to disable the wait interval by using waitSeconds of 0.
- expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
- noLoads = [],
- reqCalls = [],
- stillLoading = false,
- needCycleCheck = true;
-
- //Do not bother if this call was a result of a cycle break.
- if (inCheckLoaded) {
- return;
- }
-
- inCheckLoaded = true;
-
- //Figure out the state of all the modules.
- eachProp(enabledRegistry, function (mod) {
- var map = mod.map,
- modId = map.id;
-
- //Skip things that are not enabled or in error state.
- if (!mod.enabled) {
- return;
- }
-
- if (!map.isDefine) {
- reqCalls.push(mod);
- }
-
- if (!mod.error) {
- //If the module should be executed, and it has not
- //been inited and time is up, remember it.
- if (!mod.inited && expired) {
- if (hasPathFallback(modId)) {
- usingPathFallback = true;
- stillLoading = true;
- } else {
- noLoads.push(modId);
- removeScript(modId);
- }
- } else if (!mod.inited && mod.fetched && map.isDefine) {
- stillLoading = true;
- if (!map.prefix) {
- //No reason to keep looking for unfinished
- //loading. If the only stillLoading is a
- //plugin resource though, keep going,
- //because it may be that a plugin resource
- //is waiting on a non-plugin cycle.
- return (needCycleCheck = false);
- }
- }
- }
- });
-
- if (expired && noLoads.length) {
- //If wait time expired, throw error of unloaded modules.
- err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
- err.contextName = context.contextName;
- return onError(err);
- }
-
- //Not expired, check for a cycle.
- if (needCycleCheck) {
- each(reqCalls, function (mod) {
- breakCycle(mod, {}, {});
- });
- }
-
- //If still waiting on loads, and the waiting load is something
- //other than a plugin resource, or there are still outstanding
- //scripts, then just try back later.
- if ((!expired || usingPathFallback) && stillLoading) {
- //Something is still waiting to load. Wait for it, but only
- //if a timeout is not already in effect.
- if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
- checkLoadedTimeoutId = setTimeout(function () {
- checkLoadedTimeoutId = 0;
- checkLoaded();
- }, 50);
- }
- }
-
- inCheckLoaded = false;
- }
-
- Module = function (map) {
- this.events = getOwn(undefEvents, map.id) || {};
- this.map = map;
- this.shim = getOwn(config.shim, map.id);
- this.depExports = [];
- this.depMaps = [];
- this.depMatched = [];
- this.pluginMaps = {};
- this.depCount = 0;
-
- /* this.exports this.factory
- this.depMaps = [],
- this.enabled, this.fetched
- */
- };
-
- Module.prototype = {
- init: function (depMaps, factory, errback, options) {
- options = options || {};
-
- //Do not do more inits if already done. Can happen if there
- //are multiple define calls for the same module. That is not
- //a normal, common case, but it is also not unexpected.
- if (this.inited) {
- return;
- }
-
- this.factory = factory;
-
- if (errback) {
- //Register for errors on this module.
- this.on('error', errback);
- } else if (this.events.error) {
- //If no errback already, but there are error listeners
- //on this module, set up an errback to pass to the deps.
- errback = bind(this, function (err) {
- this.emit('error', err);
- });
- }
-
- //Do a copy of the dependency array, so that
- //source inputs are not modified. For example
- //"shim" deps are passed in here directly, and
- //doing a direct modification of the depMaps array
- //would affect that config.
- this.depMaps = depMaps && depMaps.slice(0);
-
- this.errback = errback;
-
- //Indicate this module has be initialized
- this.inited = true;
-
- this.ignore = options.ignore;
-
- //Could have option to init this module in enabled mode,
- //or could have been previously marked as enabled. However,
- //the dependencies are not known until init is called. So
- //if enabled previously, now trigger dependencies as enabled.
- if (options.enabled || this.enabled) {
- //Enable this module and dependencies.
- //Will call this.check()
- this.enable();
- } else {
- this.check();
- }
- },
-
- defineDep: function (i, depExports) {
- //Because of cycles, defined callback for a given
- //export can be called more than once.
- if (!this.depMatched[i]) {
- this.depMatched[i] = true;
- this.depCount -= 1;
- this.depExports[i] = depExports;
- }
- },
-
- fetch: function () {
- if (this.fetched) {
- return;
- }
- this.fetched = true;
-
- context.startTime = (new Date()).getTime();
-
- var map = this.map;
-
- //If the manager is for a plugin managed resource,
- //ask the plugin to load it now.
- if (this.shim) {
- context.makeRequire(this.map, {
- enableBuildCallback: true
- })(this.shim.deps || [], bind(this, function () {
- return map.prefix ? this.callPlugin() : this.load();
- }));
- } else {
- //Regular dependency.
- return map.prefix ? this.callPlugin() : this.load();
- }
- },
-
- load: function () {
- var url = this.map.url;
-
- //Regular dependency.
- if (!urlFetched[url]) {
- urlFetched[url] = true;
- context.load(this.map.id, url);
- }
- },
-
- /**
- * Checks if the module is ready to define itself, and if so,
- * define it.
- */
- check: function () {
- if (!this.enabled || this.enabling) {
- return;
- }
-
- var err, cjsModule,
- id = this.map.id,
- depExports = this.depExports,
- exports = this.exports,
- factory = this.factory;
-
- if (!this.inited) {
- this.fetch();
- } else if (this.error) {
- this.emit('error', this.error);
- } else if (!this.defining) {
- //The factory could trigger another require call
- //that would result in checking this module to
- //define itself again. If already in the process
- //of doing that, skip this work.
- this.defining = true;
-
- if (this.depCount < 1 && !this.defined) {
- if (isFunction(factory)) {
- //If there is an error listener, favor passing
- //to that instead of throwing an error. However,
- //only do it for define()'d modules. require
- //errbacks should not be called for failures in
- //their callbacks (#699). However if a global
- //onError is set, use that.
- if ((this.events.error && this.map.isDefine) ||
- req.onError !== defaultOnError) {
- try {
- exports = context.execCb(id, factory, depExports, exports);
- } catch (e) {
- err = e;
- }
- } else {
- exports = context.execCb(id, factory, depExports, exports);
- }
-
- // Favor return value over exports. If node/cjs in play,
- // then will not have a return value anyway. Favor
- // module.exports assignment over exports object.
- if (this.map.isDefine && exports === undefined) {
- cjsModule = this.module;
- if (cjsModule) {
- exports = cjsModule.exports;
- } else if (this.usingExports) {
- //exports already set the defined value.
- exports = this.exports;
- }
- }
-
- if (err) {
- err.requireMap = this.map;
- err.requireModules = this.map.isDefine ? [this.map.id] : null;
- err.requireType = this.map.isDefine ? 'define' : 'require';
- return onError((this.error = err));
- }
-
- } else {
- //Just a literal value
- exports = factory;
- }
-
- this.exports = exports;
-
- if (this.map.isDefine && !this.ignore) {
- defined[id] = exports;
-
- if (req.onResourceLoad) {
- req.onResourceLoad(context, this.map, this.depMaps);
- }
- }
-
- //Clean up
- cleanRegistry(id);
-
- this.defined = true;
- }
-
- //Finished the define stage. Allow calling check again
- //to allow define notifications below in the case of a
- //cycle.
- this.defining = false;
-
- if (this.defined && !this.defineEmitted) {
- this.defineEmitted = true;
- this.emit('defined', this.exports);
- this.defineEmitComplete = true;
- }
-
- }
- },
-
- callPlugin: function () {
- var map = this.map,
- id = map.id,
- //Map already normalized the prefix.
- pluginMap = makeModuleMap(map.prefix);
-
- //Mark this as a dependency for this plugin, so it
- //can be traced for cycles.
- this.depMaps.push(pluginMap);
-
- on(pluginMap, 'defined', bind(this, function (plugin) {
- var load, normalizedMap, normalizedMod,
- bundleId = getOwn(bundlesMap, this.map.id),
- name = this.map.name,
- parentName = this.map.parentMap ? this.map.parentMap.name : null,
- localRequire = context.makeRequire(map.parentMap, {
- enableBuildCallback: true
- });
-
- //If current map is not normalized, wait for that
- //normalized name to load instead of continuing.
- if (this.map.unnormalized) {
- //Normalize the ID if the plugin allows it.
- if (plugin.normalize) {
- name = plugin.normalize(name, function (name) {
- return normalize(name, parentName, true);
- }) || '';
- }
-
- //prefix and name should already be normalized, no need
- //for applying map config again either.
- normalizedMap = makeModuleMap(map.prefix + '!' + name,
- this.map.parentMap);
- on(normalizedMap,
- 'defined', bind(this, function (value) {
- this.init([], function () { return value; }, null, {
- enabled: true,
- ignore: true
- });
- }));
-
- normalizedMod = getOwn(registry, normalizedMap.id);
- if (normalizedMod) {
- //Mark this as a dependency for this plugin, so it
- //can be traced for cycles.
- this.depMaps.push(normalizedMap);
-
- if (this.events.error) {
- normalizedMod.on('error', bind(this, function (err) {
- this.emit('error', err);
- }));
- }
- normalizedMod.enable();
- }
-
- return;
- }
-
- //If a paths config, then just load that file instead to
- //resolve the plugin, as it is built into that paths layer.
- if (bundleId) {
- this.map.url = context.nameToUrl(bundleId);
- this.load();
- return;
- }
-
- load = bind(this, function (value) {
- this.init([], function () { return value; }, null, {
- enabled: true
- });
- });
-
- load.error = bind(this, function (err) {
- this.inited = true;
- this.error = err;
- err.requireModules = [id];
-
- //Remove temp unnormalized modules for this module,
- //since they will never be resolved otherwise now.
- eachProp(registry, function (mod) {
- if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
- cleanRegistry(mod.map.id);
- }
- });
-
- onError(err);
- });
-
- //Allow plugins to load other code without having to know the
- //context or how to 'complete' the load.
- load.fromText = bind(this, function (text, textAlt) {
- /*jslint evil: true */
- var moduleName = map.name,
- moduleMap = makeModuleMap(moduleName),
- hasInteractive = useInteractive;
-
- //As of 2.1.0, support just passing the text, to reinforce
- //fromText only being called once per resource. Still
- //support old style of passing moduleName but discard
- //that moduleName in favor of the internal ref.
- if (textAlt) {
- text = textAlt;
- }
-
- //Turn off interactive script matching for IE for any define
- //calls in the text, then turn it back on at the end.
- if (hasInteractive) {
- useInteractive = false;
- }
-
- //Prime the system by creating a module instance for
- //it.
- getModule(moduleMap);
-
- //Transfer any config to this other module.
- if (hasProp(config.config, id)) {
- config.config[moduleName] = config.config[id];
- }
-
- try {
- req.exec(text);
- } catch (e) {
- return onError(makeError('fromtexteval',
- 'fromText eval for ' + id +
- ' failed: ' + e,
- e,
- [id]));
- }
-
- if (hasInteractive) {
- useInteractive = true;
- }
-
- //Mark this as a dependency for the plugin
- //resource
- this.depMaps.push(moduleMap);
-
- //Support anonymous modules.
- context.completeLoad(moduleName);
-
- //Bind the value of that module to the value for this
- //resource ID.
- localRequire([moduleName], load);
- });
-
- //Use parentName here since the plugin's name is not reliable,
- //could be some weird string with no path that actually wants to
- //reference the parentName's path.
- plugin.load(map.name, localRequire, load, config);
- }));
-
- context.enable(pluginMap, this);
- this.pluginMaps[pluginMap.id] = pluginMap;
- },
-
- enable: function () {
- enabledRegistry[this.map.id] = this;
- this.enabled = true;
-
- //Set flag mentioning that the module is enabling,
- //so that immediate calls to the defined callbacks
- //for dependencies do not trigger inadvertent load
- //with the depCount still being zero.
- this.enabling = true;
-
- //Enable each dependency
- each(this.depMaps, bind(this, function (depMap, i) {
- var id, mod, handler;
-
- if (typeof depMap === 'string') {
- //Dependency needs to be converted to a depMap
- //and wired up to this module.
- depMap = makeModuleMap(depMap,
- (this.map.isDefine ? this.map : this.map.parentMap),
- false,
- !this.skipMap);
- this.depMaps[i] = depMap;
-
- handler = getOwn(handlers, depMap.id);
-
- if (handler) {
- this.depExports[i] = handler(this);
- return;
- }
-
- this.depCount += 1;
-
- on(depMap, 'defined', bind(this, function (depExports) {
- this.defineDep(i, depExports);
- this.check();
- }));
-
- if (this.errback) {
- on(depMap, 'error', bind(this, this.errback));
- } else if (this.events.error) {
- // No direct errback on this module, but something
- // else is listening for errors, so be sure to
- // propagate the error correctly.
- on(depMap, 'error', bind(this, function(err) {
- this.emit('error', err);
- }));
- }
- }
-
- id = depMap.id;
- mod = registry[id];
-
- //Skip special modules like 'require', 'exports', 'module'
- //Also, don't call enable if it is already enabled,
- //important in circular dependency cases.
- if (!hasProp(handlers, id) && mod && !mod.enabled) {
- context.enable(depMap, this);
- }
- }));
-
- //Enable each plugin that is used in
- //a dependency
- eachProp(this.pluginMaps, bind(this, function (pluginMap) {
- var mod = getOwn(registry, pluginMap.id);
- if (mod && !mod.enabled) {
- context.enable(pluginMap, this);
- }
- }));
-
- this.enabling = false;
-
- this.check();
- },
-
- on: function (name, cb) {
- var cbs = this.events[name];
- if (!cbs) {
- cbs = this.events[name] = [];
- }
- cbs.push(cb);
- },
-
- emit: function (name, evt) {
- each(this.events[name], function (cb) {
- cb(evt);
- });
- if (name === 'error') {
- //Now that the error handler was triggered, remove
- //the listeners, since this broken Module instance
- //can stay around for a while in the registry.
- delete this.events[name];
- }
- }
- };
-
- function callGetModule(args) {
- //Skip modules already defined.
- if (!hasProp(defined, args[0])) {
- getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
- }
- }
-
- function removeListener(node, func, name, ieName) {
- //Favor detachEvent because of IE9
- //issue, see attachEvent/addEventListener comment elsewhere
- //in this file.
- if (node.detachEvent && !isOpera) {
- //Probably IE. If not it will throw an error, which will be
- //useful to know.
- if (ieName) {
- node.detachEvent(ieName, func);
- }
- } else {
- node.removeEventListener(name, func, false);
- }
- }
-
- /**
- * Given an event from a script node, get the requirejs info from it,
- * and then removes the event listeners on the node.
- * @param {Event} evt
- * @returns {Object}
- */
- function getScriptData(evt) {
- //Using currentTarget instead of target for Firefox 2.0's sake. Not
- //all old browsers will be supported, but this one was easy enough
- //to support and still makes sense.
- var node = evt.currentTarget || evt.srcElement;
-
- //Remove the listeners once here.
- removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
- removeListener(node, context.onScriptError, 'error');
-
- return {
- node: node,
- id: node && node.getAttribute('data-requiremodule')
- };
- }
-
- function intakeDefines() {
- var args;
-
- //Any defined modules in the global queue, intake them now.
- takeGlobalQueue();
-
- //Make sure any remaining defQueue items get properly processed.
- while (defQueue.length) {
- args = defQueue.shift();
- if (args[0] === null) {
- return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
- } else {
- //args are id, deps, factory. Should be normalized by the
- //define() function.
- callGetModule(args);
- }
- }
- }
-
- context = {
- config: config,
- contextName: contextName,
- registry: registry,
- defined: defined,
- urlFetched: urlFetched,
- defQueue: defQueue,
- Module: Module,
- makeModuleMap: makeModuleMap,
- nextTick: req.nextTick,
- onError: onError,
-
- /**
- * Set a configuration for the context.
- * @param {Object} cfg config object to integrate.
- */
- configure: function (cfg) {
- //Make sure the baseUrl ends in a slash.
- if (cfg.baseUrl) {
- if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
- cfg.baseUrl += '/';
- }
- }
-
- //Save off the paths since they require special processing,
- //they are additive.
- var shim = config.shim,
- objs = {
- paths: true,
- bundles: true,
- config: true,
- map: true
- };
-
- eachProp(cfg, function (value, prop) {
- if (objs[prop]) {
- if (!config[prop]) {
- config[prop] = {};
- }
- mixin(config[prop], value, true, true);
- } else {
- config[prop] = value;
- }
- });
-
- //Reverse map the bundles
- if (cfg.bundles) {
- eachProp(cfg.bundles, function (value, prop) {
- each(value, function (v) {
- if (v !== prop) {
- bundlesMap[v] = prop;
- }
- });
- });
- }
-
- //Merge shim
- if (cfg.shim) {
- eachProp(cfg.shim, function (value, id) {
- //Normalize the structure
- if (isArray(value)) {
- value = {
- deps: value
- };
- }
- if ((value.exports || value.init) && !value.exportsFn) {
- value.exportsFn = context.makeShimExports(value);
- }
- shim[id] = value;
- });
- config.shim = shim;
- }
-
- //Adjust packages if necessary.
- if (cfg.packages) {
- each(cfg.packages, function (pkgObj) {
- var location, name;
-
- pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
-
- name = pkgObj.name;
- location = pkgObj.location;
- if (location) {
- config.paths[name] = pkgObj.location;
- }
-
- //Save pointer to main module ID for pkg name.
- //Remove leading dot in main, so main paths are normalized,
- //and remove any trailing .js, since different package
- //envs have different conventions: some use a module name,
- //some use a file name.
- config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main')
- .replace(currDirRegExp, '')
- .replace(jsSuffixRegExp, '');
- });
- }
-
- //If there are any "waiting to execute" modules in the registry,
- //update the maps for them, since their info, like URLs to load,
- //may have changed.
- eachProp(registry, function (mod, id) {
- //If module already has init called, since it is too
- //late to modify them, and ignore unnormalized ones
- //since they are transient.
- if (!mod.inited && !mod.map.unnormalized) {
- mod.map = makeModuleMap(id);
- }
- });
-
- //If a deps array or a config callback is specified, then call
- //require with those args. This is useful when require is defined as a
- //config object before require.js is loaded.
- if (cfg.deps || cfg.callback) {
- context.require(cfg.deps || [], cfg.callback);
- }
- },
-
- makeShimExports: function (value) {
- function fn() {
- var ret;
- if (value.init) {
- ret = value.init.apply(global, arguments);
- }
- return ret || (value.exports && getGlobal(value.exports));
- }
- return fn;
- },
-
- makeRequire: function (relMap, options) {
- options = options || {};
-
- function localRequire(deps, callback, errback) {
- var id, map, requireMod;
-
- if (options.enableBuildCallback && callback && isFunction(callback)) {
- callback.__requireJsBuild = true;
- }
-
- if (typeof deps === 'string') {
- if (isFunction(callback)) {
- //Invalid call
- return onError(makeError('requireargs', 'Invalid require call'), errback);
- }
-
- //If require|exports|module are requested, get the
- //value for them from the special handlers. Caveat:
- //this only works while module is being defined.
- if (relMap && hasProp(handlers, deps)) {
- return handlers[deps](registry[relMap.id]);
- }
-
- //Synchronous access to one module. If require.get is
- //available (as in the Node adapter), prefer that.
- if (req.get) {
- return req.get(context, deps, relMap, localRequire);
- }
-
- //Normalize module name, if it contains . or ..
- map = makeModuleMap(deps, relMap, false, true);
- id = map.id;
-
- if (!hasProp(defined, id)) {
- return onError(makeError('notloaded', 'Module name "' +
- id +
- '" has not been loaded yet for context: ' +
- contextName +
- (relMap ? '' : '. Use require([])')));
- }
- return defined[id];
- }
-
- //Grab defines waiting in the global queue.
- intakeDefines();
-
- //Mark all the dependencies as needing to be loaded.
- context.nextTick(function () {
- //Some defines could have been added since the
- //require call, collect them.
- intakeDefines();
-
- requireMod = getModule(makeModuleMap(null, relMap));
-
- //Store if map config should be applied to this require
- //call for dependencies.
- requireMod.skipMap = options.skipMap;
-
- requireMod.init(deps, callback, errback, {
- enabled: true
- });
-
- checkLoaded();
- });
-
- return localRequire;
- }
-
- mixin(localRequire, {
- isBrowser: isBrowser,
-
- /**
- * Converts a module name + .extension into an URL path.
- * *Requires* the use of a module name. It does not support using
- * plain URLs like nameToUrl.
- */
- toUrl: function (moduleNamePlusExt) {
- var ext,
- index = moduleNamePlusExt.lastIndexOf('.'),
- segment = moduleNamePlusExt.split('/')[0],
- isRelative = segment === '.' || segment === '..';
-
- //Have a file extension alias, and it is not the
- //dots from a relative path.
- if (index !== -1 && (!isRelative || index > 1)) {
- ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
- moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
- }
-
- return context.nameToUrl(normalize(moduleNamePlusExt,
- relMap && relMap.id, true), ext, true);
- },
-
- defined: function (id) {
- return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
- },
-
- specified: function (id) {
- id = makeModuleMap(id, relMap, false, true).id;
- return hasProp(defined, id) || hasProp(registry, id);
- }
- });
-
- //Only allow undef on top level require calls
- if (!relMap) {
- localRequire.undef = function (id) {
- //Bind any waiting define() calls to this context,
- //fix for #408
- takeGlobalQueue();
-
- var map = makeModuleMap(id, relMap, true),
- mod = getOwn(registry, id);
-
- removeScript(id);
-
- delete defined[id];
- delete urlFetched[map.url];
- delete undefEvents[id];
-
- //Clean queued defines too. Go backwards
- //in array so that the splices do not
- //mess up the iteration.
- eachReverse(defQueue, function(args, i) {
- if(args[0] === id) {
- defQueue.splice(i, 1);
- }
- });
-
- if (mod) {
- //Hold on to listeners in case the
- //module will be attempted to be reloaded
- //using a different config.
- if (mod.events.defined) {
- undefEvents[id] = mod.events;
- }
-
- cleanRegistry(id);
- }
- };
- }
-
- return localRequire;
- },
-
- /**
- * Called to enable a module if it is still in the registry
- * awaiting enablement. A second arg, parent, the parent module,
- * is passed in for context, when this method is overridden by
- * the optimizer. Not shown here to keep code compact.
- */
- enable: function (depMap) {
- var mod = getOwn(registry, depMap.id);
- if (mod) {
- getModule(depMap).enable();
- }
- },
-
- /**
- * Internal method used by environment adapters to complete a load event.
- * A load event could be a script load or just a load pass from a synchronous
- * load call.
- * @param {String} moduleName the name of the module to potentially complete.
- */
- completeLoad: function (moduleName) {
- var found, args, mod,
- shim = getOwn(config.shim, moduleName) || {},
- shExports = shim.exports;
-
- takeGlobalQueue();
-
- while (defQueue.length) {
- args = defQueue.shift();
- if (args[0] === null) {
- args[0] = moduleName;
- //If already found an anonymous module and bound it
- //to this name, then this is some other anon module
- //waiting for its completeLoad to fire.
- if (found) {
- break;
- }
- found = true;
- } else if (args[0] === moduleName) {
- //Found matching define call for this script!
- found = true;
- }
-
- callGetModule(args);
- }
-
- //Do this after the cycle of callGetModule in case the result
- //of those calls/init calls changes the registry.
- mod = getOwn(registry, moduleName);
-
- if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
- if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
- if (hasPathFallback(moduleName)) {
- return;
- } else {
- return onError(makeError('nodefine',
- 'No define call for ' + moduleName,
- null,
- [moduleName]));
- }
- } else {
- //A script that does not call define(), so just simulate
- //the call for it.
- callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
- }
- }
-
- checkLoaded();
- },
-
- /**
- * Converts a module name to a file path. Supports cases where
- * moduleName may actually be just an URL.
- * Note that it **does not** call normalize on the moduleName,
- * it is assumed to have already been normalized. This is an
- * internal API, not a public one. Use toUrl for the public API.
- */
- nameToUrl: function (moduleName, ext, skipExt) {
- var paths, syms, i, parentModule, url,
- parentPath, bundleId,
- pkgMain = getOwn(config.pkgs, moduleName);
-
- if (pkgMain) {
- moduleName = pkgMain;
- }
-
- bundleId = getOwn(bundlesMap, moduleName);
-
- if (bundleId) {
- return context.nameToUrl(bundleId, ext, skipExt);
- }
-
- //If a colon is in the URL, it indicates a protocol is used and it is just
- //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
- //or ends with .js, then assume the user meant to use an url and not a module id.
- //The slash is important for protocol-less URLs as well as full paths.
- if (req.jsExtRegExp.test(moduleName)) {
- //Just a plain path, not module name lookup, so just return it.
- //Add extension if it is included. This is a bit wonky, only non-.js things pass
- //an extension, this method probably needs to be reworked.
- url = moduleName + (ext || '');
- } else {
- //A module that needs to be converted to a path.
- paths = config.paths;
-
- syms = moduleName.split('/');
- //For each module name segment, see if there is a path
- //registered for it. Start with most specific name
- //and work up from it.
- for (i = syms.length; i > 0; i -= 1) {
- parentModule = syms.slice(0, i).join('/');
-
- parentPath = getOwn(paths, parentModule);
- if (parentPath) {
- //If an array, it means there are a few choices,
- //Choose the one that is desired
- if (isArray(parentPath)) {
- parentPath = parentPath[0];
- }
- syms.splice(0, i, parentPath);
- break;
- }
- }
-
- //Join the path parts together, then figure out if baseUrl is needed.
- url = syms.join('/');
- url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js'));
- url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
- }
-
- return config.urlArgs ? url +
- ((url.indexOf('?') === -1 ? '?' : '&') +
- config.urlArgs) : url;
- },
-
- //Delegates to req.load. Broken out as a separate function to
- //allow overriding in the optimizer.
- load: function (id, url) {
- req.load(context, id, url);
- },
-
- /**
- * Executes a module callback function. Broken out as a separate function
- * solely to allow the build system to sequence the files in the built
- * layer in the right sequence.
- *
- * @private
- */
- execCb: function (name, callback, args, exports) {
- return callback.apply(exports, args);
- },
-
- /**
- * callback for script loads, used to check status of loading.
- *
- * @param {Event} evt the event from the browser for the script
- * that was loaded.
- */
- onScriptLoad: function (evt) {
- //Using currentTarget instead of target for Firefox 2.0's sake. Not
- //all old browsers will be supported, but this one was easy enough
- //to support and still makes sense.
- if (evt.type === 'load' ||
- (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
- //Reset interactive script so a script node is not held onto for
- //to long.
- interactiveScript = null;
-
- //Pull out the name of the module and the context.
- var data = getScriptData(evt);
- context.completeLoad(data.id);
- }
- },
-
- /**
- * Callback for script errors.
- */
- onScriptError: function (evt) {
- var data = getScriptData(evt);
- if (!hasPathFallback(data.id)) {
- return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id]));
- }
- }
- };
-
- context.require = context.makeRequire();
- return context;
- }
-
- /**
- * Main entry point.
- *
- * If the only argument to require is a string, then the module that
- * is represented by that string is fetched for the appropriate context.
- *
- * If the first argument is an array, then it will be treated as an array
- * of dependency string names to fetch. An optional function callback can
- * be specified to execute when all of those dependencies are available.
- *
- * Make a local req variable to help Caja compliance (it assumes things
- * on a require that are not standardized), and to give a short
- * name for minification/local scope use.
- */
- req = requirejs = function (deps, callback, errback, optional) {
-
- //Find the right context, use default
- var context, config,
- contextName = defContextName;
-
- // Determine if have config object in the call.
- if (!isArray(deps) && typeof deps !== 'string') {
- // deps is a config object
- config = deps;
- if (isArray(callback)) {
- // Adjust args if there are dependencies
- deps = callback;
- callback = errback;
- errback = optional;
- } else {
- deps = [];
- }
- }
-
- if (config && config.context) {
- contextName = config.context;
- }
-
- context = getOwn(contexts, contextName);
- if (!context) {
- context = contexts[contextName] = req.s.newContext(contextName);
- }
-
- if (config) {
- context.configure(config);
- }
-
- return context.require(deps, callback, errback);
- };
-
- /**
- * Support require.config() to make it easier to cooperate with other
- * AMD loaders on globally agreed names.
- */
- req.config = function (config) {
- return req(config);
- };
-
- /**
- * Execute something after the current tick
- * of the event loop. Override for other envs
- * that have a better solution than setTimeout.
- * @param {Function} fn function to execute later.
- */
- req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
- setTimeout(fn, 4);
- } : function (fn) { fn(); };
-
- /**
- * Export require as a global, but only if it does not already exist.
- */
- if (!require) {
- require = req;
- }
-
- req.version = version;
-
- //Used to filter out dependencies that are already paths.
- req.jsExtRegExp = /^\/|:|\?|\.js$/;
- req.isBrowser = isBrowser;
- s = req.s = {
- contexts: contexts,
- newContext: newContext
- };
-
- //Create default context.
- req({});
-
- //Exports some context-sensitive methods on global require.
- each([
- 'toUrl',
- 'undef',
- 'defined',
- 'specified'
- ], function (prop) {
- //Reference from contexts instead of early binding to default context,
- //so that during builds, the latest instance of the default context
- //with its config gets used.
- req[prop] = function () {
- var ctx = contexts[defContextName];
- return ctx.require[prop].apply(ctx, arguments);
- };
- });
-
- if (isBrowser) {
- head = s.head = document.getElementsByTagName('head')[0];
- //If BASE tag is in play, using appendChild is a problem for IE6.
- //When that browser dies, this can be removed. Details in this jQuery bug:
- //http://dev.jquery.com/ticket/2709
- baseElement = document.getElementsByTagName('base')[0];
- if (baseElement) {
- head = s.head = baseElement.parentNode;
- }
- }
-
- /**
- * Any errors that require explicitly generates will be passed to this
- * function. Intercept/override it if you want custom error handling.
- * @param {Error} err the error object.
- */
- req.onError = defaultOnError;
-
- /**
- * Creates the node for the load command. Only used in browser envs.
- */
- req.createNode = function (config, moduleName, url) {
- var node = config.xhtml ?
- document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
- document.createElement('script');
- node.type = config.scriptType || 'text/javascript';
- node.charset = 'utf-8';
- node.async = true;
- return node;
- };
-
- /**
- * Does the request to load a module for the browser case.
- * Make this a separate function to allow other environments
- * to override it.
- *
- * @param {Object} context the require context to find state.
- * @param {String} moduleName the name of the module.
- * @param {Object} url the URL to the module.
- */
- req.load = function (context, moduleName, url) {
- var config = (context && context.config) || {},
- node;
- if (isBrowser) {
- //In the browser so use a script tag
- node = req.createNode(config, moduleName, url);
-
- node.setAttribute('data-requirecontext', context.contextName);
- node.setAttribute('data-requiremodule', moduleName);
-
- //Set up load listener. Test attachEvent first because IE9 has
- //a subtle issue in its addEventListener and script onload firings
- //that do not match the behavior of all other browsers with
- //addEventListener support, which fire the onload event for a
- //script right after the script execution. See:
- //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
- //UNFORTUNATELY Opera implements attachEvent but does not follow the script
- //script execution mode.
- if (node.attachEvent &&
- //Check if node.attachEvent is artificially added by custom script or
- //natively supported by browser
- //read https://github.com/jrburke/requirejs/issues/187
- //if we can NOT find [native code] then it must NOT natively supported.
- //in IE8, node.attachEvent does not have toString()
- //Note the test for "[native code" with no closing brace, see:
- //https://github.com/jrburke/requirejs/issues/273
- !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
- !isOpera) {
- //Probably IE. IE (at least 6-8) do not fire
- //script onload right after executing the script, so
- //we cannot tie the anonymous define call to a name.
- //However, IE reports the script as being in 'interactive'
- //readyState at the time of the define call.
- useInteractive = true;
-
- node.attachEvent('onreadystatechange', context.onScriptLoad);
- //It would be great to add an error handler here to catch
- //404s in IE9+. However, onreadystatechange will fire before
- //the error handler, so that does not help. If addEventListener
- //is used, then IE will fire error before load, but we cannot
- //use that pathway given the connect.microsoft.com issue
- //mentioned above about not doing the 'script execute,
- //then fire the script load event listener before execute
- //next script' that other browsers do.
- //Best hope: IE10 fixes the issues,
- //and then destroys all installs of IE 6-9.
- //node.attachEvent('onerror', context.onScriptError);
- } else {
- node.addEventListener('load', context.onScriptLoad, false);
- node.addEventListener('error', context.onScriptError, false);
- }
- node.src = url;
-
- //For some cache cases in IE 6-8, the script executes before the end
- //of the appendChild execution, so to tie an anonymous define
- //call to the module name (which is stored on the node), hold on
- //to a reference to this node, but clear after the DOM insertion.
- currentlyAddingScript = node;
- if (baseElement) {
- head.insertBefore(node, baseElement);
- } else {
- head.appendChild(node);
- }
- currentlyAddingScript = null;
-
- return node;
- } else if (isWebWorker) {
- try {
- //In a web worker, use importScripts. This is not a very
- //efficient use of importScripts, importScripts will block until
- //its script is downloaded and evaluated. However, if web workers
- //are in play, the expectation that a build has been done so that
- //only one script needs to be loaded anyway. This may need to be
- //reevaluated if other use cases become common.
- importScripts(url);
-
- //Account for anonymous modules
- context.completeLoad(moduleName);
- } catch (e) {
- context.onError(makeError('importscripts',
- 'importScripts failed for ' +
- moduleName + ' at ' + url,
- e,
- [moduleName]));
- }
- }
- };
-
- function getInteractiveScript() {
- if (interactiveScript && interactiveScript.readyState === 'interactive') {
- return interactiveScript;
- }
-
- eachReverse(scripts(), function (script) {
- if (script.readyState === 'interactive') {
- return (interactiveScript = script);
- }
- });
- return interactiveScript;
- }
-
- //Look for a data-main script attribute, which could also adjust the baseUrl.
- if (isBrowser && !cfg.skipDataMain) {
- //Figure out baseUrl. Get it from the script tag with require.js in it.
- eachReverse(scripts(), function (script) {
- //Set the 'head' where we can append children by
- //using the script's parent.
- if (!head) {
- head = script.parentNode;
- }
-
- //Look for a data-main attribute to set main script for the page
- //to load. If it is there, the path to data main becomes the
- //baseUrl, if it is not already set.
- dataMain = script.getAttribute('data-main');
- if (dataMain) {
- //Preserve dataMain in case it is a path (i.e. contains '?')
- mainScript = dataMain;
-
- //Set final baseUrl if there is not already an explicit one.
- if (!cfg.baseUrl) {
- //Pull off the directory of data-main for use as the
- //baseUrl.
- src = mainScript.split('/');
- mainScript = src.pop();
- subPath = src.length ? src.join('/') + '/' : './';
-
- cfg.baseUrl = subPath;
- }
-
- //Strip off any trailing .js since mainScript is now
- //like a module name.
- mainScript = mainScript.replace(jsSuffixRegExp, '');
-
- //If mainScript is still a path, fall back to dataMain
- if (req.jsExtRegExp.test(mainScript)) {
- mainScript = dataMain;
- }
-
- //Put the data-main script in the files to load.
- cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];
-
- return true;
- }
- });
- }
-
- /**
- * The function that handles definitions of modules. Differs from
- * require() in that a string for the module should be the first argument,
- * and the function to execute after dependencies are loaded should
- * return a value to define the module corresponding to the first argument's
- * name.
- */
- define = function (name, deps, callback) {
- var node, context;
-
- //Allow for anonymous modules
- if (typeof name !== 'string') {
- //Adjust args appropriately
- callback = deps;
- deps = name;
- name = null;
- }
-
- //This module may not have dependencies
- if (!isArray(deps)) {
- callback = deps;
- deps = null;
- }
-
- //If no name, and callback is a function, then figure out if it a
- //CommonJS thing with dependencies.
- if (!deps && isFunction(callback)) {
- deps = [];
- //Remove comments from the callback string,
- //look for require calls, and pull them into the dependencies,
- //but only if there are function args.
- if (callback.length) {
- callback
- .toString()
- .replace(commentRegExp, '')
- .replace(cjsRequireRegExp, function (match, dep) {
- deps.push(dep);
- });
-
- //May be a CommonJS thing even without require calls, but still
- //could use exports, and module. Avoid doing exports and module
- //work though if it just needs require.
- //REQUIRES the function to expect the CommonJS variables in the
- //order listed below.
- deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
- }
- }
-
- //If in IE 6-8 and hit an anonymous define() call, do the interactive
- //work.
- if (useInteractive) {
- node = currentlyAddingScript || getInteractiveScript();
- if (node) {
- if (!name) {
- name = node.getAttribute('data-requiremodule');
- }
- context = contexts[node.getAttribute('data-requirecontext')];
- }
- }
-
- //Always save off evaluating the def call until the script onload handler.
- //This allows multiple modules to be in a file without prematurely
- //tracing dependencies, and allows for anonymous module support,
- //where the module name is not known until the script onload event
- //occurs. If no context, use the global queue, and get it processed
- //in the onscript load callback.
- (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
- };
-
- define.amd = {
- jQuery: true
- };
-
-
- /**
- * Executes the text. Normally just uses eval, but can be modified
- * to use a better, environment-specific call. Only used for transpiling
- * loader plugins, not for plain JS modules.
- * @param {String} text the text to execute/evaluate.
- */
- req.exec = function (text) {
- /*jslint evil: true */
- return eval(text);
- };
-
- //Set up with config info.
- req(cfg);
-}(this));
diff --git a/webpack.config.js b/webpack.config.js
new file mode 100644
index 00000000..529f6b11
--- /dev/null
+++ b/webpack.config.js
@@ -0,0 +1,49 @@
+const webpack = require('webpack')
+const PACKAGE = require('./package.json')
+const TerserPlugin = require('terser-webpack-plugin')
+
+module.exports = {
+ entry: {
+ list: './src/index.js',
+ 'list.min': './src/index.js',
+ },
+ output: {
+ path: __dirname + '/dist',
+ filename: '[name].js',
+ library: 'List',
+ },
+ devtool: 'cheap-module-source-map',
+ module: {
+ rules: [
+ {
+ test: /\.js$/,
+ exclude: /(node_modules)/,
+ use: {
+ loader: 'babel-loader',
+ options: {
+ presets: ['@babel/preset-env'],
+ },
+ },
+ },
+ ],
+ },
+ devServer: {
+ inline: true,
+ },
+ plugins: [],
+ optimization: {
+ minimize: true,
+ minimizer: [
+ new TerserPlugin({
+ include: /\.min\.js$/,
+ extractComments: false,
+ terserOptions: {
+ format: {
+ comments: /^! List.js v.*/,
+ },
+ mangle: true,
+ },
+ }),
+ ],
+ },
+}