code
stringlengths
2
1.05M
/*! Select2 4.0.6-rc.0 | https://github.com/select2/select2/blob/master/LICENSE.md */ (function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var e=jQuery.fn.select2.amd;return e.define("select2/i18n/lt",[],function(){function e(e,t,n,r){return e%10===1&&(e%100<11||e%100>19)?t:e%10>=2&&e%10<=9&&(e%100<11||e%100>19)?n:r}return{inputTooLong:function(t){var n=t.input.length-t.maximum,r="Pašalinkite "+n+" simbol";return r+=e(n,"į","ius","ių"),r},inputTooShort:function(t){var n=t.minimum-t.input.length,r="Įrašykite dar "+n+" simbol";return r+=e(n,"į","ius","ių"),r},loadingMore:function(){return"Kraunama daugiau rezultatų…"},maximumSelected:function(t){var n="Jūs galite pasirinkti tik "+t.maximum+" element";return n+=e(t.maximum,"ą","us","ų"),n},noResults:function(){return"Atitikmenų nerasta"},searching:function(){return"Ieškoma…"}}}),{define:e.define,require:e.require}})();
console.warn("warn -",`Imports like "const dash = require('simple-icons/icons/dash');" have been deprecated in v6.0.0 and will no longer work from v7.0.0, use "const { siDash } = require('simple-icons/icons');" instead`),module.exports={title:"Dash",slug:"dash",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Dash</title><path d="'+this.path+'"/></svg>'},path:"M3.21 9.967C.922 9.967.595 11.457.38 12.36.093 13.538 0 14.02 0 14.02h8.947c2.29 0 2.617-1.492 2.832-2.394.285-1.178.379-1.66.379-1.66zM15.72 2.26H6.982L6.26 6.307l7.884.01c3.885 0 5.03 1.41 4.997 3.748-.019 1.196-.537 3.225-.762 3.884-.598 1.753-1.827 3.749-6.435 3.744l-7.666-.004-.725 4.052h8.718c3.075 0 4.38-.36 5.767-.995 3.071-1.426 4.9-4.455 5.633-8.41C24.76 6.448 23.403 2.26 15.72 2.26z",source:"https://www.dash.org/brand-assets/",hex:"008DE4",guidelines:"https://www.dash.org/brand-guidelines/",license:void 0};
'use strict'; /** * Stadium mechanics inherit from gen 1 mechanics, but fixes some stuff. */ exports.BattleScripts = { inherit: 'gen1', gen: 1, // BattlePokemon scripts. pokemon: { // Stadium shares gen 1 code but it fixes some problems with it. getStat: function (statName, unmodified) { statName = toId(statName); if (statName === 'hp') return this.maxhp; if (unmodified) return this.stats[statName]; return this.modifiedStats[statName]; }, // Gen 1 function to apply a stat modification that is only active until the stat is recalculated or mon switched. // Modified stats are declared in BattlePokemon object in battle-engine.js in about line 303. modifyStat: function (stat, modifier) { if (!(stat in this.stats)) return; this.modifiedStats[stat] = this.battle.clampIntRange(Math.floor(this.modifiedStats[stat] * modifier), 1); }, // This is run on Stadium after boosts and status changes. recalculateStats: function () { for (let statName in this.stats) { let stat = this.template.baseStats[statName]; stat = Math.floor(Math.floor(2 * stat + this.set.ivs[statName] + Math.floor(this.set.evs[statName] / 4)) * this.level / 100 + 5); this.baseStats[statName] = this.stats[statName] = Math.floor(stat); this.modifiedStats[statName] = Math.floor(stat); // Re-apply drops, if necessary. if (this.status === 'par') this.modifyStat('spe', 0.25); if (this.status === 'brn') this.modifyStat('atk', 0.5); if (this.boosts[statName] !== 0) { if (this.boosts[statName] >= 0) { this.modifyStat(statName, [1, 1.5, 2, 2.5, 3, 3.5, 4][this.boosts[statName]]); } else { this.modifyStat(statName, [100, 66, 50, 40, 33, 28, 25][-this.boosts[statName]] / 100); } } } }, // Stadium's fixed boosting function. boostBy: function (boost) { let changed = false; for (let i in boost) { let delta = boost[i]; this.boosts[i] += delta; if (this.boosts[i] > 6) { delta -= this.boosts[i] - 6; this.boosts[i] = 6; } if (this.boosts[i] < -6) { delta -= this.boosts[i] - (-6); this.boosts[i] = -6; } if (delta) changed = true; } this.recalculateStats(); return changed; }, }, // Battle scripts. runMove: function (move, pokemon, targetLoc, sourceEffect) { let target = this.getTarget(pokemon, move, targetLoc); move = this.getMove(move); if (!target) target = this.resolveTarget(pokemon, move); if (target.subFainted) delete target.subFainted; this.setActiveMove(move, pokemon, target); if (pokemon.movedThisTurn || !this.runEvent('BeforeMove', pokemon, target, move)) { this.debug('' + pokemon.id + ' move interrupted; movedThisTurn: ' + pokemon.movedThisTurn); this.clearActiveMove(true); // This is only run for sleep this.runEvent('AfterMoveSelf', pokemon, target, move); return; } if (move.beforeMoveCallback) { if (move.beforeMoveCallback.call(this, pokemon, target, move)) { this.clearActiveMove(true); return; } } pokemon.lastDamage = 0; let lockedMove = this.runEvent('LockMove', pokemon); if (lockedMove === true) lockedMove = false; if (!lockedMove && !pokemon.volatiles['partialtrappinglock']) { pokemon.deductPP(move, null, target); } this.useMove(move, pokemon, target, sourceEffect); this.singleEvent('AfterMove', move, null, pokemon, target, move); // If rival fainted if (target.hp <= 0) { // We remove screens target.side.removeSideCondition('reflect'); target.side.removeSideCondition('lightscreen'); } else { this.runEvent('AfterMoveSelf', pokemon, target, move); } // For partial trapping moves, we are saving the target. if (move.volatileStatus === 'partiallytrapped' && target && target.hp > 0) { // It hit, so let's remove must recharge volatile. Yup, this happens on Stadium. target.removeVolatile('mustrecharge'); // Let's check if the lock exists if (pokemon.volatiles['partialtrappinglock'] && target.volatiles['partiallytrapped']) { // Here the partialtrappinglock volatile has been already applied if (!pokemon.volatiles['partialtrappinglock'].locked) { // If it's the first hit, we save the target pokemon.volatiles['partialtrappinglock'].locked = target; } } // If we move to here, the move failed and there's no partial trapping lock } }, tryMoveHit: function (target, pokemon, move, spreadHit) { let boostTable = [1, 4 / 3, 5 / 3, 2, 7 / 3, 8 / 3, 3]; let doSelfDestruct = true; let damage = 0; // First, check if the Pokémon is immune to this move. if (move.ignoreImmunity !== true && !move.ignoreImmunity[move.type] && !target.runImmunity(move.type, true)) { if (move.selfdestruct) { this.faint(pokemon, pokemon, move); } return false; } // Now, let's calculate the accuracy. let accuracy = move.accuracy; // Partial trapping moves: true accuracy while it lasts if (pokemon.volatiles['partialtrappinglock']) { if (move.volatileStatus === 'partiallytrapped' && target === pokemon.volatiles['partialtrappinglock'].locked) { accuracy = true; } else if (pokemon.volatiles['partialtrappinglock'].locked !== target) { // The target switched, therefor, you fail using wrap. delete pokemon.volatiles['partialtrappinglock']; return false; } } // OHKO moves only have a chance to hit if the user is at least as fast as the target if (move.ohko) { if (target.speed > pokemon.speed) { this.add('-immune', target, '[ohko]'); return false; } } // Calculate true accuracy for gen 1, which uses 0-255. if (accuracy !== true) { accuracy = Math.floor(accuracy * 255 / 100); // Check also for accuracy modifiers. if (!move.ignoreAccuracy) { if (pokemon.boosts.accuracy > 0) { accuracy *= boostTable[pokemon.boosts.accuracy]; } else { accuracy = Math.floor(accuracy / boostTable[-pokemon.boosts.accuracy]); } } if (!move.ignoreEvasion) { if (target.boosts.evasion > 0 && !move.ignorePositiveEvasion) { accuracy = Math.floor(accuracy / boostTable[target.boosts.evasion]); } else if (target.boosts.evasion < 0) { accuracy *= boostTable[-target.boosts.evasion]; } } } accuracy = this.runEvent('Accuracy', target, pokemon, move, accuracy); // Stadium fixes the 1/256 accuracy bug. if (accuracy !== true && this.random(256) > accuracy) { this.attrLastMove('[miss]'); this.add('-miss', pokemon); damage = false; } // If damage is 0 and not false it means it didn't miss, let's calc. if (damage !== false) { pokemon.lastDamage = 0; if (move.multihit) { let hits = move.multihit; if (hits.length) { // Yes, it's hardcoded... meh if (hits[0] === 2 && hits[1] === 5) { hits = [2, 2, 3, 3, 4, 5][this.random(6)]; } else { hits = this.random(hits[0], hits[1] + 1); } } hits = Math.floor(hits); // In gen 1, all the hits have the same damage for multihits move let moveDamage = 0; let firstDamage; let i; for (i = 0; i < hits && target.hp && pokemon.hp; i++) { if (i === 0) { // First hit, we calculate moveDamage = this.moveHit(target, pokemon, move); firstDamage = moveDamage; } else { // We get the previous damage to make it fix damage move.damage = firstDamage; moveDamage = this.moveHit(target, pokemon, move); } if (moveDamage === false) break; damage = (moveDamage || 0); if (target.subFainted) { i++; break; } } move.damage = null; if (i === 0) return true; this.add('-hitcount', target, i); } else { damage = this.moveHit(target, pokemon, move); } } if (move.category !== 'Status') target.gotAttacked(move, damage, pokemon); // Checking if substitute fainted if (target.subFainted) doSelfDestruct = false; if (move.selfdestruct && doSelfDestruct) { this.faint(pokemon, pokemon, move); } // The move missed. if (!damage && damage !== 0) { // Delete the partial trap lock if necessary. delete pokemon.volatiles['partialtrappinglock']; return false; } if (move.ohko) this.add('-ohko'); if (!move.negateSecondary) { this.singleEvent('AfterMoveSecondary', move, null, target, pokemon, move); this.runEvent('AfterMoveSecondary', target, pokemon, move); } return damage; }, moveHit: function (target, pokemon, move, moveData, isSecondary, isSelf) { let damage = 0; move = this.getMoveCopy(move); if (!isSecondary && !isSelf) this.setActiveMove(move, pokemon, target); let hitResult = true; if (!moveData) moveData = move; if (move.ignoreImmunity === undefined) { move.ignoreImmunity = (move.category === 'Status'); } if (target) { hitResult = this.singleEvent('TryHit', moveData, {}, target, pokemon, move); // Partial trapping moves still apply their volatile to Pokémon behind a Sub let targetHadSub = (target && target.volatiles['substitute']); if (targetHadSub && moveData.volatileStatus && moveData.volatileStatus === 'partiallytrapped') { target.addVolatile(moveData.volatileStatus, pokemon, move); } if (!hitResult) { if (hitResult === false) this.add('-fail', target); return false; } // Only run the hit events for the hit itself, not the secondary or self hits if (!isSelf && !isSecondary) { hitResult = this.runEvent('TryHit', target, pokemon, move); if (!hitResult) { if (hitResult === false) this.add('-fail', target); // Special Substitute hit flag if (hitResult !== 0) { return false; } } if (!this.runEvent('TryFieldHit', target, pokemon, move)) { return false; } } else if (isSecondary && !moveData.self) { hitResult = this.runEvent('TrySecondaryHit', target, pokemon, moveData); } if (hitResult === 0) { target = null; } else if (!hitResult) { if (hitResult === false) this.add('-fail', target); return false; } } if (target) { let didSomething = false; damage = this.getDamage(pokemon, target, moveData); if ((damage || damage === 0) && !target.fainted) { if (move.noFaint && damage >= target.hp) { damage = target.hp - 1; } damage = this.damage(damage, target, pokemon, move); if (!(damage || damage === 0)) return false; didSomething = true; } else if (damage === false && typeof hitResult === 'undefined') { this.add('-fail', target); } if (damage === false || damage === null) { return false; } if (moveData.boosts && !target.fainted) { this.boost(moveData.boosts, target, pokemon, move); } if (moveData.heal && !target.fainted) { let d = target.heal(Math.floor(target.maxhp * moveData.heal[0] / moveData.heal[1])); if (!d) { this.add('-fail', target); return false; } this.add('-heal', target, target.getHealth); didSomething = true; } if (moveData.status) { if (!target.status) { target.setStatus(moveData.status, pokemon, move); target.recalculateStats(); } else if (!isSecondary) { if (target.status === moveData.status) { this.add('-fail', target, target.status); } else { this.add('-fail', target); } } didSomething = true; } if (moveData.forceStatus) { if (target.setStatus(moveData.forceStatus, pokemon, move)) { target.recalculateStats(); didSomething = true; } } if (moveData.volatileStatus) { if (target.addVolatile(moveData.volatileStatus, pokemon, move)) { didSomething = true; } } if (moveData.sideCondition) { if (target.side.addSideCondition(moveData.sideCondition, pokemon, move)) { didSomething = true; } } if (moveData.pseudoWeather) { if (this.addPseudoWeather(moveData.pseudoWeather, pokemon, move)) { didSomething = true; } } // Hit events hitResult = this.singleEvent('Hit', moveData, {}, target, pokemon, move); if (!isSelf && !isSecondary) { this.runEvent('Hit', target, pokemon, move); } if (!hitResult && !didSomething) { if (hitResult === false) this.add('-fail', target); return false; } } // Here's where self effects are applied. if (moveData.self) { this.moveHit(pokemon, pokemon, move, moveData.self, isSecondary, true); } // Now we can save the partial trapping damage. if (pokemon.volatiles['partialtrappinglock']) { pokemon.volatiles['partialtrappinglock'].damage = pokemon.lastDamage; } // Apply move secondaries. if (moveData.secondaries) { for (let i = 0; i < moveData.secondaries.length; i++) { // We check here whether to negate the probable secondary status if it's para, burn, or freeze. // In the game, this is checked and if true, the random number generator is not called. // That means that a move that does not share the type of the target can status it. // If a move that was not fire-type would exist on Gen 1, it could burn a Pokémon. if (!(moveData.secondaries[i].status && moveData.secondaries[i].status in {'par':1, 'brn':1, 'frz':1} && target && target.hasType(move.type))) { let effectChance = Math.floor(moveData.secondaries[i].chance * 255 / 100); if (typeof moveData.secondaries[i].chance === 'undefined' || this.random(256) < effectChance) { this.moveHit(target, pokemon, move, moveData.secondaries[i], true, isSelf); } } } } if (move.selfSwitch && pokemon.hp) { pokemon.switchFlag = move.selfSwitch; } return damage; }, getDamage: function (pokemon, target, move, suppressMessages) { // First of all, we get the move. if (typeof move === 'string') move = this.getMove(move); if (typeof move === 'number') { move = { basePower: move, type: '???', category: 'Physical', willCrit: false, flags: {}, }; } // Let's see if the target is immune to the move. if (!move.ignoreImmunity || (move.ignoreImmunity !== true && !move.ignoreImmunity[move.type])) { if (!target.runImmunity(move.type, true)) { return false; } } // Is it an OHKO move? if (move.ohko) { return target.maxhp; } // We edit the damage through move's damage callback if necessary. if (move.damageCallback) { return move.damageCallback.call(this, pokemon, target); } // We take damage from damage=level moves (seismic toss). if (move.damage === 'level') { return pokemon.level; } // If there's a fix move damage, we return that. if (move.damage) { return move.damage; } // If it's the first hit on a Normal-type partially trap move, it hits Ghosts anyways but damage is 0. if (move.volatileStatus === 'partiallytrapped' && move.type === 'Normal' && target.hasType('Ghost')) { return 0; } // Let's check if we are in middle of a partial trap sequence to return the previous damage. if (pokemon.volatiles['partialtrappinglock'] && (target === pokemon.volatiles['partialtrappinglock'].locked)) { return pokemon.volatiles['partialtrappinglock'].damage; } // We check the category and typing to calculate later on the damage. if (!move.category) move.category = 'Physical'; if (!move.defensiveCategory) move.defensiveCategory = move.category; // '???' is typeless damage: used for Struggle and Confusion etc if (!move.type) move.type = '???'; let type = move.type; // We get the base power and apply basePowerCallback if necessary. let basePower = move.basePower; if (move.basePowerCallback) { basePower = move.basePowerCallback.call(this, pokemon, target, move); } // We check if the base power is proper. if (!basePower) { if (basePower === 0) return; // Returning undefined means not dealing damage return basePower; } basePower = this.clampIntRange(basePower, 1); // Checking for the move's Critical Hit possibility. We check if it's a 100% crit move, otherwise we calculate the chance. move.crit = move.willCrit || false; if (!move.crit) { // In Stadium, the critical chance is based on speed. // First, we get the base speed and store it. Then we add 76. This is our current crit chance. let critChance = pokemon.template.baseStats['spe'] + 76; // Now we right logical shift it two places, essentially dividing by 4 and flooring it. critChance = critChance >> 2; // Now we check for focus energy volatile. if (pokemon.volatiles['focusenergy']) { // If it exists, crit chance is multiplied by 4 and floored with a logical left shift. critChance = critChance << 2; // Then we add 160. critChance += 160; } else { // If it is not active, we left shift it by 1. critChance = critChance << 1; } // Now we check for the move's critical hit ratio. if (move.critRatio === 2) { // High crit ratio, we multiply the result so far by 4. critChance = critChance << 2; } else if (move.critRatio === 1) { // Normal hit ratio, we divide the crit chance by 2 and floor the result again. critChance = critChance >> 1; } // Now we make sure it's a number between 1 and 255. critChance = this.clampIntRange(critChance, 1, 255); // Last, we check deppending on ratio if the move critical hits or not. // We compare our critical hit chance against a random number between 0 and 255. // If the random number is lower, we get a critical hit. This means there is always a 1/255 chance of not hitting critically. if (critChance > 0) { move.crit = (this.random(256) < critChance); } } // There is a critical hit. if (move.crit) { move.crit = this.runEvent('CriticalHit', target, null, move); } // Happens after crit calculation. if (basePower) { basePower = this.runEvent('BasePower', pokemon, target, move, basePower); if (move.basePowerModifier) { basePower *= move.basePowerModifier; } } if (!basePower) return 0; basePower = this.clampIntRange(basePower, 1); // We now check attacker's and defender's stats. let level = pokemon.level; let attacker = pokemon; let defender = target; if (move.useTargetOffensive) attacker = target; if (move.useSourceDefensive) defender = pokemon; let atkType = (move.category === 'Physical') ? 'atk' : 'spa'; let defType = (move.defensiveCategory === 'Physical') ? 'def' : 'spd'; let attack = attacker.getStat(atkType); let defense = defender.getStat(defType); // In gen 1, screen effect is applied here. if ((defType === 'def' && defender.volatiles['reflect']) || (defType === 'spd' && defender.volatiles['lightscreen'])) { this.debug('Screen doubling (Sp)Def'); defense *= 2; defense = this.clampIntRange(defense, 1, 1998); } // In the event of a critical hit, the ofense and defense changes are ignored. // This includes both boosts and screens. // Also, level is doubled in damage calculation. if (move.crit) { move.ignoreOffensive = true; move.ignoreDefensive = true; level *= 2; if (!suppressMessages) this.add('-crit', target); } if (move.ignoreOffensive) { this.debug('Negating (sp)atk boost/penalty.'); attack = attacker.getStat(atkType, true); } if (move.ignoreDefensive) { this.debug('Negating (sp)def boost/penalty.'); defense = target.getStat(defType, true); } // When either attack or defense are higher than 256, they are both divided by 4 and moded by 256. // This is what cuases the roll over bugs. if (attack >= 256 || defense >= 256) { attack = this.clampIntRange(Math.floor(attack / 4) % 256, 1); // Defense isn't checked on the cartridge, but we don't want those / 0 bugs on the sim. defense = this.clampIntRange(Math.floor(defense / 4) % 256, 1); } // Self destruct moves halve defense at this point. if (move.selfdestruct && defType === 'def') { defense = this.clampIntRange(Math.floor(defense / 2), 1); } // Let's go with the calculation now that we have what we need. // We do it step by step just like the game does. let damage = level * 2; damage = Math.floor(damage / 5); damage += 2; damage *= basePower; damage *= attack; damage = Math.floor(damage / defense); damage = this.clampIntRange(Math.floor(damage / 50), 1, 997); damage += 2; // STAB damage bonus, the "???" type never gets STAB if (type !== '???' && pokemon.hasType(type)) { damage += Math.floor(damage / 2); } // Type effectiveness. // The order here is not correct, must change to check the move versus each type. let totalTypeMod = this.getEffectiveness(type, target); // Super effective attack if (totalTypeMod > 0) { if (!suppressMessages) this.add('-supereffective', target); damage *= 20; damage = Math.floor(damage / 10); if (totalTypeMod >= 2) { damage *= 20; damage = Math.floor(damage / 10); } } if (totalTypeMod < 0) { if (!suppressMessages) this.add('-resisted', target); damage *= 5; damage = Math.floor(damage / 10); if (totalTypeMod <= -2) { damage *= 5; damage = Math.floor(damage / 10); } } // If damage becomes 0, the move is made to miss. // This occurs when damage was either 2 or 3 prior to applying STAB/Type matchup, and target is 4x resistant to the move. if (damage === 0) return damage; // Apply random factor is damage is greater than 1 if (damage > 1) { damage *= this.random(217, 256); damage = Math.floor(damage / 255); if (damage > target.hp && !target.volatiles['substitute']) damage = target.hp; if (target.volatiles['substitute'] && damage > target.volatiles['substitute'].hp) damage = target.volatiles['substitute'].hp; } // We are done, this is the final damage. return Math.floor(damage); }, damage: function (damage, target, source, effect) { if (this.event) { if (!target) target = this.event.target; if (!source) source = this.event.source; if (!effect) effect = this.effect; } if (!target || !target.hp) return 0; effect = this.getEffect(effect); if (!(damage || damage === 0)) return damage; if (damage !== 0) damage = this.clampIntRange(damage, 1); if (effect.id !== 'struggle-recoil') { // Struggle recoil is not affected by effects damage = this.runEvent('Damage', target, source, effect, damage); if (!(damage || damage === 0)) { this.debug('damage event failed'); return damage; } } if (damage !== 0) damage = this.clampIntRange(damage, 1); target.battle.lastDamage = damage; damage = target.damage(damage, source, effect); if (source) source.lastDamage = damage; let name = effect.fullname; if (name === 'tox') name = 'psn'; switch (effect.id) { case 'partiallytrapped': this.add('-damage', target, target.getHealth, '[from] ' + this.effectData.sourceEffect.fullname, '[partiallytrapped]'); break; default: if (effect.effectType === 'Move') { this.add('-damage', target, target.getHealth); } else if (source && source !== target) { this.add('-damage', target, target.getHealth, '[from] ' + effect.fullname, '[of] ' + source); } else { this.add('-damage', target, target.getHealth, '[from] ' + name); } break; } // In Stadium, recoil doesn't happen if you faint an opponent. if (effect.recoil && source && target && target.hp > 0) { this.damage(this.clampIntRange(Math.floor(damage * effect.recoil[0] / effect.recoil[1]), 1), source, target, 'recoil'); } if (effect.drain && source) { this.heal(this.clampIntRange(Math.floor(damage * effect.drain[0] / effect.drain[1]), 1), source, target, 'drain'); } if (target.fainted) { this.faint(target); } else { damage = this.runEvent('AfterDamage', target, source, effect, damage); } return damage; }, directDamage: function (damage, target, source, effect) { if (this.event) { if (!target) target = this.event.target; if (!source) source = this.event.source; if (!effect) effect = this.effect; } if (!target || !target.hp) return 0; if (!damage) return 0; damage = this.clampIntRange(damage, 1); damage = target.damage(damage, source, effect); // Now we sent the proper -damage. switch (effect.id) { case 'strugglerecoil': this.add('-damage', target, target.getHealth, '[from] recoil'); break; case 'confusion': this.add('-damage', target, target.getHealth, '[from] confusion'); break; default: this.add('-damage', target, target.getHealth); break; } if (target.fainted) this.faint(target); return damage; }, };
Clazz.declarePackage ("JM"); Clazz.load (["JU.Edge", "JV.JC"], "JM.Bond", ["JU.C"], function () { c$ = Clazz.decorateAsClass (function () { this.atom1 = null; this.atom2 = null; this.mad = 0; this.colix = 0; this.shapeVisibilityFlags = 0; Clazz.instantialize (this, arguments); }, JM, "Bond", JU.Edge); Clazz.makeConstructor (c$, function (atom1, atom2, order, mad, colix) { this.atom1 = atom1; this.atom2 = atom2; this.colix = colix; this.setOrder (order); this.setMad (mad); }, "JM.Atom,JM.Atom,~N,~N,~N"); Clazz.defineMethod (c$, "setMad", function (mad) { this.mad = mad; this.setShapeVisibility (mad != 0); }, "~N"); Clazz.defineMethod (c$, "setShapeVisibility", function (isVisible) { var wasVisible = ((this.shapeVisibilityFlags & JM.Bond.myVisibilityFlag) != 0); if (wasVisible == isVisible) return; this.atom1.addDisplayedBond (JM.Bond.myVisibilityFlag, isVisible); this.atom2.addDisplayedBond (JM.Bond.myVisibilityFlag, isVisible); if (isVisible) this.shapeVisibilityFlags |= JM.Bond.myVisibilityFlag; else this.shapeVisibilityFlags &= ~JM.Bond.myVisibilityFlag; }, "~B"); Clazz.defineMethod (c$, "getIdentity", function () { return (this.index + 1) + " " + JU.Edge.getBondOrderNumberFromOrder (this.order) + " " + this.atom1.getInfo () + " -- " + this.atom2.getInfo () + " " + this.atom1.distance (this.atom2); }); Clazz.overrideMethod (c$, "isCovalent", function () { return (this.order & 1023) != 0; }); Clazz.overrideMethod (c$, "isHydrogen", function () { return JM.Bond.isOrderH (this.order); }); c$.isOrderH = Clazz.defineMethod (c$, "isOrderH", function (order) { return (order & 30720) != 0; }, "~N"); Clazz.defineMethod (c$, "isStereo", function () { return (this.order & 1024) != 0; }); Clazz.defineMethod (c$, "isPartial", function () { return (this.order & 224) != 0; }); Clazz.defineMethod (c$, "isAromatic", function () { return (this.order & 512) != 0; }); Clazz.defineMethod (c$, "isPymolStyle", function () { return (this.order & 98304) == 98304; }); Clazz.defineMethod (c$, "getEnergy", function () { return 0; }); Clazz.defineMethod (c$, "getValence", function () { return (!this.isCovalent () ? 0 : this.isPartial () || this.is (515) ? 1 : this.order & 7); }); Clazz.defineMethod (c$, "deleteAtomReferences", function () { if (this.atom1 != null) this.atom1.deleteBond (this); if (this.atom2 != null) this.atom2.deleteBond (this); this.atom1 = this.atom2 = null; }); Clazz.defineMethod (c$, "setTranslucent", function (isTranslucent, translucentLevel) { this.colix = JU.C.getColixTranslucent3 (this.colix, isTranslucent, translucentLevel); }, "~B,~N"); Clazz.defineMethod (c$, "setOrder", function (order) { if (this.atom1.getElementNumber () == 16 && this.atom2.getElementNumber () == 16) order |= 256; if (order == 512) order = 515; this.order = order | (this.order & 131072); }, "~N"); Clazz.overrideMethod (c$, "getAtomIndex1", function () { return this.atom1.i; }); Clazz.overrideMethod (c$, "getAtomIndex2", function () { return this.atom2.i; }); Clazz.overrideMethod (c$, "getCovalentOrder", function () { return JU.Edge.getCovalentBondOrder (this.order); }); Clazz.defineMethod (c$, "getOtherAtom", function (thisAtom) { return (this.atom1 === thisAtom ? this.atom2 : this.atom2 === thisAtom ? this.atom1 : null); }, "JM.Atom"); Clazz.defineMethod (c$, "is", function (bondType) { return (this.order & -131073) == bondType; }, "~N"); Clazz.overrideMethod (c$, "getOtherAtomNode", function (thisAtom) { return (this.atom1 === thisAtom ? this.atom2 : this.atom2 === thisAtom ? this.atom1 : null); }, "JU.Node"); Clazz.overrideMethod (c$, "toString", function () { return this.atom1 + " - " + this.atom2; }); c$.myVisibilityFlag = c$.prototype.myVisibilityFlag = JV.JC.getShapeVisibilityFlag (1); });
/*! * Stylus - plugin - url * Copyright(c) 2010 LearnBoost <dev@learnboost.com> * MIT Licensed */ /** * Module dependencies. */ var Compiler = require('../visitor/compiler') , nodes = require('../nodes') , parse = require('url').parse , extname = require('path').extname , utils = require('../utils') , fs = require('fs'); /** * Mime table. */ var mimes = { '.gif': 'image/gif' , '.png': 'image/png' , '.jpg': 'image/jpeg' , '.jpeg': 'image/jpeg' }; /** * Return a url() function with the given `options`. * * Options: * * - `limit` bytesize limit defaulting to 30Kb * - `paths` image resolution path(s), merged with general lookup paths * * Examples: * * stylus(str) * .set('filename', __dirname + '/css/test.styl') * .define('url', stylus.url({ paths: [__dirname + '/public'] })) * .render(function(err, css){ ... }) * * @param {Object} options * @return {Function} * @api public */ module.exports = function(options) { options = options || {}; var sizeLimit = options.limit || 30000 , _paths = options.paths || []; function url(url){ // Compile the url var compiler = new Compiler(url); compiler.isURL = true; var url = url.nodes.map(function(node){ return compiler.visit(node); }).join(''); // Parse literal var url = parse(url) , ext = extname(url.pathname) , mime = mimes[ext] , literal = new nodes.Literal('url("' + url.href + '")') , paths = _paths.concat(this.paths) , founds , buf; // Not supported if (!mime) return literal; // Absolute if (url.protocol) return literal; // Lookup found = utils.lookup(url.pathname, paths); // Failed to lookup if (!found) return literal; // Read data buf = fs.readFileSync(found); // To large if (buf.length > sizeLimit) return literal; // Encode return new nodes.Literal('url("data:' + mime + ';base64,' + buf.toString('base64') + '")'); }; url.raw = true; return url; };
var testDocument = require("./test-document") var testDomElement = require("./test-dom-element") var document = require("../index") testDocument(document) testDomElement(document) if (typeof window !== "undefined" && window.document) { testDocument(window.document) testDomElement(window.document) }
import propName from './propName'; const DEFAULT_OPTIONS = { spreadStrict: true, ignoreCase: true, }; /** * Returns boolean indicating whether an prop exists on the props * property of a JSX element node. */ export default function hasProp(props = [], prop = '', options = DEFAULT_OPTIONS) { const propToCheck = options.ignoreCase ? prop.toUpperCase() : prop; return props.some(attribute => { // If the props contain a spread prop, then refer to strict param. if (attribute.type === 'JSXSpreadAttribute') { return !options.spreadStrict; } const currentProp = options.ignoreCase ? propName(attribute).toUpperCase() : propName(attribute); return propToCheck === currentProp; }); } /** * Given the props on a node and a list of props to check, this returns a boolean * indicating if any of them exist on the node. */ export function hasAnyProp(nodeProps = [], props = [], options = DEFAULT_OPTIONS) { const propsToCheck = typeof props === 'string' ? props.split(' ') : props; return propsToCheck.some(prop => hasProp(nodeProps, prop, options)); } /** * Given the props on a node and a list of props to check, this returns a boolean * indicating if all of them exist on the node */ export function hasEveryProp(nodeProps = [], props = [], options = DEFAULT_OPTIONS) { const propsToCheck = typeof props === 'string' ? props.split(' ') : props; return propsToCheck.every(prop => hasProp(nodeProps, prop, options)); }
//! moment.js locale configuration //! locale : spanish (es) //! author : Julio Napurí : https://github.com/julionc import moment from '../moment'; var monthsShortDot = 'Ene._Feb._Mar._Abr._May._Jun._Jul._Ago._Sep._Oct._Nov._Dic.'.split('_'), monthsShort = 'Ene_Feb_Mar_Abr_May_Jun_Jul_Ago_Sep_Oct_Nov_Dic'.split('_'); export default moment.defineLocale('es', { months : 'Enero_Febrero_Marzo_Abril_Mayo_Junio_Julio_Agosto_Septiembre_Octubre_Noviembre_Diciembre'.split('_'), monthsShort : function (m, format) { if (/-MMM-/.test(format)) { return monthsShort[m.month()]; } else { return monthsShortDot[m.month()]; } }, weekdays : 'Domingo_Lunes_Martes_Miércoles_Jueves_Viernes_Sábado'.split('_'), weekdaysShort : 'Dom._Lun._Mar._Mié._Jue._Vie._Sáb.'.split('_'), weekdaysMin : 'Do_Lu_Ma_Mi_Ju_Vi_Sá'.split('_'), longDateFormat : { LT : 'H:mm', LTS : 'H:mm:ss', L : 'DD/MM/YYYY', LL : 'D [de] MMMM [de] YYYY', LLL : 'D [de] MMMM [de] YYYY H:mm', LLLL : 'dddd, D [de] MMMM [de] YYYY H:mm' }, calendar : { sameDay : function () { return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextDay : function () { return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextWeek : function () { return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastDay : function () { return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastWeek : function () { return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : 'en %s', past : 'hace %s', s : 'unos segundos', m : 'un minuto', mm : '%d minutos', h : 'una hora', hh : '%d horas', d : 'un día', dd : '%d días', M : 'un mes', MM : '%d meses', y : 'un año', yy : '%d años' }, ordinalParse : /\d{1,2}º/, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } });
(function( $ ) { $.widget("metro.countdown", { version: "1.0.0", options: { style: { background: "bg-dark", foreground: "fg-white", divider: "fg-dark" }, blink: true, days: 1, stoptimer: 0, ontick: function(d, h, m, s){}, onstop: function(){} }, wrappers: {}, _interval: 0, _create: function(){ var that = this, countdown = this.element; $.each(['Days','Hours','Minutes','Seconds'],function(){ $('<span class="count'+this+'">').html( '<span class="digit-wrapper">\ <span class="digit">0</span>\ </span>\ <span class="digit-wrapper">\ <span class="digit">0</span>\ </span>' ).appendTo(countdown); if(this!="Seconds"){ countdown.append('<span class="divider"></span>'); } }); this.wrappers = this.element.find('.digit-wrapper'); if (countdown.data('blink') != undefined) { this.options.blink = countdown.data('blick'); } if (countdown.data('styleBackground') != undefined) { this.options.style.background = countdown.data('styleBackground'); } if (countdown.data('styleForeground') != undefined) { this.options.style.foreground = countdown.data('styleForeground'); } if (countdown.data('styleDivider') != undefined) { this.options.style.divider = countdown.data('styleDivider'); } if (this.options.style.background != "default") { this.element.find(".digit").addClass(this.options.style.background); } if (this.options.style.foreground != "default") { this.element.find(".digit").addClass(this.options.style.foreground); } if (this.options.style.divider != "default") { this.element.find(".divider").addClass(this.options.style.divider); } if (countdown.data('stoptimer') != undefined) { this.options.stoptimer = new Date(countdown.data('stoptimer')); } if (this.options.stoptimer == 0) { this.options.stoptimer = (new Date()).getTime() + this.options.days*24*60*60*1000; } setTimeout( function(){ that.tick() }, 1000); }, _destroy: function(){ }, _setOption: function(key, value){ this._super('_setOption', key, value); }, tick: function(){ var that = this; this._interval = setInterval(function(){ var days = 24*60*60, hours = 60*60, minutes = 60; var left, d, h, m, s; left = Math.floor((that.options.stoptimer - (new Date())) / 1000); if(left < 0){ left = 0; } // Number of days left d = Math.floor(left / days); that.updateDuo(0, 1, d); left -= d*days; // Number of hours left h = Math.floor(left / hours); that.updateDuo(2, 3, h); left -= h*hours; // Number of minutes left m = Math.floor(left / minutes); that.updateDuo(4, 5, m); left -= m*minutes; // Number of seconds left s = left; that.updateDuo(6, 7, s); // Calling an optional user supplied ontick that.options.ontick(d, h, m, s); that.blinkDivider(); // Scheduling another call of this function in 1s if (d === 0 && h === 0 && m === 0 && s === 0) { that.options.onstop(); that.stopDigit(); that._trigger('alarm'); clearInterval(that._interval); } }, 1000); }, blinkDivider: function(){ if (this.options.blink) this.element.find(".divider").toggleClass("no-visible"); }, stopDigit: function(){ this.wrappers.each(function(){ $(this).children(".digit").addClass("stop"); }) }, updateDuo: function(minor, major, value){ this.switchDigit(this.wrappers.eq(minor),Math.floor(value/10)%10); this.switchDigit(this.wrappers.eq(major),value%10); }, switchDigit: function(wrapper, number){ var digit = wrapper.find('.digit'); if(digit.is(':animated')){ return false; } if(wrapper.data('digit') == number){ // We are already showing this number return false; } wrapper.data('digit', number); var replacement = $('<span>',{ 'class':'digit', css:{ top:'-2.1em', opacity:0 }, html:number }); replacement.addClass(this.options.style.background); replacement.addClass(this.options.style.foreground); digit .before(replacement) .removeClass('static') .animate({top:'2.5em'},'fast',function(){ digit.remove(); }); replacement .delay(100) .animate({top:0,opacity:1},'fast'); return true; } }); })( jQuery ); $(function () { $('[data-role=countdown]').countdown(); });
/** * @ngdoc controller * @name Umbraco.Editors.Member.ListController * @function * * @description * The controller for the member list view */ function MemberListController($scope, $routeParams, $location, $q, $window, appState, memberResource, entityResource, navigationService, notificationsService, angularHelper, serverValidationManager, contentEditingHelper, fileManager, formHelper, umbModelMapper, editorState, localizationService) { //setup scope vars $scope.currentSection = appState.getSectionState("currentSection"); $scope.currentNode = null; //the editors affiliated node //we are editing so get the content item from the server memberResource.getListNode($routeParams.id) .then(function (data) { $scope.loaded = true; $scope.content = data; //translate "All Members" if ($scope.content != null && $scope.content.name != null && $scope.content.name.replace(" ", "").toLowerCase() == "allmembers") { localizationService.localize("member_allMembers").then(function (value) { $scope.content.name = value; }); } editorState.set($scope.content); navigationService.syncTree({ tree: "member", path: data.path.split(",") }).then(function (syncArgs) { $scope.currentNode = syncArgs.node; }); //in one particular special case, after we've created a new item we redirect back to the edit // route but there might be server validation errors in the collection which we need to display // after the redirect, so we will bind all subscriptions which will show the server validation errors // if there are any and then clear them so the collection no longer persists them. serverValidationManager.executeAndClearAllSubscriptions(); }); } angular.module("umbraco").controller("Umbraco.Editors.Member.ListController", MemberListController);
module.exports={title:"dwm",slug:"dwm",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>dwm icon</title><path d="M0 11h6V7h2v8h2v-4h2v4h2v-4h10v6h-2v-4h-2v4h-2v-4h-2v4H2v-2h4v-2H2v4H0z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://dwm.suckless.org",hex:"1177AA",guidelines:void 0,license:void 0};
export * from './listbox'; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHVibGljX2FwaS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9hcHAvY29tcG9uZW50cy9saXN0Ym94L3B1YmxpY19hcGkudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsY0FBYyxXQUFXLENBQUMiLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgKiBmcm9tICcuL2xpc3Rib3gnOyJdfQ==
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("widget","de",{move:"Zum verschieben anwählen und ziehen"});
"use strict"; var inherits = require('util').inherits , f = require('util').format , b = require('bson') , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain , debugOptions = require('../connection/utils').debugOptions , EventEmitter = require('events').EventEmitter , Server = require('./server') , ReadPreference = require('./read_preference') , MongoError = require('../error') , Ping = require('./strategies/ping') , Session = require('./session') , BasicCursor = require('../cursor') , BSON = require('bson').native().BSON , State = require('./replset_state') , Logger = require('../connection/logger'); /** * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is * used to construct connecctions. * * @example * var ReplSet = require('mongodb-core').ReplSet * , ReadPreference = require('mongodb-core').ReadPreference * , assert = require('assert'); * * var server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'}); * // Wait for the connection event * server.on('connect', function(server) { * server.destroy(); * }); * * // Start connecting * server.connect(); */ var DISCONNECTED = 'disconnected'; var CONNECTING = 'connecting'; var CONNECTED = 'connected'; var DESTROYED = 'destroyed'; // // ReplSet instance id var replSetId = 1; // // Clone the options var cloneOptions = function(options) { var opts = {}; for(var name in options) { opts[name] = options[name]; } return opts; } // All bson types var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; // BSON parser var bsonInstance = null; /** * Creates a new Replset instance * @class * @param {array} seedlist A list of seeds for the replicaset * @param {boolean} options.setName The Replicaset set name * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry * @param {boolean} [options.emitError=false] Server will emit errors events * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors * @param {number} [options.size=5] Server connection pool size * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled * @param {boolean} [options.noDelay=true] TCP Connection no delay * @param {number} [options.connectionTimeout=10000] TCP Connection timeout setting * @param {number} [options.socketTimeout=0] TCP Socket timeout setting * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed * @param {boolean} [options.ssl=false] Use SSL for connection * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. * @param {Buffer} [options.ca] SSL Certificate store binary buffer * @param {Buffer} [options.cert] SSL Certificate binary buffer * @param {Buffer} [options.key] SSL Key file binary buffer * @param {string} [options.passphrase] SSL Certificate pass phrase * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers * @param {number} [options.acceptableLatency=250] Acceptable latency for selecting a server for reading (in milliseconds) * @return {ReplSet} A cursor instance * @fires ReplSet#connect * @fires ReplSet#ha * @fires ReplSet#joined * @fires ReplSet#left */ var ReplSet = function(seedlist, options) { var self = this; options = options || {}; // Clone the options options = cloneOptions(options); // Validate seedlist if(!Array.isArray(seedlist)) throw new MongoError("seedlist must be an array"); // Validate list if(seedlist.length == 0) throw new MongoError("seedlist must contain at least one entry"); // Validate entries seedlist.forEach(function(e) { if(typeof e.host != 'string' || typeof e.port != 'number') throw new MongoError("seedlist entry must contain a host and port"); }); // Add event listener EventEmitter.call(this); // Set the bson instance bsonInstance = bsonInstance == null ? new BSON(bsonTypes) : bsonInstance; // Internal state hash for the object this.s = { options: options // Logger instance , logger: Logger('ReplSet', options) // Uniquely identify the replicaset instance , id: replSetId++ // Index , index: 0 // Ha Index , haId: 0 // Current credentials used for auth , credentials: [] // Factory overrides , Cursor: options.cursorFactory || BasicCursor // BSON Parser, ensure we have a single instance , bsonInstance: bsonInstance // Pick the right bson parser , bson: options.bson ? options.bson : bsonInstance // Special replicaset options , secondaryOnlyConnectionAllowed: typeof options.secondaryOnlyConnectionAllowed == 'boolean' ? options.secondaryOnlyConnectionAllowed : false , haInterval: options.haInterval || 10000 // Are we running in debug mode , debug: typeof options.debug == 'boolean' ? options.debug : false // The replicaset name , setName: options.setName // Swallow or emit errors , emitError: typeof options.emitError == 'boolean' ? options.emitError : false // Grouping tag used for debugging purposes , tag: options.tag // Do we have a not connected handler , disconnectHandler: options.disconnectHandler // Currently connecting servers , connectingServers: {} // Contains any alternate strategies for picking , readPreferenceStrategies: {} // Auth providers , authProviders: {} // All the servers , disconnectedServers: [] // Initial connection servers , initialConnectionServers: [] // High availability process running , highAvailabilityProcessRunning: false // Full setup , fullsetup: false // All servers accounted for (used for testing) , all: false // Seedlist , seedlist: seedlist // Authentication in progress , authInProgress: false // Servers added while auth in progress , authInProgressServers: [] // Minimum heartbeat frequency used if we detect a server close , minHeartbeatFrequencyMS: 500 // stores high availability timer to allow efficient destroy , haTimer : null } // Add bson parser to options options.bson = this.s.bson; // Set up the connection timeout for the options options.connectionTimeout = options.connectionTimeout || 10000; // Replicaset state var replState = new State(this, { id: this.s.id, setName: this.s.setName , connectingServers: this.s.connectingServers , secondaryOnlyConnectionAllowed: this.s.secondaryOnlyConnectionAllowed }); // Add Replicaset state to our internal state this.s.replState = replState; // BSON property (find a server and pass it along) Object.defineProperty(this, 'bson', { enumerable: true, get: function() { var servers = self.s.replState.getAll(); return servers.length > 0 ? servers[0].bson : null; } }); Object.defineProperty(this, 'id', { enumerable:true, get: function() { return self.s.id; } }); Object.defineProperty(this, 'haInterval', { enumerable:true, get: function() { return self.s.haInterval; } }); Object.defineProperty(this, 'state', { enumerable:true, get: function() { return self.s.replState; } }); // // Debug options if(self.s.debug) { // Add access to the read Preference Strategies Object.defineProperty(this, 'readPreferenceStrategies', { enumerable: true, get: function() { return self.s.readPreferenceStrategies; } }); } Object.defineProperty(this, 'type', { enumerable:true, get: function() { return 'replset'; } }); // Add the ping strategy for nearest this.addReadPreferenceStrategy('nearest', new Ping(options)); } inherits(ReplSet, EventEmitter); // // Plugin methods // /** * Add custom read preference strategy * @method * @param {string} name Name of the read preference strategy * @param {object} strategy Strategy object instance */ ReplSet.prototype.addReadPreferenceStrategy = function(name, func) { this.s.readPreferenceStrategies[name] = func; } /** * Add custom authentication mechanism * @method * @param {string} name Name of the authentication mechanism * @param {object} provider Authentication object instance */ ReplSet.prototype.addAuthProvider = function(name, provider) { if(this.s.authProviders == null) this.s.authProviders = {}; this.s.authProviders[name] = provider; } /** * Name of BSON parser currently used * @method * @return {string} */ ReplSet.prototype.parserType = function() { if(this.s.bson.serialize.toString().indexOf('[native code]') != -1) return 'c++'; return 'js'; } /** * Execute a command * @method * @param {string} type Type of BSON parser to use (c++ or js) */ ReplSet.prototype.setBSONParserType = function(type) { var nBSON = null; if(type == 'c++') { nBSON = require('bson').native().BSON; } else if(type == 'js') { nBSON = require('bson').pure().BSON; } else { throw new MongoError(f("% parser not supported", type)); } this.s.options.bson = new nBSON(bsonTypes); } /** * Returns the last known ismaster document for this server * @method * @return {object} */ ReplSet.prototype.lastIsMaster = function() { return this.s.replState.lastIsMaster(); } /** * Get connection * @method * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it * @return {Connection} */ ReplSet.prototype.getConnection = function(options) { // Ensure we have no options options = options || {}; // Pick the right server based on readPreference var server = pickServer(this, this.s, options.readPreference); if(server == null) return null; // Return connection return server.getConnection(); } /** * All raw connections * @method * @return {Connection[]} */ ReplSet.prototype.connections = function() { return this.s.replState.getAllConnections(); } /** * Get server * @method * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it * @return {Server} */ ReplSet.prototype.getServer = function(options) { // Ensure we have no options options = options || {}; // Pick the right server based on readPreference return pickServer(this, this.s, options.readPreference); } /** * Perform one or more remove operations * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId * @param {object} [options.batchSize=0] Batchsize for the operation * @param {array} [options.documents=[]] Initial documents list for cursor * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {opResultCallback} callback A callback function */ ReplSet.prototype.cursor = function(ns, cmd, cursorOptions) { cursorOptions = cursorOptions || {}; var FinalCursor = cursorOptions.cursorFactory || this.s.Cursor; return new FinalCursor(this.s.bson, ns, cmd, cursorOptions, this, this.s.options); } // // Execute write operation var executeWriteOperation = function(self, op, ns, ops, options, callback) { if(typeof options == 'function') { callback = options; options = {}; } var server = null; // Ensure we have no options options = options || {}; // Get a primary try { server = pickServer(self, self.s, ReadPreference.primary); if(self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); } catch(err) { return callback(err); } // No server returned we had an error if(server == null) return callback(new MongoError("no server found")); // Handler var handler = function(err, r) { // We have a no master error, immediately refresh the view of the replicaset if(notMasterError(r) || notMasterError(err)) replicasetInquirer(self, self.s, true)(); // Return the result callback(err, r); } // Add operationId if existing if(callback.operationId) handler.operationId = callback.operationId; // Execute the command server[op](ns, ops, options, handler); } /** * Execute a command * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {object} cmd The command hash * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it * @param {Connection} [options.connection] Specify connection object to execute command against * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {opResultCallback} callback A callback function */ ReplSet.prototype.command = function(ns, cmd, options, callback) { if(typeof options == 'function') callback = options, options = {}; if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); var server = null; var self = this; // Ensure we have no options options = options || {}; // Topology is not connected, save the call in the provided store to be // Executed at some point when the handler deems it's reconnected if(!this.isConnected(options) && this.s.disconnectHandler != null) { callback = bindToCurrentDomain(callback); return this.s.disconnectHandler.add('command', ns, cmd, options, callback); } // We need to execute the command on all servers if(options.onAll) { var servers = this.s.replState.getAll(); var count = servers.length; var cmdErr = null; for(var i = 0; i < servers.length; i++) { servers[i].command(ns, cmd, options, function(err, r) { count = count - 1; // Finished executing command if(count == 0) { // Was it a logout command clear any credentials if(cmd.logout) clearCredentials(self.s, ns); // We have a no master error, immediately refresh the view of the replicaset if(notMasterError(r) || notMasterError(err)) replicasetInquirer(self, self.s, true)(); // Return the error callback(err, r); } }); } return; } // Pick the right server based on readPreference try { server = pickServer(self, self.s, options.writeConcern ? ReadPreference.primary : options.readPreference); if(self.s.debug) self.emit('pickedServer', options.writeConcern ? ReadPreference.primary : options.readPreference, server); } catch(err) { return callback(err); } // No server returned we had an error if(server == null) return callback(new MongoError("no server found")); // Execute the command server.command(ns, cmd, options, function(err, r) { // Was it a logout command clear any credentials if(cmd.logout) clearCredentials(self.s, ns); // We have a no master error, immediately refresh the view of the replicaset if(notMasterError(r) || notMasterError(err)) { replicasetInquirer(self, self.s, true)(); } // Return the error callback(err, r); }); } /** * Perform one or more remove operations * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {array} ops An array of removes * @param {boolean} [options.ordered=true] Execute in order or out of order * @param {object} [options.writeConcern={}] Write concern for the operation * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {opResultCallback} callback A callback function */ ReplSet.prototype.remove = function(ns, ops, options, callback) { if(typeof options == 'function') callback = options, options = {}; if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); // Topology is not connected, save the call in the provided store to be // Executed at some point when the handler deems it's reconnected if(!this.isConnected() && this.s.disconnectHandler != null) { callback = bindToCurrentDomain(callback); return this.s.disconnectHandler.add('remove', ns, ops, options, callback); } executeWriteOperation(this, 'remove', ns, ops, options, callback); } /** * Insert one or more documents * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {array} ops An array of documents to insert * @param {boolean} [options.ordered=true] Execute in order or out of order * @param {object} [options.writeConcern={}] Write concern for the operation * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {opResultCallback} callback A callback function */ ReplSet.prototype.insert = function(ns, ops, options, callback) { if(typeof options == 'function') callback = options, options = {}; if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); // Topology is not connected, save the call in the provided store to be // Executed at some point when the handler deems it's reconnected if(!this.isConnected() && this.s.disconnectHandler != null) { callback = bindToCurrentDomain(callback); return this.s.disconnectHandler.add('insert', ns, ops, options, callback); } executeWriteOperation(this, 'insert', ns, ops, options, callback); } /** * Perform one or more update operations * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {array} ops An array of updates * @param {boolean} [options.ordered=true] Execute in order or out of order * @param {object} [options.writeConcern={}] Write concern for the operation * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {opResultCallback} callback A callback function */ ReplSet.prototype.update = function(ns, ops, options, callback) { if(typeof options == 'function') callback = options, options = {}; if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); // Topology is not connected, save the call in the provided store to be // Executed at some point when the handler deems it's reconnected if(!this.isConnected() && this.s.disconnectHandler != null) { callback = bindToCurrentDomain(callback); return this.s.disconnectHandler.add('update', ns, ops, options, callback); } executeWriteOperation(this, 'update', ns, ops, options, callback); } /** * Authenticate using a specified mechanism * @method * @param {string} mechanism The Auth mechanism we are invoking * @param {string} db The db we are invoking the mechanism against * @param {...object} param Parameters for the specific mechanism * @param {authResultCallback} callback A callback function */ ReplSet.prototype.auth = function(mechanism, db) { var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); var self = this; var args = Array.prototype.slice.call(arguments, 2); var callback = args.pop(); // If we don't have the mechanism fail if(this.s.authProviders[mechanism] == null && mechanism != 'default') throw new MongoError(f("auth provider %s does not exist", mechanism)); // Authenticate against all the servers var servers = this.s.replState.getAll().slice(0); var count = servers.length; // Correct authentication var authenticated = true; var authErr = null; // Set auth in progress this.s.authInProgress = true; // Authenticate against all servers while(servers.length > 0) { var server = servers.shift(); // Arguments without a callback var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); // Create arguments var finalArguments = argsWithoutCallback.concat([function(err, r) { count = count - 1; if(err) authErr = err; if(!r) authenticated = false; // We are done if(count == 0) { // We have more servers that are not authenticated, let's authenticate if(self.s.authInProgressServers.length > 0) { self.s.authInProgressServers = []; return self.auth.apply(self, [mechanism, db].concat(args).concat([callback])); } // Auth is done self.s.authInProgress = false; // Add successful credentials if(authErr == null) addCredentials(self.s, db, argsWithoutCallback); // Return the auth error if(authErr) return callback(authErr, false); // Successfully authenticated session callback(null, new Session({}, self)); } }]); // Execute the auth server.auth.apply(server, finalArguments); } } ReplSet.prototype.state = function() { return this.s.replState.state; } /** * Ensure single socket connections to arbiters and hidden servers * @method */ var handleIsmaster = function(self) { return function(ismaster, _server) { if(ismaster.arbiterOnly) { _server.s.options.size = 1; } else if(ismaster.hidden) { _server.s.options.size = 1; } } } /** * Initiate server connect * @method */ ReplSet.prototype.connect = function(_options) { var self = this; // Start replicaset inquiry process setHaTimer(self, self.s); // Additional options if(_options) for(var name in _options) this.s.options[name] = _options[name]; // Set the state as connecting this.s.replState.state = CONNECTING; // No fullsetup reached this.s.fullsetup = false; // For all entries in the seedlist build a server instance this.s.seedlist.forEach(function(e) { // Clone options var opts = cloneOptions(self.s.options); // Add host and port opts.host = e.host; opts.port = e.port; opts.reconnect = false; opts.readPreferenceStrategies = self.s.readPreferenceStrategies; opts.emitError = true; // Add a reserved connection for monitoring opts.size = opts.size + 1; opts.monitoring = true; // Set up tags if any if(self.s.tag) opts.tag = self.s.tag; // Share the auth store opts.authProviders = self.s.authProviders; // Create a new Server var server = new Server(opts); // Handle the ismaster server.on('ismaster', handleIsmaster(self)); // Add to list of disconnected servers self.s.disconnectedServers.push(server); // Add to list of inflight Connections self.s.initialConnectionServers.push(server); }); // Attempt to connect to all the servers while(this.s.disconnectedServers.length > 0) { // Get the server var server = self.s.disconnectedServers.shift(); // Set up the event handlers server.once('error', errorHandlerTemp(self, self.s, 'error')); server.once('close', errorHandlerTemp(self, self.s, 'close')); server.once('timeout', errorHandlerTemp(self, self.s, 'timeout')); server.once('connect', connectHandler(self, self.s)); // Ensure we schedule the opening of new socket // on separate ticks of the event loop var execute = function(_server) { // Attempt to connect process.nextTick(function() { _server.connect(); }); } execute(server); } } /** * Figure out if the server is connected * @method * @return {boolean} */ ReplSet.prototype.isConnected = function(options) { options = options || {}; // If we specified a read preference check if we are connected to something // than can satisfy this if(options.readPreference && options.readPreference.equals(ReadPreference.secondary)) return this.s.replState.isSecondaryConnected(); if(options.readPreference && options.readPreference.equals(ReadPreference.primary)) return this.s.replState.isSecondaryConnected() || this.s.replState.isPrimaryConnected(); if(this.s.secondaryOnlyConnectionAllowed && this.s.replState.isSecondaryConnected()) return true; return this.s.replState.isPrimaryConnected(); } /** * Figure out if the replicaset instance was destroyed by calling destroy * @method * @return {boolean} */ ReplSet.prototype.isDestroyed = function() { return this.s.replState.state == DESTROYED; } /** * Destroy the server connection * @method */ ReplSet.prototype.destroy = function(emitClose) { var self = this; if(this.s.logger.isInfo()) this.s.logger.info(f('[%s] destroyed', this.s.id)); this.s.replState.state = DESTROYED; // Emit close if(emitClose && self.listeners('close').length > 0) self.emit('close', self); // Destroy state this.s.replState.destroy(); // Clear out any listeners var events = ['timeout', 'error', 'close', 'joined', 'left']; events.forEach(function(e) { self.removeAllListeners(e); }); clearTimeout(self.s.haTimer); } /** * A replset connect event, used to verify that the connection is up and running * * @event ReplSet#connect * @type {ReplSet} */ /** * The replset high availability event * * @event ReplSet#ha * @type {function} * @param {string} type The stage in the high availability event (start|end) * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only * @param {number} data.id The id for this high availability request * @param {object} data.state An object containing the information about the current replicaset */ /** * A server member left the replicaset * * @event ReplSet#left * @type {function} * @param {string} type The type of member that left (primary|secondary|arbiter) * @param {Server} server The server object that left */ /** * A server member joined the replicaset * * @event ReplSet#joined * @type {function} * @param {string} type The type of member that joined (primary|secondary|arbiter) * @param {Server} server The server object that joined */ // // Inquires about state changes // // Add the new credential for a db, removing the old // credential from the cache var addCredentials = function(s, db, argsWithoutCallback) { // Remove any credentials for the db clearCredentials(s, db + ".dummy"); // Add new credentials to list s.credentials.push(argsWithoutCallback); } // Clear out credentials for a namespace var clearCredentials = function(s, ns) { var db = ns.split('.')[0]; var filteredCredentials = []; // Filter out all credentials for the db the user is logging out off for(var i = 0; i < s.credentials.length; i++) { if(s.credentials[i][1] != db) filteredCredentials.push(s.credentials[i]); } // Set new list of credentials s.credentials = filteredCredentials; } // // Filter serves by tags var filterByTags = function(readPreference, servers) { if(readPreference.tags == null) return servers; var filteredServers = []; var tagsArray = !Array.isArray(readPreference.tags) ? [tags] : tags; // Iterate over the tags for(var j = 0; j < tagsArray.length; j++) { var tags = tagsArray[j]; // Iterate over all the servers for(var i = 0; i < servers.length; i++) { var serverTag = servers[i].lastIsMaster().tags || {}; // Did we find the a matching server var found = true; // Check if the server is valid for(var name in tags) { if(serverTag[name] != tags[name]) found = false; } // Add to candidate list if(found) { filteredServers.push(servers[i]); } } // We found servers by the highest priority if(found) break; } // Returned filtered servers return filteredServers; } // // Pick a server based on readPreference var pickServer = function(self, s, readPreference) { // If no read Preference set to primary by default readPreference = readPreference || ReadPreference.primary; // Do we have a custom readPreference strategy, use it if(s.readPreferenceStrategies != null && s.readPreferenceStrategies[readPreference.preference] != null) { if(s.readPreferenceStrategies[readPreference.preference] == null) throw new MongoError(f("cannot locate read preference handler for %s", readPreference.preference)); var server = s.readPreferenceStrategies[readPreference.preference].pickServer(s.replState, readPreference); if(s.debug) self.emit('pickedServer', readPreference, server); return server; } // Filter out any hidden secondaries var secondaries = s.replState.secondaries.filter(function(server) { if(server.lastIsMaster().hidden) return false; return true; }); // Check if we can satisfy and of the basic read Preferences if(readPreference.equals(ReadPreference.secondary) && secondaries.length == 0) throw new MongoError("no secondary server available"); if(readPreference.equals(ReadPreference.secondaryPreferred) && secondaries.length == 0 && s.replState.primary == null) throw new MongoError("no secondary or primary server available"); if(readPreference.equals(ReadPreference.primary) && s.replState.primary == null) throw new MongoError("no primary server available"); // Secondary if(readPreference.equals(ReadPreference.secondary)) { s.index = (s.index + 1) % secondaries.length; return secondaries[s.index]; } // Secondary preferred if(readPreference.equals(ReadPreference.secondaryPreferred)) { if(secondaries.length > 0) { // Apply tags if present var servers = filterByTags(readPreference, secondaries); // If have a matching server pick one otherwise fall through to primary if(servers.length > 0) { s.index = (s.index + 1) % servers.length; return servers[s.index]; } } return s.replState.primary; } // Primary preferred if(readPreference.equals(ReadPreference.primaryPreferred)) { if(s.replState.primary) return s.replState.primary; if(secondaries.length > 0) { // Apply tags if present var servers = filterByTags(readPreference, secondaries); // If have a matching server pick one otherwise fall through to primary if(servers.length > 0) { s.index = (s.index + 1) % servers.length; return servers[s.index]; } // Throw error a we have not valid secondary or primary servers throw new MongoError("no secondary or primary server available"); } } // Return the primary return s.replState.primary; } var setHaTimer = function(self, state) { // all haTimers are set to to repeat, so we pass norepeat false self.s.haTimer = setTimeout(replicasetInquirer(self, state, false), state.haInterval); return self.s.haTimer; } var haveAvailableServers = function(state) { if(state.disconnectedServers.length == 0 && state.replState.secondaries.length == 0 && state.replState.arbiters.length == 0 && state.replState.primary == null) return false; return true; } var replicasetInquirer = function(self, state, norepeat) { return function() { if(state.replState.state == DESTROYED) return // We have no connections we need to reseed the disconnected list if(!haveAvailableServers(state)) { // For all entries in the seedlist build a server instance state.disconnectedServers = state.seedlist.map(function(e) { // Clone options var opts = cloneOptions(state.options); // Add host and port opts.host = e.host; opts.port = e.port; opts.reconnect = false; opts.readPreferenceStrategies = state.readPreferenceStrategies; opts.emitError = true; // Add a reserved connection for monitoring opts.size = opts.size + 1; opts.monitoring = true; // Set up tags if any if(state.tag) opts.tag = stage.tag; // Share the auth store opts.authProviders = state.authProviders; // Create a new Server var server = new Server(opts); // Handle the ismaster server.on('ismaster', handleIsmaster(self)); return server; }); } // Process already running don't rerun if(state.highAvailabilityProcessRunning) return; // Started processes state.highAvailabilityProcessRunning = true; if(state.logger.isInfo()) state.logger.info(f('[%s] monitoring process running %s', state.id, JSON.stringify(state.replState))); // Unique HA id to identify the current look running var localHaId = state.haId++; // Clean out any failed connection attempts state.connectingServers = {}; // Controls if we are doing a single inquiry or repeating norepeat = typeof norepeat == 'boolean' ? norepeat : false; // If we have a primary and a disconnect handler, execute // buffered operations if(state.replState.isPrimaryConnected() && state.replState.isSecondaryConnected() && state.disconnectHandler) { state.disconnectHandler.execute(); } // Emit replicasetInquirer self.emit('ha', 'start', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); // Let's process all the disconnected servers while(state.disconnectedServers.length > 0) { // Get the first disconnected server var server = state.disconnectedServers.shift(); if(state.logger.isInfo()) state.logger.info(f('[%s] monitoring attempting to connect to %s', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); // Set up the event handlers server.once('error', errorHandlerTemp(self, state, 'error')); server.once('close', errorHandlerTemp(self, state, 'close')); server.once('timeout', errorHandlerTemp(self, state, 'timeout')); server.once('connect', connectHandler(self, state)); // Ensure we schedule the opening of new socket // on separate ticks of the event loop var execute = function(_server) { // Attempt to connect process.nextTick(function() { _server.connect(); }); } execute(server); } // Cleanup state (removed disconnected servers) state.replState.clean(); // We need to query all servers var servers = state.replState.getAll({includeArbiters:true}); var serversLeft = servers.length; // If no servers and we are not destroyed keep pinging if(servers.length == 0 && state.replState.state == CONNECTED) { // Emit ha process end self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); // Ended highAvailabilityProcessRunning state.highAvailabilityProcessRunning = false; // Restart ha process if(!norepeat) setHaTimer(self, state); return; } // // ismaster for Master server var primaryIsMaster = null; // Kill the server connection if it hangs var timeoutServer = function(_server) { return setTimeout(function() { if(_server.isConnected()) { _server.connections()[0].connection.destroy(); } }, self.s.options.connectionTimeout); } // // Inspect a specific servers ismaster var inspectServer = function(server) { if(state.replState.state == DESTROYED) return; // Did we get a server if(server && server.isConnected()) { // Get the timeout id var timeoutId = timeoutServer(server); // Execute ismaster server.command('admin.$cmd', { ismaster:true }, { monitoring:true }, function(err, r) { // Clear out the timeoutServer clearTimeout(timeoutId); // If the state was destroyed if(state.replState.state == DESTROYED) return; // Count down the number of servers left serversLeft = serversLeft - 1; // If we have an error but still outstanding server request return if(err && serversLeft > 0) return; // We had an error and have no more servers to inspect, schedule a new check if(err && serversLeft == 0) { self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); // Ended highAvailabilityProcessRunnfing state.highAvailabilityProcessRunning = false; // Return the replicasetInquirer if(!norepeat) setHaTimer(self, state); return; } // Let all the read Preferences do things to the servers var rPreferencesCount = Object.keys(state.readPreferenceStrategies).length; // Handle the primary var ismaster = r.result; if(state.logger.isDebug()) state.logger.debug(f('[%s] monitoring process ismaster %s', state.id, JSON.stringify(ismaster))); // Update the replicaset state state.replState.update(ismaster, server); // // Process hosts list from ismaster under two conditions // 1. Ismaster result is from primary // 2. There is no primary and the ismaster result is from a non-primary if(err == null && (ismaster.ismaster || (!state.primary)) && Array.isArray(ismaster.hosts)) { // Hosts to process var hosts = ismaster.hosts; // Add arbiters to list of hosts if we have any if(Array.isArray(ismaster.arbiters)) { hosts = hosts.concat(ismaster.arbiters.map(function(x) { return {host: x, arbiter:true}; })); } if(Array.isArray(ismaster.passives)) hosts = hosts.concat(ismaster.passives); // Process all the hsots processHosts(self, state, hosts); } else if(err == null && !Array.isArray(ismaster.hosts)) { server.destroy(); } // No read Preferences strategies if(rPreferencesCount == 0) { // Don't schedule a new inquiry if(serversLeft > 0) return; // Emit ha process end self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); // Ended highAvailabilityProcessRunning state.highAvailabilityProcessRunning = false; // Let's keep monitoring if(!norepeat) setHaTimer(self, state); return; } // No servers left to query, execute read preference strategies if(serversLeft == 0) { // Go over all the read preferences for(var name in state.readPreferenceStrategies) { state.readPreferenceStrategies[name].ha(self, state.replState, function() { rPreferencesCount = rPreferencesCount - 1; if(rPreferencesCount == 0) { // Add any new servers in primary ismaster if(err == null && ismaster.ismaster && Array.isArray(ismaster.hosts)) { processHosts(self, state, ismaster.hosts); } // Emit ha process end self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); // Ended highAvailabilityProcessRunning state.highAvailabilityProcessRunning = false; // Let's keep monitoring if(!norepeat) setHaTimer(self, state); return; } }); } } }); } } // Call ismaster on all servers for(var i = 0; i < servers.length; i++) { inspectServer(servers[i]); } // If no more initial servers and new scheduled servers to connect if(state.replState.secondaries.length >= 1 && state.replState.primary != null && !state.fullsetup) { state.fullsetup = true; self.emit('fullsetup', self); } // If all servers are accounted for and we have not sent the all event if(state.replState.primary != null && self.lastIsMaster() && Array.isArray(self.lastIsMaster().hosts) && !state.all) { var length = 1 + state.replState.secondaries.length; // If we have all secondaries + primary if(length == self.lastIsMaster().hosts.length + 1) { state.all = true; self.emit('all', self); } } } } // Error handler for initial connect var errorHandlerTemp = function(self, state, event) { return function(err, server) { // Log the information if(state.logger.isInfo()) state.logger.info(f('[%s] server %s disconnected', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); // Filter out any connection servers state.initialConnectionServers = state.initialConnectionServers.filter(function(_server) { return server.name != _server.name; }); // Connection is destroyed, ignore if(state.replState.state == DESTROYED) return; // Remove any non used handlers ['error', 'close', 'timeout', 'connect'].forEach(function(e) { server.removeAllListeners(e); }) // Push to list of disconnected servers addToListIfNotExist(state.disconnectedServers, server); // End connection operation if we have no legal replicaset state if(state.initialConnectionServers == 0 && state.replState.state == CONNECTING) { if((state.secondaryOnlyConnectionAllowed && !state.replState.isSecondaryConnected() && !state.replState.isPrimaryConnected()) || (!state.secondaryOnlyConnectionAllowed && !state.replState.isPrimaryConnected())) { if(state.logger.isInfo()) state.logger.info(f('[%s] no valid seed servers in list', state.id)); if(self.listeners('error').length > 0) return self.emit('error', new MongoError('no valid seed servers in list')); } } // If the number of disconnected servers is equal to // the number of seed servers we cannot connect if(state.disconnectedServers.length == state.seedlist.length && state.replState.state == CONNECTING) { if(state.emitError && self.listeners('error').length > 0) { if(state.logger.isInfo()) state.logger.info(f('[%s] no valid seed servers in list', state.id)); if(self.listeners('error').length > 0) self.emit('error', new MongoError('no valid seed servers in list')); } } } } // TODO with arbiter // - if connected to an arbiter, shut down all but single server connection // Connect handler var connectHandler = function(self, state) { return function(server) { if(state.logger.isInfo()) state.logger.info(f('[%s] connected to %s', state.id, server.name)); // Destroyed connection if(state.replState.state == DESTROYED) { server.destroy(false, false); return; } // Filter out any connection servers state.initialConnectionServers = state.initialConnectionServers.filter(function(_server) { return server.name != _server.name; }); // Process the new server var processNewServer = function() { // Discover any additional servers var ismaster = server.lastIsMaster(); // Are we an arbiter, restrict number of connections to // one single connection if(ismaster.arbiterOnly) { server.capConnections(1); } // Deal with events var events = ['error', 'close', 'timeout', 'connect', 'message']; // Remove any non used handlers events.forEach(function(e) { server.removeAllListeners(e); }) // Clean up delete state.connectingServers[server.name]; // Update the replicaset state, destroy if not added if(!state.replState.update(ismaster, server)) { // Destroy the server instance server.destroy(); // No more candiate servers if(state.state == CONNECTING && state.initialConnectionServers.length == 0 && state.replState.primary == null && state.replState.secondaries.length == 0) { return self.emit('error', new MongoError("no replicaset members found in seedlist")); } return; } // Add the server handling code if(server.isConnected()) { server.on('error', errorHandler(self, state)); server.on('close', closeHandler(self, state)); server.on('timeout', timeoutHandler(self, state)); } // Hosts to process var hosts = ismaster.hosts; // Add arbiters to list of hosts if we have any if(Array.isArray(ismaster.arbiters)) { hosts = hosts.concat(ismaster.arbiters.map(function(x) { return {host: x, arbiter:true}; })); } if(Array.isArray(ismaster.passives)) hosts = hosts.concat(ismaster.passives); // Add any new servers processHosts(self, state, hosts); // If have the server instance already destroy it if(state.initialConnectionServers.length == 0 && Object.keys(state.connectingServers).length == 0 && !state.replState.isPrimaryConnected() && !state.secondaryOnlyConnectionAllowed && state.replState.state == CONNECTING) { if(state.logger.isInfo()) state.logger.info(f('[%s] no primary found in replicaset', state.id)); self.emit('error', new MongoError("no primary found in replicaset")); return self.destroy(); } // If no more initial servers and new scheduled servers to connect if(state.replState.secondaries.length >= 1 && state.replState.primary != null && !state.fullsetup) { state.fullsetup = true; self.emit('fullsetup', self); } } // Save up new members to be authenticated against if(self.s.authInProgress) { self.s.authInProgressServers.push(server); } // No credentials just process server if(state.credentials.length == 0) return processNewServer(); // Do we have credentials, let's apply them all var count = state.credentials.length; // Apply the credentials for(var i = 0; i < state.credentials.length; i++) { server.auth.apply(server, state.credentials[i].concat([function(err, r) { count = count - 1; if(count == 0) processNewServer(); }])); } } } // // Detect if we need to add new servers var processHosts = function(self, state, hosts) { if(state.replState.state == DESTROYED) return; if(Array.isArray(hosts)) { // Check any hosts exposed by ismaster for(var i = 0; i < hosts.length; i++) { // Get the object var host = hosts[i]; var options = {}; // Do we have an arbiter if(typeof host == 'object') { host = host.host; options.arbiter = host.arbiter; } // If not found we need to create a new connection if(!state.replState.contains(host)) { if(state.connectingServers[host] == null && !inInitialConnectingServers(self, state, host)) { if(state.logger.isInfo()) state.logger.info(f('[%s] scheduled server %s for connection', state.id, host)); // Make sure we know what is trying to connect state.connectingServers[host] = host; // Connect the server connectToServer(self, state, host.split(':')[0], parseInt(host.split(':')[1], 10), options); } } } } } var inInitialConnectingServers = function(self, state, address) { for(var i = 0; i < state.initialConnectionServers.length; i++) { if(state.initialConnectionServers[i].name == address) return true; } return false; } // Connect to a new server var connectToServer = function(self, state, host, port, options) { options = options || {}; var opts = cloneOptions(state.options); opts.host = host; opts.port = port; opts.reconnect = false; opts.readPreferenceStrategies = state.readPreferenceStrategies; if(state.tag) opts.tag = state.tag; // Share the auth store opts.authProviders = state.authProviders; opts.emitError = true; // Set the size to size + 1 and mark monitoring opts.size = opts.size + 1; opts.monitoring = true; // Do we have an arbiter set the poolSize to 1 if(options.arbiter) { opts.size = 1; } // Create a new server instance var server = new Server(opts); // Handle the ismaster server.on('ismaster', handleIsmaster(self)); // Set up the event handlers server.once('error', errorHandlerTemp(self, state, 'error')); server.once('close', errorHandlerTemp(self, state, 'close')); server.once('timeout', errorHandlerTemp(self, state, 'timeout')); server.once('connect', connectHandler(self, state)); // Attempt to connect process.nextTick(function() { server.connect(); }); } // // Add server to the list if it does not exist var addToListIfNotExist = function(list, server) { var found = false; // If the server is a null value return false if(server == null) return found; // Remove any non used handlers ['error', 'close', 'timeout', 'connect'].forEach(function(e) { server.removeAllListeners(e); }) // Check if the server already exists for(var i = 0; i < list.length; i++) { if(list[i].equals(server)) found = true; } if(!found) { list.push(server); } return found; } var errorHandler = function(self, state) { return function(err, server) { if(state.replState.state == DESTROYED) return; if(state.logger.isInfo()) state.logger.info(f('[%s] server %s errored out with %s', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name, JSON.stringify(err))); var found = addToListIfNotExist(state.disconnectedServers, server); if(!found) self.emit('left', state.replState.remove(server), server); if(found && state.emitError && self.listeners('error').length > 0) self.emit('error', err, server); // Fire off a detection of missing server using minHeartbeatFrequencyMS setTimeout(function() { replicasetInquirer(self, self.s, true)(); }, self.s.minHeartbeatFrequencyMS); } } var timeoutHandler = function(self, state) { return function(err, server) { if(state.replState.state == DESTROYED) return; if(state.logger.isInfo()) state.logger.info(f('[%s] server %s timed out', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); var found = addToListIfNotExist(state.disconnectedServers, server); if(!found) self.emit('left', state.replState.remove(server), server); // Fire off a detection of missing server using minHeartbeatFrequencyMS setTimeout(function() { replicasetInquirer(self, self.s, true)(); }, self.s.minHeartbeatFrequencyMS); } } var closeHandler = function(self, state) { return function(err, server) { if(state.replState.state == DESTROYED) return; if(state.logger.isInfo()) state.logger.info(f('[%s] server %s closed', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); var found = addToListIfNotExist(state.disconnectedServers, server); if(!found) { self.emit('left', state.replState.remove(server), server); } // Fire off a detection of missing server using minHeartbeatFrequencyMS setTimeout(function() { replicasetInquirer(self, self.s, true)(); }, self.s.minHeartbeatFrequencyMS); } } // // Validate if a non-master or recovering error var notMasterError = function(r) { // Get result of any var result = r && r.result ? r.result : r; // Explore if we have a not master error if(result && (result.err == 'not master' || result.errmsg == 'not master' || (result['$err'] && result['$err'].indexOf('not master or secondary') != -1) || (result['$err'] && result['$err'].indexOf("not master and slaveOk=false") != -1) || result.errmsg == 'node is recovering')) { return true; } return false; } module.exports = ReplSet;
/** * An implementation of `_.uniq` optimized for sorted arrays without support * for callback shorthands and `this` binding. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The function invoked per iteration. * @returns {Array} Returns the new duplicate-value-free array. */ function sortedUniq(array, iteratee) { var seen, index = -1, length = array.length, resIndex = -1, result = []; while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value, index, array) : value; if (!index || seen !== computed) { seen = computed; result[++resIndex] = value; } } return result; } module.exports = sortedUniq;
var chalk = require('chalk'); module.exports = chalk.cyan( " _ _" + "\n (_) (_)" + "\n _ ___ _ __ _ ___" + "\n | |/ _ \\| '_ \\| |/ __|" + "\n | | (_) | | | | | (__" + "\n |_|\\___/|_| |_|_|\\___|\n");
function fileMap(revision,tag,date) { return { "ember.js": fileObject("ember", ".js", "text/javascript", revision, tag, date), "ember.debug.js": fileObject("ember.debug", ".js", "text/javascript", revision, tag, date), "ember-testing.js": fileObject("ember-testing", ".js", "text/javascript", revision, tag, date), "ember-tests.js": fileObject("ember-tests", ".js", "text/javascript", revision, tag, date), "ember-runtime.js": fileObject("ember-runtime", ".js", "text/javascript", revision, tag, date), "ember-template-compiler.js": fileObject("ember-template-compiler", ".js", "text/javascript", revision, tag, date), "ember.min.js": fileObject("ember.min", ".js", "text/javascript", revision, tag, date), "ember.prod.js": fileObject("ember.prod", ".js", "text/javascript", revision, tag, date), "../docs/data.json": fileObject("ember-docs", ".json", "application/json", revision, tag, date), "ember-tests/index.html": fileObject("ember-tests-index", ".html", "text/html", revision, tag, date) }; }; function fileObject(baseName, extension, contentType, currentRevision, tag, date){ var fullName = "/" + baseName + extension; var obj = { contentType: contentType, destinations: { glimmer: [ "glimmer" + fullName, "canary/shas/" + currentRevision + fullName ], canary: [ "latest" + fullName, "canary" + fullName, "canary/daily/" + date + fullName, "canary/shas/" + currentRevision + fullName ], release: [ "stable" + fullName, "release" + fullName, "release/daily/" + date + fullName, "release/shas/" + currentRevision + fullName ], beta: [ "beta" + fullName, "beta/daily/" + date + fullName, "beta/shas/" + currentRevision + fullName ], wildcard: [] } }; if (tag) { for (var key in obj.destinations) { obj.destinations[key].push("tags/" + tag + fullName); } } return obj; } module.exports = fileMap;
/** * @fileoverview Main CLI object. * @author Nicholas C. Zakas */ "use strict"; /* * The CLI object should *not* call process.exit() directly. It should only return * exit codes. This allows other programs to use the CLI object and still control * when the program exits. */ //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const fs = require("fs"), path = require("path"), rules = require("./rules"), eslint = require("./eslint"), defaultOptions = require("../conf/cli-options"), IgnoredPaths = require("./ignored-paths"), Config = require("./config"), Plugins = require("./config/plugins"), fileEntryCache = require("file-entry-cache"), globUtil = require("./util/glob-util"), SourceCodeFixer = require("./util/source-code-fixer"), validator = require("./config/config-validator"), stringify = require("json-stable-stringify"), hash = require("./util/hash"), pkg = require("../package.json"); const debug = require("debug")("eslint:cli-engine"); //------------------------------------------------------------------------------ // Typedefs //------------------------------------------------------------------------------ /** * The options to configure a CLI engine with. * @typedef {Object} CLIEngineOptions * @property {boolean} allowInlineConfig Enable or disable inline configuration comments. * @property {boolean|Object} baseConfig Base config object. True enables recommend rules and environments. * @property {boolean} cache Enable result caching. * @property {string} cacheLocation The cache file to use instead of .eslintcache. * @property {string} configFile The configuration file to use. * @property {string} cwd The value to use for the current working directory. * @property {string[]} envs An array of environments to load. * @property {string[]} extensions An array of file extensions to check. * @property {boolean} fix Execute in autofix mode. * @property {string[]} globals An array of global variables to declare. * @property {boolean} ignore False disables use of .eslintignore. * @property {string} ignorePath The ignore file to use instead of .eslintignore. * @property {string} ignorePattern A glob pattern of files to ignore. * @property {boolean} useEslintrc False disables looking for .eslintrc * @property {string} parser The name of the parser to use. * @property {Object} parserOptions An object of parserOption settings to use. * @property {string[]} plugins An array of plugins to load. * @property {Object<string,*>} rules An object of rules to use. * @property {string[]} rulePaths An array of directories to load custom rules from. */ /** * A linting warning or error. * @typedef {Object} LintMessage * @property {string} message The message to display to the user. */ /** * A linting result. * @typedef {Object} LintResult * @property {string} filePath The path to the file that was linted. * @property {LintMessage[]} messages All of the messages for the result. * @property {number} errorCount Number or errors for the result. * @property {number} warningCount Number or warnings for the result. */ //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ /** * It will calculate the error and warning count for collection of messages per file * @param {Object[]} messages - Collection of messages * @returns {Object} Contains the stats * @private */ function calculateStatsPerFile(messages) { return messages.reduce(function(stat, message) { if (message.fatal || message.severity === 2) { stat.errorCount++; } else { stat.warningCount++; } return stat; }, { errorCount: 0, warningCount: 0 }); } /** * It will calculate the error and warning count for collection of results from all files * @param {Object[]} results - Collection of messages from all the files * @returns {Object} Contains the stats * @private */ function calculateStatsPerRun(results) { return results.reduce(function(stat, result) { stat.errorCount += result.errorCount; stat.warningCount += result.warningCount; return stat; }, { errorCount: 0, warningCount: 0 }); } /** * Performs multiple autofix passes over the text until as many fixes as possible * have been applied. * @param {string} text The source text to apply fixes to. * @param {Object} config The ESLint config object to use. * @param {Object} options The ESLint options object to use. * @param {string} options.filename The filename from which the text was read. * @param {boolean} options.allowInlineConfig Flag indicating if inline comments * should be allowed. * @returns {Object} The result of the fix operation as returned from the * SourceCodeFixer. * @private */ function multipassFix(text, config, options) { const MAX_PASSES = 10; let messages = [], fixedResult, fixed = false, passNumber = 0; /** * This loop continues until one of the following is true: * * 1. No more fixes have been applied. * 2. Ten passes have been made. * * That means anytime a fix is successfully applied, there will be another pass. * Essentially, guaranteeing a minimum of two passes. */ do { passNumber++; debug("Linting code for " + options.filename + " (pass " + passNumber + ")"); messages = eslint.verify(text, config, options); debug("Generating fixed text for " + options.filename + " (pass " + passNumber + ")"); fixedResult = SourceCodeFixer.applyFixes(eslint.getSourceCode(), messages); // stop if there are any syntax errors. // 'fixedResult.output' is a empty string. if (messages.length === 1 && messages[0].fatal) { break; } // keep track if any fixes were ever applied - important for return value fixed = fixed || fixedResult.fixed; // update to use the fixed output instead of the original text text = fixedResult.output; } while ( fixedResult.fixed && passNumber < MAX_PASSES ); /* * If the last result had fixes, we need to lint again to me sure we have * the most up-to-date information. */ if (fixedResult.fixed) { fixedResult.messages = eslint.verify(text, config, options); } // ensure the last result properly reflects if fixes were done fixedResult.fixed = fixed; fixedResult.output = text; return fixedResult; } /** * Processes an source code using ESLint. * @param {string} text The source code to check. * @param {Object} configHelper The configuration options for ESLint. * @param {string} filename An optional string representing the texts filename. * @param {boolean} fix Indicates if fixes should be processed. * @param {boolean} allowInlineConfig Allow/ignore comments that change config. * @returns {Result} The results for linting on this text. * @private */ function processText(text, configHelper, filename, fix, allowInlineConfig) { // clear all existing settings for a new file eslint.reset(); let filePath, messages, fileExtension, processor, fixedResult; if (filename) { filePath = path.resolve(filename); fileExtension = path.extname(filename); } filename = filename || "<text>"; debug("Linting " + filename); const config = configHelper.getConfig(filePath); if (config.plugins) { Plugins.loadAll(config.plugins); } const loadedPlugins = Plugins.getAll(); for (const plugin in loadedPlugins) { if (loadedPlugins[plugin].processors && Object.keys(loadedPlugins[plugin].processors).indexOf(fileExtension) >= 0) { processor = loadedPlugins[plugin].processors[fileExtension]; break; } } if (processor) { debug("Using processor"); const parsedBlocks = processor.preprocess(text, filename); const unprocessedMessages = []; parsedBlocks.forEach(function(block) { unprocessedMessages.push(eslint.verify(block, config, { filename, allowInlineConfig })); }); // TODO(nzakas): Figure out how fixes might work for processors messages = processor.postprocess(unprocessedMessages, filename); } else { if (fix) { fixedResult = multipassFix(text, config, { filename, allowInlineConfig }); messages = fixedResult.messages; } else { messages = eslint.verify(text, config, { filename, allowInlineConfig }); } } const stats = calculateStatsPerFile(messages); const result = { filePath: filename, messages, errorCount: stats.errorCount, warningCount: stats.warningCount }; if (fixedResult && fixedResult.fixed) { result.output = fixedResult.output; } return result; } /** * Processes an individual file using ESLint. Files used here are known to * exist, so no need to check that here. * @param {string} filename The filename of the file being checked. * @param {Object} configHelper The configuration options for ESLint. * @param {Object} options The CLIEngine options object. * @returns {Result} The results for linting on this file. * @private */ function processFile(filename, configHelper, options) { const text = fs.readFileSync(path.resolve(filename), "utf8"), result = processText(text, configHelper, filename, options.fix, options.allowInlineConfig); return result; } /** * Returns result with warning by ignore settings * @param {string} filePath - File path of checked code * @param {string} baseDir - Absolute path of base directory * @returns {Result} Result with single warning * @private */ function createIgnoreResult(filePath, baseDir) { let message; const isHidden = /^\./.test(path.basename(filePath)); const isInNodeModules = baseDir && /^node_modules/.test(path.relative(baseDir, filePath)); const isInBowerComponents = baseDir && /^bower_components/.test(path.relative(baseDir, filePath)); if (isHidden) { message = "File ignored by default. Use a negated ignore pattern (like \"--ignore-pattern \'!<relative/path/to/filename>\'\") to override."; } else if (isInNodeModules) { message = "File ignored by default. Use \"--ignore-pattern \'!node_modules/*\'\" to override."; } else if (isInBowerComponents) { message = "File ignored by default. Use \"--ignore-pattern \'!bower_components/*\'\" to override."; } else { message = "File ignored because of a matching ignore pattern. Use \"--no-ignore\" to override."; } return { filePath: path.resolve(filePath), messages: [ { fatal: false, severity: 1, message } ], errorCount: 0, warningCount: 1 }; } /** * Checks if the given message is an error message. * @param {Object} message The message to check. * @returns {boolean} Whether or not the message is an error message. * @private */ function isErrorMessage(message) { return message.severity === 2; } /** * return the cacheFile to be used by eslint, based on whether the provided parameter is * a directory or looks like a directory (ends in `path.sep`), in which case the file * name will be the `cacheFile/.cache_hashOfCWD` * * if cacheFile points to a file or looks like a file then in will just use that file * * @param {string} cacheFile The name of file to be used to store the cache * @param {string} cwd Current working directory * @returns {string} the resolved path to the cache file */ function getCacheFile(cacheFile, cwd) { /* * make sure the path separators are normalized for the environment/os * keeping the trailing path separator if present */ cacheFile = path.normalize(cacheFile); const resolvedCacheFile = path.resolve(cwd, cacheFile); const looksLikeADirectory = cacheFile[cacheFile.length - 1 ] === path.sep; /** * return the name for the cache file in case the provided parameter is a directory * @returns {string} the resolved path to the cacheFile */ function getCacheFileForDirectory() { return path.join(resolvedCacheFile, ".cache_" + hash(cwd)); } let fileStats; try { fileStats = fs.lstatSync(resolvedCacheFile); } catch (ex) { fileStats = null; } /* * in case the file exists we need to verify if the provided path * is a directory or a file. If it is a directory we want to create a file * inside that directory */ if (fileStats) { /* * is a directory or is a file, but the original file the user provided * looks like a directory but `path.resolve` removed the `last path.sep` * so we need to still treat this like a directory */ if (fileStats.isDirectory() || looksLikeADirectory) { return getCacheFileForDirectory(); } // is file so just use that file return resolvedCacheFile; } /* * here we known the file or directory doesn't exist, * so we will try to infer if its a directory if it looks like a directory * for the current operating system. */ // if the last character passed is a path separator we assume is a directory if (looksLikeADirectory) { return getCacheFileForDirectory(); } return resolvedCacheFile; } //------------------------------------------------------------------------------ // Public Interface //------------------------------------------------------------------------------ /** * Creates a new instance of the core CLI engine. * @param {CLIEngineOptions} options The options for this instance. * @constructor */ function CLIEngine(options) { options = Object.assign( Object.create(null), defaultOptions, {cwd: process.cwd()}, options ); /** * Stored options for this instance * @type {Object} */ this.options = options; const cacheFile = getCacheFile(this.options.cacheLocation || this.options.cacheFile, this.options.cwd); /** * Cache used to avoid operating on files that haven't changed since the * last successful execution (e.g., file passed linting with no errors and * no warnings). * @type {Object} */ this._fileCache = fileEntryCache.create(cacheFile); // load in additional rules if (this.options.rulePaths) { const cwd = this.options.cwd; this.options.rulePaths.forEach(function(rulesdir) { debug("Loading rules from " + rulesdir); rules.load(rulesdir, cwd); }); } Object.keys(this.options.rules || {}).forEach(function(name) { validator.validateRuleOptions(name, this.options.rules[name], "CLI"); }.bind(this)); } /** * Returns the formatter representing the given format or null if no formatter * with the given name can be found. * @param {string} [format] The name of the format to load or the path to a * custom formatter. * @returns {Function} The formatter function or null if not found. */ CLIEngine.getFormatter = function(format) { let formatterPath; // default is stylish format = format || "stylish"; // only strings are valid formatters if (typeof format === "string") { // replace \ with / for Windows compatibility format = format.replace(/\\/g, "/"); // if there's a slash, then it's a file if (format.indexOf("/") > -1) { const cwd = this.options ? this.options.cwd : process.cwd(); formatterPath = path.resolve(cwd, format); } else { formatterPath = "./formatters/" + format; } try { return require(formatterPath); } catch (ex) { ex.message = "There was a problem loading formatter: " + formatterPath + "\nError: " + ex.message; throw ex; } } else { return null; } }; /** * Returns results that only contains errors. * @param {LintResult[]} results The results to filter. * @returns {LintResult[]} The filtered results. */ CLIEngine.getErrorResults = function(results) { const filtered = []; results.forEach(function(result) { const filteredMessages = result.messages.filter(isErrorMessage); if (filteredMessages.length > 0) { filtered.push({ filePath: result.filePath, messages: filteredMessages, errorCount: filteredMessages.length, warningCount: 0 }); } }); return filtered; }; /** * Outputs fixes from the given results to files. * @param {Object} report The report object created by CLIEngine. * @returns {void} */ CLIEngine.outputFixes = function(report) { report.results.filter(function(result) { return result.hasOwnProperty("output"); }).forEach(function(result) { fs.writeFileSync(result.filePath, result.output); }); }; CLIEngine.prototype = { constructor: CLIEngine, /** * Add a plugin by passing it's configuration * @param {string} name Name of the plugin. * @param {Object} pluginobject Plugin configuration object. * @returns {void} */ addPlugin(name, pluginobject) { Plugins.define(name, pluginobject); }, /** * Resolves the patterns passed into executeOnFiles() into glob-based patterns * for easier handling. * @param {string[]} patterns The file patterns passed on the command line. * @returns {string[]} The equivalent glob patterns. */ resolveFileGlobPatterns(patterns) { return globUtil.resolveFileGlobPatterns(patterns, this.options); }, /** * Executes the current configuration on an array of file and directory names. * @param {string[]} patterns An array of file and directory names. * @returns {Object} The results for all files that were linted. */ executeOnFiles(patterns) { const results = [], options = this.options, fileCache = this._fileCache, configHelper = new Config(options); let prevConfig; // the previous configuration used /** * Calculates the hash of the config file used to validate a given file * @param {string} filename The path of the file to retrieve a config object for to calculate the hash * @returns {string} the hash of the config */ function hashOfConfigFor(filename) { const config = configHelper.getConfig(filename); if (!prevConfig) { prevConfig = {}; } // reuse the previously hashed config if the config hasn't changed if (prevConfig.config !== config) { /* * config changed so we need to calculate the hash of the config * and the hash of the plugins being used */ prevConfig.config = config; const eslintVersion = pkg.version; prevConfig.hash = hash(eslintVersion + "_" + stringify(config)); } return prevConfig.hash; } /** * Executes the linter on a file defined by the `filename`. Skips * unsupported file extensions and any files that are already linted. * @param {string} filename The resolved filename of the file to be linted * @param {boolean} warnIgnored always warn when a file is ignored * @returns {void} */ function executeOnFile(filename, warnIgnored) { let hashOfConfig, descriptor; if (warnIgnored) { results.push(createIgnoreResult(filename, options.cwd)); return; } if (options.cache) { /* * get the descriptor for this file * with the metadata and the flag that determines if * the file has changed */ descriptor = fileCache.getFileDescriptor(filename); const meta = descriptor.meta || {}; hashOfConfig = hashOfConfigFor(filename); const changed = descriptor.changed || meta.hashOfConfig !== hashOfConfig; if (!changed) { debug("Skipping file since hasn't changed: " + filename); /* * Add the the cached results (always will be 0 error and * 0 warnings). We should not cache results for files that * failed, in order to guarantee that next execution will * process those files as well. */ results.push(descriptor.meta.results); // move to the next file return; } } else { fileCache.destroy(); } debug("Processing " + filename); const res = processFile(filename, configHelper, options); if (options.cache) { /* * if a file contains errors or warnings we don't want to * store the file in the cache so we can guarantee that * next execution will also operate on this file */ if (res.errorCount > 0 || res.warningCount > 0) { debug("File has problems, skipping it: " + filename); // remove the entry from the cache fileCache.removeEntry(filename); } else { /* * since the file passed we store the result here * TODO: check this as we might not need to store the * successful runs as it will always should be 0 errors and * 0 warnings. */ descriptor.meta.hashOfConfig = hashOfConfig; descriptor.meta.results = res; } } results.push(res); } const startTime = Date.now(); patterns = this.resolveFileGlobPatterns(patterns); const fileList = globUtil.listFilesToProcess(patterns, options); fileList.forEach(function(fileInfo) { executeOnFile(fileInfo.filename, fileInfo.ignored); }); const stats = calculateStatsPerRun(results); if (options.cache) { // persist the cache to disk fileCache.reconcile(); } debug("Linting complete in: " + (Date.now() - startTime) + "ms"); return { results, errorCount: stats.errorCount, warningCount: stats.warningCount }; }, /** * Executes the current configuration on text. * @param {string} text A string of JavaScript code to lint. * @param {string} filename An optional string representing the texts filename. * @param {boolean} warnIgnored Always warn when a file is ignored * @returns {Object} The results for the linting. */ executeOnText(text, filename, warnIgnored) { const results = [], options = this.options, configHelper = new Config(options), ignoredPaths = new IgnoredPaths(options); // resolve filename based on options.cwd (for reporting, ignoredPaths also resolves) if (filename && !path.isAbsolute(filename)) { filename = path.resolve(options.cwd, filename); } if (filename && ignoredPaths.contains(filename)) { if (warnIgnored) { results.push(createIgnoreResult(filename, options.cwd)); } } else { results.push(processText(text, configHelper, filename, options.fix, options.allowInlineConfig)); } const stats = calculateStatsPerRun(results); return { results, errorCount: stats.errorCount, warningCount: stats.warningCount }; }, /** * Returns a configuration object for the given file based on the CLI options. * This is the same logic used by the ESLint CLI executable to determine * configuration for each file it processes. * @param {string} filePath The path of the file to retrieve a config object for. * @returns {Object} A configuration object for the file. */ getConfigForFile(filePath) { const configHelper = new Config(this.options); return configHelper.getConfig(filePath); }, /** * Checks if a given path is ignored by ESLint. * @param {string} filePath The path of the file to check. * @returns {boolean} Whether or not the given path is ignored. */ isPathIgnored(filePath) { const resolvedPath = path.resolve(this.options.cwd, filePath); const ignoredPaths = new IgnoredPaths(this.options); return ignoredPaths.contains(resolvedPath); }, getFormatter: CLIEngine.getFormatter }; module.exports = CLIEngine;
// // ____ _ _ // / ___|| |_ __ _ _ __ ___ ___ (_)___ (*) // \___ \| __/ _` | '_ \ / _ \/ __| | / __| // ___) | || (_| | |_) | __/\__ \_ | \__ \ // |____/ \__\__,_| .__/ \___||___(_)/ |___/ // |_| |__/ // // (*) a (really) tiny Javascript MVC microframework // // (c) Hay Kranen < hay@bykr.org > // Released under the terms of the MIT license // < http://en.wikipedia.org/wiki/MIT_License > // // Stapes.js : http://hay.github.com/stapes (function() { 'use strict'; var VERSION = "0.7.0"; // Global counter for all events in all modules (including mixed in objects) var guid = 1; // Makes _.create() faster if (!Object.create) { var CachedFunction = function(){}; } // So we can use slice.call for arguments later on var slice = Array.prototype.slice; // Private attributes and helper functions, stored in an object so they // are overwritable by plugins var _ = { // Properties attributes : {}, eventHandlers : { "-1" : {} // '-1' is used for the global event handling }, guid : -1, // Methods addEvent : function(event) { // If we don't have any handlers for this type of event, add a new // array we can use to push new handlers if (!_.eventHandlers[event.guid][event.type]) { _.eventHandlers[event.guid][event.type] = []; } // Push an event object _.eventHandlers[event.guid][event.type].push({ "guid" : event.guid, "handler" : event.handler, "scope" : event.scope, "type" : event.type }); }, addEventHandler : function(argTypeOrMap, argHandlerOrScope, argScope) { var eventMap = {}, scope; if (typeof argTypeOrMap === "string") { scope = argScope || false; eventMap[ argTypeOrMap ] = argHandlerOrScope; } else { scope = argHandlerOrScope || false; eventMap = argTypeOrMap; } for (var eventString in eventMap) { var handler = eventMap[eventString]; var events = eventString.split(" "); for (var i = 0, l = events.length; i < l; i++) { var eventType = events[i]; _.addEvent.call(this, { "guid" : this._guid || this._.guid, "handler" : handler, "scope" : scope, "type" : eventType }); } } }, addGuid : function(object, forceGuid) { if (object._guid && !forceGuid) return; object._guid = guid++; _.attributes[object._guid] = {}; _.eventHandlers[object._guid] = {}; }, // This is a really small utility function to save typing and produce // better optimized code attr : function(guid) { return _.attributes[guid]; }, clone : function(obj) { return _.extend({}, obj); }, create : function(proto) { if (Object.create) { return Object.create(proto); } else { CachedFunction.prototype = proto; return new CachedFunction(); } }, createSubclass : function(props, includeEvents) { props = props || {}; includeEvents = includeEvents || false; var superclass = props.superclass.prototype; // Objects always have a constructor, so we need to be sure this is // a property instead of something from the prototype var realConstructor = props.hasOwnProperty('constructor') ? props.constructor : function(){}; function constructor() { // Be kind to people forgetting new if (!(this instanceof constructor)) { throw new Error("Please use 'new' when initializing Stapes classes"); } if (includeEvents) { _.addGuid( this, true ); } realConstructor.apply(this, arguments); } if (includeEvents) { _.extend(superclass, Events); } constructor.prototype = _.create(superclass); constructor.prototype.constructor = constructor; _.extend(constructor, { extend : function() { return _.extendThis.apply(this, arguments); }, // We can't call this 'super' because that's a reserved keyword // and fails in IE8 'parent' : superclass, proto : function() { return _.extendThis.apply(this.prototype, arguments); }, subclass : function(obj) { obj = obj || {}; obj.superclass = this; return _.createSubclass(obj); } }); // Copy all props given in the definition to the prototype for (var key in props) { if (key !== 'constructor' && key !== 'superclass') { constructor.prototype[key] = props[key]; } } return constructor; }, emitEvents : function(type, data, explicitType, explicitGuid) { explicitType = explicitType || false; explicitGuid = explicitGuid || this._guid; var handlers = _.eventHandlers[explicitGuid][type]; for (var i = 0, l = handlers.length; i < l; i++) { // Clone the event to prevent issue #19 var event = _.extend({}, handlers[i]); var scope = (event.scope) ? event.scope : this; if (explicitType) { event.type = explicitType; } event.scope = scope; event.handler.call(event.scope, data, event); } }, // Extend an object with more objects extend : function() { var args = slice.call(arguments); var object = args.shift(); for (var i = 0, l = args.length; i < l; i++) { var props = args[i]; for (var key in props) { object[key] = props[key]; } } return object; }, // The same as extend, but uses the this value as the scope extendThis : function() { var args = slice.call(arguments); args.unshift(this); return _.extend.apply(this, args); }, // from http://stackoverflow.com/a/2117523/152809 makeUuid : function() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); }, removeAttribute : function(keys, silent) { silent = silent || false; // Split the key, maybe we want to remove more than one item var attributes = _.trim(keys).split(" "); // Actually delete the item for (var i = 0, l = attributes.length; i < l; i++) { var key = _.trim(attributes[i]); if (key) { delete _.attr(this._guid)[key]; // If 'silent' is set, do not throw any events if (!silent) { this.emit('change', key); this.emit('change:' + key); this.emit('remove', key); this.emit('remove:' + key); } } } }, removeEventHandler : function(type, handler) { var handlers = _.eventHandlers[this._guid]; if (type && handler) { // Remove a specific handler handlers = handlers[type]; if (!handlers) return; for (var i = 0, l = handlers.length, h; i < l; i++) { h = handlers[i].handler; if (h && h === handler) { handlers.splice(i--, 1); l--; } } } else if (type) { // Remove all handlers for a specific type delete handlers[type]; } else { // Remove all handlers for this module _.eventHandlers[this._guid] = {}; } }, setAttribute : function(key, value, silent) { silent = silent || false; // We need to do this before we actually add the item :) var itemExists = this.has(key); var oldValue = _.attr(this._guid)[key]; // Is the value different than the oldValue? If not, ignore this call if (value === oldValue) { return; } // Actually add the item to the attributes _.attr(this._guid)[key] = value; // If 'silent' flag is set, do not throw any events if (silent) { return; } // Throw a generic event this.emit('change', key); // And a namespaced event as well, NOTE that we pass value instead of // key here! this.emit('change:' + key, value); // Throw namespaced and non-namespaced 'mutate' events as well with // the old value data as well and some extra metadata such as the key var mutateData = { "key" : key, "newValue" : value, "oldValue" : oldValue || null }; this.emit('mutate', mutateData); this.emit('mutate:' + key, mutateData); // Also throw a specific event for this type of set var specificEvent = itemExists ? 'update' : 'create'; this.emit(specificEvent, key); // And a namespaced event as well, NOTE that we pass value instead of key this.emit(specificEvent + ':' + key, value); }, trim : function(str) { return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); }, typeOf : function(val) { if (val === null || typeof val === "undefined") { return String(val); } else { return Object.prototype.toString.call(val).replace(/\[object |\]/g, '').toLowerCase(); } }, updateAttribute : function(key, fn, silent) { var item = this.get(key); // In previous versions of Stapes we didn't have the check for object, // but still this worked. In 0.7.0 it suddenly doesn't work anymore and // we need the check. Why? I have no clue. if (_.typeOf(item) === 'object') { item = _.clone(item); } var newValue = fn.call(this, item, key); _.setAttribute.call(this, key, newValue, silent || false); } }; // Can be mixed in later using Stapes.mixinEvents(object); var Events = { emit : function(types, data) { data = (typeof data === "undefined") ? null : data; var splittedTypes = types.split(" "); for (var i = 0, l = splittedTypes.length; i < l; i++) { var type = splittedTypes[i]; // First 'all' type events: is there an 'all' handler in the // global stack? if (_.eventHandlers[-1].all) { _.emitEvents.call(this, "all", data, type, -1); } // Catch all events for this type? if (_.eventHandlers[-1][type]) { _.emitEvents.call(this, type, data, type, -1); } if (typeof this._guid === 'number') { // 'all' event for this specific module? if (_.eventHandlers[this._guid].all) { _.emitEvents.call(this, "all", data, type); } // Finally, normal events :) if (_.eventHandlers[this._guid][type]) { _.emitEvents.call(this, type, data); } } } }, off : function() { _.removeEventHandler.apply(this, arguments); }, on : function() { _.addEventHandler.apply(this, arguments); } }; _.Module = function(){}; _.Module.prototype = { // create() is deprecated from 0.8.0 create : function() { throw new Error(''.concat( 'create() on Stapes modules no longer works from 0.8.0. ', 'Check the docs.' )); }, each : function(fn, ctx) { var attr = _.attr(this._guid); for (var key in attr) { var value = attr[key]; fn.call(ctx || this, value, key); } }, extend : function() { return _.extendThis.apply(this, arguments); }, filter : function(fn) { var filtered = []; var attributes = _.attr(this._guid); for (var key in attributes) { if ( fn.call(this, attributes[key], key)) { filtered.push( attributes[key] ); } } return filtered; }, get : function(input) { if (typeof input === "string") { return this.has(input) ? _.attr(this._guid)[input] : null; } else if (typeof input === "function") { var items = this.filter(input); return (items.length) ? items[0] : null; } }, getAll : function() { return _.clone( _.attr(this._guid) ); }, getAllAsArray : function() { var arr = []; var attributes = _.attr(this._guid); for (var key in attributes) { var value = attributes[key]; if (_.typeOf(value) === "object" && !value.id) { value.id = key; } arr.push(value); } return arr; }, has : function(key) { return (typeof _.attr(this._guid)[key] !== "undefined"); }, map : function(fn, ctx) { var mapped = []; this.each(function(value, key) { mapped.push( fn.call(ctx || this, value, key) ); }, ctx || this); return mapped; }, // Akin to set(), but makes a unique id push : function(input, silent) { if (_.typeOf(input) === "array") { for (var i = 0, l = input.length; i < l; i++) { _.setAttribute.call(this, _.makeUuid(), input[i]); } } else { _.setAttribute.call(this, _.makeUuid(), input, silent || false); } return this; }, remove : function(input, silent) { if (typeof input === "function") { this.each(function(item, key) { if (input(item)) { _.removeAttribute.call(this, key, silent); } }); } else { // nb: checking for exists happens in removeAttribute _.removeAttribute.call(this, input, silent || false); } return this; }, set : function(objOrKey, value, silent) { if (typeof objOrKey === "object") { for (var key in objOrKey) { _.setAttribute.call(this, key, objOrKey[key]); } } else { _.setAttribute.call(this, objOrKey, value, silent || false); } return this; }, size : function() { var size = 0; var attr = _.attr(this._guid); for (var key in attr) { size++; } return size; }, update : function(keyOrFn, fn, silent) { if (typeof keyOrFn === "string") { _.updateAttribute.call(this, keyOrFn, fn, silent || false); } else if (typeof keyOrFn === "function") { this.each(function(value, key) { _.updateAttribute.call(this, key, keyOrFn); }); } return this; } }; var Stapes = { "_" : _, // private helper functions and properties // Compatiblity option, this method is deprecated "create" : function() { var instance = _.create( _.Module.prototype ); _.addGuid( instance, true ); // Mixin events Stapes.mixinEvents( instance ); return instance; }, "extend" : function() { return _.extendThis.apply(_.Moduel, arguments); }, "mixinEvents" : function(obj) { obj = obj || {}; _.addGuid(obj); return _.extend(obj, Events); }, "on" : function() { _.addEventHandler.apply(this, arguments); }, "subclass" : function(obj, classOnly) { classOnly = classOnly || false; obj = obj || {}; obj.superclass = classOnly ? function(){} : _.Module; return _.createSubclass(obj, !classOnly); }, "version" : VERSION }; // This library can be used as an AMD module, a Node.js module, or an // old fashioned global if (typeof exports !== "undefined") { // Server if (typeof module !== "undefined" && module.exports) { exports = module.exports = Stapes; } exports.Stapes = Stapes; } else if (typeof define === "function" && define.amd) { // AMD define(function() { return Stapes; }); } else { // Global scope window.Stapes = Stapes; } })();
/** * @fileoverview Rule to flag unnecessary double negation in Boolean contexts * @author Brandon Mills */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = function(context) { // Node types which have a test which will coerce values to booleans. var BOOLEAN_NODE_TYPES = [ "IfStatement", "DoWhileStatement", "WhileStatement", "ConditionalExpression", "ForStatement" ]; /** * Check if a node is in a context where its value would be coerced to a boolean at runtime. * * @param {Object} node The node * @param {Object} parent Its parent * @returns {Boolean} If it is in a boolean context */ function isInBooleanContext(node, parent) { return ( (BOOLEAN_NODE_TYPES.indexOf(parent.type) !== -1 && node === parent.test) || // !<bool> (parent.type === "UnaryExpression" && parent.operator === "!") ); } return { "UnaryExpression": function(node) { var ancestors = context.getAncestors(), parent = ancestors.pop(), grandparent = ancestors.pop(); // Exit early if it's guaranteed not to match if (node.operator !== "!" || parent.type !== "UnaryExpression" || parent.operator !== "!") { return; } if (isInBooleanContext(parent, grandparent) || // Boolean(<bool>) and new Boolean(<bool>) ((grandparent.type === "CallExpression" || grandparent.type === "NewExpression") && grandparent.callee.type === "Identifier" && grandparent.callee.name === "Boolean") ) { context.report(node, "Redundant double negation."); } }, "CallExpression": function(node) { var parent = node.parent; if (node.callee.type !== "Identifier" || node.callee.name !== "Boolean") { return; } if (isInBooleanContext(node, parent)) { context.report(node, "Redundant Boolean call."); } } }; }; module.exports.schema = [];
"use strict"; module.exports = require("./_iterate")(require("../array/#/find"), false);
/** * Globalize Runtime v1.2.3 * * http://github.com/jquery/globalize * * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2017-03-17T01:41Z */ /*! * Globalize Runtime v1.2.3 2017-03-17T01:41Z Released under the MIT license * http://git.io/TrdQbw */ (function( root, factory ) { // UMD returnExports if ( typeof define === "function" && define.amd ) { // AMD define([ "../globalize-runtime", "./number", "./plural" ], factory ); } else if ( typeof exports === "object" ) { // Node, CommonJS module.exports = factory( require( "../globalize-runtime" ), require( "./number" ), require( "./plural" ) ); } else { // Extend global factory( root.Globalize ); } }(this, function( Globalize ) { var formatMessage = Globalize._formatMessage, runtimeKey = Globalize._runtimeKey, validateParameterPresence = Globalize._validateParameterPresence, validateParameterTypeNumber = Globalize._validateParameterTypeNumber; /** * format( value, numberFormatter, pluralGenerator, unitProperies ) * * @value [Number] * * @numberFormatter [Object]: A numberFormatter from Globalize.numberFormatter. * * @pluralGenerator [Object]: A pluralGenerator from Globalize.pluralGenerator. * * @unitProperies [Object]: localized unit data from cldr. * * Format units such as seconds, minutes, days, weeks, etc. * * OBS: * * Unit Sequences are not implemented. * http://www.unicode.org/reports/tr35/tr35-35/tr35-general.html#Unit_Sequences * * Duration Unit (for composed time unit durations) is not implemented. * http://www.unicode.org/reports/tr35/tr35-35/tr35-general.html#durationUnit */ var unitFormat = function( value, numberFormatter, pluralGenerator, unitProperties ) { var compoundUnitPattern = unitProperties.compoundUnitPattern, dividend, dividendProperties, formattedValue, divisor, divisorProperties, message, pluralValue; unitProperties = unitProperties.unitProperties; formattedValue = numberFormatter( value ); pluralValue = pluralGenerator( value ); // computed compound unit, eg. "megabyte-per-second". if ( unitProperties instanceof Array ) { dividendProperties = unitProperties[ 0 ]; divisorProperties = unitProperties[ 1 ]; dividend = formatMessage( dividendProperties[ pluralValue ], [ value ] ); divisor = formatMessage( divisorProperties.one, [ "" ] ).trim(); return formatMessage( compoundUnitPattern, [ dividend, divisor ] ); } message = unitProperties[ pluralValue ]; return formatMessage( message, [ formattedValue ] ); }; var unitFormatterFn = function( numberFormatter, pluralGenerator, unitProperties ) { return function unitFormatter( value ) { validateParameterPresence( value, "value" ); validateParameterTypeNumber( value, "value" ); return unitFormat( value, numberFormatter, pluralGenerator, unitProperties ); }; }; Globalize._unitFormatterFn = unitFormatterFn; Globalize.formatUnit = Globalize.prototype.formatUnit = function( value, unit, options ) { return this.unitFormatter( unit, options )( value ); }; Globalize.unitFormatter = Globalize.prototype.unitFormatter = function( unit, options ) { options = options || {}; return Globalize[ runtimeKey( "unitFormatter", this._locale, [ unit, options ] ) ]; }; return Globalize; }));
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react"), require("react-dom")); else if(typeof define === 'function' && define.amd) define(["react", "react-dom"], factory); else if(typeof exports === 'object') exports["ReactBootstrapTable"] = factory(require("react"), require("react-dom")); else root["ReactBootstrapTable"] = factory(root["React"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_6__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.TableHeaderColumn = exports.BootstrapTable = undefined; var _BootstrapTable = __webpack_require__(1); var _BootstrapTable2 = _interopRequireDefault(_BootstrapTable); var _TableHeaderColumn = __webpack_require__(191); var _TableHeaderColumn2 = _interopRequireDefault(_TableHeaderColumn); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } if (typeof window !== 'undefined') { window.BootstrapTable = _BootstrapTable2.default; window.TableHeaderColumn = _TableHeaderColumn2.default; } exports.BootstrapTable = _BootstrapTable2.default; exports.TableHeaderColumn = _TableHeaderColumn2.default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } }(); ; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var _TableHeader = __webpack_require__(5); var _TableHeader2 = _interopRequireDefault(_TableHeader); var _TableBody = __webpack_require__(8); var _TableBody2 = _interopRequireDefault(_TableBody); var _PaginationList = __webpack_require__(180); var _PaginationList2 = _interopRequireDefault(_PaginationList); var _ToolBar = __webpack_require__(182); var _ToolBar2 = _interopRequireDefault(_ToolBar); var _TableFilter = __webpack_require__(183); var _TableFilter2 = _interopRequireDefault(_TableFilter); var _TableDataStore = __webpack_require__(184); var _util = __webpack_require__(9); var _util2 = _interopRequireDefault(_util); var _csv_export_util = __webpack_require__(185); var _csv_export_util2 = _interopRequireDefault(_csv_export_util); var _Filter = __webpack_require__(189); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint no-alert: 0 */ /* eslint max-len: 0 */ var BootstrapTable = function (_Component) { _inherits(BootstrapTable, _Component); function BootstrapTable(props) { _classCallCheck(this, BootstrapTable); var _this = _possibleConstructorReturn(this, (BootstrapTable.__proto__ || Object.getPrototypeOf(BootstrapTable)).call(this, props)); _this.handleSort = function () { return _this.__handleSort__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleExpandRow = function () { return _this.__handleExpandRow__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handlePaginationData = function () { return _this.__handlePaginationData__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleMouseLeave = function () { return _this.__handleMouseLeave__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleMouseEnter = function () { return _this.__handleMouseEnter__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleRowMouseOut = function () { return _this.__handleRowMouseOut__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleRowMouseOver = function () { return _this.__handleRowMouseOver__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleRowClick = function () { return _this.__handleRowClick__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleRowDoubleClick = function () { return _this.__handleRowDoubleClick__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleSelectAllRow = function () { return _this.__handleSelectAllRow__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleShowOnlySelected = function () { return _this.__handleShowOnlySelected__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleSelectRow = function () { return _this.__handleSelectRow__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleAddRow = function () { return _this.__handleAddRow__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.getPageByRowKey = function () { return _this.__getPageByRowKey__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleDropRow = function () { return _this.__handleDropRow__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleFilterData = function () { return _this.__handleFilterData__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleExportCSV = function () { return _this.__handleExportCSV__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleSearch = function () { return _this.__handleSearch__REACT_HOT_LOADER__.apply(_this, arguments); }; _this._scrollTop = function () { return _this.___scrollTop__REACT_HOT_LOADER__.apply(_this, arguments); }; _this._scrollHeader = function () { return _this.___scrollHeader__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.isIE = false; _this._attachCellEditFunc(); if (_util2.default.canUseDOM()) { _this.isIE = document.documentMode; } _this.store = new _TableDataStore.TableDataStore(_this.props.data.slice()); _this.initTable(_this.props); if (_this.props.selectRow && _this.props.selectRow.selected) { var copy = _this.props.selectRow.selected.slice(); _this.store.setSelectedRowKey(copy); } var currPage = _Const2.default.PAGE_START_INDEX; if (typeof _this.props.options.page !== 'undefined') { currPage = _this.props.options.page; } else if (typeof _this.props.options.pageStartIndex !== 'undefined') { currPage = _this.props.options.pageStartIndex; } _this._adjustHeaderWidth = _this._adjustHeaderWidth.bind(_this); _this._adjustHeight = _this._adjustHeight.bind(_this); _this._adjustTable = _this._adjustTable.bind(_this); _this.state = { data: _this.getTableData(), currPage: currPage, expanding: _this.props.options.expanding || [], sizePerPage: _this.props.options.sizePerPage || _Const2.default.SIZE_PER_PAGE_LIST[0], selectedRowKeys: _this.store.getSelectedRowKeys() }; return _this; } _createClass(BootstrapTable, [{ key: 'initTable', value: function initTable(props) { var _this2 = this; var keyField = props.keyField; var isKeyFieldDefined = typeof keyField === 'string' && keyField.length; _react2.default.Children.forEach(props.children, function (column) { if (column.props.isKey) { if (keyField) { throw new Error('Error. Multiple key column be detected in TableHeaderColumn.'); } keyField = column.props.dataField; } if (column.props.filter) { // a column contains a filter if (!_this2.filter) { // first time create the filter on the BootstrapTable _this2.filter = new _Filter.Filter(); } // pass the filter to column with filter column.props.filter.emitter = _this2.filter; } }); if (this.filter) { this.filter.removeAllListeners('onFilterChange'); this.filter.on('onFilterChange', function (currentFilter) { _this2.handleFilterData(currentFilter); }); } this.colInfos = this.getColumnsDescription(props).reduce(function (prev, curr) { prev[curr.name] = curr; return prev; }, {}); if (!isKeyFieldDefined && !keyField) { throw new Error('Error. No any key column defined in TableHeaderColumn.\n Use \'isKey={true}\' to specify a unique column after version 0.5.4.'); } this.store.setProps({ isPagination: props.pagination, keyField: keyField, colInfos: this.colInfos, multiColumnSearch: props.multiColumnSearch, multiColumnSort: props.multiColumnSort, remote: this.isRemoteDataSource() }); } }, { key: 'getTableData', value: function getTableData() { var result = []; var _props = this.props, options = _props.options, pagination = _props.pagination; var sortName = options.defaultSortName || options.sortName; var sortOrder = options.defaultSortOrder || options.sortOrder; var searchText = options.defaultSearch; if (sortName && sortOrder) { this.store.setSortInfo(sortOrder, sortName); this.store.sort(); } if (searchText) { this.store.search(searchText); } if (pagination) { var page = void 0; var sizePerPage = void 0; if (this.store.isChangedPage()) { sizePerPage = this.state.sizePerPage; page = this.state.currPage; } else { sizePerPage = options.sizePerPage || _Const2.default.SIZE_PER_PAGE_LIST[0]; page = options.page || 1; } result = this.store.page(page, sizePerPage).get(); } else { result = this.store.get(); } return result; } }, { key: 'getColumnsDescription', value: function getColumnsDescription(_ref) { var children = _ref.children; var rowCount = 0; _react2.default.Children.forEach(children, function (column) { if (Number(column.props.row) > rowCount) { rowCount = Number(column.props.row); } }); return _react2.default.Children.map(children, function (column, i) { var rowIndex = column.props.row ? Number(column.props.row) : 0; var rowSpan = column.props.rowSpan ? Number(column.props.rowSpan) : 1; if (rowSpan + rowIndex === rowCount + 1) { return { name: column.props.dataField, align: column.props.dataAlign, sort: column.props.dataSort, format: column.props.dataFormat, formatExtraData: column.props.formatExtraData, filterFormatted: column.props.filterFormatted, filterValue: column.props.filterValue, editable: column.props.editable, customEditor: column.props.customEditor, hidden: column.props.hidden, hiddenOnInsert: column.props.hiddenOnInsert, searchable: column.props.searchable, className: column.props.columnClassName, editClassName: column.props.editColumnClassName, invalidEditColumnClassName: column.props.invalidEditColumnClassName, columnTitle: column.props.columnTitle, width: column.props.width, text: column.props.headerText || column.props.children, sortFunc: column.props.sortFunc, sortFuncExtraData: column.props.sortFuncExtraData, export: column.props.export, expandable: column.props.expandable, index: i, attrs: column.props.tdAttr }; } }); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { this.initTable(nextProps); var options = nextProps.options, selectRow = nextProps.selectRow; this.store.setData(nextProps.data.slice()); // from #481 var page = this.state.currPage; if (this.props.options.page !== options.page) { page = options.page; } // from #481 var sizePerPage = this.state.sizePerPage; if (this.props.options.sizePerPage !== options.sizePerPage) { sizePerPage = options.sizePerPage; } if (this.isRemoteDataSource()) { this.setState({ data: nextProps.data.slice(), currPage: page, sizePerPage: sizePerPage }); } else { // #125 // remove !options.page for #709 if (page > Math.ceil(nextProps.data.length / sizePerPage)) { page = 1; } var sortList = this.store.getSortInfo(); var sortField = options.sortName; var sortOrder = options.sortOrder; if (sortField && sortOrder) { this.store.setSortInfo(sortOrder, sortField); this.store.sort(); } else if (sortList.length > 0) { this.store.sort(); } var data = this.store.page(page, sizePerPage).get(); this.setState({ data: data, currPage: page, sizePerPage: sizePerPage }); } if (selectRow && selectRow.selected) { // set default select rows to store. var copy = selectRow.selected.slice(); this.store.setSelectedRowKey(copy); this.setState({ selectedRowKeys: copy }); } } }, { key: 'componentDidMount', value: function componentDidMount() { this._adjustTable(); window.addEventListener('resize', this._adjustTable); this.refs.body.refs.container.addEventListener('scroll', this._scrollHeader); if (this.props.scrollTop) { this._scrollTop(); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { window.removeEventListener('resize', this._adjustTable); this.refs.body.refs.container.removeEventListener('scroll', this._scrollHeader); if (this.filter) { this.filter.removeAllListeners('onFilterChange'); } } }, { key: 'componentDidUpdate', value: function componentDidUpdate() { this._adjustTable(); this._attachCellEditFunc(); if (this.props.options.afterTableComplete) { this.props.options.afterTableComplete(); } } }, { key: '_attachCellEditFunc', value: function _attachCellEditFunc() { var cellEdit = this.props.cellEdit; if (cellEdit) { this.props.cellEdit.__onCompleteEdit__ = this.handleEditCell.bind(this); if (cellEdit.mode !== _Const2.default.CELL_EDIT_NONE) { this.props.selectRow.clickToSelect = false; } } } /** * Returns true if in the current configuration, * the datagrid should load its data remotely. * * @param {Object} [props] Optional. If not given, this.props will be used * @return {Boolean} */ }, { key: 'isRemoteDataSource', value: function isRemoteDataSource(props) { return (props || this.props).remote; } }, { key: 'render', value: function render() { var style = { height: this.props.height, maxHeight: this.props.maxHeight }; var columns = this.getColumnsDescription(this.props); var sortList = this.store.getSortInfo(); var pagination = this.renderPagination(); var toolBar = this.renderToolBar(); var tableFilter = this.renderTableFilter(columns); var isSelectAll = this.isSelectAll(); var colGroups = _util2.default.renderColGroup(columns, this.props.selectRow); var sortIndicator = this.props.options.sortIndicator; if (typeof this.props.options.sortIndicator === 'undefined') sortIndicator = true; return _react2.default.createElement( 'div', { className: (0, _classnames2.default)('react-bs-table-container', this.props.containerClass), style: this.props.containerStyle }, toolBar, _react2.default.createElement( 'div', { ref: 'table', className: (0, _classnames2.default)('react-bs-table', this.props.tableContainerClass), style: _extends({}, style, this.props.tableStyle), onMouseEnter: this.handleMouseEnter, onMouseLeave: this.handleMouseLeave }, _react2.default.createElement( _TableHeader2.default, { ref: 'header', colGroups: colGroups, headerContainerClass: this.props.headerContainerClass, tableHeaderClass: this.props.tableHeaderClass, style: this.props.headerStyle, rowSelectType: this.props.selectRow.mode, customComponent: this.props.selectRow.customComponent, hideSelectColumn: this.props.selectRow.hideSelectColumn, sortList: sortList, sortIndicator: sortIndicator, onSort: this.handleSort, onSelectAllRow: this.handleSelectAllRow, bordered: this.props.bordered, condensed: this.props.condensed, isFiltered: this.filter ? true : false, isSelectAll: isSelectAll }, this.props.children ), _react2.default.createElement(_TableBody2.default, { ref: 'body', bodyContainerClass: this.props.bodyContainerClass, tableBodyClass: this.props.tableBodyClass, style: _extends({}, style, this.props.bodyStyle), data: this.state.data, expandComponent: this.props.expandComponent, expandableRow: this.props.expandableRow, expandRowBgColor: this.props.options.expandRowBgColor, expandBy: this.props.options.expandBy || _Const2.default.EXPAND_BY_ROW, columns: columns, trClassName: this.props.trClassName, striped: this.props.striped, bordered: this.props.bordered, hover: this.props.hover, keyField: this.store.getKeyField(), condensed: this.props.condensed, selectRow: this.props.selectRow, cellEdit: this.props.cellEdit, selectedRowKeys: this.state.selectedRowKeys, onRowClick: this.handleRowClick, onRowDoubleClick: this.handleRowDoubleClick, onRowMouseOver: this.handleRowMouseOver, onRowMouseOut: this.handleRowMouseOut, onSelectRow: this.handleSelectRow, noDataText: this.props.options.noDataText, withoutNoDataText: this.props.options.withoutNoDataText, expanding: this.state.expanding, onExpand: this.handleExpandRow, beforeShowError: this.props.options.beforeShowError }) ), tableFilter, pagination ); } }, { key: 'isSelectAll', value: function isSelectAll() { if (this.store.isEmpty()) return false; var unselectable = this.props.selectRow.unselectable; var defaultSelectRowKeys = this.store.getSelectedRowKeys(); var allRowKeys = this.store.getAllRowkey(); if (defaultSelectRowKeys.length === 0) return false; var match = 0; var noFound = 0; var unSelectableCnt = 0; defaultSelectRowKeys.forEach(function (selected) { if (allRowKeys.indexOf(selected) !== -1) match++;else noFound++; if (unselectable && unselectable.indexOf(selected) !== -1) unSelectableCnt++; }); if (noFound === defaultSelectRowKeys.length) return false; if (match === allRowKeys.length) { return true; } else { if (unselectable && match <= unSelectableCnt && unSelectableCnt === unselectable.length) return false;else return 'indeterminate'; } // return (match === allRowKeys.length) ? true : 'indeterminate'; } }, { key: 'cleanSelected', value: function cleanSelected() { this.store.setSelectedRowKey([]); this.setState({ selectedRowKeys: [] }); } }, { key: '__handleSort__REACT_HOT_LOADER__', value: function __handleSort__REACT_HOT_LOADER__(order, sortField) { if (this.props.options.onSortChange) { this.props.options.onSortChange(sortField, order, this.props); } this.store.setSortInfo(order, sortField); if (this.isRemoteDataSource()) { return; } var result = this.store.sort().get(); this.setState({ data: result }); } }, { key: '__handleExpandRow__REACT_HOT_LOADER__', value: function __handleExpandRow__REACT_HOT_LOADER__(expanding) { var _this3 = this; this.setState({ expanding: expanding }, function () { _this3._adjustHeaderWidth(); }); } }, { key: '__handlePaginationData__REACT_HOT_LOADER__', value: function __handlePaginationData__REACT_HOT_LOADER__(page, sizePerPage) { var _props$options = this.props.options, onPageChange = _props$options.onPageChange, pageStartIndex = _props$options.pageStartIndex; if (onPageChange) { onPageChange(page, sizePerPage); } this.setState({ currPage: page, sizePerPage: sizePerPage }); if (this.isRemoteDataSource()) { return; } // We calculate an offset here in order to properly fetch the indexed data, // despite the page start index not always being 1 var normalizedPage = void 0; if (pageStartIndex !== undefined) { var offset = Math.abs(_Const2.default.PAGE_START_INDEX - pageStartIndex); normalizedPage = page + offset; } else { normalizedPage = page; } var result = this.store.page(normalizedPage, sizePerPage).get(); this.setState({ data: result }); } }, { key: '__handleMouseLeave__REACT_HOT_LOADER__', value: function __handleMouseLeave__REACT_HOT_LOADER__() { if (this.props.options.onMouseLeave) { this.props.options.onMouseLeave(); } } }, { key: '__handleMouseEnter__REACT_HOT_LOADER__', value: function __handleMouseEnter__REACT_HOT_LOADER__() { if (this.props.options.onMouseEnter) { this.props.options.onMouseEnter(); } } }, { key: '__handleRowMouseOut__REACT_HOT_LOADER__', value: function __handleRowMouseOut__REACT_HOT_LOADER__(row, event) { if (this.props.options.onRowMouseOut) { this.props.options.onRowMouseOut(row, event); } } }, { key: '__handleRowMouseOver__REACT_HOT_LOADER__', value: function __handleRowMouseOver__REACT_HOT_LOADER__(row, event) { if (this.props.options.onRowMouseOver) { this.props.options.onRowMouseOver(row, event); } } }, { key: '__handleRowClick__REACT_HOT_LOADER__', value: function __handleRowClick__REACT_HOT_LOADER__(row) { if (this.props.options.onRowClick) { this.props.options.onRowClick(row); } } }, { key: '__handleRowDoubleClick__REACT_HOT_LOADER__', value: function __handleRowDoubleClick__REACT_HOT_LOADER__(row) { if (this.props.options.onRowDoubleClick) { this.props.options.onRowDoubleClick(row); } } }, { key: '__handleSelectAllRow__REACT_HOT_LOADER__', value: function __handleSelectAllRow__REACT_HOT_LOADER__(e) { var isSelected = e.currentTarget.checked; var keyField = this.store.getKeyField(); var _props$selectRow = this.props.selectRow, onSelectAll = _props$selectRow.onSelectAll, unselectable = _props$selectRow.unselectable, selected = _props$selectRow.selected; var selectedRowKeys = []; var result = true; var rows = isSelected ? this.store.get() : this.store.getRowByKey(this.state.selectedRowKeys); if (unselectable && unselectable.length > 0) { if (isSelected) { rows = rows.filter(function (r) { return unselectable.indexOf(r[keyField]) === -1 || selected && selected.indexOf(r[keyField]) !== -1; }); } else { rows = rows.filter(function (r) { return unselectable.indexOf(r[keyField]) === -1; }); } } if (onSelectAll) { result = this.props.selectRow.onSelectAll(isSelected, rows); } if (typeof result == 'undefined' || result !== false) { if (isSelected) { selectedRowKeys = Array.isArray(result) ? result : rows.map(function (r) { return r[keyField]; }); } else { if (unselectable && selected) { selectedRowKeys = selected.filter(function (r) { return unselectable.indexOf(r) > -1; }); } } this.store.setSelectedRowKey(selectedRowKeys); this.setState({ selectedRowKeys: selectedRowKeys }); } } }, { key: '__handleShowOnlySelected__REACT_HOT_LOADER__', value: function __handleShowOnlySelected__REACT_HOT_LOADER__() { this.store.ignoreNonSelected(); var result = void 0; if (this.props.pagination) { result = this.store.page(1, this.state.sizePerPage).get(); } else { result = this.store.get(); } this.setState({ data: result, currPage: this.props.options.pageStartIndex || _Const2.default.PAGE_START_INDEX }); } }, { key: '__handleSelectRow__REACT_HOT_LOADER__', value: function __handleSelectRow__REACT_HOT_LOADER__(row, isSelected, e) { var result = true; var currSelected = this.store.getSelectedRowKeys(); var rowKey = row[this.store.getKeyField()]; var selectRow = this.props.selectRow; if (selectRow.onSelect) { result = selectRow.onSelect(row, isSelected, e); } if (typeof result === 'undefined' || result !== false) { if (selectRow.mode === _Const2.default.ROW_SELECT_SINGLE) { currSelected = isSelected ? [rowKey] : []; } else { if (isSelected) { currSelected.push(rowKey); } else { currSelected = currSelected.filter(function (key) { return rowKey !== key; }); } } this.store.setSelectedRowKey(currSelected); this.setState({ selectedRowKeys: currSelected }); } } }, { key: 'handleEditCell', value: function handleEditCell(newVal, rowIndex, colIndex) { var onCellEdit = this.props.options.onCellEdit; var _props$cellEdit = this.props.cellEdit, beforeSaveCell = _props$cellEdit.beforeSaveCell, afterSaveCell = _props$cellEdit.afterSaveCell; var columns = this.getColumnsDescription(this.props); var fieldName = columns[colIndex].name; if (beforeSaveCell) { var isValid = beforeSaveCell(this.state.data[rowIndex], fieldName, newVal); if (!isValid && typeof isValid !== 'undefined') { this.setState({ data: this.store.get() }); return; } } if (onCellEdit) { newVal = onCellEdit(this.state.data[rowIndex], fieldName, newVal); } if (this.isRemoteDataSource()) { if (afterSaveCell) { afterSaveCell(this.state.data[rowIndex], fieldName, newVal); } return; } var result = this.store.edit(newVal, rowIndex, fieldName).get(); this.setState({ data: result }); if (afterSaveCell) { afterSaveCell(this.state.data[rowIndex], fieldName, newVal); } } }, { key: 'handleAddRowAtBegin', value: function handleAddRowAtBegin(newObj) { try { this.store.addAtBegin(newObj); } catch (e) { return e; } this._handleAfterAddingRow(newObj, true); } }, { key: '__handleAddRow__REACT_HOT_LOADER__', value: function __handleAddRow__REACT_HOT_LOADER__(newObj) { var onAddRow = this.props.options.onAddRow; if (onAddRow) { var colInfos = this.store.getColInfos(); onAddRow(newObj, colInfos); } if (this.isRemoteDataSource()) { if (this.props.options.afterInsertRow) { this.props.options.afterInsertRow(newObj); } return null; } try { this.store.add(newObj); } catch (e) { return e.message; } this._handleAfterAddingRow(newObj, false); } }, { key: 'getSizePerPage', value: function getSizePerPage() { return this.state.sizePerPage; } }, { key: 'getCurrentPage', value: function getCurrentPage() { return this.state.currPage; } }, { key: 'getTableDataIgnorePaging', value: function getTableDataIgnorePaging() { return this.store.getCurrentDisplayData(); } }, { key: '__getPageByRowKey__REACT_HOT_LOADER__', value: function __getPageByRowKey__REACT_HOT_LOADER__(rowKey) { var sizePerPage = this.state.sizePerPage; var currentData = this.store.getCurrentDisplayData(); var keyField = this.store.getKeyField(); var result = currentData.findIndex(function (x) { return x[keyField] === rowKey; }); if (result > -1) { return parseInt(result / sizePerPage, 10) + 1; } else { return result; } } }, { key: '__handleDropRow__REACT_HOT_LOADER__', value: function __handleDropRow__REACT_HOT_LOADER__(rowKeys) { var _this4 = this; var dropRowKeys = rowKeys ? rowKeys : this.store.getSelectedRowKeys(); // add confirm before the delete action if that option is set. if (dropRowKeys && dropRowKeys.length > 0) { if (this.props.options.handleConfirmDeleteRow) { this.props.options.handleConfirmDeleteRow(function () { _this4.deleteRow(dropRowKeys); }, dropRowKeys); } else if (confirm('Are you sure you want to delete?')) { this.deleteRow(dropRowKeys); } } } }, { key: 'deleteRow', value: function deleteRow(dropRowKeys) { var onDeleteRow = this.props.options.onDeleteRow; if (onDeleteRow) { onDeleteRow(dropRowKeys); } this.store.setSelectedRowKey([]); // clear selected row key if (this.isRemoteDataSource()) { if (this.props.options.afterDeleteRow) { this.props.options.afterDeleteRow(dropRowKeys); } return; } this.store.remove(dropRowKeys); // remove selected Row var result = void 0; if (this.props.pagination) { var sizePerPage = this.state.sizePerPage; var currLastPage = Math.ceil(this.store.getDataNum() / sizePerPage); var currPage = this.state.currPage; if (currPage > currLastPage) currPage = currLastPage; result = this.store.page(currPage, sizePerPage).get(); this.setState({ data: result, selectedRowKeys: this.store.getSelectedRowKeys(), currPage: currPage }); } else { result = this.store.get(); this.setState({ data: result, selectedRowKeys: this.store.getSelectedRowKeys() }); } if (this.props.options.afterDeleteRow) { this.props.options.afterDeleteRow(dropRowKeys); } } }, { key: '__handleFilterData__REACT_HOT_LOADER__', value: function __handleFilterData__REACT_HOT_LOADER__(filterObj) { var onFilterChange = this.props.options.onFilterChange; if (onFilterChange) { var colInfos = this.store.getColInfos(); onFilterChange(filterObj, colInfos); } this.setState({ currPage: this.props.options.pageStartIndex || _Const2.default.PAGE_START_INDEX }); if (this.isRemoteDataSource()) { if (this.props.options.afterColumnFilter) { this.props.options.afterColumnFilter(filterObj, this.store.getDataIgnoringPagination()); } return; } this.store.filter(filterObj); var sortList = this.store.getSortInfo(); if (sortList.length > 0) { this.store.sort(); } var result = void 0; if (this.props.pagination) { var sizePerPage = this.state.sizePerPage; result = this.store.page(1, sizePerPage).get(); } else { result = this.store.get(); } if (this.props.options.afterColumnFilter) { this.props.options.afterColumnFilter(filterObj, this.store.getDataIgnoringPagination()); } this.setState({ data: result }); } }, { key: '__handleExportCSV__REACT_HOT_LOADER__', value: function __handleExportCSV__REACT_HOT_LOADER__() { var result = {}; var csvFileName = this.props.csvFileName; var onExportToCSV = this.props.options.onExportToCSV; if (onExportToCSV) { result = onExportToCSV(); } else { result = this.store.getDataIgnoringPagination(); } var keys = []; this.props.children.map(function (column) { if (column.props.export === true || typeof column.props.export === 'undefined' && column.props.hidden === false) { keys.push({ field: column.props.dataField, format: column.props.csvFormat, header: column.props.csvHeader || column.props.dataField, row: Number(column.props.row) || 0, rowSpan: Number(column.props.rowSpan) || 1, colSpan: Number(column.props.colSpan) || 1 }); } }); if (typeof csvFileName === 'function') { csvFileName = csvFileName(); } (0, _csv_export_util2.default)(result, keys, csvFileName); } }, { key: '__handleSearch__REACT_HOT_LOADER__', value: function __handleSearch__REACT_HOT_LOADER__(searchText) { // Set search field if this function being called outside // but it's not necessary if calling fron inside. if (this.refs.toolbar) { this.refs.toolbar.setSearchInput(searchText); } var onSearchChange = this.props.options.onSearchChange; if (onSearchChange) { var colInfos = this.store.getColInfos(); onSearchChange(searchText, colInfos, this.props.multiColumnSearch); } this.setState({ currPage: this.props.options.pageStartIndex || _Const2.default.PAGE_START_INDEX }); if (this.isRemoteDataSource()) { if (this.props.options.afterSearch) { this.props.options.afterSearch(searchText, this.store.getDataIgnoringPagination()); } return; } this.store.search(searchText); var sortList = this.store.getSortInfo(); if (sortList.length > 0) { this.store.sort(); } var result = void 0; if (this.props.pagination) { var sizePerPage = this.state.sizePerPage; result = this.store.page(1, sizePerPage).get(); } else { result = this.store.get(); } if (this.props.options.afterSearch) { this.props.options.afterSearch(searchText, this.store.getDataIgnoringPagination()); } this.setState({ data: result }); } }, { key: 'renderPagination', value: function renderPagination() { if (this.props.pagination) { var dataSize = void 0; if (this.isRemoteDataSource()) { dataSize = this.props.fetchInfo.dataTotalSize; } else { dataSize = this.store.getDataNum(); } var options = this.props.options; if (Math.ceil(dataSize / this.state.sizePerPage) <= 1 && this.props.ignoreSinglePage) return null; return _react2.default.createElement( 'div', { className: 'react-bs-table-pagination' }, _react2.default.createElement(_PaginationList2.default, { ref: 'pagination', currPage: this.state.currPage, changePage: this.handlePaginationData, sizePerPage: this.state.sizePerPage, sizePerPageList: options.sizePerPageList || _Const2.default.SIZE_PER_PAGE_LIST, pageStartIndex: options.pageStartIndex, paginationShowsTotal: options.paginationShowsTotal, paginationSize: options.paginationSize || _Const2.default.PAGINATION_SIZE, remote: this.isRemoteDataSource(), dataSize: dataSize, onSizePerPageList: options.onSizePerPageList, prePage: options.prePage || _Const2.default.PRE_PAGE, nextPage: options.nextPage || _Const2.default.NEXT_PAGE, firstPage: options.firstPage || _Const2.default.FIRST_PAGE, lastPage: options.lastPage || _Const2.default.LAST_PAGE, hideSizePerPage: options.hideSizePerPage }) ); } return null; } }, { key: 'renderToolBar', value: function renderToolBar() { var _props2 = this.props, selectRow = _props2.selectRow, insertRow = _props2.insertRow, deleteRow = _props2.deleteRow, search = _props2.search, children = _props2.children; var enableShowOnlySelected = selectRow && selectRow.showOnlySelected; if (enableShowOnlySelected || insertRow || deleteRow || search || this.props.exportCSV) { var columns = void 0; if (Array.isArray(children)) { columns = children.map(function (column, r) { var props = column.props; return { name: props.headerText || props.children, field: props.dataField, hiddenOnInsert: props.hiddenOnInsert, // when you want same auto generate value and not allow edit, example ID field autoValue: props.autoValue || false, // for create editor, no params for column.editable() indicate that editor for new row editable: props.editable && typeof props.editable === 'function' ? props.editable() : props.editable, format: props.dataFormat ? function (value) { return props.dataFormat(value, null, props.formatExtraData, r).replace(/<.*?>/g, ''); } : false }; }); } else { columns = [{ name: children.props.headerText || children.props.children, field: children.props.dataField, editable: children.props.editable, hiddenOnInsert: children.props.hiddenOnInsert }]; } return _react2.default.createElement( 'div', { className: 'react-bs-table-tool-bar' }, _react2.default.createElement(_ToolBar2.default, { ref: 'toolbar', defaultSearch: this.props.options.defaultSearch, clearSearch: this.props.options.clearSearch, searchDelayTime: this.props.options.searchDelayTime, enableInsert: insertRow, enableDelete: deleteRow, enableSearch: search, enableExportCSV: this.props.exportCSV, enableShowOnlySelected: enableShowOnlySelected, columns: columns, searchPlaceholder: this.props.searchPlaceholder, exportCSVText: this.props.options.exportCSVText, insertText: this.props.options.insertText, deleteText: this.props.options.deleteText, saveText: this.props.options.saveText, closeText: this.props.options.closeText, ignoreEditable: this.props.options.ignoreEditable, onAddRow: this.handleAddRow, onDropRow: this.handleDropRow, onSearch: this.handleSearch, onExportCSV: this.handleExportCSV, onShowOnlySelected: this.handleShowOnlySelected }) ); } else { return null; } } }, { key: 'renderTableFilter', value: function renderTableFilter(columns) { if (this.props.columnFilter) { return _react2.default.createElement(_TableFilter2.default, { columns: columns, rowSelectType: this.props.selectRow.mode, onFilter: this.handleFilterData }); } else { return null; } } }, { key: '___scrollTop__REACT_HOT_LOADER__', value: function ___scrollTop__REACT_HOT_LOADER__() { var scrollTop = this.props.scrollTop; if (scrollTop === _Const2.default.SCROLL_TOP) { this.refs.body.refs.container.scrollTop = 0; } else if (scrollTop === _Const2.default.SCROLL_BOTTOM) { this.refs.body.refs.container.scrollTop = this.refs.body.refs.container.scrollHeight; } else if (typeof scrollTop === 'number' && !isNaN(scrollTop)) { this.refs.body.refs.container.scrollTop = scrollTop; } } }, { key: '___scrollHeader__REACT_HOT_LOADER__', value: function ___scrollHeader__REACT_HOT_LOADER__(e) { this.refs.header.refs.container.scrollLeft = e.currentTarget.scrollLeft; } }, { key: '_adjustTable', value: function _adjustTable() { if (!this.props.printable) { this._adjustHeaderWidth(); } this._adjustHeight(); } }, { key: '_adjustHeaderWidth', value: function _adjustHeaderWidth() { var header = this.refs.header.getHeaderColGrouop(); var headerContainer = this.refs.header.refs.container; var tbody = this.refs.body.refs.tbody; var firstRow = tbody.childNodes[0]; var isScroll = headerContainer.offsetWidth !== tbody.parentNode.offsetWidth; var scrollBarWidth = isScroll ? _util2.default.getScrollBarWidth() : 0; if (firstRow && this.store.getDataNum()) { var cells = firstRow.childNodes; for (var i = 0; i < cells.length; i++) { var cell = cells[i]; var computedStyle = window.getComputedStyle(cell); var width = parseFloat(computedStyle.width.replace('px', '')); if (this.isIE) { var paddingLeftWidth = parseFloat(computedStyle.paddingLeft.replace('px', '')); var paddingRightWidth = parseFloat(computedStyle.paddingRight.replace('px', '')); var borderRightWidth = parseFloat(computedStyle.borderRightWidth.replace('px', '')); var borderLeftWidth = parseFloat(computedStyle.borderLeftWidth.replace('px', '')); width = width + paddingLeftWidth + paddingRightWidth + borderRightWidth + borderLeftWidth; } var lastPadding = cells.length - 1 === i ? scrollBarWidth : 0; if (width <= 0) { width = 120; cell.width = width + lastPadding + 'px'; } var result = width + lastPadding + 'px'; header[i].style.width = result; header[i].style.minWidth = result; } } else { _react2.default.Children.forEach(this.props.children, function (child, i) { if (child.props.width) { header[i].style.width = child.props.width + 'px'; header[i].style.minWidth = child.props.width + 'px'; } }); } } }, { key: '_adjustHeight', value: function _adjustHeight() { var height = this.props.height; var maxHeight = this.props.maxHeight; if (typeof height === 'number' && !isNaN(height) || height.indexOf('%') === -1) { this.refs.body.refs.container.style.height = parseFloat(height, 10) - this.refs.header.refs.container.offsetHeight + 'px'; } if (maxHeight) { maxHeight = typeof maxHeight === 'number' ? maxHeight : parseInt(maxHeight.replace('px', ''), 10); this.refs.body.refs.container.style.maxHeight = maxHeight - this.refs.header.refs.container.offsetHeight + 'px'; } } }, { key: '_handleAfterAddingRow', value: function _handleAfterAddingRow(newObj, atTheBeginning) { var result = void 0; if (this.props.pagination) { // if pagination is enabled and inserting row at the end, // change page to the last page // otherwise, change it to the first page var sizePerPage = this.state.sizePerPage; if (atTheBeginning) { var firstPage = this.props.options.pageStartIndex || _Const2.default.PAGE_START_INDEX; result = this.store.page(firstPage, sizePerPage).get(); this.setState({ data: result, currPage: firstPage }); } else { var currLastPage = Math.ceil(this.store.getDataNum() / sizePerPage); result = this.store.page(currLastPage, sizePerPage).get(); this.setState({ data: result, currPage: currLastPage }); } } else { result = this.store.get(); this.setState({ data: result }); } if (this.props.options.afterInsertRow) { this.props.options.afterInsertRow(newObj); } } }]); return BootstrapTable; }(_react.Component); BootstrapTable.propTypes = { keyField: _react.PropTypes.string, height: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]), maxHeight: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]), data: _react.PropTypes.oneOfType([_react.PropTypes.array, _react.PropTypes.object]), remote: _react.PropTypes.bool, // remote data, default is false scrollTop: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]), striped: _react.PropTypes.bool, bordered: _react.PropTypes.bool, hover: _react.PropTypes.bool, condensed: _react.PropTypes.bool, pagination: _react.PropTypes.bool, printable: _react.PropTypes.bool, searchPlaceholder: _react.PropTypes.string, selectRow: _react.PropTypes.shape({ mode: _react.PropTypes.oneOf([_Const2.default.ROW_SELECT_NONE, _Const2.default.ROW_SELECT_SINGLE, _Const2.default.ROW_SELECT_MULTI]), customComponent: _react.PropTypes.func, bgColor: _react.PropTypes.string, selected: _react.PropTypes.array, onSelect: _react.PropTypes.func, onSelectAll: _react.PropTypes.func, clickToSelect: _react.PropTypes.bool, hideSelectColumn: _react.PropTypes.bool, clickToSelectAndEditCell: _react.PropTypes.bool, clickToExpand: _react.PropTypes.bool, showOnlySelected: _react.PropTypes.bool, unselectable: _react.PropTypes.array }), cellEdit: _react.PropTypes.shape({ mode: _react.PropTypes.string, blurToSave: _react.PropTypes.bool, beforeSaveCell: _react.PropTypes.func, afterSaveCell: _react.PropTypes.func, nonEditableRows: _react.PropTypes.func }), insertRow: _react.PropTypes.bool, deleteRow: _react.PropTypes.bool, search: _react.PropTypes.bool, columnFilter: _react.PropTypes.bool, trClassName: _react.PropTypes.any, tableStyle: _react.PropTypes.object, containerStyle: _react.PropTypes.object, headerStyle: _react.PropTypes.object, bodyStyle: _react.PropTypes.object, containerClass: _react.PropTypes.string, tableContainerClass: _react.PropTypes.string, headerContainerClass: _react.PropTypes.string, bodyContainerClass: _react.PropTypes.string, tableHeaderClass: _react.PropTypes.string, tableBodyClass: _react.PropTypes.string, options: _react.PropTypes.shape({ clearSearch: _react.PropTypes.bool, sortName: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.array]), sortOrder: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.array]), defaultSortName: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.array]), defaultSortOrder: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.array]), sortIndicator: _react.PropTypes.bool, afterTableComplete: _react.PropTypes.func, afterDeleteRow: _react.PropTypes.func, afterInsertRow: _react.PropTypes.func, afterSearch: _react.PropTypes.func, afterColumnFilter: _react.PropTypes.func, onRowClick: _react.PropTypes.func, onRowDoubleClick: _react.PropTypes.func, page: _react.PropTypes.number, pageStartIndex: _react.PropTypes.number, paginationShowsTotal: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.func]), sizePerPageList: _react.PropTypes.array, sizePerPage: _react.PropTypes.number, paginationSize: _react.PropTypes.number, hideSizePerPage: _react.PropTypes.bool, onSortChange: _react.PropTypes.func, onPageChange: _react.PropTypes.func, onSizePerPageList: _react.PropTypes.func, onFilterChange: _react2.default.PropTypes.func, onSearchChange: _react2.default.PropTypes.func, onAddRow: _react2.default.PropTypes.func, onExportToCSV: _react2.default.PropTypes.func, onCellEdit: _react2.default.PropTypes.func, noDataText: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]), withoutNoDataText: _react2.default.PropTypes.bool, handleConfirmDeleteRow: _react.PropTypes.func, prePage: _react.PropTypes.string, nextPage: _react.PropTypes.string, firstPage: _react.PropTypes.string, lastPage: _react.PropTypes.string, searchDelayTime: _react.PropTypes.number, exportCSVText: _react.PropTypes.string, insertText: _react.PropTypes.string, deleteText: _react.PropTypes.string, saveText: _react.PropTypes.string, closeText: _react.PropTypes.string, ignoreEditable: _react.PropTypes.bool, defaultSearch: _react.PropTypes.string, expandRowBgColor: _react.PropTypes.string, expandBy: _react.PropTypes.string, expanding: _react.PropTypes.array, beforeShowError: _react.PropTypes.func }), fetchInfo: _react.PropTypes.shape({ dataTotalSize: _react.PropTypes.number }), exportCSV: _react.PropTypes.bool, csvFileName: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.func]), ignoreSinglePage: _react.PropTypes.bool, expandableRow: _react.PropTypes.func, expandComponent: _react.PropTypes.func }; BootstrapTable.defaultProps = { scrollTop: undefined, expandComponent: undefined, expandableRow: undefined, height: '100%', maxHeight: undefined, striped: false, bordered: true, hover: false, condensed: false, pagination: false, printable: false, searchPlaceholder: undefined, selectRow: { mode: _Const2.default.ROW_SELECT_NONE, bgColor: _Const2.default.ROW_SELECT_BG_COLOR, selected: [], onSelect: undefined, onSelectAll: undefined, clickToSelect: false, hideSelectColumn: false, clickToSelectAndEditCell: false, clickToExpand: false, showOnlySelected: false, unselectable: [], customComponent: undefined }, cellEdit: { mode: _Const2.default.CELL_EDIT_NONE, blurToSave: false, beforeSaveCell: undefined, afterSaveCell: undefined, nonEditableRows: undefined }, insertRow: false, deleteRow: false, search: false, multiColumnSearch: false, multiColumnSort: 1, columnFilter: false, trClassName: '', tableStyle: undefined, containerStyle: undefined, headerStyle: undefined, bodyStyle: undefined, containerClass: null, tableContainerClass: null, headerContainerClass: null, bodyContainerClass: null, tableHeaderClass: null, tableBodyClass: null, options: { clearSearch: false, sortName: undefined, sortOrder: undefined, defaultSortName: undefined, defaultSortOrder: undefined, sortIndicator: true, afterTableComplete: undefined, afterDeleteRow: undefined, afterInsertRow: undefined, afterSearch: undefined, afterColumnFilter: undefined, onRowClick: undefined, onRowDoubleClick: undefined, onMouseLeave: undefined, onMouseEnter: undefined, onRowMouseOut: undefined, onRowMouseOver: undefined, page: undefined, paginationShowsTotal: false, sizePerPageList: _Const2.default.SIZE_PER_PAGE_LIST, sizePerPage: undefined, paginationSize: _Const2.default.PAGINATION_SIZE, hideSizePerPage: false, onSizePerPageList: undefined, noDataText: undefined, withoutNoDataText: false, handleConfirmDeleteRow: undefined, prePage: _Const2.default.PRE_PAGE, nextPage: _Const2.default.NEXT_PAGE, firstPage: _Const2.default.FIRST_PAGE, lastPage: _Const2.default.LAST_PAGE, pageStartIndex: undefined, searchDelayTime: undefined, exportCSVText: _Const2.default.EXPORT_CSV_TEXT, insertText: _Const2.default.INSERT_BTN_TEXT, deleteText: _Const2.default.DELETE_BTN_TEXT, saveText: _Const2.default.SAVE_BTN_TEXT, closeText: _Const2.default.CLOSE_BTN_TEXT, ignoreEditable: false, defaultSearch: '', expandRowBgColor: undefined, expandBy: _Const2.default.EXPAND_BY_ROW, expanding: [], beforeShowError: undefined }, fetchInfo: { dataTotalSize: 0 }, exportCSV: false, csvFileName: 'spreadsheet.csv', ignoreSinglePage: false }; var _default = BootstrapTable; exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(BootstrapTable, 'BootstrapTable', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/BootstrapTable.js'); __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/BootstrapTable.js'); }(); ; /***/ }, /* 2 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_2__; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { classes.push(classNames.apply(null, arg)); } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } else if (true) { // register as 'classnames', consistent with npm package name !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { window.classNames = classNames; } }()); /***/ }, /* 4 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _default = { SORT_DESC: 'desc', SORT_ASC: 'asc', SIZE_PER_PAGE: 10, NEXT_PAGE: '>', LAST_PAGE: '>>', PRE_PAGE: '<', FIRST_PAGE: '<<', PAGE_START_INDEX: 1, ROW_SELECT_BG_COLOR: '', ROW_SELECT_NONE: 'none', ROW_SELECT_SINGLE: 'radio', ROW_SELECT_MULTI: 'checkbox', CELL_EDIT_NONE: 'none', CELL_EDIT_CLICK: 'click', CELL_EDIT_DBCLICK: 'dbclick', SIZE_PER_PAGE_LIST: [10, 25, 30, 50], PAGINATION_SIZE: 5, NO_DATA_TEXT: 'There is no data to display', SHOW_ONLY_SELECT: 'Show Selected Only', SHOW_ALL: 'Show All', EXPORT_CSV_TEXT: 'Export to CSV', INSERT_BTN_TEXT: 'New', DELETE_BTN_TEXT: 'Delete', SAVE_BTN_TEXT: 'Save', CLOSE_BTN_TEXT: 'Close', FILTER_DELAY: 500, SCROLL_TOP: 'Top', SCROLL_BOTTOM: 'Bottom', FILTER_TYPE: { TEXT: 'TextFilter', REGEX: 'RegexFilter', SELECT: 'SelectFilter', NUMBER: 'NumberFilter', DATE: 'DateFilter', CUSTOM: 'CustomFilter' }, FILTER_COND_EQ: 'eq', FILTER_COND_LIKE: 'like', EXPAND_BY_ROW: 'row', EXPAND_BY_COL: 'column', CANCEL_TOASTR: 'Pressed ESC can cancel' }; exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/Const.js'); }(); ; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(6); var _reactDom2 = _interopRequireDefault(_reactDom); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var _SelectRowHeaderColumn = __webpack_require__(7); var _SelectRowHeaderColumn2 = _interopRequireDefault(_SelectRowHeaderColumn); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Checkbox = function (_Component) { _inherits(Checkbox, _Component); function Checkbox() { _classCallCheck(this, Checkbox); return _possibleConstructorReturn(this, (Checkbox.__proto__ || Object.getPrototypeOf(Checkbox)).apply(this, arguments)); } _createClass(Checkbox, [{ key: 'componentDidMount', value: function componentDidMount() { this.update(this.props.checked); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { this.update(props.checked); } }, { key: 'update', value: function update(checked) { _reactDom2.default.findDOMNode(this).indeterminate = checked === 'indeterminate'; } }, { key: 'render', value: function render() { return _react2.default.createElement('input', { className: 'react-bs-select-all', type: 'checkbox', checked: this.props.checked, onChange: this.props.onChange }); } }]); return Checkbox; }(_react.Component); function getSortOrder(sortList, field, enableSort) { if (!enableSort) return undefined; var result = sortList.filter(function (sortObj) { return sortObj.sortField === field; }); if (result.length > 0) { return result[0].order; } else { return undefined; } } var TableHeader = function (_Component2) { _inherits(TableHeader, _Component2); function TableHeader() { var _ref; var _temp, _this2, _ret; _classCallCheck(this, TableHeader); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this2 = _possibleConstructorReturn(this, (_ref = TableHeader.__proto__ || Object.getPrototypeOf(TableHeader)).call.apply(_ref, [this].concat(args))), _this2), _this2.getHeaderColGrouop = function () { var _this3; return (_this3 = _this2).__getHeaderColGrouop__REACT_HOT_LOADER__.apply(_this3, arguments); }, _temp), _possibleConstructorReturn(_this2, _ret); } _createClass(TableHeader, [{ key: 'render', value: function render() { var containerClasses = (0, _classnames2.default)('react-bs-container-header', 'table-header-wrapper', this.props.headerContainerClass); var tableClasses = (0, _classnames2.default)('table', 'table-hover', { 'table-bordered': this.props.bordered, 'table-condensed': this.props.condensed }, this.props.tableHeaderClass); var rowCount = Math.max.apply(Math, _toConsumableArray(_react2.default.Children.map(this.props.children, function (elm) { return elm.props.row ? Number(elm.props.row) : 0; }))); var rows = []; var rowKey = 0; if (!this.props.hideSelectColumn) { rows[0] = [this.renderSelectRowHeader(rowCount + 1, rowKey++)]; } var _props = this.props, sortIndicator = _props.sortIndicator, sortList = _props.sortList, onSort = _props.onSort; _react2.default.Children.forEach(this.props.children, function (elm) { var _elm$props = elm.props, dataField = _elm$props.dataField, dataSort = _elm$props.dataSort; var sort = getSortOrder(sortList, dataField, dataSort); var rowIndex = elm.props.row ? Number(elm.props.row) : 0; var rowSpan = elm.props.rowSpan ? Number(elm.props.rowSpan) : 1; if (rows[rowIndex] === undefined) { rows[rowIndex] = []; } if (rowSpan + rowIndex === rowCount + 1) { rows[rowIndex].push(_react2.default.cloneElement(elm, { key: rowKey++, onSort: onSort, sort: sort, sortIndicator: sortIndicator, isOnlyHead: false })); } else { rows[rowIndex].push(_react2.default.cloneElement(elm, { key: rowKey++, isOnlyHead: true })); } }); var trs = rows.map(function (row, indexRow) { return _react2.default.createElement( 'tr', { key: indexRow }, row ); }); return _react2.default.createElement( 'div', { ref: 'container', className: containerClasses, style: this.props.style }, _react2.default.createElement( 'table', { className: tableClasses }, _react2.default.cloneElement(this.props.colGroups, { ref: 'headerGrp' }), _react2.default.createElement( 'thead', { ref: 'header' }, trs ) ) ); } }, { key: '__getHeaderColGrouop__REACT_HOT_LOADER__', value: function __getHeaderColGrouop__REACT_HOT_LOADER__() { return this.refs.headerGrp.childNodes; } }, { key: 'renderSelectRowHeader', value: function renderSelectRowHeader(rowCount, rowKey) { if (this.props.customComponent) { var CustomComponent = this.props.customComponent; return _react2.default.createElement( _SelectRowHeaderColumn2.default, { key: rowKey, rowCount: rowCount }, _react2.default.createElement(CustomComponent, { type: 'checkbox', checked: this.props.isSelectAll, indeterminate: this.props.isSelectAll === 'indeterminate', disabled: false, onChange: this.props.onSelectAllRow, rowIndex: 'Header' }) ); } else if (this.props.rowSelectType === _Const2.default.ROW_SELECT_SINGLE) { return _react2.default.createElement(_SelectRowHeaderColumn2.default, { key: rowKey, rowCount: rowCount }); } else if (this.props.rowSelectType === _Const2.default.ROW_SELECT_MULTI) { return _react2.default.createElement( _SelectRowHeaderColumn2.default, { key: rowKey, rowCount: rowCount }, _react2.default.createElement(Checkbox, { onChange: this.props.onSelectAllRow, checked: this.props.isSelectAll }) ); } else { return null; } } }]); return TableHeader; }(_react.Component); TableHeader.propTypes = { headerContainerClass: _react.PropTypes.string, tableHeaderClass: _react.PropTypes.string, style: _react.PropTypes.object, rowSelectType: _react.PropTypes.string, onSort: _react.PropTypes.func, onSelectAllRow: _react.PropTypes.func, sortList: _react.PropTypes.array, hideSelectColumn: _react.PropTypes.bool, bordered: _react.PropTypes.bool, condensed: _react.PropTypes.bool, isFiltered: _react.PropTypes.bool, isSelectAll: _react.PropTypes.oneOf([true, 'indeterminate', false]), sortIndicator: _react.PropTypes.bool, customComponent: _react.PropTypes.func, colGroups: _react.PropTypes.element }; var _default = TableHeader; exports.default = _default; ; var _temp2 = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(Checkbox, 'Checkbox', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableHeader.js'); __REACT_HOT_LOADER__.register(getSortOrder, 'getSortOrder', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableHeader.js'); __REACT_HOT_LOADER__.register(TableHeader, 'TableHeader', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableHeader.js'); __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableHeader.js'); }(); ; /***/ }, /* 6 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_6__; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var SelectRowHeaderColumn = function (_Component) { _inherits(SelectRowHeaderColumn, _Component); function SelectRowHeaderColumn() { _classCallCheck(this, SelectRowHeaderColumn); return _possibleConstructorReturn(this, (SelectRowHeaderColumn.__proto__ || Object.getPrototypeOf(SelectRowHeaderColumn)).apply(this, arguments)); } _createClass(SelectRowHeaderColumn, [{ key: 'render', value: function render() { return _react2.default.createElement( 'th', { rowSpan: this.props.rowCount, style: { textAlign: 'center' }, 'data-is-only-head': false }, this.props.children ); } }]); return SelectRowHeaderColumn; }(_react.Component); SelectRowHeaderColumn.propTypes = { children: _react.PropTypes.node, rowCount: _react.PropTypes.number }; var _default = SelectRowHeaderColumn; exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(SelectRowHeaderColumn, 'SelectRowHeaderColumn', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/SelectRowHeaderColumn.js'); __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/SelectRowHeaderColumn.js'); }(); ; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _util = __webpack_require__(9); var _util2 = _interopRequireDefault(_util); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var _TableRow = __webpack_require__(10); var _TableRow2 = _interopRequireDefault(_TableRow); var _TableColumn = __webpack_require__(11); var _TableColumn2 = _interopRequireDefault(_TableColumn); var _TableEditColumn = __webpack_require__(12); var _TableEditColumn2 = _interopRequireDefault(_TableEditColumn); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var _ExpandComponent = __webpack_require__(179); var _ExpandComponent2 = _interopRequireDefault(_ExpandComponent); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var isFun = function isFun(obj) { return obj && typeof obj === 'function'; }; var TableBody = function (_Component) { _inherits(TableBody, _Component); function TableBody(props) { _classCallCheck(this, TableBody); var _this = _possibleConstructorReturn(this, (TableBody.__proto__ || Object.getPrototypeOf(TableBody)).call(this, props)); _this.handleRowMouseOut = function () { return _this.__handleRowMouseOut__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleRowMouseOver = function () { return _this.__handleRowMouseOver__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleRowClick = function () { return _this.__handleRowClick__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleRowDoubleClick = function () { return _this.__handleRowDoubleClick__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleSelectRow = function () { return _this.__handleSelectRow__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleSelectRowColumChange = function () { return _this.__handleSelectRowColumChange__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleClickCell = function () { return _this.__handleClickCell__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleEditCell = function () { return _this.__handleEditCell__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleCompleteEditCell = function () { return _this.__handleCompleteEditCell__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.state = { currEditCell: null }; return _this; } _createClass(TableBody, [{ key: 'render', value: function render() { var _props = this.props, cellEdit = _props.cellEdit, beforeShowError = _props.beforeShowError; var tableClasses = (0, _classnames2.default)('table', { 'table-striped': this.props.striped, 'table-bordered': this.props.bordered, 'table-hover': this.props.hover, 'table-condensed': this.props.condensed }, this.props.tableBodyClass); var noneditableRows = cellEdit.nonEditableRows && cellEdit.nonEditableRows() || []; var unselectable = this.props.selectRow.unselectable || []; var isSelectRowDefined = this._isSelectRowDefined(); var tableHeader = _util2.default.renderColGroup(this.props.columns, this.props.selectRow, 'header'); var inputType = this.props.selectRow.mode === _Const2.default.ROW_SELECT_SINGLE ? 'radio' : 'checkbox'; var CustomComponent = this.props.selectRow.customComponent; var expandColSpan = this.props.columns.filter(function (col) { return !col.hidden; }).length; if (isSelectRowDefined && !this.props.selectRow.hideSelectColumn) { expandColSpan += 1; } var tableRows = this.props.data.map(function (data, r) { var tableColumns = this.props.columns.map(function (column, i) { var fieldValue = data[column.name]; if (column.name !== this.props.keyField && // Key field can't be edit column.editable && // column is editable? default is true, user can set it false this.state.currEditCell !== null && this.state.currEditCell.rid === r && this.state.currEditCell.cid === i && noneditableRows.indexOf(data[this.props.keyField]) === -1) { var editable = column.editable; var format = column.format ? function (value) { return column.format(value, data, column.formatExtraData, r).replace(/<.*?>/g, ''); } : false; if (isFun(column.editable)) { editable = column.editable(fieldValue, data, r, i); } return _react2.default.createElement(_TableEditColumn2.default, { completeEdit: this.handleCompleteEditCell // add by bluespring for column editor customize , editable: editable, customEditor: column.customEditor, format: column.format ? format : false, key: i, blurToSave: cellEdit.blurToSave, rowIndex: r, colIndex: i, row: data, fieldValue: fieldValue, className: column.editClassName, invalidColumnClassName: column.invalidEditColumnClassName, beforeShowError: beforeShowError }); } else { // add by bluespring for className customize var columnChild = fieldValue && fieldValue.toString(); var columnTitle = null; var tdClassName = column.className; if (isFun(column.className)) { tdClassName = column.className(fieldValue, data, r, i); } if (typeof column.format !== 'undefined') { var formattedValue = column.format(fieldValue, data, column.formatExtraData, r); if (!_react2.default.isValidElement(formattedValue)) { columnChild = _react2.default.createElement('div', { dangerouslySetInnerHTML: { __html: formattedValue } }); } else { columnChild = formattedValue; columnTitle = column.columnTitle && formattedValue ? formattedValue.toString() : null; } } else { columnTitle = column.columnTitle && fieldValue ? fieldValue.toString() : null; } return _react2.default.createElement( _TableColumn2.default, { key: i, rIndex: r, dataAlign: column.align, className: tdClassName, columnTitle: columnTitle, cellEdit: cellEdit, hidden: column.hidden, onEdit: this.handleEditCell, width: column.width, onClick: this.handleClickCell, attrs: column.attrs }, columnChild ); } }, this); var key = data[this.props.keyField]; var disable = unselectable.indexOf(key) !== -1; var selected = this.props.selectedRowKeys.indexOf(key) !== -1; var selectRowColumn = isSelectRowDefined && !this.props.selectRow.hideSelectColumn ? this.renderSelectRowColumn(selected, inputType, disable, CustomComponent, r) : null; // add by bluespring for className customize var trClassName = this.props.trClassName; if (isFun(this.props.trClassName)) { trClassName = this.props.trClassName(data, r); } var result = [_react2.default.createElement( _TableRow2.default, { isSelected: selected, key: key, className: trClassName, index: r, selectRow: isSelectRowDefined ? this.props.selectRow : undefined, enableCellEdit: cellEdit.mode !== _Const2.default.CELL_EDIT_NONE, onRowClick: this.handleRowClick, onRowDoubleClick: this.handleRowDoubleClick, onRowMouseOver: this.handleRowMouseOver, onRowMouseOut: this.handleRowMouseOut, onSelectRow: this.handleSelectRow, onExpandRow: this.handleClickCell, unselectableRow: disable }, selectRowColumn, tableColumns )]; if (this.props.expandableRow && this.props.expandableRow(data)) { result.push(_react2.default.createElement( _ExpandComponent2.default, { className: trClassName, bgColor: this.props.expandRowBgColor || this.props.selectRow.bgColor || undefined, hidden: !(this.props.expanding.indexOf(key) > -1), colSpan: expandColSpan, width: "100%" }, this.props.expandComponent(data) )); } return result; }, this); if (tableRows.length === 0 && !this.props.withoutNoDataText) { tableRows.push(_react2.default.createElement( _TableRow2.default, { key: '##table-empty##' }, _react2.default.createElement( 'td', { 'data-toggle': 'collapse', colSpan: this.props.columns.length + (isSelectRowDefined ? 1 : 0), className: 'react-bs-table-no-data' }, this.props.noDataText || _Const2.default.NO_DATA_TEXT ) )); } return _react2.default.createElement( 'div', { ref: 'container', className: (0, _classnames2.default)('react-bs-container-body', this.props.bodyContainerClass), style: this.props.style }, _react2.default.createElement( 'table', { className: tableClasses }, _react2.default.cloneElement(tableHeader, { ref: 'header' }), _react2.default.createElement( 'tbody', { ref: 'tbody' }, tableRows ) ) ); } }, { key: '__handleRowMouseOut__REACT_HOT_LOADER__', value: function __handleRowMouseOut__REACT_HOT_LOADER__(rowIndex, event) { var targetRow = this.props.data[rowIndex]; this.props.onRowMouseOut(targetRow, event); } }, { key: '__handleRowMouseOver__REACT_HOT_LOADER__', value: function __handleRowMouseOver__REACT_HOT_LOADER__(rowIndex, event) { var targetRow = this.props.data[rowIndex]; this.props.onRowMouseOver(targetRow, event); } }, { key: '__handleRowClick__REACT_HOT_LOADER__', value: function __handleRowClick__REACT_HOT_LOADER__(rowIndex) { this.props.onRowClick(this.props.data[rowIndex - 1]); } }, { key: '__handleRowDoubleClick__REACT_HOT_LOADER__', value: function __handleRowDoubleClick__REACT_HOT_LOADER__(rowIndex) { var onRowDoubleClick = this.props.onRowDoubleClick; var targetRow = this.props.data[rowIndex]; onRowDoubleClick(targetRow); } }, { key: '__handleSelectRow__REACT_HOT_LOADER__', value: function __handleSelectRow__REACT_HOT_LOADER__(rowIndex, isSelected, e) { var selectedRow = void 0; var _props2 = this.props, data = _props2.data, onSelectRow = _props2.onSelectRow; data.forEach(function (row, i) { if (i === rowIndex - 1) { selectedRow = row; return false; } }); onSelectRow(selectedRow, isSelected, e); } }, { key: '__handleSelectRowColumChange__REACT_HOT_LOADER__', value: function __handleSelectRowColumChange__REACT_HOT_LOADER__(e, rowIndex) { if (!this.props.selectRow.clickToSelect || !this.props.selectRow.clickToSelectAndEditCell) { this.handleSelectRow(rowIndex + 1, e.currentTarget.checked, e); } } }, { key: '__handleClickCell__REACT_HOT_LOADER__', value: function __handleClickCell__REACT_HOT_LOADER__(rowIndex) { var _this2 = this; var columnIndex = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1; var _props3 = this.props, columns = _props3.columns, keyField = _props3.keyField, expandBy = _props3.expandBy, expandableRow = _props3.expandableRow, clickToExpand = _props3.selectRow.clickToExpand; var selectRowAndExpand = this._isSelectRowDefined() && !clickToExpand ? false : true; columnIndex = this._isSelectRowDefined() ? columnIndex - 1 : columnIndex; if (expandableRow && selectRowAndExpand && (expandBy === _Const2.default.EXPAND_BY_ROW || columnIndex > 0 && expandBy === _Const2.default.EXPAND_BY_COL && columns[columnIndex].expandable)) { (function () { var rowKey = _this2.props.data[rowIndex - 1][keyField]; var expanding = _this2.props.expanding; if (expanding.indexOf(rowKey) > -1) { expanding = expanding.filter(function (k) { return k !== rowKey; }); } else { expanding.push(rowKey); } _this2.props.onExpand(expanding); })(); } } }, { key: '__handleEditCell__REACT_HOT_LOADER__', value: function __handleEditCell__REACT_HOT_LOADER__(rowIndex, columnIndex, e) { if (this._isSelectRowDefined()) { columnIndex--; if (this.props.selectRow.hideSelectColumn) columnIndex++; } rowIndex--; var stateObj = { currEditCell: { rid: rowIndex, cid: columnIndex } }; if (this.props.selectRow.clickToSelectAndEditCell && this.props.cellEdit.mode !== _Const2.default.CELL_EDIT_DBCLICK) { var selected = this.props.selectedRowKeys.indexOf(this.props.data[rowIndex][this.props.keyField]) !== -1; this.handleSelectRow(rowIndex + 1, !selected, e); } this.setState(stateObj); } }, { key: '__handleCompleteEditCell__REACT_HOT_LOADER__', value: function __handleCompleteEditCell__REACT_HOT_LOADER__(newVal, rowIndex, columnIndex) { this.setState({ currEditCell: null }); if (newVal !== null) { this.props.cellEdit.__onCompleteEdit__(newVal, rowIndex, columnIndex); } } }, { key: 'renderSelectRowColumn', value: function renderSelectRowColumn(selected, inputType, disabled) { var _this3 = this; var CustomComponent = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var rowIndex = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; return _react2.default.createElement( _TableColumn2.default, { dataAlign: 'center' }, CustomComponent ? _react2.default.createElement(CustomComponent, { type: inputType, checked: selected, disabled: disabled, rowIndex: rowIndex, onChange: function onChange(e) { return _this3.handleSelectRowColumChange(e, rowIndex); } }) : _react2.default.createElement('input', { type: inputType, checked: selected, disabled: disabled, onChange: function onChange(e) { return _this3.handleSelectRowColumChange(e, rowIndex); } }) ); } }, { key: '_isSelectRowDefined', value: function _isSelectRowDefined() { return this.props.selectRow.mode === _Const2.default.ROW_SELECT_SINGLE || this.props.selectRow.mode === _Const2.default.ROW_SELECT_MULTI; } }]); return TableBody; }(_react.Component); TableBody.propTypes = { data: _react.PropTypes.array, columns: _react.PropTypes.array, striped: _react.PropTypes.bool, bordered: _react.PropTypes.bool, hover: _react.PropTypes.bool, condensed: _react.PropTypes.bool, keyField: _react.PropTypes.string, selectedRowKeys: _react.PropTypes.array, onRowClick: _react.PropTypes.func, onRowDoubleClick: _react.PropTypes.func, onSelectRow: _react.PropTypes.func, noDataText: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]), withoutNoDataText: _react.PropTypes.bool, style: _react.PropTypes.object, tableBodyClass: _react.PropTypes.string, bodyContainerClass: _react.PropTypes.string, expandableRow: _react.PropTypes.func, expandComponent: _react.PropTypes.func, expandRowBgColor: _react.PropTypes.string, expandBy: _react.PropTypes.string, expanding: _react.PropTypes.array, onExpand: _react.PropTypes.func, beforeShowError: _react.PropTypes.func }; var _default = TableBody; exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(isFun, 'isFun', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableBody.js'); __REACT_HOT_LOADER__.register(TableBody, 'TableBody', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableBody.js'); __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableBody.js'); }(); ; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _default = { renderReactSortCaret: function renderReactSortCaret(order) { var orderClass = (0, _classnames2.default)('order', { 'dropup': order === _Const2.default.SORT_ASC }); return _react2.default.createElement( 'span', { className: orderClass }, _react2.default.createElement('span', { className: 'caret', style: { margin: '10px 5px' } }) ); }, getScrollBarWidth: function getScrollBarWidth() { var inner = document.createElement('p'); inner.style.width = '100%'; inner.style.height = '200px'; var outer = document.createElement('div'); outer.style.position = 'absolute'; outer.style.top = '0px'; outer.style.left = '0px'; outer.style.visibility = 'hidden'; outer.style.width = '200px'; outer.style.height = '150px'; outer.style.overflow = 'hidden'; outer.appendChild(inner); document.body.appendChild(outer); var w1 = inner.offsetWidth; outer.style.overflow = 'scroll'; var w2 = inner.offsetWidth; if (w1 === w2) w2 = outer.clientWidth; document.body.removeChild(outer); return w1 - w2; }, canUseDOM: function canUseDOM() { return typeof window !== 'undefined' && typeof window.document !== 'undefined'; }, renderColGroup: function renderColGroup(columns, selectRow) { var selectRowHeader = null; var isSelectRowDefined = selectRow.mode === _Const2.default.ROW_SELECT_SINGLE || selectRow.mode === _Const2.default.ROW_SELECT_MULTI; if (isSelectRowDefined) { var style = { width: 30, minWidth: 30 }; if (!selectRow.hideSelectColumn) { selectRowHeader = _react2.default.createElement('col', { style: style, key: -1 }); } } var theader = columns.map(function (column, i) { var style = { display: column.hidden ? 'none' : null }; if (column.width) { var width = parseInt(column.width, 10); style.width = width; /** add min-wdth to fix user assign column width not eq offsetWidth in large column table **/ style.minWidth = width; } return _react2.default.createElement('col', { style: style, key: i, className: column.className }); }); return _react2.default.createElement( 'colgroup', null, selectRowHeader, theader ); } }; /* eslint react/display-name: 0 */ exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/util.js'); }(); ; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var TableRow = function (_Component) { _inherits(TableRow, _Component); function TableRow(props) { _classCallCheck(this, TableRow); var _this = _possibleConstructorReturn(this, (TableRow.__proto__ || Object.getPrototypeOf(TableRow)).call(this, props)); _this.rowClick = function () { return _this.__rowClick__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.expandRow = function () { return _this.__expandRow__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.rowDoubleClick = function () { return _this.__rowDoubleClick__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.rowMouseOut = function () { return _this.__rowMouseOut__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.rowMouseOver = function () { return _this.__rowMouseOver__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.clickNum = 0; return _this; } _createClass(TableRow, [{ key: '__rowClick__REACT_HOT_LOADER__', value: function __rowClick__REACT_HOT_LOADER__(e) { var _this2 = this; if (e.target.tagName === 'TD') { (function () { var rowIndex = _this2.props.index + 1; var cellIndex = e.target.cellIndex; var _props = _this2.props, selectRow = _props.selectRow, unselectableRow = _props.unselectableRow, isSelected = _props.isSelected, onSelectRow = _props.onSelectRow, onExpandRow = _props.onExpandRow; if (selectRow) { if (selectRow.clickToSelect && !unselectableRow) { onSelectRow(rowIndex, !isSelected, e); } else if (selectRow.clickToSelectAndEditCell && !unselectableRow) { _this2.clickNum++; /** if clickToSelectAndEditCell is enabled, * there should be a delay to prevent a selection changed when * user dblick to edit cell on same row but different cell **/ setTimeout(function () { if (_this2.clickNum === 1) { onSelectRow(rowIndex, !isSelected, e); onExpandRow(rowIndex, cellIndex); } _this2.clickNum = 0; }, 200); } else { _this2.expandRow(rowIndex, cellIndex); } } else { _this2.expandRow(rowIndex, cellIndex); } if (_this2.props.onRowClick) _this2.props.onRowClick(rowIndex); })(); } } }, { key: '__expandRow__REACT_HOT_LOADER__', value: function __expandRow__REACT_HOT_LOADER__(rowIndex, cellIndex) { var _this3 = this; this.clickNum++; setTimeout(function () { if (_this3.clickNum === 1) { _this3.props.onExpandRow(rowIndex, cellIndex); } _this3.clickNum = 0; }, 200); } }, { key: '__rowDoubleClick__REACT_HOT_LOADER__', value: function __rowDoubleClick__REACT_HOT_LOADER__(e) { if (e.target.tagName !== 'INPUT' && e.target.tagName !== 'SELECT' && e.target.tagName !== 'TEXTAREA') { if (this.props.onRowDoubleClick) { this.props.onRowDoubleClick(this.props.index); } } } }, { key: '__rowMouseOut__REACT_HOT_LOADER__', value: function __rowMouseOut__REACT_HOT_LOADER__(e) { var rowIndex = this.props.index; if (this.props.onRowMouseOut) { this.props.onRowMouseOut(rowIndex, e); } } }, { key: '__rowMouseOver__REACT_HOT_LOADER__', value: function __rowMouseOver__REACT_HOT_LOADER__(e) { var rowIndex = this.props.index; if (this.props.onRowMouseOver) { this.props.onRowMouseOver(rowIndex, e); } } }, { key: 'render', value: function render() { this.clickNum = 0; var trCss = { style: { backgroundColor: this.props.isSelected ? this.props.selectRow.bgColor : null }, className: (0, _classnames2.default)(this.props.isSelected ? this.props.selectRow.className : null, this.props.className) }; if (this.props.selectRow && (this.props.selectRow.clickToSelect || this.props.selectRow.clickToSelectAndEditCell) || this.props.onRowClick || this.props.onRowDoubleClick) { return _react2.default.createElement( 'tr', _extends({}, trCss, { onMouseOver: this.rowMouseOver, onMouseOut: this.rowMouseOut, onClick: this.rowClick, onDoubleClick: this.rowDoubleClick }), this.props.children ); } else { return _react2.default.createElement( 'tr', trCss, this.props.children ); } } }]); return TableRow; }(_react.Component); TableRow.propTypes = { index: _react.PropTypes.number, isSelected: _react.PropTypes.bool, enableCellEdit: _react.PropTypes.bool, onRowClick: _react.PropTypes.func, onRowDoubleClick: _react.PropTypes.func, onSelectRow: _react.PropTypes.func, onExpandRow: _react.PropTypes.func, onRowMouseOut: _react.PropTypes.func, onRowMouseOver: _react.PropTypes.func, unselectableRow: _react.PropTypes.bool }; TableRow.defaultProps = { onRowClick: undefined, onRowDoubleClick: undefined }; var _default = TableRow; exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(TableRow, 'TableRow', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableRow.js'); __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableRow.js'); }(); ; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var TableColumn = function (_Component) { _inherits(TableColumn, _Component); function TableColumn(props) { _classCallCheck(this, TableColumn); var _this = _possibleConstructorReturn(this, (TableColumn.__proto__ || Object.getPrototypeOf(TableColumn)).call(this, props)); _this.handleCellEdit = function () { return _this.__handleCellEdit__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleCellClick = function () { return _this.__handleCellClick__REACT_HOT_LOADER__.apply(_this, arguments); }; return _this; } /* eslint no-unused-vars: [0, { "args": "after-used" }] */ _createClass(TableColumn, [{ key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps, nextState) { var children = this.props.children; var shouldUpdated = this.props.width !== nextProps.width || this.props.className !== nextProps.className || this.props.hidden !== nextProps.hidden || this.props.dataAlign !== nextProps.dataAlign || (typeof children === 'undefined' ? 'undefined' : _typeof(children)) !== _typeof(nextProps.children) || ('' + this.props.onEdit).toString() !== ('' + nextProps.onEdit).toString(); if (shouldUpdated) { return shouldUpdated; } if ((typeof children === 'undefined' ? 'undefined' : _typeof(children)) === 'object' && children !== null && children.props !== null) { if (children.props.type === 'checkbox' || children.props.type === 'radio') { shouldUpdated = shouldUpdated || children.props.type !== nextProps.children.props.type || children.props.checked !== nextProps.children.props.checked || children.props.disabled !== nextProps.children.props.disabled; } else { shouldUpdated = true; } } else { shouldUpdated = shouldUpdated || children !== nextProps.children; } if (shouldUpdated) { return shouldUpdated; } if (!(this.props.cellEdit && nextProps.cellEdit)) { return false; } else { return shouldUpdated || this.props.cellEdit.mode !== nextProps.cellEdit.mode; } } }, { key: '__handleCellEdit__REACT_HOT_LOADER__', value: function __handleCellEdit__REACT_HOT_LOADER__(e) { if (this.props.cellEdit.mode === _Const2.default.CELL_EDIT_DBCLICK) { if (document.selection && document.selection.empty) { document.selection.empty(); } else if (window.getSelection) { var sel = window.getSelection(); sel.removeAllRanges(); } } this.props.onEdit(this.props.rIndex + 1, e.currentTarget.cellIndex, e); if (this.props.cellEdit.mode !== _Const2.default.CELL_EDIT_DBCLICK) { this.props.onClick(this.props.rIndex + 1, e.currentTarget.cellIndex, e); } } }, { key: '__handleCellClick__REACT_HOT_LOADER__', value: function __handleCellClick__REACT_HOT_LOADER__(e) { var _props = this.props, onClick = _props.onClick, rIndex = _props.rIndex; if (onClick) { onClick(rIndex + 1, e.currentTarget.cellIndex, e); } } }, { key: 'render', value: function render() { var _props2 = this.props, children = _props2.children, columnTitle = _props2.columnTitle, className = _props2.className, dataAlign = _props2.dataAlign, hidden = _props2.hidden, cellEdit = _props2.cellEdit, attrs = _props2.attrs; var tdStyle = { textAlign: dataAlign, display: hidden ? 'none' : null }; var opts = {}; if (cellEdit) { if (cellEdit.mode === _Const2.default.CELL_EDIT_CLICK) { opts.onClick = this.handleCellEdit; } else if (cellEdit.mode === _Const2.default.CELL_EDIT_DBCLICK) { opts.onDoubleClick = this.handleCellEdit; } else { opts.onClick = this.handleCellClick; } } return _react2.default.createElement( 'td', _extends({ style: tdStyle, title: columnTitle, className: className }, opts, attrs), typeof children === 'boolean' ? children.toString() : children ); } }]); return TableColumn; }(_react.Component); TableColumn.propTypes = { rIndex: _react.PropTypes.number, dataAlign: _react.PropTypes.string, hidden: _react.PropTypes.bool, className: _react.PropTypes.string, columnTitle: _react.PropTypes.string, children: _react.PropTypes.node, onClick: _react.PropTypes.func, attrs: _react.PropTypes.object }; TableColumn.defaultProps = { dataAlign: 'left', hidden: false, className: '' }; var _default = TableColumn; exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(TableColumn, 'TableColumn', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableColumn.js'); __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableColumn.js'); }(); ; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Editor = __webpack_require__(13); var _Editor2 = _interopRequireDefault(_Editor); var _Notification = __webpack_require__(14); var _Notification2 = _interopRequireDefault(_Notification); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var TableEditColumn = function (_Component) { _inherits(TableEditColumn, _Component); function TableEditColumn(props) { _classCallCheck(this, TableEditColumn); var _this = _possibleConstructorReturn(this, (TableEditColumn.__proto__ || Object.getPrototypeOf(TableEditColumn)).call(this, props)); _this.handleKeyPress = function () { return _this.__handleKeyPress__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleBlur = function () { return _this.__handleBlur__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleCustomUpdate = function () { return _this.__handleCustomUpdate__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.timeouteClear = 0; var _this$props = _this.props, fieldValue = _this$props.fieldValue, row = _this$props.row, className = _this$props.className; _this.state = { shakeEditor: false, className: typeof className === 'function' ? className(fieldValue, row) : className }; return _this; } _createClass(TableEditColumn, [{ key: '__handleKeyPress__REACT_HOT_LOADER__', value: function __handleKeyPress__REACT_HOT_LOADER__(e) { if (e.keyCode === 13) { // Pressed ENTER var value = e.currentTarget.type === 'checkbox' ? this._getCheckBoxValue(e) : e.currentTarget.value; if (!this.validator(value)) { return; } this.props.completeEdit(value, this.props.rowIndex, this.props.colIndex); } else if (e.keyCode === 27) { this.props.completeEdit(null, this.props.rowIndex, this.props.colIndex); } else if (e.type === 'click' && !this.props.blurToSave) { // textarea click save button var _value = e.target.parentElement.firstChild.value; if (!this.validator(_value)) { return; } this.props.completeEdit(_value, this.props.rowIndex, this.props.colIndex); } } }, { key: '__handleBlur__REACT_HOT_LOADER__', value: function __handleBlur__REACT_HOT_LOADER__(e) { e.stopPropagation(); if (this.props.blurToSave) { var value = e.currentTarget.type === 'checkbox' ? this._getCheckBoxValue(e) : e.currentTarget.value; if (!this.validator(value)) { return; } this.props.completeEdit(value, this.props.rowIndex, this.props.colIndex); } } }, { key: '__handleCustomUpdate__REACT_HOT_LOADER__', // modified by iuculanop // BEGIN value: function __handleCustomUpdate__REACT_HOT_LOADER__(value) { this.props.completeEdit(value, this.props.rowIndex, this.props.colIndex); } }, { key: 'validator', value: function validator(value) { var ts = this; var valid = true; if (ts.props.editable.validator) { var input = ts.refs.inputRef; var checkVal = ts.props.editable.validator(value); var responseType = typeof checkVal === 'undefined' ? 'undefined' : _typeof(checkVal); if (responseType !== 'object' && checkVal !== true) { valid = false; var toastr = this.props.beforeShowError && this.props.beforeShowError('error', checkVal, _Const2.default.CANCEL_TOASTR); if (toastr) { ts.refs.notifier.notice('error', checkVal, _Const2.default.CANCEL_TOASTR); } } else if (responseType === 'object' && checkVal.isValid !== true) { valid = false; var _toastr = this.props.beforeShowError && this.props.beforeShowError(checkVal.notification.type, checkVal.notification.msg, checkVal.notification.title); if (_toastr) { ts.refs.notifier.notice(checkVal.notification.type, checkVal.notification.msg, checkVal.notification.title); } } if (!valid) { // animate input ts.clearTimeout(); var _props = this.props, invalidColumnClassName = _props.invalidColumnClassName, row = _props.row; var className = typeof invalidColumnClassName === 'function' ? invalidColumnClassName(value, row) : invalidColumnClassName; ts.setState({ shakeEditor: true, className: className }); ts.timeouteClear = setTimeout(function () { ts.setState({ shakeEditor: false }); }, 300); input.focus(); return valid; } } return valid; } // END }, { key: 'clearTimeout', value: function (_clearTimeout) { function clearTimeout() { return _clearTimeout.apply(this, arguments); } clearTimeout.toString = function () { return _clearTimeout.toString(); }; return clearTimeout; }(function () { if (this.timeouteClear !== 0) { clearTimeout(this.timeouteClear); this.timeouteClear = 0; } }) }, { key: 'componentDidMount', value: function componentDidMount() { this.refs.inputRef.focus(); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.clearTimeout(); } }, { key: 'render', value: function render() { var _props2 = this.props, editable = _props2.editable, format = _props2.format, customEditor = _props2.customEditor; var _state = this.state, shakeEditor = _state.shakeEditor, className = _state.className; var attr = { ref: 'inputRef', onKeyDown: this.handleKeyPress, onBlur: this.handleBlur }; var fieldValue = this.props.fieldValue; // put placeholder if exist editable.placeholder && (attr.placeholder = editable.placeholder); var editorClass = (0, _classnames2.default)({ 'animated': shakeEditor, 'shake': shakeEditor }); var cellEditor = void 0; if (customEditor) { var customEditorProps = _extends({ row: this.props.row }, attr, { defaultValue: fieldValue || '' }, customEditor.customEditorParameters); cellEditor = customEditor.getElement(this.handleCustomUpdate, customEditorProps); } else { fieldValue = fieldValue === 0 ? '0' : fieldValue; cellEditor = (0, _Editor2.default)(editable, attr, format, editorClass, fieldValue || ''); } return _react2.default.createElement( 'td', { ref: 'td', style: { position: 'relative' }, className: className }, cellEditor, _react2.default.createElement(_Notification2.default, { ref: 'notifier' }) ); } }, { key: '_getCheckBoxValue', value: function _getCheckBoxValue(e) { var value = ''; var values = e.currentTarget.value.split(':'); value = e.currentTarget.checked ? values[0] : values[1]; return value; } }]); return TableEditColumn; }(_react.Component); TableEditColumn.propTypes = { completeEdit: _react.PropTypes.func, rowIndex: _react.PropTypes.number, colIndex: _react.PropTypes.number, blurToSave: _react.PropTypes.bool, editable: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.object]), format: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.func]), row: _react.PropTypes.any, fieldValue: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.bool, _react.PropTypes.number, _react.PropTypes.array, _react.PropTypes.object]), className: _react.PropTypes.any, beforeShowError: _react.PropTypes.func }; var _default = TableEditColumn; exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(TableEditColumn, 'TableEditColumn', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableEditColumn.js'); __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableEditColumn.js'); }(); ; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var editor = function editor(editable, attr, format, editorClass, defaultValue, ignoreEditable) { if (editable === true || editable === false && ignoreEditable || typeof editable === 'string') { // simple declare var type = editable ? 'text' : editable; return _react2.default.createElement('input', _extends({}, attr, { type: type, defaultValue: defaultValue, className: (editorClass || '') + ' form-control editor edit-text' })); } else if (!editable) { var _type = editable ? 'text' : editable; return _react2.default.createElement('input', _extends({}, attr, { type: _type, defaultValue: defaultValue, disabled: 'disabled', className: (editorClass || '') + ' form-control editor edit-text' })); } else if (editable && (editable.type === undefined || editable.type === null || editable.type.trim() === '')) { var _type2 = editable ? 'text' : editable; return _react2.default.createElement('input', _extends({}, attr, { type: _type2, defaultValue: defaultValue, className: (editorClass || '') + ' form-control editor edit-text' })); } else if (editable.type) { // standard declare // put style if exist editable.style && (attr.style = editable.style); // put class if exist attr.className = (editorClass || '') + ' form-control editor edit-' + editable.type + (editable.className ? ' ' + editable.className : ''); if (editable.type === 'select') { // process select input var options = []; var values = editable.options.values; if (Array.isArray(values)) { (function () { // only can use arrray data for options var rowValue = void 0; options = values.map(function (d, i) { rowValue = format ? format(d) : d; return _react2.default.createElement( 'option', { key: 'option' + i, value: d }, rowValue ); }); })(); } return _react2.default.createElement( 'select', _extends({}, attr, { defaultValue: defaultValue }), options ); } else if (editable.type === 'textarea') { var _ret2 = function () { // process textarea input // put other if exist editable.cols && (attr.cols = editable.cols); editable.rows && (attr.rows = editable.rows); var saveBtn = void 0; var keyUpHandler = attr.onKeyDown; if (keyUpHandler) { attr.onKeyDown = function (e) { if (e.keyCode !== 13) { // not Pressed ENTER keyUpHandler(e); } }; saveBtn = _react2.default.createElement( 'button', { className: 'btn btn-info btn-xs textarea-save-btn', onClick: keyUpHandler }, 'save' ); } return { v: _react2.default.createElement( 'div', null, _react2.default.createElement('textarea', _extends({}, attr, { defaultValue: defaultValue })), saveBtn ) }; }(); if ((typeof _ret2 === 'undefined' ? 'undefined' : _typeof(_ret2)) === "object") return _ret2.v; } else if (editable.type === 'checkbox') { var _values = 'true:false'; if (editable.options && editable.options.values) { // values = editable.options.values.split(':'); _values = editable.options.values; } attr.className = attr.className.replace('form-control', ''); attr.className += ' checkbox pull-right'; var checked = defaultValue && defaultValue.toString() === _values.split(':')[0] ? true : false; return _react2.default.createElement('input', _extends({}, attr, { type: 'checkbox', value: _values, defaultChecked: checked })); } else if (editable.type === 'datetime') { return _react2.default.createElement('input', _extends({}, attr, { type: 'datetime-local', defaultValue: defaultValue })); } else { // process other input type. as password,url,email... return _react2.default.createElement('input', _extends({}, attr, { type: 'text', defaultValue: defaultValue })); } } // default return for other case of editable return _react2.default.createElement('input', _extends({}, attr, { type: 'text', className: (editorClass || '') + ' form-control editor edit-text' })); }; var _default = editor; exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(editor, 'editor', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/Editor.js'); __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/Editor.js'); }(); ; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _reactToastr = __webpack_require__(15); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var ToastrMessageFactory = _react2.default.createFactory(_reactToastr.ToastMessage.animation); var Notification = function (_Component) { _inherits(Notification, _Component); function Notification() { _classCallCheck(this, Notification); return _possibleConstructorReturn(this, (Notification.__proto__ || Object.getPrototypeOf(Notification)).apply(this, arguments)); } _createClass(Notification, [{ key: 'notice', // allow type is success,info,warning,error value: function notice(type, msg, title) { this.refs.toastr[type](msg, title, { mode: 'single', timeOut: 5000, extendedTimeOut: 1000, showAnimation: 'animated bounceIn', hideAnimation: 'animated bounceOut' }); } }, { key: 'render', value: function render() { return _react2.default.createElement(_reactToastr.ToastContainer, { ref: 'toastr', toastMessageFactory: ToastrMessageFactory, id: 'toast-container', className: 'toast-top-right' }); } }]); return Notification; }(_react.Component); var _default = Notification; exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(ToastrMessageFactory, 'ToastrMessageFactory', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/Notification.js'); __REACT_HOT_LOADER__.register(Notification, 'Notification', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/Notification.js'); __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/Notification.js'); }(); ; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ToastMessage = exports.ToastContainer = undefined; var _ToastContainer = __webpack_require__(16); var _ToastContainer2 = _interopRequireDefault(_ToastContainer); var _ToastMessage = __webpack_require__(172); var _ToastMessage2 = _interopRequireDefault(_ToastMessage); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.ToastContainer = _ToastContainer2.default; exports.ToastMessage = _ToastMessage2.default; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _omit2 = __webpack_require__(17); var _omit3 = _interopRequireDefault(_omit2); var _includes2 = __webpack_require__(154); var _includes3 = _interopRequireDefault(_includes2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _reactAddonsUpdate = __webpack_require__(165); var _reactAddonsUpdate2 = _interopRequireDefault(_reactAddonsUpdate); var _ToastMessage = __webpack_require__(172); var _ToastMessage2 = _interopRequireDefault(_ToastMessage); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var ToastContainer = function (_Component) { _inherits(ToastContainer, _Component); function ToastContainer() { var _ref; var _temp, _this, _ret; _classCallCheck(this, ToastContainer); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = ToastContainer.__proto__ || Object.getPrototypeOf(ToastContainer)).call.apply(_ref, [this].concat(args))), _this), _this.state = { toasts: [], toastId: 0, messageList: [] }, _this._handle_toast_remove = _this._handle_toast_remove.bind(_this), _temp), _possibleConstructorReturn(_this, _ret); } _createClass(ToastContainer, [{ key: "error", value: function error(message, title, optionsOverride) { this._notify(this.props.toastType.error, message, title, optionsOverride); } }, { key: "info", value: function info(message, title, optionsOverride) { this._notify(this.props.toastType.info, message, title, optionsOverride); } }, { key: "success", value: function success(message, title, optionsOverride) { this._notify(this.props.toastType.success, message, title, optionsOverride); } }, { key: "warning", value: function warning(message, title, optionsOverride) { this._notify(this.props.toastType.warning, message, title, optionsOverride); } }, { key: "clear", value: function clear() { var _this2 = this; Object.keys(this.refs).forEach(function (key) { _this2.refs[key].hideToast(false); }); } }, { key: "_notify", value: function _notify(type, message, title) { var _this3 = this; var optionsOverride = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; if (this.props.preventDuplicates) { if ((0, _includes3.default)(this.state.messageList, message)) { return; } } var key = this.state.toastId++; var toastId = key; var newToast = (0, _reactAddonsUpdate2.default)(optionsOverride, { $merge: { type: type, title: title, message: message, toastId: toastId, key: key, ref: "toasts__" + key, handleOnClick: function handleOnClick(e) { if ("function" === typeof optionsOverride.handleOnClick) { optionsOverride.handleOnClick(); } return _this3._handle_toast_on_click(e); }, handleRemove: this._handle_toast_remove } }); var toastOperation = _defineProperty({}, "" + (this.props.newestOnTop ? "$unshift" : "$push"), [newToast]); var messageOperation = _defineProperty({}, "" + (this.props.newestOnTop ? "$unshift" : "$push"), [message]); var nextState = (0, _reactAddonsUpdate2.default)(this.state, { toasts: toastOperation, messageList: messageOperation }); this.setState(nextState); } }, { key: "_handle_toast_on_click", value: function _handle_toast_on_click(event) { this.props.onClick(event); if (event.defaultPrevented) { return; } event.preventDefault(); event.stopPropagation(); } }, { key: "_handle_toast_remove", value: function _handle_toast_remove(toastId) { var _this4 = this; if (this.props.preventDuplicates) { this.state.previousMessage = ""; } var operationName = "" + (this.props.newestOnTop ? "reduceRight" : "reduce"); this.state.toasts[operationName](function (found, toast, index) { if (found || toast.toastId !== toastId) { return false; } _this4.setState((0, _reactAddonsUpdate2.default)(_this4.state, { toasts: { $splice: [[index, 1]] }, messageList: { $splice: [[index, 1]] } })); return true; }, false); } }, { key: "render", value: function render() { var _this5 = this; var divProps = (0, _omit3.default)(this.props, ["toastType", "toastMessageFactory", "preventDuplicates", "newestOnTop"]); return _react2.default.createElement( "div", _extends({}, divProps, { "aria-live": "polite", role: "alert" }), this.state.toasts.map(function (toast) { return _this5.props.toastMessageFactory(toast); }) ); } }]); return ToastContainer; }(_react.Component); ToastContainer.propTypes = { toastType: _react.PropTypes.shape({ error: _react.PropTypes.string, info: _react.PropTypes.string, success: _react.PropTypes.string, warning: _react.PropTypes.string }).isRequired, id: _react.PropTypes.string.isRequired, toastMessageFactory: _react.PropTypes.func.isRequired, preventDuplicates: _react.PropTypes.bool.isRequired, newestOnTop: _react.PropTypes.bool.isRequired, onClick: _react.PropTypes.func.isRequired }; ToastContainer.defaultProps = { toastType: { error: "error", info: "info", success: "success", warning: "warning" }, id: "toast-container", toastMessageFactory: _react2.default.createFactory(_ToastMessage2.default.animation), preventDuplicates: true, newestOnTop: true, onClick: function onClick() {} }; exports.default = ToastContainer; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(18), baseClone = __webpack_require__(19), baseUnset = __webpack_require__(129), castPath = __webpack_require__(130), copyObject = __webpack_require__(69), flatRest = __webpack_require__(143), getAllKeysIn = __webpack_require__(106); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = arrayMap(paths, function(path) { path = castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); copyObject(object, getAllKeysIn(object), result); if (isDeep) { result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG); } var length = paths.length; while (length--) { baseUnset(result, paths[length]); } return result; }); module.exports = omit; /***/ }, /* 18 */ /***/ function(module, exports) { /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } module.exports = arrayMap; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(20), arrayEach = __webpack_require__(64), assignValue = __webpack_require__(65), baseAssign = __webpack_require__(68), baseAssignIn = __webpack_require__(91), cloneBuffer = __webpack_require__(95), copyArray = __webpack_require__(96), copySymbols = __webpack_require__(97), copySymbolsIn = __webpack_require__(100), getAllKeys = __webpack_require__(104), getAllKeysIn = __webpack_require__(106), getTag = __webpack_require__(107), initCloneArray = __webpack_require__(112), initCloneByTag = __webpack_require__(113), initCloneObject = __webpack_require__(127), isArray = __webpack_require__(76), isBuffer = __webpack_require__(77), isObject = __webpack_require__(44), keys = __webpack_require__(70); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, baseClone, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); var keysFunc = isFull ? (isFlat ? getAllKeysIn : getAllKeys) : (isFlat ? keysIn : keys); var props = isArr ? undefined : keysFunc(value); arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } module.exports = baseClone; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(21), stackClear = __webpack_require__(29), stackDelete = __webpack_require__(30), stackGet = __webpack_require__(31), stackHas = __webpack_require__(32), stackSet = __webpack_require__(33); /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; module.exports = Stack; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var listCacheClear = __webpack_require__(22), listCacheDelete = __webpack_require__(23), listCacheGet = __webpack_require__(26), listCacheHas = __webpack_require__(27), listCacheSet = __webpack_require__(28); /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; module.exports = ListCache; /***/ }, /* 22 */ /***/ function(module, exports) { /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } module.exports = listCacheClear; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(24); /** Used for built-in method references. */ var arrayProto = Array.prototype; /** Built-in value references. */ var splice = arrayProto.splice; /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } module.exports = listCacheDelete; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(25); /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } module.exports = assocIndexOf; /***/ }, /* 25 */ /***/ function(module, exports) { /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } module.exports = eq; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(24); /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } module.exports = listCacheGet; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(24); /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } module.exports = listCacheHas; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(24); /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } module.exports = listCacheSet; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(21); /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } module.exports = stackClear; /***/ }, /* 30 */ /***/ function(module, exports) { /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } module.exports = stackDelete; /***/ }, /* 31 */ /***/ function(module, exports) { /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } module.exports = stackGet; /***/ }, /* 32 */ /***/ function(module, exports) { /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } module.exports = stackHas; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(21), Map = __webpack_require__(34), MapCache = __webpack_require__(49); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } module.exports = stackSet; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(35), root = __webpack_require__(40); /* Built-in method references that are verified to be native. */ var Map = getNative(root, 'Map'); module.exports = Map; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { var baseIsNative = __webpack_require__(36), getValue = __webpack_require__(48); /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } module.exports = getNative; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(37), isMasked = __webpack_require__(45), isObject = __webpack_require__(44), toSource = __webpack_require__(47); /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } module.exports = baseIsNative; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(38), isObject = __webpack_require__(44); /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', proxyTag = '[object Proxy]'; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } module.exports = isFunction; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(39), getRawTag = __webpack_require__(42), objectToString = __webpack_require__(43); /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } value = Object(value); return (symToStringTag && symToStringTag in value) ? getRawTag(value) : objectToString(value); } module.exports = baseGetTag; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(40); /** Built-in value references. */ var Symbol = root.Symbol; module.exports = Symbol; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { var freeGlobal = __webpack_require__(41); /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); module.exports = root; /***/ }, /* 41 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; module.exports = freeGlobal; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(39); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } module.exports = getRawTag; /***/ }, /* 43 */ /***/ function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } module.exports = objectToString; /***/ }, /* 44 */ /***/ function(module, exports) { /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } module.exports = isObject; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { var coreJsData = __webpack_require__(46); /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } module.exports = isMasked; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(40); /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; module.exports = coreJsData; /***/ }, /* 47 */ /***/ function(module, exports) { /** Used for built-in method references. */ var funcProto = Function.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } module.exports = toSource; /***/ }, /* 48 */ /***/ function(module, exports) { /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } module.exports = getValue; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { var mapCacheClear = __webpack_require__(50), mapCacheDelete = __webpack_require__(58), mapCacheGet = __webpack_require__(61), mapCacheHas = __webpack_require__(62), mapCacheSet = __webpack_require__(63); /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; module.exports = MapCache; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { var Hash = __webpack_require__(51), ListCache = __webpack_require__(21), Map = __webpack_require__(34); /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } module.exports = mapCacheClear; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { var hashClear = __webpack_require__(52), hashDelete = __webpack_require__(54), hashGet = __webpack_require__(55), hashHas = __webpack_require__(56), hashSet = __webpack_require__(57); /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; module.exports = Hash; /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(53); /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } module.exports = hashClear; /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(35); /* Built-in method references that are verified to be native. */ var nativeCreate = getNative(Object, 'create'); module.exports = nativeCreate; /***/ }, /* 54 */ /***/ function(module, exports) { /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } module.exports = hashDelete; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(53); /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } module.exports = hashGet; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(53); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); } module.exports = hashHas; /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(53); /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } module.exports = hashSet; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(59); /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } module.exports = mapCacheDelete; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { var isKeyable = __webpack_require__(60); /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } module.exports = getMapData; /***/ }, /* 60 */ /***/ function(module, exports) { /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } module.exports = isKeyable; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(59); /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } module.exports = mapCacheGet; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(59); /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } module.exports = mapCacheHas; /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(59); /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } module.exports = mapCacheSet; /***/ }, /* 64 */ /***/ function(module, exports) { /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } module.exports = arrayEach; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(66), eq = __webpack_require__(25); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } module.exports = assignValue; /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { var defineProperty = __webpack_require__(67); /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && defineProperty) { defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } module.exports = baseAssignValue; /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(35); var defineProperty = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); module.exports = defineProperty; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(69), keys = __webpack_require__(70); /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } module.exports = baseAssign; /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { var assignValue = __webpack_require__(65), baseAssignValue = __webpack_require__(66); /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } module.exports = copyObject; /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { var arrayLikeKeys = __webpack_require__(71), baseKeys = __webpack_require__(86), isArrayLike = __webpack_require__(90); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } module.exports = keys; /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { var baseTimes = __webpack_require__(72), isArguments = __webpack_require__(73), isArray = __webpack_require__(76), isBuffer = __webpack_require__(77), isIndex = __webpack_require__(80), isTypedArray = __webpack_require__(81); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } module.exports = arrayLikeKeys; /***/ }, /* 72 */ /***/ function(module, exports) { /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } module.exports = baseTimes; /***/ }, /* 73 */ /***/ function(module, exports, __webpack_require__) { var baseIsArguments = __webpack_require__(74), isObjectLike = __webpack_require__(75); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; module.exports = isArguments; /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(38), isObjectLike = __webpack_require__(75); /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } module.exports = baseIsArguments; /***/ }, /* 75 */ /***/ function(module, exports) { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } module.exports = isObjectLike; /***/ }, /* 76 */ /***/ function(module, exports) { /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; module.exports = isArray; /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(40), stubFalse = __webpack_require__(79); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; module.exports = isBuffer; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(78)(module))) /***/ }, /* 78 */ /***/ function(module, exports) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; } /***/ }, /* 79 */ /***/ function(module, exports) { /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } module.exports = stubFalse; /***/ }, /* 80 */ /***/ function(module, exports) { /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } module.exports = isIndex; /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { var baseIsTypedArray = __webpack_require__(82), baseUnary = __webpack_require__(84), nodeUtil = __webpack_require__(85); /* Node.js helper references. */ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; module.exports = isTypedArray; /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(38), isLength = __webpack_require__(83), isObjectLike = __webpack_require__(75); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } module.exports = baseIsTypedArray; /***/ }, /* 83 */ /***/ function(module, exports) { /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = isLength; /***/ }, /* 84 */ /***/ function(module, exports) { /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } module.exports = baseUnary; /***/ }, /* 85 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(41); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(78)(module))) /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { var isPrototype = __webpack_require__(87), nativeKeys = __webpack_require__(88); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } module.exports = baseKeys; /***/ }, /* 87 */ /***/ function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } module.exports = isPrototype; /***/ }, /* 88 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(89); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = overArg(Object.keys, Object); module.exports = nativeKeys; /***/ }, /* 89 */ /***/ function(module, exports) { /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } module.exports = overArg; /***/ }, /* 90 */ /***/ function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(37), isLength = __webpack_require__(83); /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } module.exports = isArrayLike; /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(69), keysIn = __webpack_require__(92); /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && copyObject(source, keysIn(source), object); } module.exports = baseAssignIn; /***/ }, /* 92 */ /***/ function(module, exports, __webpack_require__) { var arrayLikeKeys = __webpack_require__(71), baseKeysIn = __webpack_require__(93), isArrayLike = __webpack_require__(90); /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } module.exports = keysIn; /***/ }, /* 93 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(44), isPrototype = __webpack_require__(87), nativeKeysIn = __webpack_require__(94); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } module.exports = baseKeysIn; /***/ }, /* 94 */ /***/ function(module, exports) { /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } module.exports = nativeKeysIn; /***/ }, /* 95 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(40); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } module.exports = cloneBuffer; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(78)(module))) /***/ }, /* 96 */ /***/ function(module, exports) { /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } module.exports = copyArray; /***/ }, /* 97 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(69), getSymbols = __webpack_require__(98); /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } module.exports = copySymbols; /***/ }, /* 98 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(89), stubArray = __webpack_require__(99); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray; module.exports = getSymbols; /***/ }, /* 99 */ /***/ function(module, exports) { /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } module.exports = stubArray; /***/ }, /* 100 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(69), getSymbolsIn = __webpack_require__(101); /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn(source), object); } module.exports = copySymbolsIn; /***/ }, /* 101 */ /***/ function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(102), getPrototype = __webpack_require__(103), getSymbols = __webpack_require__(98), stubArray = __webpack_require__(99); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; module.exports = getSymbolsIn; /***/ }, /* 102 */ /***/ function(module, exports) { /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } module.exports = arrayPush; /***/ }, /* 103 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(89); /** Built-in value references. */ var getPrototype = overArg(Object.getPrototypeOf, Object); module.exports = getPrototype; /***/ }, /* 104 */ /***/ function(module, exports, __webpack_require__) { var baseGetAllKeys = __webpack_require__(105), getSymbols = __webpack_require__(98), keys = __webpack_require__(70); /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } module.exports = getAllKeys; /***/ }, /* 105 */ /***/ function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(102), isArray = __webpack_require__(76); /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } module.exports = baseGetAllKeys; /***/ }, /* 106 */ /***/ function(module, exports, __webpack_require__) { var baseGetAllKeys = __webpack_require__(105), getSymbolsIn = __webpack_require__(101), keysIn = __webpack_require__(92); /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } module.exports = getAllKeysIn; /***/ }, /* 107 */ /***/ function(module, exports, __webpack_require__) { var DataView = __webpack_require__(108), Map = __webpack_require__(34), Promise = __webpack_require__(109), Set = __webpack_require__(110), WeakMap = __webpack_require__(111), baseGetTag = __webpack_require__(38), toSource = __webpack_require__(47); /** `Object#toString` result references. */ var mapTag = '[object Map]', objectTag = '[object Object]', promiseTag = '[object Promise]', setTag = '[object Set]', weakMapTag = '[object WeakMap]'; var dataViewTag = '[object DataView]'; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } module.exports = getTag; /***/ }, /* 108 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(35), root = __webpack_require__(40); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'); module.exports = DataView; /***/ }, /* 109 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(35), root = __webpack_require__(40); /* Built-in method references that are verified to be native. */ var Promise = getNative(root, 'Promise'); module.exports = Promise; /***/ }, /* 110 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(35), root = __webpack_require__(40); /* Built-in method references that are verified to be native. */ var Set = getNative(root, 'Set'); module.exports = Set; /***/ }, /* 111 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(35), root = __webpack_require__(40); /* Built-in method references that are verified to be native. */ var WeakMap = getNative(root, 'WeakMap'); module.exports = WeakMap; /***/ }, /* 112 */ /***/ function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } module.exports = initCloneArray; /***/ }, /* 113 */ /***/ function(module, exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(114), cloneDataView = __webpack_require__(116), cloneMap = __webpack_require__(117), cloneRegExp = __webpack_require__(121), cloneSet = __webpack_require__(122), cloneSymbol = __webpack_require__(125), cloneTypedArray = __webpack_require__(126); /** `Object#toString` result references. */ var boolTag = '[object Boolean]', dateTag = '[object Date]', mapTag = '[object Map]', numberTag = '[object Number]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, cloneFunc, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return cloneMap(object, isDeep, cloneFunc); case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return cloneSet(object, isDeep, cloneFunc); case symbolTag: return cloneSymbol(object); } } module.exports = initCloneByTag; /***/ }, /* 114 */ /***/ function(module, exports, __webpack_require__) { var Uint8Array = __webpack_require__(115); /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } module.exports = cloneArrayBuffer; /***/ }, /* 115 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(40); /** Built-in value references. */ var Uint8Array = root.Uint8Array; module.exports = Uint8Array; /***/ }, /* 116 */ /***/ function(module, exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(114); /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } module.exports = cloneDataView; /***/ }, /* 117 */ /***/ function(module, exports, __webpack_require__) { var addMapEntry = __webpack_require__(118), arrayReduce = __webpack_require__(119), mapToArray = __webpack_require__(120); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1; /** * Creates a clone of `map`. * * @private * @param {Object} map The map to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned map. */ function cloneMap(map, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(mapToArray(map), CLONE_DEEP_FLAG) : mapToArray(map); return arrayReduce(array, addMapEntry, new map.constructor); } module.exports = cloneMap; /***/ }, /* 118 */ /***/ function(module, exports) { /** * Adds the key-value `pair` to `map`. * * @private * @param {Object} map The map to modify. * @param {Array} pair The key-value pair to add. * @returns {Object} Returns `map`. */ function addMapEntry(map, pair) { // Don't return `map.set` because it's not chainable in IE 11. map.set(pair[0], pair[1]); return map; } module.exports = addMapEntry; /***/ }, /* 119 */ /***/ function(module, exports) { /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } module.exports = arrayReduce; /***/ }, /* 120 */ /***/ function(module, exports) { /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } module.exports = mapToArray; /***/ }, /* 121 */ /***/ function(module, exports) { /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } module.exports = cloneRegExp; /***/ }, /* 122 */ /***/ function(module, exports, __webpack_require__) { var addSetEntry = __webpack_require__(123), arrayReduce = __webpack_require__(119), setToArray = __webpack_require__(124); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1; /** * Creates a clone of `set`. * * @private * @param {Object} set The set to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned set. */ function cloneSet(set, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(setToArray(set), CLONE_DEEP_FLAG) : setToArray(set); return arrayReduce(array, addSetEntry, new set.constructor); } module.exports = cloneSet; /***/ }, /* 123 */ /***/ function(module, exports) { /** * Adds `value` to `set`. * * @private * @param {Object} set The set to modify. * @param {*} value The value to add. * @returns {Object} Returns `set`. */ function addSetEntry(set, value) { // Don't return `set.add` because it's not chainable in IE 11. set.add(value); return set; } module.exports = addSetEntry; /***/ }, /* 124 */ /***/ function(module, exports) { /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } module.exports = setToArray; /***/ }, /* 125 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(39); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } module.exports = cloneSymbol; /***/ }, /* 126 */ /***/ function(module, exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(114); /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } module.exports = cloneTypedArray; /***/ }, /* 127 */ /***/ function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(128), getPrototype = __webpack_require__(103), isPrototype = __webpack_require__(87); /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } module.exports = initCloneObject; /***/ }, /* 128 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(44); /** Built-in value references. */ var objectCreate = Object.create; /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); module.exports = baseCreate; /***/ }, /* 129 */ /***/ function(module, exports, __webpack_require__) { var castPath = __webpack_require__(130), last = __webpack_require__(138), parent = __webpack_require__(139), toKey = __webpack_require__(141); /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = castPath(path, object); object = parent(object, path); return object == null || delete object[toKey(last(path))]; } module.exports = baseUnset; /***/ }, /* 130 */ /***/ function(module, exports, __webpack_require__) { var isArray = __webpack_require__(76), isKey = __webpack_require__(131), stringToPath = __webpack_require__(133), toString = __webpack_require__(136); /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } module.exports = castPath; /***/ }, /* 131 */ /***/ function(module, exports, __webpack_require__) { var isArray = __webpack_require__(76), isSymbol = __webpack_require__(132); /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/; /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } module.exports = isKey; /***/ }, /* 132 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(38), isObjectLike = __webpack_require__(75); /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } module.exports = isSymbol; /***/ }, /* 133 */ /***/ function(module, exports, __webpack_require__) { var memoizeCapped = __webpack_require__(134); /** Used to match property names within property paths. */ var reLeadingDot = /^\./, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoizeCapped(function(string) { var result = []; if (reLeadingDot.test(string)) { result.push(''); } string.replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); module.exports = stringToPath; /***/ }, /* 134 */ /***/ function(module, exports, __webpack_require__) { var memoize = __webpack_require__(135); /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } module.exports = memoizeCapped; /***/ }, /* 135 */ /***/ function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(49); /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = MapCache; module.exports = memoize; /***/ }, /* 136 */ /***/ function(module, exports, __webpack_require__) { var baseToString = __webpack_require__(137); /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } module.exports = toString; /***/ }, /* 137 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(39), arrayMap = __webpack_require__(18), isArray = __webpack_require__(76), isSymbol = __webpack_require__(132); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = baseToString; /***/ }, /* 138 */ /***/ function(module, exports) { /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } module.exports = last; /***/ }, /* 139 */ /***/ function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(140), baseSlice = __webpack_require__(142); /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); } module.exports = parent; /***/ }, /* 140 */ /***/ function(module, exports, __webpack_require__) { var castPath = __webpack_require__(130), toKey = __webpack_require__(141); /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } module.exports = baseGet; /***/ }, /* 141 */ /***/ function(module, exports, __webpack_require__) { var isSymbol = __webpack_require__(132); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = toKey; /***/ }, /* 142 */ /***/ function(module, exports) { /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } module.exports = baseSlice; /***/ }, /* 143 */ /***/ function(module, exports, __webpack_require__) { var flatten = __webpack_require__(144), overRest = __webpack_require__(147), setToString = __webpack_require__(149); /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return setToString(overRest(func, undefined, flatten), func + ''); } module.exports = flatRest; /***/ }, /* 144 */ /***/ function(module, exports, __webpack_require__) { var baseFlatten = __webpack_require__(145); /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, 1) : []; } module.exports = flatten; /***/ }, /* 145 */ /***/ function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(102), isFlattenable = __webpack_require__(146); /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } module.exports = baseFlatten; /***/ }, /* 146 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(39), isArguments = __webpack_require__(73), isArray = __webpack_require__(76); /** Built-in value references. */ var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } module.exports = isFlattenable; /***/ }, /* 147 */ /***/ function(module, exports, __webpack_require__) { var apply = __webpack_require__(148); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return apply(func, this, otherArgs); }; } module.exports = overRest; /***/ }, /* 148 */ /***/ function(module, exports) { /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } module.exports = apply; /***/ }, /* 149 */ /***/ function(module, exports, __webpack_require__) { var baseSetToString = __webpack_require__(150), shortOut = __webpack_require__(153); /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = shortOut(baseSetToString); module.exports = setToString; /***/ }, /* 150 */ /***/ function(module, exports, __webpack_require__) { var constant = __webpack_require__(151), defineProperty = __webpack_require__(67), identity = __webpack_require__(152); /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !defineProperty ? identity : function(func, string) { return defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(string), 'writable': true }); }; module.exports = baseSetToString; /***/ }, /* 151 */ /***/ function(module, exports) { /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } module.exports = constant; /***/ }, /* 152 */ /***/ function(module, exports) { /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } module.exports = identity; /***/ }, /* 153 */ /***/ function(module, exports) { /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeNow = Date.now; /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } module.exports = shortOut; /***/ }, /* 154 */ /***/ function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(155), isArrayLike = __webpack_require__(90), isString = __webpack_require__(159), toInteger = __webpack_require__(160), values = __webpack_require__(163); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return isString(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && baseIndexOf(collection, value, fromIndex) > -1); } module.exports = includes; /***/ }, /* 155 */ /***/ function(module, exports, __webpack_require__) { var baseFindIndex = __webpack_require__(156), baseIsNaN = __webpack_require__(157), strictIndexOf = __webpack_require__(158); /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } module.exports = baseIndexOf; /***/ }, /* 156 */ /***/ function(module, exports) { /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } module.exports = baseFindIndex; /***/ }, /* 157 */ /***/ function(module, exports) { /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } module.exports = baseIsNaN; /***/ }, /* 158 */ /***/ function(module, exports) { /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } module.exports = strictIndexOf; /***/ }, /* 159 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(38), isArray = __webpack_require__(76), isObjectLike = __webpack_require__(75); /** `Object#toString` result references. */ var stringTag = '[object String]'; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); } module.exports = isString; /***/ }, /* 160 */ /***/ function(module, exports, __webpack_require__) { var toFinite = __webpack_require__(161); /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } module.exports = toInteger; /***/ }, /* 161 */ /***/ function(module, exports, __webpack_require__) { var toNumber = __webpack_require__(162); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_INTEGER = 1.7976931348623157e+308; /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } module.exports = toFinite; /***/ }, /* 162 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(44), isSymbol = __webpack_require__(132); /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } module.exports = toNumber; /***/ }, /* 163 */ /***/ function(module, exports, __webpack_require__) { var baseValues = __webpack_require__(164), keys = __webpack_require__(70); /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : baseValues(object, keys(object)); } module.exports = values; /***/ }, /* 164 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(18); /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return arrayMap(props, function(key) { return object[key]; }); } module.exports = baseValues; /***/ }, /* 165 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(166); /***/ }, /* 166 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule update */ /* global hasOwnProperty:true */ 'use strict'; var _prodInvariant = __webpack_require__(168), _assign = __webpack_require__(169); var keyOf = __webpack_require__(170); var invariant = __webpack_require__(171); var hasOwnProperty = {}.hasOwnProperty; function shallowCopy(x) { if (Array.isArray(x)) { return x.concat(); } else if (x && typeof x === 'object') { return _assign(new x.constructor(), x); } else { return x; } } var COMMAND_PUSH = keyOf({ $push: null }); var COMMAND_UNSHIFT = keyOf({ $unshift: null }); var COMMAND_SPLICE = keyOf({ $splice: null }); var COMMAND_SET = keyOf({ $set: null }); var COMMAND_MERGE = keyOf({ $merge: null }); var COMMAND_APPLY = keyOf({ $apply: null }); var ALL_COMMANDS_LIST = [COMMAND_PUSH, COMMAND_UNSHIFT, COMMAND_SPLICE, COMMAND_SET, COMMAND_MERGE, COMMAND_APPLY]; var ALL_COMMANDS_SET = {}; ALL_COMMANDS_LIST.forEach(function (command) { ALL_COMMANDS_SET[command] = true; }); function invariantArrayCase(value, spec, command) { !Array.isArray(value) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected target of %s to be an array; got %s.', command, value) : _prodInvariant('1', command, value) : void 0; var specValue = spec[command]; !Array.isArray(specValue) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array; got %s. Did you forget to wrap your parameter in an array?', command, specValue) : _prodInvariant('2', command, specValue) : void 0; } /** * Returns a updated shallow copy of an object without mutating the original. * See https://facebook.github.io/react/docs/update.html for details. */ function update(value, spec) { !(typeof spec === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): You provided a key path to update() that did not contain one of %s. Did you forget to include {%s: ...}?', ALL_COMMANDS_LIST.join(', '), COMMAND_SET) : _prodInvariant('3', ALL_COMMANDS_LIST.join(', '), COMMAND_SET) : void 0; if (hasOwnProperty.call(spec, COMMAND_SET)) { !(Object.keys(spec).length === 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot have more than one key in an object with %s', COMMAND_SET) : _prodInvariant('4', COMMAND_SET) : void 0; return spec[COMMAND_SET]; } var nextValue = shallowCopy(value); if (hasOwnProperty.call(spec, COMMAND_MERGE)) { var mergeObj = spec[COMMAND_MERGE]; !(mergeObj && typeof mergeObj === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): %s expects a spec of type \'object\'; got %s', COMMAND_MERGE, mergeObj) : _prodInvariant('5', COMMAND_MERGE, mergeObj) : void 0; !(nextValue && typeof nextValue === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): %s expects a target of type \'object\'; got %s', COMMAND_MERGE, nextValue) : _prodInvariant('6', COMMAND_MERGE, nextValue) : void 0; _assign(nextValue, spec[COMMAND_MERGE]); } if (hasOwnProperty.call(spec, COMMAND_PUSH)) { invariantArrayCase(value, spec, COMMAND_PUSH); spec[COMMAND_PUSH].forEach(function (item) { nextValue.push(item); }); } if (hasOwnProperty.call(spec, COMMAND_UNSHIFT)) { invariantArrayCase(value, spec, COMMAND_UNSHIFT); spec[COMMAND_UNSHIFT].forEach(function (item) { nextValue.unshift(item); }); } if (hasOwnProperty.call(spec, COMMAND_SPLICE)) { !Array.isArray(value) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s target to be an array; got %s', COMMAND_SPLICE, value) : _prodInvariant('7', COMMAND_SPLICE, value) : void 0; !Array.isArray(spec[COMMAND_SPLICE]) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : _prodInvariant('8', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : void 0; spec[COMMAND_SPLICE].forEach(function (args) { !Array.isArray(args) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : _prodInvariant('8', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : void 0; nextValue.splice.apply(nextValue, args); }); } if (hasOwnProperty.call(spec, COMMAND_APPLY)) { !(typeof spec[COMMAND_APPLY] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be a function; got %s.', COMMAND_APPLY, spec[COMMAND_APPLY]) : _prodInvariant('9', COMMAND_APPLY, spec[COMMAND_APPLY]) : void 0; nextValue = spec[COMMAND_APPLY](nextValue); } for (var k in spec) { if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) { nextValue[k] = update(value[k], spec[k]); } } return nextValue; } module.exports = update; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(167))) /***/ }, /* 167 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 168 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule reactProdInvariant * */ 'use strict'; /** * WARNING: DO NOT manually require this module. * This is a replacement for `invariant(...)` used by the error code system * and will _only_ be required by the corresponding babel pass. * It always throws. */ function reactProdInvariant(code) { var argCount = arguments.length - 1; var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code; for (var argIdx = 0; argIdx < argCount; argIdx++) { message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]); } message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.'; var error = new Error(message); error.name = 'Invariant Violation'; error.framesToPop = 1; // we don't care about reactProdInvariant's own frame throw error; } module.exports = reactProdInvariant; /***/ }, /* 169 */ /***/ function(module, exports) { 'use strict'; /* eslint-disable no-unused-vars */ var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (e) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (Object.getOwnPropertySymbols) { symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /***/ }, /* 170 */ /***/ function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /** * Allows extraction of a minified key. Let's the build system minify keys * without losing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ var keyOf = function keyOf(oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; /***/ }, /* 171 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ function invariant(condition, format, a, b, c, d, e, f) { if (process.env.NODE_ENV !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(167))) /***/ }, /* 172 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.jQuery = exports.animation = undefined; var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _reactAddonsUpdate = __webpack_require__(165); var _reactAddonsUpdate2 = _interopRequireDefault(_reactAddonsUpdate); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var _animationMixin = __webpack_require__(173); var _animationMixin2 = _interopRequireDefault(_animationMixin); var _jQueryMixin = __webpack_require__(178); var _jQueryMixin2 = _interopRequireDefault(_jQueryMixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function noop() {} var ToastMessageSpec = { displayName: "ToastMessage", getDefaultProps: function getDefaultProps() { var iconClassNames = { error: "toast-error", info: "toast-info", success: "toast-success", warning: "toast-warning" }; return { className: "toast", iconClassNames: iconClassNames, titleClassName: "toast-title", messageClassName: "toast-message", tapToDismiss: true, closeButton: false }; }, handleOnClick: function handleOnClick(event) { this.props.handleOnClick(event); if (this.props.tapToDismiss) { this.hideToast(true); } }, _handle_close_button_click: function _handle_close_button_click(event) { event.stopPropagation(); this.hideToast(true); }, _handle_remove: function _handle_remove() { this.props.handleRemove(this.props.toastId); }, _render_close_button: function _render_close_button() { return this.props.closeButton ? _react2.default.createElement("button", { className: "toast-close-button", role: "button", onClick: this._handle_close_button_click, dangerouslySetInnerHTML: { __html: "&times;" } }) : false; }, _render_title_element: function _render_title_element() { return this.props.title ? _react2.default.createElement( "div", { className: this.props.titleClassName }, this.props.title ) : false; }, _render_message_element: function _render_message_element() { return this.props.message ? _react2.default.createElement( "div", { className: this.props.messageClassName }, this.props.message ) : false; }, render: function render() { var iconClassName = this.props.iconClassName || this.props.iconClassNames[this.props.type]; return _react2.default.createElement( "div", { className: (0, _classnames2.default)(this.props.className, iconClassName), style: this.props.style, onClick: this.handleOnClick, onMouseEnter: this.handleMouseEnter, onMouseLeave: this.handleMouseLeave }, this._render_close_button(), this._render_title_element(), this._render_message_element() ); } }; var animation = exports.animation = _react2.default.createClass((0, _reactAddonsUpdate2.default)(ToastMessageSpec, { displayName: { $set: "ToastMessage.animation" }, mixins: { $set: [_animationMixin2.default] } })); var jQuery = exports.jQuery = _react2.default.createClass((0, _reactAddonsUpdate2.default)(ToastMessageSpec, { displayName: { $set: "ToastMessage.jQuery" }, mixins: { $set: [_jQueryMixin2.default] } })); /* * assign default noop functions */ ToastMessageSpec.handleMouseEnter = noop; ToastMessageSpec.handleMouseLeave = noop; ToastMessageSpec.hideToast = noop; var ToastMessage = _react2.default.createClass(ToastMessageSpec); ToastMessage.animation = animation; ToastMessage.jQuery = jQuery; exports.default = ToastMessage; /***/ }, /* 173 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _ReactTransitionEvents = __webpack_require__(174); var _ReactTransitionEvents2 = _interopRequireDefault(_ReactTransitionEvents); var _reactDom = __webpack_require__(6); var _reactDom2 = _interopRequireDefault(_reactDom); var _elementClass = __webpack_require__(177); var _elementClass2 = _interopRequireDefault(_elementClass); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var TICK = 17; var toString = Object.prototype.toString; exports.default = { getDefaultProps: function getDefaultProps() { return { transition: null, // some examples defined in index.scss (scale, fadeInOut, rotate) showAnimation: "animated bounceIn", // or other animations from animate.css hideAnimation: "animated bounceOut", timeOut: 5000, extendedTimeOut: 1000 }; }, componentWillMount: function componentWillMount() { this.classNameQueue = []; this.isHiding = false; this.intervalId = null; }, componentDidMount: function componentDidMount() { var _this = this; this._is_mounted = true; this._show(); var node = _reactDom2.default.findDOMNode(this); var onHideComplete = function onHideComplete() { if (_this.isHiding) { _this._set_is_hiding(false); _ReactTransitionEvents2.default.removeEndEventListener(node, onHideComplete); _this._handle_remove(); } }; _ReactTransitionEvents2.default.addEndEventListener(node, onHideComplete); if (this.props.timeOut > 0) { this._set_interval_id(setTimeout(this.hideToast, this.props.timeOut)); } }, componentWillUnmount: function componentWillUnmount() { this._is_mounted = false; if (this.intervalId) { clearTimeout(this.intervalId); } }, _set_transition: function _set_transition(hide) { var animationType = hide ? "leave" : "enter"; var node = _reactDom2.default.findDOMNode(this); var className = this.props.transition + "-" + animationType; var activeClassName = className + "-active"; var endListener = function endListener(e) { if (e && e.target !== node) { return; } var classList = (0, _elementClass2.default)(node); classList.remove(className); classList.remove(activeClassName); _ReactTransitionEvents2.default.removeEndEventListener(node, endListener); }; _ReactTransitionEvents2.default.addEndEventListener(node, endListener); (0, _elementClass2.default)(node).add(className); // Need to do this to actually trigger a transition. this._queue_class(activeClassName); }, _clear_transition: function _clear_transition(hide) { var node = _reactDom2.default.findDOMNode(this); var animationType = hide ? "leave" : "enter"; var className = this.props.transition + "-" + animationType; var activeClassName = className + "-active"; var classList = (0, _elementClass2.default)(node); classList.remove(className); classList.remove(activeClassName); }, _set_animation: function _set_animation(hide) { var node = _reactDom2.default.findDOMNode(this); var animations = this._get_animation_classes(hide); var endListener = function endListener(e) { if (e && e.target !== node) { return; } animations.forEach(function (anim) { return (0, _elementClass2.default)(node).remove(anim); }); _ReactTransitionEvents2.default.removeEndEventListener(node, endListener); }; _ReactTransitionEvents2.default.addEndEventListener(node, endListener); animations.forEach(function (anim) { return (0, _elementClass2.default)(node).add(anim); }); }, _get_animation_classes: function _get_animation_classes(hide) { var animations = hide ? this.props.hideAnimation : this.props.showAnimation; if ("[object Array]" === toString.call(animations)) { return animations; } else if ("string" === typeof animations) { return animations.split(" "); } }, _clear_animation: function _clear_animation(hide) { var node = _reactDom2.default.findDOMNode(this); var animations = this._get_animation_classes(hide); animations.forEach(function (animation) { return (0, _elementClass2.default)(node).remove(animation); }); }, _queue_class: function _queue_class(className) { this.classNameQueue.push(className); if (!this.timeout) { this.timeout = setTimeout(this._flush_class_name_queue, TICK); } }, _flush_class_name_queue: function _flush_class_name_queue() { var _this2 = this; if (this._is_mounted) { (function () { var node = _reactDom2.default.findDOMNode(_this2); _this2.classNameQueue.forEach(function (className) { return (0, _elementClass2.default)(node).add(className); }); })(); } this.classNameQueue.length = 0; this.timeout = null; }, _show: function _show() { if (this.props.transition) { this._set_transition(); } else if (this.props.showAnimation) { this._set_animation(); } }, handleMouseEnter: function handleMouseEnter() { clearTimeout(this.intervalId); this._set_interval_id(null); if (this.isHiding) { this._set_is_hiding(false); if (this.props.hideAnimation) { this._clear_animation(true); } else if (this.props.transition) { this._clear_transition(true); } } }, handleMouseLeave: function handleMouseLeave() { if (!this.isHiding && (this.props.timeOut > 0 || this.props.extendedTimeOut > 0)) { this._set_interval_id(setTimeout(this.hideToast, this.props.extendedTimeOut)); } }, hideToast: function hideToast(override) { if (this.isHiding || this.intervalId === null && !override) { return; } this._set_is_hiding(true); if (this.props.transition) { this._set_transition(true); } else if (this.props.hideAnimation) { this._set_animation(true); } else { this._handle_remove(); } }, _set_interval_id: function _set_interval_id(intervalId) { this.intervalId = intervalId; }, _set_is_hiding: function _set_is_hiding(isHiding) { this.isHiding = isHiding; } }; /***/ }, /* 174 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTransitionEvents */ 'use strict'; var ExecutionEnvironment = __webpack_require__(175); var getVendorPrefixedEventName = __webpack_require__(176); var endEvents = []; function detectEvents() { var animEnd = getVendorPrefixedEventName('animationend'); var transEnd = getVendorPrefixedEventName('transitionend'); if (animEnd) { endEvents.push(animEnd); } if (transEnd) { endEvents.push(transEnd); } } if (ExecutionEnvironment.canUseDOM) { detectEvents(); } // We use the raw {add|remove}EventListener() call because EventListener // does not know how to remove event listeners and we really should // clean up. Also, these events are not triggered in older browsers // so we should be A-OK here. function addEventListener(node, eventName, eventListener) { node.addEventListener(eventName, eventListener, false); } function removeEventListener(node, eventName, eventListener) { node.removeEventListener(eventName, eventListener, false); } var ReactTransitionEvents = { addEndEventListener: function (node, eventListener) { if (endEvents.length === 0) { // If CSS transitions are not supported, trigger an "end animation" // event immediately. window.setTimeout(eventListener, 0); return; } endEvents.forEach(function (endEvent) { addEventListener(node, endEvent, eventListener); }); }, removeEndEventListener: function (node, eventListener) { if (endEvents.length === 0) { return; } endEvents.forEach(function (endEvent) { removeEventListener(node, endEvent, eventListener); }); } }; module.exports = ReactTransitionEvents; /***/ }, /* 175 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; /***/ }, /* 176 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getVendorPrefixedEventName */ 'use strict'; var ExecutionEnvironment = __webpack_require__(175); /** * Generate a mapping of standard vendor prefixes using the defined style property and event name. * * @param {string} styleProp * @param {string} eventName * @returns {object} */ function makePrefixMap(styleProp, eventName) { var prefixes = {}; prefixes[styleProp.toLowerCase()] = eventName.toLowerCase(); prefixes['Webkit' + styleProp] = 'webkit' + eventName; prefixes['Moz' + styleProp] = 'moz' + eventName; prefixes['ms' + styleProp] = 'MS' + eventName; prefixes['O' + styleProp] = 'o' + eventName.toLowerCase(); return prefixes; } /** * A list of event names to a configurable list of vendor prefixes. */ var vendorPrefixes = { animationend: makePrefixMap('Animation', 'AnimationEnd'), animationiteration: makePrefixMap('Animation', 'AnimationIteration'), animationstart: makePrefixMap('Animation', 'AnimationStart'), transitionend: makePrefixMap('Transition', 'TransitionEnd') }; /** * Event names that have already been detected and prefixed (if applicable). */ var prefixedEventNames = {}; /** * Element to check for prefixes on. */ var style = {}; /** * Bootstrap if a DOM exists. */ if (ExecutionEnvironment.canUseDOM) { style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x, // the un-prefixed "animation" and "transition" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are usable, and if not remove them from the map. if (!('AnimationEvent' in window)) { delete vendorPrefixes.animationend.animation; delete vendorPrefixes.animationiteration.animation; delete vendorPrefixes.animationstart.animation; } // Same as above if (!('TransitionEvent' in window)) { delete vendorPrefixes.transitionend.transition; } } /** * Attempts to determine the correct vendor prefixed event name. * * @param {string} eventName * @returns {string} */ function getVendorPrefixedEventName(eventName) { if (prefixedEventNames[eventName]) { return prefixedEventNames[eventName]; } else if (!vendorPrefixes[eventName]) { return eventName; } var prefixMap = vendorPrefixes[eventName]; for (var styleProp in prefixMap) { if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) { return prefixedEventNames[eventName] = prefixMap[styleProp]; } } return ''; } module.exports = getVendorPrefixedEventName; /***/ }, /* 177 */ /***/ function(module, exports) { module.exports = function(opts) { return new ElementClass(opts) } function indexOf(arr, prop) { if (arr.indexOf) return arr.indexOf(prop) for (var i = 0, len = arr.length; i < len; i++) if (arr[i] === prop) return i return -1 } function ElementClass(opts) { if (!(this instanceof ElementClass)) return new ElementClass(opts) var self = this if (!opts) opts = {} // similar doing instanceof HTMLElement but works in IE8 if (opts.nodeType) opts = {el: opts} this.opts = opts this.el = opts.el || document.body if (typeof this.el !== 'object') this.el = document.querySelector(this.el) } ElementClass.prototype.add = function(className) { var el = this.el if (!el) return if (el.className === "") return el.className = className var classes = el.className.split(' ') if (indexOf(classes, className) > -1) return classes classes.push(className) el.className = classes.join(' ') return classes } ElementClass.prototype.remove = function(className) { var el = this.el if (!el) return if (el.className === "") return var classes = el.className.split(' ') var idx = indexOf(classes, className) if (idx > -1) classes.splice(idx, 1) el.className = classes.join(' ') return classes } ElementClass.prototype.has = function(className) { var el = this.el if (!el) return var classes = el.className.split(' ') return indexOf(classes, className) > -1 } ElementClass.prototype.toggle = function(className) { var el = this.el if (!el) return if (this.has(className)) this.remove(className) else this.add(className) } /***/ }, /* 178 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _reactDom = __webpack_require__(6); var _reactDom2 = _interopRequireDefault(_reactDom); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function call_show_method($node, props) { $node[props.showMethod]({ duration: props.showDuration, easing: props.showEasing }); } exports.default = { getDefaultProps: function getDefaultProps() { return { style: { display: "none" }, showMethod: "fadeIn", // slideDown, and show are built into jQuery showDuration: 300, showEasing: "swing", // and linear are built into jQuery hideMethod: "fadeOut", hideDuration: 1000, hideEasing: "swing", // timeOut: 5000, extendedTimeOut: 1000 }; }, getInitialState: function getInitialState() { return { intervalId: null, isHiding: false }; }, componentDidMount: function componentDidMount() { call_show_method(this._get_$_node(), this.props); if (this.props.timeOut > 0) { this._set_interval_id(setTimeout(this.hideToast, this.props.timeOut)); } }, handleMouseEnter: function handleMouseEnter() { clearTimeout(this.state.intervalId); this._set_interval_id(null); this._set_is_hiding(false); call_show_method(this._get_$_node().stop(true, true), this.props); }, handleMouseLeave: function handleMouseLeave() { if (!this.state.isHiding && (this.props.timeOut > 0 || this.props.extendedTimeOut > 0)) { this._set_interval_id(setTimeout(this.hideToast, this.props.extendedTimeOut)); } }, hideToast: function hideToast(override) { if (this.state.isHiding || this.state.intervalId === null && !override) { return; } this.setState({ isHiding: true }); this._get_$_node()[this.props.hideMethod]({ duration: this.props.hideDuration, easing: this.props.hideEasing, complete: this._handle_remove }); }, _get_$_node: function _get_$_node() { /* eslint-disable no-undef */ return jQuery(_reactDom2.default.findDOMNode(this)); /* eslint-enable no-undef */ }, _set_interval_id: function _set_interval_id(intervalId) { this.setState({ intervalId: intervalId }); }, _set_is_hiding: function _set_is_hiding(isHiding) { this.setState({ isHiding: isHiding }); } }; /***/ }, /* 179 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint max-len: 0 */ var ExpandComponent = function (_Component) { _inherits(ExpandComponent, _Component); function ExpandComponent() { _classCallCheck(this, ExpandComponent); return _possibleConstructorReturn(this, (ExpandComponent.__proto__ || Object.getPrototypeOf(ExpandComponent)).apply(this, arguments)); } _createClass(ExpandComponent, [{ key: 'render', value: function render() { var trCss = { style: { backgroundColor: this.props.bgColor }, className: (0, _classnames2.default)(this.props.isSelected ? this.props.selectRow.className : null, this.props.className) }; return _react2.default.createElement( 'tr', _extends({ hidden: this.props.hidden, width: this.props.width }, trCss), _react2.default.createElement( 'td', { colSpan: this.props.colSpan }, this.props.children ) ); } }]); return ExpandComponent; }(_react.Component); var _default = ExpandComponent; exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(ExpandComponent, 'ExpandComponent', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/ExpandComponent.js'); __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/ExpandComponent.js'); }(); ; /***/ }, /* 180 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _PageButton = __webpack_require__(181); var _PageButton2 = _interopRequireDefault(_PageButton); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var PaginationList = function (_Component) { _inherits(PaginationList, _Component); function PaginationList() { var _ref; var _temp, _this, _ret; _classCallCheck(this, PaginationList); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = PaginationList.__proto__ || Object.getPrototypeOf(PaginationList)).call.apply(_ref, [this].concat(args))), _this), _this.changePage = function () { var _this2; return (_this2 = _this).__changePage__REACT_HOT_LOADER__.apply(_this2, arguments); }, _this.changeSizePerPage = function () { var _this3; return (_this3 = _this).__changeSizePerPage__REACT_HOT_LOADER__.apply(_this3, arguments); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(PaginationList, [{ key: '__changePage__REACT_HOT_LOADER__', value: function __changePage__REACT_HOT_LOADER__(page) { var _props = this.props, pageStartIndex = _props.pageStartIndex, prePage = _props.prePage, currPage = _props.currPage, nextPage = _props.nextPage, lastPage = _props.lastPage, firstPage = _props.firstPage, sizePerPage = _props.sizePerPage; if (page === prePage) { page = currPage - 1 < pageStartIndex ? pageStartIndex : currPage - 1; } else if (page === nextPage) { page = currPage + 1 > this.lastPage ? this.lastPage : currPage + 1; } else if (page === lastPage) { page = this.lastPage; } else if (page === firstPage) { page = pageStartIndex; } else { page = parseInt(page, 10); } if (page !== currPage) { this.props.changePage(page, sizePerPage); } } }, { key: '__changeSizePerPage__REACT_HOT_LOADER__', value: function __changeSizePerPage__REACT_HOT_LOADER__(e) { e.preventDefault(); var selectSize = parseInt(e.currentTarget.getAttribute('data-page'), 10); var currPage = this.props.currPage; if (selectSize !== this.props.sizePerPage) { this.totalPages = Math.ceil(this.props.dataSize / selectSize); this.lastPage = this.props.pageStartIndex + this.totalPages - 1; if (currPage > this.lastPage) currPage = this.lastPage; this.props.changePage(currPage, selectSize); if (this.props.onSizePerPageList) { this.props.onSizePerPageList(selectSize); } } } }, { key: 'render', value: function render() { var _this4 = this; var _props2 = this.props, currPage = _props2.currPage, dataSize = _props2.dataSize, sizePerPage = _props2.sizePerPage, sizePerPageList = _props2.sizePerPageList, paginationShowsTotal = _props2.paginationShowsTotal, pageStartIndex = _props2.pageStartIndex, hideSizePerPage = _props2.hideSizePerPage; var sizePerPageText = ''; this.totalPages = Math.ceil(dataSize / sizePerPage); this.lastPage = this.props.pageStartIndex + this.totalPages - 1; var pageBtns = this.makePage(); var pageListStyle = { float: 'right', // override the margin-top defined in .pagination class in bootstrap. marginTop: '0px' }; var sizePerPageOptions = sizePerPageList.map(function (_sizePerPage) { var pageText = _sizePerPage.text || _sizePerPage; var pageNum = _sizePerPage.value || _sizePerPage; if (sizePerPage === pageNum) sizePerPageText = pageText; return _react2.default.createElement( 'li', { key: pageText, role: 'presentation' }, _react2.default.createElement( 'a', { role: 'menuitem', tabIndex: '-1', href: '#', 'data-page': pageNum, onClick: _this4.changeSizePerPage }, pageText ) ); }); var offset = Math.abs(_Const2.default.PAGE_START_INDEX - pageStartIndex); var start = (currPage - pageStartIndex) * sizePerPage; start = dataSize === 0 ? 0 : start + 1; var to = Math.min(sizePerPage * (currPage + offset) - 1, dataSize); if (to >= dataSize) to--; var total = paginationShowsTotal ? _react2.default.createElement( 'span', null, 'Showing rows ', start, ' to\xA0', to + 1, ' of\xA0', dataSize ) : null; if (typeof paginationShowsTotal === 'function') { total = paginationShowsTotal(start, to + 1, dataSize); } var dropDownStyle = { visibility: hideSizePerPage ? 'hidden' : 'visible' }; return _react2.default.createElement( 'div', { className: 'row', style: { marginTop: 15 } }, sizePerPageList.length > 1 ? _react2.default.createElement( 'div', null, _react2.default.createElement( 'div', { className: 'col-md-6' }, total, ' ', _react2.default.createElement( 'span', { className: 'dropdown', style: dropDownStyle }, _react2.default.createElement( 'button', { className: 'btn btn-default dropdown-toggle', type: 'button', id: 'pageDropDown', 'data-toggle': 'dropdown', 'aria-expanded': 'true' }, sizePerPageText, _react2.default.createElement( 'span', null, ' ', _react2.default.createElement('span', { className: 'caret' }) ) ), _react2.default.createElement( 'ul', { className: 'dropdown-menu', role: 'menu', 'aria-labelledby': 'pageDropDown' }, sizePerPageOptions ) ) ), _react2.default.createElement( 'div', { className: 'col-md-6' }, _react2.default.createElement( 'ul', { className: 'pagination', style: pageListStyle }, pageBtns ) ) ) : _react2.default.createElement( 'div', null, _react2.default.createElement( 'div', { className: 'col-md-6' }, total ), _react2.default.createElement( 'div', { className: 'col-md-6' }, _react2.default.createElement( 'ul', { className: 'pagination', style: pageListStyle }, pageBtns ) ) ) ); } }, { key: 'makePage', value: function makePage() { var pages = this.getPages(); return pages.map(function (page) { var isActive = page === this.props.currPage; var disabled = false; var hidden = false; if (this.props.currPage === this.props.pageStartIndex && (page === this.props.firstPage || page === this.props.prePage)) { disabled = true; hidden = true; } if (this.props.currPage === this.lastPage && (page === this.props.nextPage || page === this.props.lastPage)) { disabled = true; hidden = true; } return _react2.default.createElement( _PageButton2.default, { key: page, changePage: this.changePage, active: isActive, disable: disabled, hidden: hidden }, page ); }, this); } }, { key: 'getPages', value: function getPages() { var pages = void 0; var endPage = this.totalPages; if (endPage <= 0) return []; var startPage = Math.max(this.props.currPage - Math.floor(this.props.paginationSize / 2), this.props.pageStartIndex); endPage = startPage + this.props.paginationSize - 1; if (endPage > this.lastPage) { endPage = this.lastPage; startPage = endPage - this.props.paginationSize + 1; } if (startPage !== this.props.pageStartIndex && this.totalPages > this.props.paginationSize) { pages = [this.props.firstPage, this.props.prePage]; } else if (this.totalPages > 1) { pages = [this.props.prePage]; } else { pages = []; } for (var i = startPage; i <= endPage; i++) { if (i >= this.props.pageStartIndex) pages.push(i); } if (endPage < this.lastPage) { pages.push(this.props.nextPage); pages.push(this.props.lastPage); } else if (endPage === this.lastPage && this.props.currPage !== this.lastPage) { pages.push(this.props.nextPage); } return pages; } }]); return PaginationList; }(_react.Component); PaginationList.propTypes = { currPage: _react.PropTypes.number, sizePerPage: _react.PropTypes.number, dataSize: _react.PropTypes.number, changePage: _react.PropTypes.func, sizePerPageList: _react.PropTypes.array, paginationShowsTotal: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.func]), paginationSize: _react.PropTypes.number, remote: _react.PropTypes.bool, onSizePerPageList: _react.PropTypes.func, prePage: _react.PropTypes.string, pageStartIndex: _react.PropTypes.number, hideSizePerPage: _react.PropTypes.bool }; PaginationList.defaultProps = { sizePerPage: _Const2.default.SIZE_PER_PAGE, pageStartIndex: _Const2.default.PAGE_START_INDEX }; var _default = PaginationList; exports.default = _default; ; var _temp2 = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(PaginationList, 'PaginationList', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/pagination/PaginationList.js'); __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/pagination/PaginationList.js'); }(); ; /***/ }, /* 181 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var PageButton = function (_Component) { _inherits(PageButton, _Component); function PageButton(props) { _classCallCheck(this, PageButton); var _this = _possibleConstructorReturn(this, (PageButton.__proto__ || Object.getPrototypeOf(PageButton)).call(this, props)); _this.pageBtnClick = function () { return _this.__pageBtnClick__REACT_HOT_LOADER__.apply(_this, arguments); }; return _this; } _createClass(PageButton, [{ key: '__pageBtnClick__REACT_HOT_LOADER__', value: function __pageBtnClick__REACT_HOT_LOADER__(e) { e.preventDefault(); this.props.changePage(e.currentTarget.textContent); } }, { key: 'render', value: function render() { var classes = (0, _classnames2.default)({ 'active': this.props.active, 'disabled': this.props.disable, 'hidden': this.props.hidden, 'page-item': true }); return _react2.default.createElement( 'li', { className: classes }, _react2.default.createElement( 'a', { href: '#', onClick: this.pageBtnClick, className: 'page-link' }, this.props.children ) ); } }]); return PageButton; }(_react.Component); PageButton.propTypes = { changePage: _react.PropTypes.func, active: _react.PropTypes.bool, disable: _react.PropTypes.bool, hidden: _react.PropTypes.bool, children: _react.PropTypes.node }; var _default = PageButton; exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(PageButton, 'PageButton', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/pagination/PageButton.js'); __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/pagination/PageButton.js'); }(); ; /***/ }, /* 182 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var _Editor = __webpack_require__(13); var _Editor2 = _interopRequireDefault(_Editor); var _Notification = __webpack_require__(14); var _Notification2 = _interopRequireDefault(_Notification); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var ToolBar = function (_Component) { _inherits(ToolBar, _Component); function ToolBar(props) { var _arguments = arguments; _classCallCheck(this, ToolBar); var _this = _possibleConstructorReturn(this, (ToolBar.__proto__ || Object.getPrototypeOf(ToolBar)).call(this, props)); _this.handleSaveBtnClick = function () { return _this.__handleSaveBtnClick__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleShowOnlyToggle = function () { return _this.__handleShowOnlyToggle__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleDropRowBtnClick = function () { return _this.__handleDropRowBtnClick__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleDebounce = function (func, wait, immediate) { var timeout = void 0; return function () { var later = function later() { timeout = null; if (!immediate) { func.apply(_this, _arguments); } }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait || 0); if (callNow) { func.appy(_this, _arguments); } }; }; _this.handleKeyUp = function () { return _this.__handleKeyUp__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleExportCSV = function () { return _this.__handleExportCSV__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleClearBtnClick = function () { return _this.__handleClearBtnClick__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.timeouteClear = 0; _this.modalClassName; _this.state = { isInsertRowTrigger: true, validateState: null, shakeEditor: false, showSelected: false }; return _this; } _createClass(ToolBar, [{ key: 'componentWillMount', value: function componentWillMount() { var _this2 = this; var delay = this.props.searchDelayTime ? this.props.searchDelayTime : 0; this.debounceCallback = this.handleDebounce(function () { _this2.props.onSearch(_this2.refs.seachInput.value); }, delay); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.clearTimeout(); } }, { key: 'setSearchInput', value: function setSearchInput(text) { if (this.refs.seachInput.value !== text) { this.refs.seachInput.value = text; } } }, { key: 'clearTimeout', value: function (_clearTimeout) { function clearTimeout() { return _clearTimeout.apply(this, arguments); } clearTimeout.toString = function () { return _clearTimeout.toString(); }; return clearTimeout; }(function () { if (this.timeouteClear) { clearTimeout(this.timeouteClear); this.timeouteClear = 0; } }) // modified by iuculanop // BEGIN }, { key: 'checkAndParseForm', value: function checkAndParseForm() { var _this3 = this; var newObj = {}; var validateState = {}; var isValid = true; var checkVal = void 0; var responseType = void 0; var tempValue = void 0; this.props.columns.forEach(function (column, i) { if (column.autoValue) { // when you want same auto generate value and not allow edit, example ID field var time = new Date().getTime(); tempValue = typeof column.autoValue === 'function' ? column.autoValue() : 'autovalue-' + time; } else if (column.hiddenOnInsert || !column.field) { tempValue = ''; } else { var dom = this.refs[column.field + i]; tempValue = dom.value; if (column.editable && column.editable.type === 'checkbox') { var values = tempValue.split(':'); tempValue = dom.checked ? values[0] : values[1]; } if (column.editable && column.editable.validator) { // process validate checkVal = column.editable.validator(tempValue); responseType = typeof checkVal === 'undefined' ? 'undefined' : _typeof(checkVal); if (responseType !== 'object' && checkVal !== true) { this.refs.notifier.notice('error', 'Form validate errors, please checking!', 'Pressed ESC can cancel'); isValid = false; validateState[column.field] = checkVal; } else if (responseType === 'object' && checkVal.isValid !== true) { this.refs.notifier.notice(checkVal.notification.type, checkVal.notification.msg, checkVal.notification.title); isValid = false; validateState[column.field] = checkVal.notification.msg; } } } newObj[column.field] = tempValue; }, this); if (isValid) { return newObj; } else { this.clearTimeout(); // show error in form and shake it this.setState({ validateState: validateState, shakeEditor: true }); this.timeouteClear = setTimeout(function () { _this3.setState({ shakeEditor: false }); }, 300); return null; } } // END }, { key: '__handleSaveBtnClick__REACT_HOT_LOADER__', value: function __handleSaveBtnClick__REACT_HOT_LOADER__() { var _this4 = this; var newObj = this.checkAndParseForm(); if (!newObj) { // validate errors return; } var msg = this.props.onAddRow(newObj); if (msg) { this.refs.notifier.notice('error', msg, 'Pressed ESC can cancel'); this.clearTimeout(); // shake form and hack prevent modal hide this.setState({ shakeEditor: true, validateState: 'this is hack for prevent bootstrap modal hide' }); // clear animate class this.timeouteClear = setTimeout(function () { _this4.setState({ shakeEditor: false }); }, 300); } else { // reset state and hide modal hide this.setState({ validateState: null, shakeEditor: false }, function () { document.querySelector('.modal-backdrop').click(); document.querySelector('.' + _this4.modalClassName).click(); }); // reset form this.refs.form.reset(); } } }, { key: '__handleShowOnlyToggle__REACT_HOT_LOADER__', value: function __handleShowOnlyToggle__REACT_HOT_LOADER__() { this.setState({ showSelected: !this.state.showSelected }); this.props.onShowOnlySelected(); } }, { key: '__handleDropRowBtnClick__REACT_HOT_LOADER__', value: function __handleDropRowBtnClick__REACT_HOT_LOADER__() { this.props.onDropRow(); } }, { key: 'handleCloseBtn', value: function handleCloseBtn() { this.refs.warning.style.display = 'none'; } }, { key: '__handleKeyUp__REACT_HOT_LOADER__', value: function __handleKeyUp__REACT_HOT_LOADER__(event) { event.persist(); this.debounceCallback(event); } }, { key: '__handleExportCSV__REACT_HOT_LOADER__', value: function __handleExportCSV__REACT_HOT_LOADER__() { this.props.onExportCSV(); } }, { key: '__handleClearBtnClick__REACT_HOT_LOADER__', value: function __handleClearBtnClick__REACT_HOT_LOADER__() { this.refs.seachInput.value = ''; this.props.onSearch(''); } }, { key: 'render', value: function render() { this.modalClassName = 'bs-table-modal-sm' + ToolBar.modalSeq++; var insertBtn = null; var deleteBtn = null; var exportCSV = null; var showSelectedOnlyBtn = null; if (this.props.enableInsert) { insertBtn = _react2.default.createElement( 'button', { type: 'button', className: 'btn btn-info react-bs-table-add-btn', 'data-toggle': 'modal', 'data-target': '.' + this.modalClassName }, _react2.default.createElement('i', { className: 'glyphicon glyphicon-plus' }), ' ', this.props.insertText ); } if (this.props.enableDelete) { deleteBtn = _react2.default.createElement( 'button', { type: 'button', className: 'btn btn-warning react-bs-table-del-btn', 'data-toggle': 'tooltip', 'data-placement': 'right', title: 'Drop selected row', onClick: this.handleDropRowBtnClick }, _react2.default.createElement('i', { className: 'glyphicon glyphicon-trash' }), ' ', this.props.deleteText ); } if (this.props.enableShowOnlySelected) { showSelectedOnlyBtn = _react2.default.createElement( 'button', { type: 'button', onClick: this.handleShowOnlyToggle, className: 'btn btn-primary', 'data-toggle': 'button', 'aria-pressed': 'false' }, this.state.showSelected ? _Const2.default.SHOW_ALL : _Const2.default.SHOW_ONLY_SELECT ); } if (this.props.enableExportCSV) { exportCSV = _react2.default.createElement( 'button', { type: 'button', className: 'btn btn-success hidden-print', onClick: this.handleExportCSV }, _react2.default.createElement('i', { className: 'glyphicon glyphicon-export' }), this.props.exportCSVText ); } var searchTextInput = this.renderSearchPanel(); var modal = this.props.enableInsert ? this.renderInsertRowModal() : null; return _react2.default.createElement( 'div', { className: 'row' }, _react2.default.createElement( 'div', { className: 'col-xs-12 col-sm-6 col-md-6 col-lg-8' }, _react2.default.createElement( 'div', { className: 'btn-group btn-group-sm', role: 'group' }, exportCSV, insertBtn, deleteBtn, showSelectedOnlyBtn ) ), _react2.default.createElement( 'div', { className: 'col-xs-12 col-sm-6 col-md-6 col-lg-4' }, searchTextInput ), _react2.default.createElement(_Notification2.default, { ref: 'notifier' }), modal ); } }, { key: 'renderSearchPanel', value: function renderSearchPanel() { if (this.props.enableSearch) { var classNames = 'form-group form-group-sm react-bs-table-search-form'; var clearBtn = null; if (this.props.clearSearch) { clearBtn = _react2.default.createElement( 'span', { className: 'input-group-btn' }, _react2.default.createElement( 'button', { className: 'btn btn-default', type: 'button', onClick: this.handleClearBtnClick }, 'Clear' ) ); classNames += ' input-group input-group-sm'; } return _react2.default.createElement( 'div', { className: classNames }, _react2.default.createElement('input', { ref: 'seachInput', className: 'form-control', type: 'text', defaultValue: this.props.defaultSearch, placeholder: this.props.searchPlaceholder ? this.props.searchPlaceholder : 'Search', onKeyUp: this.handleKeyUp }), clearBtn ); } else { return null; } } }, { key: 'renderInsertRowModal', value: function renderInsertRowModal() { var _this5 = this; var validateState = this.state.validateState || {}; var shakeEditor = this.state.shakeEditor; var inputField = this.props.columns.map(function (column, i) { var editable = column.editable, format = column.format, field = column.field, name = column.name, autoValue = column.autoValue, hiddenOnInsert = column.hiddenOnInsert; var attr = { ref: field + i, placeholder: editable.placeholder ? editable.placeholder : name }; if (autoValue || hiddenOnInsert || !column.field) { // when you want same auto generate value // and not allow edit, for example ID field return null; } var error = validateState[field] ? _react2.default.createElement( 'span', { className: 'help-block bg-danger' }, validateState[field] ) : null; // let editor = Editor(editable,attr,format); // if(editor.props.type && editor.props.type == 'checkbox'){ return _react2.default.createElement( 'div', { className: 'form-group', key: field }, _react2.default.createElement( 'label', null, name ), (0, _Editor2.default)(editable, attr, format, '', undefined, _this5.props.ignoreEditable), error ); }); var modalClass = (0, _classnames2.default)('modal', 'fade', this.modalClassName, { // hack prevent bootstrap modal hide by reRender 'in': shakeEditor || this.state.validateState }); var dialogClass = (0, _classnames2.default)('modal-dialog', 'modal-sm', { 'animated': shakeEditor, 'shake': shakeEditor }); return _react2.default.createElement( 'div', { ref: 'modal', className: modalClass, tabIndex: '-1', role: 'dialog' }, _react2.default.createElement( 'div', { className: dialogClass }, _react2.default.createElement( 'div', { className: 'modal-content' }, _react2.default.createElement( 'div', { className: 'modal-header' }, _react2.default.createElement( 'button', { type: 'button', className: 'close', 'data-dismiss': 'modal', 'aria-label': 'Close' }, _react2.default.createElement( 'span', { 'aria-hidden': 'true' }, '\xD7' ) ), _react2.default.createElement( 'h4', { className: 'modal-title' }, 'New Record' ) ), _react2.default.createElement( 'div', { className: 'modal-body' }, _react2.default.createElement( 'form', { ref: 'form' }, inputField ) ), _react2.default.createElement( 'div', { className: 'modal-footer' }, _react2.default.createElement( 'button', { type: 'button', className: 'btn btn-default', 'data-dismiss': 'modal' }, this.props.closeText ), _react2.default.createElement( 'button', { type: 'button', className: 'btn btn-primary', onClick: this.handleSaveBtnClick }, this.props.saveText ) ) ) ) ); } }]); return ToolBar; }(_react.Component); ToolBar.modalSeq = 0; ToolBar.propTypes = { onAddRow: _react.PropTypes.func, onDropRow: _react.PropTypes.func, onShowOnlySelected: _react.PropTypes.func, enableInsert: _react.PropTypes.bool, enableDelete: _react.PropTypes.bool, enableSearch: _react.PropTypes.bool, enableShowOnlySelected: _react.PropTypes.bool, columns: _react.PropTypes.array, searchPlaceholder: _react.PropTypes.string, exportCSVText: _react.PropTypes.string, insertText: _react.PropTypes.string, deleteText: _react.PropTypes.string, saveText: _react.PropTypes.string, closeText: _react.PropTypes.string, clearSearch: _react.PropTypes.bool, ignoreEditable: _react.PropTypes.bool, defaultSearch: _react.PropTypes.string }; ToolBar.defaultProps = { enableInsert: false, enableDelete: false, enableSearch: false, enableShowOnlySelected: false, clearSearch: false, ignoreEditable: false, exportCSVText: _Const2.default.EXPORT_CSV_TEXT, insertText: _Const2.default.INSERT_BTN_TEXT, deleteText: _Const2.default.DELETE_BTN_TEXT, saveText: _Const2.default.SAVE_BTN_TEXT, closeText: _Const2.default.CLOSE_BTN_TEXT }; var _default = ToolBar; exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(ToolBar, 'ToolBar', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/ToolBar.js'); __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/ToolBar.js'); }(); ; /***/ }, /* 183 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var TableFilter = function (_Component) { _inherits(TableFilter, _Component); function TableFilter(props) { _classCallCheck(this, TableFilter); var _this = _possibleConstructorReturn(this, (TableFilter.__proto__ || Object.getPrototypeOf(TableFilter)).call(this, props)); _this.handleKeyUp = function () { return _this.__handleKeyUp__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.filterObj = {}; return _this; } _createClass(TableFilter, [{ key: '__handleKeyUp__REACT_HOT_LOADER__', value: function __handleKeyUp__REACT_HOT_LOADER__(e) { var _e$currentTarget = e.currentTarget, value = _e$currentTarget.value, name = _e$currentTarget.name; if (value.trim() === '') { delete this.filterObj[name]; } else { this.filterObj[name] = value; } this.props.onFilter(this.filterObj); } }, { key: 'render', value: function render() { var _props = this.props, striped = _props.striped, condensed = _props.condensed, rowSelectType = _props.rowSelectType, columns = _props.columns; var tableClasses = (0, _classnames2.default)('table', { 'table-striped': striped, 'table-condensed': condensed }); var selectRowHeader = null; if (rowSelectType === _Const2.default.ROW_SELECT_SINGLE || rowSelectType === _Const2.default.ROW_SELECT_MULTI) { var style = { width: 35, paddingLeft: 0, paddingRight: 0 }; selectRowHeader = _react2.default.createElement( 'th', { style: style, key: -1 }, 'Filter' ); } var filterField = columns.map(function (column) { var hidden = column.hidden, width = column.width, name = column.name; var thStyle = { display: hidden ? 'none' : null, width: width }; return _react2.default.createElement( 'th', { key: name, style: thStyle }, _react2.default.createElement( 'div', { className: 'th-inner table-header-column' }, _react2.default.createElement('input', { size: '10', type: 'text', placeholder: name, name: name, onKeyUp: this.handleKeyUp }) ) ); }, this); return _react2.default.createElement( 'table', { className: tableClasses, style: { marginTop: 5 } }, _react2.default.createElement( 'thead', null, _react2.default.createElement( 'tr', { style: { borderBottomStyle: 'hidden' } }, selectRowHeader, filterField ) ) ); } }]); return TableFilter; }(_react.Component); TableFilter.propTypes = { columns: _react.PropTypes.array, rowSelectType: _react.PropTypes.string, onFilter: _react.PropTypes.func }; var _default = TableFilter; exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(TableFilter, 'TableFilter', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableFilter.js'); __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableFilter.js'); }(); ; /***/ }, /* 184 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.TableDataStore = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /* eslint no-nested-ternary: 0 */ /* eslint guard-for-in: 0 */ /* eslint no-console: 0 */ /* eslint eqeqeq: 0 */ /* eslint one-var: 0 */ var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var TableDataStore = function () { function TableDataStore(data) { _classCallCheck(this, TableDataStore); this.data = data; this.colInfos = null; this.filteredData = null; this.isOnFilter = false; this.filterObj = null; this.searchText = null; this.sortList = []; this.pageObj = {}; this.selected = []; this.multiColumnSearch = false; this.multiColumnSort = 1; this.showOnlySelected = false; this.remote = false; // remote data } _createClass(TableDataStore, [{ key: 'setProps', value: function setProps(props) { this.keyField = props.keyField; this.enablePagination = props.isPagination; this.colInfos = props.colInfos; this.remote = props.remote; this.multiColumnSearch = props.multiColumnSearch; this.multiColumnSort = props.multiColumnSort; } }, { key: 'setData', value: function setData(data) { this.data = data; if (this.remote) { return; } this._refresh(true); } }, { key: 'getColInfos', value: function getColInfos() { return this.colInfos; } }, { key: 'getSortInfo', value: function getSortInfo() { return this.sortList; } }, { key: 'setSortInfo', value: function setSortInfo(order, sortField) { if ((typeof order === 'undefined' ? 'undefined' : _typeof(order)) !== (typeof sortField === 'undefined' ? 'undefined' : _typeof(sortField))) { throw new Error('The type of sort field and order should be both with String or Array'); } if (Array.isArray(order) && Array.isArray(sortField)) { if (order.length !== sortField.length) { throw new Error('The length of sort fields and orders should be equivalent'); } order = order.reverse(); this.sortList = sortField.reverse().map(function (field, i) { return { order: order[i], sortField: field }; }); this.sortList = this.sortList.slice(0, this.multiColumnSort); } else { var sortObj = { order: order, sortField: sortField }; if (this.multiColumnSort > 1) { var i = this.sortList.length - 1; var sortFieldInHistory = false; for (; i >= 0; i--) { if (this.sortList[i].sortField === sortField) { sortFieldInHistory = true; break; } } if (sortFieldInHistory) { if (i > 0) { this.sortList = this.sortList.slice(0, i); } else { this.sortList = this.sortList.slice(1); } } this.sortList.unshift(sortObj); this.sortList = this.sortList.slice(0, this.multiColumnSort); } else { this.sortList = [sortObj]; } } } }, { key: 'setSelectedRowKey', value: function setSelectedRowKey(selectedRowKeys) { this.selected = selectedRowKeys; } }, { key: 'getRowByKey', value: function getRowByKey(keys) { var _this = this; return keys.map(function (key) { var result = _this.data.filter(function (d) { return d[_this.keyField] === key; }); if (result.length !== 0) return result[0]; }); } }, { key: 'getSelectedRowKeys', value: function getSelectedRowKeys() { return this.selected; } }, { key: 'getCurrentDisplayData', value: function getCurrentDisplayData() { if (this.isOnFilter) return this.filteredData;else return this.data; } }, { key: '_refresh', value: function _refresh(skipSorting) { if (this.isOnFilter) { if (this.filterObj !== null) this.filter(this.filterObj); if (this.searchText !== null) this.search(this.searchText); } if (!skipSorting && this.sortList.length > 0) { this.sort(); } } }, { key: 'ignoreNonSelected', value: function ignoreNonSelected() { var _this2 = this; this.showOnlySelected = !this.showOnlySelected; if (this.showOnlySelected) { this.isOnFilter = true; this.filteredData = this.data.filter(function (row) { var result = _this2.selected.find(function (x) { return row[_this2.keyField] === x; }); return typeof result !== 'undefined' ? true : false; }); } else { this.isOnFilter = false; } } }, { key: 'sort', value: function sort() { var currentDisplayData = this.getCurrentDisplayData(); currentDisplayData = this._sort(currentDisplayData); return this; } }, { key: 'page', value: function page(_page, sizePerPage) { this.pageObj.end = _page * sizePerPage - 1; this.pageObj.start = this.pageObj.end - (sizePerPage - 1); return this; } }, { key: 'edit', value: function edit(newVal, rowIndex, fieldName) { var currentDisplayData = this.getCurrentDisplayData(); var rowKeyCache = void 0; if (!this.enablePagination) { currentDisplayData[rowIndex][fieldName] = newVal; rowKeyCache = currentDisplayData[rowIndex][this.keyField]; } else { currentDisplayData[this.pageObj.start + rowIndex][fieldName] = newVal; rowKeyCache = currentDisplayData[this.pageObj.start + rowIndex][this.keyField]; } if (this.isOnFilter) { this.data.forEach(function (row) { if (row[this.keyField] === rowKeyCache) { row[fieldName] = newVal; } }, this); if (this.filterObj !== null) this.filter(this.filterObj); if (this.searchText !== null) this.search(this.searchText); } return this; } }, { key: 'addAtBegin', value: function addAtBegin(newObj) { if (!newObj[this.keyField] || newObj[this.keyField].toString() === '') { throw new Error(this.keyField + ' can\'t be empty value.'); } var currentDisplayData = this.getCurrentDisplayData(); currentDisplayData.forEach(function (row) { if (row[this.keyField].toString() === newObj[this.keyField].toString()) { throw new Error(this.keyField + ' ' + newObj[this.keyField] + ' already exists'); } }, this); currentDisplayData.unshift(newObj); if (this.isOnFilter) { this.data.unshift(newObj); } this._refresh(false); } }, { key: 'add', value: function add(newObj) { if (!newObj[this.keyField] || newObj[this.keyField].toString() === '') { throw new Error(this.keyField + ' can\'t be empty value.'); } var currentDisplayData = this.getCurrentDisplayData(); currentDisplayData.forEach(function (row) { if (row[this.keyField].toString() === newObj[this.keyField].toString()) { throw new Error(this.keyField + ' ' + newObj[this.keyField] + ' already exists'); } }, this); currentDisplayData.push(newObj); if (this.isOnFilter) { this.data.push(newObj); } this._refresh(false); } }, { key: 'remove', value: function remove(rowKey) { var _this3 = this; var currentDisplayData = this.getCurrentDisplayData(); var result = currentDisplayData.filter(function (row) { return rowKey.indexOf(row[_this3.keyField]) === -1; }); if (this.isOnFilter) { this.data = this.data.filter(function (row) { return rowKey.indexOf(row[_this3.keyField]) === -1; }); this.filteredData = result; } else { this.data = result; } } }, { key: 'filter', value: function filter(filterObj) { if (Object.keys(filterObj).length === 0) { this.filteredData = null; this.isOnFilter = false; this.filterObj = null; if (this.searchText) this._search(this.data); } else { var source = this.data; this.filterObj = filterObj; if (this.searchText) { this._search(source); source = this.filteredData; } this._filter(source); } } }, { key: 'filterNumber', value: function filterNumber(targetVal, filterVal, comparator) { var valid = true; switch (comparator) { case '=': { if (targetVal != filterVal) { valid = false; } break; } case '>': { if (targetVal <= filterVal) { valid = false; } break; } case '>=': { if (targetVal < filterVal) { valid = false; } break; } case '<': { if (targetVal >= filterVal) { valid = false; } break; } case '<=': { if (targetVal > filterVal) { valid = false; } break; } case '!=': { if (targetVal == filterVal) { valid = false; } break; } default: { console.error('Number comparator provided is not supported'); break; } } return valid; } }, { key: 'filterDate', value: function filterDate(targetVal, filterVal, comparator) { // if (!targetVal) { // return false; // } // return (targetVal.getDate() === filterVal.getDate() && // targetVal.getMonth() === filterVal.getMonth() && // targetVal.getFullYear() === filterVal.getFullYear()); var valid = true; switch (comparator) { case '=': { if (targetVal != filterVal) { valid = false; } break; } case '>': { if (targetVal <= filterVal) { valid = false; } break; } case '>=': { if (targetVal < filterVal) { valid = false; } break; } case '<': { if (targetVal >= filterVal) { valid = false; } break; } case '<=': { if (targetVal > filterVal) { valid = false; } break; } case '!=': { if (targetVal == filterVal) { valid = false; } break; } default: { console.error('Date comparator provided is not supported'); break; } } return valid; } }, { key: 'filterRegex', value: function filterRegex(targetVal, filterVal) { try { return new RegExp(filterVal, 'i').test(targetVal); } catch (e) { return true; } } }, { key: 'filterCustom', value: function filterCustom(targetVal, filterVal, callbackInfo, cond) { if (callbackInfo !== null && (typeof callbackInfo === 'undefined' ? 'undefined' : _typeof(callbackInfo)) === 'object') { return callbackInfo.callback(targetVal, callbackInfo.callbackParameters); } return this.filterText(targetVal, filterVal, cond); } }, { key: 'filterText', value: function filterText(targetVal, filterVal) { var cond = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _Const2.default.FILTER_COND_EQ; targetVal = targetVal.toString(); filterVal = filterVal.toString(); if (cond === _Const2.default.FILTER_COND_EQ) { return targetVal === filterVal; } else { targetVal = targetVal.toLowerCase(); filterVal = filterVal.toLowerCase(); return !(targetVal.indexOf(filterVal) === -1); } } /* General search function * It will search for the text if the input includes that text; */ }, { key: 'search', value: function search(searchText) { if (searchText.trim() === '') { this.filteredData = null; this.isOnFilter = false; this.searchText = null; if (this.filterObj) this._filter(this.data); } else { var source = this.data; this.searchText = searchText; if (this.filterObj) { this._filter(source); source = this.filteredData; } this._search(source); } } }, { key: '_filter', value: function _filter(source) { var _this4 = this; var filterObj = this.filterObj; this.filteredData = source.filter(function (row, r) { var valid = true; var filterVal = void 0; for (var key in filterObj) { var targetVal = row[key]; if (targetVal === null || targetVal === undefined) { targetVal = ''; } switch (filterObj[key].type) { case _Const2.default.FILTER_TYPE.NUMBER: { filterVal = filterObj[key].value.number; break; } case _Const2.default.FILTER_TYPE.CUSTOM: { filterVal = _typeof(filterObj[key].value) === 'object' ? undefined : typeof filterObj[key].value === 'string' ? filterObj[key].value.toLowerCase() : filterObj[key].value; break; } case _Const2.default.FILTER_TYPE.DATE: { filterVal = filterObj[key].value.date; break; } case _Const2.default.FILTER_TYPE.REGEX: { filterVal = filterObj[key].value; break; } default: { filterVal = filterObj[key].value; if (filterVal === undefined) { // Support old filter filterVal = filterObj[key]; } break; } } var format = void 0, filterFormatted = void 0, formatExtraData = void 0, filterValue = void 0; if (_this4.colInfos[key]) { format = _this4.colInfos[key].format; filterFormatted = _this4.colInfos[key].filterFormatted; formatExtraData = _this4.colInfos[key].formatExtraData; filterValue = _this4.colInfos[key].filterValue; if (filterFormatted && format) { targetVal = format(row[key], row, formatExtraData, r); } else if (filterValue) { targetVal = filterValue(row[key], row); } } switch (filterObj[key].type) { case _Const2.default.FILTER_TYPE.NUMBER: { valid = _this4.filterNumber(targetVal, filterVal, filterObj[key].value.comparator); break; } case _Const2.default.FILTER_TYPE.DATE: { valid = _this4.filterDate(targetVal, filterVal, filterObj[key].value.comparator); break; } case _Const2.default.FILTER_TYPE.REGEX: { valid = _this4.filterRegex(targetVal, filterVal); break; } case _Const2.default.FILTER_TYPE.CUSTOM: { var cond = filterObj[key].props ? filterObj[key].props.cond : _Const2.default.FILTER_COND_EQ; valid = _this4.filterCustom(targetVal, filterVal, filterObj[key].value, cond); break; } default: { if (filterObj[key].type === _Const2.default.FILTER_TYPE.SELECT && filterFormatted && filterFormatted && format) { filterVal = format(filterVal, row, formatExtraData, r); } var _cond = filterObj[key].props ? filterObj[key].props.cond : _Const2.default.FILTER_COND_EQ; valid = _this4.filterText(targetVal, filterVal, _cond); break; } } if (!valid) { break; } } return valid; }); this.isOnFilter = true; } }, { key: '_search', value: function _search(source) { var _this5 = this; var searchTextArray = []; if (this.multiColumnSearch) { searchTextArray = this.searchText.split(' '); } else { searchTextArray.push(this.searchText); } this.filteredData = source.filter(function (row, r) { var keys = Object.keys(row); var valid = false; // for loops are ugly, but performance matters here. // And you cant break from a forEach. // http://jsperf.com/for-vs-foreach/66 for (var i = 0, keysLength = keys.length; i < keysLength; i++) { var key = keys[i]; // fixed data filter when misunderstand 0 is false var filterSpecialNum = false; if (!isNaN(row[key]) && parseInt(row[key], 10) === 0) { filterSpecialNum = true; } if (_this5.colInfos[key] && (row[key] || filterSpecialNum)) { var _colInfos$key = _this5.colInfos[key], format = _colInfos$key.format, filterFormatted = _colInfos$key.filterFormatted, filterValue = _colInfos$key.filterValue, formatExtraData = _colInfos$key.formatExtraData, searchable = _colInfos$key.searchable; var targetVal = row[key]; if (searchable) { if (filterFormatted && format) { targetVal = format(targetVal, row, formatExtraData, r); } else if (filterValue) { targetVal = filterValue(targetVal, row); } for (var j = 0, textLength = searchTextArray.length; j < textLength; j++) { var filterVal = searchTextArray[j].toLowerCase(); if (targetVal.toString().toLowerCase().indexOf(filterVal) !== -1) { valid = true; break; } } } } } return valid; }); this.isOnFilter = true; } }, { key: '_sort', value: function _sort(arr) { var _this6 = this; if (this.sortList.length === 0 || typeof this.sortList[0] === 'undefined') { return arr; } arr.sort(function (a, b) { var result = 0; for (var i = 0; i < _this6.sortList.length; i++) { var sortDetails = _this6.sortList[i]; var isDesc = sortDetails.order.toLowerCase() === _Const2.default.SORT_DESC; var _colInfos$sortDetails = _this6.colInfos[sortDetails.sortField], sortFunc = _colInfos$sortDetails.sortFunc, sortFuncExtraData = _colInfos$sortDetails.sortFuncExtraData; if (sortFunc) { result = sortFunc(a, b, sortDetails.order, sortDetails.sortField, sortFuncExtraData); } else { var valueA = a[sortDetails.sortField] === null ? '' : a[sortDetails.sortField]; var valueB = b[sortDetails.sortField] === null ? '' : b[sortDetails.sortField]; if (isDesc) { if (typeof valueB === 'string') { result = valueB.localeCompare(valueA); } else { result = valueA > valueB ? -1 : valueA < valueB ? 1 : 0; } } else { if (typeof valueA === 'string') { result = valueA.localeCompare(valueB); } else { result = valueA < valueB ? -1 : valueA > valueB ? 1 : 0; } } } if (result !== 0) { return result; } } return result; }); return arr; } }, { key: 'getDataIgnoringPagination', value: function getDataIgnoringPagination() { return this.getCurrentDisplayData(); } }, { key: 'get', value: function get() { var _data = this.getCurrentDisplayData(); if (_data.length === 0) return _data; if (this.remote || !this.enablePagination) { return _data; } else { var result = []; for (var i = this.pageObj.start; i <= this.pageObj.end; i++) { result.push(_data[i]); if (i + 1 === _data.length) break; } return result; } } }, { key: 'getKeyField', value: function getKeyField() { return this.keyField; } }, { key: 'getDataNum', value: function getDataNum() { return this.getCurrentDisplayData().length; } }, { key: 'isChangedPage', value: function isChangedPage() { return this.pageObj.start && this.pageObj.end ? true : false; } }, { key: 'isEmpty', value: function isEmpty() { return this.data.length === 0 || this.data === null || this.data === undefined; } }, { key: 'getAllRowkey', value: function getAllRowkey() { var _this7 = this; return this.data.map(function (row) { return row[_this7.keyField]; }); } }]); return TableDataStore; }(); exports.TableDataStore = TableDataStore; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(TableDataStore, 'TableDataStore', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/store/TableDataStore.js'); }(); ; /***/ }, /* 185 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _util = __webpack_require__(9); var _util2 = _interopRequireDefault(_util); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } if (_util2.default.canUseDOM()) { var filesaver = __webpack_require__(186); var saveAs = filesaver.saveAs; } /* eslint block-scoped-var: 0 */ /* eslint vars-on-top: 0 */ /* eslint no-var: 0 */ /* eslint no-unused-vars: 0 */ function toString(data, keys) { var dataString = ''; if (data.length === 0) return dataString; var headCells = []; var rowCount = 0; keys.forEach(function (key) { if (key.row > rowCount) { rowCount = key.row; } // rowCount += (key.rowSpan + key.colSpan - 1); for (var index = 0; index < key.colSpan; index++) { headCells.push(key); } }); var _loop = function _loop(i) { dataString += headCells.map(function (x) { if (x.row + (x.rowSpan - 1) === i) { return x.header; } if (x.row === i && x.rowSpan > 1) { return ''; } }).filter(function (key) { return typeof key !== 'undefined'; }).join(',') + '\n'; }; for (var i = 0; i <= rowCount; i++) { _loop(i); } keys = keys.filter(function (key) { return key.field !== undefined; }); data.map(function (row) { keys.map(function (col, i) { var field = col.field, format = col.format; var value = typeof format !== 'undefined' ? format(row[field], row) : row[field]; var cell = typeof value !== 'undefined' ? '"' + value + '"' : ''; dataString += cell; if (i + 1 < keys.length) dataString += ','; }); dataString += '\n'; }); return dataString; } var exportCSV = function exportCSV(data, keys, filename) { var dataString = toString(data, keys); if (typeof window !== 'undefined') { saveAs(new Blob([dataString], { type: 'text/plain;charset=utf-8' }), filename, true); } }; var _default = exportCSV; exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(saveAs, 'saveAs', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/csv_export_util.js'); __REACT_HOT_LOADER__.register(toString, 'toString', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/csv_export_util.js'); __REACT_HOT_LOADER__.register(exportCSV, 'exportCSV', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/csv_export_util.js'); __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/csv_export_util.js'); }(); ; /***/ }, /* 186 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;"use strict"; /* FileSaver.js * A saveAs() FileSaver implementation. * 1.1.20151003 * * By Eli Grey, http://eligrey.com * License: MIT * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md */ /*global self */ /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */ /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ var saveAs = saveAs || function (view) { "use strict"; // IE <10 is explicitly unsupported if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) { return; } var doc = view.document // only get URL when necessary in case Blob.js hasn't overridden it yet , get_URL = function get_URL() { return view.URL || view.webkitURL || view; }, save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a"), can_use_save_link = "download" in save_link, click = function click(node) { var event = new MouseEvent("click"); node.dispatchEvent(event); }, is_safari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent), webkit_req_fs = view.webkitRequestFileSystem, req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem, throw_outside = function throw_outside(ex) { (view.setImmediate || view.setTimeout)(function () { throw ex; }, 0); }, force_saveable_type = "application/octet-stream", fs_min_size = 0 // See https://code.google.com/p/chromium/issues/detail?id=375297#c7 and // https://github.com/eligrey/FileSaver.js/commit/485930a#commitcomment-8768047 // for the reasoning behind the timeout and revocation flow , arbitrary_revoke_timeout = 500 // in ms , revoke = function revoke(file) { var revoker = function revoker() { if (typeof file === "string") { // file is an object URL get_URL().revokeObjectURL(file); } else { // file is a File file.remove(); } }; if (view.chrome) { revoker(); } else { setTimeout(revoker, arbitrary_revoke_timeout); } }, dispatch = function dispatch(filesaver, event_types, event) { event_types = [].concat(event_types); var i = event_types.length; while (i--) { var listener = filesaver["on" + event_types[i]]; if (typeof listener === "function") { try { listener.call(filesaver, event || filesaver); } catch (ex) { throw_outside(ex); } } } }, auto_bom = function auto_bom(blob) { // prepend BOM for UTF-8 XML and text/* types (including HTML) if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) { return new Blob(["\uFEFF", blob], { type: blob.type }); } return blob; }, FileSaver = function FileSaver(blob, name, no_auto_bom) { if (!no_auto_bom) { blob = auto_bom(blob); } // First try a.download, then web filesystem, then object URLs var filesaver = this, type = blob.type, blob_changed = false, object_url, target_view, dispatch_all = function dispatch_all() { dispatch(filesaver, "writestart progress write writeend".split(" ")); } // on any filesys errors revert to saving with object URLs , fs_error = function fs_error() { if (target_view && is_safari && typeof FileReader !== "undefined") { // Safari doesn't allow downloading of blob urls var reader = new FileReader(); reader.onloadend = function () { var base64Data = reader.result; target_view.location.href = "data:attachment/file" + base64Data.slice(base64Data.search(/[,;]/)); filesaver.readyState = filesaver.DONE; dispatch_all(); }; reader.readAsDataURL(blob); filesaver.readyState = filesaver.INIT; return; } // don't create more object URLs than needed if (blob_changed || !object_url) { object_url = get_URL().createObjectURL(blob); } if (target_view) { target_view.location.href = object_url; } else { var new_tab = view.open(object_url, "_blank"); if (new_tab == undefined && is_safari) { //Apple do not allow window.open, see http://bit.ly/1kZffRI view.location.href = object_url; } } filesaver.readyState = filesaver.DONE; dispatch_all(); revoke(object_url); }, abortable = function abortable(func) { return function () { if (filesaver.readyState !== filesaver.DONE) { return func.apply(this, arguments); } }; }, create_if_not_found = { create: true, exclusive: false }, slice; filesaver.readyState = filesaver.INIT; if (!name) { name = "download"; } if (can_use_save_link) { object_url = get_URL().createObjectURL(blob); save_link.href = object_url; save_link.download = name; setTimeout(function () { click(save_link); dispatch_all(); revoke(object_url); filesaver.readyState = filesaver.DONE; }); return; } // Object and web filesystem URLs have a problem saving in Google Chrome when // viewed in a tab, so I force save with application/octet-stream // http://code.google.com/p/chromium/issues/detail?id=91158 // Update: Google errantly closed 91158, I submitted it again: // https://code.google.com/p/chromium/issues/detail?id=389642 if (view.chrome && type && type !== force_saveable_type) { slice = blob.slice || blob.webkitSlice; blob = slice.call(blob, 0, blob.size, force_saveable_type); blob_changed = true; } // Since I can't be sure that the guessed media type will trigger a download // in WebKit, I append .download to the filename. // https://bugs.webkit.org/show_bug.cgi?id=65440 if (webkit_req_fs && name !== "download") { name += ".download"; } if (type === force_saveable_type || webkit_req_fs) { target_view = view; } if (!req_fs) { fs_error(); return; } fs_min_size += blob.size; req_fs(view.TEMPORARY, fs_min_size, abortable(function (fs) { fs.root.getDirectory("saved", create_if_not_found, abortable(function (dir) { var save = function save() { dir.getFile(name, create_if_not_found, abortable(function (file) { file.createWriter(abortable(function (writer) { writer.onwriteend = function (event) { target_view.location.href = file.toURL(); filesaver.readyState = filesaver.DONE; dispatch(filesaver, "writeend", event); revoke(file); }; writer.onerror = function () { var error = writer.error; if (error.code !== error.ABORT_ERR) { fs_error(); } }; "writestart progress write abort".split(" ").forEach(function (event) { writer["on" + event] = filesaver["on" + event]; }); writer.write(blob); filesaver.abort = function () { writer.abort(); filesaver.readyState = filesaver.DONE; }; filesaver.readyState = filesaver.WRITING; }), fs_error); }), fs_error); }; dir.getFile(name, { create: false }, abortable(function (file) { // delete file if it already exists file.remove(); save(); }), abortable(function (ex) { if (ex.code === ex.NOT_FOUND_ERR) { save(); } else { fs_error(); } })); }), fs_error); }), fs_error); }, FS_proto = FileSaver.prototype, saveAs = function saveAs(blob, name, no_auto_bom) { return new FileSaver(blob, name, no_auto_bom); }; // IE 10+ (native saveAs) if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) { return function (blob, name, no_auto_bom) { if (!no_auto_bom) { blob = auto_bom(blob); } return navigator.msSaveOrOpenBlob(blob, name || "download"); }; } FS_proto.abort = function () { var filesaver = this; filesaver.readyState = filesaver.DONE; dispatch(filesaver, "abort"); }; FS_proto.readyState = FS_proto.INIT = 0; FS_proto.WRITING = 1; FS_proto.DONE = 2; FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = null; return saveAs; }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined.content); // `self` is undefined in Firefox for Android content script context // while `this` is nsIContentFrameMessageManager // with an attribute `content` that corresponds to the window if (typeof module !== "undefined" && module.exports) { module.exports.saveAs = saveAs; } else if ("function" !== "undefined" && __webpack_require__(187) !== null && __webpack_require__(188) != null) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return saveAs; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(saveAs, "saveAs", "/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filesaver.js"); }(); ; /***/ }, /* 187 */ /***/ function(module, exports) { module.exports = function() { throw new Error("define cannot be used indirect"); }; /***/ }, /* 188 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {module.exports = __webpack_amd_options__; /* WEBPACK VAR INJECTION */}.call(exports, {})) /***/ }, /* 189 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Filter = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var _events = __webpack_require__(190); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Filter = exports.Filter = function (_EventEmitter) { _inherits(Filter, _EventEmitter); function Filter(data) { _classCallCheck(this, Filter); var _this = _possibleConstructorReturn(this, (Filter.__proto__ || Object.getPrototypeOf(Filter)).call(this, data)); _this.currentFilter = {}; return _this; } _createClass(Filter, [{ key: 'handleFilter', value: function handleFilter(dataField, value, type, filterObj) { var filterType = type || _Const2.default.FILTER_TYPE.CUSTOM; var props = { cond: filterObj.condition // Only for select and text filter }; if (value !== null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') { // value of the filter is an object var hasValue = true; for (var prop in value) { if (!value[prop] || value[prop] === '') { hasValue = false; break; } } // if one of the object properties is undefined or empty, we remove the filter if (hasValue) { this.currentFilter[dataField] = { value: value, type: filterType, props: props }; } else { delete this.currentFilter[dataField]; } } else if (!value || value.trim() === '') { delete this.currentFilter[dataField]; } else { this.currentFilter[dataField] = { value: value.trim(), type: filterType, props: props }; } this.emit('onFilterChange', this.currentFilter); } }]); return Filter; }(_events.EventEmitter); ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(Filter, 'Filter', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/Filter.js'); }(); ; /***/ }, /* 190 */ /***/ function(module, exports) { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } /***/ }, /* 191 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var _util = __webpack_require__(9); var _util2 = _interopRequireDefault(_util); var _Date = __webpack_require__(192); var _Date2 = _interopRequireDefault(_Date); var _Text = __webpack_require__(193); var _Text2 = _interopRequireDefault(_Text); var _Regex = __webpack_require__(194); var _Regex2 = _interopRequireDefault(_Regex); var _Select = __webpack_require__(195); var _Select2 = _interopRequireDefault(_Select); var _Number = __webpack_require__(196); var _Number2 = _interopRequireDefault(_Number); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint default-case: 0 */ /* eslint guard-for-in: 0 */ var TableHeaderColumn = function (_Component) { _inherits(TableHeaderColumn, _Component); function TableHeaderColumn(props) { _classCallCheck(this, TableHeaderColumn); var _this = _possibleConstructorReturn(this, (TableHeaderColumn.__proto__ || Object.getPrototypeOf(TableHeaderColumn)).call(this, props)); _this.handleColumnClick = function () { return _this.__handleColumnClick__REACT_HOT_LOADER__.apply(_this, arguments); }; _this.handleFilter = _this.handleFilter.bind(_this); return _this; } _createClass(TableHeaderColumn, [{ key: '__handleColumnClick__REACT_HOT_LOADER__', value: function __handleColumnClick__REACT_HOT_LOADER__() { if (this.props.isOnlyHead || !this.props.dataSort) return; var order = this.props.sort === _Const2.default.SORT_DESC ? _Const2.default.SORT_ASC : _Const2.default.SORT_DESC; this.props.onSort(order, this.props.dataField); } }, { key: 'handleFilter', value: function handleFilter(value, type) { var filter = this.props.filter; filter.emitter.handleFilter(this.props.dataField, value, type, filter); } }, { key: 'getFilters', value: function getFilters() { var _props = this.props, headerText = _props.headerText, children = _props.children; switch (this.props.filter.type) { case _Const2.default.FILTER_TYPE.TEXT: { return _react2.default.createElement(_Text2.default, _extends({ ref: 'textFilter' }, this.props.filter, { columnName: headerText || children, filterHandler: this.handleFilter })); } case _Const2.default.FILTER_TYPE.REGEX: { return _react2.default.createElement(_Regex2.default, _extends({ ref: 'regexFilter' }, this.props.filter, { columnName: headerText || children, filterHandler: this.handleFilter })); } case _Const2.default.FILTER_TYPE.SELECT: { return _react2.default.createElement(_Select2.default, _extends({ ref: 'selectFilter' }, this.props.filter, { columnName: headerText || children, filterHandler: this.handleFilter })); } case _Const2.default.FILTER_TYPE.NUMBER: { return _react2.default.createElement(_Number2.default, _extends({ ref: 'numberFilter' }, this.props.filter, { columnName: headerText || children, filterHandler: this.handleFilter })); } case _Const2.default.FILTER_TYPE.DATE: { return _react2.default.createElement(_Date2.default, _extends({ ref: 'dateFilter' }, this.props.filter, { columnName: headerText || children, filterHandler: this.handleFilter })); } case _Const2.default.FILTER_TYPE.CUSTOM: { var elm = this.props.filter.getElement(this.handleFilter, this.props.filter.customFilterParameters); return _react2.default.cloneElement(elm, { ref: 'customFilter' }); } } } }, { key: 'componentDidMount', value: function componentDidMount() { this.refs['header-col'].setAttribute('data-field', this.props.dataField); } }, { key: 'render', value: function render() { var defaultCaret = void 0; var sortCaret = void 0; var _props2 = this.props, headerText = _props2.headerText, dataAlign = _props2.dataAlign, dataField = _props2.dataField, headerAlign = _props2.headerAlign, headerTitle = _props2.headerTitle, hidden = _props2.hidden, sort = _props2.sort, dataSort = _props2.dataSort, sortIndicator = _props2.sortIndicator, children = _props2.children, caretRender = _props2.caretRender, className = _props2.className, isOnlyHead = _props2.isOnlyHead; var thStyle = { textAlign: headerAlign || dataAlign, display: hidden ? 'none' : null }; if (!isOnlyHead) { if (sortIndicator) { defaultCaret = !dataSort ? null : _react2.default.createElement( 'span', { className: 'order' }, _react2.default.createElement( 'span', { className: 'dropdown' }, _react2.default.createElement('span', { className: 'caret', style: { margin: '10px 0 10px 5px', color: '#ccc' } }) ), _react2.default.createElement( 'span', { className: 'dropup' }, _react2.default.createElement('span', { className: 'caret', style: { margin: '10px 0', color: '#ccc' } }) ) ); } sortCaret = sort ? _util2.default.renderReactSortCaret(sort) : defaultCaret; if (caretRender) { sortCaret = caretRender(sort, dataField); } } var classes = (0, _classnames2.default)(typeof className === 'function' ? className() : className, !isOnlyHead && dataSort ? 'sort-column' : ''); var title = { title: headerTitle && typeof children === 'string' ? children : headerText }; return _react2.default.createElement( 'th', _extends({ ref: 'header-col', className: classes, style: thStyle, onClick: this.handleColumnClick, rowSpan: this.props.rowSpan, colSpan: this.props.colSpan, 'data-is-only-head': this.props.isOnlyHead }, title), children, sortCaret, _react2.default.createElement( 'div', { onClick: function onClick(e) { return e.stopPropagation(); } }, this.props.filter && !isOnlyHead ? this.getFilters() : null ) ); } }, { key: 'cleanFiltered', value: function cleanFiltered() { if (this.props.filter === undefined) { return; } switch (this.props.filter.type) { case _Const2.default.FILTER_TYPE.TEXT: { this.refs.textFilter.cleanFiltered(); break; } case _Const2.default.FILTER_TYPE.REGEX: { this.refs.regexFilter.cleanFiltered(); break; } case _Const2.default.FILTER_TYPE.SELECT: { this.refs.selectFilter.cleanFiltered(); break; } case _Const2.default.FILTER_TYPE.NUMBER: { this.refs.numberFilter.cleanFiltered(); break; } case _Const2.default.FILTER_TYPE.DATE: { this.refs.dateFilter.cleanFiltered(); break; } case _Const2.default.FILTER_TYPE.CUSTOM: { this.refs.customFilter.cleanFiltered(); break; } } } }, { key: 'applyFilter', value: function applyFilter(val) { if (this.props.filter === undefined) return; switch (this.props.filter.type) { case _Const2.default.FILTER_TYPE.TEXT: { this.refs.textFilter.applyFilter(val); break; } case _Const2.default.FILTER_TYPE.REGEX: { this.refs.regexFilter.applyFilter(val); break; } case _Const2.default.FILTER_TYPE.SELECT: { this.refs.selectFilter.applyFilter(val); break; } case _Const2.default.FILTER_TYPE.NUMBER: { this.refs.numberFilter.applyFilter(val); break; } case _Const2.default.FILTER_TYPE.DATE: { this.refs.dateFilter.applyFilter(val); break; } } } }]); return TableHeaderColumn; }(_react.Component); var filterTypeArray = []; for (var key in _Const2.default.FILTER_TYPE) { filterTypeArray.push(_Const2.default.FILTER_TYPE[key]); } TableHeaderColumn.propTypes = { dataField: _react.PropTypes.string, dataAlign: _react.PropTypes.string, headerAlign: _react.PropTypes.string, headerTitle: _react.PropTypes.bool, headerText: _react.PropTypes.string, dataSort: _react.PropTypes.bool, onSort: _react.PropTypes.func, dataFormat: _react.PropTypes.func, csvFormat: _react.PropTypes.func, csvHeader: _react.PropTypes.string, isKey: _react.PropTypes.bool, editable: _react.PropTypes.any, hidden: _react.PropTypes.bool, hiddenOnInsert: _react.PropTypes.bool, searchable: _react.PropTypes.bool, className: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.func]), width: _react.PropTypes.string, sortFunc: _react.PropTypes.func, sortFuncExtraData: _react.PropTypes.any, columnClassName: _react.PropTypes.any, editColumnClassName: _react.PropTypes.any, invalidEditColumnClassName: _react.PropTypes.any, columnTitle: _react.PropTypes.bool, filterFormatted: _react.PropTypes.bool, filterValue: _react.PropTypes.func, sort: _react.PropTypes.string, caretRender: _react.PropTypes.func, formatExtraData: _react.PropTypes.any, filter: _react.PropTypes.shape({ type: _react.PropTypes.oneOf(filterTypeArray), delay: _react.PropTypes.number, options: _react.PropTypes.oneOfType([_react.PropTypes.object, // for SelectFilter _react.PropTypes.arrayOf(_react.PropTypes.number) // for NumberFilter ]), numberComparators: _react.PropTypes.arrayOf(_react.PropTypes.string), emitter: _react.PropTypes.object, placeholder: _react.PropTypes.string, getElement: _react.PropTypes.func, customFilterParameters: _react.PropTypes.object, condition: _react.PropTypes.oneOf([_Const2.default.FILTER_COND_EQ, _Const2.default.FILTER_COND_LIKE]) }), sortIndicator: _react.PropTypes.bool, export: _react.PropTypes.bool, expandable: _react.PropTypes.bool, tdAttr: _react.PropTypes.object }; TableHeaderColumn.defaultProps = { dataAlign: 'left', headerAlign: undefined, headerTitle: true, dataSort: false, dataFormat: undefined, csvFormat: undefined, csvHeader: undefined, isKey: false, editable: true, onSort: undefined, hidden: false, hiddenOnInsert: false, searchable: true, className: '', columnTitle: false, width: null, sortFunc: undefined, columnClassName: '', editColumnClassName: '', invalidEditColumnClassName: '', filterFormatted: false, filterValue: undefined, sort: undefined, formatExtraData: undefined, sortFuncExtraData: undefined, filter: undefined, sortIndicator: true, expandable: true, tdAttr: undefined }; var _default = TableHeaderColumn; exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(TableHeaderColumn, 'TableHeaderColumn', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableHeaderColumn.js'); __REACT_HOT_LOADER__.register(filterTypeArray, 'filterTypeArray', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableHeaderColumn.js'); __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableHeaderColumn.js'); }(); ; /***/ }, /* 192 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint quotes: 0 */ /* eslint max-len: 0 */ var legalComparators = ['=', '>', '>=', '<', '<=', '!=']; function dateParser(d) { return d.getFullYear() + '-' + ("0" + (d.getMonth() + 1)).slice(-2) + '-' + ("0" + d.getDate()).slice(-2); } var DateFilter = function (_Component) { _inherits(DateFilter, _Component); function DateFilter(props) { _classCallCheck(this, DateFilter); var _this = _possibleConstructorReturn(this, (DateFilter.__proto__ || Object.getPrototypeOf(DateFilter)).call(this, props)); _this.dateComparators = _this.props.dateComparators || legalComparators; _this.filter = _this.filter.bind(_this); _this.onChangeComparator = _this.onChangeComparator.bind(_this); return _this; } _createClass(DateFilter, [{ key: 'setDefaultDate', value: function setDefaultDate() { var defaultDate = ''; var defaultValue = this.props.defaultValue; if (defaultValue && defaultValue.date) { // Set the appropriate format for the input type=date, i.e. "YYYY-MM-DD" defaultDate = dateParser(new Date(defaultValue.date)); } return defaultDate; } }, { key: 'onChangeComparator', value: function onChangeComparator(event) { var date = this.refs.inputDate.value; var comparator = event.target.value; if (date === '') { return; } date = new Date(date); this.props.filterHandler({ date: date, comparator: comparator }, _Const2.default.FILTER_TYPE.DATE); } }, { key: 'getComparatorOptions', value: function getComparatorOptions() { var optionTags = []; optionTags.push(_react2.default.createElement('option', { key: '-1' })); for (var i = 0; i < this.dateComparators.length; i++) { optionTags.push(_react2.default.createElement( 'option', { key: i, value: this.dateComparators[i] }, this.dateComparators[i] )); } return optionTags; } }, { key: 'filter', value: function filter(event) { var comparator = this.refs.dateFilterComparator.value; var dateValue = event.target.value; if (dateValue) { this.props.filterHandler({ date: new Date(dateValue), comparator: comparator }, _Const2.default.FILTER_TYPE.DATE); } else { this.props.filterHandler(null, _Const2.default.FILTER_TYPE.DATE); } } }, { key: 'cleanFiltered', value: function cleanFiltered() { var value = this.setDefaultDate(); var comparator = this.props.defaultValue ? this.props.defaultValue.comparator : ''; this.setState({ isPlaceholderSelected: value === '' }); this.refs.dateFilterComparator.value = comparator; this.refs.inputDate.value = value; this.props.filterHandler({ date: new Date(value), comparator: comparator }, _Const2.default.FILTER_TYPE.DATE); } }, { key: 'applyFilter', value: function applyFilter(filterDateObj) { var date = filterDateObj.date, comparator = filterDateObj.comparator; this.setState({ isPlaceholderSelected: date === '' }); this.refs.dateFilterComparator.value = comparator; this.refs.inputDate.value = dateParser(date); this.props.filterHandler({ date: date, comparator: comparator }, _Const2.default.FILTER_TYPE.DATE); } }, { key: 'componentDidMount', value: function componentDidMount() { var comparator = this.refs.dateFilterComparator.value; var dateValue = this.refs.inputDate.value; if (comparator && dateValue) { this.props.filterHandler({ date: new Date(dateValue), comparator: comparator }, _Const2.default.FILTER_TYPE.DATE); } } }, { key: 'render', value: function render() { var defaultValue = this.props.defaultValue; return _react2.default.createElement( 'div', { className: 'filter date-filter' }, _react2.default.createElement( 'select', { ref: 'dateFilterComparator', className: 'date-filter-comparator form-control', onChange: this.onChangeComparator, defaultValue: defaultValue ? defaultValue.comparator : '' }, this.getComparatorOptions() ), _react2.default.createElement('input', { ref: 'inputDate', className: 'filter date-filter-input form-control', type: 'date', onChange: this.filter, defaultValue: this.setDefaultDate() }) ); } }]); return DateFilter; }(_react.Component); DateFilter.propTypes = { filterHandler: _react.PropTypes.func.isRequired, defaultValue: _react.PropTypes.shape({ date: _react.PropTypes.object, comparator: _react.PropTypes.oneOf(legalComparators) }), /* eslint consistent-return: 0 */ dateComparators: function dateComparators(props, propName) { if (!props[propName]) { return; } for (var i = 0; i < props[propName].length; i++) { var comparatorIsValid = false; for (var j = 0; j < legalComparators.length; j++) { if (legalComparators[j] === props[propName][i]) { comparatorIsValid = true; break; } } if (!comparatorIsValid) { return new Error('Date comparator provided is not supported.\n Use only ' + legalComparators); } } }, columnName: _react.PropTypes.string }; var _default = DateFilter; exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(legalComparators, 'legalComparators', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Date.js'); __REACT_HOT_LOADER__.register(dateParser, 'dateParser', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Date.js'); __REACT_HOT_LOADER__.register(DateFilter, 'DateFilter', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Date.js'); __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Date.js'); }(); ; /***/ }, /* 193 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var TextFilter = function (_Component) { _inherits(TextFilter, _Component); function TextFilter(props) { _classCallCheck(this, TextFilter); var _this = _possibleConstructorReturn(this, (TextFilter.__proto__ || Object.getPrototypeOf(TextFilter)).call(this, props)); _this.filter = _this.filter.bind(_this); _this.timeout = null; return _this; } _createClass(TextFilter, [{ key: 'filter', value: function filter(event) { var _this2 = this; if (this.timeout) { clearTimeout(this.timeout); } var filterValue = event.target.value; this.timeout = setTimeout(function () { _this2.props.filterHandler(filterValue, _Const2.default.FILTER_TYPE.TEXT); }, this.props.delay); } }, { key: 'cleanFiltered', value: function cleanFiltered() { var value = this.props.defaultValue ? this.props.defaultValue : ''; this.refs.inputText.value = value; this.props.filterHandler(value, _Const2.default.FILTER_TYPE.TEXT); } }, { key: 'applyFilter', value: function applyFilter(filterText) { this.refs.inputText.value = filterText; this.props.filterHandler(filterText, _Const2.default.FILTER_TYPE.TEXT); } }, { key: 'componentDidMount', value: function componentDidMount() { var defaultValue = this.refs.inputText.value; if (defaultValue) { this.props.filterHandler(defaultValue, _Const2.default.FILTER_TYPE.TEXT); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { clearTimeout(this.timeout); } }, { key: 'render', value: function render() { var _props = this.props, placeholder = _props.placeholder, columnName = _props.columnName, defaultValue = _props.defaultValue; return _react2.default.createElement('input', { ref: 'inputText', className: 'filter text-filter form-control', type: 'text', onChange: this.filter, placeholder: placeholder || 'Enter ' + columnName + '...', defaultValue: defaultValue ? defaultValue : '' }); } }]); return TextFilter; }(_react.Component); TextFilter.propTypes = { filterHandler: _react.PropTypes.func.isRequired, defaultValue: _react.PropTypes.string, delay: _react.PropTypes.number, placeholder: _react.PropTypes.string, columnName: _react.PropTypes.string }; TextFilter.defaultProps = { delay: _Const2.default.FILTER_DELAY }; var _default = TextFilter; exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(TextFilter, 'TextFilter', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Text.js'); __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Text.js'); }(); ; /***/ }, /* 194 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var RegexFilter = function (_Component) { _inherits(RegexFilter, _Component); function RegexFilter(props) { _classCallCheck(this, RegexFilter); var _this = _possibleConstructorReturn(this, (RegexFilter.__proto__ || Object.getPrototypeOf(RegexFilter)).call(this, props)); _this.filter = _this.filter.bind(_this); _this.timeout = null; return _this; } _createClass(RegexFilter, [{ key: 'filter', value: function filter(event) { var _this2 = this; if (this.timeout) { clearTimeout(this.timeout); } var filterValue = event.target.value; this.timeout = setTimeout(function () { _this2.props.filterHandler(filterValue, _Const2.default.FILTER_TYPE.REGEX); }, this.props.delay); } }, { key: 'cleanFiltered', value: function cleanFiltered() { var value = this.props.defaultValue ? this.props.defaultValue : ''; this.refs.inputText.value = value; this.props.filterHandler(value, _Const2.default.FILTER_TYPE.TEXT); } }, { key: 'applyFilter', value: function applyFilter(filterRegx) { this.refs.inputText.value = filterRegx; this.props.filterHandler(filterRegx, _Const2.default.FILTER_TYPE.REGEX); } }, { key: 'componentDidMount', value: function componentDidMount() { var value = this.refs.inputText.value; if (value) { this.props.filterHandler(value, _Const2.default.FILTER_TYPE.REGEX); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { clearTimeout(this.timeout); } }, { key: 'render', value: function render() { var _props = this.props, defaultValue = _props.defaultValue, placeholder = _props.placeholder, columnName = _props.columnName; return _react2.default.createElement('input', { ref: 'inputText', className: 'filter text-filter form-control', type: 'text', onChange: this.filter, placeholder: placeholder || 'Enter Regex for ' + columnName + '...', defaultValue: defaultValue ? defaultValue : '' }); } }]); return RegexFilter; }(_react.Component); RegexFilter.propTypes = { filterHandler: _react.PropTypes.func.isRequired, defaultValue: _react.PropTypes.string, delay: _react.PropTypes.number, placeholder: _react.PropTypes.string, columnName: _react.PropTypes.string }; RegexFilter.defaultProps = { delay: _Const2.default.FILTER_DELAY }; var _default = RegexFilter; exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(RegexFilter, 'RegexFilter', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Regex.js'); __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Regex.js'); }(); ; /***/ }, /* 195 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var SelectFilter = function (_Component) { _inherits(SelectFilter, _Component); function SelectFilter(props) { _classCallCheck(this, SelectFilter); var _this = _possibleConstructorReturn(this, (SelectFilter.__proto__ || Object.getPrototypeOf(SelectFilter)).call(this, props)); _this.filter = _this.filter.bind(_this); _this.state = { isPlaceholderSelected: _this.props.defaultValue === undefined || !_this.props.options.hasOwnProperty(_this.props.defaultValue) }; return _this; } _createClass(SelectFilter, [{ key: 'filter', value: function filter(event) { var value = event.target.value; this.setState({ isPlaceholderSelected: value === '' }); this.props.filterHandler(value, _Const2.default.FILTER_TYPE.SELECT); } }, { key: 'cleanFiltered', value: function cleanFiltered() { var value = this.props.defaultValue !== undefined ? this.props.defaultValue : ''; this.setState({ isPlaceholderSelected: value === '' }); this.refs.selectInput.value = value; this.props.filterHandler(value, _Const2.default.FILTER_TYPE.SELECT); } }, { key: 'applyFilter', value: function applyFilter(filterOption) { filterOption = filterOption + ''; this.setState({ isPlaceholderSelected: filterOption === '' }); this.refs.selectInput.value = filterOption; this.props.filterHandler(filterOption, _Const2.default.FILTER_TYPE.SELECT); } }, { key: 'getOptions', value: function getOptions() { var optionTags = []; var _props = this.props, options = _props.options, placeholder = _props.placeholder, columnName = _props.columnName, selectText = _props.selectText; var selectTextValue = selectText !== undefined ? selectText : 'Select'; optionTags.push(_react2.default.createElement( 'option', { key: '-1', value: '' }, placeholder || selectTextValue + ' ' + columnName + '...' )); Object.keys(options).map(function (key) { optionTags.push(_react2.default.createElement( 'option', { key: key, value: key }, options[key] + '' )); }); return optionTags; } }, { key: 'componentDidMount', value: function componentDidMount() { var value = this.refs.selectInput.value; if (value) { this.props.filterHandler(value, _Const2.default.FILTER_TYPE.SELECT); } } }, { key: 'render', value: function render() { var selectClass = (0, _classnames2.default)('filter', 'select-filter', 'form-control', { 'placeholder-selected': this.state.isPlaceholderSelected }); return _react2.default.createElement( 'select', { ref: 'selectInput', className: selectClass, onChange: this.filter, defaultValue: this.props.defaultValue !== undefined ? this.props.defaultValue : '' }, this.getOptions() ); } }]); return SelectFilter; }(_react.Component); SelectFilter.propTypes = { filterHandler: _react.PropTypes.func.isRequired, options: _react.PropTypes.object.isRequired, placeholder: _react.PropTypes.string, columnName: _react.PropTypes.string }; var _default = SelectFilter; exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(SelectFilter, 'SelectFilter', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Select.js'); __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Select.js'); }(); ; /***/ }, /* 196 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var legalComparators = ['=', '>', '>=', '<', '<=', '!=']; var NumberFilter = function (_Component) { _inherits(NumberFilter, _Component); function NumberFilter(props) { _classCallCheck(this, NumberFilter); var _this = _possibleConstructorReturn(this, (NumberFilter.__proto__ || Object.getPrototypeOf(NumberFilter)).call(this, props)); _this.numberComparators = _this.props.numberComparators || legalComparators; _this.timeout = null; _this.state = { isPlaceholderSelected: _this.props.defaultValue === undefined || _this.props.defaultValue.number === undefined || _this.props.options && _this.props.options.indexOf(_this.props.defaultValue.number) === -1 }; _this.onChangeNumber = _this.onChangeNumber.bind(_this); _this.onChangeNumberSet = _this.onChangeNumberSet.bind(_this); _this.onChangeComparator = _this.onChangeComparator.bind(_this); return _this; } _createClass(NumberFilter, [{ key: 'onChangeNumber', value: function onChangeNumber(event) { var _this2 = this; var comparator = this.refs.numberFilterComparator.value; if (comparator === '') { return; } if (this.timeout) { clearTimeout(this.timeout); } var filterValue = event.target.value; this.timeout = setTimeout(function () { _this2.props.filterHandler({ number: filterValue, comparator: comparator }, _Const2.default.FILTER_TYPE.NUMBER); }, this.props.delay); } }, { key: 'onChangeNumberSet', value: function onChangeNumberSet(event) { var comparator = this.refs.numberFilterComparator.value; var value = event.target.value; this.setState({ isPlaceholderSelected: value === '' }); if (comparator === '') { return; } this.props.filterHandler({ number: value, comparator: comparator }, _Const2.default.FILTER_TYPE.NUMBER); } }, { key: 'onChangeComparator', value: function onChangeComparator(event) { var value = this.refs.numberFilter.value; var comparator = event.target.value; if (value === '') { return; } this.props.filterHandler({ number: value, comparator: comparator }, _Const2.default.FILTER_TYPE.NUMBER); } }, { key: 'cleanFiltered', value: function cleanFiltered() { var value = this.props.defaultValue ? this.props.defaultValue.number : ''; var comparator = this.props.defaultValue ? this.props.defaultValue.comparator : ''; this.setState({ isPlaceholderSelected: value === '' }); this.refs.numberFilterComparator.value = comparator; this.refs.numberFilter.value = value; this.props.filterHandler({ number: value, comparator: comparator }, _Const2.default.FILTER_TYPE.NUMBER); } }, { key: 'applyFilter', value: function applyFilter(filterObj) { var number = filterObj.number, comparator = filterObj.comparator; this.setState({ isPlaceholderSelected: number === '' }); this.refs.numberFilterComparator.value = comparator; this.refs.numberFilter.value = number; this.props.filterHandler({ number: number, comparator: comparator }, _Const2.default.FILTER_TYPE.NUMBER); } }, { key: 'getComparatorOptions', value: function getComparatorOptions() { var optionTags = []; optionTags.push(_react2.default.createElement('option', { key: '-1' })); for (var i = 0; i < this.numberComparators.length; i++) { optionTags.push(_react2.default.createElement( 'option', { key: i, value: this.numberComparators[i] }, this.numberComparators[i] )); } return optionTags; } }, { key: 'getNumberOptions', value: function getNumberOptions() { var optionTags = []; var options = this.props.options; optionTags.push(_react2.default.createElement( 'option', { key: '-1', value: '' }, this.props.placeholder || 'Select ' + this.props.columnName + '...' )); for (var i = 0; i < options.length; i++) { optionTags.push(_react2.default.createElement( 'option', { key: i, value: options[i] }, options[i] )); } return optionTags; } }, { key: 'componentDidMount', value: function componentDidMount() { var comparator = this.refs.numberFilterComparator.value; var number = this.refs.numberFilter.value; if (comparator && number) { this.props.filterHandler({ number: number, comparator: comparator }, _Const2.default.FILTER_TYPE.NUMBER); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { clearTimeout(this.timeout); } }, { key: 'render', value: function render() { var selectClass = (0, _classnames2.default)('select-filter', 'number-filter-input', 'form-control', { 'placeholder-selected': this.state.isPlaceholderSelected }); return _react2.default.createElement( 'div', { className: 'filter number-filter' }, _react2.default.createElement( 'select', { ref: 'numberFilterComparator', className: 'number-filter-comparator form-control', onChange: this.onChangeComparator, defaultValue: this.props.defaultValue ? this.props.defaultValue.comparator : '' }, this.getComparatorOptions() ), this.props.options ? _react2.default.createElement( 'select', { ref: 'numberFilter', className: selectClass, onChange: this.onChangeNumberSet, defaultValue: this.props.defaultValue ? this.props.defaultValue.number : '' }, this.getNumberOptions() ) : _react2.default.createElement('input', { ref: 'numberFilter', type: 'number', className: 'number-filter-input form-control', placeholder: this.props.placeholder || 'Enter ' + this.props.columnName + '...', onChange: this.onChangeNumber, defaultValue: this.props.defaultValue ? this.props.defaultValue.number : '' }) ); } }]); return NumberFilter; }(_react.Component); NumberFilter.propTypes = { filterHandler: _react.PropTypes.func.isRequired, options: _react.PropTypes.arrayOf(_react.PropTypes.number), defaultValue: _react.PropTypes.shape({ number: _react.PropTypes.number, comparator: _react.PropTypes.oneOf(legalComparators) }), delay: _react.PropTypes.number, /* eslint consistent-return: 0 */ numberComparators: function numberComparators(props, propName) { if (!props[propName]) { return; } for (var i = 0; i < props[propName].length; i++) { var comparatorIsValid = false; for (var j = 0; j < legalComparators.length; j++) { if (legalComparators[j] === props[propName][i]) { comparatorIsValid = true; break; } } if (!comparatorIsValid) { return new Error('Number comparator provided is not supported.\n Use only ' + legalComparators); } } }, placeholder: _react.PropTypes.string, columnName: _react.PropTypes.string }; NumberFilter.defaultProps = { delay: _Const2.default.FILTER_DELAY }; var _default = NumberFilter; exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(legalComparators, 'legalComparators', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Number.js'); __REACT_HOT_LOADER__.register(NumberFilter, 'NumberFilter', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Number.js'); __REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Number.js'); }(); ; /***/ } /******/ ]) }); ; //# sourceMappingURL=react-bootstrap-table.js.map
/** * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'codesnippet', 'sq', { button: 'Shto kod copëze', codeContents: 'Përmbajtja e kodit', emptySnippetError: 'A code snippet cannot be empty.', // MISSING language: 'Gjuha', title: 'Code snippet', // MISSING pathName: 'code snippet' // MISSING } );
'use strict'; self.console || (self.console = { 'log': function() {} }); addEventListener('message', function(e) { if (e.data) { try { importScripts('../' + e.data); } catch (e) { var lineNumber = e.lineNumber, message = (lineNumber == null ? '' : (lineNumber + ': ')) + e.message; self._ = { 'VERSION': message }; } postMessage(_.VERSION); } }, false);
// kmMat4Transpose (function () { // Kernel configuration var kernelConfig = { kernelName: "kmMat4Transpose", kernelInit: init, kernelCleanup: cleanup, kernelSimd: simd, kernelNonSimd: nonSimd, kernelIterations: 10000 }; // Hook up to the harness benchmarks.add(new Benchmark(kernelConfig)); // Benchmark data, initialization and kernel functions var T1 = new cc.kmMat4(); var T2 = new cc.kmMat4(); var T1x4 = new cc.kmMat4(); var T2x4 = new cc.kmMat4(); function equals(A, B) { for (var i = 0; i < 16; ++i) { if (A[i] != B[i]) return false; } return true; } function printMatrix(matrix) { print('--------matrix----------'); for (var r = 0; r < 4; ++r) { var str = ""; var ri = r*4; for (var c = 0; c < 4; ++c) { var value = matrix[ri + c]; str += " " + value.toFixed(2); } print(str); } } function init() { T1.mat [0] = 0; T1.mat[1] = 1; T1.mat[2] = 2; T1.mat[3] = 3; T1.mat [4] = -1; T1.mat[5] = -2; T1.mat[6] = -3; T1.mat[7] = -4; T1.mat [8] = 0; T1.mat[9] = 0; T1.mat[10] = 2; T1.mat[11] = 3; T1.mat [12] = -1; T1.mat[13] = -2; T1.mat[14] = 0; T1.mat[15] = -4; T1x4.mat [0] = 0; T1x4.mat[1] = 1; T1x4.mat[2] = 2; T1x4.mat[3] = 3; T1x4.mat [4] = -1; T1x4.mat[5] = -2; T1x4.mat[6] = -3; T1x4.mat[7] = -4; T1x4.mat [8] = 0; T1x4.mat[9] = 0; T1x4.mat[10] = 2; T1x4.mat[11] = 3; T1x4.mat [12] = -1; T1x4.mat[13] = -2; T1x4.mat[14] = 0; T1x4.mat[15] = -4; nonSimd(1); //printMatrix(T2.mat); simd(1); //printMatrix(T2x4.mat); return equals(T1.mat, T1x4.mat) && equals(T2.mat, T2x4.mat); } function cleanup() { return init(); // Sanity checking before and after are the same } function nonSimd(n) { for (var i = 0; i < n; i++) { T2 = T1.transpose(); //T1.transpose(); } } function simd(n) { for (var i = 0; i < n; i++) { T2x4 = T1x4.transposeSIMD(); //T1x4.transposeSIMD(); } } } ());
angular.module('ionicApp', ['ionic']) .controller('MainCtrl', function ($scope) { $scope.settingsList = [ { text: "Wireless", checked: true }, { text: "GPS", checked: false }, { text: "Bluetooth", checked: false } ]; $scope.pushNotificationChange = function () { console.log('Push Notification Change', $scope.pushNotification.checked); }; $scope.pushNotification = { checked: true }; $scope.emailNotification = 'Subscribed'; });
/* This file is part of Ext JS 4 Copyright (c) 2011 Sencha Inc Contact: http://www.sencha.com/contact GNU General Public License Usage This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. */ /** * Ukrainian translations for ExtJS (UTF-8 encoding) * * Original translation by zlatko * 3 October 2007 * * Updated by dev.ashevchuk@gmail.com * 01.09.2009 */ Ext.onReady(function(){ if(Ext.Updater){ Ext.Updater.defaults.indicatorText = '<div class="loading-indicator">Завантаження...</div>'; } if(Ext.view.View){ Ext.view.View.prototype.emptyText = "<Порожньо>"; } if(Ext.grid.Panel){ Ext.grid.Panel.prototype.ddText = "{0} обраних рядків"; } if(Ext.TabPanelItem){ Ext.TabPanelItem.prototype.closeText = "Закрити цю вкладку"; } if(Ext.form.field.Base){ Ext.form.field.Base.prototype.invalidText = "Хибне значення"; } if(Ext.LoadMask){ Ext.LoadMask.prototype.msg = "Завантаження..."; } if(Ext.Date) { Ext.Date.monthNames = [ "Січень", "Лютий", "Березень", "Квітень", "Травень", "Червень", "Липень", "Серпень", "Вересень", "Жовтень", "Листопад", "Грудень" ]; Ext.Date.dayNames = [ "Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П’ятниця", "Субота" ]; } if(Ext.MessageBox){ Ext.MessageBox.buttonText = { ok : "OK", cancel : "Відміна", yes : "Так", no : "Ні" }; } if(Ext.util.Format){ Ext.apply(Ext.util.Format, { thousandSeparator: '.', decimalSeparator: ',', currencySign: '\u20b4', // Ukranian Hryvnia dateFormat: 'd.m.Y' }); } if(Ext.picker.Date){ Ext.apply(Ext.picker.Date.prototype, { todayText : "Сьогодні", minText : "Ця дата меньша за мінімальну допустиму дату", maxText : "Ця дата більша за максимальну допустиму дату", disabledDaysText : "", disabledDatesText : "", monthNames : Ext.Date.monthNames, dayNames : Ext.Date.dayNames, nextText : 'Наступний місяць (Control+Вправо)', prevText : 'Попередній місяць (Control+Вліво)', monthYearText : 'Вибір місяця (Control+Вверх/Вниз для вибору року)', todayTip : "{0} (Пробіл)", format : "d.m.y", startDay : 1 }); } if(Ext.picker.Month) { Ext.apply(Ext.picker.Month.prototype, { okText : "&#160;OK&#160;", cancelText : "Відміна" }); } if(Ext.toolbar.Paging){ Ext.apply(Ext.PagingToolbar.prototype, { beforePageText : "Сторінка", afterPageText : "з {0}", firstText : "Перша сторінка", prevText : "Попередня сторінка", nextText : "Наступна сторінка", lastText : "Остання сторінка", refreshText : "Освіжити", displayMsg : "Відображення записів з {0} по {1}, всього {2}", emptyMsg : 'Дані для відображення відсутні' }); } if(Ext.form.field.Text){ Ext.apply(Ext.form.field.Text.prototype, { minLengthText : "Мінімальна довжина цього поля {0}", maxLengthText : "Максимальна довжина цього поля {0}", blankText : "Це поле є обов’язковим для заповнення", regexText : "", emptyText : null }); } if(Ext.form.field.Number){ Ext.apply(Ext.form.field.Number.prototype, { minText : "Значення у цьому полі не може бути меньше {0}", maxText : "Значення у цьому полі не може бути більше {0}", nanText : "{0} не є числом" }); } if(Ext.form.field.Date){ Ext.apply(Ext.form.field.Date.prototype, { disabledDaysText : "Не доступно", disabledDatesText : "Не доступно", minText : "Дата у цьому полі повинна бути більша {0}", maxText : "Дата у цьому полі повинна бути меньша {0}", invalidText : "{0} хибна дата - дата повинна бути вказана у форматі {1}", format : "d.m.y" }); } if(Ext.form.field.ComboBox){ Ext.apply(Ext.form.field.ComboBox.prototype, { loadingText : "Завантаження...", valueNotFoundText : undefined }); } if(Ext.form.field.VTypes){ Ext.apply(Ext.form.field.VTypes, { emailText : 'Це поле повинно містити адресу електронної пошти у форматі "user@example.com"', urlText : 'Це поле повинно містити URL у форматі "http:/'+'/www.example.com"', alphaText : 'Це поле повинно містити виключно латинські літери та символ підкреслення "_"', alphanumText : 'Це поле повинно містити виключно латинські літери, цифри та символ підкреслення "_"' }); } if(Ext.form.field.HtmlEditor){ Ext.apply(Ext.form.field.HtmlEditor.prototype, { createLinkText : 'Будь-ласка введіть адресу:', buttonTips : { bold : { title: 'Напівжирний (Ctrl+B)', text: 'Зробити напівжирним виділений текст.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, italic : { title: 'Курсив (Ctrl+I)', text: 'Зробити курсивом виділений текст.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, underline : { title: 'Підкреслений (Ctrl+U)', text: 'Зробити підкресленим виділений текст.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, increasefontsize : { title: 'Збільшити розмір', text: 'Збільшити розмір шрифта.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, decreasefontsize : { title: 'Зменьшити розмір', text: 'Зменьшити розмір шрифта.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, backcolor : { title: 'Заливка', text: 'Змінити колір фону для виділеного тексту або абзацу.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, forecolor : { title: 'Колір тексту', text: 'Змінити колір виділеного тексту або абзацу.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, justifyleft : { title: 'Вирівняти текст по лівому полю', text: 'Вирівнювання тексту по лівому полю.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, justifycenter : { title: 'Вирівняти текст по центру', text: 'Вирівнювання тексту по центру.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, justifyright : { title: 'Вирівняти текст по правому полю', text: 'Вирівнювання тексту по правому полю.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, insertunorderedlist : { title: 'Маркери', text: 'Почати маркований список.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, insertorderedlist : { title: 'Нумерація', text: 'Почати нумернований список.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, createlink : { title: 'Вставити гіперпосилання', text: 'Створення посилання із виділеного тексту.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, sourceedit : { title: 'Джерельний код', text: 'Режим редагування джерельного коду.', cls: Ext.baseCSSPrefix + 'html-editor-tip' } } }); } if(Ext.grid.header.Container){ Ext.apply(Ext.grid.header.Container.prototype, { sortAscText : "Сортувати по зростанню", sortDescText : "Сортувати по спаданню", lockText : "Закріпити стовпець", unlockText : "Відкріпити стовпець", columnsText : "Стовпці" }); } if(Ext.grid.PropertyColumnModel){ Ext.apply(Ext.grid.PropertyColumnModel.prototype, { nameText : "Назва", valueText : "Значення", dateFormat : "j.m.Y" }); } if(Ext.layout.BorderLayout && Ext.layout.BorderLayout.SplitRegion){ Ext.apply(Ext.layout.BorderLayout.SplitRegion.prototype, { splitTip : "Тягніть для зміни розміру.", collapsibleSplitTip : "Тягніть для зміни розміру. Подвійний клік сховає панель." }); } });
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; import { isString, CONST, isBlank } from 'angular2/src/facade/lang'; import { Injectable, Pipe } from 'angular2/core'; import { InvalidPipeArgumentException } from './invalid_pipe_argument_exception'; /** * Transforms text to lowercase. * * ### Example * * {@example core/pipes/ts/lowerupper_pipe/lowerupper_pipe_example.ts region='LowerUpperPipe'} */ export let LowerCasePipe = class { transform(value, args = null) { if (isBlank(value)) return value; if (!isString(value)) { throw new InvalidPipeArgumentException(LowerCasePipe, value); } return value.toLowerCase(); } }; LowerCasePipe = __decorate([ CONST(), Pipe({ name: 'lowercase' }), Injectable(), __metadata('design:paramtypes', []) ], LowerCasePipe);
export default function () { return { manipulateOptions(opts, parserOpts) { parserOpts.plugins.push("functionBind"); } }; }
d3.layout.histogram = function() { var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges; function histogram(data, i) { var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x; // Initialize the bins. while (++i < m) { bin = bins[i] = []; bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]); bin.y = 0; } // Fill the bins, ignoring values outside the range. i = -1; while(++i < n) { x = values[i]; if ((x >= range[0]) && (x <= range[1])) { bin = bins[d3.bisect(thresholds, x, 1, m) - 1]; bin.y += k; bin.push(data[i]); } } return bins; } // Specifies how to extract a value from the associated data. The default // value function is `Number`, which is equivalent to the identity function. histogram.value = function(x) { if (!arguments.length) return valuer; valuer = x; return histogram; }; // Specifies the range of the histogram. Values outside the specified range // will be ignored. The argument `x` may be specified either as a two-element // array representing the minimum and maximum value of the range, or as a // function that returns the range given the array of values and the current // index `i`. The default range is the extent (minimum and maximum) of the // values. histogram.range = function(x) { if (!arguments.length) return ranger; ranger = d3.functor(x); return histogram; }; // Specifies how to bin values in the histogram. The argument `x` may be // specified as a number, in which case the range of values will be split // uniformly into the given number of bins. Or, `x` may be an array of // threshold values, defining the bins; the specified array must contain the // rightmost (upper) value, thus specifying n + 1 values for n bins. Or, `x` // may be a function which is evaluated, being passed the range, the array of // values, and the current index `i`, returning an array of thresholds. The // default bin function will divide the values into uniform bins using // Sturges' formula. histogram.bins = function(x) { if (!arguments.length) return binner; binner = typeof x === "number" ? function(range) { return d3_layout_histogramBinFixed(range, x); } : d3.functor(x); return histogram; }; // Specifies whether the histogram's `y` value is a count (frequency) or a // probability (density). The default value is true. histogram.frequency = function(x) { if (!arguments.length) return frequency; frequency = !!x; return histogram; }; return histogram; }; function d3_layout_histogramBinSturges(range, values) { return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1)); } function d3_layout_histogramBinFixed(range, n) { var x = -1, b = +range[0], m = (range[1] - b) / n, f = []; while (++x <= n) f[x] = m * x + b; return f; } function d3_layout_histogramRange(values) { return [d3.min(values), d3.max(values)]; }
Ext.define('Ext.theme.cupertino.TitleBar', { override: 'Ext.TitleBar', config: { maxButtonWidth: '80%' } }); Ext.define('Ext.theme.device_base.util.PositionMap', { override: 'Ext.util.PositionMap', config: { minimumHeight: 50 } }); Ext.define('Ext.theme.device_base.dataview.List', { override: 'Ext.dataview.List', config: { itemHeight: 42 } }); Ext.define('Ext.theme.cupertino.dataview.List', { override: 'Ext.dataview.List', config: { itemHeight: 43 } }); Ext.define('Ext.theme.device_base.dataview.NestedList', { override: 'Ext.dataview.NestedList', config: { itemHeight: 47 } }); Ext.define('Ext.theme.cupertino.dataview.NestedList', { override: 'Ext.dataview.NestedList', config: { itemHeight: 43, useTitleAsBackText: true, updateTitleText: false } }); Ext.define('Ext.theme.device_base.grid.HeaderContainer', { override: 'Ext.grid.HeaderContainer', config: { height: 65 }, privates: { doUpdateSpacer: function() { var scrollable = this.getGrid().getScrollable(); this.element.setStyle('margin-right', scrollable.getScrollbarSize().width + 'px'); } } }); Ext.define('Ext.theme.device_base.grid.Grid', { override: 'Ext.grid.Grid', config: { itemHeight: 60 } }); Ext.define('Ext.theme.device_base.grid.plugin.SummaryRow', { override: 'Ext.grid.plugin.SummaryRow', config: { height: 32 } }); Ext.namespace('Ext.theme.is').Cupertino = true; Ext.theme.name = 'Cupertino';
/* This file is part of Ext JS 4 Copyright (c) 2011 Sencha Inc Contact: http://www.sencha.com/contact GNU General Public License Usage This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. */ Ext.define('Ext.tree.ViewDragZone', { extend: 'Ext.view.DragZone', isPreventDrag: function(e, record) { return (record.get('allowDrag') === false) || !!e.getTarget(this.view.expanderSelector); }, afterRepair: function() { var me = this, view = me.view, selectedRowCls = view.selectedItemCls, records = me.dragData.records, fly = Ext.fly; if (Ext.enableFx && me.repairHighlight) { // Roll through all records and highlight all the ones we attempted to drag. Ext.Array.forEach(records, function(record) { // anonymous fns below, don't hoist up unless below is wrapped in // a self-executing function passing in item. var item = view.getNode(record); // We must remove the selected row class before animating, because // the selected row class declares !important on its background-color. fly(item.firstChild).highlight(me.repairHighlightColor, { listeners: { beforeanimate: function() { if (view.isSelected(item)) { fly(item).removeCls(selectedRowCls); } }, afteranimate: function() { if (view.isSelected(item)) { fly(item).addCls(selectedRowCls); } } } }); }); } me.dragging = false; } });
// Generated by CoffeeScript 1.4.0 /* # # Opentip v2.3.0 # # More info at [www.opentip.org](http://www.opentip.org) # # Copyright (c) 2012, Matias Meno # Graphics by Tjandra Mayerhold # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # */ var Opentip, firstAdapter, i, position, vendors, _i, _len, _ref, __slice = [].slice, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }, __hasProp = {}.hasOwnProperty; Opentip = (function() { Opentip.prototype.STICKS_OUT_TOP = 1; Opentip.prototype.STICKS_OUT_BOTTOM = 2; Opentip.prototype.STICKS_OUT_LEFT = 1; Opentip.prototype.STICKS_OUT_RIGHT = 2; Opentip.prototype["class"] = { container: "opentip-container", opentip: "opentip", header: "ot-header", content: "ot-content", loadingIndicator: "ot-loading-indicator", close: "ot-close", goingToHide: "ot-going-to-hide", hidden: "ot-hidden", hiding: "ot-hiding", goingToShow: "ot-going-to-show", showing: "ot-showing", visible: "ot-visible", loading: "ot-loading", ajaxError: "ot-ajax-error", fixed: "ot-fixed", showEffectPrefix: "ot-show-effect-", hideEffectPrefix: "ot-hide-effect-", stylePrefix: "style-" }; function Opentip(element, content, title, options) { var elementsOpentips, hideTrigger, optionSources, prop, styleName, _i, _len, _ref, _ref1, _tmpStyle, _this = this; this.id = ++Opentip.lastId; this.debug("Creating Opentip."); Opentip.tips.push(this); this.adapter = Opentip.adapter; elementsOpentips = this.adapter.data(element, "opentips") || []; elementsOpentips.push(this); this.adapter.data(element, "opentips", elementsOpentips); this.triggerElement = this.adapter.wrap(element); if (this.triggerElement.length > 1) { throw new Error("You can't call Opentip on multiple elements."); } if (this.triggerElement.length < 1) { throw new Error("Invalid element."); } this.loaded = false; this.loading = false; this.visible = false; this.waitingToShow = false; this.waitingToHide = false; this.currentPosition = { left: 0, top: 0 }; this.dimensions = { width: 100, height: 50 }; this.content = ""; this.redraw = true; this.currentObservers = { showing: false, visible: false, hiding: false, hidden: false }; options = this.adapter.clone(options); if (typeof content === "object") { options = content; content = title = void 0; } else if (typeof title === "object") { options = title; title = void 0; } if (title != null) { options.title = title; } if (content != null) { this.setContent(content); } if (options["extends"] == null) { if (options.style != null) { options["extends"] = options.style; } else { options["extends"] = Opentip.defaultStyle; } } optionSources = [options]; _tmpStyle = options; while (_tmpStyle["extends"]) { styleName = _tmpStyle["extends"]; _tmpStyle = Opentip.styles[styleName]; if (_tmpStyle == null) { throw new Error("Invalid style: " + styleName); } optionSources.unshift(_tmpStyle); if (!((_tmpStyle["extends"] != null) || styleName === "standard")) { _tmpStyle["extends"] = "standard"; } } options = (_ref = this.adapter).extend.apply(_ref, [{}].concat(__slice.call(optionSources))); options.hideTriggers = (function() { var _i, _len, _ref1, _results; _ref1 = options.hideTriggers; _results = []; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { hideTrigger = _ref1[_i]; _results.push(hideTrigger); } return _results; })(); if (options.hideTrigger && options.hideTriggers.length === 0) { options.hideTriggers.push(options.hideTrigger); } _ref1 = ["tipJoint", "targetJoint", "stem"]; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { prop = _ref1[_i]; if (options[prop] && typeof options[prop] === "string") { options[prop] = new Opentip.Joint(options[prop]); } } if (options.ajax && (options.ajax === true || !options.ajax)) { if (this.adapter.tagName(this.triggerElement) === "A") { options.ajax = this.adapter.attr(this.triggerElement, "href"); } else { options.ajax = false; } } if (options.showOn === "click" && this.adapter.tagName(this.triggerElement) === "A") { this.adapter.observe(this.triggerElement, "click", function(e) { e.preventDefault(); e.stopPropagation(); return e.stopped = true; }); } if (options.target) { options.fixed = true; } if (options.stem === true) { options.stem = new Opentip.Joint(options.tipJoint); } if (options.target === true) { options.target = this.triggerElement; } else if (options.target) { options.target = this.adapter.wrap(options.target); } this.currentStem = options.stem; if (options.delay == null) { options.delay = options.showOn === "mouseover" ? 0.2 : 0; } if (options.targetJoint == null) { options.targetJoint = new Opentip.Joint(options.tipJoint).flip(); } this.showTriggers = []; this.showTriggersWhenVisible = []; this.hideTriggers = []; if (options.showOn && options.showOn !== "creation") { this.showTriggers.push({ element: this.triggerElement, event: options.showOn }); } this.options = options; this.adapter.domReady(function() { return _this._init(); }); } Opentip.prototype._init = function() { var hideOn, hideTrigger, hideTriggerElement, i, methodToBind, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2, _this = this; this._buildContainer(); _ref = this.options.hideTriggers; for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) { hideTrigger = _ref[i]; hideTriggerElement = null; hideOn = this.options.hideOn instanceof Array ? this.options.hideOn[i] : this.options.hideOn; if (typeof hideTrigger === "string") { switch (hideTrigger) { case "trigger": hideOn = hideOn || "mouseout"; hideTriggerElement = this.triggerElement; break; case "tip": hideOn = hideOn || "mouseover"; hideTriggerElement = this.container; break; case "target": hideOn = hideOn || "mouseover"; hideTriggerElement = this.options.target; break; case "closeButton": break; default: throw new Error("Unknown hide trigger: " + hideTrigger + "."); } } else { hideOn = hideOn || "mouseover"; hideTriggerElement = this.adapter.wrap(hideTrigger); } if (hideTriggerElement) { this.hideTriggers.push({ element: hideTriggerElement, event: hideOn, original: hideTrigger }); } } _ref1 = this.hideTriggers; for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { hideTrigger = _ref1[_j]; this.showTriggersWhenVisible.push({ element: hideTrigger.element, event: "mouseover" }); } this.bound = {}; _ref2 = ["prepareToShow", "prepareToHide", "show", "hide", "reposition"]; for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { methodToBind = _ref2[_k]; this.bound[methodToBind] = (function(methodToBind) { return function() { return _this[methodToBind].apply(_this, arguments); }; })(methodToBind); } this.activate(); if (this.options.showOn === "creation") { return this.prepareToShow(); } }; Opentip.prototype._buildContainer = function() { this.container = this.adapter.create("<div id=\"opentip-" + this.id + "\" class=\"" + this["class"].container + " " + this["class"].hidden + " " + this["class"].stylePrefix + this.options.className + "\"></div>"); this.adapter.css(this.container, { position: "absolute" }); if (this.options.ajax) { this.adapter.addClass(this.container, this["class"].loading); } if (this.options.fixed) { this.adapter.addClass(this.container, this["class"].fixed); } if (this.options.showEffect) { this.adapter.addClass(this.container, "" + this["class"].showEffectPrefix + this.options.showEffect); } if (this.options.hideEffect) { return this.adapter.addClass(this.container, "" + this["class"].hideEffectPrefix + this.options.hideEffect); } }; Opentip.prototype._buildElements = function() { var headerElement, titleElement; this.tooltipElement = this.adapter.create("<div class=\"" + this["class"].opentip + "\"><div class=\"" + this["class"].header + "\"></div><div class=\"" + this["class"].content + "\"></div></div>"); this.backgroundCanvas = this.adapter.wrap(document.createElement("canvas")); this.adapter.css(this.backgroundCanvas, { position: "absolute" }); if (typeof G_vmlCanvasManager !== "undefined" && G_vmlCanvasManager !== null) { G_vmlCanvasManager.initElement(this.adapter.unwrap(this.backgroundCanvas)); } headerElement = this.adapter.find(this.tooltipElement, "." + this["class"].header); if (this.options.title) { titleElement = this.adapter.create("<h1></h1>"); this.adapter.update(titleElement, this.options.title, this.options.escapeTitle); this.adapter.append(headerElement, titleElement); } if (this.options.ajax) { this.adapter.append(this.tooltipElement, this.adapter.create("<div class=\"" + this["class"].loadingIndicator + "\"><span>↻</span></div>")); } if (__indexOf.call(this.options.hideTriggers, "closeButton") >= 0) { this.closeButtonElement = this.adapter.create("<a href=\"javascript:undefined;\" class=\"" + this["class"].close + "\"><span>Close</span></a>"); this.adapter.append(headerElement, this.closeButtonElement); } this.adapter.append(this.container, this.backgroundCanvas); this.adapter.append(this.container, this.tooltipElement); return this.adapter.append(document.body, this.container); }; Opentip.prototype.setContent = function(content) { this.content = content; if (this.visible) { return this._updateElementContent(); } }; Opentip.prototype._updateElementContent = function() { var contentDiv; contentDiv = this.adapter.find(this.container, "." + this["class"].content); if (contentDiv != null) { if (typeof this.content === "function") { this.debug("Executing content function."); this.content = this.content(this); } this.adapter.update(contentDiv, this.content, this.options.escapeContent); } this._storeAndLockDimensions(); return this.reposition(); }; Opentip.prototype._storeAndLockDimensions = function() { var prevDimension; prevDimension = this.dimensions; this.adapter.css(this.container, { width: "auto", left: "0px", top: "0px" }); this.dimensions = this.adapter.dimensions(this.container); this.dimensions.width += 1; this.adapter.css(this.container, { width: "" + this.dimensions.width + "px", top: "" + this.currentPosition.top + "px", left: "" + this.currentPosition.left + "px" }); if (!this._dimensionsEqual(this.dimensions, prevDimension)) { this.redraw = true; return this._draw(); } }; Opentip.prototype.activate = function() { return this._setupObservers("-showing", "-visible", "hidden", "hiding"); }; Opentip.prototype.deactivate = function() { this.debug("Deactivating tooltip."); return this.hide(); }; Opentip.prototype._setupObservers = function() { var observeOrStop, removeObserver, state, states, trigger, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1, _ref2, _this = this; states = 1 <= arguments.length ? __slice.call(arguments, 0) : []; for (_i = 0, _len = states.length; _i < _len; _i++) { state = states[_i]; removeObserver = false; if (state.charAt(0) === "-") { removeObserver = true; state = state.substr(1); } if (this.currentObservers[state] === !removeObserver) { continue; } this.currentObservers[state] = !removeObserver; observeOrStop = function() { var args, _ref, _ref1; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; if (removeObserver) { return (_ref = _this.adapter).stopObserving.apply(_ref, args); } else { return (_ref1 = _this.adapter).observe.apply(_ref1, args); } }; switch (state) { case "showing": _ref = this.hideTriggers; for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) { trigger = _ref[_j]; observeOrStop(trigger.element, trigger.event, this.bound.prepareToHide); } observeOrStop((document.onresize != null ? document : window), "resize", this.bound.reposition); observeOrStop(window, "scroll", this.bound.reposition); break; case "visible": _ref1 = this.showTriggersWhenVisible; for (_k = 0, _len2 = _ref1.length; _k < _len2; _k++) { trigger = _ref1[_k]; observeOrStop(trigger.element, trigger.event, this.bound.prepareToShow); } break; case "hiding": _ref2 = this.showTriggers; for (_l = 0, _len3 = _ref2.length; _l < _len3; _l++) { trigger = _ref2[_l]; observeOrStop(trigger.element, trigger.event, this.bound.prepareToShow); } break; case "hidden": break; default: throw new Error("Unknown state: " + state); } } return null; }; Opentip.prototype.prepareToShow = function() { this._abortHiding(); this._abortShowing(); if (this.visible) { return; } this.debug("Showing in " + this.options.delay + "s."); if (this.options.group) { Opentip._abortShowingGroup(this.options.group, this); } this.preparingToShow = true; this._setupObservers("-hidden", "-hiding", "showing"); this._followMousePosition(); this.reposition(); return this._showTimeoutId = this.setTimeout(this.bound.show, this.options.delay || 0); }; Opentip.prototype.show = function() { var _this = this; this._abortHiding(); if (this.visible) { return; } this._clearTimeouts(); if (!this._triggerElementExists()) { return this.deactivate(); } this.debug("Showing now."); if (this.options.group) { Opentip._hideGroup(this.options.group, this); } this.visible = true; this.preparingToShow = false; if (this.tooltipElement == null) { this._buildElements(); } this._updateElementContent(); if (this.options.ajax && (!this.loaded || !this.options.ajaxCache)) { this._loadAjax(); } this._searchAndActivateCloseButtons(); this._startEnsureTriggerElement(); this.adapter.css(this.container, { zIndex: Opentip.lastZIndex++ }); this._setupObservers("-hidden", "-hiding", "-showing", "-visible", "showing", "visible"); this.reposition(); this.adapter.removeClass(this.container, this["class"].hiding); this.adapter.removeClass(this.container, this["class"].hidden); this.adapter.addClass(this.container, this["class"].goingToShow); this.setCss3Style(this.container, { transitionDuration: "0s" }); this.defer(function() { var delay; _this.adapter.removeClass(_this.container, _this["class"].goingToShow); _this.adapter.addClass(_this.container, _this["class"].showing); delay = 0; if (_this.options.showEffect && _this.options.showEffectDuration) { delay = _this.options.showEffectDuration; } _this.setCss3Style(_this.container, { transitionDuration: "" + delay + "s" }); _this._visibilityStateTimeoutId = _this.setTimeout(function() { _this.adapter.removeClass(_this.container, _this["class"].showing); return _this.adapter.addClass(_this.container, _this["class"].visible); }, delay); return _this._activateFirstInput(); }); return this._draw(); }; Opentip.prototype._abortShowing = function() { if (this.preparingToShow) { this.debug("Aborting showing."); this._clearTimeouts(); this._stopFollowingMousePosition(); this.preparingToShow = false; return this._setupObservers("-showing", "-visible", "hiding", "hidden"); } }; Opentip.prototype.prepareToHide = function() { this._abortShowing(); this._abortHiding(); if (!this.visible) { return; } this.debug("Hiding in " + this.options.hideDelay + "s"); this.preparingToHide = true; this._setupObservers("-showing", "visible", "-hidden", "hiding"); return this._hideTimeoutId = this.setTimeout(this.bound.hide, this.options.hideDelay); }; Opentip.prototype.hide = function() { var _this = this; this._abortShowing(); if (!this.visible) { return; } this._clearTimeouts(); this.debug("Hiding!"); this.visible = false; this.preparingToHide = false; this._stopEnsureTriggerElement(); this._setupObservers("-showing", "-visible", "-hiding", "-hidden", "hiding", "hidden"); if (!this.options.fixed) { this._stopFollowingMousePosition(); } this.adapter.removeClass(this.container, this["class"].visible); this.adapter.removeClass(this.container, this["class"].showing); this.adapter.addClass(this.container, this["class"].goingToHide); this.setCss3Style(this.container, { transitionDuration: "0s" }); return this.defer(function() { var hideDelay; _this.adapter.removeClass(_this.container, _this["class"].goingToHide); _this.adapter.addClass(_this.container, _this["class"].hiding); hideDelay = 0; if (_this.options.hideEffect && _this.options.hideEffectDuration) { hideDelay = _this.options.hideEffectDuration; } _this.setCss3Style(_this.container, { transitionDuration: "" + hideDelay + "s" }); return _this._visibilityStateTimeoutId = _this.setTimeout(function() { _this.adapter.removeClass(_this.container, _this["class"].hiding); _this.adapter.addClass(_this.container, _this["class"].hidden); return _this.setCss3Style(_this.container, { transitionDuration: "0s" }); }, hideDelay); }); }; Opentip.prototype._abortHiding = function() { if (this.preparingToHide) { this.debug("Aborting hiding."); this._clearTimeouts(); this.preparingToHide = false; return this._setupObservers("-hiding", "showing", "visible"); } }; Opentip.prototype.reposition = function(e) { var position, stem, _ref, _this = this; if (e == null) { e = this.lastEvent; } position = this.getPosition(e); if (position == null) { return; } stem = this.options.stem; if (this.options.containInViewport) { _ref = this._ensureViewportContainment(e, position), position = _ref.position, stem = _ref.stem; } if (this._positionsEqual(position, this.currentPosition)) { return; } if (!(!this.options.stem || stem.eql(this.currentStem))) { this.redraw = true; } this.currentPosition = position; this.currentStem = stem; this._draw(); this.adapter.css(this.container, { left: "" + position.left + "px", top: "" + position.top + "px" }); return this.defer(function() { var rawContainer, redrawFix; rawContainer = _this.adapter.unwrap(_this.container); rawContainer.style.visibility = "hidden"; redrawFix = rawContainer.offsetHeight; return rawContainer.style.visibility = "visible"; }); }; Opentip.prototype.getPosition = function(e, tipJoint, targetJoint, stem) { var additionalHorizontal, additionalVertical, mousePosition, offsetDistance, position, stemLength, targetDimensions, targetPosition, unwrappedTarget, _ref; if (tipJoint == null) { tipJoint = this.options.tipJoint; } if (targetJoint == null) { targetJoint = this.options.targetJoint; } position = {}; if (this.options.target) { targetPosition = this.adapter.offset(this.options.target); targetDimensions = this.adapter.dimensions(this.options.target); position = targetPosition; if (targetJoint.right) { unwrappedTarget = this.adapter.unwrap(this.options.target); if (unwrappedTarget.getBoundingClientRect != null) { position.left = unwrappedTarget.getBoundingClientRect().right + ((_ref = window.pageXOffset) != null ? _ref : document.body.scrollLeft); } else { position.left += targetDimensions.width; } } else if (targetJoint.center) { position.left += Math.round(targetDimensions.width / 2); } if (targetJoint.bottom) { position.top += targetDimensions.height; } else if (targetJoint.middle) { position.top += Math.round(targetDimensions.height / 2); } if (this.options.borderWidth) { if (this.options.tipJoint.left) { position.left += this.options.borderWidth; } if (this.options.tipJoint.right) { position.left -= this.options.borderWidth; } if (this.options.tipJoint.top) { position.top += this.options.borderWidth; } else if (this.options.tipJoint.bottom) { position.top -= this.options.borderWidth; } } } else { if (e != null) { this.lastEvent = e; } mousePosition = this.adapter.mousePosition(e); if (mousePosition == null) { return; } position = { top: mousePosition.y, left: mousePosition.x }; } if (this.options.autoOffset) { stemLength = this.options.stem ? this.options.stemLength : 0; offsetDistance = stemLength && this.options.fixed ? 2 : 10; additionalHorizontal = tipJoint.middle && !this.options.fixed ? 15 : 0; additionalVertical = tipJoint.center && !this.options.fixed ? 15 : 0; if (tipJoint.right) { position.left -= offsetDistance + additionalHorizontal; } else if (tipJoint.left) { position.left += offsetDistance + additionalHorizontal; } if (tipJoint.bottom) { position.top -= offsetDistance + additionalVertical; } else if (tipJoint.top) { position.top += offsetDistance + additionalVertical; } if (stemLength) { if (stem == null) { stem = this.options.stem; } if (stem.right) { position.left -= stemLength; } else if (stem.left) { position.left += stemLength; } if (stem.bottom) { position.top -= stemLength; } else if (stem.top) { position.top += stemLength; } } } position.left += this.options.offset[0]; position.top += this.options.offset[1]; if (tipJoint.right) { position.left -= this.dimensions.width; } else if (tipJoint.center) { position.left -= Math.round(this.dimensions.width / 2); } if (tipJoint.bottom) { position.top -= this.dimensions.height; } else if (tipJoint.middle) { position.top -= Math.round(this.dimensions.height / 2); } return position; }; Opentip.prototype._ensureViewportContainment = function(e, position) { var needsRepositioning, newSticksOut, originals, revertedX, revertedY, scrollOffset, stem, sticksOut, targetJoint, tipJoint, viewportDimensions, viewportPosition; stem = this.options.stem; originals = { position: position, stem: stem }; if (!(this.visible && position)) { return originals; } sticksOut = this._sticksOut(position); if (!(sticksOut[0] || sticksOut[1])) { return originals; } tipJoint = new Opentip.Joint(this.options.tipJoint); if (this.options.targetJoint) { targetJoint = new Opentip.Joint(this.options.targetJoint); } scrollOffset = this.adapter.scrollOffset(); viewportDimensions = this.adapter.viewportDimensions(); viewportPosition = [position.left - scrollOffset[0], position.top - scrollOffset[1]]; needsRepositioning = false; if (viewportDimensions.width >= this.dimensions.width) { if (sticksOut[0]) { needsRepositioning = true; switch (sticksOut[0]) { case this.STICKS_OUT_LEFT: tipJoint.setHorizontal("left"); if (this.options.targetJoint) { targetJoint.setHorizontal("right"); } break; case this.STICKS_OUT_RIGHT: tipJoint.setHorizontal("right"); if (this.options.targetJoint) { targetJoint.setHorizontal("left"); } } } } if (viewportDimensions.height >= this.dimensions.height) { if (sticksOut[1]) { needsRepositioning = true; switch (sticksOut[1]) { case this.STICKS_OUT_TOP: tipJoint.setVertical("top"); if (this.options.targetJoint) { targetJoint.setVertical("bottom"); } break; case this.STICKS_OUT_BOTTOM: tipJoint.setVertical("bottom"); if (this.options.targetJoint) { targetJoint.setVertical("top"); } } } } if (!needsRepositioning) { return originals; } if (this.options.stem) { stem = tipJoint; } position = this.getPosition(e, tipJoint, targetJoint, stem); newSticksOut = this._sticksOut(position); revertedX = false; revertedY = false; if (newSticksOut[0] && (newSticksOut[0] !== sticksOut[0])) { revertedX = true; tipJoint.setHorizontal(this.options.tipJoint.horizontal); if (this.options.targetJoint) { targetJoint.setHorizontal(this.options.targetJoint.horizontal); } } if (newSticksOut[1] && (newSticksOut[1] !== sticksOut[1])) { revertedY = true; tipJoint.setVertical(this.options.tipJoint.vertical); if (this.options.targetJoint) { targetJoint.setVertical(this.options.targetJoint.vertical); } } if (revertedX && revertedY) { return originals; } if (revertedX || revertedY) { if (this.options.stem) { stem = tipJoint; } position = this.getPosition(e, tipJoint, targetJoint, stem); } return { position: position, stem: stem }; }; Opentip.prototype._sticksOut = function(position) { var positionOffset, scrollOffset, sticksOut, viewportDimensions; scrollOffset = this.adapter.scrollOffset(); viewportDimensions = this.adapter.viewportDimensions(); positionOffset = [position.left - scrollOffset[0], position.top - scrollOffset[1]]; sticksOut = [false, false]; if (positionOffset[0] < 0) { sticksOut[0] = this.STICKS_OUT_LEFT; } else if (positionOffset[0] + this.dimensions.width > viewportDimensions.width) { sticksOut[0] = this.STICKS_OUT_RIGHT; } if (positionOffset[1] < 0) { sticksOut[1] = this.STICKS_OUT_TOP; } else if (positionOffset[1] + this.dimensions.height > viewportDimensions.height) { sticksOut[1] = this.STICKS_OUT_BOTTOM; } return sticksOut; }; Opentip.prototype._draw = function() { var backgroundCanvas, bulge, canvasDimensions, canvasPosition, closeButton, closeButtonInner, closeButtonOuter, ctx, drawCorner, drawLine, hb, position, stemBase, stemLength, _i, _len, _ref, _ref1, _ref2, _this = this; if (!(this.backgroundCanvas && this.redraw)) { return; } this.debug("Drawing background."); this.redraw = false; if (this.currentStem) { _ref = ["top", "right", "bottom", "left"]; for (_i = 0, _len = _ref.length; _i < _len; _i++) { position = _ref[_i]; this.adapter.removeClass(this.container, "stem-" + position); } this.adapter.addClass(this.container, "stem-" + this.currentStem.horizontal); this.adapter.addClass(this.container, "stem-" + this.currentStem.vertical); } closeButtonInner = [0, 0]; closeButtonOuter = [0, 0]; if (__indexOf.call(this.options.hideTriggers, "closeButton") >= 0) { closeButton = new Opentip.Joint(((_ref1 = this.currentStem) != null ? _ref1.toString() : void 0) === "top right" ? "top left" : "top right"); closeButtonInner = [this.options.closeButtonRadius + this.options.closeButtonOffset[0], this.options.closeButtonRadius + this.options.closeButtonOffset[1]]; closeButtonOuter = [this.options.closeButtonRadius - this.options.closeButtonOffset[0], this.options.closeButtonRadius - this.options.closeButtonOffset[1]]; } canvasDimensions = this.adapter.clone(this.dimensions); canvasPosition = [0, 0]; if (this.options.borderWidth) { canvasDimensions.width += this.options.borderWidth * 2; canvasDimensions.height += this.options.borderWidth * 2; canvasPosition[0] -= this.options.borderWidth; canvasPosition[1] -= this.options.borderWidth; } if (this.options.shadow) { canvasDimensions.width += this.options.shadowBlur * 2; canvasDimensions.width += Math.max(0, this.options.shadowOffset[0] - this.options.shadowBlur * 2); canvasDimensions.height += this.options.shadowBlur * 2; canvasDimensions.height += Math.max(0, this.options.shadowOffset[1] - this.options.shadowBlur * 2); canvasPosition[0] -= Math.max(0, this.options.shadowBlur - this.options.shadowOffset[0]); canvasPosition[1] -= Math.max(0, this.options.shadowBlur - this.options.shadowOffset[1]); } bulge = { left: 0, right: 0, top: 0, bottom: 0 }; if (this.currentStem) { if (this.currentStem.left) { bulge.left = this.options.stemLength; } else if (this.currentStem.right) { bulge.right = this.options.stemLength; } if (this.currentStem.top) { bulge.top = this.options.stemLength; } else if (this.currentStem.bottom) { bulge.bottom = this.options.stemLength; } } if (closeButton) { if (closeButton.left) { bulge.left = Math.max(bulge.left, closeButtonOuter[0]); } else if (closeButton.right) { bulge.right = Math.max(bulge.right, closeButtonOuter[0]); } if (closeButton.top) { bulge.top = Math.max(bulge.top, closeButtonOuter[1]); } else if (closeButton.bottom) { bulge.bottom = Math.max(bulge.bottom, closeButtonOuter[1]); } } canvasDimensions.width += bulge.left + bulge.right; canvasDimensions.height += bulge.top + bulge.bottom; canvasPosition[0] -= bulge.left; canvasPosition[1] -= bulge.top; if (this.currentStem && this.options.borderWidth) { _ref2 = this._getPathStemMeasures(this.options.stemBase, this.options.stemLength, this.options.borderWidth), stemLength = _ref2.stemLength, stemBase = _ref2.stemBase; } backgroundCanvas = this.adapter.unwrap(this.backgroundCanvas); backgroundCanvas.width = canvasDimensions.width; backgroundCanvas.height = canvasDimensions.height; this.adapter.css(this.backgroundCanvas, { width: "" + backgroundCanvas.width + "px", height: "" + backgroundCanvas.height + "px", left: "" + canvasPosition[0] + "px", top: "" + canvasPosition[1] + "px" }); ctx = backgroundCanvas.getContext("2d"); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, backgroundCanvas.width, backgroundCanvas.height); ctx.beginPath(); ctx.fillStyle = this._getColor(ctx, this.dimensions, this.options.background, this.options.backgroundGradientHorizontal); ctx.lineJoin = "miter"; ctx.miterLimit = 500; hb = this.options.borderWidth / 2; if (this.options.borderWidth) { ctx.strokeStyle = this.options.borderColor; ctx.lineWidth = this.options.borderWidth; } else { stemLength = this.options.stemLength; stemBase = this.options.stemBase; } if (stemBase == null) { stemBase = 0; } drawLine = function(length, stem, first) { if (first) { ctx.moveTo(Math.max(stemBase, _this.options.borderRadius, closeButtonInner[0]) + 1 - hb, -hb); } if (stem) { ctx.lineTo(length / 2 - stemBase / 2, -hb); ctx.lineTo(length / 2, -stemLength - hb); return ctx.lineTo(length / 2 + stemBase / 2, -hb); } }; drawCorner = function(stem, closeButton, i) { var angle1, angle2, innerWidth, offset; if (stem) { ctx.lineTo(-stemBase + hb, 0 - hb); ctx.lineTo(stemLength + hb, -stemLength - hb); return ctx.lineTo(hb, stemBase - hb); } else if (closeButton) { offset = _this.options.closeButtonOffset; innerWidth = closeButtonInner[0]; if (i % 2 !== 0) { offset = [offset[1], offset[0]]; innerWidth = closeButtonInner[1]; } angle1 = Math.acos(offset[1] / _this.options.closeButtonRadius); angle2 = Math.acos(offset[0] / _this.options.closeButtonRadius); ctx.lineTo(-innerWidth + hb, -hb); return ctx.arc(hb - offset[0], -hb + offset[1], _this.options.closeButtonRadius, -(Math.PI / 2 + angle1), angle2, false); } else { ctx.lineTo(-_this.options.borderRadius + hb, -hb); return ctx.quadraticCurveTo(hb, -hb, hb, _this.options.borderRadius - hb); } }; ctx.translate(-canvasPosition[0], -canvasPosition[1]); ctx.save(); (function() { var cornerStem, i, lineLength, lineStem, positionIdx, positionX, positionY, rotation, _j, _ref3, _results; _results = []; for (i = _j = 0, _ref3 = Opentip.positions.length / 2; 0 <= _ref3 ? _j < _ref3 : _j > _ref3; i = 0 <= _ref3 ? ++_j : --_j) { positionIdx = i * 2; positionX = i === 0 || i === 3 ? 0 : _this.dimensions.width; positionY = i < 2 ? 0 : _this.dimensions.height; rotation = (Math.PI / 2) * i; lineLength = i % 2 === 0 ? _this.dimensions.width : _this.dimensions.height; lineStem = new Opentip.Joint(Opentip.positions[positionIdx]); cornerStem = new Opentip.Joint(Opentip.positions[positionIdx + 1]); ctx.save(); ctx.translate(positionX, positionY); ctx.rotate(rotation); drawLine(lineLength, lineStem.eql(_this.currentStem), i === 0); ctx.translate(lineLength, 0); drawCorner(cornerStem.eql(_this.currentStem), cornerStem.eql(closeButton), i); _results.push(ctx.restore()); } return _results; })(); ctx.closePath(); ctx.save(); if (this.options.shadow) { ctx.shadowColor = this.options.shadowColor; ctx.shadowBlur = this.options.shadowBlur; ctx.shadowOffsetX = this.options.shadowOffset[0]; ctx.shadowOffsetY = this.options.shadowOffset[1]; } ctx.fill(); ctx.restore(); if (this.options.borderWidth) { ctx.stroke(); } ctx.restore(); if (closeButton) { return (function() { var crossCenter, crossHeight, crossWidth, hcs, linkCenter; crossWidth = crossHeight = _this.options.closeButtonRadius * 2; if (closeButton.toString() === "top right") { linkCenter = [_this.dimensions.width - _this.options.closeButtonOffset[0], _this.options.closeButtonOffset[1]]; crossCenter = [linkCenter[0] + hb, linkCenter[1] - hb]; } else { linkCenter = [_this.options.closeButtonOffset[0], _this.options.closeButtonOffset[1]]; crossCenter = [linkCenter[0] - hb, linkCenter[1] - hb]; } ctx.translate(crossCenter[0], crossCenter[1]); hcs = _this.options.closeButtonCrossSize / 2; ctx.save(); ctx.beginPath(); ctx.strokeStyle = _this.options.closeButtonCrossColor; ctx.lineWidth = _this.options.closeButtonCrossLineWidth; ctx.lineCap = "round"; ctx.moveTo(-hcs, -hcs); ctx.lineTo(hcs, hcs); ctx.stroke(); ctx.beginPath(); ctx.moveTo(hcs, -hcs); ctx.lineTo(-hcs, hcs); ctx.stroke(); ctx.restore(); return _this.adapter.css(_this.closeButtonElement, { left: "" + (linkCenter[0] - hcs - _this.options.closeButtonLinkOverscan) + "px", top: "" + (linkCenter[1] - hcs - _this.options.closeButtonLinkOverscan) + "px", width: "" + (_this.options.closeButtonCrossSize + _this.options.closeButtonLinkOverscan * 2) + "px", height: "" + (_this.options.closeButtonCrossSize + _this.options.closeButtonLinkOverscan * 2) + "px" }); })(); } }; Opentip.prototype._getPathStemMeasures = function(outerStemBase, outerStemLength, borderWidth) { var angle, distanceBetweenTips, halfAngle, hb, rhombusSide, stemBase, stemLength; hb = borderWidth / 2; halfAngle = Math.atan((outerStemBase / 2) / outerStemLength); angle = halfAngle * 2; rhombusSide = hb / Math.sin(angle); distanceBetweenTips = 2 * rhombusSide * Math.cos(halfAngle); stemLength = hb + outerStemLength - distanceBetweenTips; if (stemLength < 0) { throw new Error("Sorry but your stemLength / stemBase ratio is strange."); } stemBase = (Math.tan(halfAngle) * stemLength) * 2; return { stemLength: stemLength, stemBase: stemBase }; }; Opentip.prototype._getColor = function(ctx, dimensions, color, horizontal) { var colorStop, gradient, i, _i, _len; if (horizontal == null) { horizontal = false; } if (typeof color === "string") { return color; } if (horizontal) { gradient = ctx.createLinearGradient(0, 0, dimensions.width, 0); } else { gradient = ctx.createLinearGradient(0, 0, 0, dimensions.height); } for (i = _i = 0, _len = color.length; _i < _len; i = ++_i) { colorStop = color[i]; gradient.addColorStop(colorStop[0], colorStop[1]); } return gradient; }; Opentip.prototype._searchAndActivateCloseButtons = function() { var element, _i, _len, _ref; _ref = this.adapter.findAll(this.container, "." + this["class"].close); for (_i = 0, _len = _ref.length; _i < _len; _i++) { element = _ref[_i]; this.hideTriggers.push({ element: this.adapter.wrap(element), event: "click" }); } if (this.currentObservers.showing) { this._setupObservers("-showing", "showing"); } if (this.currentObservers.visible) { return this._setupObservers("-visible", "visible"); } }; Opentip.prototype._activateFirstInput = function() { var input; input = this.adapter.unwrap(this.adapter.find(this.container, "input, textarea")); return input != null ? typeof input.focus === "function" ? input.focus() : void 0 : void 0; }; Opentip.prototype._followMousePosition = function() { if (!this.options.fixed) { return this.adapter.observe(document.body, "mousemove", this.bound.reposition); } }; Opentip.prototype._stopFollowingMousePosition = function() { if (!this.options.fixed) { return this.adapter.stopObserving(document.body, "mousemove", this.bound.reposition); } }; Opentip.prototype._clearShowTimeout = function() { return clearTimeout(this._showTimeoutId); }; Opentip.prototype._clearHideTimeout = function() { return clearTimeout(this._hideTimeoutId); }; Opentip.prototype._clearTimeouts = function() { clearTimeout(this._visibilityStateTimeoutId); this._clearShowTimeout(); return this._clearHideTimeout(); }; Opentip.prototype._triggerElementExists = function() { var el; el = this.adapter.unwrap(this.triggerElement); while (el.parentNode) { if (el.parentNode.tagName === "BODY") { return true; } el = el.parentNode; } return false; }; Opentip.prototype._loadAjax = function() { var _this = this; if (this.loading) { return; } this.loaded = false; this.loading = true; this.adapter.addClass(this.container, this["class"].loading); this.setContent(""); this.debug("Loading content from " + this.options.ajax); return this.adapter.ajax({ url: this.options.ajax, method: this.options.ajaxMethod, onSuccess: function(responseText) { _this.debug("Loading successful."); _this.adapter.removeClass(_this.container, _this["class"].loading); return _this.setContent(responseText); }, onError: function(error) { var message; message = _this.options.ajaxErrorMessage; _this.debug(message, error); _this.setContent(message); return _this.adapter.addClass(_this.container, _this["class"].ajaxError); }, onComplete: function() { _this.adapter.removeClass(_this.container, _this["class"].loading); _this.loading = false; _this.loaded = true; _this._searchAndActivateCloseButtons(); _this._activateFirstInput(); return _this.reposition(); } }); }; Opentip.prototype._ensureTriggerElement = function() { if (!this._triggerElementExists()) { this.deactivate(); return this._stopEnsureTriggerElement(); } }; Opentip.prototype._ensureTriggerElementInterval = 1000; Opentip.prototype._startEnsureTriggerElement = function() { var _this = this; return this._ensureTriggerElementTimeoutId = setInterval((function() { return _this._ensureTriggerElement(); }), this._ensureTriggerElementInterval); }; Opentip.prototype._stopEnsureTriggerElement = function() { return clearInterval(this._ensureTriggerElementTimeoutId); }; return Opentip; })(); vendors = ["khtml", "ms", "o", "moz", "webkit"]; Opentip.prototype.setCss3Style = function(element, styles) { var prop, value, vendor, vendorProp, _results; element = this.adapter.unwrap(element); _results = []; for (prop in styles) { if (!__hasProp.call(styles, prop)) continue; value = styles[prop]; if (element.style[prop] != null) { _results.push(element.style[prop] = value); } else { _results.push((function() { var _i, _len, _results1; _results1 = []; for (_i = 0, _len = vendors.length; _i < _len; _i++) { vendor = vendors[_i]; vendorProp = "" + (this.ucfirst(vendor)) + (this.ucfirst(prop)); if (element.style[vendorProp] != null) { _results1.push(element.style[vendorProp] = value); } else { _results1.push(void 0); } } return _results1; }).call(this)); } } return _results; }; Opentip.prototype.defer = function(func) { return setTimeout(func, 0); }; Opentip.prototype.setTimeout = function(func, seconds) { return setTimeout(func, seconds ? seconds * 1000 : 0); }; Opentip.prototype.ucfirst = function(string) { if (string == null) { return ""; } return string.charAt(0).toUpperCase() + string.slice(1); }; Opentip.prototype.dasherize = function(string) { return string.replace(/([A-Z])/g, function(_, character) { return "-" + (character.toLowerCase()); }); }; Opentip.Joint = (function() { function Joint(pointerString) { if (pointerString == null) { return; } if (pointerString instanceof Opentip.Joint) { pointerString = pointerString.toString(); } this.set(pointerString); this; } Joint.prototype.set = function(string) { string = string.toLowerCase(); this.setHorizontal(string); this.setVertical(string); return this; }; Joint.prototype.setHorizontal = function(string) { var i, valid, _i, _j, _len, _len1, _results; valid = ["left", "center", "right"]; for (_i = 0, _len = valid.length; _i < _len; _i++) { i = valid[_i]; if (~string.indexOf(i)) { this.horizontal = i.toLowerCase(); } } if (this.horizontal == null) { this.horizontal = "center"; } _results = []; for (_j = 0, _len1 = valid.length; _j < _len1; _j++) { i = valid[_j]; _results.push(this[i] = this.horizontal === i ? i : void 0); } return _results; }; Joint.prototype.setVertical = function(string) { var i, valid, _i, _j, _len, _len1, _results; valid = ["top", "middle", "bottom"]; for (_i = 0, _len = valid.length; _i < _len; _i++) { i = valid[_i]; if (~string.indexOf(i)) { this.vertical = i.toLowerCase(); } } if (this.vertical == null) { this.vertical = "middle"; } _results = []; for (_j = 0, _len1 = valid.length; _j < _len1; _j++) { i = valid[_j]; _results.push(this[i] = this.vertical === i ? i : void 0); } return _results; }; Joint.prototype.eql = function(pointer) { return (pointer != null) && this.horizontal === pointer.horizontal && this.vertical === pointer.vertical; }; Joint.prototype.flip = function() { var flippedIndex, positionIdx; positionIdx = Opentip.position[this.toString(true)]; flippedIndex = (positionIdx + 4) % 8; this.set(Opentip.positions[flippedIndex]); return this; }; Joint.prototype.toString = function(camelized) { var horizontal, vertical; if (camelized == null) { camelized = false; } vertical = this.vertical === "middle" ? "" : this.vertical; horizontal = this.horizontal === "center" ? "" : this.horizontal; if (vertical && horizontal) { if (camelized) { horizontal = Opentip.prototype.ucfirst(horizontal); } else { horizontal = " " + horizontal; } } return "" + vertical + horizontal; }; return Joint; })(); Opentip.prototype._positionsEqual = function(posA, posB) { return (posA != null) && (posB != null) && posA.left === posB.left && posA.top === posB.top; }; Opentip.prototype._dimensionsEqual = function(dimA, dimB) { return (dimA != null) && (dimB != null) && dimA.width === dimB.width && dimA.height === dimB.height; }; Opentip.prototype.debug = function() { var args; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; if (Opentip.debug && ((typeof console !== "undefined" && console !== null ? console.debug : void 0) != null)) { args.unshift("#" + this.id + " |"); return console.debug.apply(console, args); } }; Opentip.findElements = function() { var adapter, content, element, optionName, optionValue, options, _i, _len, _ref, _results; adapter = Opentip.adapter; _ref = adapter.findAll(document.body, "[data-ot]"); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { element = _ref[_i]; options = {}; content = adapter.data(element, "ot"); if (content === "" || content === "true" || content === "yes") { content = adapter.attr(element, "title"); adapter.attr(element, "title", ""); } content = content || ""; for (optionName in Opentip.styles.standard) { optionValue = adapter.data(element, "ot" + (Opentip.prototype.ucfirst(optionName))); if (optionValue != null) { if (optionValue === "yes" || optionValue === "true" || optionValue === "on") { optionValue = true; } else if (optionValue === "no" || optionValue === "false" || optionValue === "off") { optionValue = false; } options[optionName] = optionValue; } } _results.push(new Opentip(element, content, options)); } return _results; }; Opentip.version = "2.3.0"; Opentip.debug = false; Opentip.lastId = 0; Opentip.lastZIndex = 100; Opentip.tips = []; Opentip._abortShowingGroup = function(group, originatingOpentip) { var opentip, _i, _len, _ref, _results; _ref = Opentip.tips; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { opentip = _ref[_i]; if (opentip !== originatingOpentip && opentip.options.group === group) { _results.push(opentip._abortShowing()); } else { _results.push(void 0); } } return _results; }; Opentip._hideGroup = function(group, originatingOpentip) { var opentip, _i, _len, _ref, _results; _ref = Opentip.tips; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { opentip = _ref[_i]; if (opentip !== originatingOpentip && opentip.options.group === group) { _results.push(opentip.hide()); } else { _results.push(void 0); } } return _results; }; Opentip.adapters = {}; Opentip.adapter = null; firstAdapter = true; Opentip.addAdapter = function(adapter) { Opentip.adapters[adapter.name] = adapter; if (firstAdapter) { Opentip.adapter = adapter; adapter.domReady(Opentip.findElements); return firstAdapter = false; } }; Opentip.positions = ["top", "topRight", "right", "bottomRight", "bottom", "bottomLeft", "left", "topLeft"]; Opentip.position = {}; _ref = Opentip.positions; for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) { position = _ref[i]; Opentip.position[position] = i; } Opentip.styles = { standard: { "extends": null, title: void 0, escapeTitle: true, escapeContent: false, className: "standard", stem: true, delay: null, hideDelay: 0.1, fixed: false, showOn: "mouseover", hideTrigger: "trigger", hideTriggers: [], hideOn: null, offset: [0, 0], containInViewport: true, autoOffset: true, showEffect: "appear", hideEffect: "fade", showEffectDuration: 0.3, hideEffectDuration: 0.2, stemLength: 5, stemBase: 8, tipJoint: "top left", target: null, targetJoint: null, ajax: false, ajaxMethod: "GET", ajaxCache: true, ajaxErrorMessage: "There was a problem downloading the content.", group: null, style: null, background: "#fff18f", backgroundGradientHorizontal: false, closeButtonOffset: [5, 5], closeButtonRadius: 7, closeButtonCrossSize: 4, closeButtonCrossColor: "#d2c35b", closeButtonCrossLineWidth: 1.5, closeButtonLinkOverscan: 6, borderRadius: 5, borderWidth: 1, borderColor: "#f2e37b", shadow: true, shadowBlur: 10, shadowOffset: [3, 3], shadowColor: "rgba(0, 0, 0, 0.1)" }, glass: { "extends": "standard", className: "glass", background: [[0, "rgba(252, 252, 252, 0.8)"], [0.5, "rgba(255, 255, 255, 0.8)"], [0.5, "rgba(250, 250, 250, 0.9)"], [1, "rgba(245, 245, 245, 0.9)"]], borderColor: "#eee", closeButtonCrossColor: "rgba(0, 0, 0, 0.2)", borderRadius: 15, closeButtonRadius: 10, closeButtonOffset: [8, 8] }, dark: { "extends": "standard", className: "dark", borderRadius: 13, borderColor: "#444", closeButtonCrossColor: "rgba(240, 240, 240, 1)", shadowColor: "rgba(0, 0, 0, 0.3)", shadowOffset: [2, 2], background: [[0, "rgba(30, 30, 30, 0.7)"], [0.5, "rgba(30, 30, 30, 0.8)"], [0.5, "rgba(10, 10, 10, 0.8)"], [1, "rgba(10, 10, 10, 0.9)"]] }, alert: { "extends": "standard", className: "alert", borderRadius: 1, borderColor: "#AE0D11", closeButtonCrossColor: "rgba(255, 255, 255, 1)", shadowColor: "rgba(0, 0, 0, 0.3)", shadowOffset: [2, 2], background: [[0, "rgba(203, 15, 19, 0.7)"], [0.5, "rgba(203, 15, 19, 0.8)"], [0.5, "rgba(189, 14, 18, 0.8)"], [1, "rgba(179, 14, 17, 0.9)"]] } }; Opentip.defaultStyle = "standard"; if (typeof module !== "undefined" && module !== null) { module.exports = Opentip; } else { window.Opentip = Opentip; }
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "fm", "em" ], "DAY": [ "s\u00f6ndag", "m\u00e5ndag", "tisdag", "onsdag", "torsdag", "fredag", "l\u00f6rdag" ], "MONTH": [ "januari", "februari", "mars", "april", "maj", "juni", "juli", "augusti", "september", "oktober", "november", "december" ], "SHORTDAY": [ "s\u00f6n", "m\u00e5n", "tis", "ons", "tors", "fre", "l\u00f6r" ], "SHORTMONTH": [ "jan.", "feb.", "mars", "apr.", "maj", "juni", "juli", "aug.", "sep.", "okt.", "nov.", "dec." ], "fullDate": "EEEE d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y HH:mm:ss", "mediumDate": "d MMM y", "mediumTime": "HH:mm:ss", "short": "y-MM-dd HH:mm", "shortDate": "y-MM-dd", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "kr", "DECIMAL_SEP": ",", "GROUP_SEP": "\u00a0", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a0\u00a4", "posPre": "", "posSuf": "\u00a0\u00a4" } ] }, "id": "sv-se", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ /** * For already absolute URLs, returns what is passed in. * For relative URLs, converts them to absolute ones. */ exports.makeAbsolute = function makeAbsolute(url) { var anchorEl = document.createElement('a'); anchorEl.href = url; return anchorEl.href; };
/** * Given Xcode project and path, iterate over all build configurations * and execute func with HEADER_SEARCH_PATHS from current section * * We cannot use builtin addToHeaderSearchPaths method since react-native init does not * use $(TARGET_NAME) for PRODUCT_NAME, but sets it manually so that method will skip * that target. * * To workaround that issue and make it more bullet-proof for different names, * we iterate over all configurations and look if React is already there. If it is, * we assume we want to modify that section either * * Important: That function mutates `buildSettings` and it's not pure thus you should * not rely on its return value */ module.exports = function headerSearchPathIter(project, func) { const config = project.pbxXCBuildConfigurationSection(); Object .keys(config) .filter(ref => ref.indexOf('_comment') === -1) .forEach(ref => { const buildSettings = config[ref].buildSettings; const shouldVisitBuildSettings = ( Array.isArray(buildSettings.HEADER_SEARCH_PATHS) ? buildSettings.HEADER_SEARCH_PATHS : [] ) .filter(path => path.indexOf('react-native/React/**')) .length > 0; if (shouldVisitBuildSettings) { buildSettings.HEADER_SEARCH_PATHS = func(buildSettings.HEADER_SEARCH_PATHS); } }); };
/*! * # Semantic UI - Checkbox * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { "use strict"; $.fn.checkbox = function(parameters) { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var settings = $.extend(true, {}, $.fn.checkbox.settings, parameters), className = settings.className, namespace = settings.namespace, selector = settings.selector, error = settings.error, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, $module = $(this), $label = $(this).children(selector.label), $input = $(this).children(selector.input), input = $input[0], initialLoad = false, shortcutPressed = false, instance = $module.data(moduleNamespace), observer, element = this, module ; module = { initialize: function() { module.verbose('Initializing checkbox', settings); module.create.label(); module.bind.events(); module.set.tabbable(); module.hide.input(); module.observeChanges(); module.instantiate(); module.setup(); }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, module) ; }, destroy: function() { module.verbose('Destroying module'); module.unbind.events(); module.show.input(); $module.removeData(moduleNamespace); }, fix: { reference: function() { if( $module.is(selector.input) ) { module.debug('Behavior called on <input> adjusting invoked element'); $module = $module.closest(selector.checkbox); module.refresh(); } } }, setup: function() { module.set.initialLoad(); if( module.is.indeterminate() ) { module.debug('Initial value is indeterminate'); module.indeterminate(); } else if( module.is.checked() ) { module.debug('Initial value is checked'); module.check(); } else { module.debug('Initial value is unchecked'); module.uncheck(); } module.remove.initialLoad(); }, refresh: function() { $label = $module.children(selector.label); $input = $module.children(selector.input); input = $input[0]; }, hide: { input: function() { module.verbose('Modfying <input> z-index to be unselectable'); $input.addClass(className.hidden); } }, show: { input: function() { module.verbose('Modfying <input> z-index to be selectable'); $input.removeClass(className.hidden); } }, observeChanges: function() { if('MutationObserver' in window) { observer = new MutationObserver(function(mutations) { module.debug('DOM tree modified, updating selector cache'); module.refresh(); }); observer.observe(element, { childList : true, subtree : true }); module.debug('Setting up mutation observer', observer); } }, attachEvents: function(selector, event) { var $element = $(selector) ; event = $.isFunction(module[event]) ? module[event] : module.toggle ; if($element.length > 0) { module.debug('Attaching checkbox events to element', selector, event); $element .on('click' + eventNamespace, event) ; } else { module.error(error.notFound); } }, event: { click: function(event) { var $target = $(event.target) ; if( $target.is(selector.input) ) { module.verbose('Using default check action on initialized checkbox'); return; } if( $target.is(selector.link) ) { module.debug('Clicking link inside checkbox, skipping toggle'); return; } module.toggle(); $input.focus(); event.preventDefault(); }, keydown: function(event) { var key = event.which, keyCode = { enter : 13, space : 32, escape : 27 } ; if(key == keyCode.escape) { module.verbose('Escape key pressed blurring field'); $input.blur(); shortcutPressed = true; } else if(!event.ctrlKey && ( key == keyCode.space || key == keyCode.enter) ) { module.verbose('Enter/space key pressed, toggling checkbox'); module.toggle(); shortcutPressed = true; } else { shortcutPressed = false; } }, keyup: function(event) { if(shortcutPressed) { event.preventDefault(); } } }, check: function() { if( !module.should.allowCheck() ) { return; } module.debug('Checking checkbox', $input); module.set.checked(); if( !module.should.ignoreCallbacks() ) { settings.onChecked.call(input); settings.onChange.call(input); } }, uncheck: function() { if( !module.should.allowUncheck() ) { return; } module.debug('Unchecking checkbox'); module.set.unchecked(); if( !module.should.ignoreCallbacks() ) { settings.onUnchecked.call(input); settings.onChange.call(input); } }, indeterminate: function() { if( module.should.allowIndeterminate() ) { module.debug('Checkbox is already indeterminate'); return; } module.debug('Making checkbox indeterminate'); module.set.indeterminate(); if( !module.should.ignoreCallbacks() ) { settings.onIndeterminate.call(input); settings.onChange.call(input); } }, determinate: function() { if( module.should.allowDeterminate() ) { module.debug('Checkbox is already determinate'); return; } module.debug('Making checkbox determinate'); module.set.determinate(); if( !module.should.ignoreCallbacks() ) { settings.onDeterminate.call(input); settings.onChange.call(input); } }, enable: function() { if( module.is.enabled() ) { module.debug('Checkbox is already enabled'); return; } module.debug('Enabling checkbox'); module.set.enabled(); settings.onEnable.call(input); }, disable: function() { if( module.is.disabled() ) { module.debug('Checkbox is already disabled'); return; } module.debug('Disabling checkbox'); module.set.disabled(); settings.onDisable.call(input); }, get: { radios: function() { var name = module.get.name() ; return $('input[name="' + name + '"]').closest(selector.checkbox); }, otherRadios: function() { return module.get.radios().not($module); }, name: function() { return $input.attr('name'); } }, is: { initialLoad: function() { return initialLoad; }, radio: function() { return ($input.hasClass(className.radio) || $input.attr('type') == 'radio'); }, indeterminate: function() { return $input.prop('indeterminate') !== undefined && $input.prop('indeterminate'); }, checked: function() { return $input.prop('checked') !== undefined && $input.prop('checked'); }, disabled: function() { return $input.prop('disabled') !== undefined && $input.prop('disabled'); }, enabled: function() { return !module.is.disabled(); }, determinate: function() { return !module.is.indeterminate(); }, unchecked: function() { return !module.is.checked(); } }, should: { allowCheck: function() { if(module.is.determinate() && module.is.checked() && !module.should.forceCallbacks() ) { module.debug('Should not allow check, checkbox is already checked'); return false; } if(settings.beforeChecked.apply(input) === false) { module.debug('Should not allow check, beforeChecked cancelled'); return false; } return true; }, allowUncheck: function() { if(module.is.determinate() && module.is.unchecked() && !module.should.forceCallbacks() ) { module.debug('Should not allow uncheck, checkbox is already unchecked'); return false; } if(settings.beforeUnchecked.apply(input) === false) { module.debug('Should not allow uncheck, beforeUnchecked cancelled'); return false; } return true; }, allowIndeterminate: function() { if(module.is.indeterminate() && !module.should.forceCallbacks() ) { module.debug('Should not allow indeterminate, checkbox is already indeterminate'); return false; } if(settings.beforeIndeterminate.apply(input) === false) { module.debug('Should not allow indeterminate, beforeIndeterminate cancelled'); return false; } return true; }, allowDeterminate: function() { if(module.is.determinate() && !module.should.forceCallbacks() ) { module.debug('Should not allow determinate, checkbox is already determinate'); return false; } if(settings.beforeDeterminate.apply(input) === false) { module.debug('Should not allow determinate, beforeDeterminate cancelled'); return false; } return true; }, forceCallbacks: function() { return (module.is.initialLoad() && settings.fireOnInit); }, ignoreCallbacks: function() { return (initialLoad && !settings.fireOnInit); } }, can: { change: function() { return !( $module.hasClass(className.disabled) || $module.hasClass(className.readOnly) || $input.prop('disabled') || $input.prop('readonly') ); }, uncheck: function() { return (typeof settings.uncheckable === 'boolean') ? settings.uncheckable : !module.is.radio() ; } }, set: { initialLoad: function() { initialLoad = true; }, checked: function() { module.verbose('Setting class to checked'); $module .removeClass(className.indeterminate) .addClass(className.checked) ; if( module.is.radio() ) { module.uncheckOthers(); } if(!module.is.indeterminate() && module.is.checked()) { module.debug('Input is already checked, skipping input property change'); return; } module.verbose('Setting state to checked', input); $input .prop('indeterminate', false) .prop('checked', true) ; module.trigger.change(); }, unchecked: function() { module.verbose('Removing checked class'); $module .removeClass(className.indeterminate) .removeClass(className.checked) ; if(!module.is.indeterminate() && module.is.unchecked() ) { module.debug('Input is already unchecked'); return; } module.debug('Setting state to unchecked'); $input .prop('indeterminate', false) .prop('checked', false) ; module.trigger.change(); }, indeterminate: function() { module.verbose('Setting class to indeterminate'); $module .addClass(className.indeterminate) ; if( module.is.indeterminate() ) { module.debug('Input is already indeterminate, skipping input property change'); return; } module.debug('Setting state to indeterminate'); $input .prop('indeterminate', true) ; module.trigger.change(); }, determinate: function() { module.verbose('Removing indeterminate class'); $module .removeClass(className.indeterminate) ; if( module.is.determinate() ) { module.debug('Input is already determinate, skipping input property change'); return; } module.debug('Setting state to determinate'); $input .prop('indeterminate', false) ; }, disabled: function() { module.verbose('Setting class to disabled'); $module .addClass(className.disabled) ; if( module.is.disabled() ) { module.debug('Input is already disabled, skipping input property change'); return; } module.debug('Setting state to disabled'); $input .prop('disabled', 'disabled') ; module.trigger.change(); }, enabled: function() { module.verbose('Removing disabled class'); $module.removeClass(className.disabled); if( module.is.enabled() ) { module.debug('Input is already enabled, skipping input property change'); return; } module.debug('Setting state to enabled'); $input .prop('disabled', false) ; module.trigger.change(); }, tabbable: function() { module.verbose('Adding tabindex to checkbox'); if( $input.attr('tabindex') === undefined) { $input.attr('tabindex', 0); } } }, remove: { initialLoad: function() { initialLoad = false; } }, trigger: { change: function() { var events = document.createEvent('HTMLEvents'), inputElement = $input[0] ; if(inputElement) { module.verbose('Triggering native change event'); events.initEvent('change', true, false); inputElement.dispatchEvent(events); } } }, create: { label: function() { if($input.prevAll(selector.label).length > 0) { $input.prev(selector.label).detach().insertAfter($input); module.debug('Moving existing label', $label); } else if( !module.has.label() ) { $label = $('<label>').insertAfter($input); module.debug('Creating label', $label); } } }, has: { label: function() { return ($label.length > 0); } }, bind: { events: function() { module.verbose('Attaching checkbox events'); $module .on('click' + eventNamespace, module.event.click) .on('keydown' + eventNamespace, selector.input, module.event.keydown) .on('keyup' + eventNamespace, selector.input, module.event.keyup) ; } }, unbind: { events: function() { module.debug('Removing events'); $module .off(eventNamespace) ; } }, uncheckOthers: function() { var $radios = module.get.otherRadios() ; module.debug('Unchecking other radios', $radios); $radios.removeClass(className.checked); }, toggle: function() { if( !module.can.change() ) { if(!module.is.radio()) { module.debug('Checkbox is read-only or disabled, ignoring toggle'); } return; } if( module.is.indeterminate() || module.is.unchecked() ) { module.debug('Currently unchecked'); module.check(); } else if( module.is.checked() && module.can.uncheck() ) { module.debug('Currently checked'); module.uncheck(); } }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.checkbox.settings = { name : 'Checkbox', namespace : 'checkbox', debug : false, verbose : true, performance : true, // delegated event context uncheckable : 'auto', fireOnInit : false, onChange : function(){}, beforeChecked : function(){}, beforeUnchecked : function(){}, beforeDeterminate : function(){}, beforeIndeterminate : function(){}, onChecked : function(){}, onUnchecked : function(){}, onDeterminate : function() {}, onIndeterminate : function() {}, onEnabled : function(){}, onDisabled : function(){}, className : { checked : 'checked', indeterminate : 'indeterminate', disabled : 'disabled', hidden : 'hidden', radio : 'radio', readOnly : 'read-only' }, error : { method : 'The method you called is not defined' }, selector : { checkbox : '.ui.checkbox', label : 'label, .box', input : 'input[type="checkbox"], input[type="radio"]', link : 'a[href]' } }; })( jQuery, window, document );
/** * PUI Object */ var PUI = { zindex : 1000, gridColumns: { '1': 'ui-grid-col-12', '2': 'ui-grid-col-6', '3': 'ui-grid-col-4', '4': 'ui-grid-col-3', '6': 'ui-grid-col-2', '12': 'ui-grid-col-11' }, charSet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', /** * Aligns container scrollbar to keep item in container viewport, algorithm copied from jquery-ui menu widget */ scrollInView: function(container, item) { var borderTop = parseFloat(container.css('borderTopWidth')) || 0, paddingTop = parseFloat(container.css('paddingTop')) || 0, offset = item.offset().top - container.offset().top - borderTop - paddingTop, scroll = container.scrollTop(), elementHeight = container.height(), itemHeight = item.outerHeight(true); if(offset < 0) { container.scrollTop(scroll + offset); } else if((offset + itemHeight) > elementHeight) { container.scrollTop(scroll + offset - elementHeight + itemHeight); } }, generateRandomId: function() { var id = ''; for (var i = 1; i <= 10; i++) { var randPos = Math.floor(Math.random() * this.charSet.length); id += this.charSet[randPos]; } return id; }, isIE: function(version) { return (this.browser.msie && parseInt(this.browser.version, 10) === version); }, escapeRegExp: function(text) { return text.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"); }, escapeHTML: function(value) { return value.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }, escapeClientId: function(id) { return "#" + id.replace(/:/g,"\\:"); }, clearSelection: function() { if(window.getSelection) { if(window.getSelection().empty) { window.getSelection().empty(); } else if(window.getSelection().removeAllRanges) { window.getSelection().removeAllRanges(); } } else if(document.selection && document.selection.empty) { document.selection.empty(); } }, inArray: function(arr, item) { for(var i = 0; i < arr.length; i++) { if(arr[i] === item) { return true; } } return false; }, calculateScrollbarWidth: function() { if(!this.scrollbarWidth) { if(this.browser.msie) { var $textarea1 = $('<textarea cols="10" rows="2"></textarea>') .css({ position: 'absolute', top: -1000, left: -1000 }).appendTo('body'), $textarea2 = $('<textarea cols="10" rows="2" style="overflow: hidden;"></textarea>') .css({ position: 'absolute', top: -1000, left: -1000 }).appendTo('body'); this.scrollbarWidth = $textarea1.width() - $textarea2.width(); $textarea1.add($textarea2).remove(); } else { var $div = $('<div />') .css({ width: 100, height: 100, overflow: 'auto', position: 'absolute', top: -1000, left: -1000 }) .prependTo('body').append('<div />').find('div') .css({ width: '100%', height: 200 }); this.scrollbarWidth = 100 - $div.width(); $div.parent().remove(); } } return this.scrollbarWidth; }, //adapted from jquery browser plugin resolveUserAgent: function() { var matched, browser; jQuery.uaMatch = function( ua ) { ua = ua.toLowerCase(); var match = /(opr)[\/]([\w.]+)/.exec( ua ) || /(chrome)[ \/]([\w.]+)/.exec( ua ) || /(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec( ua ) || /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || ua.indexOf("trident") >= 0 && /(rv)(?::| )([\w.]+)/.exec( ua ) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || []; var platform_match = /(ipad)/.exec( ua ) || /(iphone)/.exec( ua ) || /(android)/.exec( ua ) || /(windows phone)/.exec( ua ) || /(win)/.exec( ua ) || /(mac)/.exec( ua ) || /(linux)/.exec( ua ) || /(cros)/i.exec( ua ) || []; return { browser: match[ 3 ] || match[ 1 ] || "", version: match[ 2 ] || "0", platform: platform_match[ 0 ] || "" }; }; matched = jQuery.uaMatch( window.navigator.userAgent ); browser = {}; if ( matched.browser ) { browser[ matched.browser ] = true; browser.version = matched.version; browser.versionNumber = parseInt(matched.version); } if ( matched.platform ) { browser[ matched.platform ] = true; } // These are all considered mobile platforms, meaning they run a mobile browser if ( browser.android || browser.ipad || browser.iphone || browser[ "windows phone" ] ) { browser.mobile = true; } // These are all considered desktop platforms, meaning they run a desktop browser if ( browser.cros || browser.mac || browser.linux || browser.win ) { browser.desktop = true; } // Chrome, Opera 15+ and Safari are webkit based browsers if ( browser.chrome || browser.opr || browser.safari ) { browser.webkit = true; } // IE11 has a new token so we will assign it msie to avoid breaking changes if ( browser.rv ) { var ie = "msie"; matched.browser = ie; browser[ie] = true; } // Opera 15+ are identified as opr if ( browser.opr ) { var opera = "opera"; matched.browser = opera; browser[opera] = true; } // Stock Android browsers are marked as Safari on Android. if ( browser.safari && browser.android ) { var android = "android"; matched.browser = android; browser[android] = true; } // Assign the name and platform variable browser.name = matched.browser; browser.platform = matched.platform; this.browser = browser; $.browser = browser; }, getGridColumn: function(number) { return this.gridColumns[number + '']; }, executeFunctionByName: function(functionName /*, args */) { var args = [].slice.call(arguments).splice(1), context = window, namespaces = functionName.split("."), func = namespaces.pop(); for(var i = 0; i < namespaces.length; i++) { context = context[namespaces[i]]; } return context[func].apply(this, args); }, resolveObjectByName: function(name) { if(name) { var parts = name.split("."); for(var i = 0, len = parts.length, obj = window; i < len; ++i) { obj = obj[parts[i]]; } return obj; } else { return null; } }, getCookie : function(name) { return $.cookie(name); }, setCookie : function(name, value, cfg) { $.cookie(name, value, cfg); }, deleteCookie: function(name, cfg) { $.removeCookie(name, cfg); } }; PUI.resolveUserAgent(); /** * PrimeUI Accordion widget */ (function() { $.widget("primeui.puiaccordion", { options: { activeIndex: 0, multiple: false }, _create: function() { if(this.options.multiple) { this.options.activeIndex = this.options.activeIndex||[0]; } var $this = this; this.element.addClass('ui-accordion ui-widget ui-helper-reset'); var tabContainers = this.element.children(); //primeui if(tabContainers.is('div')) { this.panelMode = 'native'; this.headers = this.element.children('h3'); this.panels = this.element.children('div'); } //primeng else { this.panelMode = 'wrapped'; this.headers = tabContainers.children('h3'); this.panels = tabContainers.children('div'); } this.headers.addClass('ui-accordion-header ui-helper-reset ui-state-default').each(function(i) { var header = $(this), title = header.html(), active = $this.options.multiple ? ($.inArray(i, $this.options.activeIndex) !== -1) : (i == $this.options.activeIndex), headerClass = (active) ? 'ui-state-active ui-corner-top' : 'ui-corner-all', iconClass = (active) ? 'fa fa-fw fa-caret-down' : 'fa fa-fw fa-caret-right'; header.addClass(headerClass).html('<span class="' + iconClass + '"></span><a href="#">' + title + '</a>'); }); this.panels.each(function(i) { var content = $(this); content.addClass('ui-accordion-content ui-helper-reset ui-widget-content'), active = $this.options.multiple ? ($.inArray(i, $this.options.activeIndex) !== -1) : (i == $this.options.activeIndex); if(!active) { content.addClass('ui-helper-hidden'); } }); this.headers.children('a').disableSelection(); this._bindEvents(); }, _destroy: function() { this._unbindEvents(); this.element.removeClass('ui-accordion ui-widget ui-helper-reset'); this.headers.removeClass('ui-accordion-header ui-helper-reset ui-state-default ui-state-hover ui-state-active ui-state-disabled ui-corner-all ui-corner-top'); this.panels.removeClass('ui-accordion-content ui-helper-reset ui-widget-content ui-helper-hidden'); this.headers.children('.fa').remove(); this.headers.children('a').contents().unwrap(); }, _bindEvents: function() { var $this = this; this.headers.on('mouseover.puiaccordion', function() { var element = $(this); if(!element.hasClass('ui-state-active')&&!element.hasClass('ui-state-disabled')) { element.addClass('ui-state-hover'); } }).on('mouseout.puiaccordion', function() { var element = $(this); if(!element.hasClass('ui-state-active')&&!element.hasClass('ui-state-disabled')) { element.removeClass('ui-state-hover'); } }).on('click.puiaccordion', function(e) { var element = $(this); if(!element.hasClass('ui-state-disabled')) { var tabIndex = ($this.panelMode === 'native') ? element.index() / 2 : element.parent().index(); if(element.hasClass('ui-state-active')) { $this.unselect(tabIndex); } else { $this.select(tabIndex, false); } } e.preventDefault(); }); }, _unbindEvents: function() { this.headers.off('mouseover.puiaccordion mouseout.puiaccordion click.puiaccordion'); }, /** * Activates a tab with given index */ select: function(index, silent) { var panel = this.panels.eq(index); if(!silent) { this._trigger('change', null, {'index': index}); } //update state if(this.options.multiple) { this._addToSelection(index); } else { this.options.activeIndex = index; } this._show(panel); }, /** * Deactivates a tab with given index */ unselect: function(index) { var panel = this.panels.eq(index), header = panel.prev(); header.attr('aria-expanded', false).children('.fa').removeClass('fa-caret-down').addClass('fa-caret-right'); header.removeClass('ui-state-active ui-corner-top').addClass('ui-corner-all'); panel.attr('aria-hidden', true).slideUp(); this._removeFromSelection(index); }, _show: function(panel) { //deactivate current if(!this.options.multiple) { var oldHeader = this.headers.filter('.ui-state-active'); oldHeader.children('.fa').removeClass('fa-caret-down').addClass('fa-caret-right'); oldHeader.attr('aria-expanded', false).removeClass('ui-state-active ui-corner-top').addClass('ui-corner-all').next().attr('aria-hidden', true).slideUp(); } //activate selected var newHeader = panel.prev(); newHeader.attr('aria-expanded', true).addClass('ui-state-active ui-corner-top').removeClass('ui-state-hover ui-corner-all') .children('.fa').removeClass('fa-caret-right').addClass('fa-caret-down'); panel.attr('aria-hidden', false).slideDown('normal'); }, _addToSelection: function(nodeId) { this.options.activeIndex.push(nodeId); }, _removeFromSelection: function(index) { this.options.activeIndex = $.grep(this.options.activeIndex, function(r) { return r != index; }); }, _setOption: function(key, value) { if(key === 'activeIndex') { this.select(value, true); } else { $.Widget.prototype._setOption.apply(this, arguments); } } }); })(); /** * PrimeUI autocomplete widget */ (function() { $.widget("primeui.puiautocomplete", { options: { delay: 300, minQueryLength: 1, multiple: false, dropdown: false, scrollHeight: 200, forceSelection: false, effect:null, effectOptions: {}, effectSpeed: 'normal', content: null, caseSensitive: false }, _create: function() { this.element.wrap('<span class="ui-autocomplete ui-widget" />'); this.element.puiinputtext(); this.panel = $('<div class="ui-autocomplete-panel ui-widget-content ui-corner-all ui-helper-hidden ui-shadow"></div>').appendTo('body'); if(this.options.multiple) { this.element.wrap('<ul class="ui-autocomplete-multiple ui-widget ui-inputtext ui-state-default ui-corner-all">' + '<li class="ui-autocomplete-input-token"></li></ul>'); this.inputContainer = this.element.parent(); this.multiContainer = this.inputContainer.parent(); } else { if(this.options.dropdown) { this.dropdown = $('<button type="button" class="ui-autocomplete-dropdown ui-button ui-widget ui-state-default ui-corner-right ui-button-icon-only">' + '<span class="fa fa-fw fa-caret-down"></span><span class="ui-button-text">&nbsp;</span></button>') .insertAfter(this.element); this.element.removeClass('ui-corner-all').addClass('ui-corner-left'); } } this._bindEvents(); }, _bindEvents: function() { var $this = this; this._bindKeyEvents(); if(this.options.dropdown) { this.dropdown.on('mouseenter.puiautocomplete', function() { if(!$this.element.prop('disabled')) { $this.dropdown.addClass('ui-state-hover'); } }) .on('mouseleave.puiautocomplete', function() { $this.dropdown.removeClass('ui-state-hover'); }) .on('mousedown.puiautocomplete', function() { if(!$this.element.prop('disabled')) { $this.dropdown.addClass('ui-state-active'); } }) .on('mouseup.puiautocomplete', function() { if(!$this.element.prop('disabled')) { $this.dropdown.removeClass('ui-state-active'); $this.search(''); $this.element.focus(); } }) .on('focus.puiautocomplete', function() { $this.dropdown.addClass('ui-state-focus'); }) .on('blur.puiautocomplete', function() { $this.dropdown.removeClass('ui-state-focus'); }) .on('keydown.puiautocomplete', function(e) { var keyCode = $.ui.keyCode; if(e.which == keyCode.ENTER || e.which == keyCode.NUMPAD_ENTER) { $this.search(''); $this.input.focus(); e.preventDefault(); } }); } if(this.options.multiple) { this.multiContainer.on('hover.puiautocomplete', function() { $(this).toggleClass('ui-state-hover'); }) .on('click.puiautocomplete', function() { $this.element.trigger('focus'); }); this.element.on('focus.ui-autocomplete', function() { $this.multiContainer.addClass('ui-state-focus'); }) .on('blur.ui-autocomplete', function(e) { $this.multiContainer.removeClass('ui-state-focus'); }); } if(this.options.forceSelection) { this.currentItems = [this.element.val()]; this.element.on('blur.puiautocomplete', function() { var value = $(this).val(), valid = false; for(var i = 0; i < $this.currentItems.length; i++) { if($this.currentItems[i] === value) { valid = true; break; } } if(!valid) { $this.element.val(''); } }); } $(document.body).bind('mousedown.puiautocomplete', function (e) { if($this.panel.is(":hidden")) { return; } if(e.target === $this.element.get(0)) { return; } var offset = $this.panel.offset(); if (e.pageX < offset.left || e.pageX > offset.left + $this.panel.width() || e.pageY < offset.top || e.pageY > offset.top + $this.panel.height()) { $this.hide(); } }); $(window).bind('resize.' + this.element.id, function() { if($this.panel.is(':visible')) { $this._alignPanel(); } }); }, _bindKeyEvents: function() { var $this = this; this.element.on('keyup.puiautocomplete', function(e) { var keyCode = $.ui.keyCode, key = e.which, shouldSearch = true; if(key == keyCode.UP || key == keyCode.LEFT || key == keyCode.DOWN || key == keyCode.RIGHT || key == keyCode.TAB || key == keyCode.SHIFT || key == keyCode.ENTER || key == keyCode.NUMPAD_ENTER) { shouldSearch = false; } if(shouldSearch) { var value = $this.element.val(); if(!value.length) { $this.hide(); } if(value.length >= $this.options.minQueryLength) { if($this.timeout) { window.clearTimeout($this.timeout); } $this.timeout = window.setTimeout(function() { $this.search(value); }, $this.options.delay); } } }).on('keydown.puiautocomplete', function(e) { if($this.panel.is(':visible')) { var keyCode = $.ui.keyCode, highlightedItem = $this.items.filter('.ui-state-highlight'); switch(e.which) { case keyCode.UP: case keyCode.LEFT: var prev = highlightedItem.prev(); if(prev.length == 1) { highlightedItem.removeClass('ui-state-highlight'); prev.addClass('ui-state-highlight'); if($this.options.scrollHeight) { PUI.scrollInView($this.panel, prev); } } e.preventDefault(); break; case keyCode.DOWN: case keyCode.RIGHT: var next = highlightedItem.next(); if(next.length == 1) { highlightedItem.removeClass('ui-state-highlight'); next.addClass('ui-state-highlight'); if($this.options.scrollHeight) { PUI.scrollInView($this.panel, next); } } e.preventDefault(); break; case keyCode.ENTER: case keyCode.NUMPAD_ENTER: highlightedItem.trigger('click'); e.preventDefault(); break; case keyCode.ALT: case 224: break; case keyCode.TAB: highlightedItem.trigger('click'); $this.hide(); break; } } }); }, _bindDynamicEvents: function() { var $this = this; this.items.on('mouseover.puiautocomplete', function() { var item = $(this); if(!item.hasClass('ui-state-highlight')) { $this.items.filter('.ui-state-highlight').removeClass('ui-state-highlight'); item.addClass('ui-state-highlight'); } }) .on('click.puiautocomplete', function(event) { var item = $(this); if($this.options.multiple) { var tokenMarkup = '<li class="ui-autocomplete-token ui-state-active ui-corner-all ui-helper-hidden">'; tokenMarkup += '<span class="ui-autocomplete-token-icon fa fa-fw fa-close" />'; tokenMarkup += '<span class="ui-autocomplete-token-label">' + item.data('label') + '</span></li>'; $(tokenMarkup).data(item.data()) .insertBefore($this.inputContainer).fadeIn() .children('.ui-autocomplete-token-icon').on('click.ui-autocomplete', function(e) { var token = $(this).parent(); $this._removeItem(token); $this._trigger('unselect', e, token); }); $this.element.val('').trigger('focus'); } else { $this.element.val(item.data('label')).focus(); } $this._trigger('select', event, item); $this.hide(); }); }, search: function(q) { this.query = this.options.caseSensitive ? q : q.toLowerCase(); var request = { query: this.query }; if(this.options.completeSource) { if($.isArray(this.options.completeSource)) { var sourceArr = this.options.completeSource, data = [], emptyQuery = ($.trim(q) === ''); for(var i = 0 ; i < sourceArr.length; i++) { var item = sourceArr[i], itemLabel = item.label||item; if(!this.options.caseSensitive) { itemLabel = itemLabel.toLowerCase(); } if(emptyQuery||itemLabel.indexOf(this.query) === 0) { data.push({label:sourceArr[i], value: item}); } } this._handleData(data); } else { this.options.completeSource.call(this, request, this._handleData); } } }, _handleData: function(data) { var $this = this; this.panel.html(''); this.listContainer = $('<ul class="ui-autocomplete-items ui-autocomplete-list ui-widget-content ui-widget ui-corner-all ui-helper-reset"></ul>').appendTo(this.panel); for(var i = 0; i < data.length; i++) { var item = $('<li class="ui-autocomplete-item ui-autocomplete-list-item ui-corner-all"></li>'); item.data(data[i]); if(this.options.content) item.html(this.options.content.call(this, data[i])); else item.text(data[i].label); this.listContainer.append(item); } this.items = this.listContainer.children('.ui-autocomplete-item'); this._bindDynamicEvents(); if(this.items.length > 0) { var firstItem = $this.items.eq(0), hidden = this.panel.is(':hidden'); firstItem.addClass('ui-state-highlight'); if($this.query.length > 0 && !$this.options.content) { $this.items.each(function() { var item = $(this), text = item.html(), re = new RegExp(PUI.escapeRegExp($this.query), 'gi'), highlighedText = text.replace(re, '<span class="ui-autocomplete-query">$&</span>'); item.html(highlighedText); }); } if(this.options.forceSelection) { this.currentItems = []; $.each(data, function(i, item) { $this.currentItems.push(item.label); }); } //adjust height if($this.options.scrollHeight) { var heightConstraint = hidden ? $this.panel.height() : $this.panel.children().height(); if(heightConstraint > $this.options.scrollHeight) $this.panel.height($this.options.scrollHeight); else $this.panel.css('height', 'auto'); } if(hidden) { $this.show(); } else { $this._alignPanel(); } } else { this.panel.hide(); } }, show: function() { this._alignPanel(); if(this.options.effect) this.panel.show(this.options.effect, {}, this.options.effectSpeed); else this.panel.show(); }, hide: function() { this.panel.hide(); this.panel.css('height', 'auto'); }, _removeItem: function(item) { item.fadeOut('fast', function() { var token = $(this); token.remove(); }); }, _alignPanel: function() { var panelWidth = null; if(this.options.multiple) { panelWidth = this.multiContainer.innerWidth() - (this.element.position().left - this.multiContainer.position().left); } else { if(this.panel.is(':visible')) { panelWidth = this.panel.children('.ui-autocomplete-items').outerWidth(); } else { this.panel.css({'visibility':'hidden','display':'block'}); panelWidth = this.panel.children('.ui-autocomplete-items').outerWidth(); this.panel.css({'visibility':'visible','display':'none'}); } var inputWidth = this.element.outerWidth(); if(panelWidth < inputWidth) { panelWidth = inputWidth; } } this.panel.css({ 'left':'', 'top':'', 'width': panelWidth, 'z-index': ++PUI.zindex }) .position({ my: 'left top', at: 'left bottom', of: this.element }); } }); })(); /** * PrimeFaces Button Widget */ (function() { $.widget("primeui.puibutton", { options: { value: null, icon: null, iconPos: 'left', click: null }, _create: function() { var element = this.element; this.elementText = this.element.text(); var value = this.options.value||(this.elementText === '' ? 'ui-button' : this.elementText), disabled = element.prop('disabled'), styleClass = null; if(this.options.icon) { styleClass = (value === 'ui-button') ? 'ui-button-icon-only' : 'ui-button-text-icon-' + this.options.iconPos; } else { styleClass = 'ui-button-text-only'; } if(disabled) { styleClass += ' ui-state-disabled'; } this.element.addClass('ui-button ui-widget ui-state-default ui-corner-all ' + styleClass).text(''); if(this.options.icon) { this.element.append('<span class="ui-button-icon-' + this.options.iconPos + ' ui-c fa fa-fw ' + this.options.icon + '" />'); } this.element.append('<span class="ui-button-text ui-c">' + value + '</span>'); if(!disabled) { this._bindEvents(); } }, _destroy: function() { this.element.removeClass('ui-button ui-widget ui-state-default ui-state-hover ui-state-active ui-state-disabled ui-state-focus ui-corner-all ' + 'ui-button-text-only ui-button-icon-only ui-button-text-icon-right ui-button-text-icon-left'); this._unbindEvents(); this.element.children('.fa').remove(); this.element.children('.ui-button-text').remove(); this.element.text(this.elementText); }, _bindEvents: function() { var element = this.element, $this = this; element.on('mouseover.puibutton', function(){ if(!element.prop('disabled')) { element.addClass('ui-state-hover'); } }).on('mouseout.puibutton', function() { $(this).removeClass('ui-state-active ui-state-hover'); }).on('mousedown.puibutton', function() { if(!element.hasClass('ui-state-disabled')) { element.addClass('ui-state-active').removeClass('ui-state-hover'); } }).on('mouseup.puibutton', function(e) { element.removeClass('ui-state-active').addClass('ui-state-hover'); $this._trigger('click', e); }).on('focus.puibutton', function() { element.addClass('ui-state-focus'); }).on('blur.puibutton', function() { element.removeClass('ui-state-focus'); }).on('keydown.puibutton',function(e) { if(e.keyCode == $.ui.keyCode.SPACE || e.keyCode == $.ui.keyCode.ENTER || e.keyCode == $.ui.keyCode.NUMPAD_ENTER) { element.addClass('ui-state-active'); } }).on('keyup.puibutton', function() { element.removeClass('ui-state-active'); }); return this; }, _unbindEvents: function() { this.element.off('mouseover.puibutton mouseout.puibutton mousedown.puibutton mouseup.puibutton focus.puibutton blur.puibutton keydown.puibutton keyup.puibutton'); }, disable: function() { this._unbindEvents(); this.element.addClass('ui-state-disabled').prop('disabled',true); }, enable: function() { if(this.element.prop('disabled')) { this._bindEvents(); this.element.prop('disabled', false).removeClass('ui-state-disabled'); } }, _setOption: function(key, value) { if(key === 'disabled') { if(value) this.disable(); else this.enable(); } else { $.Widget.prototype._setOption.apply(this, arguments); } } }); })(); /** * PrimeUI Carousel widget */ (function() { $.widget("primeui.puicarousel", { options: { datasource: null, numVisible: 3, firstVisible: 0, headerText: null, effectDuration: 500, circular :false, breakpoint: 560, itemContent: null, responsive: true, autoplayInterval: 0, easing: 'easeInOutCirc', pageLinks: 3, style: null, styleClass: null, template: null, enhanced: false }, _create: function() { this.id = this.element.attr('id'); if(!this.id) { this.id = this.element.uniqueId().attr('id'); } if(!this.options.enhanced) { this.element.wrap('<div class="ui-carousel ui-widget ui-widget-content ui-corner-all"><div class="ui-carousel-viewport"></div></div>'); } this.container = this.element.parent().parent(); this.element.addClass('ui-carousel-items'); this.viewport = this.element.parent(); this.container.prepend('<div class="ui-carousel-header ui-widget-header"><div class="ui-carousel-header-title"></div></div>'); this.header = this.container.children('.ui-carousel-header'); this.header.append('<span class="ui-carousel-button ui-carousel-next-button fa fa-arrow-circle-right"></span>' + '<span class="ui-carousel-button ui-carousel-prev-button fa fa-arrow-circle-left"></span>'); if(this.options.headerText) { this.header.children('.ui-carousel-header-title').html(this.options.headerText); } if(this.options.styleClass) { this.container.addClass(this.options.styleClass); } if(this.options.style) { this.container.attr('style', this.options.style); } if(this.options.datasource) this._loadData(); else this._render(); }, _destroy: function() { this._unbindEvents(); this.header.remove(); this.items.removeClass('ui-carousel-item ui-widget-content ui-corner-all').css('width','auto'); this.element.removeClass('ui-carousel-items').css('left','auto'); if(!this.options.enhanced) { this.element.unwrap().unwrap(); } if(this.options.datasource) { this.items.remove(); } }, _loadData: function() { if($.isArray(this.options.datasource)) this._render(this.options.datasource); else if($.type(this.options.datasource) === 'function') this.options.datasource.call(this, this._render); }, _updateDatasource: function(value) { this.options.datasource = value; this.element.children().remove(); this.header.children('.ui-carousel-page-links').remove(); this.header.children('select').remove(); this._loadData(); }, _render: function(data) { this.data = data; if(this.data) { for(var i = 0; i < data.length; i++) { var itemContent = this._createItemContent(data[i]); if($.type(itemContent) === 'string') this.element.append('<li>' + itemContent + '</li>'); else this.element.append($('<li></li>').wrapInner(itemContent)); } } this.items = this.element.children('li'); this.items.addClass('ui-carousel-item ui-widget-content ui-corner-all'); this.itemsCount = this.items.length; this.columns = this.options.numVisible; this.first = this.options.firstVisible; this.page = parseInt(this.first/this.columns); this.totalPages = Math.ceil(this.itemsCount/this.options.numVisible); this._renderPageLinks(); this.prevNav = this.header.children('.ui-carousel-prev-button'); this.nextNav = this.header.children('.ui-carousel-next-button'); this.pageLinks = this.header.find('> .ui-carousel-page-links > .ui-carousel-page-link'); this.dropdown = this.header.children('.ui-carousel-dropdown'); this.mobileDropdown = this.header.children('.ui-carousel-mobiledropdown'); this._bindEvents(); if(this.options.responsive) { this.refreshDimensions(); } else { this.calculateItemWidths(); this.container.width(this.container.width()); this.updateNavigators(); } }, _renderPageLinks: function() { if(this.totalPages <= this.options.pageLinks) { this.pageLinksContainer = $('<div class="ui-carousel-page-links"></div>'); for(var i = 0; i < this.totalPages; i++) { this.pageLinksContainer.append('<a href="#" class="ui-carousel-page-link fa fa-circle-o"></a>'); } this.header.append(this.pageLinksContainer); } else { this.dropdown = $('<select class="ui-carousel-dropdown ui-widget ui-state-default ui-corner-left"></select>'); for(var i = 0; i < this.totalPages; i++) { var pageNumber = (i+1); this.dropdown.append('<option value="' + pageNumber + '">' + pageNumber + '</option>'); } this.header.append(this.dropdown); } if(this.options.responsive) { this.mobileDropdown = $('<select class="ui-carousel-mobiledropdown ui-widget ui-state-default ui-corner-left"></select>'); for(var i = 0; i < this.itemsCount; i++) { var pageNumber = (i+1); this.mobileDropdown.append('<option value="' + pageNumber + '">' + pageNumber + '</option>'); } this.header.append(this.mobileDropdown); } }, calculateItemWidths: function() { var firstItem = this.items.eq(0); if(firstItem.length) { var itemFrameWidth = firstItem.outerWidth(true) - firstItem.width(); //sum of margin, border and padding this.items.width((this.viewport.innerWidth() - itemFrameWidth * this.columns) / this.columns); } }, refreshDimensions: function() { var win = $(window); if(win.width() <= this.options.breakpoint) { this.columns = 1; this.calculateItemWidths(this.columns); this.totalPages = this.itemsCount; this.mobileDropdown.show(); this.pageLinks.hide(); } else { this.columns = this.options.numVisible; this.calculateItemWidths(); this.totalPages = Math.ceil(this.itemsCount / this.options.numVisible); this.mobileDropdown.hide(); this.pageLinks.show(); } this.page = parseInt(this.first / this.columns); this.updateNavigators(); this.element.css('left', (-1 * (this.viewport.innerWidth() * this.page))); }, _bindEvents: function() { var $this = this; if(this.eventsBound) { return; } this.prevNav.on('click.puicarousel', function() { if($this.page !== 0) { $this.setPage($this.page - 1); } else if($this.options.circular) { $this.setPage($this.totalPages - 1); } }); this.nextNav.on('click.puicarousel', function() { var lastPage = ($this.page === ($this.totalPages - 1)); if(!lastPage) { $this.setPage($this.page + 1); } else if($this.options.circular) { $this.setPage(0); } }); if($.swipe) { this.element.swipe({ swipe:function(event, direction) { if(direction === 'left') { if($this.page === ($this.totalPages - 1)) { if($this.options.circular) $this.setPage(0); } else { $this.setPage($this.page + 1); } } else if(direction === 'right') { if($this.page === 0) { if($this.options.circular) $this.setPage($this.totalPages - 1); } else { $this.setPage($this.page - 1); } } } }); } if(this.pageLinks.length) { this.pageLinks.on('click.puicarousel', function(e) { $this.setPage($(this).index()); e.preventDefault(); }); } this.header.children('select').on('change.puicarousel', function() { $this.setPage(parseInt($(this).val()) - 1); }); if(this.options.autoplayInterval) { this.options.circular = true; this.startAutoplay(); } if(this.options.responsive) { var resizeNS = 'resize.' + this.id; $(window).off(resizeNS).on(resizeNS, function() { $this.refreshDimensions(); }); } this.eventsBound = true; }, _unbindEvents: function() { this.prevNav.off('click.puicarousel'); this.nextNav.off('click.puicarousel'); if(this.pageLinks.length) { this.pageLinks.off('click.puicarousel'); } this.header.children('select').off('change.puicarousel'); if(this.options.autoplayInterval) { this.stopAutoplay(); } if(this.options.responsive) { $(window).off('resize.' + this.id) } }, updateNavigators: function() { if(!this.options.circular) { if(this.page === 0) { this.prevNav.addClass('ui-state-disabled'); this.nextNav.removeClass('ui-state-disabled'); } else if(this.page === (this.totalPages - 1)) { this.prevNav.removeClass('ui-state-disabled'); this.nextNav.addClass('ui-state-disabled'); } else { this.prevNav.removeClass('ui-state-disabled'); this.nextNav.removeClass('ui-state-disabled'); } } if(this.pageLinks.length) { this.pageLinks.filter('.fa-dot-circle-o').removeClass('fa-dot-circle-o'); this.pageLinks.eq(this.page).addClass('fa-dot-circle-o'); } if(this.dropdown.length) { this.dropdown.val(this.page + 1); } if(this.mobileDropdown.length) { this.mobileDropdown.val(this.page + 1); } }, setPage: function(p) { if(p !== this.page && !this.element.is(':animated')) { var $this = this; this.element.animate({ left: -1 * (this.viewport.innerWidth() * p) ,easing: this.options.easing }, { duration: this.options.effectDuration, easing: this.options.easing, complete: function() { $this.page = p; $this.first = $this.page * $this.columns; $this.updateNavigators(); $this._trigger('pageChange', null, {'page':p}); } }); } }, startAutoplay: function() { var $this = this; this.interval = setInterval(function() { if($this.page === ($this.totalPages - 1)) $this.setPage(0); else $this.setPage($this.page + 1); }, this.options.autoplayInterval); }, stopAutoplay: function() { clearInterval(this.interval); }, _setOption: function(key, value) { if(key === 'datasource') this._updateDatasource(value); else $.Widget.prototype._setOption.apply(this, arguments); }, _createItemContent: function(obj) { if(this.options.template) { var template = this.options.template.html(); Mustache.parse(template); return Mustache.render(template, obj); } else { return this.options.itemContent.call(this, obj); } } }); })(); /** * PrimeUI checkbox widget */ (function() { $.widget("primeui.puicheckbox", { _create: function() { this.element.wrap('<div class="ui-chkbox ui-widget"><div class="ui-helper-hidden-accessible"></div></div>'); this.container = this.element.parent().parent(); this.box = $('<div class="ui-chkbox-box ui-widget ui-corner-all ui-state-default">').appendTo(this.container); this.icon = $('<span class="ui-chkbox-icon ui-c"></span>').appendTo(this.box); this.disabled = this.element.prop('disabled'); this.label = $('label[for="' + this.element.attr('id') + '"]'); if(this.isChecked()) { this.box.addClass('ui-state-active'); this.icon.addClass('fa fa-fw fa-check'); } if(this.disabled) { this.box.addClass('ui-state-disabled'); } else { this._bindEvents(); } }, _bindEvents: function() { var $this = this; this.box.on('mouseover.puicheckbox', function() { if(!$this.isChecked()) $this.box.addClass('ui-state-hover'); }) .on('mouseout.puicheckbox', function() { $this.box.removeClass('ui-state-hover'); }) .on('click.puicheckbox', function() { $this.toggle(); }); this.element.on('focus.puicheckbox', function() { if($this.isChecked()) { $this.box.removeClass('ui-state-active'); } $this.box.addClass('ui-state-focus'); }) .on('blur.puicheckbox', function() { if($this.isChecked()) { $this.box.addClass('ui-state-active'); } $this.box.removeClass('ui-state-focus'); }) .on('keydown.puicheckbox', function(e) { var keyCode = $.ui.keyCode; if(e.which == keyCode.SPACE) { e.preventDefault(); } }) .on('keyup.puicheckbox', function(e) { var keyCode = $.ui.keyCode; if(e.which == keyCode.SPACE) { $this.toggle(true); e.preventDefault(); } }); this.label.on('click.puicheckbox', function(e) { $this.toggle(); e.preventDefault(); }); }, toggle: function(keypress) { if(this.isChecked()) { this.uncheck(keypress); } else { this.check(keypress); } this._trigger('change', null, this.isChecked()); }, isChecked: function() { return this.element.prop('checked'); }, check: function(activate, silent) { if(!this.isChecked()) { this.element.prop('checked', true); this.icon.addClass('fa fa-fw fa-check'); if(!activate) { this.box.addClass('ui-state-active'); } if(!silent) { this.element.trigger('change'); } } }, uncheck: function() { if(this.isChecked()) { this.element.prop('checked', false); this.box.removeClass('ui-state-active'); this.icon.removeClass('fa fa-fw fa-check'); this.element.trigger('change'); } }, _unbindEvents: function() { this.box.off('mouseover.puicheckbox mouseout.puicheckbox click.puicheckbox'); this.element.off('focus.puicheckbox blur.puicheckbox keydown.puicheckbox keyup.puicheckbox'); if (this.label.length) { this.label.off('click.puicheckbox'); } }, disable: function() { this.box.prop('disabled', true); this.box.attr('aria-disabled', true); this.box.addClass('ui-state-disabled').removeClass('ui-state-hover'); this._unbindEvents(); }, enable: function() { this.box.prop('disabled', false); this.box.attr('aria-disabled', false); this.box.removeClass('ui-state-disabled'); this._bindEvents(); }, _destroy: function() { this._unbindEvents(); this.container.removeClass('ui-chkbox ui-widget'); this.box.remove(); this.element.unwrap().unwrap(); } }); })(); /** * PrimeUI Datagrid Widget */ (function() { $.widget("primeui.puidatagrid", { options: { columns: 3, datasource: null, paginator: null, header: null, footer: null, content: null, lazy: false, template: null }, _create: function() { this.id = this.element.attr('id'); if(!this.id) { this.id = this.element.uniqueId().attr('id'); } this.element.addClass('ui-datagrid ui-widget'); //header if(this.options.header) { this.element.append('<div class="ui-datagrid-header ui-widget-header ui-corner-top">' + this.options.header + '</div>'); } //content this.content = $('<div class="ui-datagrid-content ui-widget-content ui-datagrid-col-' + this.options.columns + '"></div>').appendTo(this.element); //footer if(this.options.footer) { this.element.append('<div class="ui-datagrid-footer ui-widget-header ui-corner-top">' + this.options.footer + '</div>'); } //data if(this.options.datasource) { this._initDatasource(); } }, _onDataInit: function(data) { this._onDataUpdate(data); this._initPaginator(); }, _onDataUpdate: function(data) { this.data = data; if(!this.data) { this.data = []; } this.reset(); this._renderData(); }, _onLazyLoad: function(data) { this.data = data; if(!this.data) { this.data = []; } this._renderData(); }, reset: function() { if(this.paginator) { this.paginator.puipaginator('setState', { page: 0, totalRecords: this.options.lazy ? this.options.paginator.totalRecords : this.data.length }); } }, paginate: function() { if(this.options.lazy) { this.options.datasource.call(this, this._onLazyLoad, this._createStateMeta()); } else { this._renderData(); } }, _renderData: function() { if(this.data) { this.content.html(''); var firstNonLazy = this._getFirst(), first = this.options.lazy ? 0 : firstNonLazy, rows = this._getRows(), gridRow = null; for(var i = first; i < (first + rows); i++) { var dataValue = this.data[i]; if(dataValue) { var gridColumn = $('<div></div>').appendTo(this.content), markup = this._createItemContent(dataValue); gridColumn.append(markup); } } } }, _getFirst: function() { if(this.paginator) { var page = this.paginator.puipaginator('option', 'page'), rows = this.paginator.puipaginator('option', 'rows'); return (page * rows); } else { return 0; } }, _getRows: function() { if(this.options.paginator) return this.paginator ? this.paginator.puipaginator('option', 'rows') : this.options.paginator.rows; else return this.data ? this.data.length : 0; }, _createStateMeta: function() { var state = { first: this._getFirst(), rows: this._getRows() }; return state; }, _initPaginator: function() { var $this = this; if(this.options.paginator) { this.options.paginator.paginate = function(event, state) { $this.paginate(); }; this.options.paginator.totalRecords = this.options.lazy ? this.options.paginator.totalRecords : this.data.length; this.paginator = $('<div></div>').insertAfter(this.content).puipaginator(this.options.paginator); } }, _initDatasource: function() { if($.isArray(this.options.datasource)) { this._onDataInit(this.options.datasource); } else { if($.type(this.options.datasource) === 'string') { var $this = this, dataURL = this.options.datasource; this.options.datasource = function() { $.ajax({ type: 'GET', url: dataURL, dataType: "json", context: $this, success: function (response) { this._onDataInit(response); } }); }; } if($.type(this.options.datasource) === 'function') { if(this.options.lazy) this.options.datasource.call(this, this._onDataInit, {first:0, rows: this._getRows()}); else this.options.datasource.call(this, this._onDataInit); } } }, _updateDatasource: function(datasource) { this.options.datasource = datasource; if($.isArray(this.options.datasource)) { this._onDataUpdate(this.options.datasource); } else if($.type(this.options.datasource) === 'function') { if(this.options.lazy) this.options.datasource.call(this, this._onDataUpdate, {first:0, rows: this._getRows()}); else this.options.datasource.call(this, this._onDataUpdate); } }, _setOption: function(key, value) { if(key === 'datasource') { this._updateDatasource(value); } else { $.Widget.prototype._setOption.apply(this, arguments); } }, _createItemContent: function(obj) { if(this.options.template) { var templateContent = this.options.template.html(); Mustache.parse(templateContent); return Mustache.render(templateContent, obj); } else { return this.options.content.call(this, obj); } } }); })(); /** * PrimeUI Datascroller Widget */ (function() { $.widget("primeui.puidatascroller", { options: { header: null, buffer: 0.9, chunkSize: 10, datasource: null, lazy: false, content: null, template: null, mode: 'document', loader: null, scrollHeight: null, totalSize: null }, _create: function() { this.id = this.element.attr('id'); if(!this.id) { this.id = this.element.uniqueId().attr('id'); } this.element.addClass('ui-datascroller ui-widget'); if(this.options.header) { this.header = this.element.append('<div class="ui-datascroller-header ui-widget-header ui-corner-top">' + this.options.header + '</div>').children('.ui-datascroller-header'); } this.content = this.element.append('<div class="ui-datascroller-content ui-widget-content ui-corner-bottom"></div>').children('.ui-datascroller-content'); this.list = this.content.append('<ul class="ui-datascroller-list"></ul>').children('.ui-datascroller-list'); this.loaderContainer = this.content.append('<div class="ui-datascroller-loader"></div>').children('.ui-datascroller-loader'); this.loadStatus = $('<div class="ui-datascroller-loading"></div>'); this.loading = false; this.allLoaded = false; this.offset = 0; if(this.options.mode === 'self') { this.element.addClass('ui-datascroller-inline'); if(this.options.scrollHeight) { this.content.css('height', this.options.scrollHeight); } } if(this.options.loader) { this.bindManualLoader(); } else { this.bindScrollListener(); } if(this.options.datasource) { if($.isArray(this.options.datasource)) { this._onDataInit(this.options.datasource); } else { if($.type(this.options.datasource) === 'string') { var $this = this, dataURL = this.options.datasource; this.options.datasource = function() { $.ajax({ type: 'GET', url: dataURL, dataType: "json", context: $this, success: function (response) { this._onDataInit(response); } }); }; } if($.type(this.options.datasource) === 'function') { if(this.options.lazy) this.options.datasource.call(this, this._onLazyLoad, {first:this.offset}); else this.options.datasource.call(this, this._onDataInit); } } } }, _onDataInit: function(data) { this.data = data||[]; this.options.totalSize = this.data.length; this._load(); }, _onLazyLoad: function(data) { this._renderData(data, 0, this.options.chunkSize); this._onloadComplete(); }, bindScrollListener: function() { var $this = this; if(this.options.mode === 'document') { var win = $(window), doc = $(document), $this = this, NS = 'scroll.' + this.id; win.off(NS).on(NS, function () { if(win.scrollTop() >= ((doc.height() * $this.options.buffer) - win.height()) && $this.shouldLoad()) { $this._load(); } }); } else { this.content.on('scroll', function () { var scrollTop = this.scrollTop, scrollHeight = this.scrollHeight, viewportHeight = this.clientHeight; if((scrollTop >= ((scrollHeight * $this.options.buffer) - (viewportHeight))) && $this.shouldLoad()) { $this._load(); } }); } }, bindManualLoader: function() { var $this = this; this.options.loader.on('click.dataScroller', function(e) { $this._load(); e.preventDefault(); }); }, _load: function() { this.loading = true; this.loadStatus.appendTo(this.loaderContainer); if(this.options.loader) { this.options.loader.hide(); } if(this.options.lazy) { this.options.datasource.call(this, this._onLazyLoad, {first: this.offset}); } else { this._renderData(this.data, this.offset, (this.offset + this.options.chunkSize)); this._onloadComplete(); } }, _renderData: function(data, start, end) { if(data && data.length) { for(var i = start; i < end; i++) { var listItem = $('<li class="ui-datascroller-item"></li>'), content = this._createItemContent(data[i]); listItem.append(content); this.list.append(listItem); } } }, shouldLoad: function() { return (!this.loading && !this.allLoaded); }, _createItemContent: function(obj) { if(this.options.template) { var template = this.options.template.html(); Mustache.parse(template); return Mustache.render(template, obj); } else { return this.options.content.call(this, obj); } }, _onloadComplete: function() { this.offset += this.options.chunkSize; this.loading = false; this.allLoaded = this.offset >= this.options.totalSize; this.loadStatus.remove(); if(this.options.loader && !this.allLoaded) { this.options.loader.show(); } } }); })(); /** * PrimeUI Datatable Widget */ (function() { $.widget("primeui.puidatatable", { options: { columns: null, datasource: null, paginator: null, globalFilter:null, selectionMode: null, caption: null, footer: null, sortField: null, sortOrder: 1, sortMeta: [], sortMode: null, scrollable: false, scrollHeight: null, scrollWidth: null, responsive: false, expandableRows: false, expandedRowContent: null, rowExpandMode: 'multiple', draggableColumns: false, resizableColumns: false, columnResizeMode: 'fit', draggableRows: false, filterDelay: 300, stickyHeader: false, editMode: null, tabindex: 0, emptyMessage: 'No records found', sort: null, rowSelect: null, rowUnselect: null, rowSelectContextMenu: null, rowCollapse: null, rowExpand: null, colReorder: null, colResize: null, rowReorder: null, cellEdit: null }, _create: function() { this.id = this.element.attr('id'); if(!this.id) { this.id = this.element.uniqueId().attr('id'); } this.element.addClass('ui-datatable ui-widget'); if(this.options.responsive) { this.element.addClass('ui-datatable-reflow'); } if(this.options.scrollable) { this._createScrollableDatatable(); } else { this._createRegularDatatable(); } if(this.options.datasource) { if($.isArray(this.options.datasource)) { this._onDataInit(this.options.datasource); } else { if($.type(this.options.datasource) === 'string') { var $this = this, dataURL = this.options.datasource; this.options.datasource = function() { $.ajax({ type: 'GET', url: dataURL, dataType: "json", context: $this, success: function (response) { this._onDataInit(response); } }); }; } if($.type(this.options.datasource) === 'function') { if(this.options.lazy) this.options.datasource.call(this, this._onDataInit, {first:0, rows:this._getRows(), sortField:this.options.sortField, sortOrder:this.options.sortOrder, filters: this._createFilterMap()}); else this.options.datasource.call(this, this._onDataInit); } } } }, _createRegularDatatable: function() { this.tableWrapper = $('<div class="ui-datatable-tablewrapper" />').appendTo(this.element); this.table = $('<table><thead></thead><tbody></tbody></table>').appendTo(this.tableWrapper); this.thead = this.table.children('thead'); this.tbody = this.table.children('tbody').addClass('ui-datatable-data ui-widget-content'); if(this.containsFooter()) { this.tfoot = this.thead.after('<tfoot></tfoot>').next(); } }, _createScrollableDatatable: function() { this.element.append('<div class="ui-widget-header ui-datatable-scrollable-header"><div class="ui-datatable-scrollable-header-box"><table><thead></thead></table></div></div>') .append('<div class="ui-datatable-scrollable-body"><table><tbody></tbody></table></div>'); this.thead = this.element.find('> .ui-datatable-scrollable-header > .ui-datatable-scrollable-header-box > table > thead'); this.tbody = this.element.find('> .ui-datatable-scrollable-body > table > tbody'); if(this.containsFooter()) { this.element.append('<div class="ui-widget-header ui-datatable-scrollable-footer"><div class="ui-datatable-scrollable-footer-box"><table><tfoot></tfoot></table></div></div>'); this.tfoot = this.element.find('> .ui-datatable-scrollable-footer > .ui-datatable-scrollable-footer-box > table > tfoot'); } }, _initialize: function() { var $this = this; this._initHeader(); this._initFooter(); if(this.options.caption) { this.element.prepend('<div class="ui-datatable-header ui-widget-header">' + this.options.caption + '</div>'); } if(this.options.paginator) { this.options.paginator.paginate = function(event, state) { $this.paginate(); }; this.options.paginator.totalRecords = this.options.lazy ? this.options.paginator.totalRecords : this.data.length; this.paginator = $('<div></div>').insertAfter(this.tableWrapper).puipaginator(this.options.paginator); if(this.options.paginator.contentLeft) { this.paginator.prepend(this.options.paginator.contentLeft.call()); } if(this.options.paginator.contentRight) { this.paginator.append(this.options.paginator.contentRight.call()); } } if(this.options.footer) { this.element.append('<div class="ui-datatable-footer ui-widget-header">' + this.options.footer + '</div>'); } if(this._isSortingEnabled()) { this._initSorting(); } if(this.hasFiltering) { this._initFiltering(); } if(this.options.selectionMode) { this._initSelection(); } if(this.options.expandableRows) { this._initExpandableRows(); } if(this.options.draggableColumns) { this._initDraggableColumns(); } if(this.options.stickyHeader) { this._initStickyHeader(); } if ((this.options.sortField && this.options.sortOrder) || this.options.sortMeta.length) { this.sortByDefault(); } else { this._renderData(); } if(this.options.scrollable) { this._initScrolling(); } if(this.options.resizableColumns) { this._initResizableColumns(); } if(this.options.draggableRows) { this._initDraggableRows(); } if(this.options.editMode) { this._initEditing(); } }, _initHeader: function() { if(this.options.headerRows) { for(var i = 0; i < this.options.headerRows.length; i++) { this._initHeaderColumns(this.options.headerRows[i].columns); } } else if(this.options.columns) { this._initHeaderColumns(this.options.columns); } }, _initFooter: function() { if(this.containsFooter()) { if(this.options.footerRows) { for(var i = 0; i < this.options.footerRows.length; i++) { this._initFooterColumns(this.options.footerRows[i].columns); } } else if(this.options.columns) { this._initFooterColumns(this.options.columns); } } }, _initHeaderColumns: function(columns) { var headerRow = $('<tr class="ui-state-default"></tr>').appendTo(this.thead), $this = this; $.each(columns, function(i, col) { var cell = $('<th class="ui-state-default"><span class="ui-column-title"></span></th>').data('field', col.field).uniqueId().appendTo(headerRow); if(col.headerClass) { cell.addClass(col.headerClass); } if(col.headerStyle) { cell.attr('style', col.headerStyle); } if(col.headerText) cell.children('.ui-column-title').text(col.headerText); else if(col.headerContent) cell.children('.ui-column-title').append(col.headerContent.call(this, col)); if(col.rowspan) { cell.attr('rowspan', col.rowspan); } if(col.colspan) { cell.attr('colspan', col.colspan); } if(col.sortable) { cell.addClass('ui-sortable-column') .data('order', 0) .append('<span class="ui-sortable-column-icon fa fa-fw fa-sort"></span>'); } if(col.filter) { $this.hasFiltering = true; var filterElement = $('<input type="text" class="ui-column-filter" />').puiinputtext().data({ 'field': col.field, 'filtermatchmode': col.filterMatchMode||'startsWith' }).appendTo(cell); if(col.filterFunction) { filterElement.on('filter', function(event, dataValue, filterValue) { return col.filterFunction.call($this, dataValue, filterValue); }); } } }); }, _initFooterColumns: function(columns) { var footerRow = $('<tr></tr>').appendTo(this.tfoot); $.each(columns, function(i, col) { var cell = $('<td class="ui-state-default"></td>'); if(col.footerText) { cell.text(col.footerText); } if(col.rowspan) { cell.attr('rowspan', col.rowspan); } if(col.colspan) { cell.attr('colspan', col.colspan); } cell.appendTo(footerRow); }); }, _indicateInitialSortColumn: function(sortField, sortOrder) { var $this = this; $.each(this.sortableColumns, function(i, column) { var $column = $(column), data = $column.data(); if (sortField === data.field) { var sortIcon = $column.children('.ui-sortable-column-icon'); $column.data('order', sortOrder).removeClass('ui-state-hover').addClass('ui-state-active'); if(sortOrder == -1) sortIcon.removeClass('fa-sort fa-sort-asc').addClass('fa-sort-desc'); else if(sortOrder == 1) sortIcon.removeClass('fa-sort fa-sort-desc').addClass('fa-sort-asc'); } }); }, _indicateInitialSortColumns: function() { var $this = this; for(var i = 0; i < this.options.sortMeta.length; i++) { var meta = this.options.sortMeta[i]; this._indicateInitialSortColumn(meta.field, meta.order); } }, _onDataInit: function(data) { this.data = data; if(!this.data) { this.data = []; } this._initialize(); }, _onDataUpdate: function(data) { this.data = data; if(!this.data) { this.data = []; } this.reset(); this._renderData(); }, _onLazyLoad: function(data) { this.data = data; if(!this.data) { this.data = []; } this._renderData(); }, reset: function() { if(this.options.selectionMode) { this.selection = []; } if(this.paginator) { this.paginator.puipaginator('setState', { page: 0, totalRecords: this.options.lazy ? this.options.paginator.totalRecords : this.data.length }); } this.thead.find('> tr > th.ui-sortable-column').data('order', 0).filter('.ui-state-active').removeClass('ui-state-active') .children('span.ui-sortable-column-icon').removeClass('fa-sort-asc fa-sort-desc').addClass('fa-sort'); }, _isMultiSort: function() { if(this.options.sortMode === 'multiple') return true; else return false; }, _resetSortState: function(column) { this.sortableColumns.filter('.ui-state-active').data('order', 0).removeClass('ui-state-active').children('span.ui-sortable-column-icon') .removeClass('fa-sort-asc fa-sort-desc').addClass('fa-sort'); }, _initSorting: function() { var $this = this; this.sortableColumns = this.thead.find('> tr > th.ui-sortable-column'); this.sortableColumns.on('mouseover.puidatatable', function() { var column = $(this); if(!column.hasClass('ui-state-active')) column.addClass('ui-state-hover'); }) .on('mouseout.puidatatable', function() { var column = $(this); if(!column.hasClass('ui-state-active')) column.removeClass('ui-state-hover'); }) .on('click.puidatatable', function(event) { if(!$(event.target).is('th,span')) { return; } var column = $(this), sortField = column.data('field'), order = column.data('order'), sortOrder = (order === 0) ? 1 : (order * -1), sortIcon = column.children('.ui-sortable-column-icon'), metaKey = event.metaKey||event.ctrlKey; if($this._isMultiSort()) { if(metaKey) { $this._addSortMeta({field: sortField, order: sortOrder}); $this.sort(); } else { $this.options.sortMeta = []; $this._addSortMeta({field: sortField, order: sortOrder}); $this._resetSortState(column); $this.sort(); } } else { //update state $this.options.sortField = sortField; $this.options.sortOrder = sortOrder; $this._resetSortState(column); $this.sort(); } //update visuals column.data('order', sortOrder).removeClass('ui-state-hover').addClass('ui-state-active'); if(sortOrder === -1) sortIcon.removeClass('fa-sort fa-sort-asc').addClass('fa-sort-desc'); else if(sortOrder === 1) sortIcon.removeClass('fa-sort fa-sort-desc').addClass('fa-sort-asc'); $this._trigger('sort', event, {'sortOrder': sortOrder, 'sortField': sortField}); }); }, _addSortMeta: function(meta) { var index = -1; for(var i = 0; i < this.options.sortMeta.length; i++) { if(this.options.sortMeta[i].field === meta.field) { index = i; } } if(index >= 0) this.options.sortMeta[index] = meta; else this.options.sortMeta.push(meta); }, paginate: function() { if(this.options.lazy) { this.options.datasource.call(this, this._onLazyLoad, this._createStateMeta()); } else { this._renderData(); } }, _multipleSort: function() { var $this = this; function multisort(data1,data2,sortMeta,index) { var value1 = data1[sortMeta[index].field], value2 = data2[sortMeta[index].field], result = null; if (typeof value1 == 'string' || value1 instanceof String) { if (value1.localeCompare && (value1 != value2)) { return (sortMeta[index].order * value1.localeCompare(value2)); } } else { result = (value1 < value2) ? -1 : 1; } if(value1 == value2) { return (sortMeta.length - 1) > (index) ? (multisort(data1, data2, sortMeta, index + 1)) : 0; } return (sortMeta[index].order * result); } this.data.sort(function (data1,data2) { return multisort(data1, data2, $this.options.sortMeta, 0); }); this._renderData(); }, sort: function() { if(this.options.lazy) { this.options.datasource.call(this, this._onLazyLoad, this._createStateMeta()); } else { if(this._isMultiSort()) this._multipleSort(); else this._singleSort(); } }, _singleSort: function() { var $this = this; this.data.sort(function(data1, data2) { var value1 = data1[$this.options.sortField], value2 = data2[$this.options.sortField], result = null; if (typeof value1 == 'string' || value1 instanceof String) { if ( value1.localeCompare ) { return ($this.options.sortOrder * value1.localeCompare(value2)); } else { if (value1.toLowerCase) { value1 = value1.toLowerCase(); } if (value2.toLowerCase) { value2 = value2.toLowerCase(); } result = (value1 < value2) ? -1 : (value1 > value2) ? 1 : 0; } } else { result = (value1 < value2) ? -1 : (value1 > value2) ? 1 : 0; } return ($this.options.sortOrder * result); }); if(this.paginator) { this.paginator.puipaginator('option', 'page', 0); } this._renderData(); }, sortByField: function(a, b) { var aName = a.name.toLowerCase(); var bName = b.name.toLowerCase(); return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0)); }, sortByDefault: function() { if(this._isMultiSort()) { if(this.options.sortMeta) { this._indicateInitialSortColumns(); this.sort(); } } else { this._indicateInitialSortColumn(this.options.sortField, this.options.sortOrder); this.sort(); } }, _renderData: function() { this.tbody.html(''); var dataToRender = this.filteredData||this.data; if(dataToRender && dataToRender.length) { var firstNonLazy = this._getFirst(), first = this.options.lazy ? 0 : firstNonLazy, rows = this._getRows(); for(var i = first; i < (first + rows); i++) { var rowData = dataToRender[i]; if(rowData) { var row = $('<tr class="ui-widget-content" />').appendTo(this.tbody), zebraStyle = (i%2 === 0) ? 'ui-datatable-even' : 'ui-datatable-odd', rowIndex = i; row.addClass(zebraStyle); row.data('rowdata', rowData); if(this.options.selectionMode && this._isSelected(rowData)) { row.addClass("ui-state-highlight"); } for(var j = 0; j < this.options.columns.length; j++) { var column = $('<td />').appendTo(row), columnOptions = this.options.columns[j]; if(columnOptions.bodyClass) { column.addClass(columnOptions.bodyClass); } if(columnOptions.bodyStyle) { column.attr('style', columnOptions.bodyStyle); } if(columnOptions.editor) { column.addClass('ui-editable-column').data({ 'editor': columnOptions.editor, 'rowdata': rowData, 'field': columnOptions.field }); } if(columnOptions.content) { var content = columnOptions.content.call(this, rowData, columnOptions); if($.type(content) === 'string') column.html(content); else column.append(content); } else if(columnOptions.rowToggler) { column.append('<div class="ui-row-toggler fa fa-fw fa-chevron-circle-right ui-c"></div>'); } else if(columnOptions.field) { column.text(rowData[columnOptions.field]); } if(this.options.responsive && columnOptions.headerText) { column.prepend('<span class="ui-column-title">' + columnOptions.headerText + '</span>'); } } } } } else { var emptyRow = $('<tr class="ui-widget-content"></tr>').appendTo(this.tbody); var emptyColumn = $('<td></td>').attr('colspan',this.options.columns.length).appendTo(emptyRow); emptyColumn.html(this.options.emptyMessage); } }, _getFirst: function() { if(this.paginator) { var page = this.paginator.puipaginator('option', 'page'), rows = this.paginator.puipaginator('option', 'rows'); return (page * rows); } else { return 0; } }, _getRows: function() { return this.paginator ? this.paginator.puipaginator('option', 'rows') : (this.data ? this.data.length : 0); }, _isSortingEnabled: function() { var cols = this.options.columns; if(cols) { for(var i = 0; i < cols.length; i++) { if(cols[i].sortable) { return true; } } } return false; }, _initSelection: function() { var $this = this; this.selection = []; this.rowSelector = '> tr.ui-widget-content:not(.ui-datatable-empty-message,.ui-datatable-unselectable)'; //shift key based range selection if(this._isMultipleSelection()) { this.originRowIndex = 0; this.cursorIndex = null; } this.tbody.off('mouseover.puidatatable mouseout.puidatatable mousedown.puidatatable click.puidatatable', this.rowSelector) .on('mouseover.datatable', this.rowSelector, null, function() { var element = $(this); if(!element.hasClass('ui-state-highlight')) { element.addClass('ui-state-hover'); } }) .on('mouseout.datatable', this.rowSelector, null, function() { var element = $(this); if(!element.hasClass('ui-state-highlight')) { element.removeClass('ui-state-hover'); } }) .on('mousedown.datatable', this.rowSelector, null, function() { $this.mousedownOnRow = true; }) .on('click.datatable', this.rowSelector, null, function(e) { $this._onRowClick(e, this); $this.mousedownOnRow = false; }); this._bindSelectionKeyEvents(); }, _onRowClick: function(event, rowElement) { if(!$(event.target).is(':input,:button,a,.ui-c')) { var row = $(rowElement), selected = row.hasClass('ui-state-highlight'), metaKey = event.metaKey||event.ctrlKey, shiftKey = event.shiftKey; this.focusedRow = row; //unselect a selected row if metakey is on if(selected && metaKey) { this.unselectRow(row); } else { //unselect previous selection if this is single selection or multiple one with no keys if(this._isSingleSelection() || (this._isMultipleSelection() && !metaKey && !shiftKey)) { if (this._isMultipleSelection()) { var selections = this.getSelection(); for (var i = 0; i < selections.length; i++) { this._trigger('rowUnselect', null, selections[i]); } } this.unselectAllRows(); } this.selectRow(row, false, event); } PUI.clearSelection(); } }, onRowRightClick: function(event, rowElement) { var row = $(rowElement), selectedData = row.data('rowdata'), selected = row.hasClass('ui-state-highlight'); if(this._isSingleSelection() || !selected) { this.unselectAllRows(); } this.selectRow(row, true); this.dataSelectedByContextMenu = selectedData; this._trigger('rowSelectContextMenu', event, selectedData); PUI.clearSelection(); }, _bindSelectionKeyEvents: function() { var $this = this; this.tbody.attr('tabindex', this.options.tabindex).on('focus', function(e) { //ignore mouse click on row if(!$this.mousedownOnRow) { $this.focusedRow = $this.tbody.children('tr.ui-widget-content').eq(0); $this.focusedRow.addClass('ui-state-hover'); } }) .on('blur', function() { if($this.focusedRow) { $this.focusedRow.removeClass('ui-state-hover'); $this.focusedRow = null; } }) .on('keydown', function(e) { var keyCode = $.ui.keyCode, key = e.which; if($this.focusedRow) { switch(key) { case keyCode.UP: var prevRow = $this.focusedRow.prev('tr.ui-widget-content'); if(prevRow.length) { $this.focusedRow.removeClass('ui-state-hover'); $this.focusedRow = prevRow; $this.focusedRow.addClass('ui-state-hover'); } e.preventDefault(); break; case keyCode.DOWN: var nextRow = $this.focusedRow.next('tr.ui-widget-content'); if(nextRow.length) { $this.focusedRow.removeClass('ui-state-hover'); $this.focusedRow = nextRow; $this.focusedRow.addClass('ui-state-hover'); } e.preventDefault(); break; case keyCode.ENTER: case keyCode.NUMPAD_ENTER: case keyCode.SPACE: e.target = $this.focusedRow.children().eq(0).get(0); $this._onRowClick(e, $this.focusedRow.get(0)); e.preventDefault(); break; default: break; }; } }); }, _isSingleSelection: function() { return this.options.selectionMode === 'single'; }, _isMultipleSelection: function() { return this.options.selectionMode === 'multiple'; }, unselectAllRows: function() { this.tbody.children('tr.ui-state-highlight').removeClass('ui-state-highlight').attr('aria-selected', false); this.selection = []; }, unselectRow: function(row, silent) { var unselectedData = row.data('rowdata'); row.removeClass('ui-state-highlight').attr('aria-selected', false); this._removeSelection(unselectedData); if(!silent) { this._trigger('rowUnselect', null, unselectedData); } }, selectRow: function(row, silent, event) { var selectedData = row.data('rowdata'); row.removeClass('ui-state-hover').addClass('ui-state-highlight').attr('aria-selected', true); this._addSelection(selectedData); if(!silent) { this._trigger('rowSelect', event, selectedData); } }, getSelection: function() { return this.selection; }, _removeSelection: function(rowData) { this.selection = $.grep(this.selection, function(value) { return value !== rowData; }); }, _addSelection: function(rowData) { if(!this._isSelected(rowData)) { this.selection.push(rowData); } }, _isSelected: function(rowData) { return PUI.inArray(this.selection, rowData); }, _initExpandableRows: function() { var $this = this, togglerSelector = '> tr > td > div.ui-row-toggler'; this.tbody.off('click', togglerSelector) .on('click', togglerSelector, null, function() { $this.toggleExpansion($(this)); }) .on('keydown', togglerSelector, null, function(e) { var key = e.which, keyCode = $.ui.keyCode; if((key === keyCode.ENTER||key === keyCode.NUMPAD_ENTER)) { $this.toggleExpansion($(this)); e.preventDefault(); } }); }, toggleExpansion: function(toggler) { var row = toggler.closest('tr'), expanded = toggler.hasClass('fa-chevron-circle-down'); if(expanded) { toggler.addClass('fa-chevron-circle-right').removeClass('fa-chevron-circle-down').attr('aria-expanded', false); this.collapseRow(row); this._trigger('rowCollapse', null, row.data('rowdata')); } else { if(this.options.rowExpandMode === 'single') { this.collapseAllRows(); } toggler.addClass('fa-chevron-circle-down').removeClass('fa-chevron-circle-right').attr('aria-expanded', true); this.loadExpandedRowContent(row); } }, loadExpandedRowContent: function(row) { var expandedRow = $('<tr class="ui-expanded-row-content ui-datatable-unselectable ui-widget-content"><td colspan="' + this.options.columns.length + '"></td></tr>'); expandedRow.children('td').append(this.options.expandedRowContent.call(this, row.data('rowdata'))); row.addClass('ui-expanded-row').after(expandedRow); this._trigger('rowExpand', null, row.data('rowdata')); }, collapseRow: function(row) { row.removeClass('ui-expanded-row').next('.ui-expanded-row-content').remove(); }, collapseAllRows: function() { var $this = this; this.getExpandedRows().each(function () { var expandedRow = $(this); $this.collapseRow(expandedRow); var columns = expandedRow.children('td'); for (var i = 0; i < columns.length; i++) { var column = columns.eq(i), toggler = column.children('.ui-row-toggler'); if (toggler.length) { toggler.addClass('fa-chevron-circle-right').removeClass('fa-chevron-circle-down'); } } }); }, getExpandedRows: function () { return this.tbody.children('.ui-expanded-row'); }, _createStateMeta: function() { var state = { first: this._getFirst(), rows: this._getRows(), sortField: this.options.sortField, sortOrder: this.options.sortOrder, sortMeta: this.options.sortMeta, filters: this.filterMetaMap }; return state; }, _updateDatasource: function(datasource) { this.options.datasource = datasource; if($.isArray(this.options.datasource)) { this._onDataUpdate(this.options.datasource); } else if($.type(this.options.datasource) === 'function') { if(this.options.lazy) this.options.datasource.call(this, this._onDataUpdate, {first:0, rows: this._getRows(), sortField:this.options.sortField, sortorder:this.options.sortOrder, filters: this._createFilterMap()}); else this.options.datasource.call(this, this._onDataUpdate); } }, _setOption: function(key, value) { if(key === 'datasource') { this._updateDatasource(value); } else { $.Widget.prototype._setOption.apply(this, arguments); } }, _initScrolling: function() { this.scrollHeader = this.element.children('.ui-datatable-scrollable-header'); this.scrollBody = this.element.children('.ui-datatable-scrollable-body'); this.scrollFooter = this.element.children('.ui-datatable-scrollable-footer'); this.scrollHeaderBox = this.scrollHeader.children('.ui-datatable-scrollable-header-box'); this.headerTable = this.scrollHeaderBox.children('table'); this.bodyTable = this.scrollBody.children('table'); this.percentageScrollHeight = this.options.scrollHeight && (this.options.scrollHeight.indexOf('%') !== -1); this.percentageScrollWidth = this.options.scrollWidth && (this.options.scrollWidth.indexOf('%') !== -1); var $this = this, scrollBarWidth = this.getScrollbarWidth() + 'px'; if(this.options.scrollHeight) { if(this.percentageScrollHeight) this.adjustScrollHeight(); else this.scrollBody.css('max-height', this.options.scrollHeight + 'px'); if(this.hasVerticalOverflow()) { this.scrollHeaderBox.css('margin-right', scrollBarWidth); } } this.fixColumnWidths(); if(this.options.scrollWidth) { if(this.percentageScrollWidth) this.adjustScrollWidth(); else this.setScrollWidth(parseInt(this.options.scrollWidth)); } this.cloneHead(); this.scrollBody.on('scroll.dataTable', function() { var scrollLeft = $this.scrollBody.scrollLeft(); $this.scrollHeaderBox.css('margin-left', -scrollLeft); }); this.scrollHeader.on('scroll.dataTable', function() { $this.scrollHeader.scrollLeft(0); }); var resizeNS = 'resize.' + this.id; $(window).off(resizeNS).on(resizeNS, function() { if($this.element.is(':visible')) { if($this.percentageScrollHeight) $this.adjustScrollHeight(); if($this.percentageScrollWidth) $this.adjustScrollWidth(); } }); }, cloneHead: function() { this.theadClone = this.thead.clone(); this.theadClone.find('th').each(function() { var header = $(this); header.attr('id', header.attr('id') + '_clone'); $(this).children().not('.ui-column-title').remove(); }); this.theadClone.removeAttr('id').addClass('ui-datatable-scrollable-theadclone').height(0).prependTo(this.bodyTable); //align horizontal scroller on keyboard tab if(this.options.scrollWidth) { var clonedSortableColumns = this.theadClone.find('> tr > th.ui-sortable-column'); clonedSortableColumns.each(function() { $(this).data('original', $(this).attr('id').split('_clone')[0]); }); clonedSortableColumns.on('blur.dataTable', function() { $(PUI.escapeClientId($(this).data('original'))).removeClass('ui-state-focus'); }) .on('focus.dataTable', function() { $(PUI.escapeClientId($(this).data('original'))).addClass('ui-state-focus'); }) .on('keydown.dataTable', function(e) { var key = e.which, keyCode = $.ui.keyCode; if((key === keyCode.ENTER||key === keyCode.NUMPAD_ENTER) && $(e.target).is(':not(:input)')) { $(PUI.escapeClientId($(this).data('original'))).trigger('click.dataTable', (e.metaKey||e.ctrlKey)); e.preventDefault(); } }); } }, adjustScrollHeight: function() { var relativeHeight = this.element.parent().innerHeight() * (parseInt(this.options.scrollHeight) / 100), tableHeaderHeight = this.element.children('.ui-datatable-header').outerHeight(true), tableFooterHeight = this.element.children('.ui-datatable-footer').outerHeight(true), scrollersHeight = (this.scrollHeader.outerHeight(true) + this.scrollFooter.outerHeight(true)), paginatorsHeight = this.paginator ? this.paginator.getContainerHeight(true) : 0, height = (relativeHeight - (scrollersHeight + paginatorsHeight + tableHeaderHeight + tableFooterHeight)); this.scrollBody.css('max-height', height + 'px'); }, adjustScrollWidth: function() { var width = parseInt((this.element.parent().innerWidth() * (parseInt(this.options.scrollWidth) / 100))); this.setScrollWidth(width); }, setOuterWidth: function(element, width) { var diff = element.outerWidth() - element.width(); element.width(width - diff); }, setScrollWidth: function(width) { var $this = this; this.element.children('.ui-widget-header').each(function() { $this.setOuterWidth($(this), width); }); this.scrollHeader.width(width); this.scrollBody.css('margin-right', 0).width(width); }, alignScrollBody: function() { var marginRight = this.hasVerticalOverflow() ? this.getScrollbarWidth() + 'px' : '0px'; this.scrollHeaderBox.css('margin-right', marginRight); }, getScrollbarWidth: function() { if(!this.scrollbarWidth) { this.scrollbarWidth = PUI.browser.webkit ? '15' : PUI.calculateScrollbarWidth(); } return this.scrollbarWidth; }, hasVerticalOverflow: function() { return (this.options.scrollHeight && this.bodyTable.outerHeight() > this.scrollBody.outerHeight()) }, restoreScrollState: function() { var scrollState = this.scrollStateHolder.val(), scrollValues = scrollState.split(','); this.scrollBody.scrollLeft(scrollValues[0]); this.scrollBody.scrollTop(scrollValues[1]); }, saveScrollState: function() { var scrollState = this.scrollBody.scrollLeft() + ',' + this.scrollBody.scrollTop(); this.scrollStateHolder.val(scrollState); }, clearScrollState: function() { this.scrollStateHolder.val('0,0'); }, fixColumnWidths: function() { if(!this.columnWidthsFixed) { if(this.options.scrollable) { this.scrollHeaderBox.find('> table > thead > tr > th').each(function() { var headerCol = $(this), width = headerCol.width(); headerCol.width(width); }); } else { this.element.find('> .ui-datatable-tablewrapper > table > thead > tr > th').each(function() { var col = $(this); col.width(col.width()); }); } this.columnWidthsFixed = true; } }, _initDraggableColumns: function() { var $this = this; this.dragIndicatorTop = $('<span class="fa fa-arrow-down" style="position:absolute"/></span>').hide().appendTo(this.element); this.dragIndicatorBottom = $('<span class="fa fa-arrow-up" style="position:absolute"/></span>').hide().appendTo(this.element); this.thead.find('> tr > th').draggable({ appendTo: 'body', opacity: 0.75, cursor: 'move', scope: this.id, cancel: ':input,.ui-column-resizer', drag: function(event, ui) { var droppable = ui.helper.data('droppable-column'); if(droppable) { var droppableOffset = droppable.offset(), topArrowY = droppableOffset.top - 10, bottomArrowY = droppableOffset.top + droppable.height() + 8, arrowX = null; //calculate coordinates of arrow depending on mouse location if(event.originalEvent.pageX >= droppableOffset.left + (droppable.width() / 2)) { var nextDroppable = droppable.next(); if(nextDroppable.length == 1) arrowX = nextDroppable.offset().left - 9; else arrowX = droppable.offset().left + droppable.innerWidth() - 9; ui.helper.data('drop-location', 1); //right } else { arrowX = droppableOffset.left - 9; ui.helper.data('drop-location', -1); //left } $this.dragIndicatorTop.offset({ 'left': arrowX, 'top': topArrowY - 3 }).show(); $this.dragIndicatorBottom.offset({ 'left': arrowX, 'top': bottomArrowY - 3 }).show(); } }, stop: function(event, ui) { //hide dnd arrows $this.dragIndicatorTop.css({ 'left':0, 'top':0 }).hide(); $this.dragIndicatorBottom.css({ 'left':0, 'top':0 }).hide(); }, helper: function() { var header = $(this), helper = $('<div class="ui-widget ui-state-default" style="padding:4px 10px;text-align:center;"></div>'); helper.width(header.width()); helper.height(header.height()); helper.html(header.html()); return helper.get(0); } }).droppable({ hoverClass:'ui-state-highlight', tolerance:'pointer', scope: this.id, over: function(event, ui) { ui.helper.data('droppable-column', $(this)); }, drop: function(event, ui) { var draggedColumnHeader = ui.draggable, dropLocation = ui.helper.data('drop-location'), droppedColumnHeader = $(this), draggedColumnFooter = null, droppedColumnFooter = null; var draggedCells = $this.tbody.find('> tr:not(.ui-expanded-row-content) > td:nth-child(' + (draggedColumnHeader.index() + 1) + ')'), droppedCells = $this.tbody.find('> tr:not(.ui-expanded-row-content) > td:nth-child(' + (droppedColumnHeader.index() + 1) + ')'); if($this.containsFooter()) { var footerColumns = $this.tfoot.find('> tr > td'), draggedColumnFooter = footerColumns.eq(draggedColumnHeader.index()), droppedColumnFooter = footerColumns.eq(droppedColumnHeader.index()); } //drop right if(dropLocation > 0) { /* TODO :Resizable columns * if($this.options.resizableColumns) { if(droppedColumnHeader.next().length) { droppedColumnHeader.children('span.ui-column-resizer').show(); draggedColumnHeader.children('span.ui-column-resizer').hide(); } }*/ draggedColumnHeader.insertAfter(droppedColumnHeader); draggedCells.each(function(i, item) { $(this).insertAfter(droppedCells.eq(i)); }); if(draggedColumnFooter && droppedColumnFooter) { draggedColumnFooter.insertAfter(droppedColumnFooter); } //sync clone if($this.options.scrollable) { var draggedColumnClone = $(document.getElementById(draggedColumnHeader.attr('id') + '_clone')), droppedColumnClone = $(document.getElementById(droppedColumnHeader.attr('id') + '_clone')); draggedColumnClone.insertAfter(droppedColumnClone); } } //drop left else { draggedColumnHeader.insertBefore(droppedColumnHeader); draggedCells.each(function(i, item) { $(this).insertBefore(droppedCells.eq(i)); }); if(draggedColumnFooter && droppedColumnFooter) { draggedColumnFooter.insertBefore(droppedColumnFooter); } //sync clone if($this.options.scrollable) { var draggedColumnClone = $(document.getElementById(draggedColumnHeader.attr('id') + '_clone')), droppedColumnClone = $(document.getElementById(droppedColumnHeader.attr('id') + '_clone')); draggedColumnClone.insertBefore(droppedColumnClone); } } //fire colReorder event $this._trigger('colReorder', null, { dragIndex: draggedColumnHeader.index(), dropIndex: droppedColumnHeader.index() }); } }); }, containsFooter: function() { if(this.hasFooter === undefined) { this.hasFooter = this.options.footerRows !== undefined; if(!this.hasFooter) { if(this.options.columns) { for(var i = 0; i < this.options.columns.length; i++) { if(this.options.columns[i].footerText !== undefined) { this.hasFooter = true; break; } } } } } return this.hasFooter; }, _initResizableColumns: function() { this.element.addClass('ui-datatable-resizable'); this.thead.find('> tr > th').addClass('ui-resizable-column'); this.resizerHelper = $('<div class="ui-column-resizer-helper ui-state-highlight"></div>').appendTo(this.element); this.addResizers(); var resizers = this.thead.find('> tr > th > span.ui-column-resizer'), $this = this; setTimeout(function() { $this.fixColumnWidths(); }, 5); resizers.draggable({ axis: 'x', start: function(event, ui) { ui.helper.data('originalposition', ui.helper.offset()); var height = $this.options.scrollable ? $this.scrollBody.height() : $this.thead.parent().height() - $this.thead.height() - 1; $this.resizerHelper.height(height); $this.resizerHelper.show(); }, drag: function(event, ui) { $this.resizerHelper.offset({ left: ui.helper.offset().left + ui.helper.width() / 2, top: $this.thead.offset().top + $this.thead.height() }); }, stop: function(event, ui) { ui.helper.css({ 'left': '', 'top': '0px', 'right': '0px' }); $this.resize(event, ui); $this.resizerHelper.hide(); if($this.options.columnResizeMode === 'expand') { setTimeout(function() { $this._trigger('colResize', null, {element: ui.helper.parent()}); }, 5); } else { $this._trigger('colResize', null, {element: ui.helper.parent()}); } if($this.options.stickyHeader) { $this.thead.find('.ui-column-filter').prop('disabled', false); $this.clone = $this.thead.clone(true); $this.cloneContainer.find('thead').remove(); $this.cloneContainer.children('table').append($this.clone); $this.thead.find('.ui-column-filter').prop('disabled', true); } }, containment: this.element }); }, resize: function(event, ui) { var columnHeader, nextColumnHeader, change = null, newWidth = null, nextColumnWidth = null, expandMode = (this.options.columnResizeMode === 'expand'), table = this.thead.parent(), columnHeader = ui.helper.parent(), nextColumnHeader = columnHeader.next(); change = (ui.position.left - ui.originalPosition.left), newWidth = (columnHeader.width() + change), nextColumnWidth = (nextColumnHeader.width() - change); if((newWidth > 15 && nextColumnWidth > 15) || (expandMode && newWidth > 15)) { if(expandMode) { table.width(table.width() + change); setTimeout(function() { columnHeader.width(newWidth); }, 1); } else { columnHeader.width(newWidth); nextColumnHeader.width(nextColumnWidth); } if(this.options.scrollable) { var cloneTable = this.theadClone.parent(), colIndex = columnHeader.index(); if(expandMode) { var $this = this; //body cloneTable.width(cloneTable.width() + change); //footer this.footerTable.width(this.footerTable.width() + change); setTimeout(function() { if($this.hasColumnGroup) { $this.theadClone.find('> tr:first').children('th').eq(colIndex).width(newWidth); //body $this.footerTable.find('> tfoot > tr:first').children('th').eq(colIndex).width(newWidth); //footer } else { $this.theadClone.find(PUI.escapeClientId(columnHeader.attr('id') + '_clone')).width(newWidth); //body $this.footerCols.eq(colIndex).width(newWidth); //footer } }, 1); } else { //body this.theadClone.find(PUI.escapeClientId(columnHeader.attr('id') + '_clone')).width(newWidth); this.theadClone.find(PUI.escapeClientId(nextColumnHeader.attr('id') + '_clone')).width(nextColumnWidth); //footer /*if(this.footerCols.length > 0) { var footerCol = this.footerCols.eq(colIndex), nextFooterCol = footerCol.next(); footerCol.width(newWidth); nextFooterCol.width(nextColumnWidth); }*/ } } } }, addResizers: function() { var resizableColumns = this.thead.find('> tr > th.ui-resizable-column'); resizableColumns.prepend('<span class="ui-column-resizer">&nbsp;</span>'); if(this.options.columnResizeMode === 'fit') { resizableColumns.filter(':last-child').children('span.ui-column-resizer').hide(); } }, _initDraggableRows: function() { var $this = this; this.tbody.sortable({ placeholder: 'ui-datatable-rowordering ui-state-active', cursor: 'move', handle: 'td,span:not(.ui-c)', appendTo: document.body, helper: function(event, ui) { var cells = ui.children(), helper = $('<div class="ui-datatable ui-widget"><table><tbody></tbody></table></div>'), helperRow = ui.clone(), helperCells = helperRow.children(); for(var i = 0; i < helperCells.length; i++) { helperCells.eq(i).width(cells.eq(i).width()); } helperRow.appendTo(helper.find('tbody')); return helper; }, update: function(event, ui) { $this.syncRowParity(); $this._trigger('rowReorder', null, { fromIndex: ui.item.data('ri'), toIndex: $this._getFirst() + ui.item.index() }); }, change: function(event, ui) { if($this.options.scrollable) { PUI.scrollInView($this.scrollBody, ui.placeholder); } } }); }, syncRowParity: function() { var rows = this.tbody.children('tr.ui-widget-content'); for(var i = this._getFirst(); i < rows.length; i++) { var row = rows.eq(i); row.data('ri', i).removeClass('ui-datatable-even ui-datatable-odd'); if(i % 2 === 0) row.addClass('ui-datatable-even'); else row.addClass('ui-datatable-odd'); } }, getContextMenuSelection: function(data) { return this.dataSelectedByContextMenu; }, _initFiltering: function() { var $this = this; this.filterElements = this.thead.find('.ui-column-filter'); this.filterElements.on('keyup', function() { if($this.filterTimeout) { clearTimeout($this.filterTimeout); } $this.filterTimeout = setTimeout(function() { $this.filter(); $this.filterTimeout = null; }, $this.options.filterDelay); }); if(this.options.globalFilter) { $(this.options.globalFilter).on('keyup.puidatatable', function() { $this.filter(); }); } }, filter: function() { this.filterMetaMap = []; for(var i = 0; i < this.filterElements.length; i++) { var filterElement = this.filterElements.eq(i), filterElementValue = filterElement.val(); this.filterMetaMap.push({ field: filterElement.data('field'), filterMatchMode: filterElement.data('filtermatchmode'), value: filterElementValue.toLowerCase(), element: filterElement }); } if(this.options.lazy) { this.options.datasource.call(this, this._onLazyLoad, this._createStateMeta()); } else { var globalFilterValue = $(this.options.globalFilter).val(); this.filteredData = []; for(var i = 0; i < this.data.length; i++) { var localMatch = true; var globalMatch = false; for(var j = 0; j < this.filterMetaMap.length; j++) { var filterMeta = this.filterMetaMap[j], filterValue = filterMeta.value, filterField = filterMeta.field, dataFieldValue = this.data[i][filterField]; var filterConstraint = this.filterConstraints[filterMeta.filterMatchMode]; //global if(this.options.globalFilter && !globalMatch) { var filterConstraint = this.filterConstraints['contains']; globalMatch = filterConstraint(dataFieldValue, globalFilterValue); } //local if(filterMeta.filterMatchMode === 'custom') { localMatch = filterMeta.element.triggerHandler('filter', [dataFieldValue, filterValue]); } else { var filterConstraint = this.filterConstraints[filterMeta.filterMatchMode]; if(!filterConstraint(dataFieldValue, filterValue)) { localMatch = false; } } if(!localMatch) { break; } } var matches = localMatch; if(this.options.globalFilter) { matches = localMatch && globalMatch; } if(matches) { this.filteredData.push(this.data[i]); } } if(this.filteredData.length === this.data.length) { this.filteredData = null; } if(this.paginator) { this.paginator.puipaginator('option', 'totalRecords', this.filteredData ? this.filteredData.length : this.data ? this.data.length : 0); } this._renderData(); } }, filterConstraints: { startsWith: function(value, filter) { if(filter === undefined || filter === null || $.trim(filter) === '') { return true; } if(value === undefined || value === null) { return false; } return value.toString().toLowerCase().slice(0, filter.length) === filter; }, contains: function(value, filter) { if(filter === undefined || filter === null || $.trim(filter) === '') { return true; } if(value === undefined || value === null) { return false; } return value.toString().toLowerCase().indexOf(filter) !== -1; } }, _initStickyHeader: function() { var table = this.thead.parent(), offset = table.offset(), win = $(window), $this = this, stickyNS = 'scroll.' + this.id, resizeNS = 'resize.sticky-' + this.id; this.cloneContainer = $('<div class="ui-datatable ui-datatable-sticky ui-widget"><table></table></div>'); this.clone = this.thead.clone(true); this.cloneContainer.children('table').append(this.clone); this.cloneContainer.css({ position: 'absolute', width: table.outerWidth(), top: offset.top, left: offset.left, 'z-index': ++PUI.zindex }) .appendTo(this.element); win.off(stickyNS).on(stickyNS, function() { var scrollTop = win.scrollTop(), tableOffset = table.offset(); if(scrollTop > tableOffset.top) { $this.cloneContainer.css({ 'position': 'fixed', 'top': '0px' }) .addClass('ui-shadow ui-sticky'); if(scrollTop >= (tableOffset.top + $this.tbody.height())) $this.cloneContainer.hide(); else $this.cloneContainer.show(); } else { $this.cloneContainer.css({ 'position': 'absolute', 'top': tableOffset.top }) .removeClass('ui-shadow ui-sticky'); } }) .off(resizeNS).on(resizeNS, function() { $this.cloneContainer.width(table.outerWidth()); }); //filter support this.thead.find('.ui-column-filter').prop('disabled', true); }, _initEditing: function() { var cellSelector = '> tr > td.ui-editable-column', $this = this; this.tbody.off('click', cellSelector) .on('click', cellSelector, null, function(e) { var cell = $(this); if(!cell.hasClass('ui-cell-editing')) { $this._showCellEditor(cell); e.stopPropagation(); } }); }, _showCellEditor: function(cell) { var editor = this.editors[cell.data('editor')].call(), $this = this; editor.val(cell.data('rowdata')[cell.data('field')]); cell.addClass('ui-cell-editing').html('').append(editor); editor.focus().on('change', function() { $this._onCellEditorChange(cell); }) .on('blur', function() { $this._onCellEditorBlur(cell); }) .on('keydown', function(e) { var key = e.which, keyCode = $.ui.keyCode; if((key === keyCode.ENTER||key === keyCode.NUMPAD_ENTER)) { $(this).trigger('change').trigger('blur'); e.preventDefault(); } else if(key === keyCode.TAB) { if(e.shiftKey) { var prevCell = cell.prevAll('td.ui-editable-column').eq(0); if(!prevCell.length) { prevCell = cell.parent().prev('tr').children('td.ui-editable-column:last'); } if(prevCell.length) { $this._showCellEditor(prevCell); } } else { var nextCell = cell.nextAll('td.ui-editable-column').eq(0); if(!nextCell.length) { nextCell = cell.parent().next('tr').children('td.ui-editable-column').eq(0); } if(nextCell.length) { $this._showCellEditor(nextCell); } } e.preventDefault(); } else if(key === keyCode.ESCAPE) { $this._onCellEditorBlur(cell); } }); }, _onCellEditorChange: function(cell) { var newCellValue = cell.children('.ui-cell-editor').val(); var retVal = this._trigger('cellEdit', null, { oldValue: cell.data('rowdata')[cell.data('field')], newValue: newCellValue, data: cell.data('rowdata'), field: cell.data('field') }); if(retVal !== false) { cell.data('rowdata')[cell.data('field')] = newCellValue; } }, _onCellEditorBlur: function(cell) { cell.removeClass('ui-cell-editing').text(cell.data('rowdata')[cell.data('field')]) .children('.ui-cell-editor').remove(); }, reload: function() { this._updateDatasource(this.options.datasource); }, getPaginator: function() { return this.paginator; }, setTotalRecords: function(val) { this.paginator.puipaginator('option','totalRecords', val); }, _createFilterMap: function() { var filters = null; if(this.filterElements) { filters = {}; for(var i = 0; i < this.filterElements.length; i++) { var filterElement = this.filterElements.eq(i), value = filterElement.val(); if($.trim(value).length) { filters[filterElement.data('field')] = value; } } } return filters; }, editors: { 'input': function() { return $('<input type="text" class="ui-cell-editor"/>'); } } }); })(); /** * PrimeUI Dialog Widget */ (function() { $.widget("primeui.puidialog", { options: { draggable: true, resizable: true, location: 'center', minWidth: 150, minHeight: 25, height: 'auto', width: '300px', visible: false, modal: false, showEffect: null, hideEffect: null, effectOptions: {}, effectSpeed: 'normal', closeOnEscape: true, rtl: false, closable: true, minimizable: false, maximizable: false, appendTo: null, buttons: null, responsive: false, title: null, enhanced: false }, _create: function() { this.id = this.element.attr('id'); if(!this.id) { this.id = this.element.uniqueId().attr('id'); } //container if(!this.options.enhanced) { this.element.addClass('ui-dialog ui-widget ui-widget-content ui-helper-hidden ui-corner-all ui-shadow') .contents().wrapAll('<div class="ui-dialog-content ui-widget-content" />'); //header var title = this.options.title||this.element.attr('title'); this.element.prepend('<div class="ui-dialog-titlebar ui-widget-header ui-helper-clearfix ui-corner-top">' + '<span id="' + this.element.attr('id') + '_label" class="ui-dialog-title">' + title + '</span>') .removeAttr('title'); //footer if(this.options.buttons) { this.footer = $('<div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"></div>').appendTo(this.element); for(var i = 0; i < this.options.buttons.length; i++) { var buttonMeta = this.options.buttons[i], button = $('<button type="button"></button>').appendTo(this.footer); if(buttonMeta.text) { button.text(buttonMeta.text); } button.puibutton(buttonMeta); } } if(this.options.rtl) { this.element.addClass('ui-dialog-rtl'); } } //elements this.content = this.element.children('.ui-dialog-content'); this.titlebar = this.element.children('.ui-dialog-titlebar'); if(!this.options.enhanced) { if(this.options.closable) { this._renderHeaderIcon('ui-dialog-titlebar-close', 'fa-close'); } if(this.options.maximizable) { this._renderHeaderIcon('ui-dialog-titlebar-maximize', 'fa-sort'); } if(this.options.minimizable) { this._renderHeaderIcon('ui-dialog-titlebar-minimize', 'fa-minus'); } } //icons this.icons = this.titlebar.children('.ui-dialog-titlebar-icon'); this.closeIcon = this.titlebar.children('.ui-dialog-titlebar-close'); this.minimizeIcon = this.titlebar.children('.ui-dialog-titlebar-minimize'); this.maximizeIcon = this.titlebar.children('.ui-dialog-titlebar-maximize'); this.blockEvents = 'focus.puidialog mousedown.puidialog mouseup.puidialog keydown.puidialog keyup.puidialog'; this.parent = this.element.parent(); //size this.element.css({'width': this.options.width, 'height': 'auto'}); this.content.height(this.options.height); //events this._bindEvents(); if(this.options.draggable) { this._setupDraggable(); } if(this.options.resizable) { this._setupResizable(); } if(this.options.appendTo) { this.element.appendTo(this.options.appendTo); } if(this.options.responsive) { this.resizeNS = 'resize.' + this.id; } //docking zone if($(document.body).children('.ui-dialog-docking-zone').length === 0) { $(document.body).append('<div class="ui-dialog-docking-zone"></div>'); } //aria this._applyARIA(); if(this.options.visible) { this.show(); } }, _destroy: function() { //restore dom if(!this.options.enhanced) { this.element.removeClass('ui-dialog ui-widget ui-widget-content ui-helper-hidden ui-corner-all ui-shadow'); if(this.options.buttons) { this.footer.children('button').puibutton('destroy'); this.footer.remove(); } if(this.options.rtl) { this.element.removeClass('ui-dialog-rtl'); } var title = this.titlebar.children('.ui-dialog-title').text()||this.options.title; if(title) { this.element.attr('title', title); } this.titlebar.remove(); this.content.contents().unwrap(); } //remove events this._unbindEvents(); if(this.options.draggable) { this.element.draggable('destroy'); } if(this.options.resizable) { this.element.resizable('destroy'); } if(this.options.appendTo) { this.element.appendTo(this.parent); } this._unbindResizeListener(); if(this.options.modal) { this._disableModality(); } this._removeARIA(); this.element.css({ 'width': 'auto', 'height': 'auto' }); }, _renderHeaderIcon: function(styleClass, icon) { this.titlebar.append('<a class="ui-dialog-titlebar-icon ' + styleClass + ' ui-corner-all" href="#" role="button">' + '<span class="fa fa-fw ' + icon + '"></span></a>'); }, _enableModality: function() { var $this = this, doc = $(document); this.modality = $('<div id="' + this.element.attr('id') + '_modal" class="ui-widget-overlay ui-dialog-mask"></div>').appendTo(document.body) .css('z-index', this.element.css('z-index') - 1); //Disable tabbing out of modal dialog and stop events from targets outside of dialog doc.on('keydown.puidialog', function(event) { if(event.keyCode == $.ui.keyCode.TAB) { var tabbables = $this.content.find(':tabbable'), first = tabbables.filter(':first'), last = tabbables.filter(':last'); if(event.target === last[0] && !event.shiftKey) { first.focus(1); return false; } else if (event.target === first[0] && event.shiftKey) { last.focus(1); return false; } } }) .bind(this.blockEvents, function(event) { if ($(event.target).zIndex() < $this.element.zIndex()) { return false; } }); }, _disableModality: function() { if(this.modality) { this.modality.remove(); this.modality = null; } $(document).off(this.blockEvents).off('keydown.dialog'); }, show: function() { if(this.element.is(':visible')) { return; } if(!this.positionInitialized) { this._initPosition(); } this._trigger('beforeShow', null); if(this.options.showEffect) { var $this = this; this.element.show(this.options.showEffect, this.options.effectOptions, this.options.effectSpeed, function() { $this._postShow(); }); } else { this.element.show(); this._postShow(); } this._moveToTop(); if(this.options.modal) { this._enableModality(); } }, _postShow: function() { //execute user defined callback this._trigger('afterShow', null); this.element.attr({ 'aria-hidden': false, 'aria-live': 'polite' }); this._applyFocus(); if(this.options.responsive) { this._bindResizeListener(); } }, hide: function() { if(this.element.is(':hidden')) { return; } this._trigger('beforeHide', null); if(this.options.hideEffect) { var _self = this; this.element.hide(this.options.hideEffect, this.options.effectOptions, this.options.effectSpeed, function() { _self._postHide(); }); } else { this.element.hide(); this._postHide(); } if(this.options.modal) { this._disableModality(); } }, _postHide: function() { //execute user defined callback this._trigger('afterHide', null); this.element.attr({ 'aria-hidden': true, 'aria-live': 'off' }); if(this.options.responsive) { this._unbindResizeListener(); } }, _applyFocus: function() { this.element.find(':not(:submit):not(:button):input:visible:enabled:first').focus(); }, _bindEvents: function() { var $this = this; this.element.on('mousedown.puidialog', function(e) { if(!$(e.target).data('ui-widget-overlay')) { $this._moveToTop(); } }); this.icons.mouseover(function() { $(this).addClass('ui-state-hover'); }).mouseout(function() { $(this).removeClass('ui-state-hover'); }); this.closeIcon.on('click.puidialog', function(e) { $this.hide(); $this._trigger('clickClose'); e.preventDefault(); }); this.maximizeIcon.click(function(e) { $this.toggleMaximize(); e.preventDefault(); }); this.minimizeIcon.click(function(e) { $this.toggleMinimize(); e.preventDefault(); }); if(this.options.closeOnEscape) { $(document).on('keydown.dialog_' + this.id, function(e) { var keyCode = $.ui.keyCode, active = parseInt($this.element.css('z-index'), 10) === PUI.zindex; if(e.which === keyCode.ESCAPE && $this.element.is(':visible') && active) { $this.hide(); $this._trigger('hideWithEscape'); } }); } }, _unbindEvents: function() { this.element.off('mousedown.puidialog'); this.icons.off(); $(document).off('keydown.dialog_' + this.id); }, _setupDraggable: function() { this.element.draggable({ cancel: '.ui-dialog-content, .ui-dialog-titlebar-close', handle: '.ui-dialog-titlebar', containment : 'document' }); }, _setupResizable: function() { var $this = this; this.element.resizable({ minWidth : this.options.minWidth, minHeight : this.options.minHeight, alsoResize : this.content, containment: 'document', start: function(event, ui) { $this.element.data('offset', $this.element.offset()); }, stop: function(event, ui) { var offset = $this.element.data('offset'); $this.element.css('position', 'fixed'); $this.element.offset(offset); } }); this.resizers = this.element.children('.ui-resizable-handle'); }, _initPosition: function() { //reset this.element.css({left:0,top:0}); if(/(center|left|top|right|bottom)/.test(this.options.location)) { this.options.location = this.options.location.replace(',', ' '); this.element.position({ my: 'center', at: this.options.location, collision: 'fit', of: window, //make sure dialog stays in viewport using: function(pos) { var l = pos.left < 0 ? 0 : pos.left, t = pos.top < 0 ? 0 : pos.top; $(this).css({ left: l, top: t }); } }); } else { var coords = this.options.position.split(','), x = $.trim(coords[0]), y = $.trim(coords[1]); this.element.offset({ left: x, top: y }); } this.positionInitialized = true; }, _moveToTop: function() { this.element.css('z-index',++PUI.zindex); }, toggleMaximize: function() { if(this.minimized) { this.toggleMinimize(); } if(this.maximized) { this.element.removeClass('ui-dialog-maximized'); this._restoreState(); this.maximizeIcon.removeClass('ui-state-hover'); this.maximized = false; } else { this._saveState(); var win = $(window); this.element.addClass('ui-dialog-maximized').css({ 'width': win.width() - 6, 'height': win.height() }).offset({ top: win.scrollTop(), left: win.scrollLeft() }); //maximize content this.content.css({ width: 'auto', height: 'auto' }); this.maximizeIcon.removeClass('ui-state-hover'); this.maximized = true; this._trigger('maximize'); } }, toggleMinimize: function() { var animate = true, dockingZone = $(document.body).children('.ui-dialog-docking-zone'); if(this.maximized) { this.toggleMaximize(); animate = false; } var $this = this; if(this.minimized) { this.element.appendTo(this.parent).removeClass('ui-dialog-minimized').css({'position':'fixed', 'float':'none'}); this._restoreState(); this.content.show(); this.minimizeIcon.removeClass('ui-state-hover').children('.fa').removeClass('fa-plus').addClass('fa-minus'); this.minimized = false; if(this.options.resizable) { this.resizers.show(); } if(this.footer) { this.footer.show(); } } else { this._saveState(); if(animate) { this.element.effect('transfer', { to: dockingZone, className: 'ui-dialog-minimizing' }, 500, function() { $this._dock(dockingZone); $this.element.addClass('ui-dialog-minimized'); }); } else { this._dock(dockingZone); } } }, _dock: function(zone) { this.element.appendTo(zone).css('position', 'static'); this.element.css({'height':'auto', 'width':'auto', 'float': 'left'}); this.content.hide(); this.minimizeIcon.removeClass('ui-state-hover').children('.fa').removeClass('fa-minus').addClass('fa-plus'); this.minimized = true; if(this.options.resizable) { this.resizers.hide(); } if(this.footer) { this.footer.hide(); } zone.css('z-index',++PUI.zindex); this._trigger('minimize'); }, _saveState: function() { this.state = { width: this.element.width(), height: this.element.height() }; var win = $(window); this.state.offset = this.element.offset(); this.state.windowScrollLeft = win.scrollLeft(); this.state.windowScrollTop = win.scrollTop(); }, _restoreState: function() { this.element.width(this.state.width).height(this.state.height); var win = $(window); this.element.offset({ top: this.state.offset.top + (win.scrollTop() - this.state.windowScrollTop), left: this.state.offset.left + (win.scrollLeft() - this.state.windowScrollLeft) }); }, _applyARIA: function() { this.element.attr({ 'role': 'dialog', 'aria-labelledby': this.element.attr('id') + '_title', 'aria-hidden': !this.options.visible }); this.titlebar.children('a.ui-dialog-titlebar-icon').attr('role', 'button'); }, _removeARIA: function() { this.element.removeAttr('role').removeAttr('aria-labelledby').removeAttr('aria-hidden') .removeAttr('aria-live').removeAttr('aria-hidden'); }, _bindResizeListener: function() { var $this = this; $(window).on(this.resizeNS, function(e) { if(e.target === window) { $this._initPosition(); } }); }, _unbindResizeListener: function() { $(window).off(this.resizeNS); }, _setOption: function(key, value) { if(key === 'visible') { if(value) this.show(); else this.hide(); } else { $.Widget.prototype._setOption.apply(this, arguments); } } }); })(); /** * PrimeUI dropdown widget */ (function() { $.widget("primeui.puidropdown", { options: { effect: 'fade', effectSpeed: 'normal', filter: false, filterMatchMode: 'startsWith', caseSensitiveFilter: false, filterFunction: null, data: null, content: null, scrollHeight: 200, appendTo: 'body', editable: false, value: null, style: null, styleClass: null }, _create: function() { this.id = this.element.attr('id'); if(!this.id) { this.id = this.element.uniqueId().attr('id'); } if(!this.options.enhanced) { if(this.options.data) { if($.isArray(this.options.data)) { this._generateOptionElements(this.options.data); } else { if($.type(this.options.data) === 'function') { this.options.data.call(this, this._onRemoteOptionsLoad); return; } else { if($.type(this.options.data) === 'string') { var $this = this, dataURL = this.options.data; var loader = function() { $.ajax({ type: 'GET', url: dataURL, dataType: "json", context: $this, success: function (response) { this._onRemoteOptionsLoad(response); } }); }; loader.call(this); } } return; } } this._render(); } else { this.choices = this.element.children('option'); this.container = this.element.closest('.ui-dropdown'); this.focusElementContainer = this.container.children('.ui-helper-hidden-accessible:last'); this.focusElement = this.focusElementContainer.children('input'); this.label = this.container.children('.ui-dropdown-label'); this.menuIcon = this.container.children('.ui-dropdown-trigger'); this.panel = this.container.children('.ui-dropdown-panel'); this.itemsWrapper = this.panel.children('.ui-dropdown-items-wrapper'); this.itemsContainer = this.itemsWrapper.children('ul'); this.itemsContainer.addClass('ui-dropdown-items ui-dropdown-list ui-widget-content ui-widget ui-corner-all ui-helper-reset'); this.items = this.itemsContainer.children('li').addClass('ui-dropdown-item ui-corner-all'); var $this = this; this.items.each(function(i) { $(this).data('label', $this.choices.eq(i).text()); }); if(this.options.filter) { this.filterContainer = this.panel.children('.ui-dropdown-filter-container'); this.filterInput = this.filterContainer.children('input'); } } this._postRender(); }, _render: function() { this.choices = this.element.children('option'); this.element.attr('tabindex', '-1').wrap('<div class="ui-dropdown ui-widget ui-state-default ui-corner-all ui-helper-clearfix" />') .wrap('<div class="ui-helper-hidden-accessible" />'); this.container = this.element.closest('.ui-dropdown'); this.focusElementContainer = $('<div class="ui-helper-hidden-accessible"><input type="text" /></div>').appendTo(this.container); this.focusElement = this.focusElementContainer.children('input'); this.label = this.options.editable ? $('<input type="text" class="ui-dropdown-label ui-inputtext ui-corner-all"">') : $('<label class="ui-dropdown-label ui-inputtext ui-corner-all"/>'); this.label.appendTo(this.container); this.menuIcon = $('<div class="ui-dropdown-trigger ui-state-default ui-corner-right"><span class="fa fa-fw fa-caret-down"></span></div>') .appendTo(this.container); //panel this.panel = $('<div class="ui-dropdown-panel ui-widget-content ui-corner-all ui-helper-hidden ui-shadow" />'); this.itemsWrapper = $('<div class="ui-dropdown-items-wrapper" />').appendTo(this.panel); this.itemsContainer = $('<ul class="ui-dropdown-items ui-dropdown-list ui-widget-content ui-widget ui-corner-all ui-helper-reset"></ul>') .appendTo(this.itemsWrapper); this.optGroupsSize = this.itemsContainer.children('li.puiselectonemenu-item-group').length; if(this.options.filter) { this.filterContainer = $('<div class="ui-dropdown-filter-container" />').prependTo(this.panel); this.filterInput = $('<input type="text" autocomplete="off" class="ui-dropdown-filter ui-inputtext ui-widget ui-state-default ui-corner-all" />') .appendTo(this.filterContainer); this.filterContainer.append('<span class="fa fa-search"></span>'); } this._generateItems(); }, _postRender: function() { if(this.options.style) { this.container.attr('style', this.options.style); } if(this.options.styleClass) { this.container.addClass(this.options.styleClass); } this.disabled = this.element.prop('disabled')||this.options.disabled; if(this.options.appendTo === 'self') this.panel.appendTo(this.container); else this.panel.appendTo(this.options.appendTo); if(this.options.scrollHeight && this.panel.outerHeight() > this.options.scrollHeight) { this.itemsWrapper.height(this.options.scrollHeight); } var $this = this; //preselection via value option if(this.options.value) { this.choices.filter('[value="'+this.options.value+'"]').prop('selected', true); } var selectedOption = this.choices.filter(':selected'); //disable options this.choices.filter(':disabled').each(function() { $this.items.eq($(this).index()).addClass('ui-state-disabled'); }); //triggers this.triggers = this.options.editable ? this.menuIcon : this.container.children('.ui-dropdown-trigger, .ui-dropdown-label'); //activate selected if(this.options.editable) { var customInputVal = this.label.val(); //predefined input if(customInputVal === selectedOption.text()) { this._highlightItem(this.items.eq(selectedOption.index())); } //custom input else { this.items.eq(0).addClass('ui-state-highlight'); this.customInput = true; this.customInputVal = customInputVal; } } else { this._highlightItem(this.items.eq(selectedOption.index())); } if(!this.disabled) { this._bindEvents(); this._bindConstantEvents(); } }, _onRemoteOptionsLoad: function(data) { this._generateOptionElements(data); this._render(); this._postRender(); }, _generateOptionElements: function(data) { for(var i = 0; i < data.length; i++) { var choice = data[i]; if(choice.label) this.element.append('<option value="' + choice.value + '">' + choice.label + '</option>'); else this.element.append('<option value="' + choice + '">' + choice + '</option>'); } }, _generateItems: function() { for(var i = 0; i < this.choices.length; i++) { var option = this.choices.eq(i), optionLabel = option.text(), content = this.options.content ? this.options.content.call(this, this.options.data[i]) : optionLabel; this.itemsContainer.append('<li data-label="' + optionLabel + '" class="ui-dropdown-item ui-corner-all">' + content + '</li>'); } this.items = this.itemsContainer.children('.ui-dropdown-item'); }, _bindEvents: function() { var $this = this; this.items.filter(':not(.ui-state-disabled)').each(function(i, item) { $this._bindItemEvents($(item)); }); this.triggers.on('mouseenter.puidropdown', function() { if(!$this.container.hasClass('ui-state-focus')) { $this.container.addClass('ui-state-hover'); $this.menuIcon.addClass('ui-state-hover'); } }) .on('mouseleave.puidropdown', function() { $this.container.removeClass('ui-state-hover'); $this.menuIcon.removeClass('ui-state-hover'); }) .on('click.puidropdown', function(e) { if($this.panel.is(":hidden")) { $this._show(); } else { $this._hide(); $this._revert(); } $this.container.removeClass('ui-state-hover'); $this.menuIcon.removeClass('ui-state-hover'); $this.focusElement.trigger('focus.puidropdown'); e.preventDefault(); }); this.focusElement.on('focus.puidropdown', function() { $this.container.addClass('ui-state-focus'); $this.menuIcon.addClass('ui-state-focus'); }) .on('blur.puidropdown', function() { $this.container.removeClass('ui-state-focus'); $this.menuIcon.removeClass('ui-state-focus'); }); if(this.options.editable) { this.label.on('change.ui-dropdown', function() { $this._triggerChange(true); $this.customInput = true; $this.customInputVal = $(this).val(); $this.items.filter('.ui-state-highlight').removeClass('ui-state-highlight'); $this.items.eq(0).addClass('ui-state-highlight'); }); } this._bindKeyEvents(); if(this.options.filter) { this._setupFilterMatcher(); this.filterInput.puiinputtext(); this.filterInput.on('keyup.ui-dropdown', function() { $this._filter($(this).val()); }); } }, _bindItemEvents: function(item) { var $this = this; item.on('mouseover.puidropdown', function() { var el = $(this); if(!el.hasClass('ui-state-highlight')) $(this).addClass('ui-state-hover'); }) .on('mouseout.puidropdown', function() { $(this).removeClass('ui-state-hover'); }) .on('click.puidropdown', function() { $this._selectItem($(this)); }); }, _bindConstantEvents: function() { var $this = this; $(document.body).on('mousedown.ui-dropdown-' + this.id, function (e) { if($this.panel.is(":hidden")) { return; } var offset = $this.panel.offset(); if (e.target === $this.label.get(0) || e.target === $this.menuIcon.get(0) || e.target === $this.menuIcon.children().get(0)) { return; } if (e.pageX < offset.left || e.pageX > offset.left + $this.panel.width() || e.pageY < offset.top || e.pageY > offset.top + $this.panel.height()) { $this._hide(); $this._revert(); } }); this.resizeNS = 'resize.' + this.id; this._unbindResize(); this._bindResize(); }, _bindKeyEvents: function() { var $this = this; this.focusElement.on('keydown.puidropdown', function(e) { var keyCode = $.ui.keyCode, key = e.which, activeItem; switch(key) { case keyCode.UP: case keyCode.LEFT: activeItem = $this._getActiveItem(); var prev = activeItem.prevAll(':not(.ui-state-disabled,.ui-selectonemenu-item-group):first'); if(prev.length == 1) { if($this.panel.is(':hidden')) { $this._selectItem(prev); } else { $this._highlightItem(prev); PUI.scrollInView($this.itemsWrapper, prev); } } e.preventDefault(); break; case keyCode.DOWN: case keyCode.RIGHT: activeItem = $this._getActiveItem(); var next = activeItem.nextAll(':not(.ui-state-disabled,.ui-selectonemenu-item-group):first'); if(next.length == 1) { if($this.panel.is(':hidden')) { if(e.altKey) { $this._show(); } else { $this._selectItem(next); } } else { $this._highlightItem(next); PUI.scrollInView($this.itemsWrapper, next); } } e.preventDefault(); break; case keyCode.ENTER: case keyCode.NUMPAD_ENTER: if($this.panel.is(':hidden')) { $this._show(); } else { $this._selectItem($this._getActiveItem()); } e.preventDefault(); break; case keyCode.TAB: if($this.panel.is(':visible')) { $this._revert(); $this._hide(); } break; case keyCode.ESCAPE: if($this.panel.is(':visible')) { $this._revert(); $this._hide(); } break; default: var k = String.fromCharCode((96 <= key && key <= 105)? key-48 : key), currentItem = $this.items.filter('.ui-state-highlight'); //Search items forward from current to end and on no result, search from start until current var highlightItem = $this._search(k, currentItem.index() + 1, $this.options.length); if(!highlightItem) { highlightItem = $this._search(k, 0, currentItem.index()); } if(highlightItem) { if($this.panel.is(':hidden')) { $this._selectItem(highlightItem); } else { $this._highlightItem(highlightItem); PUI.scrollInView($this.itemsWrapper, highlightItem); } } break; } }); }, _unbindEvents: function() { this.items.off('mouseover.puidropdown mouseout.puidropdown click.puidropdown'); this.triggers.off('mouseenter.puidropdown mouseleave.puidropdown click.puidropdown'); this.focusElement.off('keydown.puidropdown focus.puidropdown blur.puidropdown'); if(this.options.editable) { this.label.off('change.puidropdown'); } if(this.options.filter) { this.filterInput.off('keyup.ui-dropdown'); } $(document.body).off('mousedown.ui-dropdown-' + this.id); this._unbindResize(); }, _selectItem: function(item, silent) { var selectedOption = this.choices.eq(this._resolveItemIndex(item)), currentOption = this.choices.filter(':selected'), sameOption = selectedOption.val() == currentOption.val(), shouldChange = null; if(this.options.editable) { shouldChange = (!sameOption)||(selectedOption.text() != this.label.val()); } else { shouldChange = !sameOption; } if(shouldChange) { this._highlightItem(item); this.element.val(selectedOption.val()); this._triggerChange(); if(this.options.editable) { this.customInput = false; } } if(!silent) { this.focusElement.trigger('focus.puidropdown'); } if(this.panel.is(':visible')) { this._hide(); } }, _highlightItem: function(item) { this.items.filter('.ui-state-highlight').removeClass('ui-state-highlight'); if(item.length) { item.addClass('ui-state-highlight'); this._setLabel(item.data('label')); } else { this._setLabel('&nbsp;'); } }, _triggerChange: function(edited) { this.changed = false; var selectedOption = this.choices.filter(':selected'); if(this.options.change) { this._trigger('change', null, { value: selectedOption.val(), index: selectedOption.index() }); } if(!edited) { this.value = this.choices.filter(':selected').val(); } }, _resolveItemIndex: function(item) { if(this.optGroupsSize === 0) { return item.index(); } else { return item.index() - item.prevAll('li.ui-dropdown-item-group').length; } }, _setLabel: function(value) { if(this.options.editable) { this.label.val(value); } else { if(value === '&nbsp;') { this.label.html('&nbsp;'); } else { this.label.text(value); } } }, _bindResize: function() { var $this = this; $(window).bind(this.resizeNS, function(e) { if($this.panel.is(':visible')) { $this._alignPanel(); } }); }, _unbindResize: function() { $(window).unbind(this.resizeNS); }, _alignPanelWidth: function() { if(!this.panelWidthAdjusted) { var jqWidth = this.container.outerWidth(); if(this.panel.outerWidth() < jqWidth) { this.panel.width(jqWidth); } this.panelWidthAdjusted = true; } }, _alignPanel: function() { if(this.panel.parent().is(this.container)) { this.panel.css({ left: '0px', top: this.container.outerHeight() + 'px' }) .width(this.container.outerWidth()); } else { this._alignPanelWidth(); this.panel.css({left:'', top:''}).position({ my: 'left top', at: 'left bottom', of: this.container, collision: 'flipfit' }); } }, _show: function() { this._alignPanel(); this.panel.css('z-index', ++PUI.zindex); if(this.options.effect !== 'none') { this.panel.show(this.options.effect, {}, this.options.effectSpeed); } else { this.panel.show(); } this.preShowValue = this.choices.filter(':selected'); }, _hide: function() { this.panel.hide(); }, _revert: function() { if(this.options.editable && this.customInput) { this._setLabel(this.customInputVal); this.items.filter('.ui-state-active').removeClass('ui-state-active'); this.items.eq(0).addClass('ui-state-active'); } else { this._highlightItem(this.items.eq(this.preShowValue.index())); } }, _getActiveItem: function() { return this.items.filter('.ui-state-highlight'); }, _setupFilterMatcher: function() { this.filterMatchers = { 'startsWith': this._startsWithFilter, 'contains': this._containsFilter, 'endsWith': this._endsWithFilter, 'custom': this.options.filterFunction }; this.filterMatcher = this.filterMatchers[this.options.filterMatchMode]; }, _startsWithFilter: function(value, filter) { return value.indexOf(filter) === 0; }, _containsFilter: function(value, filter) { return value.indexOf(filter) !== -1; }, _endsWithFilter: function(value, filter) { return value.indexOf(filter, value.length - filter.length) !== -1; }, _filter: function(value) { this.initialHeight = this.initialHeight||this.itemsWrapper.height(); var filterValue = this.options.caseSensitiveFilter ? $.trim(value) : $.trim(value).toLowerCase(); if(filterValue === '') { this.items.filter(':hidden').show(); } else { for(var i = 0; i < this.choices.length; i++) { var option = this.choices.eq(i), itemLabel = this.options.caseSensitiveFilter ? option.text() : option.text().toLowerCase(), item = this.items.eq(i); if(this.filterMatcher(itemLabel, filterValue)) item.show(); else item.hide(); } } if(this.itemsContainer.height() < this.initialHeight) { this.itemsWrapper.css('height', 'auto'); } else { this.itemsWrapper.height(this.initialHeight); } this._alignPanel(); }, _search: function(text, start, end) { for(var i = start; i < end; i++) { var option = this.choices.eq(i); if(option.text().indexOf(text) === 0) { return this.items.eq(i); } } return null; }, getSelectedValue: function() { return this.element.val(); }, getSelectedLabel: function() { return this.choices.filter(':selected').text(); }, selectValue : function(value) { var option = this.choices.filter('[value="' + value + '"]'); this._selectItem(this.items.eq(option.index()), true); }, addOption: function(option, val) { var value, label; //backward compatibility for key-value parameters if(val !== undefined && val !== null) { value = val; label = option; } //key-value as properties of option object else { value = (option.value !== undefined && option.value !== null) ? option.value : option; label = (option.label !== undefined && option.label !== null) ? option.label : option; } var content = this.options.content ? this.options.content.call(this, option) : label, item = $('<li data-label="' + label + '" class="ui-dropdown-item ui-corner-all">' + content + '</li>'), optionElement = $('<option value="' + value + '">' + label + '</option>'); optionElement.appendTo(this.element); this._bindItemEvents(item); item.appendTo(this.itemsContainer); this.items.push(item[0]); this.choices = this.element.children('option'); // If this is the first option, it is the default selected one if (this.items.length === 1) { this.selectValue(value); this._highlightItem(item); } }, removeAllOptions: function() { this.element.empty(); this.itemsContainer.empty(); this.items.length = 0; this.choices.length = 0; this.element.val(''); this.label.text(''); }, _setOption: function (key, value) { if (key === 'data' || key === 'options') { this.options.data = value; this.removeAllOptions(); for(var i = 0; i < this.options.data.length; i++) { this.addOption(this.options.data[i]); } if(this.options.scrollHeight && this.panel.outerHeight() > this.options.scrollHeight) { this.itemsWrapper.height(this.options.scrollHeight); } } else if(key === 'value') { this.options.value = value; this.choices.prop('selected', false); var selectedOption = this.choices.filter('[value="'+this.options.value+'"]'); if(selectedOption.length) { selectedOption.prop('selected', true); this._highlightItem(this.items.eq(selectedOption.index())); } } else { $.Widget.prototype._setOption.apply(this, arguments); } }, disable: function() { this._unbindEvents(); this.label.addClass('ui-state-disabled'); this.menuIcon.addClass('ui-state-disabled'); }, enable: function() { this._bindEvents(); this.label.removeClass('ui-state-disabled'); this.menuIcon.removeClass('ui-state-disabled'); }, getEditableText: function() { return this.label.val(); }, _destroy: function() { this._unbindEvents(); if(!this.options.enhanced) { this.panel.remove(); this.label.remove(); this.menuIcon.remove(); this.focusElementContainer.remove(); this.element.unwrap().unwrap(); } else { if(this.options.appendTo == 'body') { this.panel.appendTo(this.container); } if(this.options.style) { this.container.removeAttr('style'); } if(this.options.styleClass) { this.container.removeClass(this.options.styleClass); } } } }); })(); /** * PrimeFaces Fieldset Widget */ (function() { $.widget("primeui.puifieldset", { options: { toggleable: false, toggleDuration: 'normal', collapsed: false, enhanced: false }, _create: function() { if(!this.options.enhanced) { this.element.addClass('ui-fieldset ui-widget ui-widget-content ui-corner-all'). children('legend').addClass('ui-fieldset-legend ui-corner-all ui-state-default'); this.element.contents().wrapAll('<div class="ui-fieldset-content" />'); this.content = this.element.children('div.ui-fieldset-content'); this.legend = this.content.children('legend.ui-fieldset-legend').prependTo(this.element); } else { this.legend = this.element.children('legend'); this.content = this.element.children('div.ui-fieldset-content'); } if(this.options.toggleable) { if(this.options.enhanced) { this.toggler = this.legend.children('.ui-fieldset-toggler'); } else { this.element.addClass('ui-fieldset-toggleable'); this.toggler = $('<span class="ui-fieldset-toggler fa fa-fw" />').prependTo(this.legend); } this._bindEvents(); if(this.options.collapsed) { this.content.hide(); this.toggler.addClass('fa-plus'); } else { this.toggler.addClass('fa-minus'); } } }, _bindEvents: function() { var $this = this; this.legend.on('click.puifieldset', function(e) {$this.toggle(e);}) .on('mouseover.puifieldset', function() {$this.legend.addClass('ui-state-hover');}) .on('mouseout.puifieldset', function() {$this.legend.removeClass('ui-state-hover ui-state-active');}) .on('mousedown.puifieldset', function() {$this.legend.removeClass('ui-state-hover').addClass('ui-state-active');}) .on('mouseup.puifieldset', function() {$this.legend.removeClass('ui-state-active').addClass('ui-state-hover');}); }, _unbindEvents: function() { this.legend.off('click.puifieldset mouseover.puifieldset mouseout.puifieldset mousedown.puifieldset mouseup.puifieldset'); }, toggle: function(e) { var $this = this; this._trigger('beforeToggle', e, this.options.collapsed); if(this.options.collapsed) { this.toggler.removeClass('fa-plus').addClass('fa-minus'); } else { this.toggler.removeClass('fa-minus').addClass('fa-plus'); } this.content.slideToggle(this.options.toggleSpeed, 'easeInOutCirc', function() { $this.options.collapsed = !$this.options.collapsed; $this._trigger('afterToggle', e, $this.options.collapsed); }); }, _destroy: function() { if(!this.options.enhanced) { this.element.removeClass('ui-fieldset ui-widget ui-widget-content ui-corner-all') .children('legend').removeClass('ui-fieldset-legend ui-corner-all ui-state-default ui-state-hover ui-state-active'); this.content.contents().unwrap(); if(this.options.toggleable) { this.element.removeClass('ui-fieldset-toggleable'); this.toggler.remove(); } } this._unbindEvents(); } }); })(); /** * PrimeUI Lightbox Widget */ (function() { $.widget("primeui.puigalleria", { options: { panelWidth: 600, panelHeight: 400, frameWidth: 60, frameHeight: 40, activeIndex: 0, showFilmstrip: true, autoPlay: true, transitionInterval: 4000, effect: 'fade', effectSpeed: 250, effectOptions: {}, showCaption: true, customContent: false }, _create: function() { this.element.addClass('ui-galleria ui-widget ui-widget-content ui-corner-all'); this.panelWrapper = this.element.children('ul'); this.panelWrapper.addClass('ui-galleria-panel-wrapper'); this.panels = this.panelWrapper.children('li'); this.panels.addClass('ui-galleria-panel ui-helper-hidden'); this.element.width(this.options.panelWidth); this.panelWrapper.width(this.options.panelWidth).height(this.options.panelHeight); this.panels.width(this.options.panelWidth).height(this.options.panelHeight); if(this.options.showFilmstrip) { this._renderStrip(); this._bindEvents(); } if(this.options.customContent) { this.panels.children('img').hide(); this.panels.children('div').addClass('ui-galleria-panel-content'); } //show first var activePanel = this.panels.eq(this.options.activeIndex); activePanel.removeClass('ui-helper-hidden'); if(this.options.showCaption) { this._showCaption(activePanel); } this.element.css('visibility', 'visible'); if(this.options.autoPlay) { this.startSlideshow(); } }, _destroy: function() { this.stopSlideshow(); this._unbindEvents(); this.element.removeClass('ui-galleria ui-widget ui-widget-content ui-corner-all').removeAttr('style'); this.panelWrapper.removeClass('ui-galleria-panel-wrapper').removeAttr('style'); this.panels.removeClass('ui-galleria-panel ui-helper-hidden').removeAttr('style'); this.strip.remove(); this.stripWrapper.remove(); this.element.children('.fa').remove(); if(this.options.showCaption) { this.caption.remove(); } this.panels.children('img').show(); }, _renderStrip: function() { var frameStyle = 'style="width:' + this.options.frameWidth + "px;height:" + this.options.frameHeight + 'px;"'; this.stripWrapper = $('<div class="ui-galleria-filmstrip-wrapper"></div>') .width(this.element.width() - 50) .height(this.options.frameHeight) .appendTo(this.element); this.strip = $('<ul class="ui-galleria-filmstrip"></div>').appendTo(this.stripWrapper); for(var i = 0; i < this.panels.length; i++) { var image = this.panels.eq(i).children('img'), frameClass = (i == this.options.activeIndex) ? 'ui-galleria-frame ui-galleria-frame-active' : 'ui-galleria-frame', frameMarkup = '<li class="'+ frameClass + '" ' + frameStyle + '>' + '<div class="ui-galleria-frame-content" ' + frameStyle + '>' + '<img src="' + image.attr('src') + '" class="ui-galleria-frame-image" ' + frameStyle + '/>' + '</div></li>'; this.strip.append(frameMarkup); } this.frames = this.strip.children('li.ui-galleria-frame'); //navigators this.element.append('<div class="ui-galleria-nav-prev fa fa-fw fa-chevron-circle-left" style="bottom:' + (this.options.frameHeight / 2) + 'px"></div>' + '<div class="ui-galleria-nav-next fa fa-fw fa-chevron-circle-right" style="bottom:' + (this.options.frameHeight / 2) + 'px"></div>'); //caption if(this.options.showCaption) { this.caption = $('<div class="ui-galleria-caption"></div>').css({ 'bottom': this.stripWrapper.outerHeight() + 10, 'width': this.panelWrapper.width() }).appendTo(this.element); } }, _bindEvents: function() { var $this = this; this.element.children('div.ui-galleria-nav-prev').on('click.puigalleria', function() { if($this.slideshowActive) { $this.stopSlideshow(); } if(!$this.isAnimating()) { $this.prev(); } }); this.element.children('div.ui-galleria-nav-next').on('click.puigalleria', function() { if($this.slideshowActive) { $this.stopSlideshow(); } if(!$this.isAnimating()) { $this.next(); } }); this.strip.children('li.ui-galleria-frame').on('click.puigalleria', function() { if($this.slideshowActive) { $this.stopSlideshow(); } $this.select($(this).index(), false); }); }, _unbindEvents: function() { this.element.children('div.ui-galleria-nav-prev').off('click.puigalleria'); this.element.children('div.ui-galleria-nav-next').off('click.puigalleria'); this.strip.children('li.ui-galleria-frame').off('click.puigalleria'); }, startSlideshow: function() { var $this = this; this.interval = window.setInterval(function() { $this.next(); }, this.options.transitionInterval); this.slideshowActive = true; }, stopSlideshow: function() { if(this.interval) { window.clearInterval(this.interval); } this.slideshowActive = false; }, isSlideshowActive: function() { return this.slideshowActive; }, select: function(index, reposition) { if(index !== this.options.activeIndex) { if(this.options.showCaption) { this._hideCaption(); } var oldPanel = this.panels.eq(this.options.activeIndex), newPanel = this.panels.eq(index); //content oldPanel.hide(this.options.effect, this.options.effectOptions, this.options.effectSpeed); newPanel.show(this.options.effect, this.options.effectOptions, this.options.effectSpeed); if (this.options.showFilmstrip) { var oldFrame = this.frames.eq(this.options.activeIndex), newFrame = this.frames.eq(index); //frame oldFrame.removeClass('ui-galleria-frame-active').css('opacity', ''); newFrame.animate({opacity:1.0}, this.options.effectSpeed, null, function() { $(this).addClass('ui-galleria-frame-active'); }); //viewport if( (reposition === undefined || reposition === true) ) { var frameLeft = newFrame.position().left, stepFactor = this.options.frameWidth + parseInt(newFrame.css('margin-right'), 10), stripLeft = this.strip.position().left, frameViewportLeft = frameLeft + stripLeft, frameViewportRight = frameViewportLeft + this.options.frameWidth; if(frameViewportRight > this.stripWrapper.width()) { this.strip.animate({left: '-=' + stepFactor}, this.options.effectSpeed, 'easeInOutCirc'); } else if(frameViewportLeft < 0) { this.strip.animate({left: '+=' + stepFactor}, this.options.effectSpeed, 'easeInOutCirc'); } } } //caption if(this.options.showCaption) { this._showCaption(newPanel); } this.options.activeIndex = index; } }, _hideCaption: function() { this.caption.slideUp(this.options.effectSpeed); }, _showCaption: function(panel) { var image = panel.children('img'); this.caption.html('<h4>' + image.attr('title') + '</h4><p>' + image.attr('alt') + '</p>').slideDown(this.options.effectSpeed); }, prev: function() { if(this.options.activeIndex !== 0) { this.select(this.options.activeIndex - 1); } }, next: function() { if(this.options.activeIndex !== (this.panels.length - 1)) { this.select(this.options.activeIndex + 1); } else { this.select(0, false); this.strip.animate({left: 0}, this.options.effectSpeed, 'easeInOutCirc'); } }, isAnimating: function() { return this.strip.is(':animated'); } }); })(); /** * PrimeFaces Growl Widget */ (function() { $.widget("primeui.puigrowl", { options: { sticky: false, life: 3000, messages: null, appendTo: document.body }, _create: function() { var container = this.element; this.originalParent = this.element.parent(); container.addClass("ui-growl ui-widget"); if(this.options.appendTo) { container.appendTo(this.options.appendTo); } if(this.options.messages) { this.show(this.options.messages); } }, show: function(msgs) { var $this = this; this.element.css('z-index', ++PUI.zindex); this.clear(); if(msgs && msgs.length) { $.each(msgs, function(i, msg) { $this._renderMessage(msg); }); } }, clear: function() { var messageElements = this.element.children('div.ui-growl-item-container'); for(var i = 0; i < messageElements.length; i++) { this._unbindMessageEvents(messageElements.eq(i)); } messageElements.remove(); }, _renderMessage: function(msg) { var markup = '<div class="ui-growl-item-container ui-state-highlight ui-corner-all ui-helper-hidden" aria-live="polite">'; markup += '<div class="ui-growl-item ui-shadow">'; markup += '<div class="ui-growl-icon-close fa fa-close" style="display:none"></div>'; markup += '<span class="ui-growl-image fa fa-2x ' + this._getIcon(msg.severity) + ' ui-growl-image-' + msg.severity + '"/>'; markup += '<div class="ui-growl-message">'; markup += '<span class="ui-growl-title">' + msg.summary + '</span>'; markup += '<p>' + (msg.detail||'') + '</p>'; markup += '</div><div style="clear: both;"></div></div></div>'; var message = $(markup); message.addClass('ui-growl-message-' + msg.severity); this._bindMessageEvents(message); message.appendTo(this.element).fadeIn(); }, _removeMessage: function(message) { message.fadeTo('normal', 0, function() { message.slideUp('normal', 'easeInOutCirc', function() { message.remove(); }); }); }, _bindMessageEvents: function(message) { var $this = this, sticky = this.options.sticky; message.on('mouseover.puigrowl', function() { var msg = $(this); if(!msg.is(':animated')) { msg.find('div.ui-growl-icon-close:first').show(); } }) .on('mouseout.puigrowl', function() { $(this).find('div.ui-growl-icon-close:first').hide(); }); //remove message on click of close icon message.find('div.ui-growl-icon-close').on('click.puigrowl',function() { $this._removeMessage(message); if(!sticky) { window.clearTimeout(message.data('timeout')); } }); if(!sticky) { this._setRemovalTimeout(message); } }, _unbindMessageEvents: function(message) { var $this = this, sticky = this.options.sticky; message.off('mouseover.puigrowl mouseout.puigrowl'); message.find('div.ui-growl-icon-close').off('click.puigrowl'); if(!sticky) { var timeout = message.data('timeout'); if(timeout) { window.clearTimeout(timeout); } } }, _setRemovalTimeout: function(message) { var $this = this; var timeout = window.setTimeout(function() { $this._removeMessage(message); }, this.options.life); message.data('timeout', timeout); }, _getIcon: function(severity) { switch(severity) { case 'info': return 'fa-info-circle'; break; case 'warn': return 'fa-warning'; break; case 'error': return 'fa-close'; break; default: return 'fa-info-circle'; break; } }, _setOption: function(key, value) { if(key === 'value' || key === 'messages') { this.show(value); } else { $.Widget.prototype._setOption.apply(this, arguments); } }, _destroy: function() { this.clear(); this.element.removeClass("ui-growl ui-widget"); if(this.options.appendTo) { this.element.appendTo(this.originalParent); } } }); })(); /** * PrimeUI inputtext widget */ (function() { $.widget("primeui.puiinputtext", { options: { disabled: false }, _create: function() { var input = this.element, disabled = input.prop('disabled'); //visuals input.addClass('ui-inputtext ui-widget ui-state-default ui-corner-all'); if(input.prop('disabled')) input.addClass('ui-state-disabled'); else if(this.options.disabled) this.disable(); else this._enableMouseEffects(); }, _destroy: function() { this.element.removeClass('ui-inputtext ui-widget ui-state-default ui-state-disabled ui-state-hover ui-state-focus ui-corner-all'); this._disableMouseEffects(); }, _enableMouseEffects: function () { var input = this.element; input.on('mouseover.puiinputtext', function() { input.addClass('ui-state-hover'); }) .on('mouseout.puiinputtext', function() { input.removeClass('ui-state-hover'); }) .on('focus.puiinputtext', function() { input.addClass('ui-state-focus'); }) .on('blur.puiinputtext', function() { input.removeClass('ui-state-focus'); }); }, _disableMouseEffects: function () { this.element.off('mouseover.puiinputtext mouseout.puiinputtext focus.puiinputtext blur.puiinputtext'); }, disable: function () { this.element.prop('disabled', true); this.element.addClass('ui-state-disabled'); this.element.removeClass('ui-state-focus ui-state-hover'); this._disableMouseEffects(); }, enable: function () { this.element.prop('disabled', false); this.element.removeClass('ui-state-disabled'); this._enableMouseEffects(); }, _setOption: function(key, value) { if(key === 'disabled') { if(value) this.disable(); else this.enable(); } else { $.Widget.prototype._setOption.apply(this, arguments); } } }); })(); /** * PrimeUI inputtextarea widget */ (function() { $.widget("primeui.puiinputtextarea", { options: { autoResize: false, autoComplete: false, maxlength: null, counter: null, counterTemplate: '{0}', minQueryLength: 3, queryDelay: 700, completeSource: null }, _create: function() { var $this = this; this.id = this.element.attr('id'); if(!this.id) { this.id = this.element.uniqueId().attr('id'); } this.element.puiinputtext(); if(this.options.autoResize) { this.options.rowsDefault = this.element.attr('rows'); this.options.colsDefault = this.element.attr('cols'); this.element.addClass('ui-inputtextarea-resizable'); this.element.on('keyup.puiinputtextarea-resize', function() { $this._resize(); }).on('focus.puiinputtextarea-resize', function() { $this._resize(); }).on('blur.puiinputtextarea-resize', function() { $this._resize(); }); } if(this.options.maxlength) { this.element.on('keyup.puiinputtextarea-maxlength', function(e) { var value = $this.element.val(), length = value.length; if(length > $this.options.maxlength) { $this.element.val(value.substr(0, $this.options.maxlength)); } if($this.options.counter) { $this._updateCounter(); } }); } if(this.options.counter) { this._updateCounter(); } if(this.options.autoComplete) { this._initAutoComplete(); } }, _destroy: function() { this.element.puiinputtext('destroy'); if(this.options.autoResize) { this.element.removeClass('ui-inputtextarea-resizable').off('keyup.puiinputtextarea-resize focus.puiinputtextarea-resize blur.puiinputtextarea-resize'); } if(this.options.maxlength) { this.element.off('keyup.puiinputtextarea-maxlength'); } if(this.options.autoComplete) { this.element.off('keyup.puiinputtextarea-autocomplete keydown.puiinputtextarea-autocomplete'); $(document.body).off('mousedown.puiinputtextarea-' + this.id); $(window).off('resize.puiinputtextarea-' + this.id); if(this.items) { this.items.off(); } this.panel.remove(); } }, _updateCounter: function() { var value = this.element.val(), length = value.length; if(this.options.counter) { var remaining = this.options.maxlength - length, remainingText = this.options.counterTemplate.replace('{0}', remaining); this.options.counter.text(remainingText); } }, _resize: function() { var linesCount = 0, lines = this.element.val().split('\n'); for(var i = lines.length-1; i >= 0 ; --i) { linesCount += Math.floor((lines[i].length / this.options.colsDefault) + 1); } var newRows = (linesCount >= this.options.rowsDefault) ? (linesCount + 1) : this.options.rowsDefault; this.element.attr('rows', newRows); }, _initAutoComplete: function() { var panelMarkup = '<div id="' + this.id + '_panel" class="ui-autocomplete-panel ui-widget-content ui-corner-all ui-helper-hidden ui-shadow"></div>', $this = this; this.panel = $(panelMarkup).appendTo(document.body); this.element.on('keyup.puiinputtextarea-autocomplete', function(e) { var keyCode = $.ui.keyCode; switch(e.which) { case keyCode.UP: case keyCode.LEFT: case keyCode.DOWN: case keyCode.RIGHT: case keyCode.ENTER: case keyCode.NUMPAD_ENTER: case keyCode.TAB: case keyCode.SPACE: case keyCode.CONTROL: case keyCode.ALT: case keyCode.ESCAPE: case 224: //mac command //do not search break; default: var query = $this._extractQuery(); if(query && query.length >= $this.options.minQueryLength) { //Cancel the search request if user types within the timeout if($this.timeout) { $this._clearTimeout($this.timeout); } $this.timeout = window.setTimeout(function() { $this.search(query); }, $this.options.queryDelay); } break; } }).on('keydown.puiinputtextarea-autocomplete', function(e) { var overlayVisible = $this.panel.is(':visible'), keyCode = $.ui.keyCode, highlightedItem; switch(e.which) { case keyCode.UP: case keyCode.LEFT: if(overlayVisible) { highlightedItem = $this.items.filter('.ui-state-highlight'); var prev = highlightedItem.length === 0 ? $this.items.eq(0) : highlightedItem.prev(); if(prev.length == 1) { highlightedItem.removeClass('ui-state-highlight'); prev.addClass('ui-state-highlight'); if($this.options.scrollHeight) { PUI.scrollInView($this.panel, prev); } } e.preventDefault(); } else { $this._clearTimeout(); } break; case keyCode.DOWN: case keyCode.RIGHT: if(overlayVisible) { highlightedItem = $this.items.filter('.ui-state-highlight'); var next = highlightedItem.length === 0 ? _self.items.eq(0) : highlightedItem.next(); if(next.length == 1) { highlightedItem.removeClass('ui-state-highlight'); next.addClass('ui-state-highlight'); if($this.options.scrollHeight) { PUI.scrollInView($this.panel, next); } } e.preventDefault(); } else { $this._clearTimeout(); } break; case keyCode.ENTER: case keyCode.NUMPAD_ENTER: if(overlayVisible) { $this.items.filter('.ui-state-highlight').trigger('click'); e.preventDefault(); } else { $this._clearTimeout(); } break; case keyCode.SPACE: case keyCode.CONTROL: case keyCode.ALT: case keyCode.BACKSPACE: case keyCode.ESCAPE: case 224: //mac command $this._clearTimeout(); if(overlayVisible) { $this._hide(); } break; case keyCode.TAB: $this._clearTimeout(); if(overlayVisible) { $this.items.filter('.ui-state-highlight').trigger('click'); $this._hide(); } break; } }); //hide panel when outside is clicked $(document.body).on('mousedown.puiinputtextarea-' + this.id, function (e) { if($this.panel.is(":hidden")) { return; } var offset = $this.panel.offset(); if(e.target === $this.element.get(0)) { return; } if (e.pageX < offset.left || e.pageX > offset.left + $this.panel.width() || e.pageY < offset.top || e.pageY > offset.top + $this.panel.height()) { $this._hide(); } }); //Hide overlay on resize var resizeNS = 'resize.puiinputtextarea-' + this.id; $(window).off(resizeNS).on(resizeNS, function() { if($this.panel.is(':visible')) { $this._hide(); } }); }, _bindDynamicEvents: function() { var $this = this; //visuals and click handler for items this.items.on('mouseover', function() { var item = $(this); if(!item.hasClass('ui-state-highlight')) { $this.items.filter('.ui-state-highlight').removeClass('ui-state-highlight'); item.addClass('ui-state-highlight'); } }) .on('click', function(event) { var item = $(this), itemValue = item.attr('data-item-value'), insertValue = itemValue.substring($this.query.length); $this.element.focus(); $this.element.insertText(insertValue, $this.element.getSelection().start, true); $this._hide(); $this._trigger("itemselect", event, item); }); }, _clearTimeout: function() { if(this.timeout) { window.clearTimeout(this.timeout); } this.timeout = null; }, _extractQuery: function() { var end = this.element.getSelection().end, result = /\S+$/.exec(this.element.get(0).value.slice(0, end)), lastWord = result ? result[0] : null; return lastWord; }, search: function(q) { this.query = q; var request = { query: q }; if(this.options.completeSource) { this.options.completeSource.call(this, request, this._handleResponse); } }, _handleResponse: function(data) { this.panel.html(''); var listContainer = $('<ul class="ui-autocomplete-items ui-autocomplete-list ui-widget-content ui-widget ui-corner-all ui-helper-reset"></ul>'); for(var i = 0; i < data.length; i++) { var item = $('<li class="ui-autocomplete-item ui-autocomplete-list-item ui-corner-all"></li>'); item.attr('data-item-value', data[i].value); item.text(data[i].label); listContainer.append(item); } this.panel.append(listContainer); this.items = this.panel.find('.ui-autocomplete-item'); this._bindDynamicEvents(); if(this.items.length > 0) { //highlight first item this.items.eq(0).addClass('ui-state-highlight'); //adjust height if(this.options.scrollHeight && this.panel.height() > this.options.scrollHeight) { this.panel.height(this.options.scrollHeight); } if(this.panel.is(':hidden')) { this._show(); } else { this._alignPanel(); //with new items } } else { this.panel.hide(); } }, _alignPanel: function() { var pos = this.element.getCaretPosition(), offset = this.element.offset(); this.panel.css({ 'left': offset.left + pos.left, 'top': offset.top + pos.top, 'width': this.element.innerWidth() }); }, _show: function() { this._alignPanel(); this.panel.show(); }, _hide: function() { this.panel.hide(); }, disable: function () { this.element.puiinputtext('disable'); }, enable: function () { this.element.puiinputtext('enable'); } }); })(); /** * PrimeUI Lightbox Widget */ (function() { $.widget("primeui.puilightbox", { options: { iframeWidth: 640, iframeHeight: 480, iframe: false }, _create: function() { this.id = this.element.attr('id'); if(!this.id) { this.id = this.element.uniqueId().attr('id'); } this.options.mode = this.options.iframe ? 'iframe' : (this.element.children('div').length == 1) ? 'inline' : 'image'; var dom = '<div class="ui-lightbox ui-widget ui-helper-hidden ui-corner-all ui-shadow">'; dom += '<div class="ui-lightbox-content-wrapper">'; dom += '<a class="ui-state-default ui-lightbox-nav-left ui-corner-right ui-helper-hidden"><span class="fa fa-fw fa-caret-left"></span></a>'; dom += '<div class="ui-lightbox-content ui-corner-all"></div>'; dom += '<a class="ui-state-default ui-lightbox-nav-right ui-corner-left ui-helper-hidden"><span class="fa fa-fw fa-caret-right"></span></a>'; dom += '</div>'; dom += '<div class="ui-lightbox-caption ui-widget-header"><span class="ui-lightbox-caption-text"></span>'; dom += '<a class="ui-lightbox-close ui-corner-all" href="#"><span class="fa fa-fw fa-close"></span></a><div style="clear:both" /></div>'; dom += '</div>'; this.panel = $(dom).appendTo(document.body); this.contentWrapper = this.panel.children('.ui-lightbox-content-wrapper'); this.content = this.contentWrapper.children('.ui-lightbox-content'); this.caption = this.panel.children('.ui-lightbox-caption'); this.captionText = this.caption.children('.ui-lightbox-caption-text'); this.closeIcon = this.caption.children('.ui-lightbox-close'); if(this.options.mode === 'image') { this._setupImaging(); } else if(this.options.mode === 'inline') { this._setupInline(); } else if(this.options.mode === 'iframe') { this._setupIframe(); } this._bindCommonEvents(); this.links.data('puilightbox-trigger', true).find('*').data('puilightbox-trigger', true); this.closeIcon.data('puilightbox-trigger', true).find('*').data('puilightbox-trigger', true); }, _bindCommonEvents: function() { var $this = this; this.closeIcon.on('hover.ui-lightbox', function() { $(this).toggleClass('ui-state-hover'); }) .on('click.ui-lightbox', function(e) { $this.hide(); e.preventDefault(); }); //hide when outside is clicked $(document.body).on('click.ui-lightbox-' + this.id, function (e) { if($this.isHidden()) { return; } //do nothing if target is the link var target = $(e.target); if(target.data('puilightbox-trigger')) { return; } //hide if mouse is outside of lightbox var offset = $this.panel.offset(); if(e.pageX < offset.left || e.pageX > offset.left + $this.panel.width() || e.pageY < offset.top || e.pageY > offset.top + $this.panel.height()) { $this.hide(); } }); //sync window resize $(window).on('resize.ui-lightbox-' + this.id, function() { if(!$this.isHidden()) { $(document.body).children('.ui-widget-overlay').css({ 'width': $(document).width(), 'height': $(document).height() }); } }); }, _destroy: function() { this.links.removeData('puilightbox-trigger').find('*').removeData('puilightbox-trigger'); this._unbindEvents(); this.panel.remove(); if(this.modality) { this._disableModality(); } }, _unbindEvents: function() { this.closeIcon.off('hover.ui-lightbox click.ui-lightbox'); $(document.body).off('click.ui-lightbox-' + this.id); $(window).off('resize.ui-lightbox-' + this.id) this.links.off('click.ui-lightbox'); if(this.options.mode === 'image') { this.imageDisplay.off('load.ui-lightbox'); this.navigators.off('hover.ui-lightbox click.ui-lightbox'); } }, _setupImaging: function() { var $this = this; this.links = this.element.children('a'); this.content.append('<img class="ui-helper-hidden"></img>'); this.imageDisplay = this.content.children('img'); this.navigators = this.contentWrapper.children('a'); this.imageDisplay.on('load.ui-lightbox', function() { var image = $(this); $this._scaleImage(image); //coordinates to center overlay var leftOffset = ($this.panel.width() - image.width()) / 2, topOffset = ($this.panel.height() - image.height()) / 2; //resize content for new image $this.content.removeClass('ui-lightbox-loading').animate({ width: image.width(), height: image.height() }, 500, function() { //show image image.fadeIn(); $this._showNavigators(); $this.caption.slideDown(); }); $this.panel.animate({ left: '+=' + leftOffset, top: '+=' + topOffset }, 500); }); this.navigators.on('hover.ui-lightbox', function() { $(this).toggleClass('ui-state-hover'); }) .on('click.ui-lightbox', function(e) { var nav = $(this), index; $this._hideNavigators(); if(nav.hasClass('ui-lightbox-nav-left')) { index = $this.current === 0 ? $this.links.length - 1 : $this.current - 1; $this.links.eq(index).trigger('click'); } else { index = $this.current == $this.links.length - 1 ? 0 : $this.current + 1; $this.links.eq(index).trigger('click'); } e.preventDefault(); }); this.links.on('click.ui-lightbox', function(e) { var link = $(this); if($this.isHidden()) { $this.content.addClass('ui-lightbox-loading').width(32).height(32); $this.show(); } else { $this.imageDisplay.fadeOut(function() { //clear for onload scaling $(this).css({ 'width': 'auto', 'height': 'auto' }); $this.content.addClass('ui-lightbox-loading'); }); $this.caption.slideUp(); } window.setTimeout(function() { $this.imageDisplay.attr('src', link.attr('href')); $this.current = link.index(); var title = link.attr('title'); if(title) { $this.captionText.html(title); } }, 1000); e.preventDefault(); }); }, _scaleImage: function(image) { var win = $(window), winWidth = win.width(), winHeight = win.height(), imageWidth = image.width(), imageHeight = image.height(), ratio = imageHeight / imageWidth; if(imageWidth >= winWidth && ratio <= 1){ imageWidth = winWidth * 0.75; imageHeight = imageWidth * ratio; } else if(imageHeight >= winHeight){ imageHeight = winHeight * 0.75; imageWidth = imageHeight / ratio; } image.css({ 'width':imageWidth + 'px', 'height':imageHeight + 'px' }); }, _setupInline: function() { this.links = this.element.children('a'); this.inline = this.element.children('div').addClass('ui-lightbox-inline'); this.inline.appendTo(this.content).show(); var $this = this; this.links.on('click.ui-lightbox', function(e) { $this.show(); var title = $(this).attr('title'); if(title) { $this.captionText.html(title); $this.caption.slideDown(); } e.preventDefault(); }); }, _setupIframe: function() { var $this = this; this.links = this.element; this.iframe = $('<iframe frameborder="0" style="width:' + this.options.iframeWidth + 'px;height:' + this.options.iframeHeight + 'px;border:0 none; display: block;"></iframe>').appendTo(this.content); if(this.options.iframeTitle) { this.iframe.attr('title', this.options.iframeTitle); } this.element.click(function(e) { if(!$this.iframeLoaded) { $this.content.addClass('ui-lightbox-loading').css({ width: $this.options.iframeWidth, height: $this.options.iframeHeight }); $this.show(); $this.iframe.on('load', function() { $this.iframeLoaded = true; $this.content.removeClass('ui-lightbox-loading'); }) .attr('src', $this.element.attr('href')); } else { $this.show(); } var title = $this.element.attr('title'); if(title) { $this.caption.html(title); $this.caption.slideDown(); } e.preventDefault(); }); }, show: function() { this.center(); this.panel.css('z-index', ++PUI.zindex).show(); if(!this.modality) { this._enableModality(); } this._trigger('show'); }, hide: function() { this.panel.fadeOut(); this._disableModality(); this.caption.hide(); if(this.options.mode === 'image') { this.imageDisplay.hide().attr('src', '').removeAttr('style'); this._hideNavigators(); } this._trigger('hide'); }, center: function() { var win = $(window), left = (win.width() / 2 ) - (this.panel.width() / 2), top = (win.height() / 2 ) - (this.panel.height() / 2); this.panel.css({ 'left': left, 'top': top }); }, _enableModality: function() { this.modality = $('<div class="ui-widget-overlay"></div>') .css({ 'width': $(document).width(), 'height': $(document).height(), 'z-index': this.panel.css('z-index') - 1 }) .appendTo(document.body); }, _disableModality: function() { this.modality.remove(); this.modality = null; }, _showNavigators: function() { this.navigators.zIndex(this.imageDisplay.zIndex() + 1).show(); }, _hideNavigators: function() { this.navigators.hide(); }, isHidden: function() { return this.panel.is(':hidden'); }, showURL: function(opt) { if(opt.width) { this.iframe.attr('width', opt.width); } if(opt.height) { this.iframe.attr('height', opt.height); } this.iframe.attr('src', opt.src); this.show(); } }); })(); /** * PrimeUI listvox widget */ (function() { $.widget("primeui.puilistbox", { options: { value: null, scrollHeight: 200, content: null, data: null, template: null, style: null, styleClass: null, multiple: false, enhanced: false, change: null }, _create: function() { if(!this.options.enhanced) { this.element.wrap('<div class="ui-listbox ui-inputtext ui-widget ui-widget-content ui-corner-all"><div class="ui-helper-hidden-accessible"></div></div>'); this.container = this.element.parent().parent(); this.listContainer = $('<ul class="ui-listbox-list"></ul>').appendTo(this.container); if(this.options.data) { this._populateInputFromData(); } this._populateContainerFromOptions(); } else { this.container = this.element.parent().parent(); this.listContainer = this.container.children('ul').addClass('ui-listbox-list'); this.items = this.listContainer.children('li').addClass('ui-listbox-item ui-corner-all'); this.choices = this.element.children('option'); } if(this.options.style) { this.container.attr('style', this.options.style); } if(this.options.styleClass) { this.container.addClass(this.options.styleClass); } if(this.options.multiple) this.element.prop('multiple', true); else this.options.multiple = this.element.prop('multiple'); //preselection if(this.options.value !== null && this.options.value !== undefined) { this._updateSelection(this.options.value); } this._restrictHeight(); this._bindEvents(); }, _populateInputFromData: function() { for(var i = 0; i < this.options.data.length; i++) { var choice = this.options.data[i]; if(choice.label) { this.element.append('<option value="' + choice.value + '">' + choice.label + '</option>'); } else { this.element.append('<option value="' + choice + '">' + choice + '</option>'); } } }, _populateContainerFromOptions: function() { this.choices = this.element.children('option'); for(var i = 0; i < this.choices.length; i++) { var choice = this.choices.eq(i); this.listContainer.append('<li class="ui-listbox-item ui-corner-all">' + this._createItemContent(choice.get(0)) + '</li>'); } this.items = this.listContainer.find('.ui-listbox-item:not(.ui-state-disabled)'); }, _restrictHeight: function() { if(this.container.height() > this.options.scrollHeight) { this.container.height(this.options.scrollHeight); } }, _bindEvents: function() { var $this = this; //items this._bindItemEvents(this.items); //input this.element.on('focus.puilistbox', function() { $this.container.addClass('ui-state-focus'); }).on('blur.puilistbox', function() { $this.container.removeClass('ui-state-focus'); }); }, _bindItemEvents: function(item) { var $this = this; item.on('mouseover.puilistbox', function() { var item = $(this); if(!item.hasClass('ui-state-highlight')) { item.addClass('ui-state-hover'); } }) .on('mouseout.puilistbox', function() { $(this).removeClass('ui-state-hover'); }) .on('dblclick.puilistbox', function(e) { $this.element.trigger('dblclick'); PUI.clearSelection(); e.preventDefault(); }) .on('click.puilistbox', function(e) { if($this.options.multiple) $this._clickMultiple(e, $(this)); else $this._clickSingle(e, $(this)); }); }, _unbindEvents: function() { this._unbindItemEvents(); this.element.off('focus.puilistbox blur.puilistbox'); }, _unbindItemEvents: function() { this.items.off('mouseover.puilistbox mouseout.puilistbox dblclick.puilistbox click.puilistbox'); }, _clickSingle: function(event, item) { var selectedItem = this.items.filter('.ui-state-highlight'); if(item.index() !== selectedItem.index()) { if(selectedItem.length) { this.unselectItem(selectedItem); } this.selectItem(item); this._trigger('change', event, { value: this.choices.eq(item.index()).attr('value'), index: item.index() }); } this.element.trigger('click'); PUI.clearSelection(); event.preventDefault(); }, _clickMultiple: function(event, item) { var selectedItems = this.items.filter('.ui-state-highlight'), metaKey = (event.metaKey||event.ctrlKey), unchanged = (!metaKey && selectedItems.length === 1 && selectedItems.index() === item.index()); if(!event.shiftKey) { if(!metaKey) { this.unselectAll(); } if(metaKey && item.hasClass('ui-state-highlight')) { this.unselectItem(item); } else { this.selectItem(item); this.cursorItem = item; } } else { //range selection if(this.cursorItem) { this.unselectAll(); var currentItemIndex = item.index(), cursorItemIndex = this.cursorItem.index(), startIndex = (currentItemIndex > cursorItemIndex) ? cursorItemIndex : currentItemIndex, endIndex = (currentItemIndex > cursorItemIndex) ? (currentItemIndex + 1) : (cursorItemIndex + 1); for(var i = startIndex ; i < endIndex; i++) { this.selectItem(this.items.eq(i)); } } else { this.selectItem(item); this.cursorItem = item; } } if(!unchanged) { var values = [], indexes = []; for(var i = 0; i < this.choices.length; i++) { if(this.choices.eq(i).prop('selected')) { values.push(this.choices.eq(i).attr('value')); indexes.push(i); } } this._trigger('change', event, { value: values, index: indexes }) } this.element.trigger('click'); PUI.clearSelection(); event.preventDefault(); }, unselectAll: function() { this.items.removeClass('ui-state-highlight ui-state-hover'); this.choices.filter(':selected').prop('selected', false); }, selectItem: function(value) { var item = null; if($.type(value) === 'number') { item = this.items.eq(value); } else { item = value; } item.addClass('ui-state-highlight').removeClass('ui-state-hover'); this.choices.eq(item.index()).prop('selected', true); this._trigger('itemSelect', null, this.choices.eq(item.index())); }, unselectItem: function(value) { var item = null; if($.type(value) === 'number') { item = this.items.eq(value); } else { item = value; } item.removeClass('ui-state-highlight'); this.choices.eq(item.index()).prop('selected', false); this._trigger('itemUnselect', null, this.choices.eq(item.index())); }, _setOption: function (key, value) { if (key === 'data') { this.element.empty(); this.listContainer.empty(); this._populateInputFromData(); this._populateContainerFromOptions(); this._restrictHeight(); this._bindEvents(); } else if (key === 'value') { this._updateSelection(value); } else if (key === 'options') { this._updateOptions(value); } else { $.Widget.prototype._setOption.apply(this, arguments); } }, disable: function () { this._unbindEvents(); this.items.addClass('ui-state-disabled'); }, enable: function () { this._bindEvents(); this.items.removeClass('ui-state-disabled'); }, _createItemContent: function(choice) { if(this.options.template) { var template = this.options.template.html(); Mustache.parse(template); return Mustache.render(template, choice); } else if(this.options.content) { return this.options.content.call(this, choice); } else { return choice.label; } }, _updateSelection: function(value) { this.choices.prop('selected', false); this.items.removeClass('ui-state-highlight'); for(var i = 0; i < this.choices.length; i++) { var choice = this.choices.eq(i); if(this.options.multiple) { if($.inArray(choice.attr('value'), value) >= 0) { choice.prop('selected', true); this.items.eq(i).addClass('ui-state-highlight'); } } else { if(choice.attr('value') == value) { choice.prop('selected', true); this.items.eq(i).addClass('ui-state-highlight'); break; } } } }, //primeng _updateOptions: function(options) { var $this = this; setTimeout(function() { $this.items = $this.listContainer.children('li').addClass('ui-listbox-item ui-corner-all'); $this.choices = $this.element.children('option'); $this._unbindItemEvents(); $this._bindItemEvents(this.items); }, 50); }, _destroy: function() { this._unbindEvents(); if(!this.options.enhanced) { this.listContainer.remove(); this.element.unwrap().unwrap(); } if(this.options.style) { this.container.removeAttr('style'); } if(this.options.styleClass) { this.container.removeClass(this.options.styleClass); } if(this.options.multiple) { this.element.prop('multiple', false); } if(this.choices) { this.choices.prop('selected', false); } }, removeAllOptions: function() { this.element.empty(); this.listContainer.empty(); this.container.empty(); this.element.val(''); }, addOption: function(value,label) { var newListItem; if(this.options.content) { var option = (label) ? {'label':label,'value':value}: {'label':value,'value':value}; newListItem = $('<li class="ui-listbox-item ui-corner-all"></li>').append(this.options.content(option)).appendTo(this.listContainer); } else { var listLabel = (label) ? label: value; newListItem = $('<li class="ui-listbox-item ui-corner-all">' + listLabel + '</li>').appendTo(this.listContainer); } if(label) this.element.append('<option value="' + value + '">' + label + '</option>'); else this.element.append('<option value="' + value + '">' + value + '</option>'); this._bindItemEvents(newListItem); this.choices = this.element.children('option'); this.items = this.items.add(newListItem); } }); })(); /** * PrimeUI Messages widget */ (function() { $.widget("primeui.puimessages", { options: { closable: true }, _create: function() { this.element.addClass('ui-messages ui-widget ui-corner-all'); if(this.options.closable) { this.closer = $('<a href="#" class="ui-messages-close"><i class="fa fa-close"></i></a>').appendTo(this.element); } this.element.append('<span class="ui-messages-icon fa fa-2x"></span>'); this.msgContainer = $('<ul></ul>').appendTo(this.element); this._bindEvents(); }, _bindEvents: function() { var $this = this; if(this.options.closable) { this.closer.on('click', function(e) { $this.element.slideUp(); e.preventDefault(); }); } }, show: function(severity, msgs) { this.clear(); this.element.removeClass('ui-messages-info ui-messages-warn ui-messages-error').addClass('ui-messages-' + severity); this.element.children('.ui-messages-icon').removeClass('fa-info-circle fa-close fa-warning').addClass(this._getIcon(severity)); if($.isArray(msgs)) { for(var i = 0; i < msgs.length; i++) { this._showMessage(msgs[i]); } } else { this._showMessage(msgs); } this.element.show(); }, _showMessage: function(msg) { this.msgContainer.append('<li><span class="ui-messages-summary">' + msg.summary + '</span><span class="ui-messages-detail">' + msg.detail + '</span></li>'); }, clear: function() { this.msgContainer.children().remove(); this.element.hide(); }, _getIcon: function(severity) { switch(severity) { case 'info': return 'fa-info-circle'; break; case 'warn': return 'fa-warning'; break; case 'error': return 'fa-close'; break; default: return 'fa-info-circle'; break; } } }); })(); /** * PrimeUI BaseMenu widget */ (function() { $.widget("primeui.puibasemenu", { options: { popup: false, trigger: null, my: 'left top', at: 'left bottom', triggerEvent: 'click' }, _create: function() { if(this.options.popup) { this._initPopup(); } }, _initPopup: function() { var $this = this; this.element.closest('.ui-menu').addClass('ui-menu-dynamic ui-shadow').appendTo(document.body); if($.type(this.options.trigger) === 'string') { this.options.trigger = $(this.options.trigger); } this.positionConfig = { my: this.options.my, at: this.options.at, of: this.options.trigger }; this.options.trigger.on(this.options.triggerEvent + '.ui-menu', function(e) { if($this.element.is(':visible')) { $this.hide(); } else { $this.show(); } e.preventDefault(); }); //hide overlay on document click $(document.body).on('click.ui-menu-' + this.id, function (e) { var popup = $this.element.closest('.ui-menu'); if(popup.is(":hidden")) { return; } //do nothing if mousedown is on trigger var target = $(e.target); if(target.is($this.options.trigger.get(0))||$this.options.trigger.has(target).length > 0) { return; } //hide if mouse is outside of overlay except trigger var offset = popup.offset(); if(e.pageX < offset.left || e.pageX > offset.left + popup.width() || e.pageY < offset.top || e.pageY > offset.top + popup.height()) { $this.hide(e); } }); //Hide overlay on resize $(window).on('resize.ui-menu-' + this.id, function() { if($this.element.closest('.ui-menu').is(':visible')) { $this.align(); } }); }, show: function() { this.align(); this.element.closest('.ui-menu').css('z-index', ++PUI.zindex).show(); }, hide: function() { this.element.closest('.ui-menu').fadeOut('fast'); }, align: function() { this.element.closest('.ui-menu').css({left:'', top:''}).position(this.positionConfig); }, _destroy: function() { if(this.options.popup) { $(document.body).off('click.ui-menu-' + this.id); $(window).off('resize.ui-menu-' + this.id); this.options.trigger.off(this.options.triggerEvent + '.ui-menu'); } } }); })(); /** * PrimeUI Menu widget */ (function() { $.widget("primeui.puimenu", $.primeui.puibasemenu, { options: { enhanced: false }, _create: function() { var $this = this; this.id = this.element.attr('id'); if(!this.id) { this.id = this.element.uniqueId().attr('id'); } if(!this.options.enhanced) { this.element.wrap('<div class="ui-menu ui-widget ui-widget-content ui-corner-all ui-helper-clearfix"></div>'); } this.container = this.element.parent(); this.originalParent = this.container.parent(); this.element.addClass('ui-menu-list ui-helper-reset'); this.element.children('li').each(function() { var listItem = $(this); if(listItem.children('h3').length > 0) { listItem.addClass('ui-widget-header ui-corner-all'); } else { listItem.addClass('ui-menuitem ui-widget ui-corner-all'); var menuitemLink = listItem.children('a'), icon = menuitemLink.data('icon'); menuitemLink.addClass('ui-menuitem-link ui-corner-all'); if($this.options.enhanced) menuitemLink.children('span').addClass('ui-menuitem-text'); else menuitemLink.contents().wrap('<span class="ui-menuitem-text" />'); if(icon) { menuitemLink.prepend('<span class="ui-menuitem-icon fa fa-fw ' + icon + '"></span>'); } } }); this.menuitemLinks = this.element.find('.ui-menuitem-link:not(.ui-state-disabled)'); this._bindEvents(); this._super(); }, _bindEvents: function() { var $this = this; this.menuitemLinks.on('mouseenter.ui-menu', function(e) { $(this).addClass('ui-state-hover'); }) .on('mouseleave.ui-menu', function(e) { $(this).removeClass('ui-state-hover'); }); if(this.options.popup) { this.menuitemLinks.on('click.ui-menu', function() { $this.hide(); }); } }, _unbindEvents: function() { this.menuitemLinks.off('mouseenter.ui-menu mouseleave.ui-menu'); if(this.options.popup) { this.menuitemLinks.off('click.ui-menu'); } }, _destroy: function() { this._super(); var $this = this; this._unbindEvents(); this.element.removeClass('ui-menu-list ui-helper-reset'); this.element.children('li.ui-widget-header').removeClass('ui-widget-header ui-corner-all'); this.element.children('li:not(.ui-widget-header)').removeClass('ui-menuitem ui-widget ui-corner-all') .children('a').removeClass('ui-menuitem-link ui-corner-all').each(function() { var link = $(this); link.children('.ui-menuitem-icon').remove(); if($this.options.enhanced) link.children('.ui-menuitem-text').removeClass('ui-menuitem-text'); else link.children('.ui-menuitem-text').contents().unwrap(); }); if(this.options.popup) { this.container.appendTo(this.originalParent); } if(!this.options.enhanced) { this.element.unwrap(); } } }); })(); /** * PrimeUI BreadCrumb Widget */ (function() { $.widget("primeui.puibreadcrumb", { _create: function() { var $this = this; if(!this.options.enhanced) { this.element.wrap('<div class="ui-breadcrumb ui-module ui-widget ui-widget-header ui-helper-clearfix ui-corner-all" role="menu">'); } this.element.children('li').each(function(index) { var listItem = $(this); listItem.attr('role', 'menuitem'); var menuitemLink = listItem.children('a'); menuitemLink.addClass('ui-menuitem-link'); if($this.options.enhanced) menuitemLink.children('span').addClass('ui-menuitem-text'); else menuitemLink.contents().wrap('<span class="ui-menuitem-text" />'); if(index > 0) { listItem.before('<li class="ui-breadcrumb-chevron fa fa-chevron-right"></li>'); } else { listItem.before('<li class="fa fa-home"></li>'); } }); }, _destroy: function() { var $this = this; if(!this.options.enhanced) { this.unwrap(); } this.element.children('li.ui-breadcrumb-chevron,.fa-home').remove(); this.element.children('li').each(function() { var listItem = $(this), link = listItem.children('a'); link.removeClass('ui-menuitem-link'); if($this.options.enhanced) link.children('.ui-menuitem-text').removeClass('ui-menuitem-text'); else link.children('.ui-menuitem-text').contents().unwrap(); }); } }); })(); /* * PrimeUI TieredMenu Widget */ (function() { $.widget("primeui.puitieredmenu", $.primeui.puibasemenu, { options: { autoDisplay: true }, _create: function() { var $this = this; this.id = this.element.attr('id'); if(!this.id) { this.id = this.element.uniqueId().attr('id'); } if(!this.options.enhanced) { this.element.wrap('<div class="ui-tieredmenu ui-menu ui-widget ui-widget-content ui-corner-all ui-helper-clearfix"></div>'); } this.container = this.element.parent(); this.originalParent = this.container.parent(); this.element.addClass('ui-menu-list ui-helper-reset'); this.element.find('li').each(function() { var listItem = $(this), menuitemLink = listItem.children('a'), icon = menuitemLink.data('icon'); menuitemLink.addClass('ui-menuitem-link ui-corner-all'); if($this.options.enhanced) menuitemLink.children('span').addClass('ui-menuitem-text'); else menuitemLink.contents().wrap('<span class="ui-menuitem-text" />'); if(icon) { menuitemLink.prepend('<span class="ui-menuitem-icon fa fa-fw ' + icon + '"></span>'); } listItem.addClass('ui-menuitem ui-widget ui-corner-all'); if(listItem.children('ul').length > 0) { var submenuIcon = listItem.parent().hasClass('ui-menu-child') ? 'fa-caret-right' : $this._getRootSubmenuIcon(); listItem.addClass('ui-menu-parent'); listItem.children('ul').addClass('ui-widget-content ui-menu-list ui-corner-all ui-helper-clearfix ui-menu-child ui-shadow'); menuitemLink.prepend('<span class="ui-submenu-icon fa fa-fw ' + submenuIcon + '"></span>'); } }); this.links = this.element.find('.ui-menuitem-link:not(.ui-state-disabled)'); this._bindEvents(); this._super(); }, _bindEvents: function() { this._bindItemEvents(); this._bindDocumentHandler(); }, _bindItemEvents: function() { var $this = this; this.links.on('mouseenter.ui-menu', function() { var link = $(this), menuitem = link.parent(), autoDisplay = $this.options.autoDisplay; var activeSibling = menuitem.siblings('.ui-menuitem-active'); if(activeSibling.length === 1) { $this._deactivate(activeSibling); } if(autoDisplay||$this.active) { if(menuitem.hasClass('ui-menuitem-active')) { $this._reactivate(menuitem); } else { $this._activate(menuitem); } } else { $this._highlight(menuitem); } }); if(this.options.autoDisplay === false) { this.rootLinks = this.element.find('> .ui-menuitem > .ui-menuitem-link'); this.rootLinks.data('primeui-tieredmenu-rootlink', this.id).find('*').data('primeui-tieredmenu-rootlink', this.id); this.rootLinks.on('click.ui-menu', function(e) { var link = $(this), menuitem = link.parent(), submenu = menuitem.children('ul.ui-menu-child'); if(submenu.length === 1) { if(submenu.is(':visible')) { $this.active = false; $this._deactivate(menuitem); } else { $this.active = true; $this._highlight(menuitem); $this._showSubmenu(menuitem, submenu); } } }); } this.element.parent().find('ul.ui-menu-list').on('mouseleave.ui-menu', function(e) { if($this.activeitem) { $this._deactivate($this.activeitem); } e.stopPropagation(); }); }, _bindDocumentHandler: function() { var $this = this; $(document.body).on('click.ui-menu-' + this.id, function(e) { var target = $(e.target); if(target.data('primeui-tieredmenu-rootlink') === $this.id) { return; } $this.active = false; $this.element.find('li.ui-menuitem-active').each(function() { $this._deactivate($(this), true); }); }); }, _unbindEvents: function() { this.links.off('mouseenter.ui-menu'); if(this.options.autoDisplay === false) { this.rootLinks.off('click.ui-menu'); } this.element.parent().find('ul.ui-menu-list').off('mouseleave.ui-menu'); $(document.body).off('click.ui-menu-' + this.id); }, _deactivate: function(menuitem, animate) { this.activeitem = null; menuitem.children('a.ui-menuitem-link').removeClass('ui-state-hover'); menuitem.removeClass('ui-menuitem-active'); if(animate) { menuitem.children('ul.ui-menu-child:visible').fadeOut('fast'); } else { menuitem.children('ul.ui-menu-child:visible').hide(); } }, _activate: function(menuitem) { this._highlight(menuitem); var submenu = menuitem.children('ul.ui-menu-child'); if(submenu.length === 1) { this._showSubmenu(menuitem, submenu); } }, _reactivate: function(menuitem) { this.activeitem = menuitem; var submenu = menuitem.children('ul.ui-menu-child'), activeChilditem = submenu.children('li.ui-menuitem-active:first'), _self = this; if(activeChilditem.length === 1) { _self._deactivate(activeChilditem); } }, _highlight: function(menuitem) { this.activeitem = menuitem; menuitem.children('a.ui-menuitem-link').addClass('ui-state-hover'); menuitem.addClass('ui-menuitem-active'); }, _showSubmenu: function(menuitem, submenu) { submenu.css({ 'left': menuitem.outerWidth(), 'top': 0, 'z-index': ++PUI.zindex }); submenu.show(); }, _getRootSubmenuIcon: function() { return 'fa-caret-right'; }, _destroy: function() { this._super(); var $this = this; this._unbindEvents(); this.element.removeClass('ui-menu-list ui-helper-reset'); this.element.find('li').removeClass('ui-menuitem ui-widget ui-corner-all ui-menu-parent').each(function() { var listItem = $(this), link = listItem.children('a'); link.removeClass('ui-menuitem-link ui-corner-all').children('.fa').remove(); if($this.options.enhanced) link.children('.ui-menuitem-text').removeClass('ui-menuitem-text'); else link.children('.ui-menuitem-text').contents().unwrap(); listItem.children('ul').removeClass('ui-widget-content ui-menu-list ui-corner-all ui-helper-clearfix ui-menu-child ui-shadow'); }); if(this.options.popup) { this.container.appendTo(this.originalParent); } if(!this.options.enhanced) { this.element.unwrap(); } } }); })(); /** * PrimeUI Menubar Widget */ (function() { $.widget("primeui.puimenubar", $.primeui.puitieredmenu, { options: { autoDisplay: true, enhanced: false }, _create: function() { this._super(); if(!this.options.enhanced) { this.element.parent().removeClass('ui-tieredmenu').addClass('ui-menubar'); } }, _showSubmenu: function(menuitem, submenu) { var win = $(window), submenuOffsetTop = null, submenuCSS = { 'z-index': ++PUI.zindex }; if(menuitem.parent().hasClass('ui-menu-child')) { submenuCSS.left = menuitem.outerWidth(); submenuCSS.top = 0; submenuOffsetTop = menuitem.offset().top - win.scrollTop(); } else { submenuCSS.left = 0; submenuCSS.top = menuitem.outerHeight(); submenuOffsetTop = menuitem.offset().top + submenuCSS.top - win.scrollTop(); } //adjust height within viewport submenu.css('height', 'auto'); if((submenuOffsetTop + submenu.outerHeight()) > win.height()) { submenuCSS.overflow = 'auto'; submenuCSS.height = win.height() - (submenuOffsetTop + 20); } submenu.css(submenuCSS).show(); }, _getRootSubmenuIcon: function() { return 'fa-caret-down'; } }); })(); /* * PrimeUI SlideMenu Widget */ (function() { $.widget("primeui.puislidemenu", $.primeui.puibasemenu, { _create: function() { this.id = this.element.attr('id'); if(!this.id) { this.id = this.element.uniqueId().attr('id'); } this._render(); //elements this.rootList = this.element; this.content = this.element.parent(); this.wrapper = this.content.parent(); this.container = this.wrapper.parent(); this.originalParent = this.container.parent(); this.submenus = this.container.find('ul.ui-menu-list'); this.links = this.element.find('a.ui-menuitem-link:not(.ui-state-disabled)'); this.backward = this.wrapper.children('div.ui-slidemenu-backward'); //config this.stack = []; this.jqWidth = this.container.width(); if(!this.options.popup) { var $this = this; setTimeout(function() { $this._applyDimensions(); }, 100); } this._bindEvents(); this._super(); }, _render: function() { var $this = this; if(!this.options.enhanced) { this.element.wrap('<div class="ui-menu ui-slidemenu ui-widget ui-widget-content ui-corner-all"></div>') .wrap('<div class="ui-slidemenu-wrapper"></div>') .wrap('<div class="ui-slidemenu-content"></div>'); this.element.parent().after('<div class="ui-slidemenu-backward ui-widget-header ui-corner-all"><span class="fa fa-fw fa-caret-left"></span>Back</div>'); } this.element.addClass('ui-menu-list ui-helper-reset'); this.element.find('li').each(function() { var listItem = $(this), menuitemLink = listItem.children('a'), icon = menuitemLink.data('icon'); menuitemLink.addClass('ui-menuitem-link ui-corner-all'); if($this.options.enhanced) menuitemLink.children('span').addClass('ui-menuitem-text'); else menuitemLink.contents().wrap('<span class="ui-menuitem-text" />'); if(icon) { menuitemLink.prepend('<span class="ui-menuitem-icon fa fa-fw ' + icon + '"></span>'); } listItem.addClass('ui-menuitem ui-widget ui-corner-all'); if(listItem.children('ul').length) { listItem.addClass('ui-menu-parent'); listItem.children('ul').addClass('ui-widget-content ui-menu-list ui-corner-all ui-helper-clearfix ui-menu-child ui-shadow'); menuitemLink.prepend('<span class="ui-submenu-icon fa fa-fw fa-caret-right"></span>'); } }); }, _destroy: function() { this._super(); this._unbindEvents(); var $this = this; this.element.removeClass('ui-menu-list ui-helper-reset'); this.element.find('li').removeClass('ui-menuitem ui-widget ui-corner-all ui-menu-parent').each(function() { var listItem = $(this), link = listItem.children('a'); link.removeClass('ui-menuitem-link ui-corner-all').children('.fa').remove(); if($this.options.enhanced) link.children('.ui-menuitem-text').removeClass('ui-menuitem-text'); else link.children('.ui-menuitem-text').contents().unwrap(); listItem.children('ul').removeClass('ui-widget-content ui-menu-list ui-corner-all ui-helper-clearfix ui-menu-child ui-shadow'); }); if(this.options.popup) { this.container.appendTo(this.originalParent); } if(!this.options.enhanced) { this.content.next('.ui-slidemenu-backward').remove(); this.element.unwrap().unwrap().unwrap(); } }, _bindEvents: function() { var $this = this; this.links.on('mouseenter.ui-menu',function() { $(this).addClass('ui-state-hover'); }) .on('mouseleave.ui-menu',function() { $(this).removeClass('ui-state-hover'); }) .on('click.ui-menu',function() { var link = $(this), submenu = link.next(); if(submenu.length == 1) { $this._forward(submenu); } }); this.backward.on('click.ui-menu',function() { $this._back(); }); }, _unbindEvents: function() { this.links.off('mouseenter.ui-menu mouseleave.ui-menu click.ui-menu'); this.backward.off('click.ui-menu'); }, _forward: function(submenu) { var $this = this; this._push(submenu); var rootLeft = -1 * (this._depth() * this.jqWidth); submenu.show().css({ left: this.jqWidth }); this.rootList.animate({ left: rootLeft }, 500, 'easeInOutCirc', function() { if($this.backward.is(':hidden')) { $this.backward.fadeIn('fast'); } }); }, _back: function() { if(!this.rootList.is(':animated')) { var $this = this, last = this._pop(), depth = this._depth(); var rootLeft = -1 * (depth * this.jqWidth); this.rootList.animate({ left: rootLeft }, 500, 'easeInOutCirc', function() { if(last) { last.hide(); } if(depth === 0) { $this.backward.fadeOut('fast'); } }); } }, _push: function(submenu) { this.stack.push(submenu); }, _pop: function() { return this.stack.pop(); }, _last: function() { return this.stack[this.stack.length - 1]; }, _depth: function() { return this.stack.length; }, _applyDimensions: function() { this.submenus.width(this.container.width()); this.wrapper.height(this.rootList.outerHeight(true) + this.backward.outerHeight(true)); this.content.height(this.rootList.outerHeight(true)); this.rendered = true; }, show: function() { this.align(); this.container.css('z-index', ++PUI.zindex).show(); if(!this.rendered) { this._applyDimensions(); } } }); })(); /** * PrimeUI Context Menu Widget */ (function() { $.widget("primeui.puicontextmenu", $.primeui.puitieredmenu, { options: { autoDisplay: true, target: null, event: 'contextmenu' }, _create: function() { this._super(); this.element.parent().removeClass('ui-tieredmenu'). addClass('ui-contextmenu ui-menu-dynamic ui-shadow'); var $this = this; if(this.options.target) { this.options.target = $(this.options.target); if(this.options.target.hasClass('ui-datatable')) { $this._bindDataTable(); } else { this.options.target.on(this.options.event + '.ui-contextmenu', function(e){ $this.show(e); }); } } if(!this.element.parent().parent().is(document.body)) { this.element.parent().appendTo('body'); } }, _bindDocumentHandler: function() { var $this = this; //hide overlay when document is clicked $(document.body).on('click.ui-contextmenu.' + this.id, function (e) { if($this.element.parent().is(":hidden")) { return; } $this._hide(); }); }, _bindDataTable: function() { var rowSelector = '#' + this.options.target.attr('id') + ' tbody.ui-datatable-data > tr.ui-widget-content:not(.ui-datatable-empty-message)', event = this.options.event + '.ui-datatable', $this = this; $(document).off(event, rowSelector) .on(event, rowSelector, null, function(e) { $this.options.target.puidatatable('onRowRightClick', event, $(this)); $this.show(e); }); }, _unbindDataTable: function() { $(document).off(this.options.event + '.ui-datatable', '#' + this.options.target.attr('id') + ' tbody.ui-datatable-data > tr.ui-widget-content:not(.ui-datatable-empty-message)'); }, _unbindEvents: function() { this._super(); if(this.options.target) { if(this.options.target.hasClass('ui-datatable')) this._unbindDataTable(); else this.options.target.off(this.options.event + '.ui-contextmenu'); } $(document.body).off('click.ui-contextmenu.' + this.id); }, show: function(e) { //hide other contextmenus if any $(document.body).children('.ui-contextmenu:visible').hide(); var win = $(window), left = e.pageX, top = e.pageY, width = this.element.parent().outerWidth(), height = this.element.parent().outerHeight(); //collision detection for window boundaries if((left + width) > (win.width())+ win.scrollLeft()) { left = left - width; } if((top + height ) > (win.height() + win.scrollTop())) { top = top - height; } if(this.options.beforeShow) { this.options.beforeShow.call(this); } this.element.parent().css({ 'left': left, 'top': top, 'z-index': ++PUI.zindex }).show(); e.preventDefault(); e.stopPropagation(); }, _hide: function() { var $this = this; //hide submenus this.element.parent().find('li.ui-menuitem-active').each(function() { $this._deactivate($(this), true); }); this.element.parent().fadeOut('fast'); }, isVisible: function() { return this.element.parent().is(':visible'); }, getTarget: function() { return this.jqTarget; }, _destroy: function() { var $this = this; this._unbindEvents(); this.element.removeClass('ui-menu-list ui-helper-reset'); this.element.find('li').removeClass('ui-menuitem ui-widget ui-corner-all ui-menu-parent').each(function() { var listItem = $(this), link = listItem.children('a'); link.removeClass('ui-menuitem-link ui-corner-all').children('.fa').remove(); if($this.options.enhanced) link.children('.ui-menuitem-text').removeClass('ui-menuitem-text'); else link.children('.ui-menuitem-text').contents().unwrap(); listItem.children('ul').removeClass('ui-widget-content ui-menu-list ui-corner-all ui-helper-clearfix ui-menu-child ui-shadow'); }); this.container.appendTo(this.originalParent); if(!this.options.enhanced) { this.element.unwrap(); } } }); })(); /* * PrimeUI MegaMenu Widget */ (function() { $.widget("primeui.puimegamenu", $.primeui.puibasemenu, { options: { autoDisplay: true, orientation:'horizontal', enhanced: false }, _create: function() { this.id = this.element.attr('id'); if(!this.id) { this.id = this.element.uniqueId().attr('id'); } this._render(); this.rootList = this.element.children('ul'); this.rootLinks = this.rootList.children('li').children('a'); this.subLinks = this.element.find('.ui-megamenu-panel a.ui-menuitem-link'); this.keyboardTarget = this.element.children('.ui-helper-hidden-accessible'); this._bindEvents(); this._bindKeyEvents(); }, _render: function() { var $this = this; if(!this.options.enhanced) { this.element.prepend('<div tabindex="0" class="ui-helper-hidden-accessible"></div>'); this.element.addClass('ui-menu ui-menubar ui-megamenu ui-widget ui-widget-content ui-corner-all ui-helper-clearfix'); if(this._isVertical()) { this.element.addClass('ui-megamenu-vertical'); } } this.element.children('ul').addClass('ui-menu-list ui-helper-reset'); this.element.find('li').each(function(){ var listItem = $(this), menuitemLink = listItem.children('a'), icon = menuitemLink.data('icon'); menuitemLink.addClass('ui-menuitem-link ui-corner-all'); if($this.options.enhanced) menuitemLink.children('span').addClass('ui-menuitem-text'); else menuitemLink.contents().wrap('<span class="ui-menuitem-text" />'); if(icon) { menuitemLink.prepend('<span class="ui-menuitem-icon fa fa-fw ' + icon + '"></span>'); } listItem.addClass('ui-menuitem ui-widget ui-corner-all'); listItem.parent().addClass('ui-menu-list ui-helper-reset'); if(listItem.children('h3').length) { listItem.addClass('ui-widget-header ui-corner-all'); listItem.removeClass('ui-widget ui-menuitem'); } else if(listItem.children('div').length) { var submenuIcon = $this._isVertical() ? 'fa-caret-right' : 'fa-caret-down'; listItem.addClass('ui-menu-parent'); listItem.children('div').addClass('ui-megamenu-panel ui-widget-content ui-menu-list ui-corner-all ui-helper-clearfix ui-menu-child ui-shadow'); menuitemLink.addClass('ui-submenu-link').prepend('<span class="ui-submenu-icon fa fa-fw ' + submenuIcon + '"></span>'); } }); }, _destroy: function() { var $this = this; this._unbindEvents(); if(!this.options.enhanced) { this.element.children('.ui-helper-hidden-accessible').remove(); this.element.removeClass('ui-menu ui-menubar ui-megamenu ui-widget ui-widget-content ui-corner-all ui-helper-clearfix ui-megamenu-vertical'); } this.element.find('li').each(function(){ var listItem = $(this), menuitemLink = listItem.children('a'); menuitemLink.removeClass('ui-menuitem-link ui-corner-all'); if($this.options.enhanced) menuitemLink.children('span').removeClass('ui-menuitem-text'); else menuitemLink.contents().unwrap(); menuitemLink.children('.ui-menuitem-icon').remove(); listItem.removeClass('ui-menuitem ui-widget ui-corner-all') .parent().removeClass('ui-menu-list ui-helper-reset'); if(listItem.children('h3').length) { listItem.removeClass('ui-widget-header ui-corner-all'); } else if(listItem.children('div').length) { var submenuIcon = $this._isVertical() ? 'fa-caret-right' : 'fa-caret-down'; listItem.removeClass('ui-menu-parent'); listItem.children('div').removeClass('ui-megamenu-panel ui-widget-content ui-menu-list ui-corner-all ui-helper-clearfix ui-menu-child ui-shadow'); menuitemLink.removeClass('ui-submenu-link').children('.ui-submenu-icon').remove(); } }); }, _bindEvents: function() { var $this = this; this.rootLinks.on('mouseenter.ui-megamenu', function(e) { var link = $(this), menuitem = link.parent(); var current = menuitem.siblings('.ui-menuitem-active'); if(current.length > 0) { current.find('li.ui-menuitem-active').each(function() { $this._deactivate($(this)); }); $this._deactivate(current, false); } if($this.options.autoDisplay||$this.active) { $this._activate(menuitem); } else { $this._highlight(menuitem); } }); if(this.options.autoDisplay === false) { this.rootLinks.data('primefaces-megamenu', this.id).find('*').data('primefaces-megamenu', this.id) this.rootLinks.on('click.ui-megamenu', function(e) { var link = $(this), menuitem = link.parent(), submenu = link.next(); if(submenu.length === 1) { if(submenu.is(':visible')) { $this.active = false; $this._deactivate(menuitem, true); } else { $this.active = true; $this._activate(menuitem); } } e.preventDefault(); }); } else { this.rootLinks.filter('.ui-submenu-link').on('click.ui-megamenu', function(e) { e.preventDefault(); }); } this.subLinks.on('mouseenter.ui-megamenu', function() { if($this.activeitem && !$this.isRootLink($this.activeitem)) { $this._deactivate($this.activeitem); } $this._highlight($(this).parent()); }) .on('mouseleave.ui-megamenu', function() { if($this.activeitem && !$this.isRootLink($this.activeitem)) { $this._deactivate($this.activeitem); } $(this).removeClass('ui-state-hover'); }); this.rootList.on('mouseleave.ui-megamenu', function(e) { var activeitem = $this.rootList.children('.ui-menuitem-active'); if(activeitem.length === 1) { $this._deactivate(activeitem, false); } }); this.rootList.find('> li.ui-menuitem > ul.ui-menu-child').on('mouseleave.ui-megamenu', function(e) { e.stopPropagation(); }); $(document.body).on('click.' + this.id, function(e) { var target = $(e.target); if(target.data('primefaces-megamenu') === $this.id) { return; } $this.active = false; $this._deactivate($this.rootList.children('li.ui-menuitem-active'), true); }); }, _unbindEvents: function() { this.rootLinks.off('mouseenter.ui-megamenu mouselave.ui-megamenu click.ui-megamenu'); this.subLinks.off('mouseenter.ui-megamenu mouselave.ui-megamenu'); this.rootList.off('mouseleave.ui-megamenu'); this.rootList.find('> li.ui-menuitem > ul.ui-menu-child').off('mouseleave.ui-megamenu'); $(document.body).off('click.' + this.id); }, _isVertical: function () { if(this.options.orientation === 'vertical') return true; else return false; }, _deactivate: function(menuitem, animate) { var link = menuitem.children('a.ui-menuitem-link'), submenu = link.next(); menuitem.removeClass('ui-menuitem-active'); link.removeClass('ui-state-hover'); this.activeitem = null; if(submenu.length > 0) { if(animate) submenu.fadeOut('fast'); else submenu.hide(); } }, _activate: function(menuitem) { var submenu = menuitem.children('.ui-megamenu-panel'), $this = this; $this._highlight(menuitem); if(submenu.length > 0) { $this._showSubmenu(menuitem, submenu); } }, _highlight: function(menuitem) { var link = menuitem.children('a.ui-menuitem-link'); menuitem.addClass('ui-menuitem-active'); link.addClass('ui-state-hover'); this.activeitem = menuitem; }, _showSubmenu: function(menuitem, submenu) { var pos = null; if(this._isVertical()) { pos = { my: 'left top', at: 'right top', of: menuitem, collision: 'flipfit' }; } else { pos = { my: 'left top', at: 'left bottom', of: menuitem, collision: 'flipfit' }; } submenu.css({ 'z-index': ++PUI.zindex }); submenu.show().position(pos); }, _bindKeyEvents: function() { var $this = this; this.keyboardTarget.on('focus.ui-megamenu', function(e) { $this._highlight($this.rootLinks.eq(0).parent()); }) .on('blur.ui-megamenu', function() { $this._reset(); }) .on('keydown.ui-megamenu', function(e) { var currentitem = $this.activeitem; if(!currentitem) { return; } var isRootLink = $this._isRootLink(currentitem), keyCode = $.ui.keyCode; switch(e.which) { case keyCode.LEFT: if(isRootLink && !$this._isVertical()) { var prevItem = currentitem.prevAll('.ui-menuitem:first'); if(prevItem.length) { $this._deactivate(currentitem); $this._highlight(prevItem); } e.preventDefault(); } else { if(currentitem.hasClass('ui-menu-parent') && currentitem.children('.ui-menu-child').is(':visible')) { $this._deactivate(currentitem); $this._highlight(currentitem); } else { var parentItem = currentitem.closest('.ui-menu-child').parent(); if(parentItem.length) { $this._deactivate(currentitem); $this._deactivate(parentItem); $this._highlight(parentItem); } } } break; case keyCode.RIGHT: if(isRootLink && !$this._isVertical()) { var nextItem = currentitem.nextAll('.ui-menuitem:visible:first'); if(nextItem.length) { $this._deactivate(currentitem); $this._highlight(nextItem); } e.preventDefault(); } else { if(currentitem.hasClass('ui-menu-parent')) { var submenu = currentitem.children('.ui-menu-child'); if(submenu.is(':visible')) { $this._highlight(submenu.find('.ui-menu-list:visible > .ui-menuitem:visible:first')); } else { $this._activate(currentitem); } } } break; case keyCode.UP: if(!isRootLink || $this._isVertical()) { var prevItem = $this._findPrevItem(currentitem); if(prevItem.length) { $this._deactivate(currentitem); $this._highlight(prevItem); } } e.preventDefault(); break; case keyCode.DOWN: if(isRootLink && !$this._isVertical()) { var submenu = currentitem.children('.ui-menu-child'); if(submenu.is(':visible')) { var firstMenulist = $this._getFirstMenuList(submenu); $this._highlight(firstMenulist.children('.ui-menuitem:visible:first')); } else { $this._activate(currentitem); } } else { var nextItem = $this._findNextItem(currentitem); if(nextItem.length) { $this._deactivate(currentitem); $this._highlight(nextItem); } } e.preventDefault(); break; case keyCode.ENTER: case keyCode.NUMPAD_ENTER: var currentLink = currentitem.children('.ui-menuitem-link'); currentLink.trigger('click'); $this.element.blur(); var href = currentLink.attr('href'); if(href && href !== '#') { window.location.href = href; } $this._deactivate(currentitem); e.preventDefault(); break; case keyCode.ESCAPE: if(currentitem.hasClass('ui-menu-parent')) { var submenu = currentitem.children('.ui-menu-list:visible'); if(submenu.length > 0) { submenu.hide(); } } else { var parentItem = currentitem.closest('.ui-menu-child').parent(); if(parentItem.length) { $this._deactivate(currentitem); $this._deactivate(parentItem); $this._highlight(parentItem); } } e.preventDefault(); break; } }); }, _findPrevItem: function(menuitem) { var previtem = menuitem.prev('.ui-menuitem'); if(!previtem.length) { var prevSubmenu = menuitem.closest('ul.ui-menu-list').prev('.ui-menu-list'); if(!prevSubmenu.length) { prevSubmenu = menuitem.closest('div').prev('div').children('.ui-menu-list:visible:last'); } if(prevSubmenu.length) { previtem = prevSubmenu.find('li.ui-menuitem:visible:last'); } } return previtem; }, _findNextItem: function(menuitem) { var nextitem = menuitem.next('.ui-menuitem'); if(!nextitem.length) { var nextSubmenu = menuitem.closest('ul.ui-menu-list').next('.ui-menu-list'); if(!nextSubmenu.length) { nextSubmenu = menuitem.closest('div').next('div').children('.ui-menu-list:visible:first'); } if(nextSubmenu.length) { nextitem = nextSubmenu.find('li.ui-menuitem:visible:first'); } } return nextitem; }, _getFirstMenuList: function(submenu) { return submenu.find('.ui-menu-list:not(.ui-state-disabled):first'); }, _isRootLink: function(menuitem) { var submenu = menuitem.closest('ul'); return submenu.parent().hasClass('ui-menu'); }, _reset: function() { var $this = this; this.active = false; this.element.find('li.ui-menuitem-active').each(function() { $this._deactivate($(this), true); }); }, isRootLink: function(menuitem) { var submenu = menuitem.closest('ul'); return submenu.parent().hasClass('ui-menu'); } }); })(); /** * PrimeUI PanelMenu Widget */ (function() { $.widget("primeui.puipanelmenu", $.primeui.puibasemenu, { options: { stateful: false, enhanced: false }, _create: function() { this.id = this.element.attr('id'); if(!this.id) { this.id = this.element.uniqueId().attr('id'); } this.panels = this.element.children('div'); this._render(); this.headers = this.element.find('> .ui-panelmenu-panel > div.ui-panelmenu-header:not(.ui-state-disabled)'); this.contents = this.element.find('> .ui-panelmenu-panel > .ui-panelmenu-content'); this.menuitemLinks = this.contents.find('.ui-menuitem-link:not(.ui-state-disabled)'); this.treeLinks = this.contents.find('.ui-menu-parent > .ui-menuitem-link:not(.ui-state-disabled)'); this._bindEvents(); if(this.options.stateful) { this.stateKey = 'panelMenu-' + this.id; } this._restoreState(); }, _render: function() { var $this = this; if(!this.options.enhanced) { this.element.addClass('ui-panelmenu ui-widget'); } this.panels.addClass('ui-panelmenu-panel'); this.element.find('li').each(function(){ var listItem = $(this), menuitemLink = listItem.children('a'), icon = menuitemLink.data('icon'); menuitemLink.addClass('ui-menuitem-link ui-corner-all') if($this.options.enhanced) menuitemLink.children('span').addClass('ui-menuitem-text'); else menuitemLink.contents().wrap('<span class="ui-menuitem-text" />'); if(icon) { menuitemLink.prepend('<span class="ui-menuitem-icon fa fa-fw ' + icon + '"></span>'); } if(listItem.children('ul').length) { listItem.addClass('ui-menu-parent'); menuitemLink.prepend('<span class="ui-panelmenu-icon fa fa-fw fa-caret-right"></span>'); listItem.children('ul').addClass('ui-helper-hidden'); if(icon) { menuitemLink.addClass('ui-menuitem-link-hasicon'); } } listItem.addClass('ui-menuitem ui-widget ui-corner-all'); listItem.parent().addClass('ui-menu-list ui-helper-reset'); }); //headers this.panels.children(':first-child').attr('tabindex', '0').each(function () { var header = $(this), headerLink = header.children('a'), icon = headerLink.data('icon'); if(icon) { headerLink.addClass('ui-panelmenu-headerlink-hasicon').prepend('<span class="ui-menuitem-icon fa fa-fw ' + icon + '"></span>'); } header.addClass('ui-widget ui-panelmenu-header ui-state-default ui-corner-all').prepend('<span class="ui-panelmenu-icon fa fa-fw fa-caret-right"></span>'); }); //contents this.panels.children(':last-child').attr('tabindex', '0').addClass('ui-panelmenu-content ui-widget-content ui-helper-hidden'); }, _destroy: function() { var $this = this; this._unbindEvents(); if(!this.options.enhanced) { this.element.removeClass('ui-panelmenu ui-widget'); } this.panels.removeClass('ui-panelmenu-panel'); this.headers.removeClass('ui-widget ui-panelmenu-header ui-state-default ui-state-hover ui-state-active ui-corner-all ui-corner-top').removeAttr('tabindex'); this.contents.removeClass('ui-panelmenu-content ui-widget-content ui-helper-hidden').removeAttr('tabindex') this.contents.find('ul').removeClass('ui-menu-list ui-helper-reset ui-helper-hidden'); this.headers.each(function () { var header = $(this), headerLink = header.children('a'); header.children('.fa').remove(); headerLink.removeClass('ui-panelmenu-headerlink-hasicon'); headerLink.children('.fa').remove(); }); this.element.find('li').each(function(){ var listItem = $(this), menuitemLink = listItem.children('a'); menuitemLink.removeClass('ui-menuitem-link ui-corner-all ui-menuitem-link-hasicon'); if($this.options.enhanced) menuitemLink.children('span').removeClass('ui-menuitem-text'); else menuitemLink.contents().unwrap(); menuitemLink.children('.fa').remove(); listItem.removeClass('ui-menuitem ui-widget ui-corner-all ui-menu-parent') .parent().removeClass('ui-menu-list ui-helper-reset ui-helper-hidden '); }); }, _unbindEvents: function() { this.headers.off('mouseover.ui-panelmenu mouseout.ui-panelmenu click.ui-panelmenu'); this.menuitemLinks.off('mouseover.ui-panelmenu mouseout.ui-panelmenu click.ui-panelmenu'); this.treeLinks.off('click.ui-panelmenu'); this._unbindKeyEvents(); }, _bindEvents: function() { var $this = this; this.headers.on('mouseover.ui-panelmenu', function() { var element = $(this); if(!element.hasClass('ui-state-active')) { element.addClass('ui-state-hover'); } }).on('mouseout.ui-panelmenu', function() { var element = $(this); if(!element.hasClass('ui-state-active')) { element.removeClass('ui-state-hover'); } }).on('click.ui-panelmenu', function(e) { var header = $(this); if(header.hasClass('ui-state-active')) $this._collapseRootSubmenu($(this)); else $this._expandRootSubmenu($(this), false); $this._removeFocusedItem(); header.focus(); e.preventDefault(); }); this.menuitemLinks.on('mouseover.ui-panelmenu', function() { $(this).addClass('ui-state-hover'); }).on('mouseout.ui-panelmenu', function() { $(this).removeClass('ui-state-hover'); }).on('click.ui-panelmenu', function(e) { var currentLink = $(this); $this._focusItem(currentLink.closest('.ui-menuitem')); var href = currentLink.attr('href'); if(href && href !== '#') { window.location.href = href; } e.preventDefault(); }); this.treeLinks.on('click.ui-panelmenu', function(e) { var link = $(this), submenu = link.parent(), submenuList = link.next(); if(submenuList.is(':visible')) { if(link.children('span.fa-caret-down').length) { link.children('span.fa-caret-down').removeClass('fa-caret-down').addClass('fa-caret-right'); } $this._collapseTreeItem(submenu); } else { if(link.children('span.fa-caret-right').length) { link.children('span.fa-caret-right').removeClass('fa-caret-right').addClass('fa-caret-down'); } $this._expandTreeItem(submenu, false); } e.preventDefault(); }); this._bindKeyEvents(); }, _bindKeyEvents: function() { var $this = this; if(PUI.isIE()) { this.focusCheck = false; } this.headers.on('focus.panelmenu', function(){ $(this).addClass('ui-menuitem-outline'); }) .on('blur.panelmenu', function(){ $(this).removeClass('ui-menuitem-outline ui-state-hover'); }) .on('keydown.panelmenu', function(e) { var keyCode = $.ui.keyCode, key = e.which; if(key === keyCode.SPACE || key === keyCode.ENTER || key === keyCode.NUMPAD_ENTER) { $(this).trigger('click'); e.preventDefault(); } }); this.contents.on('mousedown.panelmenu', function(e) { if($(e.target).is(':not(:input:enabled)')) { e.preventDefault(); } }).on('focus.panelmenu', function(){ if(!$this.focusedItem) { $this._focusItem($this._getFirstItemOfContent($(this))); if(PUI.isIE()) { $this.focusCheck = false; } } }).on('keydown.panelmenu', function(e) { if(!$this.focusedItem) { return; } var keyCode = $.ui.keyCode; switch(e.which) { case keyCode.LEFT: if($this._isExpanded($this.focusedItem)) { $this.focusedItem.children('.ui-menuitem-link').trigger('click'); } else { var parentListOfItem = $this.focusedItem.closest('ul.ui-menu-list'); if(parentListOfItem.parent().is(':not(.ui-panelmenu-content)')) { $this._focusItem(parentListOfItem.closest('li.ui-menuitem')); } } e.preventDefault(); break; case keyCode.RIGHT: if($this.focusedItem.hasClass('ui-menu-parent') && !$this._isExpanded($this.focusedItem)) { $this.focusedItem.children('.ui-menuitem-link').trigger('click'); } e.preventDefault(); break; case keyCode.UP: var itemToFocus = null, prevItem = $this.focusedItem.prev(); if(prevItem.length) { itemToFocus = prevItem.find('li.ui-menuitem:visible:last'); if(!itemToFocus.length) { itemToFocus = prevItem; } } else { itemToFocus = $this.focusedItem.closest('ul').parent('li'); } if(itemToFocus.length) { $this._focusItem(itemToFocus); } e.preventDefault(); break; case keyCode.DOWN: var itemToFocus = null, firstVisibleChildItem = $this.focusedItem.find('> ul > li:visible:first'); if(firstVisibleChildItem.length) { itemToFocus = firstVisibleChildItem; } else if($this.focusedItem.next().length) { itemToFocus = $this.focusedItem.next(); } else { if($this.focusedItem.next().length === 0) { itemToFocus = $this._searchDown($this.focusedItem); } } if(itemToFocus && itemToFocus.length) { $this._focusItem(itemToFocus); } e.preventDefault(); break; case keyCode.ENTER: case keyCode.NUMPAD_ENTER: case keyCode.SPACE: var currentLink = $this.focusedItem.children('.ui-menuitem-link'); //IE fix setTimeout(function(){ currentLink.trigger('click'); },1); $this.element.blur(); var href = currentLink.attr('href'); if(href && href !== '#') { window.location.href = href; } e.preventDefault(); break; case keyCode.TAB: if($this.focusedItem) { if(PUI.isIE()) { $this.focusCheck = true; } $(this).focus(); } break; } }).on('blur.panelmenu', function(e) { if(PUI.isIE() && !$this.focusCheck) { return; } $this._removeFocusedItem(); }); var clickNS = 'click.' + this.id; //remove focusedItem when document is clicked $(document.body).off(clickNS).on(clickNS, function(event) { if(!$(event.target).closest('.ui-panelmenu').length) { $this._removeFocusedItem(); } }); }, _unbindKeyEvents: function() { this.headers.off('focus.panelmenu blur.panelmenu keydown.panelmenu'); this.contents.off('mousedown.panelmenu focus.panelmenu keydown.panelmenu blur.panelmenu'); $(document.body).off('click.' + this.id); }, _isExpanded: function(item) { return item.children('ul.ui-menu-list').is(':visible'); }, _searchDown: function(item) { var nextOfParent = item.closest('ul').parent('li').next(), itemToFocus = null; if(nextOfParent.length) { itemToFocus = nextOfParent; } else if(item.closest('ul').parent('li').length === 0){ itemToFocus = item; } else { itemToFocus = this._searchDown(item.closest('ul').parent('li')); } return itemToFocus; }, _getFirstItemOfContent: function(content) { return content.find('> .ui-menu-list > .ui-menuitem:visible:first-child'); }, _collapseRootSubmenu: function(header) { var panel = header.next(); header.attr('aria-expanded', false).removeClass('ui-state-active ui-corner-top').addClass('ui-state-hover ui-corner-all'); header.children('span.fa').removeClass('fa-caret-down').addClass('fa-caret-right'); panel.attr('aria-hidden', true).slideUp('normal', 'easeInOutCirc'); this._removeAsExpanded(panel); }, _expandRootSubmenu: function(header, restoring) { var panel = header.next(); header.attr('aria-expanded', true).addClass('ui-state-active ui-corner-top').removeClass('ui-state-hover ui-corner-all'); header.children('span.fa').removeClass('fa-caret-right').addClass('fa-caret-down'); if(restoring) { panel.attr('aria-hidden', false).show(); } else { panel.attr('aria-hidden', false).slideDown('normal', 'easeInOutCirc'); this._addAsExpanded(panel); } }, _restoreState: function() { var expandedNodeIds = null; if(this.options.stateful) { expandedNodeIds = PUI.getCookie(this.stateKey); } if(expandedNodeIds) { this._collapseAll(); this.expandedNodes = expandedNodeIds.split(','); for(var i = 0 ; i < this.expandedNodes.length; i++) { var element = $(PUI.escapeClientId(this.expandedNodes[i])); if(element.is('div.ui-panelmenu-content')) this._expandRootSubmenu(element.prev(), true); else if(element.is('li.ui-menu-parent')) this._expandTreeItem(element, true); } } else { this.expandedNodes = []; var activeHeaders = this.headers.filter('.ui-state-active'), activeTreeSubmenus = this.element.find('.ui-menu-parent > .ui-menu-list:not(.ui-helper-hidden)'); for(var i = 0; i < activeHeaders.length; i++) { this.expandedNodes.push(activeHeaders.eq(i).next().attr('id')); } for(var i = 0; i < activeTreeSubmenus.length; i++) { this.expandedNodes.push(activeTreeSubmenus.eq(i).parent().attr('id')); } } }, _collapseAll: function() { this.headers.filter('.ui-state-active').each(function() { var header = $(this); header.removeClass('ui-state-active').next().addClass('ui-helper-hidden'); }); this.element.find('.ui-menu-parent > .ui-menu-list:not(.ui-helper-hidden)').each(function() { $(this).addClass('ui-helper-hidden'); }); }, _removeAsExpanded: function(element) { var id = element.attr('id'); this.expandedNodes = $.grep(this.expandedNodes, function(value) { return value != id; }); this._saveState(); }, _addAsExpanded: function(element) { this.expandedNodes.push(element.attr('id')); this._saveState(); }, _removeFocusedItem: function() { if(this.focusedItem) { this._getItemText(this.focusedItem).removeClass('ui-menuitem-outline'); this.focusedItem = null; } }, _focusItem: function(item) { this._removeFocusedItem(); this._getItemText(item).addClass('ui-menuitem-outline').focus(); this.focusedItem = item; }, _getItemText: function(item) { return item.find('> .ui-menuitem-link > span.ui-menuitem-text'); }, _expandTreeItem: function(submenu, restoring) { var submenuLink = submenu.find('> .ui-menuitem-link'); submenuLink.find('> .ui-menuitem-text').attr('aria-expanded', true); submenu.children('.ui-menu-list').show(); if(!restoring) { this._addAsExpanded(submenu); } }, _collapseTreeItem: function(submenu) { var submenuLink = submenu.find('> .ui-menuitem-link'); submenuLink.find('> .ui-menuitem-text').attr('aria-expanded', false); submenu.children('.ui-menu-list').hide(); this._removeAsExpanded(submenu); }, _removeAsExpanded: function(element) { var id = element.attr('id'); this.expandedNodes = $.grep(this.expandedNodes, function(value) { return value != id; }); this._saveState(); }, _addAsExpanded: function(element) { this.expandedNodes.push(element.attr('id')); this._saveState(); }, _saveState: function() { if(this.options.stateful) { var expandedNodeIds = this.expandedNodes.join(','); PUI.setCookie(this.stateKey, expandedNodeIds, {path:'/'}); } }, _clearState: function() { if(this.options.stateful) { PUI.deleteCookie(this.stateKey, {path:'/'}); } } }); })(); /** * PrimeUI MultiSelect Widget */ (function() { $.widget("primeui.puimultiselect", { options: { defaultLabel: 'Choose', caseSensitive: false, filterMatchMode: 'startsWith', filterFunction: null, data: null, scrollHeight: 200, style: null, styleClass: null, value: null }, _create: function() { this.id = this.element.attr('id'); if(!this.id) { this.id = this.element.uniqueId().attr('id'); } if(this.options.data) { if($.isArray(this.options.data)) { this._generateOptionElements(this.options.data); } } this._render(); if(this.options.style) { this.container.attr('style', this.options.style); } if(this.options.styleClass) { this.container.addClass(this.options.styleClass); } this.triggers = this.container.find('.ui-multiselect-trigger, .ui-multiselect-label'); this.label = this.labelContainer.find('.ui-multiselect-label'); this._generateItems(); //preselection via value option if(this.options.value && this.options.value.length) { var checkboxes = this.items.find('.ui-chkbox-box'); for (var i = 0; i < this.options.value.length; i++) { var index = this.findSelectionIndex(this.options.value[i]); this.selectItem(this.items.eq(index)); } this.updateLabel(); } this._bindEvents(); }, _render: function() { this.choices = this.element.children('option'); this.element.attr('tabindex', '0').wrap('<div class="ui-multiselect ui-widget ui-state-default ui-corner-all ui-shadow" />') .wrap('<div class="ui-helper-hidden-accessible" />'); this.container = this.element.closest('.ui-multiselect'); this.container.append('<div class="ui-helper-hidden-accessible"><input readonly="readonly" type="text" /></div>'); this.labelContainer = $('<div class="ui-multiselect-label-container"><label class="ui-multiselect-label ui-corner-all">' + this.options.defaultLabel + '</label></div>').appendTo(this.container); this.menuIcon = $('<div class="ui-multiselect-trigger ui-state-default ui-corner-right"><span class="fa fa-fw fa-caret-down"></span></div>') .appendTo(this.container); this._renderPanel(); //filter this.filterContainer = $('<div class="ui-multiselect-filter-container" />').appendTo(this.panelHeader); this.filterInput = $('<input type="text" aria-readonly="false" aria-disabled="false" aria-multiline="false" class="ui-inputfield ui-inputtext ui-widget ui-state-default ui-corner-all" />') .appendTo(this.filterContainer); this.filterContainer.append('<span class="fa fa-search"></span>'); this.closeIcon = $('<a class="ui-multiselect-close ui-corner-all" href="#"><span class="fa fa-close"></span></a>').appendTo(this.panelHeader); this.container.append(this.panel); }, _renderPanel: function() { //panel this.panel = $('<div id="'+this.element.attr('id')+ "_panel" +'"class="ui-multiselect-panel ui-widget ui-widget-content ui-corner-all ui-helper-hidden"/>'); this.panelHeader = $('<div class="ui-widget-header ui-corner-all ui-multiselect-header ui-helper-clearfix"></div>').appendTo(this.panel); this.toggler = $('<div class="ui-chkbox ui-widget">' + '<div class="ui-helper-hidden-accessible"><input readonly="readonly" type="checkbox"/></div>' + '<div class="ui-chkbox-box ui-widget ui-corner-all ui-state-default"><span class="ui-chkbox-icon ui-c fa fa-fw"></span></div>' + '</div>'); this.togglerBox = this.toggler.children('.ui-chkbox-box'); this.panelHeader.append(this.toggler); this.itemsWrapper = $('<div class="ui-multiselect-items-wrapper" />').appendTo(this.panel); this.itemContainer = $('<ul class="ui-multiselect-items ui-multiselect-list ui-widget-content ui-widget ui-corner-all ui-helper-reset"></ul>') .appendTo(this.itemsWrapper); this.itemsWrapper.css('max-height', this.options.scrollHeight); }, _generateItems: function() { for(var i = 0; i < this.choices.length; i++) { var option = this.choices.eq(i), optionLabel = option.text(); this.listItems = $('<li data-label="' + optionLabel + '" class="ui-multiselect-item ui-corner-all">' + '<div class="ui-chkbox ui-widget">' + '<div class="ui-helper-hidden-accessible"><input readonly="readonly" type="checkbox"/></div>' + '<div class="ui-chkbox-box ui-widget ui-corner-all ui-state-default"><span class="ui-chkbox-icon ui-c fa fa-fw"></span></div>' + '</div>' + '<label>' + optionLabel + '</label>' + '</li>').appendTo(this.itemContainer); } this.items = this.itemContainer.children('.ui-multiselect-item'); }, _generateOptionElements: function(data) { for(var i = 0; i < data.length; i++) { var choice = data[i]; if(choice.label) this.element.append('<option value="' + choice.value + '">' + choice.label + '</option>'); else this.element.append('<option value="' + choice + '">' + choice + '</option>'); } }, _bindEvents: function() { var $this = this, hideNS = 'click.' + this.id, resizeNS = 'resize.' + this.id; this._bindItemEvents(this.items.filter(':not(.ui-state-disabled)')); //Toggler this._bindCheckboxHover(this.togglerBox); this.togglerBox.on('click.puimultiselect', function() { var el = $(this); if(el.children('.ui-chkbox-icon').hasClass('fa-check')) $this.uncheckAll(); else $this.checkAll(); $this.updateLabel(); }); //Filter this._setupFilterMatcher(); this.filterInput.on('keyup.puimultiselect', function() { $(this).trigger('focus'); $this.filter($(this).val()); }) .on('focus.puimultiselect', function() { $(this).addClass('ui-state-focus'); }) .on('blur.puimultiselect', function() { $(this).removeClass('ui-state-focus'); }); //Container focus this.element.on('focus.puimultiselect', function() { $this.container.addClass('ui-state-focus'); }) .on('blur.puimultiselect', function() { $this.container.removeClass('ui-state-focus'); }); //Closer this.closeIcon.on('mouseenter.puimultiselect', function(){ $(this).addClass('ui-state-hover'); }).on('mouseleave.puimultiselect', function() { $(this).removeClass('ui-state-hover'); }).on('click.puimultiselect', function(e) { $this.hide(true); e.preventDefault(); }); //Events to show/hide the panel this.triggers.on('mouseover.puimultiselect', function() { if(!$this.disabled&&!$this.triggers.hasClass('ui-state-focus')) { $this.triggers.addClass('ui-state-hover'); } }).on('mouseout.puimultiselect', function() { if(!$this.disabled) { $this.triggers.removeClass('ui-state-hover'); } }).on('click.puimultiselect', function(e) { if(!$this.disabled) { if($this.panel.is(":hidden")) $this.show(); else $this.hide(true); } }) .on('focus.puimultiselect', function() { $(this).addClass('ui-state-focus'); }) .on('blur.puimultiselect', function() { $(this).removeClass('ui-state-focus'); }) .on('click.puimultiselect', function(e) { $this.element.trigger('focus.puimultiselect'); e.preventDefault(); }); this._bindKeyEvents(); //hide overlay when outside is clicked $(document.body).off(hideNS).on(hideNS, function (e) { if($this.panel.is(':hidden')) { return; } //do nothing on trigger mousedown var target = $(e.target); if($this.triggers.is(target)||$this.triggers.has(target).length > 0) { return; } //hide the panel and remove focus from label var offset = $this.panel.offset(); if(e.pageX < offset.left || e.pageX > offset.left + $this.panel.width() || e.pageY < offset.top || e.pageY > offset.top + $this.panel.height()) { $this.hide(true); } }); //Realign overlay on resize $(window).off(resizeNS).on(resizeNS, function() { if($this.panel.is(':visible')) { $this.alignPanel(); } }); }, _bindItemEvents: function(item) { var $this = this; item.on('mouseover.puimultiselect', function() { var el = $(this); if(!el.hasClass('ui-state-highlight')) $(this).addClass('ui-state-hover'); }) .on('mouseout.puimultiselect', function() { $(this).removeClass('ui-state-hover'); }) .on('click.puimultiselect', function() { $this._toggleItem($(this)); PUI.clearSelection(); }); }, _bindKeyEvents: function() { var $this = this; this.element.on('focus.puimultiselect', function() { $(this).addClass('ui-state-focus'); $this.menuIcon.addClass('ui-state-focus'); }).on('blur.puimultiselect', function() { $(this).removeClass('ui-state-focus'); $this.menuIcon.removeClass('ui-state-focus'); }).on('keydown.puimultiselect', function(e) { var keyCode = $.ui.keyCode, key = e.which; switch(key) { case keyCode.ENTER: case keyCode.NUMPAD_ENTER: if($this.panel.is(":hidden")) $this.show(); else $this.hide(true); e.preventDefault(); break; case keyCode.TAB: if($this.panel.is(':visible')) { $this.toggler.find('> div.ui-helper-hidden-accessible > input').trigger('focus'); e.preventDefault(); } break; }; }); this.closeIcon.on('focus.puimultiselect', function(e) { $this.closeIcon.addClass('ui-state-focus'); }) .on('blur.puimultiselect', function(e) { $this.closeIcon.removeClass('ui-state-focus'); }) .on('keydown.puimultiselect', function(e) { var keyCode = $.ui.keyCode, key = e.which; if(key === keyCode.ENTER || key === keyCode.NUMPAD_ENTER) { $this.hide(true); e.preventDefault(); } }); var togglerCheckboxInput = this.toggler.find('> div.ui-helper-hidden-accessible > input'); this._bindCheckboxKeyEvents(togglerCheckboxInput); togglerCheckboxInput.on('keyup.puimultiselect', function(e) { if(e.which === $.ui.keyCode.SPACE) { var input = $(this); if(input.prop('checked')) $this.uncheckAll(); else $this.checkAll(); e.preventDefault(); } }); var itemKeyInputs = this.itemContainer.find('> li > div.ui-chkbox > div.ui-helper-hidden-accessible > input'); this._bindCheckboxKeyEvents(itemKeyInputs); itemKeyInputs.on('keyup.selectCheckboxMenu', function(e) { if(e.which === $.ui.keyCode.SPACE) { var input = $(this), box = input.parent().next(); $this._toggleItem(input.closest('li')); e.preventDefault(); } }); }, _bindCheckboxHover: function(item) { item.on('mouseenter.puimultiselect', function() { var item = $(this); if(!item.hasClass('ui-state-active')&&!item.hasClass('ui-state-disabled')) { item.addClass('ui-state-hover'); } }).on('mouseleave.puimultiselect', function() { $(this).removeClass('ui-state-hover'); }); }, _bindCheckboxKeyEvents: function(items) { var $this = this; items.on('focus.puimultiselect', function(e) { var input = $(this), box = input.parent().next(); if(input.prop('checked')) { box.removeClass('ui-state-active'); } box.addClass('ui-state-focus'); }) .on('blur.puimultiselect', function(e) { var input = $(this), box = input.parent().next(); if(input.prop('checked')) { box.addClass('ui-state-active'); } box.removeClass('ui-state-focus'); }) .on('keydown.puimultiselect', function(e) { if(e.which === $.ui.keyCode.SPACE) { e.preventDefault(); } }); }, _toggleItem: function(item) { if(item.hasClass('ui-state-highlight')) this.unselectItem(item); else this.selectItem(item); this.updateLabel(); this.updateToggler(); }, selectItem: function(item) { var checkbox = item.find('> .ui-chkbox'); item.addClass('ui-state-highlight'); checkbox.find(':checkbox').prop('checked', true); checkbox.find('> .ui-chkbox-box > .ui-chkbox-icon').addClass('fa-check'); this.choices.eq(item.index()).prop('selected', true); }, unselectItem: function(item) { var checkbox = item.find('> .ui-chkbox'); item.removeClass('ui-state-highlight'); checkbox.find(':checkbox').prop('checked', false); checkbox.find('> .ui-chkbox-box > .ui-chkbox-icon').removeClass('fa-check'); this.choices.eq(item.index()).prop('selected', false); }, filter: function(value) { var filterValue = this.options.caseSensitive ? $.trim(value) : $.trim(value).toLowerCase(); if(filterValue === '') { this.itemContainer.children('li.ui-multiselect-item').filter(':hidden').show(); } else { for(var i = 0; i < this.choices.length; i++) { var choice = this.choices.eq(i), item = this.items.eq(i), itemLabel = this.options.caseSensitive ? choice.text() : choice.text().toLowerCase(); if(this.filterMatcher(itemLabel, filterValue)) item.show(); else item.hide(); } } this.updateToggler(); }, _setupFilterMatcher: function() { this.options.filterMatchMode = this.options.filterMatchMode||'startsWith'; this.filterMatchers = { 'startsWith': this.startsWithFilter ,'contains': this.containsFilter ,'endsWith': this.endsWithFilter ,'custom': this.options.filterFunction }; this.filterMatcher = this.filterMatchers[this.options.filterMatchMode]; }, startsWithFilter: function(value, filter) { return value.indexOf(filter) === 0; }, containsFilter: function(value, filter) { return value.indexOf(filter) !== -1; }, endsWithFilter: function(value, filter) { return value.indexOf(filter, value.length - filter.length) !== -1; }, show: function() { this.alignPanel(); this.panel.show(); this.postShow(); }, hide: function(animate) { var $this = this; if(animate) { this.panel.fadeOut('fast', function() { $this.postHide(); }); } else { this.panel.hide(); this.postHide(); } }, postShow: function() { this.panel.trigger('onShow.puimultiselect'); }, postHide: function() { this.panel.trigger('onHide.puimultiselect'); }, findSelectionIndex: function(val){ var index = -1; if(this.choices) { for(var i = 0; i < this.choices.length; i++) { if(this.choices.eq(i).val() == val) { index = i; break; } } } return index; }, updateLabel: function() { var selectedItems = this.choices.filter(':selected'), label = null; if(selectedItems.length) { label = ''; for(var i = 0; i < selectedItems.length; i++) { if(i != 0) { label = label + ','; } label = label + selectedItems.eq(i).text(); } } else { label = this.options.defaultLabel; } this.label.text(label); }, updateToggler: function() { var visibleItems = this.itemContainer.children('li.ui-multiselect-item:visible'); if(visibleItems.length && visibleItems.filter('.ui-state-highlight').length === visibleItems.length) { this.toggler.find(':checkbox').prop('checked', true); this.togglerBox.children('.ui-chkbox-icon').addClass('fa-check'); } else { this.toggler.find(':checkbox').prop('checked', false); this.togglerBox.children('.ui-chkbox-icon').removeClass('fa-check'); } }, checkAll: function() { var visibleItems = this.items.filter(':visible'), $this = this; visibleItems.each(function() { $this.selectItem($(this)); }); this.toggler.find(':checkbox').prop('checked', true); this.togglerBox.children('.ui-chkbox-icon').addClass('fa-check'); }, uncheckAll: function() { var visibleItems = this.items.filter(':visible'), $this = this; visibleItems.each(function() { $this.unselectItem($(this)); }); this.toggler.find(':checkbox').prop('checked', false); this.togglerBox.children('.ui-chkbox-icon').removeClass('fa-check'); }, alignPanel: function() { this.panel.css({ 'left':'', 'top':'', 'z-index': ++PUI.zindex }); this.panel.show().position({ my: 'left top' ,at: 'left bottom' ,of: this.container }); } }); })(); (function() { $.widget("primeui.puimultiselectlistbox", { options: { caption: null, choices: null, effect: false||'fade', name: null, value: null }, _create: function() { this.element.addClass('ui-multiselectlistbox ui-widget ui-helper-clearfix'); this.element.append('<input type="hidden"></input>'); this.element.append('<div class="ui-multiselectlistbox-listcontainer"></div>'); this.container = this.element.children('div'); this.input = this.element.children('input'); var choices = this.options.choices; if(this.options.name) { this.input.attr('name', this.options.name); } if(choices) { if(this.options.caption) { this.container.append('<div class="ui-multiselectlistbox-header ui-widget-header ui-corner-top">'+ this.options.caption +'</div>'); } this.container.append('<ul class="ui-multiselectlistbox-list ui-inputfield ui-widget-content ui-corner-bottom"></ul>'); this.rootList = this.container.children('ul'); for(var i = 0; i < choices.length; i++) { this._createItemNode(choices[i], this.rootList); } this.items = this.element.find('li.ui-multiselectlistbox-item'); this._bindEvents(); if(this.options.value !== undefined || this.options.value !== null) { this.preselect(this.options.value); } } }, _createItemNode: function(choice, parent) { var listItem = $('<li class="ui-multiselectlistbox-item"><span>'+ choice.label + '</span></li>'); listItem.appendTo(parent); if(choice.items) { listItem.append('<ul class="ui-helper-hidden"></ul>'); var sublistContainer = listItem.children('ul'); for(var i = 0; i < choice.items.length; i++) { this._createItemNode(choice.items[i], sublistContainer); } } else { listItem.attr('data-value', choice.value); } }, _unbindEvents: function() { this.items.off('mouseover.multiSelectListbox mouseout.multiSelectListbox click.multiSelectListbox'); }, _bindEvents: function() { var $this = this; this.items.on('mouseover.multiSelectListbox', function() { var item = $(this); if(!item.hasClass('ui-state-highlight')) $(this).addClass('ui-state-hover'); }) .on('mouseout.multiSelectListbox', function() { var item = $(this); if(!item.hasClass('ui-state-highlight')) $(this).removeClass('ui-state-hover'); }) .on('click.multiSelectListbox', function() { var item = $(this); if(!item.hasClass('ui-state-highlight')) { $this.showOptionGroup(item); } }); }, showOptionGroup: function(item) { item.addClass('ui-state-highlight').removeClass('ui-state-hover').siblings().filter('.ui-state-highlight').removeClass('ui-state-highlight'); item.closest('.ui-multiselectlistbox-listcontainer').nextAll().remove(); var childItemsContainer = item.children('ul'), itemValue = item.attr('data-value'); if(itemValue) { this.input.val(itemValue); } if(childItemsContainer.length) { var groupContainer = $('<div class="ui-multiselectlistbox-listcontainer" style="display:none"></div>'); childItemsContainer.clone(true).appendTo(groupContainer).addClass('ui-multiselectlistbox-list ui-inputfield ui-widget-content').removeClass('ui-helper-hidden'); groupContainer.prepend('<div class="ui-multiselectlistbox-header ui-widget-header ui-corner-top">' + item.children('span').text() + '</div>') .children('.ui-multiselectlistbox-list').addClass('ui-corner-bottom'); this.element.append(groupContainer); if (this.options.effect) groupContainer.show(this.options.effect); else groupContainer.show(); } }, disable: function() { if(!this.options.disabled) { this.options.disabled = true; this.element.addClass('ui-state-disabled'); this._unbindEvents(); this.container.nextAll().remove(); } }, getValue: function() { return this.input.val(); }, preselect: function(value) { var $this = this, item = this.items.filter('[data-value="' + value + '"]'); if(item.length === 0) { return; } var ancestors = item.parentsUntil('.ui-multiselectlistbox-list'), selectedIndexMap = []; for(var i = (ancestors.length - 1); i >= 0; i--) { var ancestor = ancestors.eq(i); if(ancestor.is('li')) { selectedIndexMap.push(ancestor.index()); } else if(ancestor.is('ul')) { var groupContainer = $('<div class="ui-multiselectlistbox-listcontainer" style="display:none"></div>'); ancestor.clone(true).appendTo(groupContainer).addClass('ui-multiselectlistbox-list ui-widget-content ui-corner-all').removeClass('ui-helper-hidden'); groupContainer.prepend('<div class="ui-multiselectlistbox-header ui-widget-header ui-corner-top">' + ancestor.prev('span').text() + '</div>') .children('.ui-multiselectlistbox-list').addClass('ui-corner-bottom').removeClass('ui-corner-all'); $this.element.append(groupContainer); } } //highlight item var lists = this.element.children('div.ui-multiselectlistbox-listcontainer'), clonedItem = lists.find(' > ul.ui-multiselectlistbox-list > li.ui-multiselectlistbox-item').filter('[data-value="' + value + '"]'); clonedItem.addClass('ui-state-highlight'); //highlight ancestors for(var i = 0; i < selectedIndexMap.length; i++) { lists.eq(i).find('> .ui-multiselectlistbox-list > li.ui-multiselectlistbox-item').eq(selectedIndexMap[i]).addClass('ui-state-highlight'); } $this.element.children('div.ui-multiselectlistbox-listcontainer:hidden').show(); } }); })(); /** * PrimeFaces Notify Widget */ (function() { $.widget("primeui.puinotify", { options: { position: 'top', visible: false, animate: true, effectSpeed: 'normal', easing: 'swing' }, _create: function() { this.element.addClass('ui-notify ui-notify-' + this.options.position + ' ui-widget ui-widget-content ui-shadow') .wrapInner('<div class="ui-notify-content" />').appendTo(document.body); this.content = this.element.children('.ui-notify-content'); this.closeIcon = $('<span class="ui-notify-close fa fa-close"></span>').appendTo(this.element); this._bindEvents(); if(this.options.visible) { this.show(); } }, _bindEvents: function() { var $this = this; this.closeIcon.on('click.puinotify', function() { $this.hide(); }); }, show: function(content) { var $this = this; if(content) { this.update(content); } this.element.css('z-index',++PUI.zindex); this._trigger('beforeShow'); if(this.options.animate) { this.element.slideDown(this.options.effectSpeed, this.options.easing, function() { $this._trigger('afterShow'); }); } else { this.element.show(); $this._trigger('afterShow'); } }, hide: function() { var $this = this; this._trigger('beforeHide'); if(this.options.animate) { this.element.slideUp(this.options.effectSpeed, this.options.easing, function() { $this._trigger('afterHide'); }); } else { this.element.hide(); $this._trigger('afterHide'); } }, update: function(content) { this.content.html(content); } }); })(); /** * PrimeUI picklist widget */ (function() { $.widget("primeui.puiorderlist", { options: { controlsLocation: 'none', dragdrop: true, effect: 'fade', caption: null, responsive: false, datasource: null, content: null, template: null }, _create: function() { this._createDom(); if(this.options.datasource) { if($.isArray(this.options.datasource)) { this._generateOptionElements(this.options.datasource); } else if($.type(this.options.datasource) === 'function') { this.options.datasource.call(this, this._generateOptionElements); } } this.optionElements = this.element.children('option'); this._createListElement(); this._bindEvents(); }, _createDom: function() { this.element.addClass('ui-helper-hidden'); if(this.options.controlsLocation !== 'none') this.element.wrap('<div class="ui-grid-col-10"></div>'); else this.element.wrap('<div class="ui-grid-col-12"></div>'); this.element.parent().wrap('<div class="ui-orderlist ui-grid ui-widget"><div class="ui-grid-row"></div></div>') this.container = this.element.closest('.ui-orderlist'); if(this.options.controlsLocation !== 'none') { this.element.parent().before('<div class="ui-orderlist-controls ui-grid-col-2"></div>'); this._createButtons(); } if(this.options.responsive) { this.container.addClass('ui-grid-responsive'); } }, _generateOptionElements: function(data) { for(var i = 0; i < data.length; i++) { var choice = data[i]; if(choice.label) this.element.append('<option value="' + choice.value + '">' + choice.label + '</option>'); else this.element.append('<option value="' + choice + '">' + choice + '</option>'); } }, _createListElement: function() { this.list = $('<ul class="ui-widget-content ui-orderlist-list"></ul>').insertBefore(this.element); for(var i = 0; i < this.optionElements.length; i++) { var optionElement = this.optionElements.eq(i), itemContent = this._createItemContent(optionElement.get(0)), listItem = $('<li class="ui-orderlist-item ui-corner-all"></li>'); if($.type(itemContent) === 'string') listItem.html(itemContent); else listItem.append(itemContent); listItem.data('item-value', optionElement.attr('value')).appendTo(this.list); } this.items = this.list.children('.ui-orderlist-item'); if(this.options.caption) { this.list.addClass('ui-corner-bottom').before('<div class="ui-orderlist-caption ui-widget-header ui-corner-top">' + this.options.caption + '</div>') } else { this.list.addClass('ui-corner-all') } }, _createButtons: function() { var $this = this; this.buttonContainer = this.element.parent().prev(); this.moveUpButton = this._createButton('fa-angle-up', 'ui-orderlist-button-moveup', function(){$this._moveUp();}); this.moveTopButton = this._createButton('fa-angle-double-up', 'ui-orderlist-button-move-top', function(){$this._moveTop();}); this.moveDownButton = this._createButton('fa-angle-down', 'ui-orderlist-button-move-down', function(){$this._moveDown();}); this.moveBottomButton = this._createButton('fa-angle-double-down', 'ui-orderlist-move-bottom', function(){$this._moveBottom();}); this.buttonContainer.append(this.moveUpButton).append(this.moveTopButton).append(this.moveDownButton).append(this.moveBottomButton); }, _createButton: function(icon, cssClass, fn) { var btn = $('<button class="' + cssClass + '" type="button"></button>').puibutton({ 'icon': icon, 'click': function() { fn(); $(this).removeClass('ui-state-hover ui-state-focus'); } }); return btn; }, _bindEvents: function() { this._bindButtonEvents(); this._bindItemEvents(this.items); if(this.options.dragdrop) { this._initDragDrop(); } }, _initDragDrop: function() { var $this = this; this.list.sortable({ revert: 1, start: function(event, ui) { PUI.clearSelection(); } ,update: function(event, ui) { $this.onDragDrop(event, ui); } }); }, _moveUp: function() { var $this = this, selectedItems = this.items.filter('.ui-state-highlight'), itemsToMoveCount = selectedItems.length, movedItemsCount = 0; selectedItems.each(function() { var item = $(this); if(!item.is(':first-child')) { item.hide($this.options.effect, {}, 'fast', function() { item.insertBefore(item.prev()).show($this.options.effect, {}, 'fast', function() { movedItemsCount++; if(itemsToMoveCount === movedItemsCount) { $this._saveState(); $this._fireReorderEvent(); } }); }); } else { itemsToMoveCount--; } }); }, _moveTop: function() { var $this = this, selectedItems = this.items.filter('.ui-state-highlight'), itemsToMoveCount = selectedItems.length, movedItemsCount = 0; selectedItems.each(function() { var item = $(this); if(!item.is(':first-child')) { item.hide($this.options.effect, {}, 'fast', function() { item.prependTo(item.parent()).show($this.options.effect, {}, 'fast', function(){ movedItemsCount++; if(itemsToMoveCount === movedItemsCount) { $this._saveState(); $this._fireReorderEvent(); } }); }); } else { itemsToMoveCount--; } }); }, _moveDown: function() { var $this = this, selectedItems = $(this.items.filter('.ui-state-highlight').get().reverse()), itemsToMoveCount = selectedItems.length, movedItemsCount = 0; selectedItems.each(function() { var item = $(this); if(!item.is(':last-child')) { item.hide($this.options.effect, {}, 'fast', function() { item.insertAfter(item.next()).show($this.options.effect, {}, 'fast', function() { movedItemsCount++; if(itemsToMoveCount === movedItemsCount) { $this._saveState(); $this._fireReorderEvent(); } }); }); } else { itemsToMoveCount--; } }); }, _moveBottom: function() { var $this = this, selectedItems = this.items.filter('.ui-state-highlight'), itemsToMoveCount = selectedItems.length, movedItemsCount = 0; selectedItems.each(function() { var item = $(this); if(!item.is(':last-child')) { item.hide($this.options.effect, {}, 'fast', function() { item.appendTo(item.parent()).show($this.options.effect, {}, 'fast', function() { movedItemsCount++; if(itemsToMoveCount === movedItemsCount) { $this._saveState(); $this._fireReorderEvent(); } }); }); } else { itemsToMoveCount--; } }); }, _saveState: function() { this.element.children().remove(); this._generateOptions(); }, _fireReorderEvent: function() { this._trigger('reorder', null); }, onDragDrop: function(event, ui) { ui.item.removeClass('ui-state-highlight'); this._saveState(); this._fireReorderEvent(); }, _generateOptions: function() { var $this = this; this.list.children('.ui-orderlist-item').each(function() { var item = $(this), itemValue = item.data('item-value'); $this.element.append('<option value="' + itemValue + '" selected="selected">' + itemValue + '</option>'); }); }, _createItemContent: function(choice) { if(this.options.template) { var template = this.options.template.html(); Mustache.parse(template); return Mustache.render(template, choice); } else if(this.options.content) { return this.options.content.call(this, choice); } else { return choice.label; } }, addOption: function(value,label) { var newListItem; if(this.options.content) { var option = (label) ? {'label':label,'value':value}: {'label':value,'value':value}; newListItem = $('<li class="ui-orderlist-item ui-corner-all"></li>').append(this.options.content(option)).appendTo(this.list); } else { var listLabel = (label) ? label: value; newListItem = $('<li class="ui-orderlist-item ui-corner-all">' + listLabel + '</li>').appendTo(this.list); } if(label) this.element.append('<option value="' + value + '">' + label + '</option>'); else this.element.append('<option value="' + value + '">' + value + '</option>'); this._bindItemEvents(newListItem); this.optionElements = this.element.children('option'); this.items = this.items.add(newListItem); if(this.options.dragdrop) { this.list.sortable('refresh'); } }, removeOption: function(value) { for (var i = 0; i < this.optionElements.length; i++) { if(this.optionElements[i].value == value) { this.optionElements[i].remove(i); this._unbindItemEvents(this.items.eq(i)); this.items[i].remove(i); } } this.optionElements = this.element.children('option'); this.items = this.list.children('.ui-orderlist-item'); if(this.options.dragdrop) { this.list.sortable('refresh'); } }, _unbindEvents: function() { this._unbindItemEvents(this.items); this._unbindButtonEvents(); }, _unbindItemEvents: function(item) { item.off('mouseover.puiorderlist mouseout.puiorderlist mousedown.puiorderlist'); }, _bindItemEvents: function(item) { var $this = this; item.on('mouseover.puiorderlist', function(e) { var element = $(this); if(!element.hasClass('ui-state-highlight')) $(this).addClass('ui-state-hover'); }) .on('mouseout.puiorderlist', function(e) { var element = $(this); if(!element.hasClass('ui-state-highlight')) $(this).removeClass('ui-state-hover'); }) .on('mousedown.puiorderlist', function(e) { var element = $(this), metaKey = (e.metaKey||e.ctrlKey); if(!metaKey) { element.removeClass('ui-state-hover').addClass('ui-state-highlight') .siblings('.ui-state-highlight').removeClass('ui-state-highlight'); //$this.fireItemSelectEvent(element, e); } else { if(element.hasClass('ui-state-highlight')) { element.removeClass('ui-state-highlight'); //$this.fireItemUnselectEvent(element); } else { element.removeClass('ui-state-hover').addClass('ui-state-highlight'); //$this.fireItemSelectEvent(element, e); } } }); }, getSelection: function() { var selectedItems = []; this.items.filter('.ui-state-highlight').each(function() { selectedItems.push($(this).data('item-value')); }); return selectedItems; }, setSelection: function(value) { for (var i = 0; i < this.items.length; i++) { for (var j = 0; j < value.length; j++) { if(this.items.eq(i).data('item-value') == value[j]) { this.items.eq(i).addClass('ui-state-highlight'); } } } }, disable: function() { this._unbindEvents(); this.items.addClass('ui-state-disabled'); this.container.addClass('ui-state-disabled'); if(this.options.dragdrop) { this.list.sortable('destroy'); } }, enable: function() { this._bindEvents(); this.items.removeClass('ui-state-disabled'); this.container.removeClass('ui-state-disabled'); if(this.options.dragdrop) { this._initDragDrop(); } }, _unbindButtonEvents: function() { if(this.buttonContainer) { this.moveUpButton.puibutton('disable'); this.moveTopButton.puibutton('disable'); this.moveDownButton.puibutton('disable'); this.moveBottomButton.puibutton('disable'); } }, _bindButtonEvents: function() { if(this.buttonContainer) { this.moveUpButton.puibutton('enable'); this.moveTopButton.puibutton('enable'); this.moveDownButton.puibutton('enable'); this.moveBottomButton.puibutton('enable'); } } }); })(); /** * PrimeFaces OverlayPanel Widget */ (function() { $.widget("primeui.puioverlaypanel", { options: { target: null, showEvent: 'click', hideEvent: 'click', showCloseIcon: false, dismissable: true, my: 'left top', at: 'left bottom', preShow: null, postShow: null, onHide: null, shared: false, delegatedTarget: null }, _create: function() { this.element.addClass('ui-overlaypanel ui-widget ui-widget-content ui-corner-all ui-shadow ui-helper-hidden'); this.container = $('<div class="ui-overlaypanel-content"></div>').appendTo(this.element); this.container.append(this.element.contents()); if(this.options.showCloseIcon) { this.closerIcon = $('<a href="#" class="ui-overlaypanel-close ui-state-default" href="#"><span class="fa fa-fw fa-close"></span></a>').appendTo(this.container); } this._bindCommonEvents(); if(this.options.target) { this.target = $(this.options.target); this._bindTargetEvents(); } }, _bindCommonEvents: function() { var $this = this; if(this.options.showCloseIcon) { this.closerIcon.on('mouseover.puioverlaypanel', function() { $(this).addClass('ui-state-hover'); }) .on('mouseout.puioverlaypanel', function() { $(this).removeClass('ui-state-hover'); }) .on('click.puioverlaypanel', function(e) { if($this._isVisible() ) { $this.hide(); } else { $this.show(); } e.preventDefault(); }); } //hide overlay when mousedown is at outside of overlay if(this.options.dismissable) { var hideNS = 'mousedown.' + this.id; $(document.body).off(hideNS).on(hideNS, function (e) { if(!$this._isVisible()) { return; } //do nothing on target mousedown if($this.target) { var target = $(e.target); if($this.target.is(target)||$this.target.has(target).length > 0) { return; } } //hide overlay if mousedown is on outside var offset = $this.element.offset(); if(e.pageX < offset.left || e.pageX > offset.left + $this.element.outerWidth() || e.pageY < offset.top || e.pageY > offset.top + $this.element.outerHeight()) { $this.hide(); } }); } //Hide overlay on resize var resizeNS = 'resize.' + this.id; $(window).off(resizeNS).on(resizeNS, function() { if($this._isVisible()) { $this._align(); } }); }, _bindTargetEvents: function() { var $this = this; //show and hide events for target if(this.options.showEvent === this.options.hideEvent) { var event = this.options.showEvent; if(this.options.shared) { this.target.on(event, this.options.delegatedTarget, null, function(e) { $this._toggle(e.currentTarget); }); } else { this.target.on(event, function(e) { $this._toggle(); }); } } else { var showEvent = this.options.showEvent + '.puioverlaypanel', hideEvent = this.options.hideEvent + '.puioverlaypanel'; if(this.options.shared) { this.target.off(showEvent + '.puioverlaypanel' + ' ' + hideEvent + '.puioverlaypanel', this.options.delegatedTarget).on(showEvent, this.options.delegatedTarget, null, function(e) { $this._onShowEvent(e); }) .on(hideEvent, this.options.delegatedTarget, null, function(e) { $this._onHideEvent(); }); } else { this.target.off(showEvent + '.puioverlaypanel' + ' ' + hideEvent + '.puioverlaypanel').on(showEvent, function(e) { $this._onShowEvent(e); }) .on(hideEvent, function(e) { $this._onHideEvent(); }); } } if(this.options.shared) { $this.target.off('keydown.puioverlaypanel keyup.puioverlaypanel', this.options.delegatedTarget).on('keydown.puioverlaypanel', this.options.delegatedTarget, null, function(e) { $this._onTargetKeydown(e); }) .on('keyup.puioverlaypanel', this.options.delegatedTarget, null, function(e) { $this._onTargetKeyup(e); }); } else { $this.target.off('keydown.puioverlaypanel keyup.puioverlaypanel').on('keydown.puioverlaypanel', function(e) { $this._onTargetKeydown(e); }) .on('keyup.puioverlaypanel', function(e) { $this._onTargetKeyup(e); }); } }, _toggle: function(target) { if(this.options.shared) { this.show(target); } else { if(this._isVisible()) this.hide(); else this.show(target); } }, _onShowEvent: function(e) { if(!this._isVisible()) { this.show(e.currentTarget); if(this.options.showEvent === 'contextmenu.puioverlaypanel') { e.preventDefault(); } } }, _onHideEvent: function() { if(this._isVisible()) { this.hide(); } }, _onTargetKeydown: function(e) { var keyCode = $.ui.keyCode, key = e.which; if(key === keyCode.ENTER||key === keyCode.NUMPAD_ENTER) { e.preventDefault(); } }, _onTargetKeyup: function(e) { var keyCode = $.ui.keyCode, key = e.which; if(key === keyCode.ENTER||key === keyCode.NUMPAD_ENTER) { $this._toggle(); e.preventDefault(); } }, _isVisible: function() { return this.element.css('visibility') == 'visible' && this.element.is(':visible'); }, show: function(target) { var $this = this; $this._trigger('preShow', null, {'target':target}); this._align(target); //replace visibility hidden with display none for effect support, toggle marker class this.element.css({ 'display':'none', 'visibility':'visible' }); if(this.options.showEffect) { this.element.show(this.options.showEffect, {}, 200, function() { $this.postShow(); }); } else { this.element.show(); this.postShow(); } }, hide: function() { var $this = this; if(this.options.hideEffect) { this.element.hide(this.options.hideEffect, {}, 200, function() { $this.postHide(); }); } else { this.element.hide(); this.postHide(); } }, postShow: function() { this._trigger('postShow'); this._applyFocus(); }, postHide: function() { //replace display block with visibility hidden for hidden container support, toggle marker class this.element.css({ 'display':'block', 'visibility':'hidden' }); this._trigger('onHide'); }, _align: function(target) { var win = $(window), ofTarget = target||this.target; this.element.css({'left':'', 'top':'', 'z-index': PUI.zindex}) .position({ my: this.options.my, at: this.options.at, of: ofTarget }); }, _applyFocus: function() { this.element.find(':not(:submit):not(:button):input:visible:enabled:first').focus(); } }); })(); /** * PrimeUI Paginator Widget */ (function() { var ElementHandlers = { '{FirstPageLink}': { markup: '<span class="ui-paginator-first ui-paginator-element ui-state-default ui-corner-all"><span class="fa fa-step-backward"></span></span>', create: function(paginator) { var element = $(this.markup); if(paginator.options.page === 0) { element.addClass('ui-state-disabled'); } element.on('click.puipaginator', function() { if(!$(this).hasClass("ui-state-disabled")) { paginator.option('page', 0); } }); return element; }, update: function(element, state) { if(state.page === 0) { element.addClass('ui-state-disabled').removeClass('ui-state-hover ui-state-active'); } else { element.removeClass('ui-state-disabled'); } } }, '{PreviousPageLink}': { markup: '<span class="ui-paginator-prev ui-paginator-element ui-state-default ui-corner-all"><span class="fa fa-backward"></span></span>', create: function(paginator) { var element = $(this.markup); if(paginator.options.page === 0) { element.addClass('ui-state-disabled'); } element.on('click.puipaginator', function() { if(!$(this).hasClass("ui-state-disabled")) { paginator.option('page', paginator.options.page - 1); } }); return element; }, update: function(element, state) { if(state.page === 0) { element.addClass('ui-state-disabled').removeClass('ui-state-hover ui-state-active'); } else { element.removeClass('ui-state-disabled'); } } }, '{NextPageLink}': { markup: '<span class="ui-paginator-next ui-paginator-element ui-state-default ui-corner-all"><span class="fa fa-forward"></span></span>', create: function(paginator) { var element = $(this.markup); if(paginator.options.page === (paginator.getPageCount() - 1)) { element.addClass('ui-state-disabled').removeClass('ui-state-hover ui-state-active'); } element.on('click.puipaginator', function() { if(!$(this).hasClass("ui-state-disabled")) { paginator.option('page', paginator.options.page + 1); } }); return element; }, update: function(element, state) { if(state.page === (state.pageCount - 1)) { element.addClass('ui-state-disabled').removeClass('ui-state-hover ui-state-active'); } else { element.removeClass('ui-state-disabled'); } } }, '{LastPageLink}': { markup: '<span class="ui-paginator-last ui-paginator-element ui-state-default ui-corner-all"><span class="fa fa-step-forward"></span></span>', create: function(paginator) { var element = $(this.markup); if(paginator.options.page === (paginator.getPageCount() - 1)) { element.addClass('ui-state-disabled').removeClass('ui-state-hover ui-state-active'); } element.on('click.puipaginator', function() { if(!$(this).hasClass("ui-state-disabled")) { paginator.option('page', paginator.getPageCount() - 1); } }); return element; }, update: function(element, state) { if(state.page === (state.pageCount - 1)) { element.addClass('ui-state-disabled').removeClass('ui-state-hover ui-state-active'); } else { element.removeClass('ui-state-disabled'); } } }, '{PageLinks}': { markup: '<span class="ui-paginator-pages"></span>', create: function(paginator) { var element = $(this.markup), boundaries = this.calculateBoundaries({ page: paginator.options.page, pageLinks: paginator.options.pageLinks, pageCount: paginator.getPageCount() }), start = boundaries[0], end = boundaries[1]; for(var i = start; i <= end; i++) { var pageLinkNumber = (i + 1), pageLinkElement = $('<span class="ui-paginator-page ui-paginator-element ui-state-default ui-corner-all">' + pageLinkNumber + "</span>"); if(i === paginator.options.page) { pageLinkElement.addClass('ui-state-active'); } pageLinkElement.on('click.puipaginator', function(e){ var link = $(this); if(!link.hasClass('ui-state-disabled')&&!link.hasClass('ui-state-active')) { paginator.option('page', parseInt(link.text(), 10) - 1); } }); element.append(pageLinkElement); } return element; }, update: function(element, state, paginator) { var pageLinks = element.children(), boundaries = this.calculateBoundaries({ page: state.page, pageLinks: state.pageLinks, pageCount: state.pageCount }), start = boundaries[0], end = boundaries[1]; pageLinks.remove(); for(var i = start; i <= end; i++) { var pageLinkNumber = (i + 1), pageLinkElement = $('<span class="ui-paginator-page ui-paginator-element ui-state-default ui-corner-all">' + pageLinkNumber + "</span>"); if(i === state.page) { pageLinkElement.addClass('ui-state-active'); } pageLinkElement.on('click.puipaginator', function(e){ var link = $(this); if(!link.hasClass('ui-state-disabled')&&!link.hasClass('ui-state-active')) { paginator.option('page', parseInt(link.text(), 10) - 1); } }); paginator._bindHover(pageLinkElement); element.append(pageLinkElement); } }, calculateBoundaries: function(config) { var page = config.page, pageLinks = config.pageLinks, pageCount = config.pageCount, visiblePages = Math.min(pageLinks, pageCount); //calculate range, keep current in middle if necessary var start = Math.max(0, parseInt(Math.ceil(page - ((visiblePages) / 2)), 10)), end = Math.min(pageCount - 1, start + visiblePages - 1); //check when approaching to last page var delta = pageLinks - (end - start + 1); start = Math.max(0, start - delta); return [start, end]; } } }; $.widget("primeui.puipaginator", { options: { pageLinks: 5, totalRecords: 0, page: 0, rows: 0, template: '{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}' }, _create: function() { this.element.addClass('ui-paginator ui-widget-header'); this.paginatorElements = []; var elementKeys = this.options.template.split(/[ ]+/); for(var i = 0; i < elementKeys.length;i++) { var elementKey = elementKeys[i], handler = ElementHandlers[elementKey]; if(handler) { var paginatorElement = handler.create(this); this.paginatorElements[elementKey] = paginatorElement; this.element.append(paginatorElement); } } this._bindEvents(); }, _bindEvents: function() { this._bindHover(this.element.find('span.ui-paginator-element')); }, _bindHover: function(elements) { elements.on('mouseover.puipaginator', function() { var el = $(this); if(!el.hasClass('ui-state-active')&&!el.hasClass('ui-state-disabled')) { el.addClass('ui-state-hover'); } }) .on('mouseout.puipaginator', function() { var el = $(this); if(el.hasClass('ui-state-hover')) { el.removeClass('ui-state-hover'); } }); }, _setOption: function(key, value) { if(key === 'page') this.setPage(value); else if(key === 'totalRecords') this.setTotalRecords(value); else $.Widget.prototype._setOption.apply(this, arguments); }, setPage: function(p, silent) { var pc = this.getPageCount(); if(p >= 0 && p < pc) { var newState = { first: this.options.rows * p, rows: this.options.rows, page: p, pageCount: pc, pageLinks: this.options.pageLinks }; this.options.page = p; if(!silent) { this._trigger('paginate', null, newState); } this.updateUI(newState); } }, //state contains page and totalRecords setState: function(state) { this.options.totalRecords = state.totalRecords; this.setPage(state.page, true); }, updateUI: function(state) { for(var paginatorElementKey in this.paginatorElements) { ElementHandlers[paginatorElementKey].update(this.paginatorElements[paginatorElementKey], state, this); } }, getPageCount: function() { return Math.ceil(this.options.totalRecords / this.options.rows)||1; }, setTotalRecords: function(value) { this.options.totalRecords = value; this.setPage(0, true); } }); })(); /** * PrimeUI Panel Widget */ (function() { $.widget("primeui.puipanel", { options: { toggleable: false, toggleDuration: 'normal', toggleOrientation: 'vertical', collapsed: false, closable: false, closeDuration: 'normal', title: null, footer: null }, _create: function() { this.element.addClass('ui-panel ui-widget ui-widget-content ui-corner-all') .contents().wrapAll('<div class="ui-panel-content ui-widget-content" />'); if(this.element.attr('title')) { this.options.title = this.element.attr('title'); this.element.removeAttr('title'); } if(this.options.title) { this.element.prepend('<div class="ui-panel-titlebar ui-widget-header ui-helper-clearfix ui-corner-all"><span class="ui-panel-title"></span></div>'); } if(this.options.footer) { this.element.append('<div class="ui-panel-footer ui-widget-content"></div>'); } this.header = this.element.children('div.ui-panel-titlebar'); this.title = this.header.children('span.ui-panel-title'); this.content = this.element.children('div.ui-panel-content'); this.footer = this.element.children('div.ui-panel-footer'); var $this = this; if(this.options.title) { this._createFacetContent(this.title, this.options.title); } if(this.options.footer) { this._createFacetContent(this.footer, this.options.footer); } if(this.options.closable) { this.closer = $('<a class="ui-panel-titlebar-icon ui-panel-titlebar-closer ui-corner-all ui-state-default" href="#"><span class="fa fa-fw fa-close"></span></a>') .appendTo(this.header); this.closer.on('click.puipanel', function(e) { $this.close(); e.preventDefault(); }); } if(this.options.toggleable) { var icon = this.options.collapsed ? 'fa-plus' : 'fa-minus'; this.toggler = $('<a class="ui-panel-titlebar-icon ui-panel-titlebar-toggler ui-corner-all ui-state-default" href="#"><span class="fa fa-fw ' + icon + '"></span></a>') .appendTo(this.header); this.toggler.on('click.puipanel', function(e) { $this.toggle(); e.preventDefault(); }); if(this.options.collapsed) { this.content.hide(); } } this._bindEvents(); }, _bindEvents: function() { this.header.children('a.ui-panel-titlebar-icon').on('mouseenter.puipanel', function() { $(this).addClass('ui-state-hover'); }) .on('mouseleave.puipanel', function() { $(this).removeClass('ui-state-hover'); }); }, _unbindEvents: function() { this.header.children('a.ui-panel-titlebar-icon').off(); }, close: function() { var $this = this; this._trigger('beforeClose', null); this.element.fadeOut(this.options.closeDuration, function() { $this._trigger('afterClose', null); } ); }, toggle: function() { if(this.options.collapsed) { this.expand(); } else { this.collapse(); } }, expand: function() { this.toggler.children('.fa').removeClass('fa-plus').addClass('fa-minus'); if(this.options.toggleOrientation === 'vertical') { this._slideDown(); } else if(this.options.toggleOrientation === 'horizontal') { this._slideRight(); } }, collapse: function() { this.toggler.children('.fa').removeClass('fa-minus').addClass('fa-plus'); if(this.options.toggleOrientation === 'vertical') { this._slideUp(); } else if(this.options.toggleOrientation === 'horizontal') { this._slideLeft(); } }, _slideUp: function() { var $this = this; this._trigger('beforeCollapse'); this.content.slideUp(this.options.toggleDuration, 'easeInOutCirc', function() { $this._trigger('afterCollapse'); $this.options.collapsed = !$this.options.collapsed; }); }, _slideDown: function() { var $this = this; this._trigger('beforeExpand'); this.content.slideDown(this.options.toggleDuration, 'easeInOutCirc', function() { $this._trigger('afterExpand'); $this.options.collapsed = !$this.options.collapsed; }); }, _slideLeft: function() { var $this = this; this.originalWidth = this.element.width(); this.title.hide(); this.toggler.hide(); this.content.hide(); this.element.animate({ width: '42px' }, this.options.toggleSpeed, 'easeInOutCirc', function() { $this.toggler.show(); $this.element.addClass('ui-panel-collapsed-h'); $this.options.collapsed = !$this.options.collapsed; }); }, _slideRight: function() { var $this = this, expandWidth = this.originalWidth||'100%'; this.toggler.hide(); this.element.animate({ width: expandWidth }, this.options.toggleSpeed, 'easeInOutCirc', function() { $this.element.removeClass('ui-panel-collapsed-h'); $this.title.show(); $this.toggler.show(); $this.options.collapsed = !$this.options.collapsed; $this.content.css({ 'visibility': 'visible', 'display': 'block', 'height': 'auto' }); }); }, _destroy: function() { this._unbindEvents(); if(this.toggler) { this.toggler.children('.fa').removeClass('fa-minus fa-plus'); } }, _createFacetContent: function(anchor, option) { var facetValue; if($.type(option) === 'string') facetValue = option; else if($.type(option) === 'function') facetValue = option.call(); anchor.append(facetValue); } }); })(); /** * PrimeUI password widget */ (function() { $.widget("primeui.puipassword", { options: { promptLabel: 'Please enter a password', weakLabel: 'Weak', mediumLabel: 'Medium', strongLabel: 'Strong', inline: false }, _create: function() { this.id = this.element.attr('id'); if(!this.id) { this.id = this.element.uniqueId().attr('id'); } this.element.puiinputtext().addClass('ui-password'); if(!this.element.prop(':disabled')) { var panelMarkup = '<div class="ui-password-panel ui-widget ui-state-highlight ui-corner-all ui-helper-hidden">'; panelMarkup += '<div class="ui-password-meter" style="background-position:0pt 0pt">&nbsp;</div>'; panelMarkup += '<div class="ui-password-info">' + this.options.promptLabel + '</div>'; panelMarkup += '</div>'; this.panel = $(panelMarkup).insertAfter(this.element); this.meter = this.panel.children('div.ui-password-meter'); this.infoText = this.panel.children('div.ui-password-info'); if(this.options.inline) { this.panel.addClass('ui-password-panel-inline'); } else { this.panel.addClass('ui-password-panel-overlay').appendTo('body'); } this._bindEvents(); } }, _destroy: function() { this.element.puiinputtext('destroy').removeClass('ui-password'); this._unbindEvents(); this.panel.remove(); $(window).off('resize.' + this.id); }, _bindEvents: function() { var $this = this; this.element.on('focus.puipassword', function() { $this.show(); }) .on('blur.puipassword', function() { $this.hide(); }) .on('keyup.puipassword', function() { var value = $this.element.val(), label = null, meterPos = null; if(value.length === 0) { label = $this.options.promptLabel; meterPos = '0px 0px'; } else { var score = $this._testStrength($this.element.val()); if(score < 30) { label = $this.options.weakLabel; meterPos = '0px -10px'; } else if(score >= 30 && score < 80) { label = $this.options.mediumLabel; meterPos = '0px -20px'; } else if(score >= 80) { label = $this.options.strongLabel; meterPos = '0px -30px'; } } $this.meter.css('background-position', meterPos); $this.infoText.text(label); }); if(!this.options.inline) { var resizeNS = 'resize.' + this.id; $(window).off(resizeNS).on(resizeNS, function() { if($this.panel.is(':visible')) { $this.align(); } }); } }, _unbindEvents: function() { this.element.off('focus.puipassword blur.puipassword keyup.puipassword'); }, _testStrength: function(str) { var grade = 0, val = 0, $this = this; val = str.match('[0-9]'); grade += $this._normalize(val ? val.length : 1/4, 1) * 25; val = str.match('[a-zA-Z]'); grade += $this._normalize(val ? val.length : 1/2, 3) * 10; val = str.match('[!@#$%^&*?_~.,;=]'); grade += $this._normalize(val ? val.length : 1/6, 1) * 35; val = str.match('[A-Z]'); grade += $this._normalize(val ? val.length : 1/6, 1) * 30; grade *= str.length / 8; return grade > 100 ? 100 : grade; }, _normalize: function(x, y) { var diff = x - y; if(diff <= 0) { return x / y; } else { return 1 + 0.5 * (x / (x + y/4)); } }, align: function() { this.panel.css({ left:'', top:'', 'z-index': ++PUI.zindex }) .position({ my: 'left top', at: 'right top', of: this.element }); }, show: function() { if(!this.options.inline) { this.align(); this.panel.fadeIn(); } else { this.panel.slideDown(); } }, hide: function() { if(this.options.inline) { this.panel.slideUp(); } else { this.panel.fadeOut(); } }, disable: function () { this.element.puiinputtext('disable'); this._unbindEvents(); }, enable: function () { this.element.puiinputtext('enable'); this._bindEvents(); }, _setOption: function(key, value) { if(key === 'disabled') { if(value) this.disable(); else this.enable(); } else { $.Widget.prototype._setOption.apply(this, arguments); } } }); })(); /** * PrimeUI picklist widget */ (function() { $.widget("primeui.puipicklist", { options: { effect: 'fade', effectSpeed: 'fast', sourceCaption: null, targetCaption: null, filter: false, filterFunction: null, filterMatchMode: 'startsWith', dragdrop: true, sourceData: null, targetData: null, content: null, template: null, responsive: false }, _create: function() { this.element.uniqueId().addClass('ui-picklist ui-widget ui-helper-clearfix'); if(this.options.responsive) { this.element.addClass('ui-picklist-responsive'); } this.inputs = this.element.children('select'); this.items = $(); this.sourceInput = this.inputs.eq(0); this.targetInput = this.inputs.eq(1); if(this.options.sourceData) { this._populateInputFromData(this.sourceInput, this.options.sourceData); } if(this.options.targetData) { this._populateInputFromData(this.targetInput, this.options.targetData); } this.sourceList = this._createList(this.sourceInput, 'ui-picklist-source', this.options.sourceCaption); this._createButtons(); this.targetList = this._createList(this.targetInput, 'ui-picklist-target', this.options.targetCaption); if(this.options.showSourceControls) { this.element.prepend(this._createListControls(this.sourceList, 'ui-picklist-source-controls')); } if(this.options.showTargetControls) { this.element.append(this._createListControls(this.targetList, 'ui-picklist-target-controls')); } this._bindEvents(); }, _populateInputFromData: function(input, data) { for(var i = 0; i < data.length; i++) { var choice = data[i]; if(choice.label) input.append('<option value="' + choice.value + '">' + choice.label + '</option>'); else input.append('<option value="' + choice + '">' + choice + '</option>'); } }, _createList: function(input, cssClass, caption) { var listWrapper = $('<div class="ui-picklist-listwrapper ' + cssClass + '-wrapper"></div>'), listContainer = $('<ul class="ui-widget-content ui-picklist-list ' + cssClass + '"></ul>'); if(this.options.filter) { listWrapper.append('<div class="ui-picklist-filter-container"><input type="text" class="ui-picklist-filter" /><span class="fa fa-fw fa-search"></span></div>'); listWrapper.find('> .ui-picklist-filter-container > input').puiinputtext(); } if(caption) { listWrapper.append('<div class="ui-picklist-caption ui-widget-header ui-corner-tl ui-corner-tr">' + caption + '</div>'); listContainer.addClass('ui-corner-bottom'); } else { listContainer.addClass('ui-corner-all'); } this._populateContainerFromOptions(input, listContainer); listWrapper.append(listContainer); input.addClass('ui-helper-hidden').appendTo(listWrapper); listWrapper.appendTo(this.element); return listContainer; }, _populateContainerFromOptions: function(input, listContainer, data) { var choices = input.children('option'); for(var i = 0; i < choices.length; i++) { var choice = choices.eq(i), content = this._createItemContent(choice.get(0)), item = $('<li class="ui-picklist-item ui-corner-all"></li>').data({ 'item-label': choice.text(), 'item-value': choice.val() }); if($.type(content) === 'string') item.html(content); else item.append(content); this.items = this.items.add(item); listContainer.append(item); } }, _createButtons: function() { var $this = this, buttonContainer = $('<div class="ui-picklist-buttons"><div class="ui-picklist-buttons-cell"></div>'); buttonContainer.children('div').append(this._createButton('fa-angle-right', 'ui-picklist-button-add', function(){$this._add();})) .append(this._createButton('fa-angle-double-right', 'ui-picklist-button-addall', function(){$this._addAll();})) .append(this._createButton('fa-angle-left', 'ui-picklist-button-remove', function(){$this._remove();})) .append(this._createButton('fa-angle-double-left', 'ui-picklist-button-removeall', function(){$this._removeAll();})); this.element.append(buttonContainer); }, _createListControls: function(list, cssClass) { var $this = this, buttonContainer = $('<div class="' + cssClass + ' ui-picklist-buttons"><div class="ui-picklist-buttons-cell"></div>'); buttonContainer.children('div').append(this._createButton('fa-angle-up', 'ui-picklist-button-move-up', function(){$this._moveUp(list);})) .append(this._createButton('fa-angle-double-up', 'ui-picklist-button-move-top', function(){$this._moveTop(list);})) .append(this._createButton('fa-angle-down', 'ui-picklist-button-move-down', function(){$this._moveDown(list);})) .append(this._createButton('fa-angle-double-down', 'ui-picklist-button-move-bottom', function(){$this._moveBottom(list);})); return buttonContainer; }, _createButton: function(icon, cssClass, fn) { var btn = $('<button class="' + cssClass + '" type="button"></button>').puibutton({ 'icon': icon, 'click': function() { fn(); $(this).removeClass('ui-state-hover ui-state-focus'); } }); return btn; }, _bindEvents: function() { var $this = this; this.items.on('mouseover.puipicklist', function(e) { var element = $(this); if(!element.hasClass('ui-state-highlight')) { $(this).addClass('ui-state-hover'); } }) .on('mouseout.puipicklist', function(e) { $(this).removeClass('ui-state-hover'); }) .on('click.puipicklist', function(e) { var item = $(this), metaKey = (e.metaKey||e.ctrlKey); if(!e.shiftKey) { if(!metaKey) { $this.unselectAll(); } if(metaKey && item.hasClass('ui-state-highlight')) { $this.unselectItem(item); } else { $this.selectItem(item); $this.cursorItem = item; } } else { $this.unselectAll(); if($this.cursorItem && ($this.cursorItem.parent().is(item.parent()))) { var currentItemIndex = item.index(), cursorItemIndex = $this.cursorItem.index(), startIndex = (currentItemIndex > cursorItemIndex) ? cursorItemIndex : currentItemIndex, endIndex = (currentItemIndex > cursorItemIndex) ? (currentItemIndex + 1) : (cursorItemIndex + 1), parentList = item.parent(); for(var i = startIndex ; i < endIndex; i++) { $this.selectItem(parentList.children('li.ui-picklist-item').eq(i)); } } else { $this.selectItem(item); $this.cursorItem = item; } } }) .on('dblclick.pickList', function() { var item = $(this); if($(this).closest('.ui-picklist-listwrapper').hasClass('ui-picklist-source-wrapper')) $this._transfer(item, $this.sourceList, $this.targetList, 'dblclick'); else $this._transfer(item, $this.targetList, $this.sourceList, 'dblclick'); PUI.clearSelection(); }); if(this.options.filter) { this._setupFilterMatcher(); this.element.find('> .ui-picklist-source-wrapper > .ui-picklist-filter-container > input').on('keyup', function(e) { $this._filter(this.value, $this.sourceList); }); this.element.find('> .ui-picklist-target-wrapper > .ui-picklist-filter-container > input').on('keyup', function(e) { $this._filter(this.value, $this.targetList); }); } if(this.options.dragdrop) { this.element.find('> .ui-picklist-listwrapper > ul.ui-picklist-list').sortable({ cancel: '.ui-state-disabled', connectWith: '#' + this.element.attr('id') + ' .ui-picklist-list', revert: 1, update: function(event, ui) { $this.unselectItem(ui.item); $this._saveState(); }, receive: function(event, ui) { $this._triggerTransferEvent(ui.item, ui.sender, ui.item.closest('ul.ui-picklist-list'), 'dragdrop'); } }); } }, selectItem: function(item) { item.removeClass('ui-state-hover').addClass('ui-state-highlight'); }, unselectItem: function(item) { item.removeClass('ui-state-highlight'); }, unselectAll: function() { var selectedItems = this.items.filter('.ui-state-highlight'); for(var i = 0; i < selectedItems.length; i++) { this.unselectItem(selectedItems.eq(i)); } }, _add: function() { var items = this.sourceList.children('li.ui-picklist-item.ui-state-highlight'); this._transfer(items, this.sourceList, this.targetList, 'command'); }, _addAll: function() { var items = this.sourceList.children('li.ui-picklist-item:visible:not(.ui-state-disabled)'); this._transfer(items, this.sourceList, this.targetList, 'command'); }, _remove: function() { var items = this.targetList.children('li.ui-picklist-item.ui-state-highlight'); this._transfer(items, this.targetList, this.sourceList, 'command'); }, _removeAll: function() { var items = this.targetList.children('li.ui-picklist-item:visible:not(.ui-state-disabled)'); this._transfer(items, this.targetList, this.sourceList, 'command'); }, _moveUp: function(list) { var $this = this, animated = $this.options.effect, items = list.children('.ui-state-highlight'), itemsCount = items.length, movedCount = 0; items.each(function() { var item = $(this); if(!item.is(':first-child')) { if(animated) { item.hide($this.options.effect, {}, $this.options.effectSpeed, function() { item.insertBefore(item.prev()).show($this.options.effect, {}, $this.options.effectSpeed, function() { movedCount++; if(movedCount === itemsCount) { $this._saveState(); } }); }); } else { item.hide().insertBefore(item.prev()).show(); } } }); if(!animated) { this._saveState(); } }, _moveTop: function(list) { var $this = this, animated = $this.options.effect, items = list.children('.ui-state-highlight'), itemsCount = items.length, movedCount = 0; list.children('.ui-state-highlight').each(function() { var item = $(this); if(!item.is(':first-child')) { if(animated) { item.hide($this.options.effect, {}, $this.options.effectSpeed, function() { item.prependTo(item.parent()).show($this.options.effect, {}, $this.options.effectSpeed, function(){ movedCount++; if(movedCount === itemsCount) { $this._saveState(); } }); }); } else { item.hide().prependTo(item.parent()).show(); } } }); if(!animated) { this._saveState(); } }, _moveDown: function(list) { var $this = this, animated = $this.options.effect, items = list.children('.ui-state-highlight'), itemsCount = items.length, movedCount = 0; $(list.children('.ui-state-highlight').get().reverse()).each(function() { var item = $(this); if(!item.is(':last-child')) { if(animated) { item.hide($this.options.effect, {}, $this.options.effectSpeed, function() { item.insertAfter(item.next()).show($this.options.effect, {}, $this.options.effectSpeed, function() { movedCount++; if(movedCount === itemsCount) { $this._saveState(); } }); }); } else { item.hide().insertAfter(item.next()).show(); } } }); if(!animated) { this._saveState(); } }, _moveBottom: function(list) { var $this = this, animated = $this.options.effect, items = list.children('.ui-state-highlight'), itemsCount = items.length, movedCount = 0; list.children('.ui-state-highlight').each(function() { var item = $(this); if(!item.is(':last-child')) { if(animated) { item.hide($this.options.effect, {}, $this.options.effectSpeed, function() { item.appendTo(item.parent()).show($this.options.effect, {}, $this.options.effectSpeed, function() { movedCount++; if(movedCount === itemsCount) { $this._saveState(); } }); }); } else { item.hide().appendTo(item.parent()).show(); } } }); if(!animated) { this._saveState(); } }, _transfer: function(items, from, to, type) { var $this = this, itemsCount = items.length, transferCount = 0; if(this.options.effect) { items.hide(this.options.effect, {}, this.options.effectSpeed, function() { var item = $(this); $this.unselectItem(item); item.appendTo(to).show($this.options.effect, {}, $this.options.effectSpeed, function() { transferCount++; if(transferCount === itemsCount) { $this._saveState(); $this._triggerTransferEvent(items, from, to, type); } }); }); } else { items.hide().removeClass('ui-state-highlight ui-state-hover').appendTo(to).show(); this._saveState(); this._triggerTransferEvent(items, from, to, type); } }, _triggerTransferEvent: function(items, from, to, type) { var obj = {}; obj.items = items; obj.from = from; obj.to = to; obj.type = type; this._trigger('transfer', null, obj); }, _saveState: function() { this.sourceInput.children().remove(); this.targetInput.children().remove(); this._generateItems(this.sourceList, this.sourceInput); this._generateItems(this.targetList, this.targetInput); this.cursorItem = null; }, _generateItems: function(list, input) { list.children('.ui-picklist-item').each(function() { var item = $(this), itemValue = item.data('item-value'), itemLabel = item.data('item-label'); input.append('<option value="' + itemValue + '" selected="selected">' + itemLabel + '</option>'); }); }, _setupFilterMatcher: function() { this.filterMatchers = { 'startsWith': this._startsWithFilter, 'contains': this._containsFilter, 'endsWith': this._endsWithFilter, 'custom': this.options.filterFunction }; this.filterMatcher = this.filterMatchers[this.options.filterMatchMode]; }, _filter: function(value, list) { var filterValue = $.trim(value).toLowerCase(), items = list.children('li.ui-picklist-item'); if(filterValue === '') { items.filter(':hidden').show(); } else { for(var i = 0; i < items.length; i++) { var item = items.eq(i), itemLabel = item.data('item-label'); if(this.filterMatcher(itemLabel, filterValue)) item.show(); else item.hide(); } } }, _startsWithFilter: function(value, filter) { return value.toLowerCase().indexOf(filter) === 0; }, _containsFilter: function(value, filter) { return value.toLowerCase().indexOf(filter) !== -1; }, _endsWithFilter: function(value, filter) { return value.indexOf(filter, value.length - filter.length) !== -1; }, _setOption: function (key, value) { $.Widget.prototype._setOption.apply(this, arguments); if (key === 'sourceData') { this._setOptionData(this.sourceInput, this.sourceList, this.options.sourceData); } if (key === 'targetData') { this._setOptionData(this.targetInput, this.targetList, this.options.targetData); } }, _setOptionData: function(input, listContainer, data) { input.empty(); listContainer.empty(); this._populateInputFromData(input, data); this._populateContainerFromOptions(input, listContainer, data); this._bindEvents(); }, _unbindEvents: function() { this.items.off("mouseover.puipicklist mouseout.puipicklist click.puipicklist dblclick.pickList"); }, disable: function () { this._unbindEvents(); this.items.addClass('ui-state-disabled'); this.element.find('.ui-picklist-buttons > button').each(function (idx, btn) { $(btn).puibutton('disable'); }); }, enable: function () { this._bindEvents(); this.items.removeClass('ui-state-disabled'); this.element.find('.ui-picklist-buttons > button').each(function (idx, btn) { $(btn).puibutton('enable'); }); }, _createItemContent: function(choice) { if(this.options.template) { var template = this.options.template.html(); Mustache.parse(template); return Mustache.render(template, choice); } else if(this.options.content) { return this.options.content.call(this, choice); } else { return choice.label; } } }); })(); /** * PrimeUI progressbar widget */ (function() { $.widget("primeui.puiprogressbar", { options: { value: 0, labelTemplate: '{value}%', complete: null, easing: 'easeInOutCirc', effectSpeed: 'normal', showLabel: true }, _create: function() { this.element.addClass('ui-progressbar ui-widget ui-widget-content ui-corner-all') .append('<div class="ui-progressbar-value ui-widget-header ui-corner-all"></div>') .append('<div class="ui-progressbar-label"></div>'); this.jqValue = this.element.children('.ui-progressbar-value'); this.jqLabel = this.element.children('.ui-progressbar-label'); if(this.options.value !==0) { this._setValue(this.options.value, false); } this.enableARIA(); }, _setValue: function(value, animate) { var anim = (animate === undefined || animate) ? true : false; if(value >= 0 && value <= 100) { if(value === 0) { this.jqValue.hide().css('width', '0%').removeClass('ui-corner-right'); this.jqLabel.hide(); } else { if(anim) { this.jqValue.show().animate({ 'width': value + '%' }, this.options.effectSpeed, this.options.easing); } else { this.jqValue.show().css('width', value + '%'); } if(this.options.labelTemplate && this.options.showLabel) { var formattedLabel = this.options.labelTemplate.replace(/{value}/gi, value); this.jqLabel.html(formattedLabel).show(); } if(value === 100) { this._trigger('complete'); } } this.options.value = value; this.element.attr('aria-valuenow', value); } }, _getValue: function() { return this.options.value; }, enableARIA: function() { this.element.attr('role', 'progressbar') .attr('aria-valuemin', 0) .attr('aria-valuenow', this.options.value) .attr('aria-valuemax', 100); }, _setOption: function(key, value) { if(key === 'value') { this._setValue(value); } $.Widget.prototype._setOption.apply(this, arguments); }, _destroy: function() { } }); })(); /** * PrimeUI radiobutton widget */ (function() { var checkedRadios = {}; $.widget("primeui.puiradiobutton", { _create: function() { this.element.wrap('<div class="ui-radiobutton ui-widget"><div class="ui-helper-hidden-accessible"></div></div>'); this.container = this.element.parent().parent(); this.box = $('<div class="ui-radiobutton-box ui-widget ui-radiobutton-relative ui-state-default">').appendTo(this.container); this.icon = $('<span class="ui-radiobutton-icon"></span>').appendTo(this.box); this.disabled = this.element.prop('disabled'); this.label = $('label[for="' + this.element.attr('id') + '"]'); if(this.element.prop('checked')) { this.box.addClass('ui-state-active'); this.icon.addClass('fa fa-fw fa-circle'); checkedRadios[this.element.attr('name')] = this.box; } if(this.disabled) { this.box.addClass('ui-state-disabled'); } else { this._bindEvents(); } }, _bindEvents: function() { var $this = this; this.box.on('mouseover.puiradiobutton', function() { if(!$this._isChecked()) $this.box.addClass('ui-state-hover'); }).on('mouseout.puiradiobutton', function() { if(!$this._isChecked()) $this.box.removeClass('ui-state-hover'); }).on('click.puiradiobutton', function() { if(!$this._isChecked()) { $this.element.trigger('click'); if(PUI.browser.msie && parseInt(PUI.browser.version, 10) < 9) { $this.element.trigger('change'); } } }); if(this.label.length > 0) { this.label.on('click.puiradiobutton', function(e) { $this.element.trigger('click'); e.preventDefault(); }); } this.element.on('focus.puiradiobutton', function() { if($this._isChecked()) { $this.box.removeClass('ui-state-active'); } $this.box.addClass('ui-state-focus'); }) .on('blur.puiradiobutton', function() { if($this._isChecked()) { $this.box.addClass('ui-state-active'); } $this.box.removeClass('ui-state-focus'); }) .on('change.puiradiobutton', function(e) { var name = $this.element.attr('name'); if(checkedRadios[name]) { checkedRadios[name].removeClass('ui-state-active ui-state-focus ui-state-hover').children('.ui-radiobutton-icon').removeClass('fa fa-fw fa-circle'); } $this.icon.addClass('fa fa-fw fa-circle'); if(!$this.element.is(':focus')) { $this.box.addClass('ui-state-active'); } checkedRadios[name] = $this.box; $this._trigger('change', null); }); }, _isChecked: function() { return this.element.prop('checked'); }, _unbindEvents: function () { this.box.off('mouseover.puiradiobutton mouseout.puiradiobutton click.puiradiobutton'); this.element.off('focus.puiradiobutton blur.puiradiobutton change.puiradiobutton'); if (this.label.length) { this.label.off('click.puiradiobutton'); } }, enable: function () { this._bindEvents(); this.box.removeClass('ui-state-disabled'); }, disable: function () { this._unbindEvents(); this.box.addClass('ui-state-disabled'); }, _destroy: function () { this._unbindEvents(); this.container.removeClass('ui-radiobutton ui-widget'); this.box.remove(); this.element.unwrap().unwrap(); } }); })(); /** * PrimeUI rating widget */ (function() { $.widget("primeui.puirating", { options: { stars: 5, cancel: true, readonly: false, disabled: false, value: 0 }, _create: function() { var input = this.element; input.wrap('<div />'); this.container = input.parent(); this.container.addClass('ui-rating'); var inputVal = input.val(), value = inputVal === '' ? this.options.value : parseInt(inputVal, 10); if(this.options.cancel) { this.container.append('<div class="ui-rating-cancel"><a></a></div>'); } for(var i = 0; i < this.options.stars; i++) { var styleClass = (value > i) ? "ui-rating-star ui-rating-star-on" : "ui-rating-star"; this.container.append('<div class="' + styleClass + '"><a></a></div>'); } this.stars = this.container.children('.ui-rating-star'); if(input.prop('disabled')||this.options.disabled) { this.container.addClass('ui-state-disabled'); } else if(!input.prop('readonly')&&!this.options.readonly){ this._bindEvents(); } }, _bindEvents: function() { var $this = this; this.stars.click(function() { var value = $this.stars.index(this) + 1; //index starts from zero $this.setValue(value); }); this.container.children('.ui-rating-cancel').hover(function() { $(this).toggleClass('ui-rating-cancel-hover'); }) .click(function() { $this.cancel(); }); }, cancel: function() { this.element.val(''); this.stars.filter('.ui-rating-star-on').removeClass('ui-rating-star-on'); this._trigger('oncancel', null); }, getValue: function() { var inputVal = this.element.val(); return inputVal === '' ? null : parseInt(inputVal, 10); }, setValue: function(value) { this.element.val(value); //update visuals this.stars.removeClass('ui-rating-star-on'); for(var i = 0; i < value; i++) { this.stars.eq(i).addClass('ui-rating-star-on'); } this._trigger('rate', null, value); }, enable: function() { this.container.removeClass('ui-state-disabled'); this._bindEvents(); }, disable: function() { this.container.addClass('ui-state-disabled'); this._unbindEvents(); }, _unbindEvents: function() { this.stars.off(); this.container.children('.ui-rating-cancel').off(); }, _updateValue: function(value) { var stars = this.container.children('div.ui-rating-star'); stars.removeClass('ui-rating-star-on'); for(var i = 0; i < stars.length; i++) { if(i < value) { stars.eq(i).addClass('ui-rating-star-on'); } } this.element.val(value); }, _setOption: function(key, value) { if(key === 'value') { this.options.value = value; this._updateValue(value); } else { $.Widget.prototype._setOption.apply(this, arguments); } }, _destroy: function() { this._unbindEvents(); this.stars.remove(); this.container.children('.ui-rating-cancel').remove(); this.element.unwrap(); } }); })(); /** * PrimeUI SelectButton Widget */ (function() { $.widget("primeui.puiselectbutton", { options: { value: null, choices: null, formfield: null, tabindex: '0', multiple: false, enhanced: false }, _create: function() { if(!this.options.enhanced) { this.element.addClass('ui-selectbutton ui-buttonset ui-widget ui-corner-all').attr('tabindex'); if(this.options.choices) { this.element.addClass('ui-buttonset-' + this.options.choices.length); for(var i = 0; i < this.options.choices.length; i++) { this.element.append('<div class="ui-button ui-widget ui-state-default ui-button-text-only" tabindex="' + this.options.tabindex + '" data-value="' + this.options.choices[i].value + '">' + '<span class="ui-button-text ui-c">' + this.options.choices[i].label + '</span></div>'); } } } else { var $this = this; this.options.choices = []; this.element.children('.ui-button').each(function() { var btn = $(this), value = btn.attr('data-value'), label = btn.children('span').text(); $this.options.choices.push({'label': label, 'value': value}); }); } //cornering this.buttons = this.element.children('div.ui-button'); this.buttons.filter(':first-child').addClass('ui-corner-left'); this.buttons.filter(':last-child').addClass('ui-corner-right'); if(!this.options.multiple) { this.input = $('<input type="hidden" />').appendTo(this.element); } else { this.input = $('<select class="ui-helper-hidden-accessible" multiple></select>').appendTo(this.element); for (var i = 0; i < this.options.choices.length; i++) { var selectOption = '<option value = "'+ this.options.choices[i].value +'"></option>'; this.input.append(selectOption); } this.selectOptions = this.input.children('option'); } if(this.options.formfield) { this.input.attr('name', this.options.formfield); } //preselection if(this.options.value !== null && this.options.value !== undefined) { this._updateSelection(this.options.value); } this._bindEvents(); }, _destroy: function() { this._unbindEvents(); if(!this.options.enhanced) { this.buttons.remove(); this.element.removeClass('ui-selectbutton ui-buttonset ui-widget ui-corner-all').removeAttr('tabindex'); } else { this.buttons.removeClass('ui-state-focus ui-state-hover ui-state-active ui-corner-left ui-corner-right'); } this.input.remove(); }, _triggerChangeEvent: function(event) { var $this = this; if(this.options.multiple) { var values = [], indexes = []; for(var i = 0; i < $this.buttons.length; i++) { var btn = $this.buttons.eq(i); if(btn.hasClass('ui-state-active')) { values.push(btn.data('value')); indexes.push(i); } } $this._trigger('change', event, { value: values, index: indexes }); } else { for(var i = 0; i < $this.buttons.length; i++) { var btn = $this.buttons.eq(i); if(btn.hasClass('ui-state-active')) { $this._trigger('change', event, { value: btn.data('value'), index: i }); break; } } } }, _bindEvents: function() { var $this = this; this.buttons.on('mouseover.puiselectbutton', function() { var btn = $(this); if(!btn.hasClass('ui-state-active')) { btn.addClass('ui-state-hover'); } }) .on('mouseout.puiselectbutton', function() { $(this).removeClass('ui-state-hover'); }) .on('click.puiselectbutton', function(e) { var btn = $(this); if($(this).hasClass("ui-state-active")) { $this.unselectOption(btn); } else { if($this.options.multiple) { $this.selectOption(btn); } else { $this.unselectOption(btn.siblings('.ui-state-active')); $this.selectOption(btn); } } $this._triggerChangeEvent(e); }) .on('focus.puiselectbutton', function() { $(this).addClass('ui-state-focus'); }) .on('blur.puiselectbutton', function() { $(this).removeClass('ui-state-focus'); }) .on('keydown.puiselectbutton', function(e) { var keyCode = $.ui.keyCode; if(e.which === keyCode.SPACE||e.which === keyCode.ENTER||e.which === keyCode.NUMPAD_ENTER) { $(this).trigger('click'); e.preventDefault(); } }); }, _unbindEvents: function() { this.buttons.off('mouseover.puiselectbutton mouseout.puiselectbutton focus.puiselectbutton blur.puiselectbutton keydown.puiselectbutton click.puiselectbutton'); }, selectOption: function(value) { var btn = $.isNumeric(value) ? this.element.children('.ui-button').eq(value) : value; if(this.options.multiple) { this.selectOptions.eq(btn.index()).prop('selected',true); } else this.input.val(btn.data('value')); btn.addClass('ui-state-active'); }, unselectOption: function(value){ var btn = $.isNumeric(value) ? this.element.children('.ui-button').eq(value) : value; if(this.options.multiple) this.selectOptions.eq(btn.index()).prop('selected',false); else this.input.val(''); btn.removeClass('ui-state-active'); btn.removeClass('ui-state-focus'); }, _setOption: function (key, value) { if (key === 'data') { this.element.empty(); this._bindEvents(); } else if (key === 'value') { this._updateSelection(value); } else { $.Widget.prototype._setOption.apply(this, arguments); } }, _updateSelection: function(value) { this.buttons.removeClass('ui-state-active'); for(var i = 0; i < this.buttons.length; i++) { var button = this.buttons.eq(i), buttonValue = button.attr('data-value'); if(this.options.multiple) { if($.inArray(buttonValue, value) >= 0) { button.addClass('ui-state-active'); } } else { if(buttonValue == value) { button.addClass('ui-state-active'); break; } } } } }); })(); /** * PrimeUI spinner widget */ (function() { $.widget("primeui.puispinner", { options: { step: 1.0, min: undefined, max: undefined, prefix: null, suffix: null }, _create: function() { var input = this.element, disabled = input.prop('disabled'); input.puiinputtext().addClass('ui-spinner-input').wrap('<span class="ui-spinner ui-widget ui-corner-all" />'); this.wrapper = input.parent(); this.wrapper.append('<a class="ui-spinner-button ui-spinner-up ui-corner-tr ui-button ui-widget ui-state-default ui-button-text-only"><span class="ui-button-text"><span class="fa fa-fw fa-caret-up"></span></span></a><a class="ui-spinner-button ui-spinner-down ui-corner-br ui-button ui-widget ui-state-default ui-button-text-only"><span class="ui-button-text"><span class="fa fa-fw fa-caret-down"></span></span></a>'); this.upButton = this.wrapper.children('a.ui-spinner-up'); this.downButton = this.wrapper.children('a.ui-spinner-down'); this.options.step = this.options.step||1; if(parseInt(this.options.step, 10) === 0) { this.options.precision = this.options.step.toString().split(/[,]|[.]/)[1].length; } this._initValue(); if(!disabled&&!input.prop('readonly')) { this._bindEvents(); } if(disabled) { this.wrapper.addClass('ui-state-disabled'); } if(this.options.min !== undefined) { input.attr('aria-valuemin', this.options.min); } if(this.options.max !== undefined){ input.attr('aria-valuemax', this.options.max); } }, _destroy: function() { this.element.puiinputtext('destroy').removeClass('ui-spinner-input').off('keydown.puispinner keyup.puispinner blur.puispinner focus.puispinner mousewheel.puispinner'); this.wrapper.children('.ui-spinner-button').off().remove(); this.element.unwrap(); }, _bindEvents: function() { var $this = this; //visuals for spinner buttons this.wrapper.children('.ui-spinner-button') .mouseover(function() { $(this).addClass('ui-state-hover'); }).mouseout(function() { $(this).removeClass('ui-state-hover ui-state-active'); if($this.timer) { window.clearInterval($this.timer); } }).mouseup(function() { window.clearInterval($this.timer); $(this).removeClass('ui-state-active').addClass('ui-state-hover'); }).mousedown(function(e) { var element = $(this), dir = element.hasClass('ui-spinner-up') ? 1 : -1; element.removeClass('ui-state-hover').addClass('ui-state-active'); if($this.element.is(':not(:focus)')) { $this.element.focus(); } $this._repeat(null, dir); //keep focused e.preventDefault(); }); this.element.on('keydown.puispinner', function (e) { var keyCode = $.ui.keyCode; switch(e.which) { case keyCode.UP: $this._spin($this.options.step); break; case keyCode.DOWN: $this._spin(-1 * $this.options.step); break; default: //do nothing break; } }) .on('keyup.puispinner', function () { $this._updateValue(); }) .on('blur.puispinner', function () { $this._format(); }) .on('focus.puispinner', function () { //remove formatting $this.element.val($this.value); }); //mousewheel this.element.on('mousewheel.puispinner', function(event, delta) { if($this.element.is(':focus')) { if(delta > 0) { $this._spin($this.options.step); } else { $this._spin(-1 * $this.options.step); } return false; } }); }, _repeat: function(interval, dir) { var $this = this, i = interval || 500; window.clearTimeout(this.timer); this.timer = window.setTimeout(function() { $this._repeat(40, dir); }, i); this._spin(this.options.step * dir); }, _toFixed: function (value, precision) { var power = Math.pow(10, precision||0); return String(Math.round(value * power) / power); }, _spin: function(step) { var newValue, currentValue = this.value ? this.value : 0; if(this.options.precision) { newValue = parseFloat(this._toFixed(currentValue + step, this.options.precision)); } else { newValue = parseInt(currentValue + step, 10); } if(this.options.min !== undefined && newValue < this.options.min) { newValue = this.options.min; } if(this.options.max !== undefined && newValue > this.options.max) { newValue = this.options.max; } this.element.val(newValue).attr('aria-valuenow', newValue); this.value = newValue; this.element.trigger('change'); }, _updateValue: function() { var value = this.element.val(); if(value === '') { if(this.options.min !== undefined) { this.value = this.options.min; } else { this.value = 0; } } else { if(this.options.step) { value = parseFloat(value); } else { value = parseInt(value, 10); } if(!isNaN(value)) { this.value = value; } } }, _initValue: function() { var value = this.element.val(); if(value === '') { if(this.options.min !== undefined) { this.value = this.options.min; } else { this.value = 0; } } else { if(this.options.prefix) { value = value.split(this.options.prefix)[1]; } if(this.options.suffix) { value = value.split(this.options.suffix)[0]; } if(this.options.step) { this.value = parseFloat(value); } else { this.value = parseInt(value, 10); } } }, _format: function() { var value = this.value; if(this.options.prefix) { value = this.options.prefix + value; } if(this.options.suffix) { value = value + this.options.suffix; } this.element.val(value); }, _unbindEvents: function() { //visuals for spinner buttons this.wrapper.children('.ui-spinner-button').off(); this.element.off(); }, enable: function() { this.wrapper.removeClass('ui-state-disabled'); this.element.puiinputtext('enable'); this._bindEvents(); }, disable: function() { this.wrapper.addClass('ui-state-disabled'); this.element.puiinputtext('disable'); this._unbindEvents(); }, _setOption: function(key, value) { if(key === 'disabled') { if(value) this.disable(); else this.enable(); } else { $.Widget.prototype._setOption.apply(this, arguments); } } }); })(); /** * PrimeFaces SplitButton Widget */ (function() { $.widget("primeui.puisplitbutton", { options: { icon: null, iconPos: 'left', items: null }, _create: function() { this.element.wrap('<div class="ui-splitbutton ui-buttonset ui-widget"></div>'); this.container = this.element.parent().uniqueId(); this.menuButton = this.container.append('<button class="ui-splitbutton-menubutton" type="button"></button>').children('.ui-splitbutton-menubutton'); this.options.disabled = this.element.prop('disabled'); if(this.options.disabled) { this.menuButton.prop('disabled', true); } this.element.puibutton(this.options).removeClass('ui-corner-all').addClass('ui-corner-left'); this.menuButton.puibutton({ icon: 'fa-caret-down' }).removeClass('ui-corner-all').addClass('ui-corner-right'); if(this.options.items && this.options.items.length) { this._renderPanel(); this._bindEvents(); } }, _renderPanel: function() { this.menu = $('<div class="ui-menu ui-menu-dynamic ui-widget ui-widget-content ui-corner-all ui-helper-clearfix ui-shadow"></div>'). append('<ul class="ui-menu-list ui-helper-reset"></ul>'); this.menuList = this.menu.children('.ui-menu-list'); for(var i = 0; i < this.options.items.length; i++) { var item = this.options.items[i], menuitem = $('<li class="ui-menuitem ui-widget ui-corner-all" role="menuitem"></li>'), link = $('<a class="ui-menuitem-link ui-corner-all"><span class="ui-menuitem-icon fa fa-fw ' + item.icon +'"></span><span class="ui-menuitem-text">' + item.text +'</span></a>'); if(item.url) { link.attr('href', item.url); } if(item.click) { link.on('click.puisplitbutton', item.click); } menuitem.append(link).appendTo(this.menuList); } this.menu.appendTo(this.options.appendTo||this.container); this.options.position = { my: 'left top', at: 'left bottom', of: this.element.parent() }; }, _bindEvents: function() { var $this = this; this.menuButton.on('click.puisplitbutton', function() { if($this.menu.is(':hidden')) $this.show(); else $this.hide(); }); this.menuList.children().on('mouseover.puisplitbutton', function(e) { $(this).addClass('ui-state-hover'); }).on('mouseout.puisplitbutton', function(e) { $(this).removeClass('ui-state-hover'); }).on('click.puisplitbutton', function() { $this.hide(); }); $(document.body).bind('mousedown.' + this.container.attr('id'), function (e) { if($this.menu.is(":hidden")) { return; } var target = $(e.target); if(target.is($this.element)||$this.element.has(target).length > 0) { return; } var offset = $this.menu.offset(); if(e.pageX < offset.left || e.pageX > offset.left + $this.menu.width() || e.pageY < offset.top || e.pageY > offset.top + $this.menu.height()) { $this.element.removeClass('ui-state-focus ui-state-hover'); $this.hide(); } }); var resizeNS = 'resize.' + this.container.attr('id'); $(window).unbind(resizeNS).bind(resizeNS, function() { if($this.menu.is(':visible')) { $this._alignPanel(); } }); }, show: function() { this.menuButton.trigger('focus'); this.menu.show(); this._alignPanel(); this._trigger('show', null); }, hide: function() { this.menuButton.removeClass('ui-state-focus'); this.menu.fadeOut('fast'); this._trigger('hide', null); }, _alignPanel: function() { this.menu.css({left:'', top:'','z-index': ++PUI.zindex}).position(this.options.position); }, disable: function() { this.element.puibutton('disable'); this.menuButton.puibutton('disable'); }, enable: function() { this.element.puibutton('enable'); this.menuButton.puibutton('enable'); } }); })(); /** * PrimeUI sticky widget */ (function() { $.widget("primeui.puisticky", { _create: function() { this.initialState = { top: this.element.offset().top, height: this.element.height() }; this.id = this.element.attr('id'); if(!this.id) { this.id = this.element.uniqueId().attr('id'); } this._bindEvents(); }, _bindEvents: function() { var $this = this, win = $(window), scrollNS = 'scroll.' + this.id, resizeNS = 'resize.' + this.id; win.off(scrollNS).on(scrollNS, function() { if(win.scrollTop() > $this.initialState.top) $this._fix(); else $this._restore(); }) .off(resizeNS).on(resizeNS, function() { if($this.fixed) { $this.element.width($this.ghost.outerWidth() - ($this.element.outerWidth() - $this.element.width())); } }); }, _fix: function() { if(!this.fixed) { this.element.css({ 'position': 'fixed', 'top': 0, 'z-index': 10000 }) .addClass('ui-shadow ui-sticky'); this.ghost = $('<div class="ui-sticky-ghost"></div>').height(this.initialState.height).insertBefore(this.element); this.element.width(this.ghost.outerWidth() - (this.element.outerWidth() - this.element.width())); this.fixed = true; } }, _restore: function() { if(this.fixed) { this.element.css({ position: 'static', top: 'auto', width: 'auto' }) .removeClass('ui-shadow ui-sticky'); this.ghost.remove(); this.fixed = false; } } }); })(); /** * PrimeUI Switch Widget */ (function() { $.widget("primeui.puiswitch", { options: { onLabel: 'On', offLabel: 'Off', checked: false, change: null, enhanced: false }, _create: function() { if(!this.options.enhanced) { this.element.wrap('<div class="ui-inputswitch ui-widget ui-widget-content ui-corner-all"></div>'); this.container = this.element.parent(); this.element.wrap('<div class="ui-helper-hidden-accessible"></div>'); this.container.prepend('<div class="ui-inputswitch-off"></div>' + '<div class="ui-inputswitch-on ui-state-active"></div>' + '<div class="ui-inputswitch-handle ui-state-default"></div>'); this.onContainer = this.container.children('.ui-inputswitch-on'); this.offContainer = this.container.children('.ui-inputswitch-off'); this.onContainer.append('<span>'+ this.options.onLabel +'</span>'); this.offContainer.append('<span>'+ this.options.offLabel +'</span>'); } else { this.container = this.element.closest('.ui-inputswitch'); this.onContainer = this.container.children('.ui-inputswitch-on'); this.offContainer = this.container.children('.ui-inputswitch-off'); } this.onLabel = this.onContainer.children('span'); this.offLabel = this.offContainer.children('span'); this.handle = this.container.children('.ui-inputswitch-handle'); var onContainerWidth = this.onContainer.width(), offContainerWidth = this.offContainer.width(), spanPadding = this.offLabel.innerWidth() - this.offLabel.width(), handleMargins = this.handle.outerWidth() - this.handle.innerWidth(); var containerWidth = (onContainerWidth > offContainerWidth) ? onContainerWidth : offContainerWidth, handleWidth = containerWidth; this.handle.css({'width':handleWidth}); handleWidth = this.handle.width(); containerWidth = containerWidth + handleWidth + 6; var labelWidth = containerWidth - handleWidth - spanPadding - handleMargins; this.container.css({'width': containerWidth }); this.onLabel.width(labelWidth); this.offLabel.width(labelWidth); //position this.offContainer.css({ width: this.container.width() - 5 }); this.offset = this.container.width() - this.handle.outerWidth(); //default value if(this.element.prop('checked')||this.options.checked) { this.handle.css({ 'left': this.offset}); this.onContainer.css({ 'width': this.offset}); this.offLabel.css({ 'margin-right': -this.offset}); } else { this.onContainer.css({ 'width': 0 }); this.onLabel.css({'margin-left': -this.offset}); } if(!this.element.prop('disabled')) { this._bindEvents(); } }, _bindEvents: function() { var $this = this; this.container.on('click.puiswitch', function(e) { $this.toggle(); $this.element.trigger('focus'); }); this.element.on('focus.puiswitch', function(e) { $this.handle.addClass('ui-state-focus'); }) .on('blur.puiswitch', function(e) { $this.handle.removeClass('ui-state-focus'); }) .on('keydown.puiswitch', function(e) { var keyCode = $.ui.keyCode; if(e.which === keyCode.SPACE) { e.preventDefault(); } }) .on('keyup.puiswitch', function(e) { var keyCode = $.ui.keyCode; if(e.which === keyCode.SPACE) { $this.toggle(); e.preventDefault(); } }) .on('change.puiswitch', function(e) { if($this.element.prop('checked')||$this.options.checked) $this._checkUI(); else $this._uncheckUI(); $this._trigger('change', e, {checked: $this.options.checked}); }); }, _unbindEvents: function() { this.container.off('click.puiswitch'); this.element.off('focus.puiswitch blur.puiswitch keydown.puiswitch keyup.puiswitch change.puiswitch'); }, _destroy: function() { this._unbindEvents(); if(!this.options.enhanced) { this.onContainer.remove(); this.offContainer.remove(); this.handle.remove(); this.element.unwrap().unwrap(); } else { this.container.css('width', 'auto'); this.onContainer.css('width', 'auto'); this.onLabel.css('width', 'auto').css('margin-left', 0); this.offContainer.css('width', 'auto'); this.offLabel.css('width', 'auto').css('margin-left', 0); } }, toggle: function() { if(this.element.prop('checked')||this.options.checked) this.uncheck(); else this.check(); }, check: function() { this.options.checked = true; this.element.prop('checked', true).trigger('change'); }, uncheck: function() { this.options.checked = false; this.element.prop('checked', false).trigger('change'); }, _checkUI: function() { this.onContainer.animate({width:this.offset}, 200); this.onLabel.animate({marginLeft:0}, 200); this.offLabel.animate({marginRight:-this.offset}, 200); this.handle.animate({left:this.offset}, 200); }, _uncheckUI: function() { this.onContainer.animate({width:0}, 200); this.onLabel.animate({marginLeft:-this.offset}, 200); this.offLabel.animate({marginRight:0}, 200); this.handle.animate({left:0}, 200); }, _setOption: function(key, value) { if(key === 'checked') { if(value) this.check(); else this.uncheck(); } else { $.Widget.prototype._setOption.apply(this, arguments); } }, }); })(); /** * PrimeUI tabview widget */ (function() { $.widget("primeui.puitabview", { options: { activeIndex: 0, orientation:'top' }, _create: function() { var element = this.element; this.navContainer = element.children('ul'); this.tabHeaders = this.navContainer.children('li'); this.panelContainer = element.children('div'); this._resolvePanelMode(); this.panels = this._findPanels(); element.addClass('ui-tabview ui-widget ui-widget-content ui-corner-all ui-hidden-container ui-tabview-' + this.options.orientation); this.navContainer.addClass('ui-tabview-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all'); this.tabHeaders.addClass('ui-state-default ui-corner-top'); this.panelContainer.addClass('ui-tabview-panels'); this.panels.addClass('ui-tabview-panel ui-widget-content ui-corner-bottom'); this.tabHeaders.eq(this.options.activeIndex).addClass('ui-tabview-selected ui-state-active'); this.panels.filter(':not(:eq(' + this.options.activeIndex + '))').addClass('ui-helper-hidden'); this._bindEvents(); }, _destroy: function() { this.element.removeClass('ui-tabview ui-widget ui-widget-content ui-corner-all ui-hidden-container ui-tabview-' + this.options.orientation); this.navContainer.removeClass('ui-tabview-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all'); this.tabHeaders.removeClass('ui-state-default ui-corner-top ui-tabview-selected ui-state-active'); this.panelContainer.removeClass('ui-tabview-panels'); this.panels.removeClass('ui-tabview-panel ui-widget-content ui-corner-bottom ui-helper-hidden').removeData('loaded'); this._unbindEvents(); }, _bindEvents: function() { var $this = this; //Tab header events this.tabHeaders.on('mouseover.puitabview', function(e) { var element = $(this); if(!element.hasClass('ui-state-disabled')&&!element.hasClass('ui-state-active')) { element.addClass('ui-state-hover'); } }) .on('mouseout.puitabview', function(e) { var element = $(this); if(!element.hasClass('ui-state-disabled')&&!element.hasClass('ui-state-active')) { element.removeClass('ui-state-hover'); } }) .on('click.puitabview', function(e) { var element = $(this); if($(e.target).is(':not(.fa-close)')) { var index = element.index(); if(!element.hasClass('ui-state-disabled') && !element.hasClass('ui-state-active')) { $this.select(index); } } e.preventDefault(); }); //Closable tabs this.navContainer.find('li .fa-close') .on('click.puitabview', function(e) { var index = $(this).parent().index(); $this.remove(index); e.preventDefault(); }); }, _unbindEvents: function() { this.tabHeaders.off('mouseover.puitabview mouseout.puitabview click.puitabview'); this.navContainer.find('li .fa-close').off('click.puitabview'); }, select: function(index) { this.options.activeIndex = index; var newPanel = this.panels.eq(index), oldHeader = this.tabHeaders.filter('.ui-state-active'), newHeader = this._getHeaderOfPanel(newPanel), oldPanel = this.panels.filter('.ui-tabview-panel:visible'), $this = this; //aria oldPanel.attr('aria-hidden', true); oldHeader.attr('aria-expanded', false); newPanel.attr('aria-hidden', false); newHeader.attr('aria-expanded', true); if(this.options.effect) { oldPanel.hide(this.options.effect.name, null, this.options.effect.duration, function() { oldHeader.removeClass('ui-tabview-selected ui-state-active'); newHeader.removeClass('ui-state-hover').addClass('ui-tabview-selected ui-state-active'); newPanel.show($this.options.name, null, $this.options.effect.duration, function() { $this._trigger('change', null, {'index':index}); }); }); } else { oldHeader.removeClass('ui-tabview-selected ui-state-active'); oldPanel.hide(); newHeader.removeClass('ui-state-hover').addClass('ui-tabview-selected ui-state-active'); newPanel.show(); $this._trigger('change', null, {'index':index}); } }, remove: function(index) { var header = this.tabHeaders.eq(index), panel = this.panels.eq(index); this._trigger('close', null, {'index':index}); header.remove(); panel.remove(); this.tabHeaders = this.navContainer.children('li'); this.panels = this._findPanels(); if(index < this.options.activeIndex) { this.options.activeIndex--; } else if(index == this.options.activeIndex) { var newIndex = (this.options.activeIndex == this.getLength()) ? this.options.activeIndex - 1: this.options.activeIndex, newHeader = this.tabHeaders.eq(newIndex), newPanel = this.panels.eq(newIndex); newHeader.removeClass('ui-state-hover').addClass('ui-tabview-selected ui-state-active'); newPanel.show(); } }, getLength: function() { return this.tabHeaders.length; }, getActiveIndex: function() { return this.options.activeIndex; }, _markAsLoaded: function(panel) { panel.data('loaded', true); }, _isLoaded: function(panel) { return panel.data('loaded') === true; }, disable: function(index) { this.tabHeaders.eq(index).addClass('ui-state-disabled'); }, enable: function(index) { this.tabHeaders.eq(index).removeClass('ui-state-disabled'); }, _findPanels: function() { var containers = this.panelContainer.children(); //primeui if(this.panelMode === 'native') { return containers; } //primeng else if(this.panelMode === 'wrapped') { return containers.children(':first-child'); } }, _resolvePanelMode: function() { var containers = this.panelContainer.children(); this.panelMode = containers.is('div') ? 'native' : 'wrapped'; }, _getHeaderOfPanel: function(panel) { if(this.panelMode === 'native') return this.tabHeaders.eq(panel.index()); else if(this.panelMode === 'wrapped') return this.tabHeaders.eq(panel.parent().index()); }, _setOption: function(key, value) { if(key === 'activeIndex') { this.select(value); } else { $.Widget.prototype._setOption.apply(this, arguments); } } }); })(); /** * PrimeUI Terminal widget */ (function() { $.widget("primeui.puiterminal", { options: { welcomeMessage: '', prompt:'prime $', handler: null }, _create: function() { this.element.addClass('ui-terminal ui-widget ui-widget-content ui-corner-all') .append('<div>' + this.options.welcomeMessage + '</div>') .append('<div class="ui-terminal-content"></div>') .append('<div><span class="ui-terminal-prompt">' + this.options.prompt + '</span>' + '<input type="text" class="ui-terminal-input" autocomplete="off"></div>' ); this.promptContainer = this.element.find('> div:last-child > span.ui-terminal-prompt'); this.content = this.element.children('.ui-terminal-content'); this.input = this.promptContainer.next(); this.commands = []; this.commandIndex = 0; this._bindEvents(); }, _bindEvents: function() { var $this = this; this.input.on('keydown.terminal', function(e) { var keyCode = $.ui.keyCode; switch(e.which) { case keyCode.UP: if($this.commandIndex > 0) { $this.input.val($this.commands[--$this.commandIndex]); } e.preventDefault(); break; case keyCode.DOWN: if($this.commandIndex < ($this.commands.length - 1)) { $this.input.val($this.commands[++$this.commandIndex]); } else { $this.commandIndex = $this.commands.length; $this.input.val(''); } e.preventDefault(); break; case keyCode.ENTER: case keyCode.NUMPAD_ENTER: $this._processCommand(); e.preventDefault(); break; } }); this.element.on('click', function() { $this.input.trigger('focus'); }); }, _processCommand: function() { var command = this.input.val(); this.commands.push(); this.commandIndex++; if(this.options.handler && $.type(this.options.handler) === 'function') { this.options.handler.call(this, command, this._updateContent); } }, _updateContent: function(content) { var commandResponseContainer = $('<div></div>'); commandResponseContainer.append('<span>' + this.options.prompt + '</span><span class="ui-terminal-command">' + this.input.val() + '</span>') .append('<div>' + content + '</div>').appendTo(this.content); this.input.val(''); this.element.scrollTop(this.content.height()); }, clear: function() { this.content.html(''); this.input.val(''); } }); })(); /** * PrimeUI togglebutton widget */ (function() { $.widget("primeui.puitogglebutton", { options: { onLabel: 'Yes', offLabel: 'No', onIcon: null, offIcon: null, checked: false }, _create: function() { this.element.wrap('<div class="ui-button ui-togglebutton ui-widget ui-state-default ui-corner-all" />'); this.container = this.element.parent(); this.element.addClass('ui-helper-hidden-accessible'); if(this.options.onIcon && this.options.offIcon) { this.container.addClass('ui-button-text-icon-left'); this.container.append('<span class="ui-button-icon-left fa fa-fw"></span>'); } else { this.container.addClass('ui-button-text-only'); } this.container.append('<span class="ui-button-text"></span>'); if(this.options.style) { this.container.attr('style', this.options.style); } if(this.options.styleClass) { this.container.attr('class', this.options.styleClass); } this.label = this.container.children('.ui-button-text'); this.icon = this.container.children('.fa'); //initial state if(this.element.prop('checked')||this.options.checked) { this.check(true); } else { this.uncheck(true); } if(!this.element.prop('disabled')) { this._bindEvents(); } }, _bindEvents: function() { var $this = this; this.container.on('mouseover.puitogglebutton', function() { if(!$this.container.hasClass('ui-state-active')) { $this.container.addClass('ui-state-hover'); } }).on('mouseout.puitogglebutton', function() { $this.container.removeClass('ui-state-hover'); }) .on('click.puitogglebutton', function() { $this.toggle(); $this.element.trigger('focus'); }); this.element.on('focus.puitogglebutton', function() { $this.container.addClass('ui-state-focus'); }) .on('blur.puitogglebutton', function() { $this.container.removeClass('ui-state-focus'); }) .on('keydown.puitogglebutton', function(e) { var keyCode = $.ui.keyCode; if(e.which === keyCode.SPACE) { e.preventDefault(); } }) .on('keyup.puitogglebutton', function(e) { var keyCode = $.ui.keyCode; if(e.which === keyCode.SPACE) { $this.toggle(); e.preventDefault(); } }); }, _unbindEvents: function() { this.container.off('mouseover.puitogglebutton mouseout.puitogglebutton click.puitogglebutton'); this.element.off('focus.puitogglebutton blur.puitogglebutton keydown.puitogglebutton keyup.puitogglebutton'); }, toggle: function() { if(this.element.prop('checked')) this.uncheck(); else this.check(); }, check: function(silent) { this.container.addClass('ui-state-active'); this.label.text(this.options.onLabel); this.element.prop('checked', true); if(this.options.onIcon) { this.icon.removeClass(this.options.offIcon).addClass(this.options.onIcon); } if(!silent) { this._trigger('change', null, {checked: true}); } }, uncheck: function(silent) { this.container.removeClass('ui-state-active') this.label.text(this.options.offLabel); this.element.prop('checked', false); if(this.options.offIcon) { this.icon.removeClass(this.options.onIcon).addClass(this.options.offIcon); } if(!silent) { this._trigger('change', null, {checked: false}); } }, disable: function () { this.element.prop('disabled', true); this.container.attr('aria-disabled', true); this.container.addClass('ui-state-disabled').removeClass('ui-state-focus ui-state-hover'); this._unbindEvents(); }, enable: function () { this.element.prop('disabled', false); this.container.attr('aria-disabled', false); this.container.removeClass('ui-state-disabled'); this._bindEvents(); }, isChecked: function() { return this.element.prop('checked'); }, _setOption: function(key, value) { if(key === 'checked') { this.options.checked = value; if(value) this.check(true); else this.uncheck(true); } else if(key === 'disabled') { if(value) this.disable(); else this.enable(); } else { $.Widget.prototype._setOption.apply(this, arguments); } }, _destroy: function() { this._unbindEvents(); this.container.children('span').remove(); this.element.removeClass('ui-helper-hidden-accessible').unwrap(); } }); })(); /** * PrimeFaces Tooltip Widget */ (function() { $.widget("primeui.puitooltip", { options: { showEvent: 'mouseover', hideEvent: 'mouseout', showEffect: 'fade', hideEffect: null, showEffectSpeed: 'normal', hideEffectSpeed: 'normal', my: 'left top', at: 'right bottom', showDelay: 150, content: null }, _create: function() { this.options.showEvent = this.options.showEvent + '.puitooltip'; this.options.hideEvent = this.options.hideEvent + '.puitooltip'; if(this.element.get(0) === document) { this._bindGlobal(); } else { this._bindTarget(); } }, _bindGlobal: function() { this.container = $('<div class="ui-tooltip ui-tooltip-global ui-widget ui-widget-content ui-corner-all ui-shadow" />').appendTo(document.body); this.globalSelector = 'a,:input,:button,img'; var $this = this; $(document).off(this.options.showEvent + ' ' + this.options.hideEvent, this.globalSelector) .on(this.options.showEvent, this.globalSelector, null, function() { var target = $(this), title = target.attr('title'); if(title) { $this.container.text(title); $this.globalTitle = title; $this.target = target; target.attr('title', ''); $this.show(); } }) .on(this.options.hideEvent, this.globalSelector, null, function() { var target = $(this); if($this.globalTitle) { $this.container.hide(); target.attr('title', $this.globalTitle); $this.globalTitle = null; $this.target = null; } }); var resizeNS = 'resize.puitooltip'; $(window).unbind(resizeNS).bind(resizeNS, function() { if($this.container.is(':visible')) { $this._align(); } }); }, _bindTarget: function() { this.container = $('<div class="ui-tooltip ui-widget ui-widget-content ui-corner-all ui-shadow" />').appendTo(document.body); var $this = this; this.element.off(this.options.showEvent + ' ' + this.options.hideEvent) .on(this.options.showEvent, function() { $this.show(); }) .on(this.options.hideEvent, function() { $this.hide(); }); this.container.html(this.options.content); this.element.removeAttr('title'); this.target = this.element; var resizeNS = 'resize.' + this.element.attr('id'); $(window).unbind(resizeNS).bind(resizeNS, function() { if($this.container.is(':visible')) { $this._align(); } }); }, _align: function() { this.container.css({ left:'', top:'', 'z-index': ++PUI.zindex }) .position({ my: this.options.my, at: this.options.at, of: this.target }); }, show: function() { var $this = this; this.timeout = window.setTimeout(function() { $this._align(); $this.container.show($this.options.showEffect, {}, $this.options.showEffectSpeed); }, this.options.showDelay); }, hide: function() { window.clearTimeout(this.timeout); this.container.hide(this.options.hideEffect, {}, this.options.hideEffectSpeed, function() { $(this).css('z-index', ''); }); } }); })(); /** * PrimeUI Tree widget */ (function() { $.widget("primeui.puitree", { options: { nodes: null, lazy: false, animate: false, selectionMode: null, icons: null }, _create: function() { this.element.uniqueId().addClass('ui-tree ui-widget ui-widget-content ui-corner-all') .append('<ul class="ui-tree-container"></ul>'); this.rootContainer = this.element.children('.ui-tree-container'); if(this.options.selectionMode) { this.selection = []; } this._bindEvents(); if($.type(this.options.nodes) === 'array') { this._renderNodes(this.options.nodes, this.rootContainer); } else if($.type(this.options.nodes) === 'function') { this.options.nodes.call(this, {}, this._initData); } else { throw 'Unsupported type. nodes option can be either an array or a function'; } }, _renderNodes: function(nodes, container) { for(var i = 0; i < nodes.length; i++) { this._renderNode(nodes[i], container); } }, _renderNode: function(node, container) { var leaf = this.options.lazy ? node.leaf : !(node.children && node.children.length), iconType = node.iconType||'def', expanded = node.expanded, selectable = this.options.selectionMode ? (node.selectable === false ? false : true) : false, toggleIcon = leaf ? 'ui-treenode-leaf-icon' : (node.expanded ? 'ui-tree-toggler fa fa-fw fa-caret-down' : 'ui-tree-toggler fa fa-fw fa-caret-right'), styleClass = leaf ? 'ui-treenode ui-treenode-leaf' : 'ui-treenode ui-treenode-parent', nodeElement = $('<li class="' + styleClass + '"></li>'), contentElement = $('<span class="ui-treenode-content"></span>'); nodeElement.data('puidata', node.data).appendTo(container); if(selectable) { contentElement.addClass('ui-treenode-selectable'); } contentElement.append('<span class="' + toggleIcon + '"></span>') .append('<span class="ui-treenode-icon"></span>') .append('<span class="ui-treenode-label ui-corner-all">' + node.label + '</span>') .appendTo(nodeElement); var iconConfig = this.options.icons && this.options.icons[iconType]; if(iconConfig) { var iconContainer = contentElement.children('.ui-treenode-icon'), icon = ($.type(iconConfig) === 'string') ? iconConfig : (expanded ? iconConfig.expanded : iconConfig.collapsed); iconContainer.addClass('fa fa-fw ' + icon); } if(!leaf) { var childrenContainer = $('<ul class="ui-treenode-children"></ul>'); if(!node.expanded) { childrenContainer.hide(); } childrenContainer.appendTo(nodeElement); if(node.children) { for(var i = 0; i < node.children.length; i++) { this._renderNode(node.children[i], childrenContainer); } } } }, _initData: function(data) { this._renderNodes(data, this.rootContainer); }, _handleNodeData: function(data, node) { this._renderNodes(data, node.children('.ui-treenode-children')); this._showNodeChildren(node); node.data('puiloaded', true); }, _bindEvents: function() { var $this = this, elementId = this.element.attr('id'), togglerSelector = '#' + elementId + ' .ui-tree-toggler'; $(document).off('click.puitree-' + elementId, togglerSelector) .on('click.puitree-' + elementId, togglerSelector, null, function(e) { var toggleIcon = $(this), node = toggleIcon.closest('li'); if(node.hasClass('ui-treenode-expanded')) $this.collapseNode(node); else $this.expandNode(node); }); if(this.options.selectionMode) { var nodeLabelSelector = '#' + elementId + ' .ui-treenode-selectable .ui-treenode-label', nodeContentSelector = '#' + elementId + ' .ui-treenode-selectable.ui-treenode-content'; $(document).off('mouseout.puitree-' + elementId + ' mouseover.puitree-' + elementId, nodeLabelSelector) .on('mouseout.puitree-' + elementId, nodeLabelSelector, null, function() { $(this).removeClass('ui-state-hover'); }) .on('mouseover.puitree-' + elementId, nodeLabelSelector, null, function() { $(this).addClass('ui-state-hover'); }) .off('click.puitree-' + elementId, nodeContentSelector) .on('click.puitree-' + elementId, nodeContentSelector, null, function(e) { $this._nodeClick(e, $(this)); }); } }, expandNode: function(node) { this._trigger('beforeExpand', null, {'node': node, 'data': node.data('puidata')}); if(this.options.lazy && !node.data('puiloaded')) { this.options.nodes.call(this, { 'node': node, 'data': node.data('puidata') }, this._handleNodeData); } else { this._showNodeChildren(node); } }, collapseNode: function(node) { this._trigger('beforeCollapse', null, {'node': node, 'data': node.data('puidata')}); node.removeClass('ui-treenode-expanded'); var iconType = node.iconType||'def', iconConfig = this.options.icons && this.options.icons[iconType]; if(iconConfig && $.type(iconConfig) !== 'string') { node.find('> .ui-treenode-content > .ui-treenode-icon').removeClass(iconConfig.expanded).addClass(iconConfig.collapsed); } var toggleIcon = node.find('> .ui-treenode-content > .ui-tree-toggler'), childrenContainer = node.children('.ui-treenode-children'); toggleIcon.addClass('fa-caret-right').removeClass('fa-caret-down'); if(this.options.animate) { childrenContainer.slideUp('fast'); } else { childrenContainer.hide(); } this._trigger('afterCollapse', null, {'node': node, 'data': node.data('puidata')}); }, _showNodeChildren: function(node) { node.addClass('ui-treenode-expanded').attr('aria-expanded', true); var iconType = node.iconType||'def', iconConfig = this.options.icons && this.options.icons[iconType]; if(iconConfig && $.type(iconConfig) !== 'string') { node.find('> .ui-treenode-content > .ui-treenode-icon').removeClass(iconConfig.collapsed).addClass(iconConfig.expanded); } var toggleIcon = node.find('> .ui-treenode-content > .ui-tree-toggler'); toggleIcon.addClass('fa-caret-down').removeClass('fa-caret-right'); if(this.options.animate) { node.children('.ui-treenode-children').slideDown('fast'); } else { node.children('.ui-treenode-children').show(); } this._trigger('afterExpand', null, {'node': node, 'data': node.data('puidata')}); }, _nodeClick: function(event, nodeContent) { PUI.clearSelection(); if($(event.target).is(':not(.ui-tree-toggler)')) { var node = nodeContent.parent(); var selected = this._isNodeSelected(node.data('puidata')), metaKey = event.metaKey||event.ctrlKey; if(selected && metaKey) { this.unselectNode(node); } else { if(this._isSingleSelection()||(this._isMultipleSelection() && !metaKey)) { this.unselectAllNodes(); } this.selectNode(node); } } }, selectNode: function(node) { node.attr('aria-selected', true).find('> .ui-treenode-content > .ui-treenode-label').removeClass('ui-state-hover').addClass('ui-state-highlight'); this._addToSelection(node.data('puidata')); this._trigger('nodeSelect', null, {'node': node, 'data': node.data('puidata')}); }, unselectNode: function(node) { node.attr('aria-selected', false).find('> .ui-treenode-content > .ui-treenode-label').removeClass('ui-state-highlight ui-state-hover'); this._removeFromSelection(node.data('puidata')); this._trigger('nodeUnselect', null, {'node': node, 'data': node.data('puidata')}); }, unselectAllNodes: function() { this.selection = []; this.element.find('.ui-treenode-label.ui-state-highlight').each(function() { $(this).removeClass('ui-state-highlight').closest('.ui-treenode').attr('aria-selected', false); }); }, _addToSelection: function(nodedata) { if(nodedata) { var selected = this._isNodeSelected(nodedata); if(!selected) { this.selection.push(nodedata); } } }, _removeFromSelection: function(nodedata) { if(nodedata) { var index = -1; for(var i = 0; i < this.selection.length; i++) { var data = this.selection[i]; if(data && (JSON.stringify(data) === JSON.stringify(nodedata))) { index = i; break; } } if(index >= 0) { this.selection.splice(index, 1); } } }, _isNodeSelected: function(nodedata) { var selected = false; if(nodedata) { for(var i = 0; i < this.selection.length; i++) { var data = this.selection[i]; if(data && (JSON.stringify(data) === JSON.stringify(nodedata))) { selected = true; break; } } } return selected; }, _isSingleSelection: function() { return this.options.selectionMode && this.options.selectionMode === 'single'; }, _isMultipleSelection: function() { return this.options.selectionMode && this.options.selectionMode === 'multiple'; } }); })(); /** * PrimeUI TreeTable widget */ (function() { $.widget("primeui.puitreetable", { options: { nodes: null, lazy: false, selectionMode: null, header: null }, _create: function() { this.id = this.element.attr('id'); if(!this.id) { this.id = this.element.uniqueId().attr('id'); } this.element.addClass('ui-treetable ui-widget'); this.tableWrapper = $('<div class="ui-treetable-tablewrapper" />').appendTo(this.element); this.table = $('<table><thead></thead><tbody></tbody></table>').appendTo(this.tableWrapper); this.thead = this.table.children('thead'); this.tbody = this.table.children('tbody').addClass('ui-treetable-data'); var $this = this; if(this.options.columns) { var headerRow = $('<tr></tr>').appendTo(this.thead); $.each(this.options.columns, function(i, col) { var header = $('<th class="ui-state-default"></th>').data('field', col.field).appendTo(headerRow); if(col.headerClass) { header.addClass(col.headerClass); } if(col.headerStyle) { header.attr('style', col.headerStyle); } if(col.headerText) { header.text(col.headerText); } }); } if(this.options.header) { this.element.prepend('<div class="ui-treetable-header ui-widget-header ui-corner-top">' + this.options.header + '</div>'); } if(this.options.footer) { this.element.append('<div class="ui-treetable-footer ui-widget-header ui-corner-bottom">' + this.options.footer + '</div>'); } if($.isArray(this.options.nodes)) { this._renderNodes(this.options.nodes, null, true); } else if($.type(this.options.nodes) === 'function') { this.options.nodes.call(this, {}, this._initData); } else { throw 'Unsupported type. nodes option can be either an array or a function'; } this._bindEvents(); }, _initData: function(data) { this._renderNodes(data, null, true); }, _renderNodes: function(nodes, rootRow, expanded) { for(var i = 0; i < nodes.length; i++) { var node = nodes[i], nodeData = node.data, leaf = this.options.lazy ? node.leaf : !(node.children && node.children.length), row = $('<tr class="ui-widget-content"></tr>'), depth = rootRow ? rootRow.data('depth') + 1 : 0, parentRowkey = rootRow ? rootRow.data('rowkey'): null, rowkey = parentRowkey ? parentRowkey + '_' + i : i.toString(); row.data({ 'depth': depth, 'rowkey': rowkey, 'parentrowkey': parentRowkey, 'puidata': nodeData }); if(!expanded) { row.addClass('ui-helper-hidden'); } for(var j = 0; j < this.options.columns.length; j++) { var column = $('<td />').appendTo(row), columnOptions = this.options.columns[j]; if(columnOptions.bodyClass) { column.addClass(columnOptions.bodyClass); } if(columnOptions.bodyStyle) { column.attr('style', columnOptions.bodyStyle); } if(j === 0) { var toggler = $('<span class="ui-treetable-toggler fa fa-fw fa-caret-right ui-c"></span>'); toggler.css('margin-left', depth * 16 + 'px'); if(leaf) { toggler.css('visibility', 'hidden'); } toggler.appendTo(column); } if(columnOptions.content) { var content = columnOptions.content.call(this, nodeData); if($.type(content) === 'string') column.text(content); else column.append(content); } else { column.append(nodeData[columnOptions.field]); } } if(rootRow) row.insertAfter(rootRow); else row.appendTo(this.tbody); if(!leaf) { this._renderNodes(node.children, row, node.expanded); } } }, _bindEvents: function() { var $this = this, togglerSelector = '> tr > td:first-child > .ui-treetable-toggler'; //expand and collapse this.tbody.off('click.puitreetable', togglerSelector) .on('click.puitreetable', togglerSelector, null, function(e) { var toggler = $(this), row = toggler.closest('tr'); if(!row.data('processing')) { row.data('processing', true); if(toggler.hasClass('fa-caret-right')) $this.expandNode(row); else $this.collapseNode(row); } }); //selection if(this.options.selectionMode) { this.selection = []; var rowSelector = '> tr'; this.tbody.off('mouseover.puitreetable mouseout.puitreetable click.puitreetable', rowSelector) .on('mouseover.puitreetable', rowSelector, null, function(e) { var element = $(this); if(!element.hasClass('ui-state-highlight')) { element.addClass('ui-state-hover'); } }) .on('mouseout.puitreetable', rowSelector, null, function(e) { var element = $(this); if(!element.hasClass('ui-state-highlight')) { element.removeClass('ui-state-hover'); } }) .on('click.puitreetable', rowSelector, null, function(e) { $this.onRowClick(e, $(this)); }); } }, expandNode: function(row) { this._trigger('beforeExpand', null, {'node': row, 'data': row.data('puidata')}); if(this.options.lazy && !row.data('puiloaded')) { this.options.nodes.call(this, { 'node': row, 'data': row.data('puidata') }, this._handleNodeData); } else { this._showNodeChildren(row, false); this._trigger('afterExpand', null, {'node': row, 'data': row.data('puidata')}); } }, _handleNodeData: function(data, node) { this._renderNodes(data, node, true); this._showNodeChildren(node, false); node.data('puiloaded', true); this._trigger('afterExpand', null, {'node': node, 'data': node.data('puidata')}); }, _showNodeChildren: function(row, showOnly) { if(!showOnly) { row.data('expanded', true).attr('aria-expanded', true) .find('.ui-treetable-toggler:first').addClass('fa-caret-down').removeClass('fa-caret-right'); } var children = this._getChildren(row); for(var i = 0; i < children.length; i++) { var child = children[i]; child.removeClass('ui-helper-hidden'); if(child.data('expanded')) { this._showNodeChildren(child, true); } } row.data('processing', false); }, collapseNode: function(row) { this._trigger('beforeCollapse', null, {'node': row, 'data': row.data('puidata')}); this._hideNodeChildren(row, false); row.data('processing', false); this._trigger('afterCollapse', null, {'node': row, 'data': row.data('puidata')}); }, _hideNodeChildren: function(row, hideOnly) { if(!hideOnly) { row.data('expanded', false).attr('aria-expanded', false) .find('.ui-treetable-toggler:first').addClass('fa-caret-right').removeClass('fa-caret-down'); } var children = this._getChildren(row); for(var i = 0; i < children.length; i++) { var child = children[i]; child.addClass('ui-helper-hidden'); if(child.data('expanded')) { this._hideNodeChildren(child, true); } } }, onRowClick: function(event, row) { if(!$(event.target).is(':input,:button,a,.ui-c')) { var selected = row.hasClass('ui-state-highlight'), metaKey = event.metaKey||event.ctrlKey; if(selected && metaKey) { this.unselectNode(row); } else { if(this.isSingleSelection()||(this.isMultipleSelection() && !metaKey)) { this.unselectAllNodes(); } this.selectNode(row); } PUI.clearSelection(); } }, selectNode: function(row, silent) { row.removeClass('ui-state-hover').addClass('ui-state-highlight').attr('aria-selected', true); if(!silent) { this._trigger('nodeSelect', {}, {'node': row, 'data': row.data('puidata')}); } }, unselectNode: function(row, silent) { row.removeClass('ui-state-highlight').attr('aria-selected', false); if(!silent) { this._trigger('nodeUnselect', {}, {'node': row, 'data': row.data('puidata')}); } }, unselectAllNodes: function() { var selectedNodes = this.tbody.children('tr.ui-state-highlight'); for(var i = 0; i < selectedNodes.length; i++) { this.unselectNode(selectedNodes.eq(i), true); } }, isSingleSelection: function() { return this.options.selectionMode === 'single'; }, isMultipleSelection: function() { return this.options.selectionMode === 'multiple'; }, _getChildren: function(node) { var nodeKey = node.data('rowkey'), nextNodes = node.nextAll(), children = []; for(var i = 0; i < nextNodes.length; i++) { var nextNode = nextNodes.eq(i), nextNodeParentKey = nextNode.data('parentrowkey'); if(nextNodeParentKey === nodeKey) { children.push(nextNode); } } return children; } }); })(); /** * PrimeUI ColResize widget */ (function() { $.widget("primeui.puicolresize", { options: { mode: 'fit' }, _create: function() { this.element.addClass('ui-datatable-resizable'); this.thead = this.element.find('> .ui-datatable-tablewrapper > table > thead'); this.thead.find('> tr > th').addClass('ui-resizable-column'); this.resizerHelper = $('<div class="ui-column-resizer-helper ui-state-highlight"></div>').appendTo(this.element); this.addResizers(); var resizers = this.thead.find('> tr > th > span.ui-column-resizer'), $this = this; setTimeout(function() { $this.fixColumnWidths(); }, 5); resizers.draggable({ axis: 'x', start: function(event, ui) { ui.helper.data('originalposition', ui.helper.offset()); var height = $this.options.scrollable ? $this.scrollBody.height() : $this.thead.parent().height() - $this.thead.height() - 1; $this.resizerHelper.height(height); $this.resizerHelper.show(); }, drag: function(event, ui) { $this.resizerHelper.offset({ left: ui.helper.offset().left + ui.helper.width() / 2, top: $this.thead.offset().top + $this.thead.height() }); }, stop: function(event, ui) { ui.helper.css({ 'left': '', 'top': '0px', 'right': '0px' }); $this.resize(event, ui); $this.resizerHelper.hide(); if($this.options.mode === 'expand') { setTimeout(function() { $this._trigger('colResize', null, {element: ui.helper.parent().get(0)}); }, 5); } else { $this._trigger('colResize', null, {element: ui.helper.parent().get(0)}); } }, containment: this.element }); }, resize: function(event, ui) { var columnHeader, nextColumnHeader, change = null, newWidth = null, nextColumnWidth = null, expandMode = (this.options.mode === 'expand'), table = this.thead.parent(), columnHeader = ui.helper.parent(), nextColumnHeader = columnHeader.next(); change = (ui.position.left - ui.originalPosition.left), newWidth = (columnHeader.width() + change), nextColumnWidth = (nextColumnHeader.width() - change); if((newWidth > 15 && nextColumnWidth > 15) || (expandMode && newWidth > 15)) { if(expandMode) { table.width(table.width() + change); setTimeout(function() { columnHeader.width(newWidth); }, 1); } else { columnHeader.width(newWidth); nextColumnHeader.width(nextColumnWidth); } } }, addResizers: function() { var resizableColumns = this.thead.find('> tr > th.ui-resizable-column'); resizableColumns.prepend('<span class="ui-column-resizer">&nbsp;</span>'); if(this.options.columnResizeMode === 'fit') { resizableColumns.filter(':last-child').children('span.ui-column-resizer').hide(); } }, fixColumnWidths: function() { if(!this.columnWidthsFixed) { this.element.find('> .ui-datatable-tablewrapper > table > thead > tr > th').each(function() { var col = $(this); col.width(col.width()); }); this.columnWidthsFixed = true; } }, _destroy: function() { this.element.removeClass('ui-datatable-resizable'); this.thead.find('> tr > th').removeClass('ui-resizable-column'); this.resizerHelper.remove(); this.thead.find('> tr > th > span.ui-column-resizer').draggable('destroy').remove(); } }); })(); /** * PrimeUI ColReorder widget */ (function() { $.widget("primeui.puicolreorder", { _create: function() { var $this = this; this.thead = this.element.find('> .ui-datatable-tablewrapper > table > thead'); this.tbody = this.element.find('> .ui-datatable-tablewrapper > table > tbody'); this.dragIndicatorTop = $('<span class="fa fa-arrow-down" style="position:absolute"/></span>').hide().appendTo(this.element); this.dragIndicatorBottom = $('<span class="fa fa-arrow-up" style="position:absolute"/></span>').hide().appendTo(this.element); this.thead.find('> tr > th').draggable({ appendTo: 'body', opacity: 0.75, cursor: 'move', scope: this.id, cancel: ':input,.ui-column-resizer', drag: function(event, ui) { var droppable = ui.helper.data('droppable-column'); if(droppable) { var droppableOffset = droppable.offset(), topArrowY = droppableOffset.top - 10, bottomArrowY = droppableOffset.top + droppable.height() + 8, arrowX = null; //calculate coordinates of arrow depending on mouse location if(event.originalEvent.pageX >= droppableOffset.left + (droppable.width() / 2)) { var nextDroppable = droppable.next(); if(nextDroppable.length == 1) arrowX = nextDroppable.offset().left - 9; else arrowX = droppable.offset().left + droppable.innerWidth() - 9; ui.helper.data('drop-location', 1); //right } else { arrowX = droppableOffset.left - 9; ui.helper.data('drop-location', -1); //left } $this.dragIndicatorTop.offset({ 'left': arrowX, 'top': topArrowY - 3 }).show(); $this.dragIndicatorBottom.offset({ 'left': arrowX, 'top': bottomArrowY - 3 }).show(); } }, stop: function(event, ui) { //hide dnd arrows $this.dragIndicatorTop.css({ 'left':0, 'top':0 }).hide(); $this.dragIndicatorBottom.css({ 'left':0, 'top':0 }).hide(); }, helper: function() { var header = $(this), helper = $('<div class="ui-widget ui-state-default" style="padding:4px 10px;text-align:center;"></div>'); helper.width(header.width()); helper.height(header.height()); helper.html(header.html()); return helper.get(0); } }) .droppable({ hoverClass:'ui-state-highlight', tolerance:'pointer', scope: this.id, over: function(event, ui) { ui.helper.data('droppable-column', $(this)); }, drop: function(event, ui) { var draggedColumnHeader = ui.draggable, droppedColumnHeader = $(this), dropLocation = ui.helper.data('drop-location'); $this._trigger('colReorder', null, { dragIndex: draggedColumnHeader.index(), dropIndex: droppedColumnHeader.index(), dropSide: dropLocation }); } }); }, _destroy: function() { this.dragIndicatorTop.remove(); this.dragIndicatorBottom.remove(); this.thead.find('> tr > th').draggable('destroy').droppable('destroy'); } }); })(); /** * PrimeUI TableScroll widget */ (function() { $.widget("primeui.puitablescroll", { options: { scrollHeight: null, scrollWidth: null }, _create: function() { this.id = PUI.generateRandomId(); this.scrollHeader = this.element.children('.ui-datatable-scrollable-header'); this.scrollBody = this.element.children('.ui-datatable-scrollable-body'); this.scrollFooter = this.element.children('.ui-datatable-scrollable-footer'); this.scrollHeaderBox = this.scrollHeader.children('.ui-datatable-scrollable-header-box'); this.bodyTable = this.scrollBody.children('table'); this.percentageScrollHeight = this.options.scrollHeight && (this.options.scrollHeight.indexOf('%') !== -1); this.percentageScrollWidth = this.options.scrollWidth && (this.options.scrollWidth.indexOf('%') !== -1); var $this = this, scrollBarWidth = this.getScrollbarWidth() + 'px'; if(this.options.scrollHeight) { if(this.percentageScrollHeight) this.adjustScrollHeight(); else this.scrollBody.css('max-height', this.options.scrollHeight + 'px'); this.scrollHeaderBox.css('margin-right', scrollBarWidth); } if(this.options.scrollWidth) { if(this.percentageScrollWidth) this.adjustScrollWidth(); else this.setScrollWidth(parseInt(this.options.scrollWidth)); } this.scrollBody.on('scroll.dataTable', function() { var scrollLeft = $this.scrollBody.scrollLeft(); $this.scrollHeaderBox.css('margin-left', -scrollLeft); }); this.scrollHeader.on('scroll.dataTable', function() { $this.scrollHeader.scrollLeft(0); }); $(window).on('resize.' + this.id, function() { if($this.element.is(':visible')) { if($this.percentageScrollHeight) $this.adjustScrollHeight(); if($this.percentageScrollWidth) $this.adjustScrollWidth(); } }); }, _destroy: function() { $(window).off('resize.' + this.id); this.scrollHeader.off('scroll.dataTable'); this.scrollBody.off('scroll.dataTable'); }, adjustScrollHeight: function() { var relativeHeight = this.element.parent().parent().innerHeight() * (parseInt(this.options.scrollHeight) / 100), tableHeaderHeight = this.element.children('.ui-datatable-header').outerHeight(true), tableFooterHeight = this.element.children('.ui-datatable-footer').outerHeight(true), scrollersHeight = (this.scrollHeader.outerHeight(true) + this.scrollFooter.outerHeight(true)), paginatorsHeight = this.paginator ? this.paginator.getContainerHeight(true) : 0, height = (relativeHeight - (scrollersHeight + paginatorsHeight + tableHeaderHeight + tableFooterHeight)); this.scrollBody.css('max-height', height + 'px'); }, adjustScrollWidth: function() { var width = parseInt((this.element.parent().parent().innerWidth() * (parseInt(this.options.scrollWidth) / 100))); this.setScrollWidth(width); }, setOuterWidth: function(element, width) { var diff = element.outerWidth() - element.width(); element.width(width - diff); }, setScrollWidth: function(width) { var $this = this; this.element.children('.ui-widget-header').each(function() { $this.setOuterWidth($(this), width); }); this.scrollHeader.width(width); this.scrollBody.css('margin-right', 0).width(width); }, getScrollbarWidth: function() { if(!this.scrollbarWidth) { this.scrollbarWidth = PUI.calculateScrollbarWidth(); } return this.scrollbarWidth; } }); })();
'use strict'; var url = require('url'); exports = module.exports = function historyApiFallback(options) { options = options || {}; var logger = getLogger(options); return function(req, res, next) { var headers = req.headers; if (req.method !== 'GET') { logger( 'Not rewriting', req.method, req.url, 'because the method is not GET.' ); return next(); } else if (!headers || typeof headers.accept !== 'string') { logger( 'Not rewriting', req.method, req.url, 'because the client did not send an HTTP accept header.' ); return next(); } else if (headers.accept.indexOf('application/json') === 0) { logger( 'Not rewriting', req.method, req.url, 'because the client prefers JSON.' ); return next(); } else if (!acceptsHtml(headers.accept, options)) { logger( 'Not rewriting', req.method, req.url, 'because the client does not accept HTML.' ); return next(); } var parsedUrl = url.parse(req.url); var rewriteTarget; options.rewrites = options.rewrites || []; for (var i = 0; i < options.rewrites.length; i++) { var rewrite = options.rewrites[i]; var match = parsedUrl.pathname.match(rewrite.from); if (match !== null) { rewriteTarget = evaluateRewriteRule(parsedUrl, match, rewrite.to, req); logger('Rewriting', req.method, req.url, 'to', rewriteTarget); req.url = rewriteTarget; return next(); } } var pathname = parsedUrl.pathname; if (pathname.lastIndexOf('.') > pathname.lastIndexOf('/') && options.disableDotRule !== true) { logger( 'Not rewriting', req.method, req.url, 'because the path includes a dot (.) character.' ); return next(); } rewriteTarget = options.index || '/index.html'; logger('Rewriting', req.method, req.url, 'to', rewriteTarget); req.url = rewriteTarget; next(); }; }; function evaluateRewriteRule(parsedUrl, match, rule, req) { if (typeof rule === 'string') { return rule; } else if (typeof rule !== 'function') { throw new Error('Rewrite rule can only be of type string of function.'); } return rule({ parsedUrl: parsedUrl, match: match, request: req }); } function acceptsHtml(header, options) { options.htmlAcceptHeaders = options.htmlAcceptHeaders || ['text/html', '*/*']; for (var i = 0; i < options.htmlAcceptHeaders.length; i++) { if (header.indexOf(options.htmlAcceptHeaders[i]) !== -1) { return true; } } return false; } function getLogger(options) { if (options && options.logger) { return options.logger; } else if (options && options.verbose) { return console.log.bind(console); } return function(){}; }
(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<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), ShimIE8 = _dereq_('../lib/Shim.IE8'); module.exports = Core; },{"../lib/Core":3,"../lib/Shim.IE8":21}],2:[function(_dereq_,module,exports){ /** * The main collection class. Collections store multiple documents and * can operate on them using the query language to insert, read, update * and delete. */ var Shared, Core, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Crc; Shared = _dereq_('./Shared'); /** * Collection object used to store data. * @constructor */ var Collection = function (name) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name) { this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._groups = []; this._metrics = new Metrics(); this._deferQueue = { insert: [], update: [], remove: [], upsert: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; // Set the subset to itself since it is the root collection this._subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Crc = _dereq_('./Crc'); Core = Shared.modules.Core; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Collection.prototype.crc = Crc; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Get the internal data * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function () { if (this._state !== 'dropped') { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log('Dropping collection ' + this._name); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; if (this._groups && this._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < this._groups.length; i++) { groupArr.push(this._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { this._groups[i].removeCollection(this); } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._name; delete this._data; delete this._groups; delete this._metrics; return true; } } else { return true; } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Gets / sets the db instance this class instance belongs to. * @param {Core=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); } } return this.$super.apply(this, arguments); }); /** * Sets the collection's data to the array of documents passed. * @param data * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = function (data, options, callback) { if (data) { var op = this._metrics.create('setData'); op.start(); options = this.options(options); this.preSetData(data, options, callback); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } op.time('transformIn'); data = this.transformIn(data); op.time('transformIn'); var oldData = [].concat(this._data); this._dataReplace(data); // Update the primary key index op.time('Rebuild Primary Key Index'); this.rebuildPrimaryKeyIndex(options); op.time('Rebuild Primary Key Index'); // Rebuild all other indexes op.time('Rebuild All Other Indexes'); this._rebuildIndexes(); op.time('Rebuild All Other Indexes'); op.time('Resolve chains'); this.chainSend('setData', data, {oldData: oldData}); op.time('Resolve chains'); op.stop(); this.emit('setData', this._data, oldData); } if (callback) { callback(false); } return this; }; /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw('ForerunnerDB.Collection "' + this.name() + '": Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a CRC string jString = JSON.stringify(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert; var returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback(); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj); break; case 'update': returnData.result = this.update(query, obj); break; default: break; } return returnData; } else { if (callback) { callback(); } } return {}; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options) { // Decouple the update data update = this.decouple(update); // Handle transform update = this.transformIn(update); if (this.debug()) { console.log('Updating some collection data for collection "' + this.name() + '"'); } var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (originalDoc) { var newDoc = self.decouple(originalDoc), triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, originalDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(originalDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, originalDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(originalDoc, update, query, options, ''); } return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { op.time('Resolve chains'); this.chainSend('update', { query: query, update: update, dataSet: dataSet }, options); op.time('Resolve chains'); this._onUpdate(updated); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw('ForerunnerDB.Collection "' + this.name() + '": Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return true; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Array} The items that were updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update); }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } var oldDoc = this.decouple(doc), updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, pathInstance, sourceIsArray, updateIsArray, i, k; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': // Ignore some operators operation = true; break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': this._updateIncrement(doc, i, update[i]); updated = true; break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = JSON.stringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (JSON.stringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot addToSet on a key that is not an array! (' + k + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { var tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot splicePush without a $index integer value!'); } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot move without a $index integer value!'); } break; } } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot pop from a key that is not an array! (' + i + ')'); } break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Updates a property on an object depending on if the collection is * currently running data-binding or not. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ Collection.prototype._updateProperty = function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log('ForerunnerDB.Collection: Setting non-data-bound document property "' + prop + '" for collection "' + this.name() + '"'); } }; /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ Collection.prototype._updateIncrement = function (doc, prop, val) { doc[prop] += val; }; /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ Collection.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log('ForerunnerDB.Collection: Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '" for collection "' + this.name() + '"'); } }; /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ Collection.prototype._updateSplicePush = function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }; /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ Collection.prototype._updatePush = function (arr, doc) { arr.push(doc); }; /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ Collection.prototype._updatePull = function (arr, index) { arr.splice(index, 1); }; /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ Collection.prototype._updateMultiply = function (doc, prop, val) { doc[prop] *= val; }; /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ Collection.prototype._updateRename = function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }; /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ Collection.prototype._updateUnset = function (doc, prop) { delete doc[prop]; }; /** * Pops an item from the array stack. * @param {Object} doc The document to modify. * @param {Number=} val Optional, if set to 1 will pop, if set to -1 will shift. * @return {Boolean} * @private */ Collection.prototype._updatePop = function (doc, val) { var updated = false; if (doc.length > 0) { if (val === 1) { doc.pop(); updated = true; } else if (val === -1) { doc.shift(); updated = true; } } return updated; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { var self = this, dataSet, index, dataItem, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } return returnArr; } else { dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } //op.time('Resolve chains'); this.chainSend('remove', { query: query, dataSet: dataSet }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(dataSet); } this.deferEmit('change', {type: 'remove', data: dataSet}); } return dataSet; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Array} An array of documents that were removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj); }; /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. * @private */ Collection.prototype.deferEmit = function () { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout if (this._changeTimeout) { clearTimeout(this._changeTimeout); } // Set a timeout this._changeTimeout = setTimeout(function () { if (self.debug()) { console.log('ForerunnerDB.Collection: Emitting ' + args[0]); } self.emit.apply(self, args); }, 100); } else { this.emit.apply(this, arguments); } }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. */ Collection.prototype.processQueue = function (type, callback) { var queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type]; if (queue.length) { var self = this, dataArr; // Process items up to the threshold if (queue.length) { if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } this[type](dataArr); } // Queue another process setTimeout(function () { self.processQueue(type, callback); }, deferTime); } else { if (callback) { callback(); } } }; /** * Inserts a document or array of documents into the collection. * @param {Object||Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype.insert = function (data, index, callback) { if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * Inserts a document or array of documents into the collection. * @param {Object||Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype._insertHandle = function (data, index, callback) { var self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } //op.time('Resolve chains'); this.chainSend('insert', data, {index: index}); //op.time('Resolve chains'); this._onInsert(inserted, failed); if (callback) { callback(); } this.deferEmit('change', {type: 'insert', data: inserted}); return { inserted: inserted, failed: failed }; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc; this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return false; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, jString = JSON.stringify(doc); // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc); this._primaryCrc.uniqueSet(doc[this._primaryKey], jString); this._crcLookup.uniqueSet(jString, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, jString = JSON.stringify(doc); // Remove from primary key index this._primaryIndex.unSet(doc[this._primaryKey]); this._primaryCrc.unSet(doc[this._primaryKey]); this._crcLookup.unSet(jString); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Returns the index of the document identified by the passed item's primary key. * @param {Object} item The item whose primary key should be used to lookup. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (item) { return this._data.indexOf( this._primaryIndex.get( item[this._primaryKey] ) ); }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() ._subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Gets the collection that this collection is a subset of. * @returns {Collection} */ Collection.prototype.subsetOf = function () { return this.__subsetOf; }; /** * Sets the collection that this collection is a subset of. * @param {Collection} collection The collection to set as the parent of this subset. * @returns {*} This object for chaining. * @private */ Collection.prototype._subsetOf = function (collection) { this.__subsetOf = collection; return this; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = JSON.stringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options) { // TODO: This method is quite long, break into smaller pieces query = query || {}; options = this.options(options); var op = this._metrics.create('find'), self = this, analysis, finalQuery, scanLength, requiresTableScan = true, resultArr, joinCollectionIndex, joinIndex, joinCollection = {}, joinQuery, joinPath, joinCollectionName, joinCollectionInstance, joinMatch, joinMatchIndex, joinSearch, joinMulti, joinRequire, joinFindResults, resultCollectionName, resultIndex, resultRemove = [], index, i, matcherTmpOptions = {}, matcher = function (doc) { return self._match(doc, query, 'and', matcherTmpOptions); }; op.start(); if (query) { // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(query, options, op); op.time('analyseQuery'); op.data('analysis', analysis); if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get an instance reference to the join collections op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinCollectionName = analysis.joinsOn[joinIndex]; joinPath = new Path(analysis.joinQueries[joinCollectionName]); joinQuery = joinPath.value(query)[0]; joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery); } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } op.time('tableScan: ' + scanLength); } if (options.limit && resultArr && resultArr.length > options.limit) { resultArr.length = options.limit; op.data('limit', options.limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { // Set the key to store the join result in to the collection name by default resultCollectionName = joinCollectionName; // Get the join collection instance from the DB joinCollectionInstance = this._db.collection(joinCollectionName); // Get the match data for the join joinMatch = options.$join[joinCollectionIndex][joinCollectionName]; // Loop our result data array for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearch = {}; joinMulti = false; joinRequire = false; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$as': // Rename the collection when stored in the result document resultCollectionName = joinMatch[joinMatchIndex]; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatch[joinMatchIndex]; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatch[joinMatchIndex]; break; default: // Check for a double-dollar which is a back-reference to the root collection item if (joinMatchIndex.substr(0, 3) === '$$.') { // Back reference // TODO: Support complex joins } break; } } else { // TODO: Could optimise this by caching path objects // Get the data to match against and store in the search object joinSearch[joinMatchIndex] = new Path(joinMatch[joinMatchIndex]).value(resultArr[resultIndex])[0]; } } } // Do a find on the target collection against the match data joinFindResults = joinCollectionInstance.find(joinSearch); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultArr[resultIndex]); } } } } } op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); for (i = 0; i < resultRemove.length; i++) { index = resultArr.indexOf(resultRemove[i]); if (index > -1) { resultArr.splice(index, 1); } } op.time('removalQueue'); } if (options.transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); op.stop(); resultArr.__fdbOp = op; return resultArr; } else { op.stop(); resultArr = []; resultArr.__fdbOp = op; return resultArr; } }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @returns {Number} */ Collection.prototype.indexOf = function (query) { var item = this.find(query, {$decouple: false})[0]; if (item) { return this._data.indexOf(item); } }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformIn(data[i]); } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformOut(data[i]); } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = sortKey; sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } }; /** * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets buckets = this.bucket(keyObj.___fdbKey, arr); // Loop buckets and sort contents for (i in buckets) { if (buckets.hasOwnProperty(i)) { arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[i])); } } return finalArr; } else { return this._sort(keyObj, arr); } }; /** * Sorts array by individual sort path. * @param key * @param arr * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw('ForerunnerDB.Collection "' + this.name() + '": $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ Collection.prototype.bucket = function (key, arr) { var i, buckets = {}; for (i = 0; i < arr.length; i++) { buckets[arr[i][key]] = buckets[arr[i][key]] || []; buckets[arr[i][key]].push(arr[i]); } return buckets; }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [this._name], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinCollectionIndex, joinCollectionName, joinCollections = [], joinCollectionReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.countKeys(query); if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); analysis.indexMatch.push({ lookup: this._primaryIndex.lookup(query, options), keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { // Loop the join collections and keep a reference to them for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { joinCollections.push(joinCollectionName); // Check if the join uses an $as operator if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) { joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as); } else { joinCollectionReferences.push(joinCollectionName); } } } } // Loop the join collection references and determine if the query references // any of the collections that are used in the join. If there no queries against // joined collections the find method can use a code path optimised for this. // Queries against joined collections requires the joined collections to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinCollectionReferences.length; index++) { // Check if the query references any collection data that the join will create queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], ''); if (queryPath) { analysis.joinQueries[joinCollections[index]] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinCollections; analysis.queriesOn = analysis.queriesOn.concat(joinCollections); } return analysis; }; /** * Checks if the passed query references this collection. * @param query * @param collection * @param path * @returns {*} * @private */ Collection.prototype._queryReferencesCollection = function (query, collection, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === collection) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesCollection(query[i], collection, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param match * @param path * @param subDocQuery * @param subDocOptions * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docArr = this.find(match), docCount = docArr.length, docIndex, subDocArr, subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } resultObj.subDocs.push(subDocResults); resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.noStats) { return resultObj.subDocs; } if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } return resultObj; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { switch (options.type) { case 'hashed': index = new IndexHashMap(keys, options, this); break; case 'btree': index = new IndexBinaryTree(keys, options, this); break; default: // Default index = new IndexHashMap(keys, options, this); break; } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; } // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pm = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pm === collection.primaryKey()) { // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pm])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pm]) === collection._primaryCrc.get(arrItem[pm])) { // Matching objects, no update required } else { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert requried diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pm])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Collection diffing requires that both collections have the same primary key!'); } return diff; }; /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @param {String} collectionName The name of the collection. * @param {String=} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ Core.prototype.collection = function (collectionName, primaryKey) { if (collectionName) { if (!this._collection[collectionName]) { if (this.debug()) { console.log('Creating collection ' + collectionName); } } this._collection[collectionName] = this._collection[collectionName] || new Collection(collectionName).db(this); if (primaryKey !== undefined) { this._collection[collectionName].primaryKey(primaryKey); } return this._collection[collectionName]; } else { throw('ForerunnerDB.Core "' + this.name() + '": Cannot get collection with undefined name!'); } }; /** * Determine if a collection with the passed name already exists. * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Core.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Core.prototype.collections = function (search) { var arr = [], i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { if (search) { if (search.exec(i)) { arr.push({ name: i, count: this._collection[i].count() }); } } else { arr.push({ name: i, count: this._collection[i].count() }); } } } return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Crc":4,"./IndexBinaryTree":5,"./IndexHashMap":6,"./KeyValueStore":7,"./Metrics":8,"./Path":19,"./Shared":20}],3:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ var Shared, Collection, Metrics, Crc, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * The main ForerunnerDB core object. * @constructor */ var Core = function (name) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Core.prototype.moduleLoaded = Overload({ /** * Checks if a module has been loaded into the database. * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.ChainReactor'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Crc = _dereq_('./Crc.js'); Core.prototype._isServer = false; /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Core.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Core.prototype.crc = Crc; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Core.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Core.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Core.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Core.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Core.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Core.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; /** * Drops all collections in the database. * @param {Function=} callback Optional callback method. */ Core.prototype.drop = function (callback) { if (this._state !== 'dropped') { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); } return true; }; module.exports = Core; },{"./Collection.js":2,"./Crc.js":4,"./Metrics.js":8,"./Overload":18,"./Shared":20}],4:[function(_dereq_,module,exports){ var crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); module.exports = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; },{}],5:[function(_dereq_,module,exports){ /* name id rebuild state match lookup */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), btree = function () {}; /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new (btree.create(2, this.sortAsc))(); this._size = 0; this._id = this._itemKeyHash(keys, keys); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree = new (btree.create(2, this.sortAsc))(); if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // We store multiple items that match a key inside an array // that is then stored against that key in the tree... // Check if item exists for this key already keyArr = this._btree.get(dataItemHash); // Check if the array exists if (keyArr === undefined) { // Generate an array for this key first keyArr = []; // Put the new array into the tree under the key this._btree.put(dataItemHash, keyArr); } // Push the item into the array keyArr.push(dataItem); this._size++; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr, itemIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Try and get the array for the item hash key keyArr = this._btree.get(dataItemHash); if (keyArr !== undefined) { // The key array exits, remove the item from the key array itemIndex = keyArr.indexOf(dataItem); if (itemIndex > -1) { // Check the length of the array if (keyArr.length === 1) { // This item is the last in the array, just kill the tree entry this._btree.del(dataItemHash); } else { // Remove the item keyArr.splice(itemIndex, 1); } this._size--; } } }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexBinaryTree.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./Path":19,"./Shared":20}],6:[function(_dereq_,module,exports){ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":19,"./Shared":20}],7:[function(_dereq_,module,exports){ var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} obj A lookup query, can be a string key, an array of string keys, * an object with further query clauses or a regular expression that should be * run against all keys. * @returns {*} */ KeyValueStore.prototype.lookup = function (obj) { var pKeyVal = obj[this._primaryKey], arrIndex, arrCount, lookupItem, result; if (pKeyVal instanceof Array) { // An array of primary keys, find all matches arrCount = pKeyVal.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this._data[pKeyVal[arrIndex]]; if (lookupItem) { result.push(lookupItem); } } return result; } else if (pKeyVal instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.test(arrIndex)) { result.push(this._data[arrIndex]); } } } return result; } else if (typeof pKeyVal === 'object') { // The primary key clause is an object, now we have to do some // more extensive searching if (pKeyVal.$ne) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (arrIndex !== pKeyVal.$ne) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$in.indexOf(arrIndex) > -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$nin.indexOf(arrIndex) === -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) { result = result.concat(this.lookup(pKeyVal.$or[arrIndex])); } return result; } } else { // Key is a basic lookup from string lookupItem = this._data[pKeyVal]; if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } }; /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":20}],8:[function(_dereq_,module,exports){ var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":17,"./Shared":20}],9:[function(_dereq_,module,exports){ var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],10:[function(_dereq_,module,exports){ var ChainReactor = { chain: function (obj) { this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, count = arr.length, index; for (index = 0; index < count; index++) { arr[index].chainReceive(this, type, data, options); } } }, chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }; // Fire our internal handler if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],11:[function(_dereq_,module,exports){ var idCounter = 0, Overload = _dereq_('./Overload'), Common; Common = { /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined) { if (!copies) { return JSON.parse(JSON.stringify(data)); } else { var i, json = JSON.stringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(JSON.parse(json)); } return copyArr; } } return undefined; }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]) }; module.exports = Common; },{"./Overload":18}],12:[function(_dereq_,module,exports){ var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],13:[function(_dereq_,module,exports){ var Overload = _dereq_('./Overload'); var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), off: new Overload({ 'string': function (event) { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } return this; }, 'string, function': function (event, listener) { var arr, index; if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } return this; }, 'string, *, function': function (event, id, listener) { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } }, 'string, *': function (event, id) { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } }), emit: function (event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arrIndex, arrCount; // Handle global emit if (this._listeners[event]['*']) { var arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key var listenerIdArr = this._listeners[event], listenerIdCount, listenerIdIndex; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } return this; } }; module.exports = Events; },{"./Overload":18}],14:[function(_dereq_,module,exports){ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison if (source.localeCompare(test)) { matchedAll = false; } } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Reset operation flag operation = false; substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (typeof(source) === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$ne': // Not equals return source != test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (inArr[inArrIndex] === source) { return true; } } return false; } else { throw('ForerunnerDB.Mixin.Matching "' + this.name() + '": Cannot use an $in operator on a non-array key: ' + key); } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (notInArr[notInArrIndex] === source) { return false; } } return true; } else { throw('ForerunnerDB.Mixin.Matching "' + this.name() + '": Cannot use a $nin operator on a non-array key: ' + key); } break; case '$distinct': // Ensure options holds an distinct lookup options.distinctLookup = options.distinctLookup || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.distinctLookup[distinctProp] = options.distinctLookup[distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.distinctLookup[distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.distinctLookup[distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; } return -1; } }; module.exports = Matching; },{}],15:[function(_dereq_,module,exports){ var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],16:[function(_dereq_,module,exports){ var Triggers = { addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method }); return true; } return false; }, removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger does not exist, create it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, willTrigger: function (type, phase) { return this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length; }, processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } // Triggers all ran without issue, return a success (true) return true; } }, _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{}],17:[function(_dereq_,module,exports){ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":19,"./Shared":20}],18:[function(_dereq_,module,exports){ /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {Object} def * @returns {Function} * @constructor */ var Overload = function (def) { if (def) { var index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return def[index].apply(this, arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return def[lookup].apply(this, arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return def[lookup + ',...'].apply(this, arguments); } } } } throw('ForerunnerDB.Overload "' + this.name() + '": Overloaded method does not have a matching signature for the passed arguments: ' + JSON.stringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ var generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; module.exports = Overload; },{}],19:[function(_dereq_,module,exports){ var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path) { if (obj !== undefined && typeof obj === 'object') { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr = [], i, k; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i])); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":20}],20:[function(_dereq_,module,exports){ var Shared = { version: '1.3.14', modules: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { this.modules[name] = module; this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { this.modules[name]._fdbFinished = true; this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { callback(name, this.modules[name]); } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, /** * Adds the properties and methods defined in the mixin to the passed object. * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ mixin: function (obj, mixinName) { var system = this.mixins[mixinName]; if (system) { for (var i in system) { if (system.hasOwnProperty(i)) { obj[i] = system[i]; } } } else { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } }, /** * Generates a generic getter/setter method for the passed method name. * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @param arr * @returns {Function} * @constructor */ overload: _dereq_('./Overload'), /** * Define the mixins that other modules can use as required. */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":9,"./Mixin.ChainReactor":10,"./Mixin.Common":11,"./Mixin.Constants":12,"./Mixin.Events":13,"./Mixin.Matching":14,"./Mixin.Sorting":15,"./Mixin.Triggers":16,"./Overload":18}],21:[function(_dereq_,module,exports){ if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { 'use strict'; if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } if (typeof Object.create !== 'function') { Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype !== 'object') { throw TypeError('Argument must be an object'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; return result; }; })(); } // Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14e if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this === null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; } module.exports = {}; },{}]},{},[1]);
'use strict'; module.exports = { set: function (v) { this.setProperty('counter-reset', v); }, get: function () { return this.getPropertyValue('counter-reset'); }, enumerable: true };
'use strict'; /** * Watcher for separate Js files files */ module.exports = () => { return tars.packages.chokidar.watch( `markup/${tars.config.fs.staticFolderName}/${tars.cssPreproc.name}/separate-css/**/*.css`, tars.options.watch ).on('all', (event, watchedPath) => { tars.helpers.watcherLog(event, watchedPath); tars.packages.gulp.start('css:move-separate'); }); };
/* * transports.js: Set of all transports Winston knows about * * (C) 2010 Charlie Robbins * MIT LICENCE * */ var fs = require('fs'), path = require('path'), common = require('./common'); var transports = exports; // // Setup all transports as lazy-loaded getters. // fs.readdirSync(path.join(__dirname, 'transports')).forEach(function (file) { var transport = file.replace('.js', ''), name = common.capitalize(transport); if (transport === 'transport') { return; } transports.__defineGetter__(name, function () { return require('./transports/' + transport)[name]; }); });
var util = require('util') var resolve = require('url').resolve var SourceMapConsumer = require('source-map').SourceMapConsumer var WeakMap = require('core-js/es6/weak-map') var _ = require('lodash') var log = require('./logger').create('reporter') var MultiReporter = require('./reporters/multi') var baseReporterDecoratorFactory = require('./reporters/base').decoratorFactory var createErrorFormatter = function (config, emitter, SourceMapConsumer) { var basePath = config.basePath var lastServedFiles = [] emitter.on('file_list_modified', function (files) { lastServedFiles = files.served }) var findFile = function (path) { for (var i = 0; i < lastServedFiles.length; i++) { if (lastServedFiles[i].path === path) { return lastServedFiles[i] } } return null } var URL_REGEXP = new RegExp('(?:https?:\\/\\/' + config.hostname + '(?:\\:' + config.port + ')?' + ')?\\/?' + '(base/|absolute)' + // prefix, including slash for base/ to create relative paths. '((?:[A-z]\\:)?[^\\?\\s\\:]*)' + // path '(\\?\\w*)?' + // sha '(\\:(\\d+))?' + // line '(\\:(\\d+))?' + // column '', 'g') var getSourceMapConsumer = (function () { var cache = new WeakMap() return function (sourceMap) { if (!cache.has(sourceMap)) { cache.set(sourceMap, new SourceMapConsumer(sourceMap)) } return cache.get(sourceMap) } }()) return function (input, indentation) { indentation = _.isString(indentation) ? indentation : '' if (_.isError(input)) { input = input.message } else if (_.isEmpty(input)) { input = '' } else if (!_.isString(input)) { input = JSON.stringify(input, null, indentation) } // remove domain and timestamp from source files // and resolve base path / absolute path urls into absolute path var msg = input.replace(URL_REGEXP, function (_, prefix, path, __, ___, line, ____, column) { // Find the file using basePath + path, but use the more readable path down below. var file = findFile(prefix === 'base/' ? basePath + '/' + path : path) if (file && file.sourceMap && line) { line = parseInt(line || '0', 10) column = parseInt(column, 10) // When no column is given and we default to 0, it doesn't make sense to only search for smaller // or equal columns in the sourcemap, let's search for equal or greater columns. var bias = column ? SourceMapConsumer.GREATEST_LOWER_BOUND : SourceMapConsumer.LEAST_UPPER_BOUND try { var original = getSourceMapConsumer(file.sourceMap) .originalPositionFor({line: line, column: (column || 0), bias: bias}) // Source maps often only have a local file name, resolve to turn into a full path if // the path is not absolute yet. var sourcePath = resolve(path, original.source) var formattedColumn = column ? util.format(':%s', column) : '' return util.format('%s:%d:%d <- %s:%d%s', sourcePath, original.line, original.column, path, line, formattedColumn) } catch (e) { log.warn('SourceMap position not found for trace: %s', msg) // Fall back to non-source-mapped formatting. } } var result = path + (line ? ':' + line : '') + (column ? ':' + column : '') return result || prefix }) // indent every line if (indentation) { msg = indentation + msg.replace(/\n/g, '\n' + indentation) } // allow the user to format the error if (config.formatError) { msg = config.formatError(msg) } return msg + '\n' } } var createReporters = function (names, config, emitter, injector) { var errorFormatter = createErrorFormatter(config, emitter, SourceMapConsumer) var reporters = [] // TODO(vojta): instantiate all reporters through DI names.forEach(function (name) { if (['dots', 'progress'].indexOf(name) !== -1) { var Cls = require('./reporters/' + name) var ClsColor = require('./reporters/' + name + '_color') reporters.push(new Cls(errorFormatter, config.reportSlowerThan, config.colors, config.browserConsoleLogOptions)) return reporters.push(new ClsColor(errorFormatter, config.reportSlowerThan, config.colors, config.browserConsoleLogOptions)) } var locals = { baseReporterDecorator: ['factory', baseReporterDecoratorFactory], formatError: ['value', errorFormatter] } try { log.debug('Trying to load reporter: %s', name) reporters.push(injector.createChild([locals], ['reporter:' + name]).get('reporter:' + name)) } catch (e) { if (e.message.indexOf('No provider for "reporter:' + name + '"') !== -1) { log.error('Can not load reporter "%s", it is not registered!\n ' + 'Perhaps you are missing some plugin?', name) } else { log.error('Can not load "%s"!\n ' + e.stack, name) } emitter.emit('load_error', 'reporter', name) return } var colorName = name + '_color' if (names.indexOf(colorName) !== -1) { return } try { log.debug('Trying to load color-version of reporter: %s (%s)', name, colorName) reporters.push(injector.createChild([locals], ['reporter:' + name + '_color']).get('reporter:' + name)) } catch (e) { log.debug('Couldn\'t load color-version.') } }) // bind all reporters reporters.forEach(function (reporter) { emitter.bind(reporter) }) return new MultiReporter(reporters) } createReporters.$inject = [ 'config.reporters', 'config', 'emitter', 'injector' ] // PUBLISH exports.createReporters = createReporters
module.exports = require("github:jmcriffey/bower-traceur-runtime@0.0.88/traceur-runtime");
odoo.define('website_payment.website_payment', function (require) { "use strict"; var website = require('website.website'); var ajax = require('web.ajax'); if(!$('.o_website_payment').length) { return $.Deferred().reject("DOM doesn't contain '.o_website_payment'"); } // When clicking on payment button: create the tx using json then continue to the acquirer var $payment = $(".o_website_payment_form"); $payment.on("click", 'button[type="submit"],button[name="submit"]', function (ev) { ev.preventDefault(); ev.stopPropagation(); $(ev.currentTarget).attr('disabled', true); $(ev.currentTarget).prepend('<i class="fa fa-refresh fa-spin"></i> '); var $form = $(ev.currentTarget).parents('form'); var data =$("div[class~='o_website_payment_new_payment']").data(); console.log(data); ajax.jsonRpc('/website_payment/transaction/', 'call', data).then(function (result) { $form.submit(); }); function getFormData($form){ var unindexed_array = $form.serializeArray(); var indexed_array = {}; $.map(unindexed_array, function(n, i){ indexed_array[n.name] = n.value; }); return indexed_array; } }); });
'use strict'; /** * Binds a CodeMirror widget to a <textarea> element. */ angular.module('ui.codemirror', []) .constant('uiCodemirrorConfig', {}) .directive('uiCodemirror', uiCodemirrorDirective); /** * @ngInject */ function uiCodemirrorDirective($timeout, uiCodemirrorConfig) { return { restrict: 'EA', require: '?ngModel', compile: function compile() { // Require CodeMirror if (angular.isUndefined(window.CodeMirror)) { throw new Error('ui-codemirror needs CodeMirror to work... (o rly?)'); } return postLink; } }; function postLink(scope, iElement, iAttrs, ngModel) { var codemirrorOptions = angular.extend( { value: iElement.text() }, uiCodemirrorConfig.codemirror || {}, scope.$eval(iAttrs.uiCodemirror), scope.$eval(iAttrs.uiCodemirrorOpts) ); var codemirror = newCodemirrorEditor(iElement, codemirrorOptions); configOptionsWatcher( codemirror, iAttrs.uiCodemirror || iAttrs.uiCodemirrorOpts, scope ); configNgModelLink(codemirror, ngModel, scope); configUiRefreshAttribute(codemirror, iAttrs.uiRefresh, scope); // Allow access to the CodeMirror instance through a broadcasted event // eg: $broadcast('CodeMirror', function(cm){...}); scope.$on('CodeMirror', function(event, callback) { if (angular.isFunction(callback)) { callback(codemirror); } else { throw new Error('the CodeMirror event requires a callback function'); } }); // onLoad callback if (angular.isFunction(codemirrorOptions.onLoad)) { codemirrorOptions.onLoad(codemirror); } } function newCodemirrorEditor(iElement, codemirrorOptions) { var codemirrot; if (iElement[0].tagName === 'TEXTAREA') { // Might bug but still ... codemirrot = window.CodeMirror.fromTextArea(iElement[0], codemirrorOptions); } else { iElement.html(''); codemirrot = new window.CodeMirror(function(cm_el) { iElement.append(cm_el); }, codemirrorOptions); } return codemirrot; } function configOptionsWatcher(codemirrot, uiCodemirrorAttr, scope) { if (!uiCodemirrorAttr) { return; } var codemirrorDefaultsKeys = Object.keys(window.CodeMirror.defaults); scope.$watch(uiCodemirrorAttr, updateOptions, true); function updateOptions(newValues, oldValue) { if (!angular.isObject(newValues)) { return; } codemirrorDefaultsKeys.forEach(function(key) { if (newValues.hasOwnProperty(key)) { if (oldValue && newValues[key] === oldValue[key]) { return; } codemirrot.setOption(key, newValues[key]); } }); } } function configNgModelLink(codemirror, ngModel, scope) { if (!ngModel) { return; } // CodeMirror expects a string, so make sure it gets one. // This does not change the model. ngModel.$formatters.push(function(value) { if (angular.isUndefined(value) || value === null) { return ''; } else if (angular.isObject(value) || angular.isArray(value)) { throw new Error('ui-codemirror cannot use an object or an array as a model'); } return value; }); // Override the ngModelController $render method, which is what gets called when the model is updated. // This takes care of the synchronizing the codeMirror element with the underlying model, in the case that it is changed by something else. ngModel.$render = function() { //Code mirror expects a string so make sure it gets one //Although the formatter have already done this, it can be possible that another formatter returns undefined (for example the required directive) var safeViewValue = ngModel.$viewValue || ''; codemirror.setValue(safeViewValue); }; // Keep the ngModel in sync with changes from CodeMirror codemirror.on('change', function(instance) { var newValue = instance.getValue(); if (newValue !== ngModel.$viewValue) { scope.$evalAsync(function() { ngModel.$setViewValue(newValue); }); } }); } function configUiRefreshAttribute(codeMirror, uiRefreshAttr, scope) { if (!uiRefreshAttr) { return; } scope.$watch(uiRefreshAttr, function(newVal, oldVal) { // Skip the initial watch firing if (newVal !== oldVal) { $timeout(function() { codeMirror.refresh(); }); } }); } } uiCodemirrorDirective.$inject = ["$timeout", "uiCodemirrorConfig"];
/** * Globalize Runtime v1.1.0-rc.3 * * http://github.com/jquery/globalize * * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2015-10-02T16:26Z */ /*! * Globalize Runtime v1.1.0-rc.3 2015-10-02T16:26Z Released under the MIT license * http://git.io/TrdQbw */ (function( root, factory ) { // UMD returnExports if ( typeof define === "function" && define.amd ) { // AMD define([ "../globalize-runtime" ], factory ); } else if ( typeof exports === "object" ) { // Node, CommonJS module.exports = factory( require( "../globalize-runtime" ) ); } else { // Extend global factory( root.Globalize ); } }(this, function( Globalize ) { var runtimeKey = Globalize._runtimeKey, validateParameterType = Globalize._validateParameterType; /** * Function inspired by jQuery Core, but reduced to our use case. */ var isPlainObject = function( obj ) { return obj !== null && "" + obj === "[object Object]"; }; var validateParameterTypeMessageVariables = function( value, name ) { validateParameterType( value, name, value === undefined || isPlainObject( value ) || Array.isArray( value ), "Array or Plain Object" ); }; var messageFormatterFn = function( formatter ) { return function messageFormatter( variables ) { if ( typeof variables === "number" || typeof variables === "string" ) { variables = [].slice.call( arguments, 0 ); } validateParameterTypeMessageVariables( variables, "variables" ); return formatter( variables ); }; }; Globalize._messageFormatterFn = messageFormatterFn; /* jshint ignore:start */ Globalize._messageFormat = (function() { var number = function (value, offset) { if (isNaN(value)) throw new Error("'" + value + "' isn't a number."); return value - (offset || 0); }; var plural = function (value, offset, lcfunc, data, isOrdinal) { if ({}.hasOwnProperty.call(data, value)) return data[value](); if (offset) value -= offset; var key = lcfunc(value, isOrdinal); if (key in data) return data[key](); return data.other(); }; var select = function (value, data) { if ({}.hasOwnProperty.call(data, value)) return data[value](); return data.other() }; return {number: number, plural: plural, select: select}; }()); /* jshint ignore:end */ Globalize._validateParameterTypeMessageVariables = validateParameterTypeMessageVariables; Globalize.messageFormatter = Globalize.prototype.messageFormatter = function( /* path */ ) { return Globalize[ runtimeKey( "messageFormatter", this._locale, [].slice.call( arguments, 0 ) ) ]; }; Globalize.formatMessage = Globalize.prototype.formatMessage = function( path /* , variables */ ) { return this.messageFormatter( path ).apply( {}, [].slice.call( arguments, 1 ) ); }; return Globalize; }));
/*! * numbro.js language configuration * language : spanish Spain * author : Hernan Garcia : https://github.com/hgarcia */ !function(){var a={delimiters:{thousands:".",decimal:","},abbreviations:{thousand:"k",million:"mm",billion:"b",trillion:"t"},ordinal:function(a){var b=a%10;return 1===b||3===b?"er":2===b?"do":7===b||0===b?"mo":8===b?"vo":9===b?"no":"to"},currency:{symbol:"€",position:"postfix"},defaults:{currencyFormat:",0000 a"},formats:{fourDigits:"0000 a",fullWithTwoDecimals:",0.00 $",fullWithTwoDecimalsNoCurrency:",0.00",fullWithNoDecimals:",0 $"}};"undefined"!=typeof module&&module.exports&&(module.exports=a),"undefined"!=typeof window&&this.numbro&&this.numbro.language&&this.numbro.language("es",a)}();
/* Highcharts JS v5.0.11 (2017-05-04) 3D features for Highcharts JS @license: www.highcharts.com/license */ (function(r){"object"===typeof module&&module.exports?module.exports=r:r(Highcharts)})(function(r){(function(a){var m=a.deg2rad,h=a.pick;a.perspective=function(v,l,F){var f=l.options.chart.options3d,n=F?l.inverted:!1,g=l.plotWidth/2,q=l.plotHeight/2,d=f.depth/2,e=h(f.depth,1)*h(f.viewDistance,0),c=l.scale3d||1,b=m*f.beta*(n?-1:1),f=m*f.alpha*(n?-1:1),k=Math.cos(f),t=Math.cos(-b),B=Math.sin(f),w=Math.sin(-b);F||(g+=l.plotLeft,q+=l.plotTop);return a.map(v,function(b){var a,h;h=(n?b.y:b.x)-g;var f=(n? b.x:b.y)-q,u=(b.z||0)-d;a=t*h-w*u;b=-B*w*h+k*f-t*B*u;h=k*w*h+B*f+k*t*u;f=0<e&&e<Number.POSITIVE_INFINITY?e/(h+d+e):1;a=a*f*c+g;b=b*f*c+q;return{x:n?b:a,y:n?a:b,z:h*c+d}})};a.pointCameraDistance=function(a,l){var v=l.options.chart.options3d,f=l.plotWidth/2;l=l.plotHeight/2;v=h(v.depth,1)*h(v.viewDistance,0)+v.depth;return Math.sqrt(Math.pow(f-a.plotX,2)+Math.pow(l-a.plotY,2)+Math.pow(v-a.plotZ,2))}})(r);(function(a){function m(b){var c=0,a,A;for(a=0;a<b.length;a++)A=(a+1)%b.length,c+=b[a].x*b[A].y- b[A].x*b[a].y;return c/2}function h(b,c,a,A,k,d,e,f){var p=[],D=d-k;return d>k&&d-k>Math.PI/2+.0001?(p=p.concat(h(b,c,a,A,k,k+Math.PI/2,e,f)),p=p.concat(h(b,c,a,A,k+Math.PI/2,d,e,f))):d<k&&k-d>Math.PI/2+.0001?(p=p.concat(h(b,c,a,A,k,k-Math.PI/2,e,f)),p=p.concat(h(b,c,a,A,k-Math.PI/2,d,e,f))):["C",b+a*Math.cos(k)-a*y*D*Math.sin(k)+e,c+A*Math.sin(k)+A*y*D*Math.cos(k)+f,b+a*Math.cos(d)+a*y*D*Math.sin(d)+e,c+A*Math.sin(d)-A*y*D*Math.cos(d)+f,b+a*Math.cos(d)+e,c+A*Math.sin(d)+f]}var v=Math.cos,l=Math.PI, F=Math.sin,f=a.animObject,n=a.charts,g=a.color,q=a.defined,d=a.deg2rad,e=a.each,c=a.extend,b=a.inArray,k=a.map,t=a.merge,B=a.perspective,w=a.pick,x=a.SVGElement,C=a.SVGRenderer,z=a.wrap,y=4*(Math.sqrt(2)-1)/3/(l/2);C.prototype.toLinePath=function(b,a){var c=[];e(b,function(b){c.push("L",b.x,b.y)});b.length&&(c[0]="M",a&&c.push("Z"));return c};C.prototype.cuboid=function(b){var c=this.g(),k=c.destroy;b=this.cuboidPath(b);c.attr({"stroke-linejoin":"round"});c.front=this.path(b[0]).attr({"class":"highcharts-3d-front"}).add(c); c.top=this.path(b[1]).attr({"class":"highcharts-3d-top"}).add(c);c.side=this.path(b[2]).attr({"class":"highcharts-3d-side"}).add(c);c.fillSetter=function(b){this.front.attr({fill:b});this.top.attr({fill:g(b).brighten(.1).get()});this.side.attr({fill:g(b).brighten(-.1).get()});this.color=b;return this};c.opacitySetter=function(b){this.front.attr({opacity:b});this.top.attr({opacity:b});this.side.attr({opacity:b});return this};c.attr=function(b,c){if("string"===typeof b&&"undefined"!==typeof c){var k= b;b={};b[k]=c}if(b.shapeArgs||q(b.x))b=this.renderer.cuboidPath(b.shapeArgs||b),this.front.attr({d:b[0]}),this.top.attr({d:b[1]}),this.side.attr({d:b[2]});else return a.SVGElement.prototype.attr.call(this,b);return this};c.animate=function(b,c,a){q(b.x)&&q(b.y)?(b=this.renderer.cuboidPath(b),this.front.animate({d:b[0]},c,a),this.top.animate({d:b[1]},c,a),this.side.animate({d:b[2]},c,a),this.attr({zIndex:-b[3]})):b.opacity?(this.front.animate(b,c,a),this.top.animate(b,c,a),this.side.animate(b,c,a)): x.prototype.animate.call(this,b,c,a);return this};c.destroy=function(){this.front.destroy();this.top.destroy();this.side.destroy();return k.call(this)};c.attr({zIndex:-b[3]});return c};a.SVGRenderer.prototype.cuboidPath=function(b){function c(b){return w[b]}var a=b.x,d=b.y,e=b.z,f=b.height,D=b.width,h=b.depth,q=n[this.chartIndex],t,g,l=q.options.chart.options3d.alpha,u=0,w=[{x:a,y:d,z:e},{x:a+D,y:d,z:e},{x:a+D,y:d+f,z:e},{x:a,y:d+f,z:e},{x:a,y:d+f,z:e+h},{x:a+D,y:d+f,z:e+h},{x:a+D,y:d,z:e+h},{x:a, y:d,z:e+h}],w=B(w,q,b.insidePlotArea);g=function(b,a){var d=[[],-1];b=k(b,c);a=k(a,c);0>m(b)?d=[b,0]:0>m(a)&&(d=[a,1]);return d};t=g([3,2,1,0],[7,6,5,4]);b=t[0];D=t[1];t=g([1,6,7,0],[4,5,2,3]);f=t[0];h=t[1];t=g([1,2,5,6],[0,7,4,3]);g=t[0];t=t[1];1===t?u+=1E4*(1E3-a):t||(u+=1E4*a);u+=10*(!h||0<=l&&180>=l||360>l&&357.5<l?q.plotHeight-d:10+d);1===D?u+=100*e:D||(u+=100*(1E3-e));u=-Math.round(u);return[this.toLinePath(b,!0),this.toLinePath(f,!0),this.toLinePath(g,!0),u]};a.SVGRenderer.prototype.arc3d= function(a){function k(a){var c=!1,k={};a=t(a);for(var d in a)-1!==b(d,q)&&(k[d]=a[d],delete a[d],c=!0);return c?k:!1}var p=this.g(),h=p.renderer,q="x y r innerR start end".split(" ");a=t(a);a.alpha*=d;a.beta*=d;p.top=h.path();p.side1=h.path();p.side2=h.path();p.inn=h.path();p.out=h.path();p.onAdd=function(){var b=p.parentGroup,a=p.attr("class");p.top.add(p);e(["out","inn","side1","side2"],function(c){p[c].addClass(a+" highcharts-3d-side").add(b)})};p.setPaths=function(b){var a=p.renderer.arc3dPath(b), c=100*a.zTop;p.attribs=b;p.top.attr({d:a.top,zIndex:a.zTop});p.inn.attr({d:a.inn,zIndex:a.zInn});p.out.attr({d:a.out,zIndex:a.zOut});p.side1.attr({d:a.side1,zIndex:a.zSide1});p.side2.attr({d:a.side2,zIndex:a.zSide2});p.zIndex=c;p.attr({zIndex:c});b.center&&(p.top.setRadialReference(b.center),delete b.center)};p.setPaths(a);p.fillSetter=function(b){var a=g(b).brighten(-.1).get();this.fill=b;this.side1.attr({fill:a});this.side2.attr({fill:a});this.inn.attr({fill:a});this.out.attr({fill:a});this.top.attr({fill:b}); return this};e(["opacity","translateX","translateY","visibility"],function(b){p[b+"Setter"]=function(b,a){p[a]=b;e(["out","inn","side1","side2","top"],function(c){p[c].attr(a,b)})}});z(p,"attr",function(b,a){var d;"object"===typeof a&&(d=k(a))&&(c(p.attribs,d),p.setPaths(p.attribs));return b.apply(this,[].slice.call(arguments,1))});z(p,"animate",function(b,a,c,d){var e,h=this.attribs,p;delete a.center;delete a.z;delete a.depth;delete a.alpha;delete a.beta;p=f(w(c,this.renderer.globalAnimation));p.duration&& (e=k(a),a.dummy=1,e&&(p.step=function(b,a){function c(b){return h[b]+(w(e[b],h[b])-h[b])*a.pos}"dummy"===a.prop&&a.elem.setPaths(t(h,{x:c("x"),y:c("y"),r:c("r"),innerR:c("innerR"),start:c("start"),end:c("end")}))}),c=p);return b.call(this,a,c,d)});p.destroy=function(){this.top.destroy();this.out.destroy();this.inn.destroy();this.side1.destroy();this.side2.destroy();x.prototype.destroy.call(this)};p.hide=function(){this.top.hide();this.out.hide();this.inn.hide();this.side1.hide();this.side2.hide()}; p.show=function(){this.top.show();this.out.show();this.inn.show();this.side1.show();this.side2.show()};return p};C.prototype.arc3dPath=function(b){function a(b){b%=2*Math.PI;b>Math.PI&&(b=2*Math.PI-b);return b}var c=b.x,d=b.y,k=b.start,e=b.end-.00001,f=b.r,q=b.innerR,t=b.depth,g=b.alpha,n=b.beta,w=Math.cos(k),B=Math.sin(k);b=Math.cos(e);var u=Math.sin(e),m=f*Math.cos(n),f=f*Math.cos(g),z=q*Math.cos(n),y=q*Math.cos(g),q=t*Math.sin(n),x=t*Math.sin(g),t=["M",c+m*w,d+f*B],t=t.concat(h(c,d,m,f,k,e,0,0)), t=t.concat(["L",c+z*b,d+y*u]),t=t.concat(h(c,d,z,y,e,k,0,0)),t=t.concat(["Z"]),C=0<n?Math.PI/2:0,n=0<g?0:Math.PI/2,C=k>-C?k:e>-C?-C:k,E=e<l-n?e:k<l-n?l-n:e,r=2*l-n,g=["M",c+m*v(C),d+f*F(C)],g=g.concat(h(c,d,m,f,C,E,0,0));e>r&&k<r?(g=g.concat(["L",c+m*v(E)+q,d+f*F(E)+x]),g=g.concat(h(c,d,m,f,E,r,q,x)),g=g.concat(["L",c+m*v(r),d+f*F(r)]),g=g.concat(h(c,d,m,f,r,e,0,0)),g=g.concat(["L",c+m*v(e)+q,d+f*F(e)+x]),g=g.concat(h(c,d,m,f,e,r,q,x)),g=g.concat(["L",c+m*v(r),d+f*F(r)]),g=g.concat(h(c,d,m,f,r,E, 0,0))):e>l-n&&k<l-n&&(g=g.concat(["L",c+m*Math.cos(E)+q,d+f*Math.sin(E)+x]),g=g.concat(h(c,d,m,f,E,e,q,x)),g=g.concat(["L",c+m*Math.cos(e),d+f*Math.sin(e)]),g=g.concat(h(c,d,m,f,e,E,0,0)));g=g.concat(["L",c+m*Math.cos(E)+q,d+f*Math.sin(E)+x]);g=g.concat(h(c,d,m,f,E,C,q,x));g=g.concat(["Z"]);n=["M",c+z*w,d+y*B];n=n.concat(h(c,d,z,y,k,e,0,0));n=n.concat(["L",c+z*Math.cos(e)+q,d+y*Math.sin(e)+x]);n=n.concat(h(c,d,z,y,e,k,q,x));n=n.concat(["Z"]);w=["M",c+m*w,d+f*B,"L",c+m*w+q,d+f*B+x,"L",c+z*w+q,d+y* B+x,"L",c+z*w,d+y*B,"Z"];c=["M",c+m*b,d+f*u,"L",c+m*b+q,d+f*u+x,"L",c+z*b+q,d+y*u+x,"L",c+z*b,d+y*u,"Z"];u=Math.atan2(x,-q);d=Math.abs(e+u);b=Math.abs(k+u);k=Math.abs((k+e)/2+u);d=a(d);b=a(b);k=a(k);k*=1E5;e=1E5*b;d*=1E5;return{top:t,zTop:1E5*Math.PI+1,out:g,zOut:Math.max(k,e,d),inn:n,zInn:Math.max(k,e,d),side1:w,zSide1:.99*d,side2:c,zSide2:.99*e}}})(r);(function(a){function m(a,d){var e=a.plotLeft,c=a.plotWidth+e,b=a.plotTop,k=a.plotHeight+b,f=e+a.plotWidth/2,g=b+a.plotHeight/2,h=Number.MAX_VALUE, n=-Number.MAX_VALUE,q=Number.MAX_VALUE,l=-Number.MAX_VALUE,m,u=1;m=[{x:e,y:b,z:0},{x:e,y:b,z:d}];v([0,1],function(b){m.push({x:c,y:m[b].y,z:m[b].z})});v([0,1,2,3],function(b){m.push({x:m[b].x,y:k,z:m[b].z})});m=r(m,a,!1);v(m,function(b){h=Math.min(h,b.x);n=Math.max(n,b.x);q=Math.min(q,b.y);l=Math.max(l,b.y)});e>h&&(u=Math.min(u,1-Math.abs((e+f)/(h+f))%1));c<n&&(u=Math.min(u,(c-f)/(n-f)));b>q&&(u=0>q?Math.min(u,(b+g)/(-q+b+g)):Math.min(u,1-(b+g)/(q+g)%1));k<l&&(u=Math.min(u,Math.abs((k-g)/(l-g)))); return u}var h=a.Chart,v=a.each,l=a.merge,r=a.perspective,f=a.pick,n=a.wrap;h.prototype.is3d=function(){return this.options.chart.options3d&&this.options.chart.options3d.enabled};h.prototype.propsRequireDirtyBox.push("chart.options3d");h.prototype.propsRequireUpdateSeries.push("chart.options3d");a.wrap(a.Chart.prototype,"isInsidePlot",function(a){return this.is3d()||a.apply(this,[].slice.call(arguments,1))});var g=a.getOptions();l(!0,g,{chart:{options3d:{enabled:!1,alpha:0,beta:0,depth:100,fitToPlot:!0, viewDistance:25,frame:{bottom:{size:1},side:{size:1},back:{size:1}}}}});n(h.prototype,"setClassName",function(a){a.apply(this,[].slice.call(arguments,1));this.is3d()&&(this.container.className+=" highcharts-3d-chart")});a.wrap(a.Chart.prototype,"setChartSize",function(a){var d=this.options.chart.options3d;a.apply(this,[].slice.call(arguments,1));if(this.is3d()){var e=this.inverted,c=this.clipBox,b=this.margin;c[e?"y":"x"]=-(b[3]||0);c[e?"x":"y"]=-(b[0]||0);c[e?"height":"width"]=this.chartWidth+(b[3]|| 0)+(b[1]||0);c[e?"width":"height"]=this.chartHeight+(b[0]||0)+(b[2]||0);this.scale3d=1;!0===d.fitToPlot&&(this.scale3d=m(this,d.depth))}});n(h.prototype,"redraw",function(a){this.is3d()&&(this.isDirtyBox=!0);a.apply(this,[].slice.call(arguments,1))});n(h.prototype,"renderSeries",function(a){var d=this.series.length;if(this.is3d())for(;d--;)a=this.series[d],a.translate(),a.render();else a.call(this)});h.prototype.retrieveStacks=function(a){var d=this.series,e={},c,b=1;v(this.series,function(k){c=f(k.options.stack, a?0:d.length-1-k.index);e[c]?e[c].series.push(k):(e[c]={series:[k],position:b},b++)});e.totalStacks=b+1;return e}})(r);(function(a){var m,h=a.Axis,v=a.Chart,l=a.each,r=a.extend,f=a.merge,n=a.perspective,g=a.pick,q=a.splat,d=a.Tick,e=a.wrap;e(h.prototype,"setOptions",function(a,b){a.call(this,b);this.chart.is3d()&&"colorAxis"!==this.coll&&(a=this.options,a.tickWidth=g(a.tickWidth,0),a.gridLineWidth=g(a.gridLineWidth,1))});e(h.prototype,"render",function(a){a.apply(this,[].slice.call(arguments,1)); if(this.chart.is3d()&&"colorAxis"!==this.coll){var b=this.chart,c=b.renderer,d=b.options.chart.options3d,e=d.frame,f=e.bottom,g=e.back,e=e.side,h=d.depth,n=this.height,q=this.width,l=this.left,m=this.top;this.isZAxis||(this.horiz?(g={x:l,y:m+(b.xAxis[0].opposite?-f.size:n),z:0,width:q,height:f.size,depth:h,insidePlotArea:!1},this.bottomFrame?this.bottomFrame.animate(g):(this.bottomFrame=c.cuboid(g).attr({"class":"highcharts-3d-frame highcharts-3d-frame-bottom",zIndex:b.yAxis[0].reversed&&0<d.alpha? 4:-1}).add(),this.bottomFrame.attr({fill:f.color||"none",stroke:f.color||"none"}))):(d={x:l+(b.yAxis[0].opposite?0:-e.size),y:m+(b.xAxis[0].opposite?-f.size:0),z:h,width:q+e.size,height:n+f.size,depth:g.size,insidePlotArea:!1},this.backFrame?this.backFrame.animate(d):(this.backFrame=c.cuboid(d).attr({"class":"highcharts-3d-frame highcharts-3d-frame-back",zIndex:-3}).add(),this.backFrame.attr({fill:g.color||"none",stroke:g.color||"none"})),b={x:l+(b.yAxis[0].opposite?q:-e.size),y:m+(b.xAxis[0].opposite? -f.size:0),z:0,width:e.size,height:n+f.size,depth:h,insidePlotArea:!1},this.sideFrame?this.sideFrame.animate(b):(this.sideFrame=c.cuboid(b).attr({"class":"highcharts-3d-frame highcharts-3d-frame-side",zIndex:-2}).add(),this.sideFrame.attr({fill:e.color||"none",stroke:e.color||"none"}))))}});e(h.prototype,"getPlotLinePath",function(a){var b=a.apply(this,[].slice.call(arguments,1));if(!this.chart.is3d()||"colorAxis"===this.coll||null===b)return b;var c=this.chart,d=c.options.chart.options3d,c=this.isZAxis? c.plotWidth:d.depth,d=this.opposite;this.horiz&&(d=!d);b=[this.swapZ({x:b[1],y:b[2],z:d?c:0}),this.swapZ({x:b[1],y:b[2],z:c}),this.swapZ({x:b[4],y:b[5],z:c}),this.swapZ({x:b[4],y:b[5],z:d?0:c})];b=n(b,this.chart,!1);return b=this.chart.renderer.toLinePath(b,!1)});e(h.prototype,"getLinePath",function(a){return this.chart.is3d()?[]:a.apply(this,[].slice.call(arguments,1))});e(h.prototype,"getPlotBandPath",function(a){if(!this.chart.is3d()||"colorAxis"===this.coll)return a.apply(this,[].slice.call(arguments, 1));var b=arguments,c=b[1],b=this.getPlotLinePath(b[2]);(c=this.getPlotLinePath(c))&&b?c.push("L",b[10],b[11],"L",b[7],b[8],"L",b[4],b[5],"L",b[1],b[2]):c=null;return c});e(d.prototype,"getMarkPath",function(a){var b=a.apply(this,[].slice.call(arguments,1));if(!this.axis.chart.is3d()||"colorAxis"===this.axis.coll)return b;b=[this.axis.swapZ({x:b[1],y:b[2],z:0}),this.axis.swapZ({x:b[4],y:b[5],z:0})];b=n(b,this.axis.chart,!1);return b=["M",b[0].x,b[0].y,"L",b[1].x,b[1].y]});e(d.prototype,"getLabelPosition", function(a){var b=a.apply(this,[].slice.call(arguments,1));this.axis.chart.is3d()&&"colorAxis"!==this.axis.coll&&(b=n([this.axis.swapZ({x:b.x,y:b.y,z:0})],this.axis.chart,!1)[0]);return b});a.wrap(h.prototype,"getTitlePosition",function(a){var b=this.chart.is3d()&&"colorAxis"!==this.coll,c,d;b&&(d=this.axisTitleMargin,this.axisTitleMargin=0);c=a.apply(this,[].slice.call(arguments,1));b&&(c=n([this.swapZ({x:c.x,y:c.y,z:0})],this.chart,!1)[0],c[this.horiz?"y":"x"]+=(this.horiz?1:-1)*(this.opposite? -1:1)*d,this.axisTitleMargin=d);return c});e(h.prototype,"drawCrosshair",function(a){var b=arguments;this.chart.is3d()&&b[2]&&(b[2]={plotX:b[2].plotXold||b[2].plotX,plotY:b[2].plotYold||b[2].plotY});a.apply(this,[].slice.call(b,1))});e(h.prototype,"destroy",function(a){l(["backFrame","bottomFrame","sideFrame"],function(b){this[b]&&(this[b]=this[b].destroy())},this);a.apply(this,[].slice.call(arguments,1))});h.prototype.swapZ=function(a,b){if(this.isZAxis){b=b?0:this.chart.plotLeft;var c=this.chart; return{x:b+(c.yAxis[0].opposite?a.z:c.xAxis[0].width-a.z),y:a.y,z:a.x-b}}return a};m=a.ZAxis=function(){this.init.apply(this,arguments)};r(m.prototype,h.prototype);r(m.prototype,{isZAxis:!0,setOptions:function(a){a=f({offset:0,lineWidth:0},a);h.prototype.setOptions.call(this,a);this.coll="zAxis"},setAxisSize:function(){h.prototype.setAxisSize.call(this);this.width=this.len=this.chart.options.chart.options3d.depth;this.right=this.chart.chartWidth-this.width-this.left},getSeriesExtremes:function(){var a= this,b=a.chart;a.hasVisibleSeries=!1;a.dataMin=a.dataMax=a.ignoreMinPadding=a.ignoreMaxPadding=null;a.buildStacks&&a.buildStacks();l(a.series,function(c){if(c.visible||!b.options.chart.ignoreHiddenSeries)a.hasVisibleSeries=!0,c=c.zData,c.length&&(a.dataMin=Math.min(g(a.dataMin,c[0]),Math.min.apply(null,c)),a.dataMax=Math.max(g(a.dataMax,c[0]),Math.max.apply(null,c)))})}});e(v.prototype,"getAxes",function(a){var b=this,c=this.options,c=c.zAxis=q(c.zAxis||{});a.call(this);b.is3d()&&(this.zAxis=[],l(c, function(a,c){a.index=c;a.isX=!0;(new m(b,a)).setScale()}))})})(r);(function(a){function m(a){var d=a.apply(this,[].slice.call(arguments,1));this.chart.is3d()&&(d.stroke=this.options.edgeColor||d.fill,d["stroke-width"]=l(this.options.edgeWidth,1));return d}var h=a.each,v=a.perspective,l=a.pick,r=a.Series,f=a.seriesTypes,n=a.inArray,g=a.svg;a=a.wrap;a(f.column.prototype,"translate",function(a){a.apply(this,[].slice.call(arguments,1));if(this.chart.is3d()){var d=this,e=d.chart,c=d.options,b=c.depth|| 25,f=d.borderWidth%2?.5:0;if(e.inverted&&!d.yAxis.reversed||!e.inverted&&d.yAxis.reversed)f*=-1;var g=(c.stacking?c.stack||0:d.index)*(b+(c.groupZPadding||1));!1!==c.grouping&&(g=0);g+=c.groupZPadding||1;h(d.data,function(a){if(null!==a.y){var c=a.shapeArgs,k=a.tooltipPos,n;h([["x","width"],["y","height"]],function(a){n=c[a[0]]-f;if(0>n+c[a[1]]||n>d[a[0]+"Axis"].len)for(var b in c)c[b]=0;0>n&&(c[a[1]]+=c[a[0]],c[a[0]]=0);n+c[a[1]]>d[a[0]+"Axis"].len&&(c[a[1]]=d[a[0]+"Axis"].len-c[a[0]])});a.shapeType= "cuboid";c.z=g;c.depth=b;c.insidePlotArea=!0;k=v([{x:k[0],y:k[1],z:g}],e,!0)[0];a.tooltipPos=[k.x,k.y]}});d.z=g}});a(f.column.prototype,"animate",function(a){if(this.chart.is3d()){var d=arguments[1],e=this.yAxis,c=this,b=this.yAxis.reversed;g&&(d?h(c.data,function(a){null!==a.y&&(a.height=a.shapeArgs.height,a.shapey=a.shapeArgs.y,a.shapeArgs.height=1,b||(a.shapeArgs.y=a.stackY?a.plotY+e.translate(a.stackY):a.plotY+(a.negative?-a.height:a.height)))}):(h(c.data,function(a){null!==a.y&&(a.shapeArgs.height= a.height,a.shapeArgs.y=a.shapey,a.graphic&&a.graphic.animate(a.shapeArgs,c.options.animation))}),this.drawDataLabels(),c.animate=null))}else a.apply(this,[].slice.call(arguments,1))});a(f.column.prototype,"plotGroup",function(a,d,e,c,b,f){this.chart.is3d()&&f&&!this[d]&&(this[d]=f,f.attr(this.getPlotBox()),this[d].survive=!0);return a.apply(this,Array.prototype.slice.call(arguments,1))});a(f.column.prototype,"setVisible",function(a,d){var e=this,c;e.chart.is3d()&&h(e.data,function(a){c=(a.visible= a.options.visible=d=void 0===d?!a.visible:d)?"visible":"hidden";e.options.data[n(a,e.data)]=a.options;a.graphic&&a.graphic.attr({visibility:c})});a.apply(this,Array.prototype.slice.call(arguments,1))});a(f.column.prototype,"init",function(a){a.apply(this,[].slice.call(arguments,1));if(this.chart.is3d()){var d=this.options,e=d.grouping,c=d.stacking,b=l(this.yAxis.options.reversedStacks,!0),f=0;if(void 0===e||e){e=this.chart.retrieveStacks(c);f=d.stack||0;for(c=0;c<e[f].series.length&&e[f].series[c]!== this;c++);f=10*(e.totalStacks-e[f].position)+(b?c:-c);this.xAxis.reversed||(f=10*e.totalStacks-f)}d.zIndex=f}});a(f.column.prototype,"pointAttribs",m);f.columnrange&&(a(f.columnrange.prototype,"pointAttribs",m),f.columnrange.prototype.plotGroup=f.column.prototype.plotGroup,f.columnrange.prototype.setVisible=f.column.prototype.setVisible);a(r.prototype,"alignDataLabel",function(a){if(this.chart.is3d()&&("column"===this.type||"columnrange"===this.type)){var d=arguments[4],e={x:d.x,y:d.y,z:this.z},e= v([e],this.chart,!0)[0];d.x=e.x;d.y=e.y}a.apply(this,[].slice.call(arguments,1))})})(r);(function(a){var m=a.deg2rad,h=a.each,v=a.pick,l=a.seriesTypes,r=a.svg;a=a.wrap;a(l.pie.prototype,"translate",function(a){a.apply(this,[].slice.call(arguments,1));if(this.chart.is3d()){var f=this,g=f.options,l=g.depth||0,d=f.chart.options.chart.options3d,e=d.alpha,c=d.beta,b=g.stacking?(g.stack||0)*l:f._i*l,b=b+l/2;!1!==g.grouping&&(b=0);h(f.data,function(a){var d=a.shapeArgs;a.shapeType="arc3d";d.z=b;d.depth= .75*l;d.alpha=e;d.beta=c;d.center=f.center;d=(d.end+d.start)/2;a.slicedTranslation={translateX:Math.round(Math.cos(d)*g.slicedOffset*Math.cos(e*m)),translateY:Math.round(Math.sin(d)*g.slicedOffset*Math.cos(e*m))}})}});a(l.pie.prototype.pointClass.prototype,"haloPath",function(a){var f=arguments;return this.series.chart.is3d()?[]:a.call(this,f[1])});a(l.pie.prototype,"pointAttribs",function(a,h,g){a=a.call(this,h,g);g=this.options;this.chart.is3d()&&(a.stroke=g.edgeColor||h.color||this.color,a["stroke-width"]= v(g.edgeWidth,1));return a});a(l.pie.prototype,"drawPoints",function(a){a.apply(this,[].slice.call(arguments,1));this.chart.is3d()&&h(this.points,function(a){var f=a.graphic;if(f)f[a.y&&a.visible?"show":"hide"]()})});a(l.pie.prototype,"drawDataLabels",function(a){if(this.chart.is3d()){var f=this.chart.options.chart.options3d;h(this.data,function(a){var g=a.shapeArgs,d=g.r,e=(g.start+g.end)/2,c=a.labelPos,b=-d*(1-Math.cos((g.alpha||f.alpha)*m))*Math.sin(e),n=d*(Math.cos((g.beta||f.beta)*m)-1)*Math.cos(e); h([0,2,4],function(a){c[a]+=n;c[a+1]+=b})})}a.apply(this,[].slice.call(arguments,1))});a(l.pie.prototype,"addPoint",function(a){a.apply(this,[].slice.call(arguments,1));this.chart.is3d()&&this.update(this.userOptions,!0)});a(l.pie.prototype,"animate",function(a){if(this.chart.is3d()){var f=arguments[1],g=this.options.animation,h=this.center,d=this.group,e=this.markerGroup;r&&(!0===g&&(g={}),f?(d.oldtranslateX=d.translateX,d.oldtranslateY=d.translateY,f={translateX:h[0],translateY:h[1],scaleX:.001, scaleY:.001},d.attr(f),e&&(e.attrSetters=d.attrSetters,e.attr(f))):(f={translateX:d.oldtranslateX,translateY:d.oldtranslateY,scaleX:1,scaleY:1},d.animate(f,g),e&&e.animate(f,g),this.animate=null))}else a.apply(this,[].slice.call(arguments,1))})})(r);(function(a){var m=a.perspective,h=a.pick,v=a.Point,l=a.seriesTypes,r=a.wrap;r(l.scatter.prototype,"translate",function(a){a.apply(this,[].slice.call(arguments,1));if(this.chart.is3d()){var f=this.chart,g=h(this.zAxis,f.options.zAxis[0]),l=[],d,e,c;for(c= 0;c<this.data.length;c++)d=this.data[c],e=g.isLog&&g.val2lin?g.val2lin(d.z):d.z,d.plotZ=g.translate(e),d.isInside=d.isInside?e>=g.min&&e<=g.max:!1,l.push({x:d.plotX,y:d.plotY,z:d.plotZ});f=m(l,f,!0);for(c=0;c<this.data.length;c++)d=this.data[c],g=f[c],d.plotXold=d.plotX,d.plotYold=d.plotY,d.plotZold=d.plotZ,d.plotX=g.x,d.plotY=g.y,d.plotZ=g.z}});r(l.scatter.prototype,"init",function(a,h,g){h.is3d()&&(this.axisTypes=["xAxis","yAxis","zAxis"],this.pointArrayMap=["x","y","z"],this.parallelArrays=["x", "y","z"],this.directTouch=!0);a=a.apply(this,[h,g]);this.chart.is3d()&&(this.tooltipOptions.pointFormat=this.userOptions.tooltip?this.userOptions.tooltip.pointFormat||"x: \x3cb\x3e{point.x}\x3c/b\x3e\x3cbr/\x3ey: \x3cb\x3e{point.y}\x3c/b\x3e\x3cbr/\x3ez: \x3cb\x3e{point.z}\x3c/b\x3e\x3cbr/\x3e":"x: \x3cb\x3e{point.x}\x3c/b\x3e\x3cbr/\x3ey: \x3cb\x3e{point.y}\x3c/b\x3e\x3cbr/\x3ez: \x3cb\x3e{point.z}\x3c/b\x3e\x3cbr/\x3e");return a});r(l.scatter.prototype,"pointAttribs",function(f,h){var g=f.apply(this, [].slice.call(arguments,1));this.chart.is3d()&&h&&(g.zIndex=a.pointCameraDistance(h,this.chart));return g});r(v.prototype,"applyOptions",function(a){var f=a.apply(this,[].slice.call(arguments,1));this.series.chart.is3d()&&void 0===f.z&&(f.z=0);return f})})(r);(function(a){var m=a.Axis,h=a.SVGRenderer,r=a.VMLRenderer;r&&(a.setOptions({animate:!1}),r.prototype.cuboid=h.prototype.cuboid,r.prototype.cuboidPath=h.prototype.cuboidPath,r.prototype.toLinePath=h.prototype.toLinePath,r.prototype.createElement3D= h.prototype.createElement3D,r.prototype.arc3d=function(a){a=h.prototype.arc3d.call(this,a);a.css({zIndex:a.zIndex});return a},a.VMLRenderer.prototype.arc3dPath=a.SVGRenderer.prototype.arc3dPath,a.wrap(m.prototype,"render",function(a){a.apply(this,[].slice.call(arguments,1));this.sideFrame&&(this.sideFrame.css({zIndex:0}),this.sideFrame.front.attr({fill:this.sideFrame.color}));this.bottomFrame&&(this.bottomFrame.css({zIndex:1}),this.bottomFrame.front.attr({fill:this.bottomFrame.color}));this.backFrame&& (this.backFrame.css({zIndex:0}),this.backFrame.front.attr({fill:this.backFrame.color}))}))})(r)});
/** * @version: 2.1.16 * @author: Dan Grossman http://www.dangrossman.info/ * @copyright: Copyright (c) 2012-2015 Dan Grossman. All rights reserved. * @license: Licensed under the MIT license. See http://www.opensource.org/licenses/mit-license.php * @website: https://www.improvely.com/ */ (function(root, factory) { if (typeof define === 'function' && define.amd) { define(['moment', 'jquery', 'exports'], function(momentjs, $, exports) { root.daterangepicker = factory(root, exports, momentjs, $); }); } else if (typeof exports !== 'undefined') { var momentjs = require('moment'); var jQuery = (typeof window != 'undefined') ? window.jQuery : undefined; //isomorphic issue if (!jQuery) { try { jQuery = require('jquery'); if (!jQuery.fn) jQuery.fn = {}; //isomorphic issue } catch (err) { if (!jQuery) throw new Error('jQuery dependency not found'); } } factory(root, exports, momentjs, jQuery); // Finally, as a browser global. } else { root.daterangepicker = factory(root, {}, root.moment || moment, (root.jQuery || root.Zepto || root.ender || root.$)); } }(this || {}, function(root, daterangepicker, moment, $) { // 'this' doesn't exist on a server var DateRangePicker = function(element, options, cb) { //default settings for options this.parentEl = 'body'; this.element = $(element); this.startDate = moment().startOf('day'); this.endDate = moment().endOf('day'); this.minDate = false; this.maxDate = false; this.dateLimit = false; this.autoApply = false; this.singleDatePicker = false; this.showDropdowns = false; this.showWeekNumbers = false; this.timePicker = false; this.timePicker24Hour = false; this.timePickerIncrement = 1; this.timePickerSeconds = false; this.linkedCalendars = true; this.autoUpdateInput = true; this.ranges = {}; this.opens = 'right'; if (this.element.hasClass('pull-right')) this.opens = 'left'; this.drops = 'down'; if (this.element.hasClass('dropup')) this.drops = 'up'; this.buttonClasses = 'btn btn-sm'; this.applyClass = 'btn-success'; this.cancelClass = 'btn-default'; this.locale = { format: 'MM/DD/YYYY', separator: ' - ', applyLabel: 'Apply', cancelLabel: 'Cancel', weekLabel: 'W', customRangeLabel: 'Custom Range', daysOfWeek: moment.weekdaysMin(), monthNames: moment.monthsShort(), firstDay: moment.localeData().firstDayOfWeek() }; this.callback = function() { }; //some state information this.isShowing = false; this.leftCalendar = {}; this.rightCalendar = {}; //custom options from user if (typeof options !== 'object' || options === null) options = {}; //allow setting options with data attributes //data-api options will be overwritten with custom javascript options options = $.extend(this.element.data(), options); //html template for the picker UI if (typeof options.template !== 'string') options.template = '<div class="daterangepicker dropdown-menu">' + '<div class="calendar left">' + '<div class="daterangepicker_input">' + '<input class="input-mini" type="text" name="daterangepicker_start" value="" />' + '<i class="fa fa-calendar glyphicon glyphicon-calendar"></i>' + '<div class="calendar-time">' + '<div></div>' + '<i class="fa fa-clock-o glyphicon glyphicon-time"></i>' + '</div>' + '</div>' + '<div class="calendar-table"></div>' + '</div>' + '<div class="calendar right">' + '<div class="daterangepicker_input">' + '<input class="input-mini" type="text" name="daterangepicker_end" value="" />' + '<i class="fa fa-calendar glyphicon glyphicon-calendar"></i>' + '<div class="calendar-time">' + '<div></div>' + '<i class="fa fa-clock-o glyphicon glyphicon-time"></i>' + '</div>' + '</div>' + '<div class="calendar-table"></div>' + '</div>' + '<div class="ranges">' + '<div class="range_inputs">' + '<button class="applyBtn" disabled="disabled" type="button"></button> ' + '<button class="cancelBtn" type="button"></button>' + '</div>' + '</div>' + '</div>'; this.parentEl = (options.parentEl && $(options.parentEl).length) ? $(options.parentEl) : $(this.parentEl); this.container = $(options.template).appendTo(this.parentEl); // // handle all the possible options overriding defaults // if (typeof options.locale === 'object') { if (typeof options.locale.format === 'string') this.locale.format = options.locale.format; if (typeof options.locale.separator === 'string') this.locale.separator = options.locale.separator; if (typeof options.locale.daysOfWeek === 'object') this.locale.daysOfWeek = options.locale.daysOfWeek.slice(); if (typeof options.locale.monthNames === 'object') this.locale.monthNames = options.locale.monthNames.slice(); if (typeof options.locale.firstDay === 'number') this.locale.firstDay = options.locale.firstDay; if (typeof options.locale.applyLabel === 'string') this.locale.applyLabel = options.locale.applyLabel; if (typeof options.locale.cancelLabel === 'string') this.locale.cancelLabel = options.locale.cancelLabel; if (typeof options.locale.weekLabel === 'string') this.locale.weekLabel = options.locale.weekLabel; if (typeof options.locale.customRangeLabel === 'string') this.locale.customRangeLabel = options.locale.customRangeLabel; } if (typeof options.startDate === 'string') this.startDate = moment(options.startDate, this.locale.format); if (typeof options.endDate === 'string') this.endDate = moment(options.endDate, this.locale.format); if (typeof options.minDate === 'string') this.minDate = moment(options.minDate, this.locale.format); if (typeof options.maxDate === 'string') this.maxDate = moment(options.maxDate, this.locale.format); if (typeof options.startDate === 'object') this.startDate = moment(options.startDate); if (typeof options.endDate === 'object') this.endDate = moment(options.endDate); if (typeof options.minDate === 'object') this.minDate = moment(options.minDate); if (typeof options.maxDate === 'object') this.maxDate = moment(options.maxDate); // sanity check for bad options if (this.minDate && this.startDate.isBefore(this.minDate)) this.startDate = this.minDate.clone(); // sanity check for bad options if (this.maxDate && this.endDate.isAfter(this.maxDate)) this.endDate = this.maxDate.clone(); if (typeof options.applyClass === 'string') this.applyClass = options.applyClass; if (typeof options.cancelClass === 'string') this.cancelClass = options.cancelClass; if (typeof options.dateLimit === 'object') this.dateLimit = options.dateLimit; if (typeof options.opens === 'string') this.opens = options.opens; if (typeof options.drops === 'string') this.drops = options.drops; if (typeof options.showWeekNumbers === 'boolean') this.showWeekNumbers = options.showWeekNumbers; if (typeof options.buttonClasses === 'string') this.buttonClasses = options.buttonClasses; if (typeof options.buttonClasses === 'object') this.buttonClasses = options.buttonClasses.join(' '); if (typeof options.showDropdowns === 'boolean') this.showDropdowns = options.showDropdowns; if (typeof options.singleDatePicker === 'boolean') { this.singleDatePicker = options.singleDatePicker; if (this.singleDatePicker) this.endDate = this.startDate.clone(); } if (typeof options.timePicker === 'boolean') this.timePicker = options.timePicker; if (typeof options.timePickerSeconds === 'boolean') this.timePickerSeconds = options.timePickerSeconds; if (typeof options.timePickerIncrement === 'number') this.timePickerIncrement = options.timePickerIncrement; if (typeof options.timePicker24Hour === 'boolean') this.timePicker24Hour = options.timePicker24Hour; if (typeof options.autoApply === 'boolean') this.autoApply = options.autoApply; if (typeof options.autoUpdateInput === 'boolean') this.autoUpdateInput = options.autoUpdateInput; if (typeof options.linkedCalendars === 'boolean') this.linkedCalendars = options.linkedCalendars; if (typeof options.isInvalidDate === 'function') this.isInvalidDate = options.isInvalidDate; // update day names order to firstDay if (this.locale.firstDay != 0) { var iterator = this.locale.firstDay; while (iterator > 0) { this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift()); iterator--; } } var start, end, range; //if no start/end dates set, check if an input element contains initial values if (typeof options.startDate === 'undefined' && typeof options.endDate === 'undefined') { if ($(this.element).is('input[type=text]')) { var val = $(this.element).val(), split = val.split(this.locale.separator); start = end = null; if (split.length == 2) { start = moment(split[0], this.locale.format); end = moment(split[1], this.locale.format); } else if (this.singleDatePicker && val !== "") { start = moment(val, this.locale.format); end = moment(val, this.locale.format); } if (start !== null && end !== null) { this.setStartDate(start); this.setEndDate(end); } } } if (typeof options.ranges === 'object') { for (range in options.ranges) { if (typeof options.ranges[range][0] === 'string') start = moment(options.ranges[range][0], this.locale.format); else start = moment(options.ranges[range][0]); if (typeof options.ranges[range][1] === 'string') end = moment(options.ranges[range][1], this.locale.format); else end = moment(options.ranges[range][1]); // If the start or end date exceed those allowed by the minDate or dateLimit // options, shorten the range to the allowable period. if (this.minDate && start.isBefore(this.minDate)) start = this.minDate.clone(); var maxDate = this.maxDate; if (this.dateLimit && start.clone().add(this.dateLimit).isAfter(maxDate)) maxDate = start.clone().add(this.dateLimit); if (maxDate && end.isAfter(maxDate)) end = maxDate.clone(); // If the end of the range is before the minimum or the start of the range is // after the maximum, don't display this range option at all. if ((this.minDate && end.isBefore(this.minDate)) || (maxDate && start.isAfter(maxDate))) continue; //Support unicode chars in the range names. var elem = document.createElement('textarea'); elem.innerHTML = range; var rangeHtml = elem.value; this.ranges[rangeHtml] = [start, end]; } var list = '<ul>'; for (range in this.ranges) { list += '<li>' + range + '</li>'; } list += '<li>' + this.locale.customRangeLabel + '</li>'; list += '</ul>'; this.container.find('.ranges').prepend(list); } if (typeof cb === 'function') { this.callback = cb; } if (!this.timePicker) { this.startDate = this.startDate.startOf('day'); this.endDate = this.endDate.endOf('day'); this.container.find('.calendar-time').hide(); } //can't be used together for now if (this.timePicker && this.autoApply) this.autoApply = false; if (this.autoApply && typeof options.ranges !== 'object') { this.container.find('.ranges').hide(); } else if (this.autoApply) { this.container.find('.applyBtn, .cancelBtn').addClass('hide'); } if (this.singleDatePicker) { this.container.addClass('single'); this.container.find('.calendar.left').addClass('single'); this.container.find('.calendar.left').show(); this.container.find('.calendar.right').hide(); this.container.find('.daterangepicker_input input, .daterangepicker_input i').hide(); if (!this.timePicker) { this.container.find('.ranges').hide(); } } if (typeof options.ranges === 'undefined' && !this.singleDatePicker) { this.container.addClass('show-calendar'); } this.container.addClass('opens' + this.opens); //swap the position of the predefined ranges if opens right if (typeof options.ranges !== 'undefined' && this.opens == 'right') { var ranges = this.container.find('.ranges'); var html = ranges.clone(); ranges.remove(); this.container.find('.calendar.left').parent().prepend(html); } //apply CSS classes and labels to buttons this.container.find('.applyBtn, .cancelBtn').addClass(this.buttonClasses); if (this.applyClass.length) this.container.find('.applyBtn').addClass(this.applyClass); if (this.cancelClass.length) this.container.find('.cancelBtn').addClass(this.cancelClass); this.container.find('.applyBtn').html(this.locale.applyLabel); this.container.find('.cancelBtn').html(this.locale.cancelLabel); // // event listeners // this.container.find('.calendar') .on('click.daterangepicker', '.prev', $.proxy(this.clickPrev, this)) .on('click.daterangepicker', '.next', $.proxy(this.clickNext, this)) .on('click.daterangepicker', 'td.available', $.proxy(this.clickDate, this)) .on('mouseenter.daterangepicker', 'td.available', $.proxy(this.hoverDate, this)) .on('mouseleave.daterangepicker', 'td.available', $.proxy(this.updateFormInputs, this)) .on('change.daterangepicker', 'select.yearselect', $.proxy(this.monthOrYearChanged, this)) .on('change.daterangepicker', 'select.monthselect', $.proxy(this.monthOrYearChanged, this)) .on('change.daterangepicker', 'select.hourselect,select.minuteselect,select.secondselect,select.ampmselect', $.proxy(this.timeChanged, this)) .on('click.daterangepicker', '.daterangepicker_input input', $.proxy(this.showCalendars, this)) //.on('keyup.daterangepicker', '.daterangepicker_input input', $.proxy(this.formInputsChanged, this)) .on('change.daterangepicker', '.daterangepicker_input input', $.proxy(this.formInputsChanged, this)); this.container.find('.ranges') .on('click.daterangepicker', 'button.applyBtn', $.proxy(this.clickApply, this)) .on('click.daterangepicker', 'button.cancelBtn', $.proxy(this.clickCancel, this)) .on('click.daterangepicker', 'li', $.proxy(this.clickRange, this)) .on('mouseenter.daterangepicker', 'li', $.proxy(this.hoverRange, this)) .on('mouseleave.daterangepicker', 'li', $.proxy(this.updateFormInputs, this)); if (this.element.is('input')) { this.element.on({ 'click.daterangepicker': $.proxy(this.show, this), 'focus.daterangepicker': $.proxy(this.show, this), 'keyup.daterangepicker': $.proxy(this.elementChanged, this), 'keydown.daterangepicker': $.proxy(this.keydown, this) }); } else { this.element.on('click.daterangepicker', $.proxy(this.toggle, this)); } // // if attached to a text input, set the initial value // if (this.element.is('input') && !this.singleDatePicker && this.autoUpdateInput) { this.element.val(this.startDate.format(this.locale.format) + this.locale.separator + this.endDate.format(this.locale.format)); this.element.trigger('change'); } else if (this.element.is('input') && this.autoUpdateInput) { this.element.val(this.startDate.format(this.locale.format)); this.element.trigger('change'); } }; DateRangePicker.prototype = { constructor: DateRangePicker, setStartDate: function(startDate) { if (typeof startDate === 'string') this.startDate = moment(startDate, this.locale.format); if (typeof startDate === 'object') this.startDate = moment(startDate); if (!this.timePicker) this.startDate = this.startDate.startOf('day'); if (this.timePicker && this.timePickerIncrement) this.startDate.minute(Math.round(this.startDate.minute() / this.timePickerIncrement) * this.timePickerIncrement); if (this.minDate && this.startDate.isBefore(this.minDate)) this.startDate = this.minDate; if (this.maxDate && this.startDate.isAfter(this.maxDate)) this.startDate = this.maxDate; if (!this.isShowing) this.updateElement(); this.updateMonthsInView(); }, setEndDate: function(endDate) { if (typeof endDate === 'string') this.endDate = moment(endDate, this.locale.format); if (typeof endDate === 'object') this.endDate = moment(endDate); if (!this.timePicker) this.endDate = this.endDate.endOf('day'); if (this.timePicker && this.timePickerIncrement) this.endDate.minute(Math.round(this.endDate.minute() / this.timePickerIncrement) * this.timePickerIncrement); if (this.endDate.isBefore(this.startDate)) this.endDate = this.startDate.clone(); if (this.maxDate && this.endDate.isAfter(this.maxDate)) this.endDate = this.maxDate; if (this.dateLimit && this.startDate.clone().add(this.dateLimit).isBefore(this.endDate)) this.endDate = this.startDate.clone().add(this.dateLimit); if (!this.isShowing) this.updateElement(); this.updateMonthsInView(); }, isInvalidDate: function() { return false; }, updateView: function() { if (this.timePicker) { this.renderTimePicker('left'); this.renderTimePicker('right'); if (!this.endDate) { this.container.find('.right .calendar-time select').attr('disabled', 'disabled').addClass('disabled'); } else { this.container.find('.right .calendar-time select').removeAttr('disabled').removeClass('disabled'); } } if (this.endDate) { this.container.find('input[name="daterangepicker_end"]').removeClass('active'); this.container.find('input[name="daterangepicker_start"]').addClass('active'); } else { this.container.find('input[name="daterangepicker_end"]').addClass('active'); this.container.find('input[name="daterangepicker_start"]').removeClass('active'); } this.updateMonthsInView(); this.updateCalendars(); this.updateFormInputs(); }, updateMonthsInView: function() { if (this.endDate) { //if both dates are visible already, do nothing if (!this.singleDatePicker && this.leftCalendar.month && this.rightCalendar.month && (this.startDate.format('YYYY-MM') == this.leftCalendar.month.format('YYYY-MM') || this.startDate.format('YYYY-MM') == this.rightCalendar.month.format('YYYY-MM')) && (this.endDate.format('YYYY-MM') == this.leftCalendar.month.format('YYYY-MM') || this.endDate.format('YYYY-MM') == this.rightCalendar.month.format('YYYY-MM')) ) { return; } this.leftCalendar.month = this.startDate.clone().date(2); if (!this.linkedCalendars && (this.endDate.month() != this.startDate.month() || this.endDate.year() != this.startDate.year())) { this.rightCalendar.month = this.endDate.clone().date(2); } else { this.rightCalendar.month = this.startDate.clone().date(2).add(1, 'month'); } } else { if (this.leftCalendar.month.format('YYYY-MM') != this.startDate.format('YYYY-MM') && this.rightCalendar.month.format('YYYY-MM') != this.startDate.format('YYYY-MM')) { this.leftCalendar.month = this.startDate.clone().date(2); this.rightCalendar.month = this.startDate.clone().date(2).add(1, 'month'); } } }, updateCalendars: function() { if (this.timePicker) { var hour, minute, second; if (this.endDate) { hour = parseInt(this.container.find('.left .hourselect').val(), 10); minute = parseInt(this.container.find('.left .minuteselect').val(), 10); second = this.timePickerSeconds ? parseInt(this.container.find('.left .secondselect').val(), 10) : 0; if (!this.timePicker24Hour) { var ampm = this.container.find('.left .ampmselect').val(); if (ampm === 'PM' && hour < 12) hour += 12; if (ampm === 'AM' && hour === 12) hour = 0; } } else { hour = parseInt(this.container.find('.right .hourselect').val(), 10); minute = parseInt(this.container.find('.right .minuteselect').val(), 10); second = this.timePickerSeconds ? parseInt(this.container.find('.right .secondselect').val(), 10) : 0; if (!this.timePicker24Hour) { var ampm = this.container.find('.right .ampmselect').val(); if (ampm === 'PM' && hour < 12) hour += 12; if (ampm === 'AM' && hour === 12) hour = 0; } } this.leftCalendar.month.hour(hour).minute(minute).second(second); this.rightCalendar.month.hour(hour).minute(minute).second(second); } this.renderCalendar('left'); this.renderCalendar('right'); //highlight any predefined range matching the current start and end dates this.container.find('.ranges li').removeClass('active'); if (this.endDate == null) return; var customRange = true; var i = 0; for (var range in this.ranges) { if (this.timePicker) { if (this.startDate.isSame(this.ranges[range][0]) && this.endDate.isSame(this.ranges[range][1])) { customRange = false; this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')').addClass('active').html(); break; } } else { //ignore times when comparing dates if time picker is not enabled if (this.startDate.format('YYYY-MM-DD') == this.ranges[range][0].format('YYYY-MM-DD') && this.endDate.format('YYYY-MM-DD') == this.ranges[range][1].format('YYYY-MM-DD')) { customRange = false; this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')').addClass('active').html(); break; } } i++; } if (customRange) { this.chosenLabel = this.container.find('.ranges li:last').addClass('active').html(); this.showCalendars(); } }, renderCalendar: function(side) { // // Build the matrix of dates that will populate the calendar // var calendar = side == 'left' ? this.leftCalendar : this.rightCalendar; var month = calendar.month.month(); var year = calendar.month.year(); var hour = calendar.month.hour(); var minute = calendar.month.minute(); var second = calendar.month.second(); var daysInMonth = moment([year, month]).daysInMonth(); var firstDay = moment([year, month, 1]); var lastDay = moment([year, month, daysInMonth]); var lastMonth = moment(firstDay).subtract(1, 'month').month(); var lastYear = moment(firstDay).subtract(1, 'month').year(); var daysInLastMonth = moment([lastYear, lastMonth]).daysInMonth(); var dayOfWeek = firstDay.day(); //initialize a 6 rows x 7 columns array for the calendar var calendar = []; calendar.firstDay = firstDay; calendar.lastDay = lastDay; for (var i = 0; i < 6; i++) { calendar[i] = []; } //populate the calendar with date objects var startDay = daysInLastMonth - dayOfWeek + this.locale.firstDay + 1; if (startDay > daysInLastMonth) startDay -= 7; if (dayOfWeek == this.locale.firstDay) startDay = daysInLastMonth - 6; var curDate = moment([lastYear, lastMonth, startDay, 12, minute, second]); var col, row; for (var i = 0, col = 0, row = 0; i < 42; i++, col++, curDate = moment(curDate).add(24, 'hour')) { if (i > 0 && col % 7 === 0) { col = 0; row++; } calendar[row][col] = curDate.clone().hour(hour).minute(minute).second(second); curDate.hour(12); if (this.minDate && calendar[row][col].format('YYYY-MM-DD') == this.minDate.format('YYYY-MM-DD') && calendar[row][col].isBefore(this.minDate) && side == 'left') { calendar[row][col] = this.minDate.clone(); } if (this.maxDate && calendar[row][col].format('YYYY-MM-DD') == this.maxDate.format('YYYY-MM-DD') && calendar[row][col].isAfter(this.maxDate) && side == 'right') { calendar[row][col] = this.maxDate.clone(); } } //make the calendar object available to hoverDate/clickDate if (side == 'left') { this.leftCalendar.calendar = calendar; } else { this.rightCalendar.calendar = calendar; } // // Display the calendar // var minDate = side == 'left' ? this.minDate : this.startDate; var maxDate = this.maxDate; var selected = side == 'left' ? this.startDate : this.endDate; var html = '<table class="table-condensed">'; html += '<thead>'; html += '<tr>'; // add empty cell for week number if (this.showWeekNumbers) html += '<th></th>'; if ((!minDate || minDate.isBefore(calendar.firstDay)) && (!this.linkedCalendars || side == 'left')) { html += '<th class="prev available"><i class="fa fa-chevron-left glyphicon glyphicon-chevron-left"></i></th>'; } else { html += '<th></th>'; } var dateHtml = this.locale.monthNames[calendar[1][1].month()] + calendar[1][1].format(" YYYY"); if (this.showDropdowns) { var currentMonth = calendar[1][1].month(); var currentYear = calendar[1][1].year(); var maxYear = (maxDate && maxDate.year()) || (currentYear + 5); var minYear = (minDate && minDate.year()) || (currentYear - 50); var inMinYear = currentYear == minYear; var inMaxYear = currentYear == maxYear; var monthHtml = '<select class="monthselect">'; for (var m = 0; m < 12; m++) { if ((!inMinYear || m >= minDate.month()) && (!inMaxYear || m <= maxDate.month())) { monthHtml += "<option value='" + m + "'" + (m === currentMonth ? " selected='selected'" : "") + ">" + this.locale.monthNames[m] + "</option>"; } else { monthHtml += "<option value='" + m + "'" + (m === currentMonth ? " selected='selected'" : "") + " disabled='disabled'>" + this.locale.monthNames[m] + "</option>"; } } monthHtml += "</select>"; var yearHtml = '<select class="yearselect">'; for (var y = minYear; y <= maxYear; y++) { yearHtml += '<option value="' + y + '"' + (y === currentYear ? ' selected="selected"' : '') + '>' + y + '</option>'; } yearHtml += '</select>'; dateHtml = monthHtml + yearHtml; } html += '<th colspan="5" class="month">' + dateHtml + '</th>'; if ((!maxDate || maxDate.isAfter(calendar.lastDay)) && (!this.linkedCalendars || side == 'right' || this.singleDatePicker)) { html += '<th class="next available"><i class="fa fa-chevron-right glyphicon glyphicon-chevron-right"></i></th>'; } else { html += '<th></th>'; } html += '</tr>'; html += '<tr>'; // add week number label if (this.showWeekNumbers) html += '<th class="week">' + this.locale.weekLabel + '</th>'; $.each(this.locale.daysOfWeek, function(index, dayOfWeek) { html += '<th>' + dayOfWeek + '</th>'; }); html += '</tr>'; html += '</thead>'; html += '<tbody>'; //adjust maxDate to reflect the dateLimit setting in order to //grey out end dates beyond the dateLimit if (this.endDate == null && this.dateLimit) { var maxLimit = this.startDate.clone().add(this.dateLimit).endOf('day'); if (!maxDate || maxLimit.isBefore(maxDate)) { maxDate = maxLimit; } } for (var row = 0; row < 6; row++) { html += '<tr>'; // add week number if (this.showWeekNumbers) html += '<td class="week">' + calendar[row][0].week() + '</td>'; for (var col = 0; col < 7; col++) { var classes = []; //highlight today's date if (calendar[row][col].isSame(new Date(), "day")) classes.push('today'); //highlight weekends if (calendar[row][col].isoWeekday() > 5) classes.push('weekend'); //grey out the dates in other months displayed at beginning and end of this calendar if (calendar[row][col].month() != calendar[1][1].month()) classes.push('off'); //don't allow selection of dates before the minimum date if (this.minDate && calendar[row][col].isBefore(this.minDate, 'day')) classes.push('off', 'disabled'); //don't allow selection of dates after the maximum date if (maxDate && calendar[row][col].isAfter(maxDate, 'day')) classes.push('off', 'disabled'); //don't allow selection of date if a custom function decides it's invalid if (this.isInvalidDate(calendar[row][col])) classes.push('off', 'disabled'); //highlight the currently selected start date if (calendar[row][col].format('YYYY-MM-DD') == this.startDate.format('YYYY-MM-DD')) classes.push('active', 'start-date'); //highlight the currently selected end date if (this.endDate != null && calendar[row][col].format('YYYY-MM-DD') == this.endDate.format('YYYY-MM-DD')) classes.push('active', 'end-date'); //highlight dates in-between the selected dates if (this.endDate != null && calendar[row][col] > this.startDate && calendar[row][col] < this.endDate) classes.push('in-range'); var cname = '', disabled = false; for (var i = 0; i < classes.length; i++) { cname += classes[i] + ' '; if (classes[i] == 'disabled') disabled = true; } if (!disabled) cname += 'available'; html += '<td class="' + cname.replace(/^\s+|\s+$/g, '') + '" data-title="' + 'r' + row + 'c' + col + '">' + calendar[row][col].date() + '</td>'; } html += '</tr>'; } html += '</tbody>'; html += '</table>'; this.container.find('.calendar.' + side + ' .calendar-table').html(html); }, renderTimePicker: function(side) { var html, selected, minDate, maxDate = this.maxDate; if (this.dateLimit && (!this.maxDate || this.startDate.clone().add(this.dateLimit).isAfter(this.maxDate))) maxDate = this.startDate.clone().add(this.dateLimit); if (side == 'left') { selected = this.startDate.clone(); minDate = this.minDate; } else if (side == 'right') { selected = this.endDate ? this.endDate.clone() : this.startDate.clone(); minDate = this.startDate; //Preserve the time already selected var timeSelector = this.container.find('.calendar.right .calendar-time div'); if (timeSelector.html() != '') { selected.hour(timeSelector.find('.hourselect option:selected').val() || selected.hour()); selected.minute(timeSelector.find('.minuteselect option:selected').val() || selected.minute()); selected.second(timeSelector.find('.secondselect option:selected').val() || selected.second()); if (!this.timePicker24Hour) { var ampm = timeSelector.find('.ampmselect option:selected').val(); if (ampm === 'PM' && selected.hour() < 12) selected.hour(selected.hour() + 12); if (ampm === 'AM' && selected.hour() === 12) selected.hour(0); } if (selected.isAfter(maxDate)) selected = maxDate.clone(); } } // // hours // html = '<select class="hourselect">'; var start = this.timePicker24Hour ? 0 : 1; var end = this.timePicker24Hour ? 23 : 12; for (var i = start; i <= end; i++) { var i_in_24 = i; if (!this.timePicker24Hour) i_in_24 = selected.hour() >= 12 ? (i == 12 ? 12 : i + 12) : (i == 12 ? 0 : i); var time = selected.clone().hour(i_in_24); var disabled = false; if (minDate && time.minute(59).isBefore(minDate)) disabled = true; if (maxDate && time.minute(0).isAfter(maxDate)) disabled = true; if (i_in_24 == selected.hour() && !disabled) { html += '<option value="' + i + '" selected="selected">' + i + '</option>'; } else if (disabled) { html += '<option value="' + i + '" disabled="disabled" class="disabled">' + i + '</option>'; } else { html += '<option value="' + i + '">' + i + '</option>'; } } html += '</select> '; // // minutes // html += ': <select class="minuteselect">'; for (var i = 0; i < 60; i += this.timePickerIncrement) { var padded = i < 10 ? '0' + i : i; var time = selected.clone().minute(i); var disabled = false; if (minDate && time.second(59).isBefore(minDate)) disabled = true; if (maxDate && time.second(0).isAfter(maxDate)) disabled = true; if (selected.minute() == i && !disabled) { html += '<option value="' + i + '" selected="selected">' + padded + '</option>'; } else if (disabled) { html += '<option value="' + i + '" disabled="disabled" class="disabled">' + padded + '</option>'; } else { html += '<option value="' + i + '">' + padded + '</option>'; } } html += '</select> '; // // seconds // if (this.timePickerSeconds) { html += ': <select class="secondselect">'; for (var i = 0; i < 60; i++) { var padded = i < 10 ? '0' + i : i; var time = selected.clone().second(i); var disabled = false; if (minDate && time.isBefore(minDate)) disabled = true; if (maxDate && time.isAfter(maxDate)) disabled = true; if (selected.second() == i && !disabled) { html += '<option value="' + i + '" selected="selected">' + padded + '</option>'; } else if (disabled) { html += '<option value="' + i + '" disabled="disabled" class="disabled">' + padded + '</option>'; } else { html += '<option value="' + i + '">' + padded + '</option>'; } } html += '</select> '; } // // AM/PM // if (!this.timePicker24Hour) { html += '<select class="ampmselect">'; var am_html = ''; var pm_html = ''; if (minDate && selected.clone().hour(12).minute(0).second(0).isBefore(minDate)) am_html = ' disabled="disabled" class="disabled"'; if (maxDate && selected.clone().hour(0).minute(0).second(0).isAfter(maxDate)) pm_html = ' disabled="disabled" class="disabled"'; if (selected.hour() >= 12) { html += '<option value="AM"' + am_html + '>AM</option><option value="PM" selected="selected"' + pm_html + '>PM</option>'; } else { html += '<option value="AM" selected="selected"' + am_html + '>AM</option><option value="PM"' + pm_html + '>PM</option>'; } html += '</select>'; } this.container.find('.calendar.' + side + ' .calendar-time div').html(html); }, updateFormInputs: function() { //ignore mouse movements while an above-calendar text input has focus if (this.container.find('input[name=daterangepicker_start]').is(":focus") || this.container.find('input[name=daterangepicker_end]').is(":focus")) return; this.container.find('input[name=daterangepicker_start]').val(this.startDate.format(this.locale.format)); if (this.endDate) this.container.find('input[name=daterangepicker_end]').val(this.endDate.format(this.locale.format)); if (this.singleDatePicker || (this.endDate && (this.startDate.isBefore(this.endDate) || this.startDate.isSame(this.endDate)))) { this.container.find('button.applyBtn').removeAttr('disabled'); } else { this.container.find('button.applyBtn').attr('disabled', 'disabled'); } }, move: function() { var parentOffset = { top: 0, left: 0 }, containerTop; var parentRightEdge = $(window).width(); if (!this.parentEl.is('body')) { parentOffset = { top: this.parentEl.offset().top - this.parentEl.scrollTop(), left: this.parentEl.offset().left - this.parentEl.scrollLeft() }; parentRightEdge = this.parentEl[0].clientWidth + this.parentEl.offset().left; } if (this.drops == 'up') containerTop = this.element.offset().top - this.container.outerHeight() - parentOffset.top; else containerTop = this.element.offset().top + this.element.outerHeight() - parentOffset.top; this.container[this.drops == 'up' ? 'addClass' : 'removeClass']('dropup'); if (this.opens == 'left') { this.container.css({ top: containerTop, right: parentRightEdge - this.element.offset().left - this.element.outerWidth(), left: 'auto' }); if (this.container.offset().left < 0) { this.container.css({ right: 'auto', left: 9 }); } } else if (this.opens == 'center') { this.container.css({ top: containerTop, left: this.element.offset().left - parentOffset.left + this.element.outerWidth() / 2 - this.container.outerWidth() / 2, right: 'auto' }); if (this.container.offset().left < 0) { this.container.css({ right: 'auto', left: 9 }); } } else { this.container.css({ top: containerTop, left: this.element.offset().left - parentOffset.left, right: 'auto' }); if (this.container.offset().left + this.container.outerWidth() > $(window).width()) { this.container.css({ left: 'auto', right: 0 }); } } }, show: function(e) { if (this.isShowing) return; // Create a click proxy that is private to this instance of datepicker, for unbinding this._outsideClickProxy = $.proxy(function(e) { this.outsideClick(e); }, this); // Bind global datepicker mousedown for hiding and $(document) .on('mousedown.daterangepicker', this._outsideClickProxy) // also support mobile devices .on('touchend.daterangepicker', this._outsideClickProxy) // also explicitly play nice with Bootstrap dropdowns, which stopPropagation when clicking them .on('click.daterangepicker', '[data-toggle=dropdown]', this._outsideClickProxy) // and also close when focus changes to outside the picker (eg. tabbing between controls) .on('focusin.daterangepicker', this._outsideClickProxy); // Reposition the picker if the window is resized while it's open $(window).on('resize.daterangepicker', $.proxy(function(e) { this.move(e); }, this)); this.oldStartDate = this.startDate.clone(); this.oldEndDate = this.endDate.clone(); this.updateView(); this.container.show(); this.move(); this.element.trigger('show.daterangepicker', this); this.isShowing = true; }, hide: function(e) { if (!this.isShowing) return; //incomplete date selection, revert to last values if (!this.endDate) { this.startDate = this.oldStartDate.clone(); this.endDate = this.oldEndDate.clone(); } //if a new date range was selected, invoke the user callback function if (!this.startDate.isSame(this.oldStartDate) || !this.endDate.isSame(this.oldEndDate)) this.callback(this.startDate, this.endDate, this.chosenLabel); //if picker is attached to a text input, update it this.updateElement(); $(document).off('.daterangepicker'); $(window).off('.daterangepicker'); this.container.hide(); this.element.trigger('hide.daterangepicker', this); this.isShowing = false; }, toggle: function(e) { if (this.isShowing) { this.hide(); } else { this.show(); } }, outsideClick: function(e) { var target = $(e.target); // if the page is clicked anywhere except within the daterangerpicker/button // itself then call this.hide() if ( // ie modal dialog fix e.type == "focusin" || target.closest(this.element).length || target.closest(this.container).length || target.closest('.calendar-table').length ) return; this.hide(); }, showCalendars: function() { this.container.addClass('show-calendar'); this.move(); this.element.trigger('showCalendar.daterangepicker', this); }, hideCalendars: function() { this.container.removeClass('show-calendar'); this.element.trigger('hideCalendar.daterangepicker', this); }, hoverRange: function(e) { //ignore mouse movements while an above-calendar text input has focus if (this.container.find('input[name=daterangepicker_start]').is(":focus") || this.container.find('input[name=daterangepicker_end]').is(":focus")) return; var label = e.target.innerHTML; if (label == this.locale.customRangeLabel) { this.updateView(); } else { var dates = this.ranges[label]; this.container.find('input[name=daterangepicker_start]').val(dates[0].format(this.locale.format)); this.container.find('input[name=daterangepicker_end]').val(dates[1].format(this.locale.format)); } }, clickRange: function(e) { var label = e.target.innerHTML; this.chosenLabel = label; if (label == this.locale.customRangeLabel) { this.showCalendars(); } else { var dates = this.ranges[label]; this.startDate = dates[0]; this.endDate = dates[1]; if (!this.timePicker) { this.startDate.startOf('day'); this.endDate.endOf('day'); } this.hideCalendars(); this.clickApply(); } }, clickPrev: function(e) { var cal = $(e.target).parents('.calendar'); if (cal.hasClass('left')) { this.leftCalendar.month.subtract(1, 'month'); if (this.linkedCalendars) this.rightCalendar.month.subtract(1, 'month'); } else { this.rightCalendar.month.subtract(1, 'month'); } this.updateCalendars(); }, clickNext: function(e) { var cal = $(e.target).parents('.calendar'); if (cal.hasClass('left')) { this.leftCalendar.month.add(1, 'month'); } else { this.rightCalendar.month.add(1, 'month'); if (this.linkedCalendars) this.leftCalendar.month.add(1, 'month'); } this.updateCalendars(); }, hoverDate: function(e) { //ignore mouse movements while an above-calendar text input has focus if (this.container.find('input[name=daterangepicker_start]').is(":focus") || this.container.find('input[name=daterangepicker_end]').is(":focus")) return; //ignore dates that can't be selected if (!$(e.target).hasClass('available')) return; //have the text inputs above calendars reflect the date being hovered over var title = $(e.target).attr('data-title'); var row = title.substr(1, 1); var col = title.substr(3, 1); var cal = $(e.target).parents('.calendar'); var date = cal.hasClass('left') ? this.leftCalendar.calendar[row][col] : this.rightCalendar.calendar[row][col]; if (this.endDate) { this.container.find('input[name=daterangepicker_start]').val(date.format(this.locale.format)); } else { this.container.find('input[name=daterangepicker_end]').val(date.format(this.locale.format)); } //highlight the dates between the start date and the date being hovered as a potential end date var leftCalendar = this.leftCalendar; var rightCalendar = this.rightCalendar; var startDate = this.startDate; if (!this.endDate) { this.container.find('.calendar td').each(function(index, el) { //skip week numbers, only look at dates if ($(el).hasClass('week')) return; var title = $(el).attr('data-title'); var row = title.substr(1, 1); var col = title.substr(3, 1); var cal = $(el).parents('.calendar'); var dt = cal.hasClass('left') ? leftCalendar.calendar[row][col] : rightCalendar.calendar[row][col]; if (dt.isAfter(startDate) && dt.isBefore(date)) { $(el).addClass('in-range'); } else { $(el).removeClass('in-range'); } }); } }, clickDate: function(e) { if (!$(e.target).hasClass('available')) return; var title = $(e.target).attr('data-title'); var row = title.substr(1, 1); var col = title.substr(3, 1); var cal = $(e.target).parents('.calendar'); var date = cal.hasClass('left') ? this.leftCalendar.calendar[row][col] : this.rightCalendar.calendar[row][col]; // // this function needs to do a few things: // * alternate between selecting a start and end date for the range, // * if the time picker is enabled, apply the hour/minute/second from the select boxes to the clicked date // * if autoapply is enabled, and an end date was chosen, apply the selection // * if single date picker mode, and time picker isn't enabled, apply the selection immediately // if (this.endDate || date.isBefore(this.startDate)) { if (this.timePicker) { var hour = parseInt(this.container.find('.left .hourselect').val(), 10); if (!this.timePicker24Hour) { var ampm = cal.find('.ampmselect').val(); if (ampm === 'PM' && hour < 12) hour += 12; if (ampm === 'AM' && hour === 12) hour = 0; } var minute = parseInt(this.container.find('.left .minuteselect').val(), 10); var second = this.timePickerSeconds ? parseInt(this.container.find('.left .secondselect').val(), 10) : 0; date = date.clone().hour(hour).minute(minute).second(second); } this.endDate = null; this.setStartDate(date.clone()); } else { if (this.timePicker) { var hour = parseInt(this.container.find('.right .hourselect').val(), 10); if (!this.timePicker24Hour) { var ampm = this.container.find('.right .ampmselect').val(); if (ampm === 'PM' && hour < 12) hour += 12; if (ampm === 'AM' && hour === 12) hour = 0; } var minute = parseInt(this.container.find('.right .minuteselect').val(), 10); var second = this.timePickerSeconds ? parseInt(this.container.find('.right .secondselect').val(), 10) : 0; date = date.clone().hour(hour).minute(minute).second(second); } this.setEndDate(date.clone()); if (this.autoApply) this.clickApply(); } if (this.singleDatePicker) { this.setEndDate(this.startDate); if (!this.timePicker) this.clickApply(); } this.updateView(); }, clickApply: function(e) { this.hide(); this.element.trigger('apply.daterangepicker', this); }, clickCancel: function(e) { this.startDate = this.oldStartDate; this.endDate = this.oldEndDate; this.hide(); this.element.trigger('cancel.daterangepicker', this); }, monthOrYearChanged: function(e) { var isLeft = $(e.target).closest('.calendar').hasClass('left'), leftOrRight = isLeft ? 'left' : 'right', cal = this.container.find('.calendar.'+leftOrRight); // Month must be Number for new moment versions var month = parseInt(cal.find('.monthselect').val(), 10); var year = cal.find('.yearselect').val(); if (!isLeft) { if (year < this.startDate.year() || (year == this.startDate.year() && month < this.startDate.month())) { month = this.startDate.month(); year = this.startDate.year(); } } if (this.minDate) { if (year < this.minDate.year() || (year == this.minDate.year() && month < this.minDate.month())) { month = this.minDate.month(); year = this.minDate.year(); } } if (this.maxDate) { if (year > this.maxDate.year() || (year == this.maxDate.year() && month > this.maxDate.month())) { month = this.maxDate.month(); year = this.maxDate.year(); } } if (isLeft) { this.leftCalendar.month.month(month).year(year); if (this.linkedCalendars) this.rightCalendar.month = this.leftCalendar.month.clone().add(1, 'month'); } else { this.rightCalendar.month.month(month).year(year); if (this.linkedCalendars) this.leftCalendar.month = this.rightCalendar.month.clone().subtract(1, 'month'); } this.updateCalendars(); }, timeChanged: function(e) { var cal = $(e.target).closest('.calendar'), isLeft = cal.hasClass('left'); var hour = parseInt(cal.find('.hourselect').val(), 10); var minute = parseInt(cal.find('.minuteselect').val(), 10); var second = this.timePickerSeconds ? parseInt(cal.find('.secondselect').val(), 10) : 0; if (!this.timePicker24Hour) { var ampm = cal.find('.ampmselect').val(); if (ampm === 'PM' && hour < 12) hour += 12; if (ampm === 'AM' && hour === 12) hour = 0; } if (isLeft) { var start = this.startDate.clone(); start.hour(hour); start.minute(minute); start.second(second); this.setStartDate(start); if (this.singleDatePicker) { this.endDate = this.startDate.clone(); } else if (this.endDate && this.endDate.format('YYYY-MM-DD') == start.format('YYYY-MM-DD') && this.endDate.isBefore(start)) { this.setEndDate(start.clone()); } } else if (this.endDate) { var end = this.endDate.clone(); end.hour(hour); end.minute(minute); end.second(second); this.setEndDate(end); } //update the calendars so all clickable dates reflect the new time component this.updateCalendars(); //update the form inputs above the calendars with the new time this.updateFormInputs(); //re-render the time pickers because changing one selection can affect what's enabled in another this.renderTimePicker('left'); this.renderTimePicker('right'); }, formInputsChanged: function(e) { var isRight = $(e.target).closest('.calendar').hasClass('right'); var start = moment(this.container.find('input[name="daterangepicker_start"]').val(), this.locale.format); var end = moment(this.container.find('input[name="daterangepicker_end"]').val(), this.locale.format); if (start.isValid() && end.isValid()) { if (isRight && end.isBefore(start)) start = end.clone(); this.setStartDate(start); this.setEndDate(end); if (isRight) { this.container.find('input[name="daterangepicker_start"]').val(this.startDate.format(this.locale.format)); } else { this.container.find('input[name="daterangepicker_end"]').val(this.endDate.format(this.locale.format)); } } this.updateCalendars(); if (this.timePicker) { this.renderTimePicker('left'); this.renderTimePicker('right'); } }, elementChanged: function() { if (!this.element.is('input')) return; if (!this.element.val().length) return; if (this.element.val().length < this.locale.format.length) return; var dateString = this.element.val().split(this.locale.separator), start = null, end = null; if (dateString.length === 2) { start = moment(dateString[0], this.locale.format); end = moment(dateString[1], this.locale.format); } if (this.singleDatePicker || start === null || end === null) { start = moment(this.element.val(), this.locale.format); end = start; } if (!start.isValid() || !end.isValid()) return; this.setStartDate(start); this.setEndDate(end); this.updateView(); }, keydown: function(e) { //hide on tab or enter if ((e.keyCode === 9) || (e.keyCode === 13)) { this.hide(); } }, updateElement: function() { if (this.element.is('input') && !this.singleDatePicker && this.autoUpdateInput) { this.element.val(this.startDate.format(this.locale.format) + this.locale.separator + this.endDate.format(this.locale.format)); this.element.trigger('change'); } else if (this.element.is('input') && this.autoUpdateInput) { this.element.val(this.startDate.format(this.locale.format)); this.element.trigger('change'); } }, remove: function() { this.container.remove(); this.element.off('.daterangepicker'); this.element.removeData(); } }; $.fn.daterangepicker = function(options, callback) { this.each(function() { var el = $(this); if (el.data('daterangepicker')) el.data('daterangepicker').remove(); el.data('daterangepicker', new DateRangePicker(el, options, callback)); }); return this; }; return DateRangePicker; }));
d3.parcoords = function(config) { var __ = { data: [], dimensions: [], types: {}, brushed: false, mode: "default", rate: 20, width: 600, height: 300, margin: { top: 24, right: 0, bottom: 12, left: 0 }, color: "#069", composite: "source-over", alpha: 0.7 }; extend(__, config); var pc = function(selection) { selection = pc.selection = d3.select(selection); __.width = selection[0][0].clientWidth; __.height = selection[0][0].clientHeight; // canvas data layers ["shadows", "marks", "foreground", "highlight"].forEach(function(layer) { canvas[layer] = selection .append("canvas") .attr("class", layer)[0][0]; ctx[layer] = canvas[layer].getContext("2d"); }); // svg tick and brush layers pc.svg = selection .append("svg") .attr("width", __.width) .attr("height", __.height) .append("svg:g") .attr("transform", "translate(" + __.margin.left + "," + __.margin.top + ")"); return pc; }; var events = d3.dispatch.apply(this,["render", "resize", "highlight", "brush"].concat(d3.keys(__))), w = function() { return __.width - __.margin.right - __.margin.left; }, h = function() { return __.height - __.margin.top - __.margin.bottom }, flags = { brushable: false, reorderable: false, axes: false, interactive: false, shadows: false, debug: false }, xscale = d3.scale.ordinal(), yscale = {}, dragging = {}, line = d3.svg.line(), axis = d3.svg.axis().orient("left").ticks(5), g, // groups for axes, brushes ctx = {}, canvas = {}; // side effects for setters var side_effects = d3.dispatch.apply(this,d3.keys(__)) .on("composite", function(d) { ctx.foreground.globalCompositeOperation = d.value; }) .on("alpha", function(d) { ctx.foreground.globalAlpha = d.value; }) .on("width", function(d) { pc.resize(); }) .on("height", function(d) { pc.resize(); }) .on("margin", function(d) { pc.resize(); }) .on("rate", function(d) { rqueue.rate(d.value); }) .on("data", function(d) { if (flags.shadows) paths(__.data, ctx.shadows); }) .on("dimensions", function(d) { xscale.domain(__.dimensions); if (flags.interactive) pc.render().updateAxes(); }); // expose the state of the chart pc.state = __; pc.flags = flags; // create getter/setters getset(pc, __, events); // expose events d3.rebind(pc, events, "on"); // tick formatting d3.rebind(pc, axis, "ticks", "orient", "tickValues", "tickSubdivide", "tickSize", "tickPadding", "tickFormat"); // getter/setter with event firing function getset(obj,state,events) { d3.keys(state).forEach(function(key) { obj[key] = function(x) { if (!arguments.length) return state[key]; var old = state[key]; state[key] = x; side_effects[key].call(pc,{"value": x, "previous": old}); events[key].call(pc,{"value": x, "previous": old}); return obj; }; }); }; function extend(target, source) { for (key in source) { target[key] = source[key]; } return target; }; pc.autoscale = function() { // yscale var defaultScales = { "number": function(k) { return d3.scale.linear() .domain(d3.extent(__.data, function(d) { return +d[k]; })) .range([h()+1, 1]) }, "string": function(k) { return d3.scale.ordinal() .domain(__.data.map(function(p) { return p[k]; })) .rangePoints([h()+1, 1]) } }; __.dimensions.forEach(function(k) { yscale[k] = defaultScales[__.types[k]](k); }); // hack to remove ordinal dimensions with many values pc.dimensions(pc.dimensions().filter(function(p,i) { var uniques = yscale[p].domain().length; if (__.types[p] == "string" && (uniques > 60 || uniques < 2)) { return false; } return true; })); // xscale xscale.rangePoints([0, w()], 1); // canvas sizes pc.selection.selectAll("canvas") .style("margin-top", __.margin.top + "px") .style("margin-left", __.margin.left + "px") .attr("width", w()+2) .attr("height", h()+2) // default styles, needs to be set when canvas width changes ctx.foreground.strokeStyle = __.color; ctx.foreground.lineWidth = 1.4; ctx.foreground.globalCompositeOperation = __.composite; ctx.foreground.globalAlpha = __.alpha; ctx.highlight.lineWidth = 3; ctx.shadows.strokeStyle = "#dadada"; return this; }; pc.detectDimensions = function() { pc.types(pc.detectDimensionTypes(__.data)); pc.dimensions(d3.keys(pc.types())); return this; }; // a better "typeof" from this post: http://stackoverflow.com/questions/7390426/better-way-to-get-type-of-a-javascript-variable pc.toType = function(v) { return ({}).toString.call(v).match(/\s([a-zA-Z]+)/)[1].toLowerCase() }; // try to coerce to number before returning type pc.toTypeCoerceNumbers = function(v) { if ((parseFloat(v) == v) && (v != null)) return "number"; return pc.toType(v); }; // attempt to determine types of each dimension based on first row of data pc.detectDimensionTypes = function(data) { var types = {} d3.keys(data[0]) .forEach(function(col) { types[col] = pc.toTypeCoerceNumbers(data[0][col]); }); return types; }; pc.render = function() { // try to autodetect dimensions and create scales if (!__.dimensions.length) pc.detectDimensions(); if (!(__.dimensions[0] in yscale)) pc.autoscale(); pc.render[__.mode](); events.render.call(this); return this; }; pc.render.default = function() { pc.clear('foreground'); if (__.brushed) { __.brushed.forEach(path_foreground); } else { __.data.forEach(path_foreground); } }; var rqueue = d3.renderQueue(path_foreground) .rate(50) .clear(function() { pc.clear('foreground'); }); pc.render.queue = function() { if (__.brushed) { rqueue(__.brushed); } else { rqueue(__.data); } }; pc.shadows = function() { flags.shadows = true; if (__.data.length > 0) paths(__.data, ctx.shadows); return this; }; // draw little dots on the axis line where data intersects pc.axisDots = function() { var ctx = pc.ctx.marks; ctx.globalAlpha = d3.min([1/Math.pow(data.length, 1/2), 1]); __.data.forEach(function(d) { __.dimensions.map(function(p,i) { ctx.fillRect(position(p)-0.75,yscale[p](d[p])-0.75,1.5,1.5); }); }); return this; }; // draw single polyline function color_path(d, ctx) { ctx.strokeStyle = d3.functor(__.color)(d); ctx.beginPath(); __.dimensions.map(function(p,i) { if (i == 0) { ctx.moveTo(position(p),yscale[p](d[p])); } else { ctx.lineTo(position(p),yscale[p](d[p])); } }); ctx.stroke(); }; // draw many polylines of the same color function paths(data, ctx) { ctx.clearRect(-1,-1,w()+2,h()+2); ctx.beginPath(); data.forEach(function(d) { __.dimensions.map(function(p,i) { if (i == 0) { ctx.moveTo(position(p),yscale[p](d[p])); } else { ctx.lineTo(position(p),yscale[p](d[p])); } }); }); ctx.stroke(); }; function path_foreground(d) { return color_path(d, ctx.foreground); }; function path_highlight(d) { return color_path(d, ctx.highlight); }; pc.clear = function(layer) { ctx[layer].clearRect(0,0,w()+2,h()+2); return this; }; pc.createAxes = function() { if (g) pc.removeAxes(); // Add a group element for each dimension. g = pc.svg.selectAll(".dimension") .data(__.dimensions, function(d) { return d; }) .enter().append("svg:g") .attr("class", "dimension") .attr("transform", function(d) { return "translate(" + xscale(d) + ")"; }) // Add an axis and title. g.append("svg:g") .attr("class", "axis") .attr("transform", "translate(0,0)") .each(function(d) { d3.select(this).call(axis.scale(yscale[d])); }) .append("svg:text") .attr({ "text-anchor": "middle", "y": 0, "transform": "translate(0,-12)", "x": 0, "class": "label" }) .text(String) flags.axes= true; return this; }; pc.removeAxes = function() { g.remove(); return this; }; pc.updateAxes = function() { var g_data = pc.svg.selectAll(".dimension") .data(__.dimensions, function(d) { return d; }) g_data.enter().append("svg:g") .attr("class", "dimension") .attr("transform", function(p) { return "translate(" + position(p) + ")"; }) .style("opacity", 0) .append("svg:g") .attr("class", "axis") .attr("transform", "translate(0,0)") .each(function(d) { d3.select(this).call(axis.scale(yscale[d])); }) .append("svg:text") .attr({ "text-anchor": "middle", "y": 0, "transform": "translate(0,-12)", "x": 0, "class": "label" }) .text(String); g_data.exit().remove(); g = pc.svg.selectAll(".dimension"); g.transition().duration(1100) .attr("transform", function(p) { return "translate(" + position(p) + ")"; }) .style("opacity", 1) if (flags.shadows) paths(__.data, ctx.shadows); return this; }; pc.brushable = function() { if (!g) pc.createAxes(); // Add and store a brush for each axis. g.append("svg:g") .attr("class", "brush") .each(function(d) { d3.select(this).call( yscale[d].brush = d3.svg.brush() .y(yscale[d]) .on("brush", pc.brush) ); }) .selectAll("rect") .style("visibility", null) .attr("x", -15) .attr("width", 30) flags.brushable = true; return this; }; // Jason Davies, http://bl.ocks.org/1341281 pc.reorderable = function() { if (!g) pc.createAxes(); g.style("cursor", "move") .call(d3.behavior.drag() .on("dragstart", function(d) { dragging[d] = this.__origin__ = xscale(d); }) .on("drag", function(d) { dragging[d] = Math.min(w(), Math.max(0, this.__origin__ += d3.event.dx)); __.dimensions.sort(function(a, b) { return position(a) - position(b); }); xscale.domain(__.dimensions); pc.render(); g.attr("transform", function(d) { return "translate(" + position(d) + ")"; }) }) .on("dragend", function(d) { delete this.__origin__; delete dragging[d]; d3.select(this).transition().attr("transform", "translate(" + xscale(d) + ")"); pc.render(); })); flags.reorderable = true; return this; }; // pairs of adjacent dimensions pc.adjacent_pairs = function(arr) { var ret = []; for (var i = 0; i < arr.length-1; i++) { ret.push([arr[i],arr[i+1]]); }; return ret; }; pc.interactive = function() { flags.interactive = true; return this; }; // Get data within brushes pc.brush = function() { __.brushed = selected(); events.brush.call(pc,__.brushed); pc.render(); }; // expose a few objects pc.xscale = xscale; pc.yscale = yscale; pc.ctx = ctx; pc.canvas = canvas; pc.g = function() { return g; }; // TODO pc.brushReset = function(dimension) { yscale[dimension].brush.clear()( pc.g() .filter(function(p) { return dimension == p; }) ) return this; }; // rescale for height, width and margins // TODO currently assumes chart is brushable, and destroys old brushes pc.resize = function() { // selection size pc.selection.select("svg") .attr("width", __.width) .attr("height", __.height) pc.svg.attr("transform", "translate(" + __.margin.left + "," + __.margin.top + ")"); // scales pc.autoscale(); // axes, destroys old brushes. the current brush state should pass through in the future if (g) pc.createAxes().brushable(); events.resize.call(this, {width: __.width, height: __.height, margin: __.margin}); return this; }; // highlight an array of data pc.highlight = function(data) { pc.clear("highlight"); d3.select(canvas.foreground).classed("faded", true); data.forEach(path_highlight); events.highlight.call(this,data); return this; }; // clear highlighting pc.unhighlight = function(data) { pc.clear("highlight"); d3.select(canvas.foreground).classed("faded", false); return this; }; // calculate 2d intersection of line a->b with line c->d // points are objects with x and y properties pc.intersection = function(a, b, c, d) { return { x: ((a.x * b.y - a.y * b.x) * (c.x - d.x) - (a.x - b.x) * (c.x * d.y - c.y * d.x)) / ((a.x - b.x) * (c.y - d.y) - (a.y - b.y) * (c.x - d.x)), y: ((a.x * b.y - a.y * b.x) * (c.y - d.y) - (a.y - b.y) * (c.x * d.y - c.y * d.x)) / ((a.x - b.x) * (c.y - d.y) - (a.y - b.y) * (c.x - d.x)) }; }; function is_brushed(p) { return !yscale[p].brush.empty(); }; // data within extents function selected() { var actives = __.dimensions.filter(is_brushed), extents = actives.map(function(p) { return yscale[p].brush.extent(); }); // test if within range var within = { "number": function(d,p,dimension) { return extents[dimension][0] <= d[p] && d[p] <= extents[dimension][1] }, "string": function(d,p,dimension) { return extents[dimension][0] <= yscale[p](d[p]) && yscale[p](d[p]) <= extents[dimension][1] } }; return __.data .filter(function(d) { return actives.every(function(p, dimension) { return within[__.types[p]](d,p,dimension); }); }); }; function position(d) { var v = dragging[d]; return v == null ? xscale(d) : v; } pc.toString = function() { return "Parallel Coordinates: " + __.dimensions.length + " dimensions (" + d3.keys(__.data[0]).length + " total) , " + __.data.length + " rows"; }; pc.version = "0.1.7"; return pc; }; d3.renderQueue = (function(func) { var _queue = [], // data to be rendered _rate = 10, // number of calls per frame _clear = function() {}, // clearing function _i = 0; // current iteration var rq = function(data) { if (data) rq.data(data); rq.invalidate(); _clear(); rq.render(); }; rq.render = function() { _i = 0; var valid = true; rq.invalidate = function() { valid = false; }; function doFrame() { if (!valid) return false; if (_i > _queue.length) return false; var chunk = _queue.slice(_i,_i+_rate); _i += _rate; chunk.map(func); d3.timer(doFrame); } doFrame(); }; rq.data = function(data) { rq.invalidate(); _queue = data.slice(0); return rq; }; rq.rate = function(value) { if (!arguments.length) return _rate; _rate = value; return rq; }; rq.remaining = function() { return _queue.length - _i; }; // clear the canvas rq.clear = function(func) { if (!arguments.length) { _clear(); return rq; } _clear = func; return rq; }; rq.invalidate = function() {}; return rq; });
define(function () { // Italian function ending (count, first, second, third) { if ((count % 100 > 9 && count % 100 < 21) || count % 10 === 0) { if (count % 10 > 1) { return second; } else { return third; } } else { return first; } } return { inputTooLong: function (args) { var overChars = args.input.length - args.maximum; var message = 'Pašalinkite ' + overChars + ' simbol'; message += ending(overChars, 'ių', 'ius', 'į'); return message; }, inputTooShort: function (args) { var remainingChars = args.minimum - args.input.length; var message = 'Įrašykite dar ' + remainingChars + ' simbol'; message += ending(remainingChars, 'ių', 'ius', 'į'); return message; }, loadingMore: function () { return 'Kraunama daugiau rezultatų…'; }, maximumSelected: function (args) { var message = 'Jūs galite pasirinkti tik ' + args.maximum + ' element'; message += ending(args.maximum, 'ų', 'us', 'ą'); return message; }, noResults: function () { return 'Atitikmenų nerasta'; }, searching: function () { return 'Ieškoma…'; } }; });
// // ShellJS // Unix shell commands on top of Node's API // // Copyright (c) 2012 Artur Adib // http://github.com/shelljs/shelljs // var common = require('./src/common'); //@ //@ All commands run synchronously, unless otherwise stated. //@ All commands accept standard bash globbing characters (`*`, `?`, etc.), //@ compatible with the [node glob module](https://github.com/isaacs/node-glob). //@ //@ For less-commonly used commands and features, please check out our [wiki //@ page](https://github.com/shelljs/shelljs/wiki). //@ // Include the docs for all the default commands //@commands // Load all default commands require('./commands').forEach(function (command) { require('./src/' + command); }); //@ //@ ### exit(code) //@ Exits the current process with the given exit code. exports.exit = process.exit; //@include ./src/error exports.error = require('./src/error'); //@include ./src/common exports.ShellString = common.ShellString; //@ //@ ### env['VAR_NAME'] //@ Object containing environment variables (both getter and setter). Shortcut //@ to process.env. exports.env = process.env; //@ //@ ### Pipes //@ //@ Examples: //@ //@ ```javascript //@ grep('foo', 'file1.txt', 'file2.txt').sed(/o/g, 'a').to('output.txt'); //@ echo('files with o\'s in the name:\n' + ls().grep('o')); //@ cat('test.js').exec('node'); // pipe to exec() call //@ ``` //@ //@ Commands can send their output to another command in a pipe-like fashion. //@ `sed`, `grep`, `cat`, `exec`, `to`, and `toEnd` can appear on the right-hand //@ side of a pipe. Pipes can be chained. //@ //@ ## Configuration //@ exports.config = common.config; //@ //@ ### config.silent //@ //@ Example: //@ //@ ```javascript //@ var sh = require('shelljs'); //@ var silentState = sh.config.silent; // save old silent state //@ sh.config.silent = true; //@ /* ... */ //@ sh.config.silent = silentState; // restore old silent state //@ ``` //@ //@ Suppresses all command output if `true`, except for `echo()` calls. //@ Default is `false`. //@ //@ ### config.fatal //@ //@ Example: //@ //@ ```javascript //@ require('shelljs/global'); //@ config.fatal = true; // or set('-e'); //@ cp('this_file_does_not_exist', '/dev/null'); // throws Error here //@ /* more commands... */ //@ ``` //@ //@ If `true` the script will throw a Javascript error when any shell.js //@ command encounters an error. Default is `false`. This is analogous to //@ Bash's `set -e` //@ //@ ### config.verbose //@ //@ Example: //@ //@ ```javascript //@ config.verbose = true; // or set('-v'); //@ cd('dir/'); //@ ls('subdir/'); //@ ``` //@ //@ Will print each command as follows: //@ //@ ``` //@ cd dir/ //@ ls subdir/ //@ ``` //@ //@ ### config.globOptions //@ //@ Example: //@ //@ ```javascript //@ config.globOptions = {nodir: true}; //@ ``` //@ //@ Use this value for calls to `glob.sync()` instead of the default options. //@ //@ ### config.reset() //@ //@ Example: //@ //@ ```javascript //@ var shell = require('shelljs'); //@ // Make changes to shell.config, and do stuff... //@ /* ... */ //@ shell.config.reset(); // reset to original state //@ // Do more stuff, but with original settings //@ /* ... */ //@ ``` //@ //@ Reset shell.config to the defaults: //@ //@ ```javascript //@ { //@ fatal: false, //@ globOptions: {}, //@ maxdepth: 255, //@ noglob: false, //@ silent: false, //@ verbose: false, //@ } //@ ```
!function() { var topojson = { version: "1.4.6", mesh: mesh, feature: featureOrCollection, neighbors: neighbors, presimplify: presimplify }; function merge(topology, arcs) { var fragmentByStart = {}, fragmentByEnd = {}; arcs.forEach(function(i) { var e = ends(i), start = e[0], end = e[1], f, g; if (f = fragmentByEnd[start]) { delete fragmentByEnd[f.end]; f.push(i); f.end = end; if (g = fragmentByStart[end]) { delete fragmentByStart[g.start]; var fg = g === f ? f : f.concat(g); fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg; } else if (g = fragmentByEnd[end]) { delete fragmentByStart[g.start]; delete fragmentByEnd[g.end]; var fg = f.concat(g.map(function(i) { return ~i; }).reverse()); fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.start] = fg; } else { fragmentByStart[f.start] = fragmentByEnd[f.end] = f; } } else if (f = fragmentByStart[end]) { delete fragmentByStart[f.start]; f.unshift(i); f.start = start; if (g = fragmentByEnd[start]) { delete fragmentByEnd[g.end]; var gf = g === f ? f : g.concat(f); fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf; } else if (g = fragmentByStart[start]) { delete fragmentByStart[g.start]; delete fragmentByEnd[g.end]; var gf = g.map(function(i) { return ~i; }).reverse().concat(f); fragmentByStart[gf.start = g.end] = fragmentByEnd[gf.end = f.end] = gf; } else { fragmentByStart[f.start] = fragmentByEnd[f.end] = f; } } else if (f = fragmentByStart[start]) { delete fragmentByStart[f.start]; f.unshift(~i); f.start = end; if (g = fragmentByEnd[end]) { delete fragmentByEnd[g.end]; var gf = g === f ? f : g.concat(f); fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf; } else if (g = fragmentByStart[end]) { delete fragmentByStart[g.start]; delete fragmentByEnd[g.end]; var gf = g.map(function(i) { return ~i; }).reverse().concat(f); fragmentByStart[gf.start = g.end] = fragmentByEnd[gf.end = f.end] = gf; } else { fragmentByStart[f.start] = fragmentByEnd[f.end] = f; } } else if (f = fragmentByEnd[end]) { delete fragmentByEnd[f.end]; f.push(~i); f.end = start; if (g = fragmentByEnd[start]) { delete fragmentByStart[g.start]; var fg = g === f ? f : f.concat(g); fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg; } else if (g = fragmentByStart[start]) { delete fragmentByStart[g.start]; delete fragmentByEnd[g.end]; var fg = f.concat(g.map(function(i) { return ~i; }).reverse()); fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.start] = fg; } else { fragmentByStart[f.start] = fragmentByEnd[f.end] = f; } } else { f = [i]; fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f; } }); function ends(i) { var arc = topology.arcs[i], p0 = arc[0], p1 = [0, 0]; arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; }); return [p0, p1]; } var fragments = []; for (var k in fragmentByEnd) fragments.push(fragmentByEnd[k]); return fragments; } function mesh(topology, o, filter) { var arcs = []; if (arguments.length > 1) { var geomsByArc = [], geom; function arc(i) { if (i < 0) i = ~i; (geomsByArc[i] || (geomsByArc[i] = [])).push(geom); } function line(arcs) { arcs.forEach(arc); } function polygon(arcs) { arcs.forEach(line); } function geometry(o) { if (o.type === "GeometryCollection") o.geometries.forEach(geometry); else if (o.type in geometryType) { geom = o; geometryType[o.type](o.arcs); } } var geometryType = { LineString: line, MultiLineString: polygon, Polygon: polygon, MultiPolygon: function(arcs) { arcs.forEach(polygon); } }; geometry(o); geomsByArc.forEach(arguments.length < 3 ? function(geoms, i) { arcs.push(i); } : function(geoms, i) { if (filter(geoms[0], geoms[geoms.length - 1])) arcs.push(i); }); } else { for (var i = 0, n = topology.arcs.length; i < n; ++i) arcs.push(i); } return object(topology, {type: "MultiLineString", arcs: merge(topology, arcs)}); } function featureOrCollection(topology, o) { return o.type === "GeometryCollection" ? { type: "FeatureCollection", features: o.geometries.map(function(o) { return feature(topology, o); }) } : feature(topology, o); } function feature(topology, o) { var f = { type: "Feature", id: o.id, properties: o.properties || {}, geometry: object(topology, o) }; if (o.id == null) delete f.id; return f; } function object(topology, o) { var absolute = transformAbsolute(topology.transform), arcs = topology.arcs; function arc(i, points) { if (points.length) points.pop(); for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length, p; k < n; ++k) { points.push(p = a[k].slice()); absolute(p, k); } if (i < 0) reverse(points, n); } function point(p) { p = p.slice(); absolute(p, 0); return p; } function line(arcs) { var points = []; for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points); if (points.length < 2) points.push(points[0].slice()); return points; } function ring(arcs) { var points = line(arcs); while (points.length < 4) points.push(points[0].slice()); return points; } function polygon(arcs) { return arcs.map(ring); } function geometry(o) { var t = o.type; return t === "GeometryCollection" ? {type: t, geometries: o.geometries.map(geometry)} : t in geometryType ? {type: t, coordinates: geometryType[t](o)} : null; } var geometryType = { Point: function(o) { return point(o.coordinates); }, MultiPoint: function(o) { return o.coordinates.map(point); }, LineString: function(o) { return line(o.arcs); }, MultiLineString: function(o) { return o.arcs.map(line); }, Polygon: function(o) { return polygon(o.arcs); }, MultiPolygon: function(o) { return o.arcs.map(polygon); } }; return geometry(o); } function reverse(array, n) { var t, j = array.length, i = j - n; while (i < --j) t = array[i], array[i++] = array[j], array[j] = t; } function bisect(a, x) { var lo = 0, hi = a.length; while (lo < hi) { var mid = lo + hi >>> 1; if (a[mid] < x) lo = mid + 1; else hi = mid; } return lo; } function neighbors(objects) { var indexesByArc = {}, // arc index -> array of object indexes neighbors = objects.map(function() { return []; }); function line(arcs, i) { arcs.forEach(function(a) { if (a < 0) a = ~a; var o = indexesByArc[a]; if (o) o.push(i); else indexesByArc[a] = [i]; }); } function polygon(arcs, i) { arcs.forEach(function(arc) { line(arc, i); }); } function geometry(o, i) { if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); }); else if (o.type in geometryType) geometryType[o.type](o.arcs, i); } var geometryType = { LineString: line, MultiLineString: polygon, Polygon: polygon, MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); } }; objects.forEach(geometry); for (var i in indexesByArc) { for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) { for (var k = j + 1; k < m; ++k) { var ij = indexes[j], ik = indexes[k], n; if ((n = neighbors[ij])[i = bisect(n, ik)] !== ik) n.splice(i, 0, ik); if ((n = neighbors[ik])[i = bisect(n, ij)] !== ij) n.splice(i, 0, ij); } } } return neighbors; } function presimplify(topology, triangleArea) { var absolute = transformAbsolute(topology.transform), relative = transformRelative(topology.transform), heap = minHeap(compareArea), maxArea = 0, triangle; if (!triangleArea) triangleArea = cartesianArea; topology.arcs.forEach(function(arc) { var triangles = []; arc.forEach(absolute); for (var i = 1, n = arc.length - 1; i < n; ++i) { triangle = arc.slice(i - 1, i + 2); triangle[1][2] = triangleArea(triangle); triangles.push(triangle); heap.push(triangle); } // Always keep the arc endpoints! arc[0][2] = arc[n][2] = Infinity; for (var i = 0, n = triangles.length; i < n; ++i) { triangle = triangles[i]; triangle.previous = triangles[i - 1]; triangle.next = triangles[i + 1]; } }); while (triangle = heap.pop()) { var previous = triangle.previous, next = triangle.next; // If the area of the current point is less than that of the previous point // to be eliminated, use the latter's area instead. This ensures that the // current point cannot be eliminated without eliminating previously- // eliminated points. if (triangle[1][2] < maxArea) triangle[1][2] = maxArea; else maxArea = triangle[1][2]; if (previous) { previous.next = next; previous[2] = triangle[2]; update(previous); } if (next) { next.previous = previous; next[0] = triangle[0]; update(next); } } topology.arcs.forEach(function(arc) { arc.forEach(relative); }); function update(triangle) { heap.remove(triangle); triangle[1][2] = triangleArea(triangle); heap.push(triangle); } return topology; }; function cartesianArea(triangle) { return Math.abs( (triangle[0][0] - triangle[2][0]) * (triangle[1][1] - triangle[0][1]) - (triangle[0][0] - triangle[1][0]) * (triangle[2][1] - triangle[0][1]) ); } function compareArea(a, b) { return a[1][2] - b[1][2]; } function minHeap(compare) { var heap = {}, array = []; heap.push = function() { for (var i = 0, n = arguments.length; i < n; ++i) { var object = arguments[i]; up(object.index = array.push(object) - 1); } return array.length; }; heap.pop = function() { var removed = array[0], object = array.pop(); if (array.length) { array[object.index = 0] = object; down(0); } return removed; }; heap.remove = function(removed) { var i = removed.index, object = array.pop(); if (i !== array.length) { array[object.index = i] = object; (compare(object, removed) < 0 ? up : down)(i); } return i; }; function up(i) { var object = array[i]; while (i > 0) { var up = ((i + 1) >> 1) - 1, parent = array[up]; if (compare(object, parent) >= 0) break; array[parent.index = i] = parent; array[object.index = i = up] = object; } } function down(i) { var object = array[i]; while (true) { var right = (i + 1) << 1, left = right - 1, down = i, child = array[down]; if (left < array.length && compare(array[left], child) < 0) child = array[down = left]; if (right < array.length && compare(array[right], child) < 0) child = array[down = right]; if (down === i) break; array[child.index = i] = child; array[object.index = i = down] = object; } } return heap; } function transformAbsolute(transform) { if (!transform) return noop; var x0, y0, kx = transform.scale[0], ky = transform.scale[1], dx = transform.translate[0], dy = transform.translate[1]; return function(point, i) { if (!i) x0 = y0 = 0; point[0] = (x0 += point[0]) * kx + dx; point[1] = (y0 += point[1]) * ky + dy; }; } function transformRelative(transform) { if (!transform) return noop; var x0, y0, kx = transform.scale[0], ky = transform.scale[1], dx = transform.translate[0], dy = transform.translate[1]; return function(point, i) { if (!i) x0 = y0 = 0; var x1 = (point[0] - dx) / kx | 0, y1 = (point[1] - dy) / ky | 0; point[0] = x1 - x0; point[1] = y1 - y0; x0 = x1; y0 = y1; }; } function noop() {} if (typeof define === "function" && define.amd) define(topojson); else if (typeof module === "object" && module.exports) module.exports = topojson; else this.topojson = topojson; }();
module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.l = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 236); /******/ }) /************************************************************************/ /******/ ({ /***/ 0: /***/ function(module, exports) { /* globals __VUE_SSR_CONTEXT__ */ // this module is a runtime utility for cleaner component module output and will // be included in the final webpack user bundle module.exports = function normalizeComponent ( rawScriptExports, compiledTemplate, injectStyles, scopeId, moduleIdentifier /* server only */ ) { var esModule var scriptExports = rawScriptExports = rawScriptExports || {} // ES6 modules interop var type = typeof rawScriptExports.default if (type === 'object' || type === 'function') { esModule = rawScriptExports scriptExports = rawScriptExports.default } // Vue.extend constructor export interop var options = typeof scriptExports === 'function' ? scriptExports.options : scriptExports // render functions if (compiledTemplate) { options.render = compiledTemplate.render options.staticRenderFns = compiledTemplate.staticRenderFns } // scopedId if (scopeId) { options._scopeId = scopeId } var hook if (moduleIdentifier) { // server build hook = function (context) { // 2.3 injection context = context || // cached call (this.$vnode && this.$vnode.ssrContext) || // stateful (this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional // 2.2 with runInNewContext: true if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') { context = __VUE_SSR_CONTEXT__ } // inject component styles if (injectStyles) { injectStyles.call(this, context) } // register component module identifier for async chunk inferrence if (context && context._registeredComponents) { context._registeredComponents.add(moduleIdentifier) } } // used by ssr in case component is cached and beforeCreate // never gets called options._ssrRegister = hook } else if (injectStyles) { hook = injectStyles } if (hook) { var functional = options.functional var existing = functional ? options.render : options.beforeCreate if (!functional) { // inject component registration as beforeCreate hook options.beforeCreate = existing ? [].concat(existing, hook) : [hook] } else { // register for functioal component in vue file options.render = function renderWithStyleInjection (h, context) { hook.call(context) return existing(h, context) } } } return { esModule: esModule, exports: scriptExports, options: options } } /***/ }, /***/ 157: /***/ function(module, exports, __webpack_require__) { var Component = __webpack_require__(0)( /* script */ __webpack_require__(79), /* template */ __webpack_require__(181), /* styles */ null, /* scopeId */ null, /* moduleIdentifier (server only) */ null ) module.exports = Component.exports /***/ }, /***/ 181: /***/ function(module, exports) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h; return _c('div', { staticClass: "mint-swipe-item" }, [_vm._t("default")], 2) },staticRenderFns: []} /***/ }, /***/ 236: /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(43); /***/ }, /***/ 43: /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_mint_ui_src_style_empty_css__ = __webpack_require__(5); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_mint_ui_src_style_empty_css___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_mint_ui_src_style_empty_css__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__swipe_src_swipe_item_vue__ = __webpack_require__(157); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__swipe_src_swipe_item_vue___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1__swipe_src_swipe_item_vue__); /* harmony reexport (default from non-hamory) */ __webpack_require__.d(exports, "default", function() { return __WEBPACK_IMPORTED_MODULE_1__swipe_src_swipe_item_vue___default.a; }); /***/ }, /***/ 5: /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /***/ 79: /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // // // // // // /* harmony default export */ exports["default"] = { name: 'mt-swipe-item', mounted: function mounted() { this.$parent && this.$parent.swipeItemCreated(this); }, destroyed: function destroyed() { this.$parent && this.$parent.swipeItemDestroyed(this); } }; /***/ } /******/ });
/*! * json-schema-faker library v0.2.9 * http://json-schema-faker.js.org * @preserve * * Copyright (c) 2014-2016 Alvaro Cabrera & Tomasz Ducin * Released under the MIT license * * Date: 2016-02-04 17:24:39.878Z */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.jsf = f()}})(function(){var define,module,exports;return (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<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ var container = require('./util/container'), traverse = require('./util/traverse'), formats = require('./util/formats'), random = require('./util/random'), merge = require('./util/merge'); var deref = require('deref'); function isKey(prop) { return prop === 'enum' || prop === 'required' || prop === 'definitions'; } function generate(schema, refs, ex) { var $ = deref(); try { var seen = {}; return traverse($(schema, refs, ex), [], function reduce(sub) { if (seen[sub.$ref] <= 0) { delete sub.$ref; delete sub.oneOf; delete sub.anyOf; delete sub.allOf; return sub; } if (typeof sub.$ref === 'string') { var id = sub.$ref; delete sub.$ref; if (!seen[id]) { // TODO: this should be configurable seen[id] = random(1, 5); } seen[id] -= 1; merge(sub, $.util.findByRef(id, $.refs)); } if (Array.isArray(sub.allOf)) { var schemas = sub.allOf; delete sub.allOf; // this is the only case where all sub-schemas // must be resolved before any merge schemas.forEach(function(s) { merge(sub, reduce(s)); }); } if (Array.isArray(sub.oneOf || sub.anyOf)) { var mix = sub.oneOf || sub.anyOf; delete sub.anyOf; delete sub.oneOf; merge(sub, random.pick(mix)); } for (var prop in sub) { if ((Array.isArray(sub[prop]) || typeof sub[prop] === 'object') && !isKey(prop)) { sub[prop] = reduce(sub[prop]); } } return sub; }); } catch (e) { if (e.path) { throw new Error(e.message + ' in ' + '/' + e.path.join('/')); } else { throw e; } } } generate.formats = formats; // returns itself for chaining generate.extend = function(name, cb) { container.set(name, cb); return generate; }; module.exports = generate; },{"./util/container":9,"./util/formats":11,"./util/merge":14,"./util/random":16,"./util/traverse":17,"deref":20}],2:[function(require,module,exports){ var random = require('../util/random'), traverse = require('../util/traverse'), hasProps = require('../util/has-props'); var ParseError = require('../util/error'); function unique(path, items, value, sample, resolve) { var tmp = [], seen = []; function walk(obj) { var json = JSON.stringify(obj); if (seen.indexOf(json) === -1) { seen.push(json); tmp.push(obj); } } items.forEach(walk); // TODO: find a better solution? var limit = 100; while (tmp.length !== items.length) { walk(traverse(value.items || sample, path, resolve)); if (!limit--) { break; } } return tmp; } module.exports = function(value, path, resolve) { var items = []; if (!(value.items || value.additionalItems)) { if (hasProps(value, 'minItems', 'maxItems', 'uniqueItems')) { throw new ParseError('missing items for ' + JSON.stringify(value), path); } return items; } if (Array.isArray(value.items)) { return Array.prototype.concat.apply(items, value.items.map(function(item, key) { return traverse(item, path.concat(['items', key]), resolve); })); } var length = random(value.minItems, value.maxItems, 1, 5), sample = typeof value.additionalItems === 'object' ? value.additionalItems : {}; for (var current = items.length; current < length; current += 1) { items.push(traverse(value.items || sample, path.concat(['items', current]), resolve)); } if (value.uniqueItems) { return unique(path.concat(['items']), items, value, sample, resolve); } return items; }; },{"../util/error":10,"../util/has-props":12,"../util/random":16,"../util/traverse":17}],3:[function(require,module,exports){ module.exports = function() { return Math.random() > 0.5; }; },{}],4:[function(require,module,exports){ var number = require('./number'); // The `integer` type is just a wrapper for the `number` type. The `number` type // returns floating point numbers, and `integer` type truncates the fraction // part, leaving the result as an integer. // module.exports = function(value) { var generated = number(value); // whether the generated number is positive or negative, need to use either // floor (positive) or ceil (negative) function to get rid of the fraction return generated > 0 ? Math.floor(generated) : Math.ceil(generated); }; },{"./number":6}],5:[function(require,module,exports){ module.exports = function() { return null; }; },{}],6:[function(require,module,exports){ var MIN_INTEGER = -100000000, MAX_INTEGER = 100000000; var random = require('../util/random'), string = require('./string'); module.exports = function(value) { if (value.faker || value.chance) { return string(value); } var multipleOf = value.multipleOf; var min = typeof value.minimum === 'undefined' ? MIN_INTEGER : value.minimum, max = typeof value.maximum === 'undefined' ? MAX_INTEGER : value.maximum; if (multipleOf) { max = Math.floor(max / multipleOf) * multipleOf; min = Math.ceil(min / multipleOf) * multipleOf; } if (value.exclusiveMinimum && value.minimum && min === value.minimum) { min += multipleOf || 1; } if (value.exclusiveMaximum && value.maximum && max === value.maximum) { max -= multipleOf || 1; } if (multipleOf) { return Math.floor(random(min, max) / multipleOf) * multipleOf; } if (min > max) { return NaN; } return random({ min: min, max: max, hasPrecision: true }); }; },{"../util/random":16,"./string":8}],7:[function(require,module,exports){ var container = require('../util/container'), random = require('../util/random'), words = require('../util/words'), traverse = require('../util/traverse'), hasProps = require('../util/has-props'); var RandExp = container.get('randexp'), randexp = RandExp.randexp; var ParseError = require('../util/error'); module.exports = function(value, path, resolve) { var props = {}; if (!(value.properties || value.patternProperties || value.additionalProperties)) { if (hasProps(value, 'minProperties', 'maxProperties', 'dependencies', 'required')) { throw new ParseError('missing properties for ' + JSON.stringify(value), path); } return props; } var reqProps = value.required || [], allProps = value.properties ? Object.keys(value.properties) : []; reqProps.forEach(function(key) { if (value.properties && value.properties[key]) { props[key] = value.properties[key]; } }); var optProps = allProps.filter(function(prop) { return reqProps.indexOf(prop) === -1; }); if (value.patternProperties) { optProps = Array.prototype.concat.apply(optProps, Object.keys(value.patternProperties)); } var length = random(value.minProperties, value.maxProperties, 0, optProps.length); random.shuffle(optProps).slice(0, length).forEach(function(key) { if (value.properties && value.properties[key]) { props[key] = value.properties[key]; } else { props[randexp(key)] = value.patternProperties[key]; } }); var current = Object.keys(props).length, sample = typeof value.additionalProperties === 'object' ? value.additionalProperties : {}; if (current < length) { words(length - current).forEach(function(key) { props[key + randexp('[a-f\\d]{4,7}')] = sample; }); } return traverse(props, path.concat(['properties']), resolve); }; },{"../util/container":9,"../util/error":10,"../util/has-props":12,"../util/random":16,"../util/traverse":17,"../util/words":18}],8:[function(require,module,exports){ var container = require('../util/container'); var faker = container.get('faker'), chance = container.get('chance'), RandExp = container.get('randexp'), randexp = RandExp.randexp; var words = require('../util/words'), random = require('../util/random'), formats = require('../util/formats'); var regexps = { email: '[a-zA-Z\\d][a-zA-Z\\d-]{1,13}[a-zA-Z\\d]@{hostname}', hostname: '[a-zA-Z]{1,33}\\.[a-z]{2,4}', ipv6: '[abcdef\\d]{4}(:[abcdef\\d]{4}){7}', uri: '[a-zA-Z][a-zA-Z0-9+-.]*' }; function get(obj, key) { var parts = key.split('.'); while (parts.length) { var prop = parts.shift(); if (!obj[prop]) { break; } obj = obj[prop]; } return obj; } function thunk() { return words().join(' '); } function generate(value) { if (value.use) { var args = [], path = value.key; if (typeof path === 'object') { path = Object.keys(path)[0]; if (Array.isArray(value.key[path])) { args = value.key[path]; } else { args.push(value.key[path]); } } var gen = get(value.gen, path); if (typeof gen !== 'function') { throw new Error('unknown ' + value.use + '-generator for ' + JSON.stringify(value.key)); } return gen.apply(value.gen, args); } switch (value.format) { case 'date-time': return new Date(random(0, 100000000000000)).toISOString(); case 'email': case 'hostname': case 'ipv6': case 'uri': return randexp(regexps[value.format]).replace(/\{(\w+)\}/, function(matches, key) { return randexp(regexps[key]); }); case 'ipv4': return [0, 0, 0, 0].map(function() { return random(0, 255); }).join('.'); case 'regex': // TODO: discuss return '.+?'; default: var callback = formats(value.format); if (typeof callback !== 'function') { throw new Error('unknown generator for ' + JSON.stringify(value.format)); } var generators = { faker: faker, chance: chance, randexp: randexp }; return callback(generators, value); } } module.exports = function(value) { if (value.faker || value.chance) { return generate({ use: value.faker ? 'faker' : 'chance', gen: value.faker ? faker : chance, key: value.faker || value.chance }); } if (value.format) { return generate(value); } if (value.pattern) { return randexp(value.pattern); } var min = Math.max(0, value.minLength || 0), max = random(min, value.maxLength || 140); var sample = thunk(); while (sample.length < min) { sample += thunk(); } if (sample.length > max) { sample = sample.substr(0, max); } return sample; }; },{"../util/container":9,"../util/formats":11,"../util/random":16,"../util/words":18}],9:[function(require,module,exports){ // static requires - handle both initial dependency load (deps will be available // among other modules) as well as they will be included by browserify AST var container = { faker: null, chance: null, // randexp is required for "pattern" values randexp: require('randexp') }; module.exports = { set: function(name, callback) { if (typeof container[name] === 'undefined') { throw new ReferenceError('"' + name + '" dependency is not allowed.'); } container[name] = callback(container[name]); }, get: function(name) { if (typeof container[name] === 'undefined') { throw new ReferenceError('"' + name + '" dependency doesn\'t exist.'); } return container[name]; } }; },{"randexp":146}],10:[function(require,module,exports){ function ParseError(message, path) { this.message = message; this.path = path; this.name = 'ParseError'; } ParseError.prototype = Error.prototype; module.exports = ParseError; },{}],11:[function(require,module,exports){ var registry = {}; module.exports = function(name, callback) { if (callback) { registry[name] = callback; } else if (typeof name === 'object') { for (var method in name) { registry[method] = name[method]; } } else if (name) { return registry[name]; } return registry; }; },{}],12:[function(require,module,exports){ module.exports = function(obj) { return Array.prototype.slice.call(arguments, 1).filter(function(key) { return typeof obj[key] !== 'undefined'; }).length > 0; }; },{}],13:[function(require,module,exports){ var inferredProperties = { array: [ 'additionalItems', 'items', 'maxItems', 'minItems', 'uniqueItems' ], integer: [ 'exclusiveMaximum', 'exclusiveMinimum', 'maximum', 'minimum', 'multipleOf' ], object: [ 'additionalProperties', 'dependencies', 'maxProperties', 'minProperties', 'patternProperties', 'properties', 'required' ], string: [ 'maxLength', 'menlength', 'pattern' ] }; var subschemaProperties = [ 'additionalItems', 'items', 'additionalProperties', 'dependencies', 'patternProperties', 'properties' ]; inferredProperties.number = inferredProperties.integer; function mayHaveType(obj, path, props) { return Object.keys(obj).filter(function(prop) { // Do not attempt to infer properties named as subschema containers. The reason for this is // that any property name within those containers that matches one of the properties used for inferring missing type // values causes the container itself to get processed which leads to invalid output. (Issue 62) if (props.indexOf(prop) > -1 && subschemaProperties.indexOf(path[path.length - 1]) === -1) { return true; } }).length > 0; } module.exports = function(obj, path) { for (var type in inferredProperties) { if (mayHaveType(obj, path, inferredProperties[type])) { return type; } } }; },{}],14:[function(require,module,exports){ var merge; function clone(arr) { var out = []; arr.forEach(function(item, index) { if (typeof item === 'object' && item !== null) { out[index] = Array.isArray(item) ? clone(item) : merge({}, item); } else { out[index] = item; } }); return out; } merge = module.exports = function(a, b) { for (var key in b) { if (typeof b[key] !== 'object' || b[key] === null) { a[key] = b[key]; } else if (Array.isArray(b[key])) { a[key] = (a[key] || []).concat(clone(b[key])); } else if (typeof a[key] !== 'object' || a[key] === null || Array.isArray(a[key])) { a[key] = merge({}, b[key]); } else { a[key] = merge(a[key], b[key]); } } return a; }; },{}],15:[function(require,module,exports){ module.exports = { array: require('../types/array'), boolean: require('../types/boolean'), integer: require('../types/integer'), number: require('../types/number'), null: require('../types/null'), object: require('../types/object'), string: require('../types/string') }; },{"../types/array":2,"../types/boolean":3,"../types/integer":4,"../types/null":5,"../types/number":6,"../types/object":7,"../types/string":8}],16:[function(require,module,exports){ var random = module.exports = function(min, max, defMin, defMax) { var hasPrecision = false; if (typeof min === 'object') { hasPrecision = min.hasPrecision; max = min.max; defMin = min.defMin; defMax = min.defMax; min = min.min; } defMin = typeof defMin === 'undefined' ? random.MIN_NUMBER : defMin; defMax = typeof defMax === 'undefined' ? random.MAX_NUMBER : defMax; min = typeof min === 'undefined' ? defMin : min; max = typeof max === 'undefined' ? defMax : max; if (max < min) { max += min; } var number = Math.random() * (max - min) + min; if (!hasPrecision) { return parseInt(number, 10); } return number; }; random.shuffle = function(obj) { var copy = obj.slice(), length = obj.length; for (; length > 0;) { var key = Math.floor(Math.random() * length), tmp = copy[--length]; copy[length] = copy[key]; copy[key] = tmp; } return copy; }; random.pick = function(obj) { return obj[Math.floor(Math.random() * obj.length)]; }; random.MIN_NUMBER = -100; random.MAX_NUMBER = 100; },{}],17:[function(require,module,exports){ var random = require('./random'); var ParseError = require('./error'); var inferredType = require('./inferred'); var primitives = null; function traverse(obj, path, resolve) { resolve(obj); var copy = {}; if (Array.isArray(obj)) { copy = []; } if (Array.isArray(obj.enum)) { return random.pick(obj.enum); } var type = obj.type; if (Array.isArray(type)) { type = random.pick(type); } else if (typeof type === 'undefined') { // Attempt to infer the type type = inferredType(obj, path) || type; } if (typeof type === 'string') { if (!primitives[type]) { throw new ParseError('unknown primitive ' + JSON.stringify(type), path.concat(['type'])); } try { return primitives[type](obj, path, resolve); } catch (e) { if (typeof e.path === 'undefined') { throw new ParseError(e.message, path); } throw e; } } for (var prop in obj) { if (typeof obj[prop] === 'object' && prop !== 'definitions') { copy[prop] = traverse(obj[prop], path.concat([prop]), resolve); } else { copy[prop] = obj[prop]; } } return copy; } module.exports = function() { primitives = primitives || require('./primitives'); return traverse.apply(null, arguments); }; },{"./error":10,"./inferred":13,"./primitives":15,"./random":16}],18:[function(require,module,exports){ var random = require('./random'); var LIPSUM_WORDS = ('Lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore' + ' et dolore magna aliqua Ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea' + ' commodo consequat Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla' + ' pariatur Excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est' + ' laborum').split(' '); module.exports = function(min, max) { var words = random.shuffle(LIPSUM_WORDS), length = random(min || 1, Math.min(LIPSUM_WORDS.length, max || min || 5)); return words.slice(0, length); }; },{"./random":16}],19:[function(require,module,exports){ /*! * @description Recursive object extending * @author Viacheslav Lotsmanov <lotsmanov89@gmail.com> * @license MIT * * The MIT License (MIT) * * Copyright (c) 2013-2015 Viacheslav Lotsmanov * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ 'use strict'; function isSpecificValue(val) { return ( val instanceof Buffer || val instanceof Date || val instanceof RegExp ) ? true : false; } function cloneSpecificValue(val) { if (val instanceof Buffer) { var x = new Buffer(val.length); val.copy(x); return x; } else if (val instanceof Date) { return new Date(val.getTime()); } else if (val instanceof RegExp) { return new RegExp(val); } else { throw new Error('Unexpected situation'); } } /** * Recursive cloning array. */ function deepCloneArray(arr) { var clone = []; arr.forEach(function (item, index) { if (typeof item === 'object' && item !== null) { if (Array.isArray(item)) { clone[index] = deepCloneArray(item); } else if (isSpecificValue(item)) { clone[index] = cloneSpecificValue(item); } else { clone[index] = deepExtend({}, item); } } else { clone[index] = item; } }); return clone; } /** * Extening object that entered in first argument. * * Returns extended object or false if have no target object or incorrect type. * * If you wish to clone source object (without modify it), just use empty new * object as first argument, like this: * deepExtend({}, yourObj_1, [yourObj_N]); */ var deepExtend = module.exports = function (/*obj_1, [obj_2], [obj_N]*/) { if (arguments.length < 1 || typeof arguments[0] !== 'object') { return false; } if (arguments.length < 2) { return arguments[0]; } var target = arguments[0]; // convert arguments to array and cut off target object var args = Array.prototype.slice.call(arguments, 1); var val, src, clone; args.forEach(function (obj) { // skip argument if it is array or isn't object if (typeof obj !== 'object' || Array.isArray(obj)) { return; } Object.keys(obj).forEach(function (key) { src = target[key]; // source value val = obj[key]; // new value // recursion prevention if (val === target) { return; /** * if new value isn't object then just overwrite by new value * instead of extending. */ } else if (typeof val !== 'object' || val === null) { target[key] = val; return; // just clone arrays (and recursive clone objects inside) } else if (Array.isArray(val)) { target[key] = deepCloneArray(val); return; // custom cloning and overwrite for specific objects } else if (isSpecificValue(val)) { target[key] = cloneSpecificValue(val); return; // overwrite by new value if source isn't object or array } else if (typeof src !== 'object' || src === null || Array.isArray(src)) { target[key] = deepExtend({}, val); return; // source value and new value is objects both, extending... } else { target[key] = deepExtend(src, val); return; } }); }); return target; } },{}],20:[function(require,module,exports){ 'use strict'; var $ = require('./util/uri-helpers'); $.findByRef = require('./util/find-reference'); $.resolveSchema = require('./util/resolve-schema'); $.normalizeSchema = require('./util/normalize-schema'); var instance = module.exports = function() { function $ref(fakeroot, schema, refs, ex) { if (typeof fakeroot === 'object') { ex = refs; refs = schema; schema = fakeroot; fakeroot = undefined; } if (typeof schema !== 'object') { throw new Error('schema must be an object'); } if (typeof refs === 'object' && refs !== null) { var aux = refs; refs = []; for (var k in aux) { aux[k].id = aux[k].id || k; refs.push(aux[k]); } } if (typeof refs !== 'undefined' && !Array.isArray(refs)) { ex = !!refs; refs = []; } function push(ref) { if (typeof ref.id === 'string') { var id = $.resolveURL(fakeroot, ref.id).replace(/\/#?$/, ''); if (id.indexOf('#') > -1) { var parts = id.split('#'); if (parts[1].charAt() === '/') { id = parts[0]; } else { id = parts[1] || parts[0]; } } if (!$ref.refs[id]) { $ref.refs[id] = ref; } } } (refs || []).concat([schema]).forEach(function(ref) { schema = $.normalizeSchema(fakeroot, ref, push); push(schema); }); return $.resolveSchema(schema, $ref.refs, ex); } $ref.refs = {}; $ref.util = $; return $ref; }; instance.util = $; },{"./util/find-reference":22,"./util/normalize-schema":23,"./util/resolve-schema":24,"./util/uri-helpers":25}],21:[function(require,module,exports){ 'use strict'; var clone = module.exports = function(obj, seen) { seen = seen || []; if (seen.indexOf(obj) > -1) { throw new Error('unable dereference circular structures'); } if (!obj || typeof obj !== 'object') { return obj; } seen = seen.concat([obj]); var target = Array.isArray(obj) ? [] : {}; function copy(key, value) { target[key] = clone(value, seen); } if (Array.isArray(target)) { obj.forEach(function(value, key) { copy(key, value); }); } else if (Object.prototype.toString.call(obj) === '[object Object]') { Object.keys(obj).forEach(function(key) { copy(key, obj[key]); }); } return target; }; },{}],22:[function(require,module,exports){ 'use strict'; var $ = require('./uri-helpers'); function get(obj, path) { var hash = path.split('#')[1]; var parts = hash.split('/').slice(1); while (parts.length) { var key = decodeURIComponent(parts.shift()).replace(/~1/g, '/').replace(/~0/g, '~'); if (typeof obj[key] === 'undefined') { throw new Error('JSON pointer not found: ' + path); } obj = obj[key]; } return obj; } var find = module.exports = function(id, refs) { var target = refs[id] || refs[id.split('#')[1]] || refs[$.getDocumentURI(id)]; if (target) { target = id.indexOf('#/') > -1 ? get(target, id) : target; } else { for (var key in refs) { if ($.resolveURL(refs[key].id, id) === refs[key].id) { target = refs[key]; break; } } } if (!target) { throw new Error('Reference not found: ' + id); } while (target.$ref) { target = find(target.$ref, refs); } return target; }; },{"./uri-helpers":25}],23:[function(require,module,exports){ 'use strict'; var $ = require('./uri-helpers'); var cloneObj = require('./clone-obj'); var SCHEMA_URI = [ 'http://json-schema.org/schema#', 'http://json-schema.org/draft-04/schema#' ]; function expand(obj, parent, callback) { if (obj) { var id = typeof obj.id === 'string' ? obj.id : '#'; if (!$.isURL(id)) { id = $.resolveURL(parent === id ? null : parent, id); } if (typeof obj.$ref === 'string' && !$.isURL(obj.$ref)) { obj.$ref = $.resolveURL(id, obj.$ref); } if (typeof obj.id === 'string') { obj.id = parent = id; } } for (var key in obj) { var value = obj[key]; if (typeof value === 'object' && !(key === 'enum' || key === 'required')) { expand(value, parent, callback); } } if (typeof callback === 'function') { callback(obj); } } module.exports = function(fakeroot, schema, push) { if (typeof fakeroot === 'object') { push = schema; schema = fakeroot; fakeroot = null; } var base = fakeroot || '', copy = cloneObj(schema); if (copy.$schema && SCHEMA_URI.indexOf(copy.$schema) === -1) { throw new Error('Unsupported schema version (v4 only)'); } base = $.resolveURL(copy.$schema || SCHEMA_URI[0], base); expand(copy, $.resolveURL(copy.id || '#', base), push); copy.id = copy.id || base; return copy; }; },{"./clone-obj":21,"./uri-helpers":25}],24:[function(require,module,exports){ 'use strict'; var $ = require('./uri-helpers'); var find = require('./find-reference'); var deepExtend = require('deep-extend'); function isKey(prop) { return prop === 'enum' || prop === 'required' || prop === 'definitions'; } function copy(obj, refs, parent, resolve) { var target = Array.isArray(obj) ? [] : {}; if (typeof obj.$ref === 'string') { var base = $.getDocumentURI(obj.$ref); if (parent !== base || (resolve && obj.$ref.indexOf('#/') > -1)) { var fixed = find(obj.$ref, refs); deepExtend(obj, fixed); delete obj.$ref; delete obj.id; } } for (var prop in obj) { if (typeof obj[prop] === 'object' && !isKey(prop)) { target[prop] = copy(obj[prop], refs, parent, resolve); } else { target[prop] = obj[prop]; } } return target; } module.exports = function(obj, refs, resolve) { var fixedId = $.resolveURL(obj.$schema, obj.id), parent = $.getDocumentURI(fixedId); return copy(obj, refs, parent, resolve); }; },{"./find-reference":22,"./uri-helpers":25,"deep-extend":19}],25:[function(require,module,exports){ 'use strict'; // https://gist.github.com/pjt33/efb2f1134bab986113fd function URLUtils(url, baseURL) { // remove leading ./ url = url.replace(/^\.\//, ''); var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(?:\/\/(?:([^:@]*)(?::([^:@]*))?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/); if (!m) { throw new RangeError(); } var href = m[0] || ''; var protocol = m[1] || ''; var username = m[2] || ''; var password = m[3] || ''; var host = m[4] || ''; var hostname = m[5] || ''; var port = m[6] || ''; var pathname = m[7] || ''; var search = m[8] || ''; var hash = m[9] || ''; if (baseURL !== undefined) { var base = new URLUtils(baseURL); var flag = protocol === '' && host === '' && username === ''; if (flag && pathname === '' && search === '') { search = base.search; } if (flag && pathname.charAt(0) !== '/') { pathname = (pathname !== '' ? (base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + pathname) : base.pathname); } // dot segments removal var output = []; pathname.replace(/\/?[^\/]+/g, function(p) { if (p === '/..') { output.pop(); } else { output.push(p); } }); pathname = output.join('') || '/'; if (flag) { port = base.port; hostname = base.hostname; host = base.host; password = base.password; username = base.username; } if (protocol === '') { protocol = base.protocol; } href = protocol + (host !== '' ? '//' : '') + (username !== '' ? username + (password !== '' ? ':' + password : '') + '@' : '') + host + pathname + search + hash; } this.href = href; this.origin = protocol + (host !== '' ? '//' + host : ''); this.protocol = protocol; this.username = username; this.password = password; this.host = host; this.hostname = hostname; this.port = port; this.pathname = pathname; this.search = search; this.hash = hash; } function isURL(path) { if (typeof path === 'string' && /^\w+:\/\//.test(path)) { return true; } } function parseURI(href, base) { return new URLUtils(href, base); } function resolveURL(base, href) { base = base || 'http://json-schema.org/schema#'; href = parseURI(href, base); base = parseURI(base); if (base.hash && !href.hash) { return href.href + base.hash; } return href.href; } function getDocumentURI(uri) { return typeof uri === 'string' && uri.split('#')[0]; } module.exports = { isURL: isURL, parseURI: parseURI, resolveURL: resolveURL, getDocumentURI: getDocumentURI }; },{}],26:[function(require,module,exports){ function Address (faker) { var f = faker.fake, Helpers = faker.helpers; this.zipCode = function(format) { // if zip format is not specified, use the zip format defined for the locale if (typeof format === 'undefined') { var localeFormat = faker.definitions.address.postcode; if (typeof localeFormat === 'string') { format = localeFormat; } else { format = faker.random.arrayElement(localeFormat); } } return Helpers.replaceSymbols(format); } this.city = function (format) { var formats = [ '{{address.cityPrefix}} {{name.firstName}} {{address.citySuffix}}', '{{address.cityPrefix}} {{name.firstName}}', '{{name.firstName}} {{address.citySuffix}}', '{{name.lastName}} {{address.citySuffix}}' ]; if (typeof format !== "number") { format = faker.random.number(formats.length - 1); } return f(formats[format]); } this.cityPrefix = function () { return faker.random.arrayElement(faker.definitions.address.city_prefix); } this.citySuffix = function () { return faker.random.arrayElement(faker.definitions.address.city_suffix); } this.streetName = function () { var result; var suffix = faker.address.streetSuffix(); if (suffix !== "") { suffix = " " + suffix } switch (faker.random.number(1)) { case 0: result = faker.name.lastName() + suffix; break; case 1: result = faker.name.firstName() + suffix; break; } return result; } // // TODO: change all these methods that accept a boolean to instead accept an options hash. // this.streetAddress = function (useFullAddress) { if (useFullAddress === undefined) { useFullAddress = false; } var address = ""; switch (faker.random.number(2)) { case 0: address = Helpers.replaceSymbolWithNumber("#####") + " " + faker.address.streetName(); break; case 1: address = Helpers.replaceSymbolWithNumber("####") + " " + faker.address.streetName(); break; case 2: address = Helpers.replaceSymbolWithNumber("###") + " " + faker.address.streetName(); break; } return useFullAddress ? (address + " " + faker.address.secondaryAddress()) : address; } this.streetSuffix = function () { return faker.random.arrayElement(faker.definitions.address.street_suffix); } this.streetPrefix = function () { return faker.random.arrayElement(faker.definitions.address.street_prefix); } this.secondaryAddress = function () { return Helpers.replaceSymbolWithNumber(faker.random.arrayElement( [ 'Apt. ###', 'Suite ###' ] )); } this.county = function () { return faker.random.arrayElement(faker.definitions.address.county); } this.country = function () { return faker.random.arrayElement(faker.definitions.address.country); } this.countryCode = function () { return faker.random.arrayElement(faker.definitions.address.country_code); } this.state = function (useAbbr) { return faker.random.arrayElement(faker.definitions.address.state); } this.stateAbbr = function () { return faker.random.arrayElement(faker.definitions.address.state_abbr); } this.latitude = function () { return (faker.random.number(180 * 10000) / 10000.0 - 90.0).toFixed(4); } this.longitude = function () { return (faker.random.number(360 * 10000) / 10000.0 - 180.0).toFixed(4); } return this; } module.exports = Address; },{}],27:[function(require,module,exports){ var Commerce = function (faker) { var self = this; self.color = function() { return faker.random.arrayElement(faker.definitions.commerce.color); }; self.department = function(max, fixedAmount) { return faker.random.arrayElement(faker.definitions.commerce.department); /* max = max || 3; var num = Math.floor((Math.random() * max) + 1); if (fixedAmount) { num = max; } var categories = faker.commerce.categories(num); if(num > 1) { return faker.commerce.mergeCategories(categories); } return categories[0]; */ }; self.productName = function() { return faker.commerce.productAdjective() + " " + faker.commerce.productMaterial() + " " + faker.commerce.product(); }; self.price = function(min, max, dec, symbol) { min = min || 0; max = max || 1000; dec = dec || 2; symbol = symbol || ''; if(min < 0 || max < 0) { return symbol + 0.00; } return symbol + (Math.round((Math.random() * (max - min) + min) * Math.pow(10, dec)) / Math.pow(10, dec)).toFixed(dec); }; /* self.categories = function(num) { var categories = []; do { var category = faker.random.arrayElement(faker.definitions.commerce.department); if(categories.indexOf(category) === -1) { categories.push(category); } } while(categories.length < num); return categories; }; */ /* self.mergeCategories = function(categories) { var separator = faker.definitions.separator || " &"; // TODO: find undefined here categories = categories || faker.definitions.commerce.categories; var commaSeparated = categories.slice(0, -1).join(', '); return [commaSeparated, categories[categories.length - 1]].join(separator + " "); }; */ self.productAdjective = function() { return faker.random.arrayElement(faker.definitions.commerce.product_name.adjective); }; self.productMaterial = function() { return faker.random.arrayElement(faker.definitions.commerce.product_name.material); }; self.product = function() { return faker.random.arrayElement(faker.definitions.commerce.product_name.product); } return self; }; module['exports'] = Commerce; },{}],28:[function(require,module,exports){ var Company = function (faker) { var self = this; var f = faker.fake; this.suffixes = function () { // Don't want the source array exposed to modification, so return a copy return faker.definitions.company.suffix.slice(0); } this.companyName = function (format) { var formats = [ '{{name.lastName}} {{company.companySuffix}}', '{{name.lastName}} - {{name.lastName}}', '{{name.lastName}}, {{name.lastName}} and {{name.lastName}}' ]; if (typeof format !== "number") { format = faker.random.number(formats.length - 1); } return f(formats[format]); } this.companySuffix = function () { return faker.random.arrayElement(faker.company.suffixes()); } this.catchPhrase = function () { return f('{{company.catchPhraseAdjective}} {{company.catchPhraseDescriptor}} {{company.catchPhraseNoun}}') } this.bs = function () { return f('{{company.bsAdjective}} {{company.bsBuzz}} {{company.bsNoun}}'); } this.catchPhraseAdjective = function () { return faker.random.arrayElement(faker.definitions.company.adjective); } this.catchPhraseDescriptor = function () { return faker.random.arrayElement(faker.definitions.company.descriptor); } this.catchPhraseNoun = function () { return faker.random.arrayElement(faker.definitions.company.noun); } this.bsAdjective = function () { return faker.random.arrayElement(faker.definitions.company.bs_adjective); } this.bsBuzz = function () { return faker.random.arrayElement(faker.definitions.company.bs_verb); } this.bsNoun = function () { return faker.random.arrayElement(faker.definitions.company.bs_noun); } } module['exports'] = Company; },{}],29:[function(require,module,exports){ var _Date = function (faker) { var self = this; self.past = function (years, refDate) { var date = (refDate) ? new Date(Date.parse(refDate)) : new Date(); var range = { min: 1000, max: (years || 1) * 365 * 24 * 3600 * 1000 }; var past = date.getTime(); past -= faker.random.number(range); // some time from now to N years ago, in milliseconds date.setTime(past); return date; }; self.future = function (years, refDate) { var date = (refDate) ? new Date(Date.parse(refDate)) : new Date(); var range = { min: 1000, max: (years || 1) * 365 * 24 * 3600 * 1000 }; var future = date.getTime(); future += faker.random.number(range); // some time from now to N years later, in milliseconds date.setTime(future); return date; }; self.between = function (from, to) { var fromMilli = Date.parse(from); var dateOffset = faker.random.number(Date.parse(to) - fromMilli); var newDate = new Date(fromMilli + dateOffset); return newDate; }; self.recent = function (days) { var date = new Date(); var range = { min: 1000, max: (days || 1) * 24 * 3600 * 1000 }; var future = date.getTime(); future -= faker.random.number(range); // some time from now to N days ago, in milliseconds date.setTime(future); return date; }; self.month = function (options) { options = options || {}; var type = 'wide'; if (options.abbr) { type = 'abbr'; } if (options.context && typeof faker.definitions.date.month[type + '_context'] !== 'undefined') { type += '_context'; } var source = faker.definitions.date.month[type]; return faker.random.arrayElement(source); }; self.weekday = function (options) { options = options || {}; var type = 'wide'; if (options.abbr) { type = 'abbr'; } if (options.context && typeof faker.definitions.date.weekday[type + '_context'] !== 'undefined') { type += '_context'; } var source = faker.definitions.date.weekday[type]; return faker.random.arrayElement(source); }; return self; }; module['exports'] = _Date; },{}],30:[function(require,module,exports){ /* fake.js - generator method for combining faker methods based on string input */ function Fake (faker) { this.fake = function fake (str) { // setup default response as empty string var res = ''; // if incoming str parameter is not provided, return error message if (typeof str !== 'string' || str.length === 0) { res = 'string parameter is required!'; return res; } // find first matching {{ and }} var start = str.search('{{'); var end = str.search('}}'); // if no {{ and }} is found, we are done if (start === -1 && end === -1) { return str; } // console.log('attempting to parse', str); // extract method name from between the {{ }} that we found // for example: {{name.firstName}} var method = str.substr(start + 2, end - start - 2); method = method.replace('}}', ''); method = method.replace('{{', ''); // console.log('method', method) // split the method into module and function var parts = method.split('.'); if (typeof faker[parts[0]] === "undefined") { throw new Error('Invalid module: ' + parts[0]); } if (typeof faker[parts[0]][parts[1]] === "undefined") { throw new Error('Invalid method: ' + parts[0] + "." + parts[1]); } // assign the function from the module.function namespace var fn = faker[parts[0]][parts[1]]; // replace the found tag with the returned fake value res = str.replace('{{' + method + '}}', fn()); // return the response recursively until we are done finding all tags return fake(res); } return this; } module['exports'] = Fake; },{}],31:[function(require,module,exports){ var Finance = function (faker) { var Helpers = faker.helpers, self = this; self.account = function (length) { length = length || 8; var template = ''; for (var i = 0; i < length; i++) { template = template + '#'; } length = null; return Helpers.replaceSymbolWithNumber(template); } self.accountName = function () { return [Helpers.randomize(faker.definitions.finance.account_type), 'Account'].join(' '); } self.mask = function (length, parens, elipsis) { //set defaults length = (length == 0 || !length || typeof length == 'undefined') ? 4 : length; parens = (parens === null) ? true : parens; elipsis = (elipsis === null) ? true : elipsis; //create a template for length var template = ''; for (var i = 0; i < length; i++) { template = template + '#'; } //prefix with elipsis template = (elipsis) ? ['...', template].join('') : template; template = (parens) ? ['(', template, ')'].join('') : template; //generate random numbers template = Helpers.replaceSymbolWithNumber(template); return template; } //min and max take in minimum and maximum amounts, dec is the decimal place you want rounded to, symbol is $, €, £, etc //NOTE: this returns a string representation of the value, if you want a number use parseFloat and no symbol self.amount = function (min, max, dec, symbol) { min = min || 0; max = max || 1000; dec = dec || 2; symbol = symbol || ''; return symbol + (Math.round((Math.random() * (max - min) + min) * Math.pow(10, dec)) / Math.pow(10, dec)).toFixed(dec); } self.transactionType = function () { return Helpers.randomize(faker.definitions.finance.transaction_type); } self.currencyCode = function () { return faker.random.objectElement(faker.definitions.finance.currency)['code']; } self.currencyName = function () { return faker.random.objectElement(faker.definitions.finance.currency, 'key'); } self.currencySymbol = function () { var symbol; while (!symbol) { symbol = faker.random.objectElement(faker.definitions.finance.currency)['symbol']; } return symbol; } } module['exports'] = Finance; },{}],32:[function(require,module,exports){ var Hacker = function (faker) { var self = this; self.abbreviation = function () { return faker.random.arrayElement(faker.definitions.hacker.abbreviation); }; self.adjective = function () { return faker.random.arrayElement(faker.definitions.hacker.adjective); }; self.noun = function () { return faker.random.arrayElement(faker.definitions.hacker.noun); }; self.verb = function () { return faker.random.arrayElement(faker.definitions.hacker.verb); }; self.ingverb = function () { return faker.random.arrayElement(faker.definitions.hacker.ingverb); }; self.phrase = function () { var data = { abbreviation: self.abbreviation(), adjective: self.adjective(), ingverb: self.ingverb(), noun: self.noun(), verb: self.verb() }; var phrase = faker.random.arrayElement([ "If we {{verb}} the {{noun}}, we can get to the {{abbreviation}} {{noun}} through the {{adjective}} {{abbreviation}} {{noun}}!", "We need to {{verb}} the {{adjective}} {{abbreviation}} {{noun}}!", "Try to {{verb}} the {{abbreviation}} {{noun}}, maybe it will {{verb}} the {{adjective}} {{noun}}!", "You can't {{verb}} the {{noun}} without {{ingverb}} the {{adjective}} {{abbreviation}} {{noun}}!", "Use the {{adjective}} {{abbreviation}} {{noun}}, then you can {{verb}} the {{adjective}} {{noun}}!", "The {{abbreviation}} {{noun}} is down, {{verb}} the {{adjective}} {{noun}} so we can {{verb}} the {{abbreviation}} {{noun}}!", "{{ingverb}} the {{noun}} won't do anything, we need to {{verb}} the {{adjective}} {{abbreviation}} {{noun}}!", "I'll {{verb}} the {{adjective}} {{abbreviation}} {{noun}}, that should {{noun}} the {{abbreviation}} {{noun}}!" ]); return faker.helpers.mustache(phrase, data); }; return self; }; module['exports'] = Hacker; },{}],33:[function(require,module,exports){ var Helpers = function (faker) { var self = this; // backword-compatibility self.randomize = function (array) { array = array || ["a", "b", "c"]; return faker.random.arrayElement(array); }; // slugifies string self.slugify = function (string) { string = string || ""; return string.replace(/ /g, '-').replace(/[^\w\.\-]+/g, ''); }; // parses string for a symbol and replace it with a random number from 1-10 self.replaceSymbolWithNumber = function (string, symbol) { string = string || ""; // default symbol is '#' if (symbol === undefined) { symbol = '#'; } var str = ''; for (var i = 0; i < string.length; i++) { if (string.charAt(i) == symbol) { str += faker.random.number(9); } else { str += string.charAt(i); } } return str; }; // parses string for symbols (numbers or letters) and replaces them appropriately self.replaceSymbols = function (string) { string = string || ""; var alpha = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] var str = ''; for (var i = 0; i < string.length; i++) { if (string.charAt(i) == "#") { str += faker.random.number(9); } else if (string.charAt(i) == "?") { str += alpha[Math.floor(Math.random() * alpha.length)]; } else { str += string.charAt(i); } } return str; }; // takes an array and returns it randomized self.shuffle = function (o) { o = o || ["a", "b", "c"]; for (var j, x, i = o.length-1; i; j = faker.random.number(i), x = o[--i], o[i] = o[j], o[j] = x); return o; }; self.mustache = function (str, data) { if (typeof str === 'undefined') { return ''; } for(var p in data) { var re = new RegExp('{{' + p + '}}', 'g') str = str.replace(re, data[p]); } return str; }; self.createCard = function () { return { "name": faker.name.findName(), "username": faker.internet.userName(), "email": faker.internet.email(), "address": { "streetA": faker.address.streetName(), "streetB": faker.address.streetAddress(), "streetC": faker.address.streetAddress(true), "streetD": faker.address.secondaryAddress(), "city": faker.address.city(), "state": faker.address.state(), "country": faker.address.country(), "zipcode": faker.address.zipCode(), "geo": { "lat": faker.address.latitude(), "lng": faker.address.longitude() } }, "phone": faker.phone.phoneNumber(), "website": faker.internet.domainName(), "company": { "name": faker.company.companyName(), "catchPhrase": faker.company.catchPhrase(), "bs": faker.company.bs() }, "posts": [ { "words": faker.lorem.words(), "sentence": faker.lorem.sentence(), "sentences": faker.lorem.sentences(), "paragraph": faker.lorem.paragraph() }, { "words": faker.lorem.words(), "sentence": faker.lorem.sentence(), "sentences": faker.lorem.sentences(), "paragraph": faker.lorem.paragraph() }, { "words": faker.lorem.words(), "sentence": faker.lorem.sentence(), "sentences": faker.lorem.sentences(), "paragraph": faker.lorem.paragraph() } ], "accountHistory": [faker.helpers.createTransaction(), faker.helpers.createTransaction(), faker.helpers.createTransaction()] }; }; self.contextualCard = function () { var name = faker.name.firstName(), userName = faker.internet.userName(name); return { "name": name, "username": userName, "avatar": faker.internet.avatar(), "email": faker.internet.email(userName), "dob": faker.date.past(50, new Date("Sat Sep 20 1992 21:35:02 GMT+0200 (CEST)")), "phone": faker.phone.phoneNumber(), "address": { "street": faker.address.streetName(true), "suite": faker.address.secondaryAddress(), "city": faker.address.city(), "zipcode": faker.address.zipCode(), "geo": { "lat": faker.address.latitude(), "lng": faker.address.longitude() } }, "website": faker.internet.domainName(), "company": { "name": faker.company.companyName(), "catchPhrase": faker.company.catchPhrase(), "bs": faker.company.bs() } }; }; self.userCard = function () { return { "name": faker.name.findName(), "username": faker.internet.userName(), "email": faker.internet.email(), "address": { "street": faker.address.streetName(true), "suite": faker.address.secondaryAddress(), "city": faker.address.city(), "zipcode": faker.address.zipCode(), "geo": { "lat": faker.address.latitude(), "lng": faker.address.longitude() } }, "phone": faker.phone.phoneNumber(), "website": faker.internet.domainName(), "company": { "name": faker.company.companyName(), "catchPhrase": faker.company.catchPhrase(), "bs": faker.company.bs() } }; }; self.createTransaction = function(){ return { "amount" : faker.finance.amount(), "date" : new Date(2012, 1, 2), //TODO: add a ranged date method "business": faker.company.companyName(), "name": [faker.finance.accountName(), faker.finance.mask()].join(' '), "type" : self.randomize(faker.definitions.finance.transaction_type), "account" : faker.finance.account() }; }; return self; }; /* String.prototype.capitalize = function () { //v1.0 return this.replace(/\w+/g, function (a) { return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase(); }); }; */ module['exports'] = Helpers; },{}],34:[function(require,module,exports){ var Image = function (faker) { var self = this; self.image = function () { var categories = ["abstract", "animals", "business", "cats", "city", "food", "nightlife", "fashion", "people", "nature", "sports", "technics", "transport"]; return self[faker.random.arrayElement(categories)](); }; self.avatar = function () { return faker.internet.avatar(); }; self.imageUrl = function (width, height, category) { var width = width || 640; var height = height || 480; var url ='http://lorempixel.com/' + width + '/' + height; if (typeof category !== 'undefined') { url += '/' + category; } return url; }; self.abstract = function (width, height) { return faker.image.imageUrl(width, height, 'abstract'); }; self.animals = function (width, height) { return faker.image.imageUrl(width, height, 'animals'); }; self.business = function (width, height) { return faker.image.imageUrl(width, height, 'business'); }; self.cats = function (width, height) { return faker.image.imageUrl(width, height, 'cats'); }; self.city = function (width, height) { return faker.image.imageUrl(width, height, 'city'); }; self.food = function (width, height) { return faker.image.imageUrl(width, height, 'food'); }; self.nightlife = function (width, height) { return faker.image.imageUrl(width, height, 'nightlife'); }; self.fashion = function (width, height) { return faker.image.imageUrl(width, height, 'fashion'); }; self.people = function (width, height) { return faker.image.imageUrl(width, height, 'people'); }; self.nature = function (width, height) { return faker.image.imageUrl(width, height, 'nature'); }; self.sports = function (width, height) { return faker.image.imageUrl(width, height, 'sports'); }; self.technics = function (width, height) { return faker.image.imageUrl(width, height, 'technics'); }; self.transport = function (width, height) { return faker.image.imageUrl(width, height, 'transport'); } } module["exports"] = Image; },{}],35:[function(require,module,exports){ /* this index.js file is used for including the faker library as a CommonJS module, instead of a bundle you can include the faker library into your existing node.js application by requiring the entire /faker directory var faker = require(./faker); var randomName = faker.name.findName(); you can also simply include the "faker.js" file which is the auto-generated bundled version of the faker library var faker = require(./customAppPath/faker); var randomName = faker.name.findName(); if you plan on modifying the faker library you should be performing your changes in the /lib/ directory */ function Faker (opts) { var self = this; opts = opts || {}; // assign options var locales = self.locales || opts.locales || {}; var locale = self.locale || opts.locale || "en"; var localeFallback = self.localeFallback || opts.localeFallback || "en"; self.locales = locales; self.locale = locale; self.localeFallback = localeFallback; self.definitions = {}; var Fake = require('./fake'); self.fake = new Fake(self).fake; var Random = require('./random'); self.random = new Random(self); // self.random = require('./random'); var Helpers = require('./helpers'); self.helpers = new Helpers(self); var Name = require('./name'); self.name = new Name(self); // self.name = require('./name'); var Address = require('./address'); self.address = new Address(self); var Company = require('./company'); self.company = new Company(self); var Finance = require('./finance'); self.finance = new Finance(self); var Image = require('./image'); self.image = new Image(self); var Lorem = require('./lorem'); self.lorem = new Lorem(self); var Hacker = require('./hacker'); self.hacker = new Hacker(self); var Internet = require('./internet'); self.internet = new Internet(self); var Phone = require('./phone_number'); self.phone = new Phone(self); var _Date = require('./date'); self.date = new _Date(self); var Commerce = require('./commerce'); self.commerce = new Commerce(self); // TODO: fix self.commerce = require('./commerce'); var _definitions = { "name": ["first_name", "last_name", "prefix", "suffix", "title", "male_first_name", "female_first_name", "male_middle_name", "female_middle_name", "male_last_name", "female_last_name"], "address": ["city_prefix", "city_suffix", "street_suffix", "county", "country", "country_code", "state", "state_abbr", "street_prefix", "postcode"], "company": ["adjective", "noun", "descriptor", "bs_adjective", "bs_noun", "bs_verb", "suffix"], "lorem": ["words"], "hacker": ["abbreviation", "adjective", "noun", "verb", "ingverb"], "phone_number": ["formats"], "finance": ["account_type", "transaction_type", "currency"], "internet": ["avatar_uri", "domain_suffix", "free_email", "password"], "commerce": ["color", "department", "product_name", "price", "categories"], "date": ["month", "weekday"], "title": "", "separator": "" }; // Create a Getter for all definitions.foo.bar propetries Object.keys(_definitions).forEach(function(d){ if (typeof self.definitions[d] === "undefined") { self.definitions[d] = {}; } if (typeof _definitions[d] === "string") { self.definitions[d] = _definitions[d]; return; } _definitions[d].forEach(function(p){ Object.defineProperty(self.definitions[d], p, { get: function () { if (typeof self.locales[self.locale][d] === "undefined" || typeof self.locales[self.locale][d][p] === "undefined") { // certain localization sets contain less data then others. // in the case of a missing defintion, use the default localeFallback to substitute the missing set data // throw new Error('unknown property ' + d + p) return self.locales[localeFallback][d][p]; } else { // return localized data return self.locales[self.locale][d][p]; } } }); }); }); }; Faker.prototype.seed = function(value) { var Random = require('./random'); this.seedValue = value; this.random = new Random(this, this.seedValue); } module['exports'] = Faker; },{"./address":26,"./commerce":27,"./company":28,"./date":29,"./fake":30,"./finance":31,"./hacker":32,"./helpers":33,"./image":34,"./internet":36,"./lorem":138,"./name":139,"./phone_number":140,"./random":141}],36:[function(require,module,exports){ var password_generator = require('../vendor/password-generator.js'), random_ua = require('../vendor/user-agent'); var Internet = function (faker) { var self = this; self.avatar = function () { return faker.random.arrayElement(faker.definitions.internet.avatar_uri); }; self.email = function (firstName, lastName, provider) { provider = provider || faker.random.arrayElement(faker.definitions.internet.free_email); return faker.helpers.slugify(faker.internet.userName(firstName, lastName)) + "@" + provider; }; self.userName = function (firstName, lastName) { var result; firstName = firstName || faker.name.firstName(); lastName = lastName || faker.name.lastName(); switch (faker.random.number(2)) { case 0: result = firstName + faker.random.number(99); break; case 1: result = firstName + faker.random.arrayElement([".", "_"]) + lastName; break; case 2: result = firstName + faker.random.arrayElement([".", "_"]) + lastName + faker.random.number(99); break; } result = result.toString().replace(/'/g, ""); result = result.replace(/ /g, ""); return result; }; self.protocol = function () { var protocols = ['http','https']; return faker.random.arrayElement(protocols); }; self.url = function () { return faker.internet.protocol() + '://' + faker.internet.domainName(); }; self.domainName = function () { return faker.internet.domainWord() + "." + faker.internet.domainSuffix(); }; self.domainSuffix = function () { return faker.random.arrayElement(faker.definitions.internet.domain_suffix); }; self.domainWord = function () { return faker.name.firstName().replace(/([\\~#&*{}/:<>?|\"])/ig, '').toLowerCase(); }; self.ip = function () { var randNum = function () { return (faker.random.number(255)).toFixed(0); }; var result = []; for (var i = 0; i < 4; i++) { result[i] = randNum(); } return result.join("."); }; self.userAgent = function () { return random_ua.generate(); }; self.color = function (baseRed255, baseGreen255, baseBlue255) { baseRed255 = baseRed255 || 0; baseGreen255 = baseGreen255 || 0; baseBlue255 = baseBlue255 || 0; // based on awesome response : http://stackoverflow.com/questions/43044/algorithm-to-randomly-generate-an-aesthetically-pleasing-color-palette var red = Math.floor((faker.random.number(256) + baseRed255) / 2); var green = Math.floor((faker.random.number(256) + baseGreen255) / 2); var blue = Math.floor((faker.random.number(256) + baseBlue255) / 2); var redStr = red.toString(16); var greenStr = green.toString(16); var blueStr = blue.toString(16); return '#' + (redStr.length === 1 ? '0' : '') + redStr + (greenStr.length === 1 ? '0' : '') + greenStr + (blueStr.length === 1 ? '0': '') + blueStr; }; self.mac = function(){ var i, mac = ""; for (i=0; i < 12; i++) { mac+= parseInt(Math.random()*16).toString(16); if (i%2==1 && i != 11) { mac+=":"; } } return mac; }; self.password = function (len, memorable, pattern, prefix) { len = len || 15; if (typeof memorable === "undefined") { memorable = false; } return password_generator(len, memorable, pattern, prefix); } }; module["exports"] = Internet; },{"../vendor/password-generator.js":144,"../vendor/user-agent":145}],37:[function(require,module,exports){ module["exports"] = [ "#####", "####", "###" ]; },{}],38:[function(require,module,exports){ module["exports"] = [ "#{city_prefix} #{Name.first_name}#{city_suffix}", "#{city_prefix} #{Name.first_name}", "#{Name.first_name}#{city_suffix}", "#{Name.last_name}#{city_suffix}" ]; },{}],39:[function(require,module,exports){ module["exports"] = [ "North", "East", "West", "South", "New", "Lake", "Port" ]; },{}],40:[function(require,module,exports){ module["exports"] = [ "town", "ton", "land", "ville", "berg", "burgh", "borough", "bury", "view", "port", "mouth", "stad", "furt", "chester", "mouth", "fort", "haven", "side", "shire" ]; },{}],41:[function(require,module,exports){ module["exports"] = [ "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica (the territory South of 60 deg S)", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Bouvet Island (Bouvetoya)", "Brazil", "British Indian Ocean Territory (Chagos Archipelago)", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Congo", "Cook Islands", "Costa Rica", "Cote d'Ivoire", "Croatia", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Faroe Islands", "Falkland Islands (Malvinas)", "Fiji", "Finland", "France", "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guernsey", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard Island and McDonald Islands", "Holy See (Vatican City State)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Isle of Man", "Israel", "Italy", "Jamaica", "Japan", "Jersey", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Democratic People's Republic of Korea", "Republic of Korea", "Kuwait", "Kyrgyz Republic", "Lao People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania", "Luxembourg", "Macao", "Macedonia", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia", "Montenegro", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands Antilles", "Netherlands", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Palestinian Territory", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saint Barthelemy", "Saint Helena", "Saint Kitts and Nevis", "Saint Lucia", "Saint Martin", "Saint Pierre and Miquelon", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Serbia", "Seychelles", "Sierra Leone", "Singapore", "Slovakia (Slovak Republic)", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard & Jan Mayen Islands", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "Timor-Leste", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States of America", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Virgin Islands, British", "Virgin Islands, U.S.", "Wallis and Futuna", "Western Sahara", "Yemen", "Zambia", "Zimbabwe" ]; },{}],42:[function(require,module,exports){ module["exports"] = [ "AD", "AE", "AF", "AG", "AI", "AL", "AM", "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AX", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BL", "BM", "BN", "BO", "BQ", "BQ", "BR", "BS", "BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CU", "CV", "CW", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "GA", "GB", "GD", "GE", "GF", "GG", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IM", "IN", "IO", "IQ", "IR", "IS", "IT", "JE", "JM", "JO", "JP", "KE", "KG", "KH", "KI", "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "ME", "MF", "MG", "MH", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", "QA", "RE", "RO", "RS", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "SS", "ST", "SV", "SX", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ", "TK", "TL", "TM", "TN", "TO", "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF", "WS", "YE", "YT", "ZA", "ZM", "ZW" ]; },{}],43:[function(require,module,exports){ module["exports"] = [ "Avon", "Bedfordshire", "Berkshire", "Borders", "Buckinghamshire", "Cambridgeshire" ]; },{}],44:[function(require,module,exports){ module["exports"] = [ "United States of America" ]; },{}],45:[function(require,module,exports){ var address = {}; module['exports'] = address; address.city_prefix = require("./city_prefix"); address.city_suffix = require("./city_suffix"); address.county = require("./county"); address.country = require("./country"); address.country_code = require("./country_code"); address.building_number = require("./building_number"); address.street_suffix = require("./street_suffix"); address.secondary_address = require("./secondary_address"); address.postcode = require("./postcode"); address.postcode_by_state = require("./postcode_by_state"); address.state = require("./state"); address.state_abbr = require("./state_abbr"); address.time_zone = require("./time_zone"); address.city = require("./city"); address.street_name = require("./street_name"); address.street_address = require("./street_address"); address.default_country = require("./default_country"); },{"./building_number":37,"./city":38,"./city_prefix":39,"./city_suffix":40,"./country":41,"./country_code":42,"./county":43,"./default_country":44,"./postcode":46,"./postcode_by_state":47,"./secondary_address":48,"./state":49,"./state_abbr":50,"./street_address":51,"./street_name":52,"./street_suffix":53,"./time_zone":54}],46:[function(require,module,exports){ module["exports"] = [ "#####", "#####-####" ]; },{}],47:[function(require,module,exports){ arguments[4][46][0].apply(exports,arguments) },{"dup":46}],48:[function(require,module,exports){ module["exports"] = [ "Apt. ###", "Suite ###" ]; },{}],49:[function(require,module,exports){ module["exports"] = [ "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming" ]; },{}],50:[function(require,module,exports){ module["exports"] = [ "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY" ]; },{}],51:[function(require,module,exports){ module["exports"] = [ "#{building_number} #{street_name}" ]; },{}],52:[function(require,module,exports){ module["exports"] = [ "#{Name.first_name} #{street_suffix}", "#{Name.last_name} #{street_suffix}" ]; },{}],53:[function(require,module,exports){ module["exports"] = [ "Alley", "Avenue", "Branch", "Bridge", "Brook", "Brooks", "Burg", "Burgs", "Bypass", "Camp", "Canyon", "Cape", "Causeway", "Center", "Centers", "Circle", "Circles", "Cliff", "Cliffs", "Club", "Common", "Corner", "Corners", "Course", "Court", "Courts", "Cove", "Coves", "Creek", "Crescent", "Crest", "Crossing", "Crossroad", "Curve", "Dale", "Dam", "Divide", "Drive", "Drive", "Drives", "Estate", "Estates", "Expressway", "Extension", "Extensions", "Fall", "Falls", "Ferry", "Field", "Fields", "Flat", "Flats", "Ford", "Fords", "Forest", "Forge", "Forges", "Fork", "Forks", "Fort", "Freeway", "Garden", "Gardens", "Gateway", "Glen", "Glens", "Green", "Greens", "Grove", "Groves", "Harbor", "Harbors", "Haven", "Heights", "Highway", "Hill", "Hills", "Hollow", "Inlet", "Inlet", "Island", "Island", "Islands", "Islands", "Isle", "Isle", "Junction", "Junctions", "Key", "Keys", "Knoll", "Knolls", "Lake", "Lakes", "Land", "Landing", "Lane", "Light", "Lights", "Loaf", "Lock", "Locks", "Locks", "Lodge", "Lodge", "Loop", "Mall", "Manor", "Manors", "Meadow", "Meadows", "Mews", "Mill", "Mills", "Mission", "Mission", "Motorway", "Mount", "Mountain", "Mountain", "Mountains", "Mountains", "Neck", "Orchard", "Oval", "Overpass", "Park", "Parks", "Parkway", "Parkways", "Pass", "Passage", "Path", "Pike", "Pine", "Pines", "Place", "Plain", "Plains", "Plains", "Plaza", "Plaza", "Point", "Points", "Port", "Port", "Ports", "Ports", "Prairie", "Prairie", "Radial", "Ramp", "Ranch", "Rapid", "Rapids", "Rest", "Ridge", "Ridges", "River", "Road", "Road", "Roads", "Roads", "Route", "Row", "Rue", "Run", "Shoal", "Shoals", "Shore", "Shores", "Skyway", "Spring", "Springs", "Springs", "Spur", "Spurs", "Square", "Square", "Squares", "Squares", "Station", "Station", "Stravenue", "Stravenue", "Stream", "Stream", "Street", "Street", "Streets", "Summit", "Summit", "Terrace", "Throughway", "Trace", "Track", "Trafficway", "Trail", "Trail", "Tunnel", "Tunnel", "Turnpike", "Turnpike", "Underpass", "Union", "Unions", "Valley", "Valleys", "Via", "Viaduct", "View", "Views", "Village", "Village", "Villages", "Ville", "Vista", "Vista", "Walk", "Walks", "Wall", "Way", "Ways", "Well", "Wells" ]; },{}],54:[function(require,module,exports){ module["exports"] = [ "Pacific/Midway", "Pacific/Pago_Pago", "Pacific/Honolulu", "America/Juneau", "America/Los_Angeles", "America/Tijuana", "America/Denver", "America/Phoenix", "America/Chihuahua", "America/Mazatlan", "America/Chicago", "America/Regina", "America/Mexico_City", "America/Mexico_City", "America/Monterrey", "America/Guatemala", "America/New_York", "America/Indiana/Indianapolis", "America/Bogota", "America/Lima", "America/Lima", "America/Halifax", "America/Caracas", "America/La_Paz", "America/Santiago", "America/St_Johns", "America/Sao_Paulo", "America/Argentina/Buenos_Aires", "America/Guyana", "America/Godthab", "Atlantic/South_Georgia", "Atlantic/Azores", "Atlantic/Cape_Verde", "Europe/Dublin", "Europe/London", "Europe/Lisbon", "Europe/London", "Africa/Casablanca", "Africa/Monrovia", "Etc/UTC", "Europe/Belgrade", "Europe/Bratislava", "Europe/Budapest", "Europe/Ljubljana", "Europe/Prague", "Europe/Sarajevo", "Europe/Skopje", "Europe/Warsaw", "Europe/Zagreb", "Europe/Brussels", "Europe/Copenhagen", "Europe/Madrid", "Europe/Paris", "Europe/Amsterdam", "Europe/Berlin", "Europe/Berlin", "Europe/Rome", "Europe/Stockholm", "Europe/Vienna", "Africa/Algiers", "Europe/Bucharest", "Africa/Cairo", "Europe/Helsinki", "Europe/Kiev", "Europe/Riga", "Europe/Sofia", "Europe/Tallinn", "Europe/Vilnius", "Europe/Athens", "Europe/Istanbul", "Europe/Minsk", "Asia/Jerusalem", "Africa/Harare", "Africa/Johannesburg", "Europe/Moscow", "Europe/Moscow", "Europe/Moscow", "Asia/Kuwait", "Asia/Riyadh", "Africa/Nairobi", "Asia/Baghdad", "Asia/Tehran", "Asia/Muscat", "Asia/Muscat", "Asia/Baku", "Asia/Tbilisi", "Asia/Yerevan", "Asia/Kabul", "Asia/Yekaterinburg", "Asia/Karachi", "Asia/Karachi", "Asia/Tashkent", "Asia/Kolkata", "Asia/Kolkata", "Asia/Kolkata", "Asia/Kolkata", "Asia/Kathmandu", "Asia/Dhaka", "Asia/Dhaka", "Asia/Colombo", "Asia/Almaty", "Asia/Novosibirsk", "Asia/Rangoon", "Asia/Bangkok", "Asia/Bangkok", "Asia/Jakarta", "Asia/Krasnoyarsk", "Asia/Shanghai", "Asia/Chongqing", "Asia/Hong_Kong", "Asia/Urumqi", "Asia/Kuala_Lumpur", "Asia/Singapore", "Asia/Taipei", "Australia/Perth", "Asia/Irkutsk", "Asia/Ulaanbaatar", "Asia/Seoul", "Asia/Tokyo", "Asia/Tokyo", "Asia/Tokyo", "Asia/Yakutsk", "Australia/Darwin", "Australia/Adelaide", "Australia/Melbourne", "Australia/Melbourne", "Australia/Sydney", "Australia/Brisbane", "Australia/Hobart", "Asia/Vladivostok", "Pacific/Guam", "Pacific/Port_Moresby", "Asia/Magadan", "Asia/Magadan", "Pacific/Noumea", "Pacific/Fiji", "Asia/Kamchatka", "Pacific/Majuro", "Pacific/Auckland", "Pacific/Auckland", "Pacific/Tongatapu", "Pacific/Fakaofo", "Pacific/Apia" ]; },{}],55:[function(require,module,exports){ module["exports"] = [ "#{Name.name}", "#{Company.name}" ]; },{}],56:[function(require,module,exports){ var app = {}; module['exports'] = app; app.name = require("./name"); app.version = require("./version"); app.author = require("./author"); },{"./author":55,"./name":57,"./version":58}],57:[function(require,module,exports){ module["exports"] = [ "Redhold", "Treeflex", "Trippledex", "Kanlam", "Bigtax", "Daltfresh", "Toughjoyfax", "Mat Lam Tam", "Otcom", "Tres-Zap", "Y-Solowarm", "Tresom", "Voltsillam", "Biodex", "Greenlam", "Viva", "Matsoft", "Temp", "Zoolab", "Subin", "Rank", "Job", "Stringtough", "Tin", "It", "Home Ing", "Zamit", "Sonsing", "Konklab", "Alpha", "Latlux", "Voyatouch", "Alphazap", "Holdlamis", "Zaam-Dox", "Sub-Ex", "Quo Lux", "Bamity", "Ventosanzap", "Lotstring", "Hatity", "Tempsoft", "Overhold", "Fixflex", "Konklux", "Zontrax", "Tampflex", "Span", "Namfix", "Transcof", "Stim", "Fix San", "Sonair", "Stronghold", "Fintone", "Y-find", "Opela", "Lotlux", "Ronstring", "Zathin", "Duobam", "Keylex" ]; },{}],58:[function(require,module,exports){ module["exports"] = [ "0.#.#", "0.##", "#.##", "#.#", "#.#.#" ]; },{}],59:[function(require,module,exports){ module["exports"] = [ "2011-10-12", "2012-11-12", "2015-11-11", "2013-9-12" ]; },{}],60:[function(require,module,exports){ module["exports"] = [ "1234-2121-1221-1211", "1212-1221-1121-1234", "1211-1221-1234-2201", "1228-1221-1221-1431" ]; },{}],61:[function(require,module,exports){ module["exports"] = [ "visa", "mastercard", "americanexpress", "discover" ]; },{}],62:[function(require,module,exports){ var business = {}; module['exports'] = business; business.credit_card_numbers = require("./credit_card_numbers"); business.credit_card_expiry_dates = require("./credit_card_expiry_dates"); business.credit_card_types = require("./credit_card_types"); },{"./credit_card_expiry_dates":59,"./credit_card_numbers":60,"./credit_card_types":61}],63:[function(require,module,exports){ module["exports"] = [ "###-###-####", "(###) ###-####", "1-###-###-####", "###.###.####" ]; },{}],64:[function(require,module,exports){ var cell_phone = {}; module['exports'] = cell_phone; cell_phone.formats = require("./formats"); },{"./formats":63}],65:[function(require,module,exports){ module["exports"] = [ "red", "green", "blue", "yellow", "purple", "mint green", "teal", "white", "black", "orange", "pink", "grey", "maroon", "violet", "turquoise", "tan", "sky blue", "salmon", "plum", "orchid", "olive", "magenta", "lime", "ivory", "indigo", "gold", "fuchsia", "cyan", "azure", "lavender", "silver" ]; },{}],66:[function(require,module,exports){ module["exports"] = [ "Books", "Movies", "Music", "Games", "Electronics", "Computers", "Home", "Garden", "Tools", "Grocery", "Health", "Beauty", "Toys", "Kids", "Baby", "Clothing", "Shoes", "Jewelery", "Sports", "Outdoors", "Automotive", "Industrial" ]; },{}],67:[function(require,module,exports){ var commerce = {}; module['exports'] = commerce; commerce.color = require("./color"); commerce.department = require("./department"); commerce.product_name = require("./product_name"); },{"./color":65,"./department":66,"./product_name":68}],68:[function(require,module,exports){ module["exports"] = { "adjective": [ "Small", "Ergonomic", "Rustic", "Intelligent", "Gorgeous", "Incredible", "Fantastic", "Practical", "Sleek", "Awesome", "Generic", "Handcrafted", "Handmade", "Licensed", "Refined", "Unbranded", "Tasty" ], "material": [ "Steel", "Wooden", "Concrete", "Plastic", "Cotton", "Granite", "Rubber", "Metal", "Soft", "Fresh", "Frozen" ], "product": [ "Chair", "Car", "Computer", "Keyboard", "Mouse", "Bike", "Ball", "Gloves", "Pants", "Shirt", "Table", "Shoes", "Hat", "Towels", "Soap", "Tuna", "Chicken", "Fish", "Cheese", "Bacon", "Pizza", "Salad", "Sausages", "Chips" ] }; },{}],69:[function(require,module,exports){ module["exports"] = [ "Adaptive", "Advanced", "Ameliorated", "Assimilated", "Automated", "Balanced", "Business-focused", "Centralized", "Cloned", "Compatible", "Configurable", "Cross-group", "Cross-platform", "Customer-focused", "Customizable", "Decentralized", "De-engineered", "Devolved", "Digitized", "Distributed", "Diverse", "Down-sized", "Enhanced", "Enterprise-wide", "Ergonomic", "Exclusive", "Expanded", "Extended", "Face to face", "Focused", "Front-line", "Fully-configurable", "Function-based", "Fundamental", "Future-proofed", "Grass-roots", "Horizontal", "Implemented", "Innovative", "Integrated", "Intuitive", "Inverse", "Managed", "Mandatory", "Monitored", "Multi-channelled", "Multi-lateral", "Multi-layered", "Multi-tiered", "Networked", "Object-based", "Open-architected", "Open-source", "Operative", "Optimized", "Optional", "Organic", "Organized", "Persevering", "Persistent", "Phased", "Polarised", "Pre-emptive", "Proactive", "Profit-focused", "Profound", "Programmable", "Progressive", "Public-key", "Quality-focused", "Reactive", "Realigned", "Re-contextualized", "Re-engineered", "Reduced", "Reverse-engineered", "Right-sized", "Robust", "Seamless", "Secured", "Self-enabling", "Sharable", "Stand-alone", "Streamlined", "Switchable", "Synchronised", "Synergistic", "Synergized", "Team-oriented", "Total", "Triple-buffered", "Universal", "Up-sized", "Upgradable", "User-centric", "User-friendly", "Versatile", "Virtual", "Visionary", "Vision-oriented" ]; },{}],70:[function(require,module,exports){ module["exports"] = [ "clicks-and-mortar", "value-added", "vertical", "proactive", "robust", "revolutionary", "scalable", "leading-edge", "innovative", "intuitive", "strategic", "e-business", "mission-critical", "sticky", "one-to-one", "24/7", "end-to-end", "global", "B2B", "B2C", "granular", "frictionless", "virtual", "viral", "dynamic", "24/365", "best-of-breed", "killer", "magnetic", "bleeding-edge", "web-enabled", "interactive", "dot-com", "sexy", "back-end", "real-time", "efficient", "front-end", "distributed", "seamless", "extensible", "turn-key", "world-class", "open-source", "cross-platform", "cross-media", "synergistic", "bricks-and-clicks", "out-of-the-box", "enterprise", "integrated", "impactful", "wireless", "transparent", "next-generation", "cutting-edge", "user-centric", "visionary", "customized", "ubiquitous", "plug-and-play", "collaborative", "compelling", "holistic", "rich" ]; },{}],71:[function(require,module,exports){ module["exports"] = [ "synergies", "web-readiness", "paradigms", "markets", "partnerships", "infrastructures", "platforms", "initiatives", "channels", "eyeballs", "communities", "ROI", "solutions", "e-tailers", "e-services", "action-items", "portals", "niches", "technologies", "content", "vortals", "supply-chains", "convergence", "relationships", "architectures", "interfaces", "e-markets", "e-commerce", "systems", "bandwidth", "infomediaries", "models", "mindshare", "deliverables", "users", "schemas", "networks", "applications", "metrics", "e-business", "functionalities", "experiences", "web services", "methodologies" ]; },{}],72:[function(require,module,exports){ module["exports"] = [ "implement", "utilize", "integrate", "streamline", "optimize", "evolve", "transform", "embrace", "enable", "orchestrate", "leverage", "reinvent", "aggregate", "architect", "enhance", "incentivize", "morph", "empower", "envisioneer", "monetize", "harness", "facilitate", "seize", "disintermediate", "synergize", "strategize", "deploy", "brand", "grow", "target", "syndicate", "synthesize", "deliver", "mesh", "incubate", "engage", "maximize", "benchmark", "expedite", "reintermediate", "whiteboard", "visualize", "repurpose", "innovate", "scale", "unleash", "drive", "extend", "engineer", "revolutionize", "generate", "exploit", "transition", "e-enable", "iterate", "cultivate", "matrix", "productize", "redefine", "recontextualize" ]; },{}],73:[function(require,module,exports){ module["exports"] = [ "24 hour", "24/7", "3rd generation", "4th generation", "5th generation", "6th generation", "actuating", "analyzing", "asymmetric", "asynchronous", "attitude-oriented", "background", "bandwidth-monitored", "bi-directional", "bifurcated", "bottom-line", "clear-thinking", "client-driven", "client-server", "coherent", "cohesive", "composite", "context-sensitive", "contextually-based", "content-based", "dedicated", "demand-driven", "didactic", "directional", "discrete", "disintermediate", "dynamic", "eco-centric", "empowering", "encompassing", "even-keeled", "executive", "explicit", "exuding", "fault-tolerant", "foreground", "fresh-thinking", "full-range", "global", "grid-enabled", "heuristic", "high-level", "holistic", "homogeneous", "human-resource", "hybrid", "impactful", "incremental", "intangible", "interactive", "intermediate", "leading edge", "local", "logistical", "maximized", "methodical", "mission-critical", "mobile", "modular", "motivating", "multimedia", "multi-state", "multi-tasking", "national", "needs-based", "neutral", "next generation", "non-volatile", "object-oriented", "optimal", "optimizing", "radical", "real-time", "reciprocal", "regional", "responsive", "scalable", "secondary", "solution-oriented", "stable", "static", "systematic", "systemic", "system-worthy", "tangible", "tertiary", "transitional", "uniform", "upward-trending", "user-facing", "value-added", "web-enabled", "well-modulated", "zero administration", "zero defect", "zero tolerance" ]; },{}],74:[function(require,module,exports){ var company = {}; module['exports'] = company; company.suffix = require("./suffix"); company.adjective = require("./adjective"); company.descriptor = require("./descriptor"); company.noun = require("./noun"); company.bs_verb = require("./bs_verb"); company.bs_adjective = require("./bs_adjective"); company.bs_noun = require("./bs_noun"); company.name = require("./name"); },{"./adjective":69,"./bs_adjective":70,"./bs_noun":71,"./bs_verb":72,"./descriptor":73,"./name":75,"./noun":76,"./suffix":77}],75:[function(require,module,exports){ module["exports"] = [ "#{Name.last_name} #{suffix}", "#{Name.last_name}-#{Name.last_name}", "#{Name.last_name}, #{Name.last_name} and #{Name.last_name}" ]; },{}],76:[function(require,module,exports){ module["exports"] = [ "ability", "access", "adapter", "algorithm", "alliance", "analyzer", "application", "approach", "architecture", "archive", "artificial intelligence", "array", "attitude", "benchmark", "budgetary management", "capability", "capacity", "challenge", "circuit", "collaboration", "complexity", "concept", "conglomeration", "contingency", "core", "customer loyalty", "database", "data-warehouse", "definition", "emulation", "encoding", "encryption", "extranet", "firmware", "flexibility", "focus group", "forecast", "frame", "framework", "function", "functionalities", "Graphic Interface", "groupware", "Graphical User Interface", "hardware", "help-desk", "hierarchy", "hub", "implementation", "info-mediaries", "infrastructure", "initiative", "installation", "instruction set", "interface", "internet solution", "intranet", "knowledge user", "knowledge base", "local area network", "leverage", "matrices", "matrix", "methodology", "middleware", "migration", "model", "moderator", "monitoring", "moratorium", "neural-net", "open architecture", "open system", "orchestration", "paradigm", "parallelism", "policy", "portal", "pricing structure", "process improvement", "product", "productivity", "project", "projection", "protocol", "secured line", "service-desk", "software", "solution", "standardization", "strategy", "structure", "success", "superstructure", "support", "synergy", "system engine", "task-force", "throughput", "time-frame", "toolset", "utilisation", "website", "workforce" ]; },{}],77:[function(require,module,exports){ module["exports"] = [ "Inc", "and Sons", "LLC", "Group" ]; },{}],78:[function(require,module,exports){ module["exports"] = [ "/34##-######-####L/", "/37##-######-####L/" ]; },{}],79:[function(require,module,exports){ module["exports"] = [ "/30[0-5]#-######-###L/", "/368#-######-###L/" ]; },{}],80:[function(require,module,exports){ module["exports"] = [ "/6011-####-####-###L/", "/65##-####-####-###L/", "/64[4-9]#-####-####-###L/", "/6011-62##-####-####-###L/", "/65##-62##-####-####-###L/", "/64[4-9]#-62##-####-####-###L/" ]; },{}],81:[function(require,module,exports){ var credit_card = {}; module['exports'] = credit_card; credit_card.visa = require("./visa"); credit_card.mastercard = require("./mastercard"); credit_card.discover = require("./discover"); credit_card.american_express = require("./american_express"); credit_card.diners_club = require("./diners_club"); credit_card.jcb = require("./jcb"); credit_card.switch = require("./switch"); credit_card.solo = require("./solo"); credit_card.maestro = require("./maestro"); credit_card.laser = require("./laser"); },{"./american_express":78,"./diners_club":79,"./discover":80,"./jcb":82,"./laser":83,"./maestro":84,"./mastercard":85,"./solo":86,"./switch":87,"./visa":88}],82:[function(require,module,exports){ module["exports"] = [ "/3528-####-####-###L/", "/3529-####-####-###L/", "/35[3-8]#-####-####-###L/" ]; },{}],83:[function(require,module,exports){ module["exports"] = [ "/6304###########L/", "/6706###########L/", "/6771###########L/", "/6709###########L/", "/6304#########{5,6}L/", "/6706#########{5,6}L/", "/6771#########{5,6}L/", "/6709#########{5,6}L/" ]; },{}],84:[function(require,module,exports){ module["exports"] = [ "/50#{9,16}L/", "/5[6-8]#{9,16}L/", "/56##{9,16}L/" ]; },{}],85:[function(require,module,exports){ module["exports"] = [ "/5[1-5]##-####-####-###L/", "/6771-89##-####-###L/" ]; },{}],86:[function(require,module,exports){ module["exports"] = [ "/6767-####-####-###L/", "/6767-####-####-####-#L/", "/6767-####-####-####-##L/" ]; },{}],87:[function(require,module,exports){ module["exports"] = [ "/6759-####-####-###L/", "/6759-####-####-####-#L/", "/6759-####-####-####-##L/" ]; },{}],88:[function(require,module,exports){ module["exports"] = [ "/4###########L/", "/4###-####-####-###L/" ]; },{}],89:[function(require,module,exports){ var date = {}; module["exports"] = date; date.month = require("./month"); date.weekday = require("./weekday"); },{"./month":90,"./weekday":91}],90:[function(require,module,exports){ // Source: http://unicode.org/cldr/trac/browser/tags/release-27/common/main/en.xml#L1799 module["exports"] = { wide: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], // Property "wide_context" is optional, if not set then "wide" will be used instead // It is used to specify a word in context, which may differ from a stand-alone word wide_context: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], abbr: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], // Property "abbr_context" is optional, if not set then "abbr" will be used instead // It is used to specify a word in context, which may differ from a stand-alone word abbr_context: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] }; },{}],91:[function(require,module,exports){ // Source: http://unicode.org/cldr/trac/browser/tags/release-27/common/main/en.xml#L1847 module["exports"] = { wide: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], // Property "wide_context" is optional, if not set then "wide" will be used instead // It is used to specify a word in context, which may differ from a stand-alone word wide_context: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], abbr: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], // Property "abbr_context" is optional, if not set then "abbr" will be used instead // It is used to specify a word in context, which may differ from a stand-alone word abbr_context: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ] }; },{}],92:[function(require,module,exports){ module["exports"] = [ "Checking", "Savings", "Money Market", "Investment", "Home Loan", "Credit Card", "Auto Loan", "Personal Loan" ]; },{}],93:[function(require,module,exports){ module["exports"] = { "UAE Dirham": { "code": "AED", "symbol": "" }, "Afghani": { "code": "AFN", "symbol": "؋" }, "Lek": { "code": "ALL", "symbol": "Lek" }, "Armenian Dram": { "code": "AMD", "symbol": "" }, "Netherlands Antillian Guilder": { "code": "ANG", "symbol": "ƒ" }, "Kwanza": { "code": "AOA", "symbol": "" }, "Argentine Peso": { "code": "ARS", "symbol": "$" }, "Australian Dollar": { "code": "AUD", "symbol": "$" }, "Aruban Guilder": { "code": "AWG", "symbol": "ƒ" }, "Azerbaijanian Manat": { "code": "AZN", "symbol": "ман" }, "Convertible Marks": { "code": "BAM", "symbol": "KM" }, "Barbados Dollar": { "code": "BBD", "symbol": "$" }, "Taka": { "code": "BDT", "symbol": "" }, "Bulgarian Lev": { "code": "BGN", "symbol": "лв" }, "Bahraini Dinar": { "code": "BHD", "symbol": "" }, "Burundi Franc": { "code": "BIF", "symbol": "" }, "Bermudian Dollar (customarily known as Bermuda Dollar)": { "code": "BMD", "symbol": "$" }, "Brunei Dollar": { "code": "BND", "symbol": "$" }, "Boliviano Mvdol": { "code": "BOB BOV", "symbol": "$b" }, "Brazilian Real": { "code": "BRL", "symbol": "R$" }, "Bahamian Dollar": { "code": "BSD", "symbol": "$" }, "Pula": { "code": "BWP", "symbol": "P" }, "Belarussian Ruble": { "code": "BYR", "symbol": "p." }, "Belize Dollar": { "code": "BZD", "symbol": "BZ$" }, "Canadian Dollar": { "code": "CAD", "symbol": "$" }, "Congolese Franc": { "code": "CDF", "symbol": "" }, "Swiss Franc": { "code": "CHF", "symbol": "CHF" }, "Chilean Peso Unidades de fomento": { "code": "CLP CLF", "symbol": "$" }, "Yuan Renminbi": { "code": "CNY", "symbol": "¥" }, "Colombian Peso Unidad de Valor Real": { "code": "COP COU", "symbol": "$" }, "Costa Rican Colon": { "code": "CRC", "symbol": "₡" }, "Cuban Peso Peso Convertible": { "code": "CUP CUC", "symbol": "₱" }, "Cape Verde Escudo": { "code": "CVE", "symbol": "" }, "Czech Koruna": { "code": "CZK", "symbol": "Kč" }, "Djibouti Franc": { "code": "DJF", "symbol": "" }, "Danish Krone": { "code": "DKK", "symbol": "kr" }, "Dominican Peso": { "code": "DOP", "symbol": "RD$" }, "Algerian Dinar": { "code": "DZD", "symbol": "" }, "Kroon": { "code": "EEK", "symbol": "" }, "Egyptian Pound": { "code": "EGP", "symbol": "£" }, "Nakfa": { "code": "ERN", "symbol": "" }, "Ethiopian Birr": { "code": "ETB", "symbol": "" }, "Euro": { "code": "EUR", "symbol": "€" }, "Fiji Dollar": { "code": "FJD", "symbol": "$" }, "Falkland Islands Pound": { "code": "FKP", "symbol": "£" }, "Pound Sterling": { "code": "GBP", "symbol": "£" }, "Lari": { "code": "GEL", "symbol": "" }, "Cedi": { "code": "GHS", "symbol": "" }, "Gibraltar Pound": { "code": "GIP", "symbol": "£" }, "Dalasi": { "code": "GMD", "symbol": "" }, "Guinea Franc": { "code": "GNF", "symbol": "" }, "Quetzal": { "code": "GTQ", "symbol": "Q" }, "Guyana Dollar": { "code": "GYD", "symbol": "$" }, "Hong Kong Dollar": { "code": "HKD", "symbol": "$" }, "Lempira": { "code": "HNL", "symbol": "L" }, "Croatian Kuna": { "code": "HRK", "symbol": "kn" }, "Gourde US Dollar": { "code": "HTG USD", "symbol": "" }, "Forint": { "code": "HUF", "symbol": "Ft" }, "Rupiah": { "code": "IDR", "symbol": "Rp" }, "New Israeli Sheqel": { "code": "ILS", "symbol": "₪" }, "Indian Rupee": { "code": "INR", "symbol": "" }, "Indian Rupee Ngultrum": { "code": "INR BTN", "symbol": "" }, "Iraqi Dinar": { "code": "IQD", "symbol": "" }, "Iranian Rial": { "code": "IRR", "symbol": "﷼" }, "Iceland Krona": { "code": "ISK", "symbol": "kr" }, "Jamaican Dollar": { "code": "JMD", "symbol": "J$" }, "Jordanian Dinar": { "code": "JOD", "symbol": "" }, "Yen": { "code": "JPY", "symbol": "¥" }, "Kenyan Shilling": { "code": "KES", "symbol": "" }, "Som": { "code": "KGS", "symbol": "лв" }, "Riel": { "code": "KHR", "symbol": "៛" }, "Comoro Franc": { "code": "KMF", "symbol": "" }, "North Korean Won": { "code": "KPW", "symbol": "₩" }, "Won": { "code": "KRW", "symbol": "₩" }, "Kuwaiti Dinar": { "code": "KWD", "symbol": "" }, "Cayman Islands Dollar": { "code": "KYD", "symbol": "$" }, "Tenge": { "code": "KZT", "symbol": "лв" }, "Kip": { "code": "LAK", "symbol": "₭" }, "Lebanese Pound": { "code": "LBP", "symbol": "£" }, "Sri Lanka Rupee": { "code": "LKR", "symbol": "₨" }, "Liberian Dollar": { "code": "LRD", "symbol": "$" }, "Lithuanian Litas": { "code": "LTL", "symbol": "Lt" }, "Latvian Lats": { "code": "LVL", "symbol": "Ls" }, "Libyan Dinar": { "code": "LYD", "symbol": "" }, "Moroccan Dirham": { "code": "MAD", "symbol": "" }, "Moldovan Leu": { "code": "MDL", "symbol": "" }, "Malagasy Ariary": { "code": "MGA", "symbol": "" }, "Denar": { "code": "MKD", "symbol": "ден" }, "Kyat": { "code": "MMK", "symbol": "" }, "Tugrik": { "code": "MNT", "symbol": "₮" }, "Pataca": { "code": "MOP", "symbol": "" }, "Ouguiya": { "code": "MRO", "symbol": "" }, "Mauritius Rupee": { "code": "MUR", "symbol": "₨" }, "Rufiyaa": { "code": "MVR", "symbol": "" }, "Kwacha": { "code": "MWK", "symbol": "" }, "Mexican Peso Mexican Unidad de Inversion (UDI)": { "code": "MXN MXV", "symbol": "$" }, "Malaysian Ringgit": { "code": "MYR", "symbol": "RM" }, "Metical": { "code": "MZN", "symbol": "MT" }, "Naira": { "code": "NGN", "symbol": "₦" }, "Cordoba Oro": { "code": "NIO", "symbol": "C$" }, "Norwegian Krone": { "code": "NOK", "symbol": "kr" }, "Nepalese Rupee": { "code": "NPR", "symbol": "₨" }, "New Zealand Dollar": { "code": "NZD", "symbol": "$" }, "Rial Omani": { "code": "OMR", "symbol": "﷼" }, "Balboa US Dollar": { "code": "PAB USD", "symbol": "B/." }, "Nuevo Sol": { "code": "PEN", "symbol": "S/." }, "Kina": { "code": "PGK", "symbol": "" }, "Philippine Peso": { "code": "PHP", "symbol": "Php" }, "Pakistan Rupee": { "code": "PKR", "symbol": "₨" }, "Zloty": { "code": "PLN", "symbol": "zł" }, "Guarani": { "code": "PYG", "symbol": "Gs" }, "Qatari Rial": { "code": "QAR", "symbol": "﷼" }, "New Leu": { "code": "RON", "symbol": "lei" }, "Serbian Dinar": { "code": "RSD", "symbol": "Дин." }, "Russian Ruble": { "code": "RUB", "symbol": "руб" }, "Rwanda Franc": { "code": "RWF", "symbol": "" }, "Saudi Riyal": { "code": "SAR", "symbol": "﷼" }, "Solomon Islands Dollar": { "code": "SBD", "symbol": "$" }, "Seychelles Rupee": { "code": "SCR", "symbol": "₨" }, "Sudanese Pound": { "code": "SDG", "symbol": "" }, "Swedish Krona": { "code": "SEK", "symbol": "kr" }, "Singapore Dollar": { "code": "SGD", "symbol": "$" }, "Saint Helena Pound": { "code": "SHP", "symbol": "£" }, "Leone": { "code": "SLL", "symbol": "" }, "Somali Shilling": { "code": "SOS", "symbol": "S" }, "Surinam Dollar": { "code": "SRD", "symbol": "$" }, "Dobra": { "code": "STD", "symbol": "" }, "El Salvador Colon US Dollar": { "code": "SVC USD", "symbol": "$" }, "Syrian Pound": { "code": "SYP", "symbol": "£" }, "Lilangeni": { "code": "SZL", "symbol": "" }, "Baht": { "code": "THB", "symbol": "฿" }, "Somoni": { "code": "TJS", "symbol": "" }, "Manat": { "code": "TMT", "symbol": "" }, "Tunisian Dinar": { "code": "TND", "symbol": "" }, "Pa'anga": { "code": "TOP", "symbol": "" }, "Turkish Lira": { "code": "TRY", "symbol": "TL" }, "Trinidad and Tobago Dollar": { "code": "TTD", "symbol": "TT$" }, "New Taiwan Dollar": { "code": "TWD", "symbol": "NT$" }, "Tanzanian Shilling": { "code": "TZS", "symbol": "" }, "Hryvnia": { "code": "UAH", "symbol": "₴" }, "Uganda Shilling": { "code": "UGX", "symbol": "" }, "US Dollar": { "code": "USD", "symbol": "$" }, "Peso Uruguayo Uruguay Peso en Unidades Indexadas": { "code": "UYU UYI", "symbol": "$U" }, "Uzbekistan Sum": { "code": "UZS", "symbol": "лв" }, "Bolivar Fuerte": { "code": "VEF", "symbol": "Bs" }, "Dong": { "code": "VND", "symbol": "₫" }, "Vatu": { "code": "VUV", "symbol": "" }, "Tala": { "code": "WST", "symbol": "" }, "CFA Franc BEAC": { "code": "XAF", "symbol": "" }, "Silver": { "code": "XAG", "symbol": "" }, "Gold": { "code": "XAU", "symbol": "" }, "Bond Markets Units European Composite Unit (EURCO)": { "code": "XBA", "symbol": "" }, "European Monetary Unit (E.M.U.-6)": { "code": "XBB", "symbol": "" }, "European Unit of Account 9(E.U.A.-9)": { "code": "XBC", "symbol": "" }, "European Unit of Account 17(E.U.A.-17)": { "code": "XBD", "symbol": "" }, "East Caribbean Dollar": { "code": "XCD", "symbol": "$" }, "SDR": { "code": "XDR", "symbol": "" }, "UIC-Franc": { "code": "XFU", "symbol": "" }, "CFA Franc BCEAO": { "code": "XOF", "symbol": "" }, "Palladium": { "code": "XPD", "symbol": "" }, "CFP Franc": { "code": "XPF", "symbol": "" }, "Platinum": { "code": "XPT", "symbol": "" }, "Codes specifically reserved for testing purposes": { "code": "XTS", "symbol": "" }, "Yemeni Rial": { "code": "YER", "symbol": "﷼" }, "Rand": { "code": "ZAR", "symbol": "R" }, "Rand Loti": { "code": "ZAR LSL", "symbol": "" }, "Rand Namibia Dollar": { "code": "ZAR NAD", "symbol": "" }, "Zambian Kwacha": { "code": "ZMK", "symbol": "" }, "Zimbabwe Dollar": { "code": "ZWL", "symbol": "" } }; },{}],94:[function(require,module,exports){ var finance = {}; module['exports'] = finance; finance.account_type = require("./account_type"); finance.transaction_type = require("./transaction_type"); finance.currency = require("./currency"); },{"./account_type":92,"./currency":93,"./transaction_type":95}],95:[function(require,module,exports){ module["exports"] = [ "deposit", "withdrawal", "payment", "invoice" ]; },{}],96:[function(require,module,exports){ module["exports"] = [ "TCP", "HTTP", "SDD", "RAM", "GB", "CSS", "SSL", "AGP", "SQL", "FTP", "PCI", "AI", "ADP", "RSS", "XML", "EXE", "COM", "HDD", "THX", "SMTP", "SMS", "USB", "PNG", "SAS", "IB", "SCSI", "JSON", "XSS", "JBOD" ]; },{}],97:[function(require,module,exports){ module["exports"] = [ "auxiliary", "primary", "back-end", "digital", "open-source", "virtual", "cross-platform", "redundant", "online", "haptic", "multi-byte", "bluetooth", "wireless", "1080p", "neural", "optical", "solid state", "mobile" ]; },{}],98:[function(require,module,exports){ var hacker = {}; module['exports'] = hacker; hacker.abbreviation = require("./abbreviation"); hacker.adjective = require("./adjective"); hacker.noun = require("./noun"); hacker.verb = require("./verb"); hacker.ingverb = require("./ingverb"); },{"./abbreviation":96,"./adjective":97,"./ingverb":99,"./noun":100,"./verb":101}],99:[function(require,module,exports){ module["exports"] = [ "backing up", "bypassing", "hacking", "overriding", "compressing", "copying", "navigating", "indexing", "connecting", "generating", "quantifying", "calculating", "synthesizing", "transmitting", "programming", "parsing" ]; },{}],100:[function(require,module,exports){ module["exports"] = [ "driver", "protocol", "bandwidth", "panel", "microchip", "program", "port", "card", "array", "interface", "system", "sensor", "firewall", "hard drive", "pixel", "alarm", "feed", "monitor", "application", "transmitter", "bus", "circuit", "capacitor", "matrix" ]; },{}],101:[function(require,module,exports){ module["exports"] = [ "back up", "bypass", "hack", "override", "compress", "copy", "navigate", "index", "connect", "generate", "quantify", "calculate", "synthesize", "input", "transmit", "program", "reboot", "parse" ]; },{}],102:[function(require,module,exports){ var en = {}; module['exports'] = en; en.title = "English"; en.separator = " & "; en.address = require("./address"); en.credit_card = require("./credit_card"); en.company = require("./company"); en.internet = require("./internet"); en.lorem = require("./lorem"); en.name = require("./name"); en.phone_number = require("./phone_number"); en.cell_phone = require("./cell_phone"); en.business = require("./business"); en.commerce = require("./commerce"); en.team = require("./team"); en.hacker = require("./hacker"); en.app = require("./app"); en.finance = require("./finance"); en.date = require("./date"); },{"./address":45,"./app":56,"./business":62,"./cell_phone":64,"./commerce":67,"./company":74,"./credit_card":81,"./date":89,"./finance":94,"./hacker":98,"./internet":106,"./lorem":107,"./name":111,"./phone_number":118,"./team":120}],103:[function(require,module,exports){ module["exports"] = [ "https://s3.amazonaws.com/uifaces/faces/twitter/jarjan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mahdif/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sprayaga/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ruzinav/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/Skyhartman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/moscoz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kurafire/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/91bilal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/igorgarybaldi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/malykhinv/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joelhelin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kushsolitary/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/coreyweb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/snowshade/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/areus/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/holdenweb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/heyimjuani/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/envex/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/unterdreht/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/collegeman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/peejfancher/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andyisonline/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ultragex/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/fuck_you_two/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/adellecharles/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ateneupopular/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ahmetalpbalkan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/Stievius/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kerem/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/osvaldas/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/angelceballos/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thierrykoblentz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/peterlandt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/catarino/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/wr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/weglov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/brandclay/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/flame_kaizar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ahmetsulek/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nicolasfolliot/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jayrobinson/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/victorerixon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kolage/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/michzen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/markjenkins/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nicolai_larsen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/noxdzine/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alagoon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/idiot/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mizko/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chadengle/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mutlu82/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/simobenso/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vocino/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/guiiipontes/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/soyjavi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joshaustin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tomaslau/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/VinThomas/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ManikRathee/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/langate/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cemshid/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/leemunroe/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/_shahedk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/enda/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/BillSKenney/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/divya/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joshhemsley/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sindresorhus/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/soffes/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/9lessons/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/linux29/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/Chakintosh/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/anaami/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joreira/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/shadeed9/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/scottkclark/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jedbridges/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/salleedesign/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marakasina/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ariil/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/BrianPurkiss/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/michaelmartinho/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bublienko/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/devankoshal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ZacharyZorbas/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/timmillwood/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joshuasortino/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/damenleeturks/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tomas_janousek/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/herrhaase/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/RussellBishop/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/brajeshwar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nachtmeister/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cbracco/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bermonpainter/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/abdullindenis/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/isacosta/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/suprb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/yalozhkin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chandlervdw/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/iamgarth/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/_victa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/commadelimited/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/roybarberuk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/axel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vladarbatov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ffbel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/syropian/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ankitind/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/traneblow/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/flashmurphy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ChrisFarina78/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/baliomega/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/saschamt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jm_denis/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/anoff/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kennyadr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chatyrko/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dingyi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mds/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/terryxlife/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aaroni/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kinday/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/prrstn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/eduardostuart/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dhilipsiva/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/GavicoInd/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/baires/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rohixx/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/blakesimkins/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/leeiio/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tjrus/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/uberschizo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kylefoundry/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/claudioguglieri/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ripplemdk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/exentrich/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jakemoore/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joaoedumedeiros/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/poormini/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tereshenkov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/keryilmaz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/haydn_woods/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rude/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/llun/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sgaurav_baghel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jamiebrittain/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/badlittleduck/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/pifagor/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/agromov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/benefritz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/erwanhesry/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/diesellaws/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jeremiaha/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/koridhandy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chaensel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andrewcohen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/smaczny/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gonzalorobaina/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nandini_m/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sydlawrence/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cdharrison/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tgerken/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lewisainslie/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/charliecwaite/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/robbschiller/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/flexrs/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mattdetails/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/raquelwilson/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/karsh/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mrmartineau/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/opnsrce/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hgharrygo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/maximseshuk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/uxalex/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/samihah/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chanpory/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sharvin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/josemarques/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jefffis/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/krystalfister/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lokesh_coder/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thedamianhdez/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dpmachado/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/funwatercat/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/timothycd/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ivanfilipovbg/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/picard102/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marcobarbosa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/krasnoukhov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/g3d/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ademilter/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rickdt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/operatino/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bungiwan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hugomano/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/logorado/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dc_user/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/horaciobella/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/SlaapMe/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/teeragit/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/iqonicd/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ilya_pestov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andrewarrow/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ssiskind/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/stan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/HenryHoffman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rdsaunders/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/adamsxu/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/curiousoffice/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/themadray/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/michigangraham/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kohette/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nickfratter/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/runningskull/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/madysondesigns/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/brenton_clarke/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jennyshen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bradenhamm/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kurtinc/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/amanruzaini/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/coreyhaggard/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/Karimmove/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aaronalfred/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/wtrsld/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jitachi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/therealmarvin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/pmeissner/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ooomz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chacky14/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jesseddy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thinmatt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/shanehudson/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/akmur/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/IsaryAmairani/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/arthurholcombe1/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andychipster/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/boxmodel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ehsandiary/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/LucasPerdidao/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/shalt0ni/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/swaplord/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kaelifa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/plbabin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/guillemboti/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/arindam_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/renbyrd/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thiagovernetti/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jmillspaysbills/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mikemai2awesome/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jervo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mekal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sta1ex/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/robergd/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/felipecsl/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andrea211087/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/garand/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dhooyenga/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/abovefunction/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/pcridesagain/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/randomlies/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/BryanHorsey/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/heykenneth/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dahparra/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/allthingssmitty/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/danvernon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/beweinreich/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/increase/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/falvarad/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alxndrustinov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/souuf/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/orkuncaylar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/AM_Kn2/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gearpixels/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bassamology/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vimarethomas/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kosmar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/SULiik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mrjamesnoble/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/silvanmuhlemann/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/shaneIxD/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nacho/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/yigitpinarbasi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/buzzusborne/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aaronkwhite/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rmlewisuk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/giancarlon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nbirckel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/d_nny_m_cher/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sdidonato/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/atariboy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/abotap/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/karalek/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/psdesignuk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ludwiczakpawel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nemanjaivanovic/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/baluli/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ahmadajmi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vovkasolovev/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/samgrover/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/derienzo777/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jonathansimmons/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nelsonjoyce/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/S0ufi4n3/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/xtopherpaul/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/oaktreemedia/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nateschulte/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/findingjenny/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/namankreative/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/antonyzotov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/we_social/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/leehambley/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/solid_color/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/abelcabans/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mbilderbach/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kkusaa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jordyvdboom/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/carlosgavina/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/pechkinator/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vc27/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rdbannon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/croakx/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/suribbles/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kerihenare/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/catadeleon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gcmorley/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/duivvv/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/saschadroste/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/victorDubugras/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/wintopia/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mattbilotti/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/taylorling/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/megdraws/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/meln1ks/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mahmoudmetwally/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/Silveredge9/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/derekebradley/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/happypeter1983/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/travis_arnold/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/artem_kostenko/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/adobi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/daykiine/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alek_djuric/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/scips/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/miguelmendes/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/justinrhee/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alsobrooks/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/fronx/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mcflydesign/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/santi_urso/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/allfordesign/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/stayuber/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bertboerland/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marosholly/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/adamnac/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cynthiasavard/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/muringa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/danro/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hiemil/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jackiesaik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/zacsnider/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/iduuck/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/antjanus/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aroon_sharma/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dshster/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thehacker/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/michaelbrooksjr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ryanmclaughlin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/clubb3rry/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/taybenlor/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/xripunov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/myastro/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/adityasutomo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/digitalmaverick/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hjartstrorn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/itolmach/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vaughanmoffitt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/abdots/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/isnifer/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sergeysafonov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/maz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/scrapdnb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chrismj83/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vitorleal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sokaniwaal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/zaki3d/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/illyzoren/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mocabyte/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/osmanince/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/djsherman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/davidhemphill/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/waghner/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/necodymiconer/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/praveen_vijaya/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/fabbrucci/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cliffseal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/travishines/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kuldarkalvik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/Elt_n/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/phillapier/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/okseanjay/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/id835559/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kudretkeskin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/anjhero/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/duck4fuck/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/scott_riley/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/noufalibrahim/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/h1brd/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/borges_marcos/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/devinhalladay/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ciaranr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/stefooo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mikebeecham/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tonymillion/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joshuaraichur/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/irae/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/petrangr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dmitriychuta/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/charliegann/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/arashmanteghi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ainsleywagon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/svenlen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/faisalabid/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/beshur/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/carlyson/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dutchnadia/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/teddyzetterlund/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/samuelkraft/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aoimedia/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/toddrew/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/codepoet_ru/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/artvavs/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/benoitboucart/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jomarmen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kolmarlopez/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/creartinc/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/homka/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gaborenton/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/robinclediere/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/maximsorokin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/plasticine/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/j2deme/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/peachananr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kapaluccio/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/de_ascanio/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rikas/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dawidwu/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/angelcreative/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rpatey/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/popey/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rehatkathuria/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/the_purplebunny/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/1markiz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ajaxy_ru/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/brenmurrell/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dudestein/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/oskarlevinson/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/victorstuber/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nehfy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vicivadeline/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/leandrovaranda/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/scottgallant/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/victor_haydin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sawrb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ryhanhassan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/amayvs/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/a_brixen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/karolkrakowiak_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/herkulano/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/geran7/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cggaurav/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chris_witko/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lososina/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/polarity/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mattlat/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/brandonburke/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/constantx/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/teylorfeliz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/craigelimeliah/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rachelreveley/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/reabo101/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rahmeen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ky/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rickyyean/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/j04ntoh/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/spbroma/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sebashton/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jpenico/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/francis_vega/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/oktayelipek/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kikillo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/fabbianz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/larrygerard/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/BroumiYoussef/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/0therplanet/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mbilalsiddique1/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ionuss/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/grrr_nl/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/liminha/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rawdiggie/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ryandownie/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sethlouey/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/pixage/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/arpitnj/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/switmer777/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/josevnclch/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kanickairaj/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/puzik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tbakdesigns/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/besbujupi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/supjoey/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lowie/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/linkibol/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/balintorosz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/imcoding/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/agustincruiz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gusoto/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thomasschrijer/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/superoutman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kalmerrautam/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gabrielizalo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gojeanyn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/davidbaldie/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/_vojto/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/laurengray/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jydesign/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mymyboy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nellleo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marciotoledo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ninjad3m0/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/to_soham/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hasslunsford/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/muridrahhal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/levisan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/grahamkennery/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lepetitogre/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/antongenkin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nessoila/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/amandabuzard/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/safrankov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cocolero/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dss49/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/matt3224/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bluesix/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/quailandquasar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/AlbertoCococi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lepinski/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sementiy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mhudobivnik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thibaut_re/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/olgary/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/shojberg/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mtolokonnikov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bereto/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/naupintos/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/wegotvices/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/xadhix/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/macxim/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rodnylobos/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/madcampos/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/madebyvadim/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bartoszdawydzik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/supervova/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/markretzloff/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vonachoo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/darylws/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/stevedesigner/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mylesb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/herbigt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/depaulawagner/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/geshan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gizmeedevil1991/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/_scottburgess/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lisovsky/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/davidsasda/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/artd_sign/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/YoungCutlass/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mgonto/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/itstotallyamy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/victorquinn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/osmond/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/oksanafrewer/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/zauerkraut/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/iamkeithmason/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nitinhayaran/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lmjabreu/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mandalareopens/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thinkleft/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ponchomendivil/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/juamperro/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/brunodesign1206/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/caseycavanagh/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/luxe/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dotgridline/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/spedwig/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/madewulf/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mattsapii/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/helderleal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chrisstumph/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jayphen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nsamoylov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chrisvanderkooi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/justme_timothyg/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/otozk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/prinzadi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gu5taf/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cyril_gaillard/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/d_kobelyatsky/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/daniloc/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nwdsha/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/romanbulah/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/skkirilov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dvdwinden/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dannol/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thekevinjones/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jwalter14/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/timgthomas/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/buddhasource/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/uxpiper/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thatonetommy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/diansigitp/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/adrienths/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/klimmka/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gkaam/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/derekcramer/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jennyyo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nerrsoft/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/xalionmalik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/edhenderson/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/keyuri85/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/roxanejammet/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kimcool/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/edkf/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/matkins/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alessandroribe/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jacksonlatka/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lebronjennan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kostaspt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/karlkanall/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/moynihan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/danpliego/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/saulihirvi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/wesleytrankin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/fjaguero/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bowbrick/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mashaaaaal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/yassiryahya/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dparrelli/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/fotomagin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aka_james/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/denisepires/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/iqbalperkasa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/martinansty/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jarsen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/r_oy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/justinrob/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gabrielrosser/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/malgordon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/carlfairclough/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/michaelabehsera/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/pierrestoffe/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/enjoythetau/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/loganjlambert/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rpeezy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/coreyginnivan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/michalhron/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/msveet/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lingeswaran/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kolsvein/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/peter576/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/reideiredale/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joeymurdah/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/raphaelnikson/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mvdheuvel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/maxlinderman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jimmuirhead/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/begreative/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/frankiefreesbie/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/robturlinckx/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/Talbi_ConSept/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/longlivemyword/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vanchesz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/maiklam/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hermanobrother/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rez___a/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gregsqueeb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/greenbes/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/_ragzor/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/anthonysukow/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/fluidbrush/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dactrtr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jehnglynn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bergmartin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hugocornejo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/_kkga/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dzantievm/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sawalazar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sovesove/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jonsgotwood/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/byryan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vytautas_a/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mizhgan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cicerobr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nilshelmersson/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/d33pthought/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/davecraige/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nckjrvs/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alexandermayes/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jcubic/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/craigrcoles/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bagawarman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rob_thomas10/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cofla/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/maikelk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rtgibbons/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/russell_baylis/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mhesslow/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/codysanfilippo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/webtanya/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/madebybrenton/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dcalonaci/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/perfectflow/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jjsiii/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/saarabpreet/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kumarrajan12123/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/iamsteffen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/themikenagle/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ceekaytweet/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/larrybolt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/conspirator/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dallasbpeters/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/n3dmax/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/terpimost/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kirillz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/byrnecore/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/j_drake_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/calebjoyce/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/russoedu/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hoangloi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tobysaxon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gofrasdesign/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dimaposnyy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tjisousa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/okandungel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/billyroshan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/oskamaya/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/motionthinks/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/knilob/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ashocka18/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marrimo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bartjo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/omnizya/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ernestsemerda/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andreas_pr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/edgarchris99/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thomasgeisen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gseguin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joannefournier/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/demersdesigns/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/adammarsbar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nasirwd/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/n_tassone/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/javorszky/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/themrdave/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/yecidsm/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nicollerich/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/canapud/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nicoleglynn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/judzhin_miles/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/designervzm/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kianoshp/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/evandrix/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alterchuca/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dhrubo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ma_tiax/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ssbb_me/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dorphern/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mauriolg/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bruno_mart/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mactopus/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/the_winslet/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joemdesign/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/Shriiiiimp/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jacobbennett/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nfedoroff/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/iamglimy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/allagringaus/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aiiaiiaii/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/olaolusoga/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/buryaknick/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/wim1k/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nicklacke/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/a1chapone/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/steynviljoen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/strikewan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ryankirkman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andrewabogado/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/doooon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jagan123/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ariffsetiawan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/elenadissi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mwarkentin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thierrymeier_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/r_garcia/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dmackerman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/borantula/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/konus/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/spacewood_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ryuchi311/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/evanshajed/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tristanlegros/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/shoaib253/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aislinnkelly/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/okcoker/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/timpetricola/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sunshinedgirl/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chadami/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aleclarsoniv/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nomidesigns/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/petebernardo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/scottiedude/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/millinet/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/imsoper/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/imammuht/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/benjamin_knight/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nepdud/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joki4/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lanceguyatt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bboy1895/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/amywebbb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rweve/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/haruintesettden/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ricburton/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nelshd/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/batsirai/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/primozcigler/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jffgrdnr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/8d3k/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/geneseleznev/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/al_li/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/souperphly/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mslarkina/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/2fockus/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cdavis565/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/xiel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/turkutuuli/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/uxward/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lebinoclard/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gauravjassal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/davidmerrique/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mdsisto/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andrewofficer/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kojourin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dnirmal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kevka/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mr_shiznit/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aluisio_azevedo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cloudstudio/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/danvierich/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alexivanichkin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/fran_mchamy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/perretmagali/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/betraydan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cadikkara/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/matbeedotcom/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jeremyworboys/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bpartridge/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/michaelkoper/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/silv3rgvn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alevizio/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/johnsmithagency/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lawlbwoy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vitor376/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/desastrozo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thimo_cz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jasonmarkjones/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lhausermann/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/xravil/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/guischmitt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vigobronx/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/panghal0/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/miguelkooreman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/surgeonist/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/christianoliff/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/caspergrl/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/iamkarna/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ipavelek/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/pierre_nel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/y2graphic/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sterlingrules/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/elbuscainfo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bennyjien/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/stushona/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/estebanuribe/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/embrcecreations/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/danillos/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/elliotlewis/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/charlesrpratt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vladyn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/emmeffess/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/carlosblanco_eu/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/leonfedotov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rangafangs/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chris_frees/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tgormtx/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bryan_topham/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jpscribbles/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mighty55/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/carbontwelve/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/isaacfifth/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/iamjdeleon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/snowwrite/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/barputro/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/drewbyreese/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sachacorazzi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bistrianiosip/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/magoo04/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/pehamondello/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/yayteejay/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/a_harris88/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/algunsanabria/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/zforrester/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ovall/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/carlosjgsousa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/geobikas/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ah_lice/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/looneydoodle/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nerdgr8/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ddggccaa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/zackeeler/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/normanbox/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/el_fuertisimo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ismail_biltagi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/juangomezw/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jnmnrd/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/patrickcoombe/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ryanjohnson_me/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/markolschesky/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jeffgolenski/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kvasnic/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lindseyzilla/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gauchomatt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/afusinatto/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kevinoh/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/okansurreel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/adamawesomeface/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/emileboudeling/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/arishi_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/juanmamartinez/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/wikiziner/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/danthms/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mkginfo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/terrorpixel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/curiousonaut/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/prheemo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/michaelcolenso/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/foczzi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/martip07/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thaodang17/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/johncafazza/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/robinlayfield/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/franciscoamk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/abdulhyeuk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marklamb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/edobene/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andresenfredrik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mikaeljorhult/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chrisslowik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vinciarts/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/meelford/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/elliotnolten/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/yehudab/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vijaykarthik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bfrohs/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/josep_martins/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/attacks/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sur4dye/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tumski/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/instalox/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mangosango/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/paulfarino/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kazaky999/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kiwiupover/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nvkznemo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tom_even/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ratbus/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/woodsman001/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joshmedeski/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thewillbeard/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/psaikali/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joe_black/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aleinadsays/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marcusgorillius/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hota_v/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jghyllebert/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/shinze/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/janpalounek/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jeremiespoken/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/her_ruu/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dansowter/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/felipeapiress/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/magugzbrand2d/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/posterjob/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nathalie_fs/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bobbytwoshoes/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dreizle/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jeremymouton/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/elisabethkjaer/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/notbadart/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mohanrohith/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jlsolerdeltoro/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/itskawsar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/slowspock/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/zvchkelly/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/wiljanslofstra/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/craighenneberry/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/trubeatto/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/juaumlol/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/samscouto/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/BenouarradeM/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gipsy_raf/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/netonet_il/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/arkokoley/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/itsajimithing/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/smalonso/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/victordeanda/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/_dwite_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/richardgarretts/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gregrwilkinson/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/anatolinicolae/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lu4sh1i/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/stefanotirloni/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ostirbu/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/darcystonge/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/naitanamoreno/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/michaelcomiskey/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/adhiardana/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marcomano_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/davidcazalis/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/falconerie/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gregkilian/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bcrad/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bolzanmarco/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/low_res/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vlajki/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/petar_prog/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jonkspr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/akmalfikri/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mfacchinello/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/atanism/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/harry_sistalam/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/murrayswift/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bobwassermann/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gavr1l0/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/madshensel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mr_subtle/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/deviljho_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/salimianoff/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joetruesdell/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/twittypork/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/airskylar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dnezkumar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dgajjar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cherif_b/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/salvafc/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/louis_currie/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/deeenright/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cybind/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/eyronn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vickyshits/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sweetdelisa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cboller1/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andresdjasso/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/melvindidit/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andysolomon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thaisselenator_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lvovenok/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/giuliusa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/belyaev_rs/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/overcloacked/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kamal_chaneman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/incubo82/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hellofeverrrr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mhaligowski/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sunlandictwin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bu7921/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andytlaw/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jeremery/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/finchjke/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/manigm/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/umurgdk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/scottfeltham/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ganserene/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mutu_krish/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jodytaggart/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ntfblog/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tanveerrao/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hfalucas/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alxleroydeval/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kucingbelang4/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bargaorobalo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/colgruv/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/stalewine/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kylefrost/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/baumannzone/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/angelcolberg/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sachingawas/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jjshaw14/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ramanathan_pdy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/johndezember/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nilshoenson/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/brandonmorreale/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nutzumi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/brandonflatsoda/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sergeyalmone/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/klefue/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kirangopal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/baumann_alex/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/matthewkay_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jay_wilburn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/shesgared/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/apriendeau/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/johnriordan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/wake_gs/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aleksitappura/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/emsgulam/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/xilantra/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/imomenui/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sircalebgrove/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/newbrushes/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hsinyo23/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/m4rio/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/katiemdaly/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/s4f1/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ecommerceil/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marlinjayakody/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/swooshycueb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sangdth/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/coderdiaz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bluefx_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vivekprvr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sasha_shestakov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/eugeneeweb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dgclegg/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/n1ght_coder/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dixchen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/blakehawksworth/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/trueblood_33/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hai_ninh_nguyen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marclgonzales/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/yesmeck/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/stephcoue/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/doronmalki/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ruehldesign/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/anasnakawa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kijanmaharjan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/wearesavas/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/stefvdham/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tweetubhai/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alecarpentier/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/fiterik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/antonyryndya/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/d00maz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/theonlyzeke/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/missaaamy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/carlosm/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/manekenthe/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/reetajayendra/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jeremyshimko/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/justinrgraham/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/stefanozoffoli/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/overra/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mrebay007/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/shvelo96/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/pyronite/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thedjpetersen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rtyukmaev/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/_williamguerra/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/albertaugustin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vikashpathak18/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kevinjohndayy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vj_demien/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/colirpixoil/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/goddardlewis/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/laasli/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jqiuss/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/heycamtaylor/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nastya_mane/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mastermindesign/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ccinojasso1/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nyancecom/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sandywoodruff/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bighanddesign/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sbtransparent/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aviddayentonbay/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/richwild/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kaysix_dizzy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tur8le/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/seyedhossein1/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/privetwagner/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/emmandenn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dev_essentials/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jmfsocial/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/_yardenoon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mateaodviteza/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/weavermedia/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mufaddal_mw/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hafeeskhan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ashernatali/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sulaqo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/eddiechen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/josecarlospsh/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vm_f/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/enricocicconi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/danmartin70/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gmourier/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/donjain/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mrxloka/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/_pedropinho/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/eitarafa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/oscarowusu/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ralph_lam/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/panchajanyag/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/woodydotmx/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jerrybai1907/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marshallchen_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/xamorep/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aio___/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chaabane_wail/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/txcx/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/akashsharma39/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/falling_soul/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sainraja/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mugukamil/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/johannesneu/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/markwienands/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/karthipanraj/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/balakayuriy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alan_zhang_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/layerssss/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kaspernordkvist/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mirfanqureshi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hanna_smi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/VMilescu/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aeon56/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/m_kalibry/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sreejithexp/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dicesales/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dhoot_amit/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/smenov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lonesomelemon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vladimirdevic/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joelcipriano/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/haligaliharun/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/buleswapnil/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/serefka/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ifarafonow/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vikasvinfotech/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/urrutimeoli/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/areandacom/128.jpg" ]; },{}],104:[function(require,module,exports){ module["exports"] = [ "com", "biz", "info", "name", "net", "org" ]; },{}],105:[function(require,module,exports){ module["exports"] = [ "gmail.com", "yahoo.com", "hotmail.com" ]; },{}],106:[function(require,module,exports){ var internet = {}; module['exports'] = internet; internet.free_email = require("./free_email"); internet.domain_suffix = require("./domain_suffix"); internet.avatar_uri = require("./avatar_uri"); },{"./avatar_uri":103,"./domain_suffix":104,"./free_email":105}],107:[function(require,module,exports){ var lorem = {}; module['exports'] = lorem; lorem.words = require("./words"); lorem.supplemental = require("./supplemental"); },{"./supplemental":108,"./words":109}],108:[function(require,module,exports){ module["exports"] = [ "abbas", "abduco", "abeo", "abscido", "absconditus", "absens", "absorbeo", "absque", "abstergo", "absum", "abundans", "abutor", "accedo", "accendo", "acceptus", "accipio", "accommodo", "accusator", "acer", "acerbitas", "acervus", "acidus", "acies", "acquiro", "acsi", "adamo", "adaugeo", "addo", "adduco", "ademptio", "adeo", "adeptio", "adfectus", "adfero", "adficio", "adflicto", "adhaero", "adhuc", "adicio", "adimpleo", "adinventitias", "adipiscor", "adiuvo", "administratio", "admiratio", "admitto", "admoneo", "admoveo", "adnuo", "adopto", "adsidue", "adstringo", "adsuesco", "adsum", "adulatio", "adulescens", "adultus", "aduro", "advenio", "adversus", "advoco", "aedificium", "aeger", "aegre", "aegrotatio", "aegrus", "aeneus", "aequitas", "aequus", "aer", "aestas", "aestivus", "aestus", "aetas", "aeternus", "ager", "aggero", "aggredior", "agnitio", "agnosco", "ago", "ait", "aiunt", "alienus", "alii", "alioqui", "aliqua", "alius", "allatus", "alo", "alter", "altus", "alveus", "amaritudo", "ambitus", "ambulo", "amicitia", "amiculum", "amissio", "amita", "amitto", "amo", "amor", "amoveo", "amplexus", "amplitudo", "amplus", "ancilla", "angelus", "angulus", "angustus", "animadverto", "animi", "animus", "annus", "anser", "ante", "antea", "antepono", "antiquus", "aperio", "aperte", "apostolus", "apparatus", "appello", "appono", "appositus", "approbo", "apto", "aptus", "apud", "aqua", "ara", "aranea", "arbitro", "arbor", "arbustum", "arca", "arceo", "arcesso", "arcus", "argentum", "argumentum", "arguo", "arma", "armarium", "armo", "aro", "ars", "articulus", "artificiose", "arto", "arx", "ascisco", "ascit", "asper", "aspicio", "asporto", "assentator", "astrum", "atavus", "ater", "atqui", "atrocitas", "atrox", "attero", "attollo", "attonbitus", "auctor", "auctus", "audacia", "audax", "audentia", "audeo", "audio", "auditor", "aufero", "aureus", "auris", "aurum", "aut", "autem", "autus", "auxilium", "avaritia", "avarus", "aveho", "averto", "avoco", "baiulus", "balbus", "barba", "bardus", "basium", "beatus", "bellicus", "bellum", "bene", "beneficium", "benevolentia", "benigne", "bestia", "bibo", "bis", "blandior", "bonus", "bos", "brevis", "cado", "caecus", "caelestis", "caelum", "calamitas", "calcar", "calco", "calculus", "callide", "campana", "candidus", "canis", "canonicus", "canto", "capillus", "capio", "capitulus", "capto", "caput", "carbo", "carcer", "careo", "caries", "cariosus", "caritas", "carmen", "carpo", "carus", "casso", "caste", "casus", "catena", "caterva", "cattus", "cauda", "causa", "caute", "caveo", "cavus", "cedo", "celebrer", "celer", "celo", "cena", "cenaculum", "ceno", "censura", "centum", "cerno", "cernuus", "certe", "certo", "certus", "cervus", "cetera", "charisma", "chirographum", "cibo", "cibus", "cicuta", "cilicium", "cimentarius", "ciminatio", "cinis", "circumvenio", "cito", "civis", "civitas", "clam", "clamo", "claro", "clarus", "claudeo", "claustrum", "clementia", "clibanus", "coadunatio", "coaegresco", "coepi", "coerceo", "cogito", "cognatus", "cognomen", "cogo", "cohaero", "cohibeo", "cohors", "colligo", "colloco", "collum", "colo", "color", "coma", "combibo", "comburo", "comedo", "comes", "cometes", "comis", "comitatus", "commemoro", "comminor", "commodo", "communis", "comparo", "compello", "complectus", "compono", "comprehendo", "comptus", "conatus", "concedo", "concido", "conculco", "condico", "conduco", "confero", "confido", "conforto", "confugo", "congregatio", "conicio", "coniecto", "conitor", "coniuratio", "conor", "conqueror", "conscendo", "conservo", "considero", "conspergo", "constans", "consuasor", "contabesco", "contego", "contigo", "contra", "conturbo", "conventus", "convoco", "copia", "copiose", "cornu", "corona", "corpus", "correptius", "corrigo", "corroboro", "corrumpo", "coruscus", "cotidie", "crapula", "cras", "crastinus", "creator", "creber", "crebro", "credo", "creo", "creptio", "crepusculum", "cresco", "creta", "cribro", "crinis", "cruciamentum", "crudelis", "cruentus", "crur", "crustulum", "crux", "cubicularis", "cubitum", "cubo", "cui", "cuius", "culpa", "culpo", "cultellus", "cultura", "cum", "cunabula", "cunae", "cunctatio", "cupiditas", "cupio", "cuppedia", "cupressus", "cur", "cura", "curatio", "curia", "curiositas", "curis", "curo", "curriculum", "currus", "cursim", "curso", "cursus", "curto", "curtus", "curvo", "curvus", "custodia", "damnatio", "damno", "dapifer", "debeo", "debilito", "decens", "decerno", "decet", "decimus", "decipio", "decor", "decretum", "decumbo", "dedecor", "dedico", "deduco", "defaeco", "defendo", "defero", "defessus", "defetiscor", "deficio", "defigo", "defleo", "defluo", "defungo", "degenero", "degero", "degusto", "deinde", "delectatio", "delego", "deleo", "delibero", "delicate", "delinquo", "deludo", "demens", "demergo", "demitto", "demo", "demonstro", "demoror", "demulceo", "demum", "denego", "denique", "dens", "denuncio", "denuo", "deorsum", "depereo", "depono", "depopulo", "deporto", "depraedor", "deprecator", "deprimo", "depromo", "depulso", "deputo", "derelinquo", "derideo", "deripio", "desidero", "desino", "desipio", "desolo", "desparatus", "despecto", "despirmatio", "infit", "inflammatio", "paens", "patior", "patria", "patrocinor", "patruus", "pauci", "paulatim", "pauper", "pax", "peccatus", "pecco", "pecto", "pectus", "pecunia", "pecus", "peior", "pel", "ocer", "socius", "sodalitas", "sol", "soleo", "solio", "solitudo", "solium", "sollers", "sollicito", "solum", "solus", "solutio", "solvo", "somniculosus", "somnus", "sonitus", "sono", "sophismata", "sopor", "sordeo", "sortitus", "spargo", "speciosus", "spectaculum", "speculum", "sperno", "spero", "spes", "spiculum", "spiritus", "spoliatio", "sponte", "stabilis", "statim", "statua", "stella", "stillicidium", "stipes", "stips", "sto", "strenuus", "strues", "studio", "stultus", "suadeo", "suasoria", "sub", "subito", "subiungo", "sublime", "subnecto", "subseco", "substantia", "subvenio", "succedo", "succurro", "sufficio", "suffoco", "suffragium", "suggero", "sui", "sulum", "sum", "summa", "summisse", "summopere", "sumo", "sumptus", "supellex", "super", "suppellex", "supplanto", "suppono", "supra", "surculus", "surgo", "sursum", "suscipio", "suspendo", "sustineo", "suus", "synagoga", "tabella", "tabernus", "tabesco", "tabgo", "tabula", "taceo", "tactus", "taedium", "talio", "talis", "talus", "tam", "tamdiu", "tamen", "tametsi", "tamisium", "tamquam", "tandem", "tantillus", "tantum", "tardus", "tego", "temeritas", "temperantia", "templum", "temptatio", "tempus", "tenax", "tendo", "teneo", "tener", "tenuis", "tenus", "tepesco", "tepidus", "ter", "terebro", "teres", "terga", "tergeo", "tergiversatio", "tergo", "tergum", "termes", "terminatio", "tero", "terra", "terreo", "territo", "terror", "tersus", "tertius", "testimonium", "texo", "textilis", "textor", "textus", "thalassinus", "theatrum", "theca", "thema", "theologus", "thermae", "thesaurus", "thesis", "thorax", "thymbra", "thymum", "tibi", "timidus", "timor", "titulus", "tolero", "tollo", "tondeo", "tonsor", "torqueo", "torrens", "tot", "totidem", "toties", "totus", "tracto", "trado", "traho", "trans", "tredecim", "tremo", "trepide", "tres", "tribuo", "tricesimus", "triduana", "triginta", "tripudio", "tristis", "triumphus", "trucido", "truculenter", "tubineus", "tui", "tum", "tumultus", "tunc", "turba", "turbo", "turpe", "turpis", "tutamen", "tutis", "tyrannus", "uberrime", "ubi", "ulciscor", "ullus", "ulterius", "ultio", "ultra", "umbra", "umerus", "umquam", "una", "unde", "undique", "universe", "unus", "urbanus", "urbs", "uredo", "usitas", "usque", "ustilo", "ustulo", "usus", "uter", "uterque", "utilis", "utique", "utor", "utpote", "utrimque", "utroque", "utrum", "uxor", "vaco", "vacuus", "vado", "vae", "valde", "valens", "valeo", "valetudo", "validus", "vallum", "vapulus", "varietas", "varius", "vehemens", "vel", "velociter", "velum", "velut", "venia", "venio", "ventito", "ventosus", "ventus", "venustas", "ver", "verbera", "verbum", "vere", "verecundia", "vereor", "vergo", "veritas", "vero", "versus", "verto", "verumtamen", "verus", "vesco", "vesica", "vesper", "vespillo", "vester", "vestigium", "vestrum", "vetus", "via", "vicinus", "vicissitudo", "victoria", "victus", "videlicet", "video", "viduata", "viduo", "vigilo", "vigor", "vilicus", "vilis", "vilitas", "villa", "vinco", "vinculum", "vindico", "vinitor", "vinum", "vir", "virga", "virgo", "viridis", "viriliter", "virtus", "vis", "viscus", "vita", "vitiosus", "vitium", "vito", "vivo", "vix", "vobis", "vociferor", "voco", "volaticus", "volo", "volubilis", "voluntarius", "volup", "volutabrum", "volva", "vomer", "vomica", "vomito", "vorago", "vorax", "voro", "vos", "votum", "voveo", "vox", "vulariter", "vulgaris", "vulgivagus", "vulgo", "vulgus", "vulnero", "vulnus", "vulpes", "vulticulus", "vultuosus", "xiphias" ]; },{}],109:[function(require,module,exports){ module["exports"] = [ "alias", "consequatur", "aut", "perferendis", "sit", "voluptatem", "accusantium", "doloremque", "aperiam", "eaque", "ipsa", "quae", "ab", "illo", "inventore", "veritatis", "et", "quasi", "architecto", "beatae", "vitae", "dicta", "sunt", "explicabo", "aspernatur", "aut", "odit", "aut", "fugit", "sed", "quia", "consequuntur", "magni", "dolores", "eos", "qui", "ratione", "voluptatem", "sequi", "nesciunt", "neque", "dolorem", "ipsum", "quia", "dolor", "sit", "amet", "consectetur", "adipisci", "velit", "sed", "quia", "non", "numquam", "eius", "modi", "tempora", "incidunt", "ut", "labore", "et", "dolore", "magnam", "aliquam", "quaerat", "voluptatem", "ut", "enim", "ad", "minima", "veniam", "quis", "nostrum", "exercitationem", "ullam", "corporis", "nemo", "enim", "ipsam", "voluptatem", "quia", "voluptas", "sit", "suscipit", "laboriosam", "nisi", "ut", "aliquid", "ex", "ea", "commodi", "consequatur", "quis", "autem", "vel", "eum", "iure", "reprehenderit", "qui", "in", "ea", "voluptate", "velit", "esse", "quam", "nihil", "molestiae", "et", "iusto", "odio", "dignissimos", "ducimus", "qui", "blanditiis", "praesentium", "laudantium", "totam", "rem", "voluptatum", "deleniti", "atque", "corrupti", "quos", "dolores", "et", "quas", "molestias", "excepturi", "sint", "occaecati", "cupiditate", "non", "provident", "sed", "ut", "perspiciatis", "unde", "omnis", "iste", "natus", "error", "similique", "sunt", "in", "culpa", "qui", "officia", "deserunt", "mollitia", "animi", "id", "est", "laborum", "et", "dolorum", "fuga", "et", "harum", "quidem", "rerum", "facilis", "est", "et", "expedita", "distinctio", "nam", "libero", "tempore", "cum", "soluta", "nobis", "est", "eligendi", "optio", "cumque", "nihil", "impedit", "quo", "porro", "quisquam", "est", "qui", "minus", "id", "quod", "maxime", "placeat", "facere", "possimus", "omnis", "voluptas", "assumenda", "est", "omnis", "dolor", "repellendus", "temporibus", "autem", "quibusdam", "et", "aut", "consequatur", "vel", "illum", "qui", "dolorem", "eum", "fugiat", "quo", "voluptas", "nulla", "pariatur", "at", "vero", "eos", "et", "accusamus", "officiis", "debitis", "aut", "rerum", "necessitatibus", "saepe", "eveniet", "ut", "et", "voluptates", "repudiandae", "sint", "et", "molestiae", "non", "recusandae", "itaque", "earum", "rerum", "hic", "tenetur", "a", "sapiente", "delectus", "ut", "aut", "reiciendis", "voluptatibus", "maiores", "doloribus", "asperiores", "repellat" ]; },{}],110:[function(require,module,exports){ module["exports"] = [ "Aaliyah", "Aaron", "Abagail", "Abbey", "Abbie", "Abbigail", "Abby", "Abdiel", "Abdul", "Abdullah", "Abe", "Abel", "Abelardo", "Abigail", "Abigale", "Abigayle", "Abner", "Abraham", "Ada", "Adah", "Adalberto", "Adaline", "Adam", "Adan", "Addie", "Addison", "Adela", "Adelbert", "Adele", "Adelia", "Adeline", "Adell", "Adella", "Adelle", "Aditya", "Adolf", "Adolfo", "Adolph", "Adolphus", "Adonis", "Adrain", "Adrian", "Adriana", "Adrianna", "Adriel", "Adrien", "Adrienne", "Afton", "Aglae", "Agnes", "Agustin", "Agustina", "Ahmad", "Ahmed", "Aida", "Aidan", "Aiden", "Aileen", "Aimee", "Aisha", "Aiyana", "Akeem", "Al", "Alaina", "Alan", "Alana", "Alanis", "Alanna", "Alayna", "Alba", "Albert", "Alberta", "Albertha", "Alberto", "Albin", "Albina", "Alda", "Alden", "Alec", "Aleen", "Alejandra", "Alejandrin", "Alek", "Alena", "Alene", "Alessandra", "Alessandro", "Alessia", "Aletha", "Alex", "Alexa", "Alexander", "Alexandra", "Alexandre", "Alexandrea", "Alexandria", "Alexandrine", "Alexandro", "Alexane", "Alexanne", "Alexie", "Alexis", "Alexys", "Alexzander", "Alf", "Alfonso", "Alfonzo", "Alford", "Alfred", "Alfreda", "Alfredo", "Ali", "Alia", "Alice", "Alicia", "Alisa", "Alisha", "Alison", "Alivia", "Aliya", "Aliyah", "Aliza", "Alize", "Allan", "Allen", "Allene", "Allie", "Allison", "Ally", "Alphonso", "Alta", "Althea", "Alva", "Alvah", "Alvena", "Alvera", "Alverta", "Alvina", "Alvis", "Alyce", "Alycia", "Alysa", "Alysha", "Alyson", "Alysson", "Amalia", "Amanda", "Amani", "Amara", "Amari", "Amaya", "Amber", "Ambrose", "Amelia", "Amelie", "Amely", "America", "Americo", "Amie", "Amina", "Amir", "Amira", "Amiya", "Amos", "Amparo", "Amy", "Amya", "Ana", "Anabel", "Anabelle", "Anahi", "Anais", "Anastacio", "Anastasia", "Anderson", "Andre", "Andreane", "Andreanne", "Andres", "Andrew", "Andy", "Angel", "Angela", "Angelica", "Angelina", "Angeline", "Angelita", "Angelo", "Angie", "Angus", "Anibal", "Anika", "Anissa", "Anita", "Aniya", "Aniyah", "Anjali", "Anna", "Annabel", "Annabell", "Annabelle", "Annalise", "Annamae", "Annamarie", "Anne", "Annetta", "Annette", "Annie", "Ansel", "Ansley", "Anthony", "Antoinette", "Antone", "Antonetta", "Antonette", "Antonia", "Antonietta", "Antonina", "Antonio", "Antwan", "Antwon", "Anya", "April", "Ara", "Araceli", "Aracely", "Arch", "Archibald", "Ardella", "Arden", "Ardith", "Arely", "Ari", "Ariane", "Arianna", "Aric", "Ariel", "Arielle", "Arjun", "Arlene", "Arlie", "Arlo", "Armand", "Armando", "Armani", "Arnaldo", "Arne", "Arno", "Arnold", "Arnoldo", "Arnulfo", "Aron", "Art", "Arthur", "Arturo", "Arvel", "Arvid", "Arvilla", "Aryanna", "Asa", "Asha", "Ashlee", "Ashleigh", "Ashley", "Ashly", "Ashlynn", "Ashton", "Ashtyn", "Asia", "Assunta", "Astrid", "Athena", "Aubree", "Aubrey", "Audie", "Audra", "Audreanne", "Audrey", "August", "Augusta", "Augustine", "Augustus", "Aurelia", "Aurelie", "Aurelio", "Aurore", "Austen", "Austin", "Austyn", "Autumn", "Ava", "Avery", "Avis", "Axel", "Ayana", "Ayden", "Ayla", "Aylin", "Baby", "Bailee", "Bailey", "Barbara", "Barney", "Baron", "Barrett", "Barry", "Bart", "Bartholome", "Barton", "Baylee", "Beatrice", "Beau", "Beaulah", "Bell", "Bella", "Belle", "Ben", "Benedict", "Benjamin", "Bennett", "Bennie", "Benny", "Benton", "Berenice", "Bernadette", "Bernadine", "Bernard", "Bernardo", "Berneice", "Bernhard", "Bernice", "Bernie", "Berniece", "Bernita", "Berry", "Bert", "Berta", "Bertha", "Bertram", "Bertrand", "Beryl", "Bessie", "Beth", "Bethany", "Bethel", "Betsy", "Bette", "Bettie", "Betty", "Bettye", "Beulah", "Beverly", "Bianka", "Bill", "Billie", "Billy", "Birdie", "Blair", "Blaise", "Blake", "Blanca", "Blanche", "Blaze", "Bo", "Bobbie", "Bobby", "Bonita", "Bonnie", "Boris", "Boyd", "Brad", "Braden", "Bradford", "Bradley", "Bradly", "Brady", "Braeden", "Brain", "Brandi", "Brando", "Brandon", "Brandt", "Brandy", "Brandyn", "Brannon", "Branson", "Brant", "Braulio", "Braxton", "Brayan", "Breana", "Breanna", "Breanne", "Brenda", "Brendan", "Brenden", "Brendon", "Brenna", "Brennan", "Brennon", "Brent", "Bret", "Brett", "Bria", "Brian", "Briana", "Brianne", "Brice", "Bridget", "Bridgette", "Bridie", "Brielle", "Brigitte", "Brionna", "Brisa", "Britney", "Brittany", "Brock", "Broderick", "Brody", "Brook", "Brooke", "Brooklyn", "Brooks", "Brown", "Bruce", "Bryana", "Bryce", "Brycen", "Bryon", "Buck", "Bud", "Buddy", "Buford", "Bulah", "Burdette", "Burley", "Burnice", "Buster", "Cade", "Caden", "Caesar", "Caitlyn", "Cale", "Caleb", "Caleigh", "Cali", "Calista", "Callie", "Camden", "Cameron", "Camila", "Camilla", "Camille", "Camren", "Camron", "Camryn", "Camylle", "Candace", "Candelario", "Candice", "Candida", "Candido", "Cara", "Carey", "Carissa", "Carlee", "Carleton", "Carley", "Carli", "Carlie", "Carlo", "Carlos", "Carlotta", "Carmel", "Carmela", "Carmella", "Carmelo", "Carmen", "Carmine", "Carol", "Carolanne", "Carole", "Carolina", "Caroline", "Carolyn", "Carolyne", "Carrie", "Carroll", "Carson", "Carter", "Cary", "Casandra", "Casey", "Casimer", "Casimir", "Casper", "Cassandra", "Cassandre", "Cassidy", "Cassie", "Catalina", "Caterina", "Catharine", "Catherine", "Cathrine", "Cathryn", "Cathy", "Cayla", "Ceasar", "Cecelia", "Cecil", "Cecile", "Cecilia", "Cedrick", "Celestine", "Celestino", "Celia", "Celine", "Cesar", "Chad", "Chadd", "Chadrick", "Chaim", "Chance", "Chandler", "Chanel", "Chanelle", "Charity", "Charlene", "Charles", "Charley", "Charlie", "Charlotte", "Chase", "Chasity", "Chauncey", "Chaya", "Chaz", "Chelsea", "Chelsey", "Chelsie", "Chesley", "Chester", "Chet", "Cheyanne", "Cheyenne", "Chloe", "Chris", "Christ", "Christa", "Christelle", "Christian", "Christiana", "Christina", "Christine", "Christop", "Christophe", "Christopher", "Christy", "Chyna", "Ciara", "Cicero", "Cielo", "Cierra", "Cindy", "Citlalli", "Clair", "Claire", "Clara", "Clarabelle", "Clare", "Clarissa", "Clark", "Claud", "Claude", "Claudia", "Claudie", "Claudine", "Clay", "Clemens", "Clement", "Clementina", "Clementine", "Clemmie", "Cleo", "Cleora", "Cleta", "Cletus", "Cleve", "Cleveland", "Clifford", "Clifton", "Clint", "Clinton", "Clotilde", "Clovis", "Cloyd", "Clyde", "Coby", "Cody", "Colby", "Cole", "Coleman", "Colin", "Colleen", "Collin", "Colt", "Colten", "Colton", "Columbus", "Concepcion", "Conner", "Connie", "Connor", "Conor", "Conrad", "Constance", "Constantin", "Consuelo", "Cooper", "Cora", "Coralie", "Corbin", "Cordelia", "Cordell", "Cordia", "Cordie", "Corene", "Corine", "Cornelius", "Cornell", "Corrine", "Cortez", "Cortney", "Cory", "Coty", "Courtney", "Coy", "Craig", "Crawford", "Creola", "Cristal", "Cristian", "Cristina", "Cristobal", "Cristopher", "Cruz", "Crystal", "Crystel", "Cullen", "Curt", "Curtis", "Cydney", "Cynthia", "Cyril", "Cyrus", "Dagmar", "Dahlia", "Daija", "Daisha", "Daisy", "Dakota", "Dale", "Dallas", "Dallin", "Dalton", "Damaris", "Dameon", "Damian", "Damien", "Damion", "Damon", "Dan", "Dana", "Dandre", "Dane", "D'angelo", "Dangelo", "Danial", "Daniela", "Daniella", "Danielle", "Danika", "Dannie", "Danny", "Dante", "Danyka", "Daphne", "Daphnee", "Daphney", "Darby", "Daren", "Darian", "Dariana", "Darien", "Dario", "Darion", "Darius", "Darlene", "Daron", "Darrel", "Darrell", "Darren", "Darrick", "Darrin", "Darrion", "Darron", "Darryl", "Darwin", "Daryl", "Dashawn", "Dasia", "Dave", "David", "Davin", "Davion", "Davon", "Davonte", "Dawn", "Dawson", "Dax", "Dayana", "Dayna", "Dayne", "Dayton", "Dean", "Deangelo", "Deanna", "Deborah", "Declan", "Dedric", "Dedrick", "Dee", "Deion", "Deja", "Dejah", "Dejon", "Dejuan", "Delaney", "Delbert", "Delfina", "Delia", "Delilah", "Dell", "Della", "Delmer", "Delores", "Delpha", "Delphia", "Delphine", "Delta", "Demarco", "Demarcus", "Demario", "Demetris", "Demetrius", "Demond", "Dena", "Denis", "Dennis", "Deon", "Deondre", "Deontae", "Deonte", "Dereck", "Derek", "Derick", "Deron", "Derrick", "Deshaun", "Deshawn", "Desiree", "Desmond", "Dessie", "Destany", "Destin", "Destinee", "Destiney", "Destini", "Destiny", "Devan", "Devante", "Deven", "Devin", "Devon", "Devonte", "Devyn", "Dewayne", "Dewitt", "Dexter", "Diamond", "Diana", "Dianna", "Diego", "Dillan", "Dillon", "Dimitri", "Dina", "Dino", "Dion", "Dixie", "Dock", "Dolly", "Dolores", "Domenic", "Domenica", "Domenick", "Domenico", "Domingo", "Dominic", "Dominique", "Don", "Donald", "Donato", "Donavon", "Donna", "Donnell", "Donnie", "Donny", "Dora", "Dorcas", "Dorian", "Doris", "Dorothea", "Dorothy", "Dorris", "Dortha", "Dorthy", "Doug", "Douglas", "Dovie", "Doyle", "Drake", "Drew", "Duane", "Dudley", "Dulce", "Duncan", "Durward", "Dustin", "Dusty", "Dwight", "Dylan", "Earl", "Earlene", "Earline", "Earnest", "Earnestine", "Easter", "Easton", "Ebba", "Ebony", "Ed", "Eda", "Edd", "Eddie", "Eden", "Edgar", "Edgardo", "Edison", "Edmond", "Edmund", "Edna", "Eduardo", "Edward", "Edwardo", "Edwin", "Edwina", "Edyth", "Edythe", "Effie", "Efrain", "Efren", "Eileen", "Einar", "Eino", "Eladio", "Elaina", "Elbert", "Elda", "Eldon", "Eldora", "Eldred", "Eldridge", "Eleanora", "Eleanore", "Eleazar", "Electa", "Elena", "Elenor", "Elenora", "Eleonore", "Elfrieda", "Eli", "Elian", "Eliane", "Elias", "Eliezer", "Elijah", "Elinor", "Elinore", "Elisa", "Elisabeth", "Elise", "Eliseo", "Elisha", "Elissa", "Eliza", "Elizabeth", "Ella", "Ellen", "Ellie", "Elliot", "Elliott", "Ellis", "Ellsworth", "Elmer", "Elmira", "Elmo", "Elmore", "Elna", "Elnora", "Elody", "Eloisa", "Eloise", "Elouise", "Eloy", "Elroy", "Elsa", "Else", "Elsie", "Elta", "Elton", "Elva", "Elvera", "Elvie", "Elvis", "Elwin", "Elwyn", "Elyse", "Elyssa", "Elza", "Emanuel", "Emelia", "Emelie", "Emely", "Emerald", "Emerson", "Emery", "Emie", "Emil", "Emile", "Emilia", "Emiliano", "Emilie", "Emilio", "Emily", "Emma", "Emmalee", "Emmanuel", "Emmanuelle", "Emmet", "Emmett", "Emmie", "Emmitt", "Emmy", "Emory", "Ena", "Enid", "Enoch", "Enola", "Enos", "Enrico", "Enrique", "Ephraim", "Era", "Eriberto", "Eric", "Erica", "Erich", "Erick", "Ericka", "Erik", "Erika", "Erin", "Erling", "Erna", "Ernest", "Ernestina", "Ernestine", "Ernesto", "Ernie", "Ervin", "Erwin", "Eryn", "Esmeralda", "Esperanza", "Esta", "Esteban", "Estefania", "Estel", "Estell", "Estella", "Estelle", "Estevan", "Esther", "Estrella", "Etha", "Ethan", "Ethel", "Ethelyn", "Ethyl", "Ettie", "Eudora", "Eugene", "Eugenia", "Eula", "Eulah", "Eulalia", "Euna", "Eunice", "Eusebio", "Eva", "Evalyn", "Evan", "Evangeline", "Evans", "Eve", "Eveline", "Evelyn", "Everardo", "Everett", "Everette", "Evert", "Evie", "Ewald", "Ewell", "Ezekiel", "Ezequiel", "Ezra", "Fabian", "Fabiola", "Fae", "Fannie", "Fanny", "Fatima", "Faustino", "Fausto", "Favian", "Fay", "Faye", "Federico", "Felicia", "Felicita", "Felicity", "Felipa", "Felipe", "Felix", "Felton", "Fermin", "Fern", "Fernando", "Ferne", "Fidel", "Filiberto", "Filomena", "Finn", "Fiona", "Flavie", "Flavio", "Fleta", "Fletcher", "Flo", "Florence", "Florencio", "Florian", "Florida", "Florine", "Flossie", "Floy", "Floyd", "Ford", "Forest", "Forrest", "Foster", "Frances", "Francesca", "Francesco", "Francis", "Francisca", "Francisco", "Franco", "Frank", "Frankie", "Franz", "Fred", "Freda", "Freddie", "Freddy", "Frederic", "Frederick", "Frederik", "Frederique", "Fredrick", "Fredy", "Freeda", "Freeman", "Freida", "Frida", "Frieda", "Friedrich", "Fritz", "Furman", "Gabe", "Gabriel", "Gabriella", "Gabrielle", "Gaetano", "Gage", "Gail", "Gardner", "Garett", "Garfield", "Garland", "Garnet", "Garnett", "Garret", "Garrett", "Garrick", "Garrison", "Garry", "Garth", "Gaston", "Gavin", "Gay", "Gayle", "Gaylord", "Gene", "General", "Genesis", "Genevieve", "Gennaro", "Genoveva", "Geo", "Geoffrey", "George", "Georgette", "Georgiana", "Georgianna", "Geovanni", "Geovanny", "Geovany", "Gerald", "Geraldine", "Gerard", "Gerardo", "Gerda", "Gerhard", "Germaine", "German", "Gerry", "Gerson", "Gertrude", "Gia", "Gianni", "Gideon", "Gilbert", "Gilberto", "Gilda", "Giles", "Gillian", "Gina", "Gino", "Giovani", "Giovanna", "Giovanni", "Giovanny", "Gisselle", "Giuseppe", "Gladyce", "Gladys", "Glen", "Glenda", "Glenna", "Glennie", "Gloria", "Godfrey", "Golda", "Golden", "Gonzalo", "Gordon", "Grace", "Gracie", "Graciela", "Grady", "Graham", "Grant", "Granville", "Grayce", "Grayson", "Green", "Greg", "Gregg", "Gregoria", "Gregorio", "Gregory", "Greta", "Gretchen", "Greyson", "Griffin", "Grover", "Guadalupe", "Gudrun", "Guido", "Guillermo", "Guiseppe", "Gunnar", "Gunner", "Gus", "Gussie", "Gust", "Gustave", "Guy", "Gwen", "Gwendolyn", "Hadley", "Hailee", "Hailey", "Hailie", "Hal", "Haleigh", "Haley", "Halie", "Halle", "Hallie", "Hank", "Hanna", "Hannah", "Hans", "Hardy", "Harley", "Harmon", "Harmony", "Harold", "Harrison", "Harry", "Harvey", "Haskell", "Hassan", "Hassie", "Hattie", "Haven", "Hayden", "Haylee", "Hayley", "Haylie", "Hazel", "Hazle", "Heath", "Heather", "Heaven", "Heber", "Hector", "Heidi", "Helen", "Helena", "Helene", "Helga", "Hellen", "Helmer", "Heloise", "Henderson", "Henri", "Henriette", "Henry", "Herbert", "Herman", "Hermann", "Hermina", "Herminia", "Herminio", "Hershel", "Herta", "Hertha", "Hester", "Hettie", "Hilario", "Hilbert", "Hilda", "Hildegard", "Hillard", "Hillary", "Hilma", "Hilton", "Hipolito", "Hiram", "Hobart", "Holden", "Hollie", "Hollis", "Holly", "Hope", "Horace", "Horacio", "Hortense", "Hosea", "Houston", "Howard", "Howell", "Hoyt", "Hubert", "Hudson", "Hugh", "Hulda", "Humberto", "Hunter", "Hyman", "Ian", "Ibrahim", "Icie", "Ida", "Idell", "Idella", "Ignacio", "Ignatius", "Ike", "Ila", "Ilene", "Iliana", "Ima", "Imani", "Imelda", "Immanuel", "Imogene", "Ines", "Irma", "Irving", "Irwin", "Isaac", "Isabel", "Isabell", "Isabella", "Isabelle", "Isac", "Isadore", "Isai", "Isaiah", "Isaias", "Isidro", "Ismael", "Isobel", "Isom", "Israel", "Issac", "Itzel", "Iva", "Ivah", "Ivory", "Ivy", "Izabella", "Izaiah", "Jabari", "Jace", "Jacey", "Jacinthe", "Jacinto", "Jack", "Jackeline", "Jackie", "Jacklyn", "Jackson", "Jacky", "Jaclyn", "Jacquelyn", "Jacques", "Jacynthe", "Jada", "Jade", "Jaden", "Jadon", "Jadyn", "Jaeden", "Jaida", "Jaiden", "Jailyn", "Jaime", "Jairo", "Jakayla", "Jake", "Jakob", "Jaleel", "Jalen", "Jalon", "Jalyn", "Jamaal", "Jamal", "Jamar", "Jamarcus", "Jamel", "Jameson", "Jamey", "Jamie", "Jamil", "Jamir", "Jamison", "Jammie", "Jan", "Jana", "Janae", "Jane", "Janelle", "Janessa", "Janet", "Janice", "Janick", "Janie", "Janis", "Janiya", "Jannie", "Jany", "Jaquan", "Jaquelin", "Jaqueline", "Jared", "Jaren", "Jarod", "Jaron", "Jarred", "Jarrell", "Jarret", "Jarrett", "Jarrod", "Jarvis", "Jasen", "Jasmin", "Jason", "Jasper", "Jaunita", "Javier", "Javon", "Javonte", "Jay", "Jayce", "Jaycee", "Jayda", "Jayde", "Jayden", "Jaydon", "Jaylan", "Jaylen", "Jaylin", "Jaylon", "Jayme", "Jayne", "Jayson", "Jazlyn", "Jazmin", "Jazmyn", "Jazmyne", "Jean", "Jeanette", "Jeanie", "Jeanne", "Jed", "Jedediah", "Jedidiah", "Jeff", "Jefferey", "Jeffery", "Jeffrey", "Jeffry", "Jena", "Jenifer", "Jennie", "Jennifer", "Jennings", "Jennyfer", "Jensen", "Jerad", "Jerald", "Jeramie", "Jeramy", "Jerel", "Jeremie", "Jeremy", "Jermain", "Jermaine", "Jermey", "Jerod", "Jerome", "Jeromy", "Jerrell", "Jerrod", "Jerrold", "Jerry", "Jess", "Jesse", "Jessica", "Jessie", "Jessika", "Jessy", "Jessyca", "Jesus", "Jett", "Jettie", "Jevon", "Jewel", "Jewell", "Jillian", "Jimmie", "Jimmy", "Jo", "Joan", "Joana", "Joanie", "Joanne", "Joannie", "Joanny", "Joany", "Joaquin", "Jocelyn", "Jodie", "Jody", "Joe", "Joel", "Joelle", "Joesph", "Joey", "Johan", "Johann", "Johanna", "Johathan", "John", "Johnathan", "Johnathon", "Johnnie", "Johnny", "Johnpaul", "Johnson", "Jolie", "Jon", "Jonas", "Jonatan", "Jonathan", "Jonathon", "Jordan", "Jordane", "Jordi", "Jordon", "Jordy", "Jordyn", "Jorge", "Jose", "Josefa", "Josefina", "Joseph", "Josephine", "Josh", "Joshua", "Joshuah", "Josiah", "Josiane", "Josianne", "Josie", "Josue", "Jovan", "Jovani", "Jovanny", "Jovany", "Joy", "Joyce", "Juana", "Juanita", "Judah", "Judd", "Jude", "Judge", "Judson", "Judy", "Jules", "Julia", "Julian", "Juliana", "Julianne", "Julie", "Julien", "Juliet", "Julio", "Julius", "June", "Junior", "Junius", "Justen", "Justice", "Justina", "Justine", "Juston", "Justus", "Justyn", "Juvenal", "Juwan", "Kacey", "Kaci", "Kacie", "Kade", "Kaden", "Kadin", "Kaela", "Kaelyn", "Kaia", "Kailee", "Kailey", "Kailyn", "Kaitlin", "Kaitlyn", "Kale", "Kaleb", "Kaleigh", "Kaley", "Kali", "Kallie", "Kameron", "Kamille", "Kamren", "Kamron", "Kamryn", "Kane", "Kara", "Kareem", "Karelle", "Karen", "Kari", "Kariane", "Karianne", "Karina", "Karine", "Karl", "Karlee", "Karley", "Karli", "Karlie", "Karolann", "Karson", "Kasandra", "Kasey", "Kassandra", "Katarina", "Katelin", "Katelyn", "Katelynn", "Katharina", "Katherine", "Katheryn", "Kathleen", "Kathlyn", "Kathryn", "Kathryne", "Katlyn", "Katlynn", "Katrina", "Katrine", "Kattie", "Kavon", "Kay", "Kaya", "Kaycee", "Kayden", "Kayla", "Kaylah", "Kaylee", "Kayleigh", "Kayley", "Kayli", "Kaylie", "Kaylin", "Keagan", "Keanu", "Keara", "Keaton", "Keegan", "Keeley", "Keely", "Keenan", "Keira", "Keith", "Kellen", "Kelley", "Kelli", "Kellie", "Kelly", "Kelsi", "Kelsie", "Kelton", "Kelvin", "Ken", "Kendall", "Kendra", "Kendrick", "Kenna", "Kennedi", "Kennedy", "Kenneth", "Kennith", "Kenny", "Kenton", "Kenya", "Kenyatta", "Kenyon", "Keon", "Keshaun", "Keshawn", "Keven", "Kevin", "Kevon", "Keyon", "Keyshawn", "Khalid", "Khalil", "Kian", "Kiana", "Kianna", "Kiara", "Kiarra", "Kiel", "Kiera", "Kieran", "Kiley", "Kim", "Kimberly", "King", "Kip", "Kira", "Kirk", "Kirsten", "Kirstin", "Kitty", "Kobe", "Koby", "Kody", "Kolby", "Kole", "Korbin", "Korey", "Kory", "Kraig", "Kris", "Krista", "Kristian", "Kristin", "Kristina", "Kristofer", "Kristoffer", "Kristopher", "Kristy", "Krystal", "Krystel", "Krystina", "Kurt", "Kurtis", "Kyla", "Kyle", "Kylee", "Kyleigh", "Kyler", "Kylie", "Kyra", "Lacey", "Lacy", "Ladarius", "Lafayette", "Laila", "Laisha", "Lamar", "Lambert", "Lamont", "Lance", "Landen", "Lane", "Laney", "Larissa", "Laron", "Larry", "Larue", "Laura", "Laurel", "Lauren", "Laurence", "Lauretta", "Lauriane", "Laurianne", "Laurie", "Laurine", "Laury", "Lauryn", "Lavada", "Lavern", "Laverna", "Laverne", "Lavina", "Lavinia", "Lavon", "Lavonne", "Lawrence", "Lawson", "Layla", "Layne", "Lazaro", "Lea", "Leann", "Leanna", "Leanne", "Leatha", "Leda", "Lee", "Leif", "Leila", "Leilani", "Lela", "Lelah", "Leland", "Lelia", "Lempi", "Lemuel", "Lenna", "Lennie", "Lenny", "Lenora", "Lenore", "Leo", "Leola", "Leon", "Leonard", "Leonardo", "Leone", "Leonel", "Leonie", "Leonor", "Leonora", "Leopold", "Leopoldo", "Leora", "Lera", "Lesley", "Leslie", "Lesly", "Lessie", "Lester", "Leta", "Letha", "Letitia", "Levi", "Lew", "Lewis", "Lexi", "Lexie", "Lexus", "Lia", "Liam", "Liana", "Libbie", "Libby", "Lila", "Lilian", "Liliana", "Liliane", "Lilla", "Lillian", "Lilliana", "Lillie", "Lilly", "Lily", "Lilyan", "Lina", "Lincoln", "Linda", "Lindsay", "Lindsey", "Linnea", "Linnie", "Linwood", "Lionel", "Lisa", "Lisandro", "Lisette", "Litzy", "Liza", "Lizeth", "Lizzie", "Llewellyn", "Lloyd", "Logan", "Lois", "Lola", "Lolita", "Loma", "Lon", "London", "Lonie", "Lonnie", "Lonny", "Lonzo", "Lora", "Loraine", "Loren", "Lorena", "Lorenz", "Lorenza", "Lorenzo", "Lori", "Lorine", "Lorna", "Lottie", "Lou", "Louie", "Louisa", "Lourdes", "Louvenia", "Lowell", "Loy", "Loyal", "Loyce", "Lucas", "Luciano", "Lucie", "Lucienne", "Lucile", "Lucinda", "Lucio", "Lucious", "Lucius", "Lucy", "Ludie", "Ludwig", "Lue", "Luella", "Luigi", "Luis", "Luisa", "Lukas", "Lula", "Lulu", "Luna", "Lupe", "Lura", "Lurline", "Luther", "Luz", "Lyda", "Lydia", "Lyla", "Lynn", "Lyric", "Lysanne", "Mabel", "Mabelle", "Mable", "Mac", "Macey", "Maci", "Macie", "Mack", "Mackenzie", "Macy", "Madaline", "Madalyn", "Maddison", "Madeline", "Madelyn", "Madelynn", "Madge", "Madie", "Madilyn", "Madisen", "Madison", "Madisyn", "Madonna", "Madyson", "Mae", "Maegan", "Maeve", "Mafalda", "Magali", "Magdalen", "Magdalena", "Maggie", "Magnolia", "Magnus", "Maia", "Maida", "Maiya", "Major", "Makayla", "Makenna", "Makenzie", "Malachi", "Malcolm", "Malika", "Malinda", "Mallie", "Mallory", "Malvina", "Mandy", "Manley", "Manuel", "Manuela", "Mara", "Marc", "Marcel", "Marcelina", "Marcelino", "Marcella", "Marcelle", "Marcellus", "Marcelo", "Marcia", "Marco", "Marcos", "Marcus", "Margaret", "Margarete", "Margarett", "Margaretta", "Margarette", "Margarita", "Marge", "Margie", "Margot", "Margret", "Marguerite", "Maria", "Mariah", "Mariam", "Marian", "Mariana", "Mariane", "Marianna", "Marianne", "Mariano", "Maribel", "Marie", "Mariela", "Marielle", "Marietta", "Marilie", "Marilou", "Marilyne", "Marina", "Mario", "Marion", "Marisa", "Marisol", "Maritza", "Marjolaine", "Marjorie", "Marjory", "Mark", "Markus", "Marlee", "Marlen", "Marlene", "Marley", "Marlin", "Marlon", "Marques", "Marquis", "Marquise", "Marshall", "Marta", "Martin", "Martina", "Martine", "Marty", "Marvin", "Mary", "Maryam", "Maryjane", "Maryse", "Mason", "Mateo", "Mathew", "Mathias", "Mathilde", "Matilda", "Matilde", "Matt", "Matteo", "Mattie", "Maud", "Maude", "Maudie", "Maureen", "Maurice", "Mauricio", "Maurine", "Maverick", "Mavis", "Max", "Maxie", "Maxime", "Maximilian", "Maximillia", "Maximillian", "Maximo", "Maximus", "Maxine", "Maxwell", "May", "Maya", "Maybell", "Maybelle", "Maye", "Maymie", "Maynard", "Mayra", "Mazie", "Mckayla", "Mckenna", "Mckenzie", "Meagan", "Meaghan", "Meda", "Megane", "Meggie", "Meghan", "Mekhi", "Melany", "Melba", "Melisa", "Melissa", "Mellie", "Melody", "Melvin", "Melvina", "Melyna", "Melyssa", "Mercedes", "Meredith", "Merl", "Merle", "Merlin", "Merritt", "Mertie", "Mervin", "Meta", "Mia", "Micaela", "Micah", "Michael", "Michaela", "Michale", "Micheal", "Michel", "Michele", "Michelle", "Miguel", "Mikayla", "Mike", "Mikel", "Milan", "Miles", "Milford", "Miller", "Millie", "Milo", "Milton", "Mina", "Minerva", "Minnie", "Miracle", "Mireille", "Mireya", "Misael", "Missouri", "Misty", "Mitchel", "Mitchell", "Mittie", "Modesta", "Modesto", "Mohamed", "Mohammad", "Mohammed", "Moises", "Mollie", "Molly", "Mona", "Monica", "Monique", "Monroe", "Monserrat", "Monserrate", "Montana", "Monte", "Monty", "Morgan", "Moriah", "Morris", "Mortimer", "Morton", "Mose", "Moses", "Moshe", "Mossie", "Mozell", "Mozelle", "Muhammad", "Muriel", "Murl", "Murphy", "Murray", "Mustafa", "Mya", "Myah", "Mylene", "Myles", "Myra", "Myriam", "Myrl", "Myrna", "Myron", "Myrtice", "Myrtie", "Myrtis", "Myrtle", "Nadia", "Nakia", "Name", "Nannie", "Naomi", "Naomie", "Napoleon", "Narciso", "Nash", "Nasir", "Nat", "Natalia", "Natalie", "Natasha", "Nathan", "Nathanael", "Nathanial", "Nathaniel", "Nathen", "Nayeli", "Neal", "Ned", "Nedra", "Neha", "Neil", "Nelda", "Nella", "Nelle", "Nellie", "Nels", "Nelson", "Neoma", "Nestor", "Nettie", "Neva", "Newell", "Newton", "Nia", "Nicholas", "Nicholaus", "Nichole", "Nick", "Nicklaus", "Nickolas", "Nico", "Nicola", "Nicolas", "Nicole", "Nicolette", "Nigel", "Nikita", "Nikki", "Nikko", "Niko", "Nikolas", "Nils", "Nina", "Noah", "Noble", "Noe", "Noel", "Noelia", "Noemi", "Noemie", "Noemy", "Nola", "Nolan", "Nona", "Nora", "Norbert", "Norberto", "Norene", "Norma", "Norris", "Norval", "Norwood", "Nova", "Novella", "Nya", "Nyah", "Nyasia", "Obie", "Oceane", "Ocie", "Octavia", "Oda", "Odell", "Odessa", "Odie", "Ofelia", "Okey", "Ola", "Olaf", "Ole", "Olen", "Oleta", "Olga", "Olin", "Oliver", "Ollie", "Oma", "Omari", "Omer", "Ona", "Onie", "Opal", "Ophelia", "Ora", "Oral", "Oran", "Oren", "Orie", "Orin", "Orion", "Orland", "Orlando", "Orlo", "Orpha", "Orrin", "Orval", "Orville", "Osbaldo", "Osborne", "Oscar", "Osvaldo", "Oswald", "Oswaldo", "Otha", "Otho", "Otilia", "Otis", "Ottilie", "Ottis", "Otto", "Ova", "Owen", "Ozella", "Pablo", "Paige", "Palma", "Pamela", "Pansy", "Paolo", "Paris", "Parker", "Pascale", "Pasquale", "Pat", "Patience", "Patricia", "Patrick", "Patsy", "Pattie", "Paul", "Paula", "Pauline", "Paxton", "Payton", "Pearl", "Pearlie", "Pearline", "Pedro", "Peggie", "Penelope", "Percival", "Percy", "Perry", "Pete", "Peter", "Petra", "Peyton", "Philip", "Phoebe", "Phyllis", "Pierce", "Pierre", "Pietro", "Pink", "Pinkie", "Piper", "Polly", "Porter", "Precious", "Presley", "Preston", "Price", "Prince", "Princess", "Priscilla", "Providenci", "Prudence", "Queen", "Queenie", "Quentin", "Quincy", "Quinn", "Quinten", "Quinton", "Rachael", "Rachel", "Rachelle", "Rae", "Raegan", "Rafael", "Rafaela", "Raheem", "Rahsaan", "Rahul", "Raina", "Raleigh", "Ralph", "Ramiro", "Ramon", "Ramona", "Randal", "Randall", "Randi", "Randy", "Ransom", "Raoul", "Raphael", "Raphaelle", "Raquel", "Rashad", "Rashawn", "Rasheed", "Raul", "Raven", "Ray", "Raymond", "Raymundo", "Reagan", "Reanna", "Reba", "Rebeca", "Rebecca", "Rebeka", "Rebekah", "Reece", "Reed", "Reese", "Regan", "Reggie", "Reginald", "Reid", "Reilly", "Reina", "Reinhold", "Remington", "Rene", "Renee", "Ressie", "Reta", "Retha", "Retta", "Reuben", "Reva", "Rex", "Rey", "Reyes", "Reymundo", "Reyna", "Reynold", "Rhea", "Rhett", "Rhianna", "Rhiannon", "Rhoda", "Ricardo", "Richard", "Richie", "Richmond", "Rick", "Rickey", "Rickie", "Ricky", "Rico", "Rigoberto", "Riley", "Rita", "River", "Robb", "Robbie", "Robert", "Roberta", "Roberto", "Robin", "Robyn", "Rocio", "Rocky", "Rod", "Roderick", "Rodger", "Rodolfo", "Rodrick", "Rodrigo", "Roel", "Rogelio", "Roger", "Rogers", "Rolando", "Rollin", "Roma", "Romaine", "Roman", "Ron", "Ronaldo", "Ronny", "Roosevelt", "Rory", "Rosa", "Rosalee", "Rosalia", "Rosalind", "Rosalinda", "Rosalyn", "Rosamond", "Rosanna", "Rosario", "Roscoe", "Rose", "Rosella", "Roselyn", "Rosemarie", "Rosemary", "Rosendo", "Rosetta", "Rosie", "Rosina", "Roslyn", "Ross", "Rossie", "Rowan", "Rowena", "Rowland", "Roxane", "Roxanne", "Roy", "Royal", "Royce", "Rozella", "Ruben", "Rubie", "Ruby", "Rubye", "Rudolph", "Rudy", "Rupert", "Russ", "Russel", "Russell", "Rusty", "Ruth", "Ruthe", "Ruthie", "Ryan", "Ryann", "Ryder", "Rylan", "Rylee", "Ryleigh", "Ryley", "Sabina", "Sabrina", "Sabryna", "Sadie", "Sadye", "Sage", "Saige", "Sallie", "Sally", "Salma", "Salvador", "Salvatore", "Sam", "Samanta", "Samantha", "Samara", "Samir", "Sammie", "Sammy", "Samson", "Sandra", "Sandrine", "Sandy", "Sanford", "Santa", "Santiago", "Santina", "Santino", "Santos", "Sarah", "Sarai", "Sarina", "Sasha", "Saul", "Savanah", "Savanna", "Savannah", "Savion", "Scarlett", "Schuyler", "Scot", "Scottie", "Scotty", "Seamus", "Sean", "Sebastian", "Sedrick", "Selena", "Selina", "Selmer", "Serena", "Serenity", "Seth", "Shad", "Shaina", "Shakira", "Shana", "Shane", "Shanel", "Shanelle", "Shania", "Shanie", "Shaniya", "Shanna", "Shannon", "Shanny", "Shanon", "Shany", "Sharon", "Shaun", "Shawn", "Shawna", "Shaylee", "Shayna", "Shayne", "Shea", "Sheila", "Sheldon", "Shemar", "Sheridan", "Sherman", "Sherwood", "Shirley", "Shyann", "Shyanne", "Sibyl", "Sid", "Sidney", "Sienna", "Sierra", "Sigmund", "Sigrid", "Sigurd", "Silas", "Sim", "Simeon", "Simone", "Sincere", "Sister", "Skye", "Skyla", "Skylar", "Sofia", "Soledad", "Solon", "Sonia", "Sonny", "Sonya", "Sophia", "Sophie", "Spencer", "Stacey", "Stacy", "Stan", "Stanford", "Stanley", "Stanton", "Stefan", "Stefanie", "Stella", "Stephan", "Stephania", "Stephanie", "Stephany", "Stephen", "Stephon", "Sterling", "Steve", "Stevie", "Stewart", "Stone", "Stuart", "Summer", "Sunny", "Susan", "Susana", "Susanna", "Susie", "Suzanne", "Sven", "Syble", "Sydnee", "Sydney", "Sydni", "Sydnie", "Sylvan", "Sylvester", "Sylvia", "Tabitha", "Tad", "Talia", "Talon", "Tamara", "Tamia", "Tania", "Tanner", "Tanya", "Tara", "Taryn", "Tate", "Tatum", "Tatyana", "Taurean", "Tavares", "Taya", "Taylor", "Teagan", "Ted", "Telly", "Terence", "Teresa", "Terrance", "Terrell", "Terrence", "Terrill", "Terry", "Tess", "Tessie", "Tevin", "Thad", "Thaddeus", "Thalia", "Thea", "Thelma", "Theo", "Theodora", "Theodore", "Theresa", "Therese", "Theresia", "Theron", "Thomas", "Thora", "Thurman", "Tia", "Tiana", "Tianna", "Tiara", "Tierra", "Tiffany", "Tillman", "Timmothy", "Timmy", "Timothy", "Tina", "Tito", "Titus", "Tobin", "Toby", "Tod", "Tom", "Tomas", "Tomasa", "Tommie", "Toney", "Toni", "Tony", "Torey", "Torrance", "Torrey", "Toy", "Trace", "Tracey", "Tracy", "Travis", "Travon", "Tre", "Tremaine", "Tremayne", "Trent", "Trenton", "Tressa", "Tressie", "Treva", "Trever", "Trevion", "Trevor", "Trey", "Trinity", "Trisha", "Tristian", "Tristin", "Triston", "Troy", "Trudie", "Trycia", "Trystan", "Turner", "Twila", "Tyler", "Tyra", "Tyree", "Tyreek", "Tyrel", "Tyrell", "Tyrese", "Tyrique", "Tyshawn", "Tyson", "Ubaldo", "Ulices", "Ulises", "Una", "Unique", "Urban", "Uriah", "Uriel", "Ursula", "Vada", "Valentin", "Valentina", "Valentine", "Valerie", "Vallie", "Van", "Vance", "Vanessa", "Vaughn", "Veda", "Velda", "Vella", "Velma", "Velva", "Vena", "Verda", "Verdie", "Vergie", "Verla", "Verlie", "Vern", "Verna", "Verner", "Vernice", "Vernie", "Vernon", "Verona", "Veronica", "Vesta", "Vicenta", "Vicente", "Vickie", "Vicky", "Victor", "Victoria", "Vida", "Vidal", "Vilma", "Vince", "Vincent", "Vincenza", "Vincenzo", "Vinnie", "Viola", "Violet", "Violette", "Virgie", "Virgil", "Virginia", "Virginie", "Vita", "Vito", "Viva", "Vivian", "Viviane", "Vivianne", "Vivien", "Vivienne", "Vladimir", "Wade", "Waino", "Waldo", "Walker", "Wallace", "Walter", "Walton", "Wanda", "Ward", "Warren", "Watson", "Wava", "Waylon", "Wayne", "Webster", "Weldon", "Wellington", "Wendell", "Wendy", "Werner", "Westley", "Weston", "Whitney", "Wilber", "Wilbert", "Wilburn", "Wiley", "Wilford", "Wilfred", "Wilfredo", "Wilfrid", "Wilhelm", "Wilhelmine", "Will", "Willa", "Willard", "William", "Willie", "Willis", "Willow", "Willy", "Wilma", "Wilmer", "Wilson", "Wilton", "Winfield", "Winifred", "Winnifred", "Winona", "Winston", "Woodrow", "Wyatt", "Wyman", "Xander", "Xavier", "Xzavier", "Yadira", "Yasmeen", "Yasmin", "Yasmine", "Yazmin", "Yesenia", "Yessenia", "Yolanda", "Yoshiko", "Yvette", "Yvonne", "Zachariah", "Zachary", "Zachery", "Zack", "Zackary", "Zackery", "Zakary", "Zander", "Zane", "Zaria", "Zechariah", "Zelda", "Zella", "Zelma", "Zena", "Zetta", "Zion", "Zita", "Zoe", "Zoey", "Zoie", "Zoila", "Zola", "Zora", "Zula" ]; },{}],111:[function(require,module,exports){ var name = {}; module['exports'] = name; name.first_name = require("./first_name"); name.last_name = require("./last_name"); name.prefix = require("./prefix"); name.suffix = require("./suffix"); name.title = require("./title"); name.name = require("./name"); },{"./first_name":110,"./last_name":112,"./name":113,"./prefix":114,"./suffix":115,"./title":116}],112:[function(require,module,exports){ module["exports"] = [ "Abbott", "Abernathy", "Abshire", "Adams", "Altenwerth", "Anderson", "Ankunding", "Armstrong", "Auer", "Aufderhar", "Bahringer", "Bailey", "Balistreri", "Barrows", "Bartell", "Bartoletti", "Barton", "Bashirian", "Batz", "Bauch", "Baumbach", "Bayer", "Beahan", "Beatty", "Bechtelar", "Becker", "Bednar", "Beer", "Beier", "Berge", "Bergnaum", "Bergstrom", "Bernhard", "Bernier", "Bins", "Blanda", "Blick", "Block", "Bode", "Boehm", "Bogan", "Bogisich", "Borer", "Bosco", "Botsford", "Boyer", "Boyle", "Bradtke", "Brakus", "Braun", "Breitenberg", "Brekke", "Brown", "Bruen", "Buckridge", "Carroll", "Carter", "Cartwright", "Casper", "Cassin", "Champlin", "Christiansen", "Cole", "Collier", "Collins", "Conn", "Connelly", "Conroy", "Considine", "Corkery", "Cormier", "Corwin", "Cremin", "Crist", "Crona", "Cronin", "Crooks", "Cruickshank", "Cummerata", "Cummings", "Dach", "D'Amore", "Daniel", "Dare", "Daugherty", "Davis", "Deckow", "Denesik", "Dibbert", "Dickens", "Dicki", "Dickinson", "Dietrich", "Donnelly", "Dooley", "Douglas", "Doyle", "DuBuque", "Durgan", "Ebert", "Effertz", "Eichmann", "Emard", "Emmerich", "Erdman", "Ernser", "Fadel", "Fahey", "Farrell", "Fay", "Feeney", "Feest", "Feil", "Ferry", "Fisher", "Flatley", "Frami", "Franecki", "Friesen", "Fritsch", "Funk", "Gaylord", "Gerhold", "Gerlach", "Gibson", "Gislason", "Gleason", "Gleichner", "Glover", "Goldner", "Goodwin", "Gorczany", "Gottlieb", "Goyette", "Grady", "Graham", "Grant", "Green", "Greenfelder", "Greenholt", "Grimes", "Gulgowski", "Gusikowski", "Gutkowski", "Gutmann", "Haag", "Hackett", "Hagenes", "Hahn", "Haley", "Halvorson", "Hamill", "Hammes", "Hand", "Hane", "Hansen", "Harber", "Harris", "Hartmann", "Harvey", "Hauck", "Hayes", "Heaney", "Heathcote", "Hegmann", "Heidenreich", "Heller", "Herman", "Hermann", "Hermiston", "Herzog", "Hessel", "Hettinger", "Hickle", "Hilll", "Hills", "Hilpert", "Hintz", "Hirthe", "Hodkiewicz", "Hoeger", "Homenick", "Hoppe", "Howe", "Howell", "Hudson", "Huel", "Huels", "Hyatt", "Jacobi", "Jacobs", "Jacobson", "Jakubowski", "Jaskolski", "Jast", "Jenkins", "Jerde", "Johns", "Johnson", "Johnston", "Jones", "Kassulke", "Kautzer", "Keebler", "Keeling", "Kemmer", "Kerluke", "Kertzmann", "Kessler", "Kiehn", "Kihn", "Kilback", "King", "Kirlin", "Klein", "Kling", "Klocko", "Koch", "Koelpin", "Koepp", "Kohler", "Konopelski", "Koss", "Kovacek", "Kozey", "Krajcik", "Kreiger", "Kris", "Kshlerin", "Kub", "Kuhic", "Kuhlman", "Kuhn", "Kulas", "Kunde", "Kunze", "Kuphal", "Kutch", "Kuvalis", "Labadie", "Lakin", "Lang", "Langosh", "Langworth", "Larkin", "Larson", "Leannon", "Lebsack", "Ledner", "Leffler", "Legros", "Lehner", "Lemke", "Lesch", "Leuschke", "Lind", "Lindgren", "Littel", "Little", "Lockman", "Lowe", "Lubowitz", "Lueilwitz", "Luettgen", "Lynch", "Macejkovic", "MacGyver", "Maggio", "Mann", "Mante", "Marks", "Marquardt", "Marvin", "Mayer", "Mayert", "McClure", "McCullough", "McDermott", "McGlynn", "McKenzie", "McLaughlin", "Medhurst", "Mertz", "Metz", "Miller", "Mills", "Mitchell", "Moen", "Mohr", "Monahan", "Moore", "Morar", "Morissette", "Mosciski", "Mraz", "Mueller", "Muller", "Murazik", "Murphy", "Murray", "Nader", "Nicolas", "Nienow", "Nikolaus", "Nitzsche", "Nolan", "Oberbrunner", "O'Connell", "O'Conner", "O'Hara", "O'Keefe", "O'Kon", "Okuneva", "Olson", "Ondricka", "O'Reilly", "Orn", "Ortiz", "Osinski", "Pacocha", "Padberg", "Pagac", "Parisian", "Parker", "Paucek", "Pfannerstill", "Pfeffer", "Pollich", "Pouros", "Powlowski", "Predovic", "Price", "Prohaska", "Prosacco", "Purdy", "Quigley", "Quitzon", "Rath", "Ratke", "Rau", "Raynor", "Reichel", "Reichert", "Reilly", "Reinger", "Rempel", "Renner", "Reynolds", "Rice", "Rippin", "Ritchie", "Robel", "Roberts", "Rodriguez", "Rogahn", "Rohan", "Rolfson", "Romaguera", "Roob", "Rosenbaum", "Rowe", "Ruecker", "Runolfsdottir", "Runolfsson", "Runte", "Russel", "Rutherford", "Ryan", "Sanford", "Satterfield", "Sauer", "Sawayn", "Schaden", "Schaefer", "Schamberger", "Schiller", "Schimmel", "Schinner", "Schmeler", "Schmidt", "Schmitt", "Schneider", "Schoen", "Schowalter", "Schroeder", "Schulist", "Schultz", "Schumm", "Schuppe", "Schuster", "Senger", "Shanahan", "Shields", "Simonis", "Sipes", "Skiles", "Smith", "Smitham", "Spencer", "Spinka", "Sporer", "Stamm", "Stanton", "Stark", "Stehr", "Steuber", "Stiedemann", "Stokes", "Stoltenberg", "Stracke", "Streich", "Stroman", "Strosin", "Swaniawski", "Swift", "Terry", "Thiel", "Thompson", "Tillman", "Torp", "Torphy", "Towne", "Toy", "Trantow", "Tremblay", "Treutel", "Tromp", "Turcotte", "Turner", "Ullrich", "Upton", "Vandervort", "Veum", "Volkman", "Von", "VonRueden", "Waelchi", "Walker", "Walsh", "Walter", "Ward", "Waters", "Watsica", "Weber", "Wehner", "Weimann", "Weissnat", "Welch", "West", "White", "Wiegand", "Wilderman", "Wilkinson", "Will", "Williamson", "Willms", "Windler", "Wintheiser", "Wisoky", "Wisozk", "Witting", "Wiza", "Wolf", "Wolff", "Wuckert", "Wunsch", "Wyman", "Yost", "Yundt", "Zboncak", "Zemlak", "Ziemann", "Zieme", "Zulauf" ]; },{}],113:[function(require,module,exports){ module["exports"] = [ "#{prefix} #{first_name} #{last_name}", "#{first_name} #{last_name} #{suffix}", "#{first_name} #{last_name}", "#{first_name} #{last_name}", "#{first_name} #{last_name}", "#{first_name} #{last_name}" ]; },{}],114:[function(require,module,exports){ module["exports"] = [ "Mr.", "Mrs.", "Ms.", "Miss", "Dr." ]; },{}],115:[function(require,module,exports){ module["exports"] = [ "Jr.", "Sr.", "I", "II", "III", "IV", "V", "MD", "DDS", "PhD", "DVM" ]; },{}],116:[function(require,module,exports){ module["exports"] = { "descriptor": [ "Lead", "Senior", "Direct", "Corporate", "Dynamic", "Future", "Product", "National", "Regional", "District", "Central", "Global", "Customer", "Investor", "Dynamic", "International", "Legacy", "Forward", "Internal", "Human", "Chief", "Principal" ], "level": [ "Solutions", "Program", "Brand", "Security", "Research", "Marketing", "Directives", "Implementation", "Integration", "Functionality", "Response", "Paradigm", "Tactics", "Identity", "Markets", "Group", "Division", "Applications", "Optimization", "Operations", "Infrastructure", "Intranet", "Communications", "Web", "Branding", "Quality", "Assurance", "Mobility", "Accounts", "Data", "Creative", "Configuration", "Accountability", "Interactions", "Factors", "Usability", "Metrics" ], "job": [ "Supervisor", "Associate", "Executive", "Liason", "Officer", "Manager", "Engineer", "Specialist", "Director", "Coordinator", "Administrator", "Architect", "Analyst", "Designer", "Planner", "Orchestrator", "Technician", "Developer", "Producer", "Consultant", "Assistant", "Facilitator", "Agent", "Representative", "Strategist" ] }; },{}],117:[function(require,module,exports){ module["exports"] = [ "###-###-####", "(###) ###-####", "1-###-###-####", "###.###.####", "###-###-####", "(###) ###-####", "1-###-###-####", "###.###.####", "###-###-#### x###", "(###) ###-#### x###", "1-###-###-#### x###", "###.###.#### x###", "###-###-#### x####", "(###) ###-#### x####", "1-###-###-#### x####", "###.###.#### x####", "###-###-#### x#####", "(###) ###-#### x#####", "1-###-###-#### x#####", "###.###.#### x#####" ]; },{}],118:[function(require,module,exports){ var phone_number = {}; module['exports'] = phone_number; phone_number.formats = require("./formats"); },{"./formats":117}],119:[function(require,module,exports){ module["exports"] = [ "ants", "bats", "bears", "bees", "birds", "buffalo", "cats", "chickens", "cattle", "dogs", "dolphins", "ducks", "elephants", "fishes", "foxes", "frogs", "geese", "goats", "horses", "kangaroos", "lions", "monkeys", "owls", "oxen", "penguins", "people", "pigs", "rabbits", "sheep", "tigers", "whales", "wolves", "zebras", "banshees", "crows", "black cats", "chimeras", "ghosts", "conspirators", "dragons", "dwarves", "elves", "enchanters", "exorcists", "sons", "foes", "giants", "gnomes", "goblins", "gooses", "griffins", "lycanthropes", "nemesis", "ogres", "oracles", "prophets", "sorcerors", "spiders", "spirits", "vampires", "warlocks", "vixens", "werewolves", "witches", "worshipers", "zombies", "druids" ]; },{}],120:[function(require,module,exports){ var team = {}; module['exports'] = team; team.creature = require("./creature"); team.name = require("./name"); },{"./creature":119,"./name":121}],121:[function(require,module,exports){ module["exports"] = [ "#{Address.state} #{creature}" ]; },{}],122:[function(require,module,exports){ module["exports"] = [ "Bhaktapur", "Biratnagar", "Birendranagar", "Birgunj", "Butwal", "Damak", "Dharan", "Gaur", "Gorkha", "Hetauda", "Itahari", "Janakpur", "Kathmandu", "Lahan", "Nepalgunj", "Pokhara" ]; },{}],123:[function(require,module,exports){ module["exports"] = [ "Nepal" ]; },{}],124:[function(require,module,exports){ var address = {}; module['exports'] = address; address.postcode = require("./postcode"); address.state = require("./state"); address.city = require("./city"); address.default_country = require("./default_country"); },{"./city":122,"./default_country":123,"./postcode":125,"./state":126}],125:[function(require,module,exports){ module["exports"] = [ 0 ]; },{}],126:[function(require,module,exports){ module["exports"] = [ "Baglung", "Banke", "Bara", "Bardiya", "Bhaktapur", "Bhojupu", "Chitwan", "Dailekh", "Dang", "Dhading", "Dhankuta", "Dhanusa", "Dolakha", "Dolpha", "Gorkha", "Gulmi", "Humla", "Ilam", "Jajarkot", "Jhapa", "Jumla", "Kabhrepalanchok", "Kalikot", "Kapilvastu", "Kaski", "Kathmandu", "Lalitpur", "Lamjung", "Manang", "Mohottari", "Morang", "Mugu", "Mustang", "Myagdi", "Nawalparasi", "Nuwakot", "Palpa", "Parbat", "Parsa", "Ramechhap", "Rauswa", "Rautahat", "Rolpa", "Rupandehi", "Sankhuwasabha", "Sarlahi", "Sindhuli", "Sindhupalchok", "Sunsari", "Surket", "Syangja", "Tanahu", "Terhathum" ]; },{}],127:[function(require,module,exports){ var company = {}; module['exports'] = company; company.suffix = require("./suffix"); },{"./suffix":128}],128:[function(require,module,exports){ module["exports"] = [ "Pvt Ltd", "Group", "Ltd", "Limited" ]; },{}],129:[function(require,module,exports){ var nep = {}; module['exports'] = nep; nep.title = "Nepalese"; nep.name = require("./name"); nep.address = require("./address"); nep.internet = require("./internet"); nep.company = require("./company"); nep.phone_number = require("./phone_number"); },{"./address":124,"./company":127,"./internet":132,"./name":134,"./phone_number":137}],130:[function(require,module,exports){ module["exports"] = [ "np", "com", "info", "net", "org" ]; },{}],131:[function(require,module,exports){ module["exports"] = [ "worldlink.com.np", "gmail.com", "yahoo.com", "hotmail.com" ]; },{}],132:[function(require,module,exports){ var internet = {}; module['exports'] = internet; internet.free_email = require("./free_email"); internet.domain_suffix = require("./domain_suffix"); },{"./domain_suffix":130,"./free_email":131}],133:[function(require,module,exports){ module["exports"] = [ "Aarav", "Ajita", "Amit", "Amita", "Amrit", "Arijit", "Ashmi", "Asmita", "Bibek", "Bijay", "Bikash", "Bina", "Bishal", "Bishnu", "Buddha", "Deepika", "Dipendra", "Gagan", "Ganesh", "Khem", "Krishna", "Laxmi", "Manisha", "Nabin", "Nikita", "Niraj", "Nischal", "Padam", "Pooja", "Prabin", "Prakash", "Prashant", "Prem", "Purna", "Rajendra", "Rajina", "Raju", "Rakesh", "Ranjan", "Ratna", "Sagar", "Sandeep", "Sanjay", "Santosh", "Sarita", "Shilpa", "Shirisha", "Shristi", "Siddhartha", "Subash", "Sumeet", "Sunita", "Suraj", "Susan", "Sushant" ]; },{}],134:[function(require,module,exports){ var name = {}; module['exports'] = name; name.first_name = require("./first_name"); name.last_name = require("./last_name"); },{"./first_name":133,"./last_name":135}],135:[function(require,module,exports){ module["exports"] = [ "Adhikari", "Aryal", "Baral", "Basnet", "Bastola", "Basynat", "Bhandari", "Bhattarai", "Chettri", "Devkota", "Dhakal", "Dongol", "Ghale", "Gurung", "Gyawali", "Hamal", "Jung", "KC", "Kafle", "Karki", "Khadka", "Koirala", "Lama", "Limbu", "Magar", "Maharjan", "Niroula", "Pandey", "Pradhan", "Rana", "Raut", "Sai", "Shai", "Shakya", "Sherpa", "Shrestha", "Subedi", "Tamang", "Thapa" ]; },{}],136:[function(require,module,exports){ module["exports"] = [ "##-#######", "+977-#-#######", "+977########" ]; },{}],137:[function(require,module,exports){ arguments[4][118][0].apply(exports,arguments) },{"./formats":136,"dup":118}],138:[function(require,module,exports){ var Lorem = function (faker) { var self = this; var Helpers = faker.helpers; self.words = function (num) { if (typeof num == 'undefined') { num = 3; } return Helpers.shuffle(faker.definitions.lorem.words).slice(0, num); }; self.sentence = function (wordCount, range) { if (typeof wordCount == 'undefined') { wordCount = 3; } if (typeof range == 'undefined') { range = 7; } // strange issue with the node_min_test failing for captialize, please fix and add faker.lorem.back //return faker.lorem.words(wordCount + Helpers.randomNumber(range)).join(' ').capitalize(); var sentence = faker.lorem.words(wordCount + faker.random.number(range)).join(' '); return sentence.charAt(0).toUpperCase() + sentence.slice(1) + '.'; }; self.sentences = function (sentenceCount) { if (typeof sentenceCount == 'undefined') { sentenceCount = 3; } var sentences = []; for (sentenceCount; sentenceCount > 0; sentenceCount--) { sentences.push(faker.lorem.sentence()); } return sentences.join("\n"); }; self.paragraph = function (sentenceCount) { if (typeof sentenceCount == 'undefined') { sentenceCount = 3; } return faker.lorem.sentences(sentenceCount + faker.random.number(3)); }; self.paragraphs = function (paragraphCount, separator) { if (typeof separator === "undefined") { separator = "\n \r"; } if (typeof paragraphCount == 'undefined') { paragraphCount = 3; } var paragraphs = []; for (paragraphCount; paragraphCount > 0; paragraphCount--) { paragraphs.push(faker.lorem.paragraph()); } return paragraphs.join(separator); } return self; }; module["exports"] = Lorem; },{}],139:[function(require,module,exports){ function Name (faker) { this.firstName = function (gender) { if (typeof faker.definitions.name.male_first_name !== "undefined" && typeof faker.definitions.name.female_first_name !== "undefined") { // some locale datasets ( like ru ) have first_name split by gender. since the name.first_name field does not exist in these datasets, // we must randomly pick a name from either gender array so faker.name.firstName will return the correct locale data ( and not fallback ) if (typeof gender !== 'number') { gender = faker.random.number(1); } if (gender === 0) { return faker.random.arrayElement(faker.locales[faker.locale].name.male_first_name) } else { return faker.random.arrayElement(faker.locales[faker.locale].name.female_first_name); } } return faker.random.arrayElement(faker.definitions.name.first_name); }; this.lastName = function (gender) { if (typeof faker.definitions.name.male_last_name !== "undefined" && typeof faker.definitions.name.female_last_name !== "undefined") { // some locale datasets ( like ru ) have last_name split by gender. i have no idea how last names can have genders, but also i do not speak russian // see above comment of firstName method if (typeof gender !== 'number') { gender = faker.random.number(1); } if (gender === 0) { return faker.random.arrayElement(faker.locales[faker.locale].name.male_last_name); } else { return faker.random.arrayElement(faker.locales[faker.locale].name.female_last_name); } } return faker.random.arrayElement(faker.definitions.name.last_name); }; this.findName = function (firstName, lastName, gender) { var r = faker.random.number(8); var prefix, suffix; // in particular locales first and last names split by gender, // thus we keep consistency by passing 0 as male and 1 as female if (typeof gender !== 'number') { gender = faker.random.number(1); } firstName = firstName || faker.name.firstName(gender); lastName = lastName || faker.name.lastName(gender); switch (r) { case 0: prefix = faker.name.prefix(); if (prefix) { return prefix + " " + firstName + " " + lastName; } case 1: suffix = faker.name.prefix(); if (suffix) { return firstName + " " + lastName + " " + suffix; } } return firstName + " " + lastName; }; this.jobTitle = function () { return faker.name.jobDescriptor() + " " + faker.name.jobArea() + " " + faker.name.jobType(); }; this.prefix = function () { return faker.random.arrayElement(faker.definitions.name.prefix); }; this.suffix = function () { return faker.random.arrayElement(faker.definitions.name.suffix); }; this.title = function() { var descriptor = faker.random.arrayElement(faker.definitions.name.title.descriptor), level = faker.random.arrayElement(faker.definitions.name.title.level), job = faker.random.arrayElement(faker.definitions.name.title.job); return descriptor + " " + level + " " + job; }; this.jobDescriptor = function () { return faker.random.arrayElement(faker.definitions.name.title.descriptor); }; this.jobArea = function () { return faker.random.arrayElement(faker.definitions.name.title.level); }; this.jobType = function () { return faker.random.arrayElement(faker.definitions.name.title.job); }; } module['exports'] = Name; },{}],140:[function(require,module,exports){ var Phone = function (faker) { var self = this; self.phoneNumber = function (format) { format = format || faker.phone.phoneFormats(); return faker.helpers.replaceSymbolWithNumber(format); }; // FIXME: this is strange passing in an array index. self.phoneNumberFormat = function (phoneFormatsArrayIndex) { phoneFormatsArrayIndex = phoneFormatsArrayIndex || 0; return faker.helpers.replaceSymbolWithNumber(faker.definitions.phone_number.formats[phoneFormatsArrayIndex]); }; self.phoneFormats = function () { return faker.random.arrayElement(faker.definitions.phone_number.formats); }; return self; }; module['exports'] = Phone; },{}],141:[function(require,module,exports){ var mersenne = require('../vendor/mersenne'); function Random (faker, seed) { // Use a user provided seed if it exists if (seed) { if (Array.isArray(seed) && seed.length) { mersenne.seed_array(seed); } else { mersenne.seed(seed); } } // returns a single random number based on a max number or range this.number = function (options) { if (typeof options === "number") { options = { max: options }; } options = options || {}; if (typeof options.min === "undefined") { options.min = 0; } if (typeof options.max === "undefined") { options.max = 99999; } if (typeof options.precision === "undefined") { options.precision = 1; } // Make the range inclusive of the max value var max = options.max; if (max >= 0) { max += options.precision; } var randomNumber = options.precision * Math.floor( mersenne.rand(max / options.precision, options.min / options.precision)); return randomNumber; } // takes an array and returns a random element of the array this.arrayElement = function (array) { array = array || ["a", "b", "c"]; var r = faker.random.number({ max: array.length - 1 }); return array[r]; } // takes an object and returns the randomly key or value this.objectElement = function (object, field) { object = object || { "foo": "bar", "too": "car" }; var array = Object.keys(object); var key = faker.random.arrayElement(array); return field === "key" ? key : object[key]; } this.uuid = function () { var RFC4122_TEMPLATE = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'; var replacePlaceholders = function (placeholder) { var random = Math.random()*16|0; var value = placeholder == 'x' ? random : (random &0x3 | 0x8); return value.toString(16); }; return RFC4122_TEMPLATE.replace(/[xy]/g, replacePlaceholders); } this.boolean =function () { return !!faker.random.number(1) } return this; } module['exports'] = Random; // module.exports = random; },{"../vendor/mersenne":143}],142:[function(require,module,exports){ var Faker = require('../lib'); var faker = new Faker({ locale: 'nep', localeFallback: 'en' }); faker.locales['nep'] = require('../lib/locales/nep'); faker.locales['en'] = require('../lib/locales/en'); module['exports'] = faker; },{"../lib":35,"../lib/locales/en":102,"../lib/locales/nep":129}],143:[function(require,module,exports){ // this program is a JavaScript version of Mersenne Twister, with concealment and encapsulation in class, // an almost straight conversion from the original program, mt19937ar.c, // translated by y. okada on July 17, 2006. // and modified a little at july 20, 2006, but there are not any substantial differences. // in this program, procedure descriptions and comments of original source code were not removed. // lines commented with //c// were originally descriptions of c procedure. and a few following lines are appropriate JavaScript descriptions. // lines commented with /* and */ are original comments. // lines commented with // are additional comments in this JavaScript version. // before using this version, create at least one instance of MersenneTwister19937 class, and initialize the each state, given below in c comments, of all the instances. /* A C-program for MT19937, with initialization improved 2002/1/26. Coded by Takuji Nishimura and Makoto Matsumoto. Before using, initialize the state by using init_genrand(seed) or init_by_array(init_key, key_length). Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Any feedback is very welcome. http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) */ function MersenneTwister19937() { /* constants should be scoped inside the class */ var N, M, MATRIX_A, UPPER_MASK, LOWER_MASK; /* Period parameters */ //c//#define N 624 //c//#define M 397 //c//#define MATRIX_A 0x9908b0dfUL /* constant vector a */ //c//#define UPPER_MASK 0x80000000UL /* most significant w-r bits */ //c//#define LOWER_MASK 0x7fffffffUL /* least significant r bits */ N = 624; M = 397; MATRIX_A = 0x9908b0df; /* constant vector a */ UPPER_MASK = 0x80000000; /* most significant w-r bits */ LOWER_MASK = 0x7fffffff; /* least significant r bits */ //c//static unsigned long mt[N]; /* the array for the state vector */ //c//static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */ var mt = new Array(N); /* the array for the state vector */ var mti = N+1; /* mti==N+1 means mt[N] is not initialized */ function unsigned32 (n1) // returns a 32-bits unsiged integer from an operand to which applied a bit operator. { return n1 < 0 ? (n1 ^ UPPER_MASK) + UPPER_MASK : n1; } function subtraction32 (n1, n2) // emulates lowerflow of a c 32-bits unsiged integer variable, instead of the operator -. these both arguments must be non-negative integers expressible using unsigned 32 bits. { return n1 < n2 ? unsigned32((0x100000000 - (n2 - n1)) & 0xffffffff) : n1 - n2; } function addition32 (n1, n2) // emulates overflow of a c 32-bits unsiged integer variable, instead of the operator +. these both arguments must be non-negative integers expressible using unsigned 32 bits. { return unsigned32((n1 + n2) & 0xffffffff) } function multiplication32 (n1, n2) // emulates overflow of a c 32-bits unsiged integer variable, instead of the operator *. these both arguments must be non-negative integers expressible using unsigned 32 bits. { var sum = 0; for (var i = 0; i < 32; ++i){ if ((n1 >>> i) & 0x1){ sum = addition32(sum, unsigned32(n2 << i)); } } return sum; } /* initializes mt[N] with a seed */ //c//void init_genrand(unsigned long s) this.init_genrand = function (s) { //c//mt[0]= s & 0xffffffff; mt[0]= unsigned32(s & 0xffffffff); for (mti=1; mti<N; mti++) { mt[mti] = //c//(1812433253 * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); addition32(multiplication32(1812433253, unsigned32(mt[mti-1] ^ (mt[mti-1] >>> 30))), mti); /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ /* In the previous versions, MSBs of the seed affect */ /* only MSBs of the array mt[]. */ /* 2002/01/09 modified by Makoto Matsumoto */ //c//mt[mti] &= 0xffffffff; mt[mti] = unsigned32(mt[mti] & 0xffffffff); /* for >32 bit machines */ } } /* initialize by an array with array-length */ /* init_key is the array for initializing keys */ /* key_length is its length */ /* slight change for C++, 2004/2/26 */ //c//void init_by_array(unsigned long init_key[], int key_length) this.init_by_array = function (init_key, key_length) { //c//int i, j, k; var i, j, k; //c//init_genrand(19650218); this.init_genrand(19650218); i=1; j=0; k = (N>key_length ? N : key_length); for (; k; k--) { //c//mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525)) //c// + init_key[j] + j; /* non linear */ mt[i] = addition32(addition32(unsigned32(mt[i] ^ multiplication32(unsigned32(mt[i-1] ^ (mt[i-1] >>> 30)), 1664525)), init_key[j]), j); mt[i] = //c//mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */ unsigned32(mt[i] & 0xffffffff); i++; j++; if (i>=N) { mt[0] = mt[N-1]; i=1; } if (j>=key_length) j=0; } for (k=N-1; k; k--) { //c//mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941)) //c//- i; /* non linear */ mt[i] = subtraction32(unsigned32((dbg=mt[i]) ^ multiplication32(unsigned32(mt[i-1] ^ (mt[i-1] >>> 30)), 1566083941)), i); //c//mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */ mt[i] = unsigned32(mt[i] & 0xffffffff); i++; if (i>=N) { mt[0] = mt[N-1]; i=1; } } mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */ } /* moved outside of genrand_int32() by jwatte 2010-11-17; generate less garbage */ var mag01 = [0x0, MATRIX_A]; /* generates a random number on [0,0xffffffff]-interval */ //c//unsigned long genrand_int32(void) this.genrand_int32 = function () { //c//unsigned long y; //c//static unsigned long mag01[2]={0x0UL, MATRIX_A}; var y; /* mag01[x] = x * MATRIX_A for x=0,1 */ if (mti >= N) { /* generate N words at one time */ //c//int kk; var kk; if (mti == N+1) /* if init_genrand() has not been called, */ //c//init_genrand(5489); /* a default initial seed is used */ this.init_genrand(5489); /* a default initial seed is used */ for (kk=0;kk<N-M;kk++) { //c//y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); //c//mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1]; y = unsigned32((mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK)); mt[kk] = unsigned32(mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]); } for (;kk<N-1;kk++) { //c//y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); //c//mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1]; y = unsigned32((mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK)); mt[kk] = unsigned32(mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]); } //c//y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK); //c//mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1]; y = unsigned32((mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK)); mt[N-1] = unsigned32(mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]); mti = 0; } y = mt[mti++]; /* Tempering */ //c//y ^= (y >> 11); //c//y ^= (y << 7) & 0x9d2c5680; //c//y ^= (y << 15) & 0xefc60000; //c//y ^= (y >> 18); y = unsigned32(y ^ (y >>> 11)); y = unsigned32(y ^ ((y << 7) & 0x9d2c5680)); y = unsigned32(y ^ ((y << 15) & 0xefc60000)); y = unsigned32(y ^ (y >>> 18)); return y; } /* generates a random number on [0,0x7fffffff]-interval */ //c//long genrand_int31(void) this.genrand_int31 = function () { //c//return (genrand_int32()>>1); return (this.genrand_int32()>>>1); } /* generates a random number on [0,1]-real-interval */ //c//double genrand_real1(void) this.genrand_real1 = function () { //c//return genrand_int32()*(1.0/4294967295.0); return this.genrand_int32()*(1.0/4294967295.0); /* divided by 2^32-1 */ } /* generates a random number on [0,1)-real-interval */ //c//double genrand_real2(void) this.genrand_real2 = function () { //c//return genrand_int32()*(1.0/4294967296.0); return this.genrand_int32()*(1.0/4294967296.0); /* divided by 2^32 */ } /* generates a random number on (0,1)-real-interval */ //c//double genrand_real3(void) this.genrand_real3 = function () { //c//return ((genrand_int32()) + 0.5)*(1.0/4294967296.0); return ((this.genrand_int32()) + 0.5)*(1.0/4294967296.0); /* divided by 2^32 */ } /* generates a random number on [0,1) with 53-bit resolution*/ //c//double genrand_res53(void) this.genrand_res53 = function () { //c//unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6; var a=this.genrand_int32()>>>5, b=this.genrand_int32()>>>6; return(a*67108864.0+b)*(1.0/9007199254740992.0); } /* These real versions are due to Isaku Wada, 2002/01/09 added */ } // Exports: Public API // Export the twister class exports.MersenneTwister19937 = MersenneTwister19937; // Export a simplified function to generate random numbers var gen = new MersenneTwister19937; gen.init_genrand((new Date).getTime() % 1000000000); // Added max, min range functionality, Marak Squires Sept 11 2014 exports.rand = function(max, min) { if (max === undefined) { min = 0; max = 32768; } return Math.floor(gen.genrand_real2() * (max - min) + min); } exports.seed = function(S) { if (typeof(S) != 'number') { throw new Error("seed(S) must take numeric argument; is " + typeof(S)); } gen.init_genrand(S); } exports.seed_array = function(A) { if (typeof(A) != 'object') { throw new Error("seed_array(A) must take array of numbers; is " + typeof(A)); } gen.init_by_array(A); } },{}],144:[function(require,module,exports){ /* * password-generator * Copyright(c) 2011-2013 Bermi Ferrer <bermi@bermilabs.com> * MIT Licensed */ (function (root) { var localName, consonant, letter, password, vowel; letter = /[a-zA-Z]$/; vowel = /[aeiouAEIOU]$/; consonant = /[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]$/; // Defines the name of the local variable the passwordGenerator library will use // this is specially useful if window.passwordGenerator is already being used // by your application and you want a different name. For example: // // Declare before including the passwordGenerator library // var localPasswordGeneratorLibraryName = 'pass'; localName = root.localPasswordGeneratorLibraryName || "generatePassword", password = function (length, memorable, pattern, prefix) { var char, n; if (length == null) { length = 10; } if (memorable == null) { memorable = true; } if (pattern == null) { pattern = /\w/; } if (prefix == null) { prefix = ''; } if (prefix.length >= length) { return prefix; } if (memorable) { if (prefix.match(consonant)) { pattern = vowel; } else { pattern = consonant; } } n = Math.floor(Math.random() * 94) + 33; char = String.fromCharCode(n); if (memorable) { char = char.toLowerCase(); } if (!char.match(pattern)) { return password(length, memorable, pattern, prefix); } return password(length, memorable, pattern, "" + prefix + char); }; ((typeof exports !== 'undefined') ? exports : root)[localName] = password; if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { module.exports = password; } } // Establish the root object, `window` in the browser, or `global` on the server. }(this)); },{}],145:[function(require,module,exports){ /* Copyright (c) 2012-2014 Jeffrey Mealo Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------------------------------------------------ Based loosely on Luka Pusic's PHP Script: http://360percents.com/posts/php-random-user-agent-generator/ The license for that script is as follows: "THE BEER-WARE LICENSE" (Revision 42): <pusic93@gmail.com> wrote this file. As long as you retain this notice you can do whatever you want with this stuff. If we meet some day, and you think this stuff is worth it, you can buy me a beer in return. Luka Pusic */ function rnd(a, b) { //calling rnd() with no arguments is identical to rnd(0, 100) a = a || 0; b = b || 100; if (typeof b === 'number' && typeof a === 'number') { //rnd(int min, int max) returns integer between min, max return (function (min, max) { if (min > max) { throw new RangeError('expected min <= max; got min = ' + min + ', max = ' + max); } return Math.floor(Math.random() * (max - min + 1)) + min; }(a, b)); } if (Object.prototype.toString.call(a) === "[object Array]") { //returns a random element from array (a), even weighting return a[Math.floor(Math.random() * a.length)]; } if (a && typeof a === 'object') { //returns a random key from the passed object; keys are weighted by the decimal probability in their value return (function (obj) { var rand = rnd(0, 100) / 100, min = 0, max = 0, key, return_val; for (key in obj) { if (obj.hasOwnProperty(key)) { max = obj[key] + min; return_val = key; if (rand >= min && rand <= max) { break; } min = min + obj[key]; } } return return_val; }(a)); } throw new TypeError('Invalid arguments passed to rnd. (' + (b ? a + ', ' + b : a) + ')'); } function randomLang() { return rnd(['AB', 'AF', 'AN', 'AR', 'AS', 'AZ', 'BE', 'BG', 'BN', 'BO', 'BR', 'BS', 'CA', 'CE', 'CO', 'CS', 'CU', 'CY', 'DA', 'DE', 'EL', 'EN', 'EO', 'ES', 'ET', 'EU', 'FA', 'FI', 'FJ', 'FO', 'FR', 'FY', 'GA', 'GD', 'GL', 'GV', 'HE', 'HI', 'HR', 'HT', 'HU', 'HY', 'ID', 'IS', 'IT', 'JA', 'JV', 'KA', 'KG', 'KO', 'KU', 'KW', 'KY', 'LA', 'LB', 'LI', 'LN', 'LT', 'LV', 'MG', 'MK', 'MN', 'MO', 'MS', 'MT', 'MY', 'NB', 'NE', 'NL', 'NN', 'NO', 'OC', 'PL', 'PT', 'RM', 'RO', 'RU', 'SC', 'SE', 'SK', 'SL', 'SO', 'SQ', 'SR', 'SV', 'SW', 'TK', 'TR', 'TY', 'UK', 'UR', 'UZ', 'VI', 'VO', 'YI', 'ZH']); } function randomBrowserAndOS() { var browser = rnd({ chrome: .45132810566, iexplorer: .27477061836, firefox: .19384170608, safari: .06186781118, opera: .01574236955 }), os = { chrome: {win: .89, mac: .09 , lin: .02}, firefox: {win: .83, mac: .16, lin: .01}, opera: {win: .91, mac: .03 , lin: .06}, safari: {win: .04 , mac: .96 }, iexplorer: ['win'] }; return [browser, rnd(os[browser])]; } function randomProc(arch) { var procs = { lin:['i686', 'x86_64'], mac: {'Intel' : .48, 'PPC': .01, 'U; Intel':.48, 'U; PPC' :.01}, win:['', 'WOW64', 'Win64; x64'] }; return rnd(procs[arch]); } function randomRevision(dots) { var return_val = ''; //generate a random revision //dots = 2 returns .x.y where x & y are between 0 and 9 for (var x = 0; x < dots; x++) { return_val += '.' + rnd(0, 9); } return return_val; } var version_string = { net: function () { return [rnd(1, 4), rnd(0, 9), rnd(10000, 99999), rnd(0, 9)].join('.'); }, nt: function () { return rnd(5, 6) + '.' + rnd(0, 3); }, ie: function () { return rnd(7, 11); }, trident: function () { return rnd(3, 7) + '.' + rnd(0, 1); }, osx: function (delim) { return [10, rnd(5, 10), rnd(0, 9)].join(delim || '.'); }, chrome: function () { return [rnd(13, 39), 0, rnd(800, 899), 0].join('.'); }, presto: function () { return '2.9.' + rnd(160, 190); }, presto2: function () { return rnd(10, 12) + '.00'; }, safari: function () { return rnd(531, 538) + '.' + rnd(0, 2) + '.' + rnd(0,2); } }; var browser = { firefox: function firefox(arch) { //https://developer.mozilla.org/en-US/docs/Gecko_user_agent_string_reference var firefox_ver = rnd(5, 15) + randomRevision(2), gecko_ver = 'Gecko/20100101 Firefox/' + firefox_ver, proc = randomProc(arch), os_ver = (arch === 'win') ? '(Windows NT ' + version_string.nt() + ((proc) ? '; ' + proc : '') : (arch === 'mac') ? '(Macintosh; ' + proc + ' Mac OS X ' + version_string.osx() : '(X11; Linux ' + proc; return 'Mozilla/5.0 ' + os_ver + '; rv:' + firefox_ver.slice(0, -2) + ') ' + gecko_ver; }, iexplorer: function iexplorer() { var ver = version_string.ie(); if (ver >= 11) { //http://msdn.microsoft.com/en-us/library/ie/hh869301(v=vs.85).aspx return 'Mozilla/5.0 (Windows NT 6.' + rnd(1,3) + '; Trident/7.0; ' + rnd(['Touch; ', '']) + 'rv:11.0) like Gecko'; } //http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx return 'Mozilla/5.0 (compatible; MSIE ' + ver + '.0; Windows NT ' + version_string.nt() + '; Trident/' + version_string.trident() + ((rnd(0, 1) === 1) ? '; .NET CLR ' + version_string.net() : '') + ')'; }, opera: function opera(arch) { //http://www.opera.com/docs/history/ var presto_ver = ' Presto/' + version_string.presto() + ' Version/' + version_string.presto2() + ')', os_ver = (arch === 'win') ? '(Windows NT ' + version_string.nt() + '; U; ' + randomLang() + presto_ver : (arch === 'lin') ? '(X11; Linux ' + randomProc(arch) + '; U; ' + randomLang() + presto_ver : '(Macintosh; Intel Mac OS X ' + version_string.osx() + ' U; ' + randomLang() + ' Presto/' + version_string.presto() + ' Version/' + version_string.presto2() + ')'; return 'Opera/' + rnd(9, 14) + '.' + rnd(0, 99) + ' ' + os_ver; }, safari: function safari(arch) { var safari = version_string.safari(), ver = rnd(4, 7) + '.' + rnd(0,1) + '.' + rnd(0,10), os_ver = (arch === 'mac') ? '(Macintosh; ' + randomProc('mac') + ' Mac OS X '+ version_string.osx('_') + ' rv:' + rnd(2, 6) + '.0; '+ randomLang() + ') ' : '(Windows; U; Windows NT ' + version_string.nt() + ')'; return 'Mozilla/5.0 ' + os_ver + 'AppleWebKit/' + safari + ' (KHTML, like Gecko) Version/' + ver + ' Safari/' + safari; }, chrome: function chrome(arch) { var safari = version_string.safari(), os_ver = (arch === 'mac') ? '(Macintosh; ' + randomProc('mac') + ' Mac OS X ' + version_string.osx('_') + ') ' : (arch === 'win') ? '(Windows; U; Windows NT ' + version_string.nt() + ')' : '(X11; Linux ' + randomProc(arch); return 'Mozilla/5.0 ' + os_ver + ' AppleWebKit/' + safari + ' (KHTML, like Gecko) Chrome/' + version_string.chrome() + ' Safari/' + safari; } }; exports.generate = function generate() { var random = randomBrowserAndOS(); return browser[random[0]](random[1]); }; },{}],146:[function(require,module,exports){ var ret = require('ret'); var DRange = require('discontinuous-range'); var types = ret.types; /** * If code is alphabetic, converts to other case. * If not alphabetic, returns back code. * * @param {Number} code * @return {Number} */ function toOtherCase(code) { return code + (97 <= code && code <= 122 ? -32 : 65 <= code && code <= 90 ? 32 : 0); } /** * Randomly returns a true or false value. * * @return {Boolean} */ function randBool() { return !this.randInt(0, 1); } /** * Randomly selects and returns a value from the array. * * @param {Array.<Object>} arr * @return {Object} */ function randSelect(arr) { if (arr instanceof DRange) { return arr.index(this.randInt(0, arr.length - 1)); } return arr[this.randInt(0, arr.length - 1)]; } /** * expands a token to a DiscontinuousRange of characters which has a * length and an index function (for random selecting) * * @param {Object} token * @return {DiscontinuousRange} */ function expand(token) { if (token.type === ret.types.CHAR) return new DRange(token.value); if (token.type === ret.types.RANGE) return new DRange(token.from, token.to); if (token.type === ret.types.SET) { var drange = new DRange(); for (var i = 0; i < token.set.length; i++) { var subrange = expand.call(this, token.set[i]); drange.add(subrange); if (this.ignoreCase) { for (var j = 0; j < subrange.length; j++) { var code = subrange.index(j); var otherCaseCode = toOtherCase(code); if (code !== otherCaseCode) { drange.add(otherCaseCode); } } } } if (token.not) { return this.defaultRange.clone().subtract(drange); } else { return drange; } } throw new Error('unexpandable token type: ' + token.type); } /** * @constructor * @param {RegExp|String} regexp * @param {String} m */ var RandExp = module.exports = function(regexp, m) { this.defaultRange = this.defaultRange.clone(); if (regexp instanceof RegExp) { this.ignoreCase = regexp.ignoreCase; this.multiline = regexp.multiline; if (typeof regexp.max === 'number') { this.max = regexp.max; } regexp = regexp.source; } else if (typeof regexp === 'string') { this.ignoreCase = m && m.indexOf('i') !== -1; this.multiline = m && m.indexOf('m') !== -1; } else { throw new Error('Expected a regexp or string'); } this.tokens = ret(regexp); }; // When a repetitional token has its max set to Infinite, // randexp won't actually generate a random amount between min and Infinite // instead it will see Infinite as min + 100. RandExp.prototype.max = 100; // Generates the random string. RandExp.prototype.gen = function() { return gen.call(this, this.tokens, []); }; // Enables use of randexp with a shorter call. RandExp.randexp = function(regexp, m) { var randexp; if (regexp._randexp === undefined) { randexp = new RandExp(regexp, m); regexp._randexp = randexp; } else { randexp = regexp._randexp; if (typeof regexp.max === 'number') { randexp.max = regexp.max; } if (regexp.defaultRange instanceof DRange) { randexp.defaultRange = regexp.defaultRange; } if (typeof regexp.randInt === 'function') { randexp.randInt = regexp.randInt; } } return randexp.gen(); }; // This enables sugary /regexp/.gen syntax. RandExp.sugar = function() { /* jshint freeze:false */ RegExp.prototype.gen = function() { return RandExp.randexp(this); }; }; // This allows expanding to include additional characters // for instance: RandExp.defaultRange.add(0, 65535); RandExp.prototype.defaultRange = new DRange(32, 126); /** * Randomly generates and returns a number between a and b (inclusive). * * @param {Number} a * @param {Number} b * @return {Number} */ RandExp.prototype.randInt = function(a, b) { return a + Math.floor(Math.random() * (1 + b - a)); }; /** * Generate random string modeled after given tokens. * * @param {Object} token * @param {Array.<String>} groups * @return {String} */ function gen(token, groups) { var stack, str, n, i, l; switch (token.type) { case types.ROOT: case types.GROUP: if (token.notFollowedBy) { return ''; } // Insert placeholder until group string is generated. if (token.remember && token.groupNumber === undefined) { token.groupNumber = groups.push(null) - 1; } stack = token.options ? randSelect.call(this, token.options) : token.stack; str = ''; for (i = 0, l = stack.length; i < l; i++) { str += gen.call(this, stack[i], groups); } if (token.remember) { groups[token.groupNumber] = str; } return str; case types.POSITION: // Do nothing for now. return ''; case types.SET: var expanded_set = expand.call(this, token); if (!expanded_set.length) return ''; return String.fromCharCode(randSelect.call(this, expanded_set)); case types.REPETITION: // Randomly generate number between min and max. n = this.randInt(token.min, token.max === Infinity ? token.min + this.max : token.max); str = ''; for (i = 0; i < n; i++) { str += gen.call(this, token.value, groups); } return str; case types.REFERENCE: return groups[token.value - 1] || ''; case types.CHAR: var code = this.ignoreCase && randBool.call(this) ? toOtherCase(token.value) : token.value; return String.fromCharCode(code); } } },{"discontinuous-range":147,"ret":148}],147:[function(require,module,exports){ //protected helper class function _SubRange(low, high) { this.low = low; this.high = high; this.length = 1 + high - low; } _SubRange.prototype.overlaps = function (range) { return !(this.high < range.low || this.low > range.high); }; _SubRange.prototype.touches = function (range) { return !(this.high + 1 < range.low || this.low - 1 > range.high); }; //returns inclusive combination of _SubRanges as a _SubRange _SubRange.prototype.add = function (range) { return this.touches(range) && new _SubRange(Math.min(this.low, range.low), Math.max(this.high, range.high)); }; //returns subtraction of _SubRanges as an array of _SubRanges (there's a case where subtraction divides it in 2) _SubRange.prototype.subtract = function (range) { if (!this.overlaps(range)) return false; if (range.low <= this.low && range.high >= this.high) return []; if (range.low > this.low && range.high < this.high) return [new _SubRange(this.low, range.low - 1), new _SubRange(range.high + 1, this.high)]; if (range.low <= this.low) return [new _SubRange(range.high + 1, this.high)]; return [new _SubRange(this.low, range.low - 1)]; }; _SubRange.prototype.toString = function () { if (this.low == this.high) return this.low.toString(); return this.low + '-' + this.high; }; _SubRange.prototype.clone = function () { return new _SubRange(this.low, this.high); }; function DiscontinuousRange(a, b) { if (this instanceof DiscontinuousRange) { this.ranges = []; this.length = 0; if (a !== undefined) this.add(a, b); } else { return new DiscontinuousRange(a, b); } } function _update_length(self) { self.length = self.ranges.reduce(function (previous, range) {return previous + range.length}, 0); } DiscontinuousRange.prototype.add = function (a, b) { var self = this; function _add(subrange) { var new_ranges = []; var i = 0; while (i < self.ranges.length && !subrange.touches(self.ranges[i])) { new_ranges.push(self.ranges[i].clone()); i++; } while (i < self.ranges.length && subrange.touches(self.ranges[i])) { subrange = subrange.add(self.ranges[i]); i++; } new_ranges.push(subrange); while (i < self.ranges.length) { new_ranges.push(self.ranges[i].clone()); i++; } self.ranges = new_ranges; _update_length(self); } if (a instanceof DiscontinuousRange) { a.ranges.forEach(_add); } else { if (a instanceof _SubRange) { _add(a); } else { if (b === undefined) b = a; _add(new _SubRange(a, b)); } } return this; }; DiscontinuousRange.prototype.subtract = function (a, b) { var self = this; function _subtract(subrange) { var new_ranges = []; var i = 0; while (i < self.ranges.length && !subrange.overlaps(self.ranges[i])) { new_ranges.push(self.ranges[i].clone()); i++; } while (i < self.ranges.length && subrange.overlaps(self.ranges[i])) { new_ranges = new_ranges.concat(self.ranges[i].subtract(subrange)); i++; } while (i < self.ranges.length) { new_ranges.push(self.ranges[i].clone()); i++; } self.ranges = new_ranges; _update_length(self); } if (a instanceof DiscontinuousRange) { a.ranges.forEach(_subtract); } else { if (a instanceof _SubRange) { _subtract(a); } else { if (b === undefined) b = a; _subtract(new _SubRange(a, b)); } } return this; }; DiscontinuousRange.prototype.index = function (index) { var i = 0; while (i < this.ranges.length && this.ranges[i].length <= index) { index -= this.ranges[i].length; i++; } if (i >= this.ranges.length) return null; return this.ranges[i].low + index; }; DiscontinuousRange.prototype.toString = function () { return '[ ' + this.ranges.join(', ') + ' ]' }; DiscontinuousRange.prototype.clone = function () { return new DiscontinuousRange(this); }; module.exports = DiscontinuousRange; },{}],148:[function(require,module,exports){ var util = require('./util'); var types = require('./types'); var sets = require('./sets'); var positions = require('./positions'); module.exports = function(regexpStr) { var i = 0, l, c, start = { type: types.ROOT, stack: []}, // Keep track of last clause/group and stack. lastGroup = start, last = start.stack, groupStack = []; var repeatErr = function(i) { util.error(regexpStr, 'Nothing to repeat at column ' + (i - 1)); }; // Decode a few escaped characters. var str = util.strToChars(regexpStr); l = str.length; // Iterate through each character in string. while (i < l) { c = str[i++]; switch (c) { // Handle escaped characters, inclues a few sets. case '\\': c = str[i++]; switch (c) { case 'b': last.push(positions.wordBoundary()); break; case 'B': last.push(positions.nonWordBoundary()); break; case 'w': last.push(sets.words()); break; case 'W': last.push(sets.notWords()); break; case 'd': last.push(sets.ints()); break; case 'D': last.push(sets.notInts()); break; case 's': last.push(sets.whitespace()); break; case 'S': last.push(sets.notWhitespace()); break; default: // Check if c is integer. // In which case it's a reference. if (/\d/.test(c)) { last.push({ type: types.REFERENCE, value: parseInt(c, 10) }); // Escaped character. } else { last.push({ type: types.CHAR, value: c.charCodeAt(0) }); } } break; // Positionals. case '^': last.push(positions.begin()); break; case '$': last.push(positions.end()); break; // Handle custom sets. case '[': // Check if this class is 'anti' i.e. [^abc]. var not; if (str[i] === '^') { not = true; i++; } else { not = false; } // Get all the characters in class. var classTokens = util.tokenizeClass(str.slice(i), regexpStr); // Increase index by length of class. i += classTokens[1]; last.push({ type: types.SET , set: classTokens[0] , not: not }); break; // Class of any character except \n. case '.': last.push(sets.anyChar()); break; // Push group onto stack. case '(': // Create group. var group = { type: types.GROUP , stack: [] , remember: true }; c = str[i]; // if if this is a special kind of group. if (c === '?') { c = str[i + 1]; i += 2; // Match if followed by. if (c === '=') { group.followedBy = true; // Match if not followed by. } else if (c === '!') { group.notFollowedBy = true; } else if (c !== ':') { util.error(regexpStr, 'Invalid group, character \'' + c + '\' after \'?\' at column ' + (i - 1)); } group.remember = false; } // Insert subgroup into current group stack. last.push(group); // Remember the current group for when the group closes. groupStack.push(lastGroup); // Make this new group the current group. lastGroup = group; last = group.stack; break; // Pop group out of stack. case ')': if (groupStack.length === 0) { util.error(regexpStr, 'Unmatched ) at column ' + (i - 1)); } lastGroup = groupStack.pop(); // Check if this group has a PIPE. // To get back the correct last stack. last = lastGroup.options ? lastGroup.options[lastGroup.options.length - 1] : lastGroup.stack; break; // Use pipe character to give more choices. case '|': // Create array where options are if this is the first PIPE // in this clause. if (!lastGroup.options) { lastGroup.options = [lastGroup.stack]; delete lastGroup.stack; } // Create a new stack and add to options for rest of clause. var stack = []; lastGroup.options.push(stack); last = stack; break; // Repetition. // For every repetition, remove last element from last stack // then insert back a RANGE object. // This design is chosen because there could be more than // one repetition symbols in a regex i.e. `a?+{2,3}`. case '{': var rs = /^(\d+)(,(\d+)?)?\}/.exec(str.slice(i)), min, max; if (rs !== null) { min = parseInt(rs[1], 10); max = rs[2] ? rs[3] ? parseInt(rs[3], 10) : Infinity : min; i += rs[0].length; last.push({ type: types.REPETITION , min: min , max: max , value: last.pop() }); } else { last.push({ type: types.CHAR , value: 123 }); } break; case '?': if (last.length === 0) { repeatErr(i); } last.push({ type: types.REPETITION , min: 0 , max: 1 , value: last.pop() }); break; case '+': if (last.length === 0) { repeatErr(i); } last.push({ type: types.REPETITION , min: 1 , max: Infinity , value: last.pop() }); break; case '*': if (last.length === 0) { repeatErr(i); } last.push({ type: types.REPETITION , min: 0 , max: Infinity , value: last.pop() }); break; // Default is a character that is not `\[](){}?+*^$`. default: last.push({ type: types.CHAR , value: c.charCodeAt(0) }); } } // Check if any groups have not been closed. if (groupStack.length !== 0) { util.error(regexpStr, 'Unterminated group'); } return start; }; module.exports.types = types; },{"./positions":149,"./sets":150,"./types":151,"./util":152}],149:[function(require,module,exports){ var types = require('./types'); exports.wordBoundary = function() { return { type: types.POSITION, value: 'b' }; }; exports.nonWordBoundary = function() { return { type: types.POSITION, value: 'B' }; }; exports.begin = function() { return { type: types.POSITION, value: '^' }; }; exports.end = function() { return { type: types.POSITION, value: '$' }; }; },{"./types":151}],150:[function(require,module,exports){ var types = require('./types'); var INTS = function() { return [{ type: types.RANGE , from: 48, to: 57 }]; }; var WORDS = function() { return [ { type: types.CHAR, value: 95 } , { type: types.RANGE, from: 97, to: 122 } , { type: types.RANGE, from: 65, to: 90 } ].concat(INTS()); }; var WHITESPACE = function() { return [ { type: types.CHAR, value: 9 } , { type: types.CHAR, value: 10 } , { type: types.CHAR, value: 11 } , { type: types.CHAR, value: 12 } , { type: types.CHAR, value: 13 } , { type: types.CHAR, value: 32 } , { type: types.CHAR, value: 160 } , { type: types.CHAR, value: 5760 } , { type: types.CHAR, value: 6158 } , { type: types.CHAR, value: 8192 } , { type: types.CHAR, value: 8193 } , { type: types.CHAR, value: 8194 } , { type: types.CHAR, value: 8195 } , { type: types.CHAR, value: 8196 } , { type: types.CHAR, value: 8197 } , { type: types.CHAR, value: 8198 } , { type: types.CHAR, value: 8199 } , { type: types.CHAR, value: 8200 } , { type: types.CHAR, value: 8201 } , { type: types.CHAR, value: 8202 } , { type: types.CHAR, value: 8232 } , { type: types.CHAR, value: 8233 } , { type: types.CHAR, value: 8239 } , { type: types.CHAR, value: 8287 } , { type: types.CHAR, value: 12288 } , { type: types.CHAR, value: 65279 } ]; }; var NOTANYCHAR = function() { return [ { type: types.CHAR, value: 10 } , { type: types.CHAR, value: 13 } , { type: types.CHAR, value: 8232 } , { type: types.CHAR, value: 8233 } ]; }; // predefined class objects exports.words = function() { return { type: types.SET, set: WORDS(), not: false }; }; exports.notWords = function() { return { type: types.SET, set: WORDS(), not: true }; }; exports.ints = function() { return { type: types.SET, set: INTS(), not: false }; }; exports.notInts = function() { return { type: types.SET, set: INTS(), not: true }; }; exports.whitespace = function() { return { type: types.SET, set: WHITESPACE(), not: false }; }; exports.notWhitespace = function() { return { type: types.SET, set: WHITESPACE(), not: true }; }; exports.anyChar = function() { return { type: types.SET, set: NOTANYCHAR(), not: true }; }; },{"./types":151}],151:[function(require,module,exports){ module.exports = { ROOT : 0 , GROUP : 1 , POSITION : 2 , SET : 3 , RANGE : 4 , REPETITION : 5 , REFERENCE : 6 , CHAR : 7 }; },{}],152:[function(require,module,exports){ var types = require('./types'); var sets = require('./sets'); // All of these are private and only used by randexp. // It's assumed that they will always be called with the correct input. var CTRL = '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?'; var SLSH = { '0': 0, 't': 9, 'n': 10, 'v': 11, 'f': 12, 'r': 13 }; /** * Finds character representations in str and convert all to * their respective characters * * @param {String} str * @return {String} */ exports.strToChars = function(str) { var chars_regex = /(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|(0?[0-7]{2})|c([@A-Z\[\\\]\^?])|([0tnvfr]))/g; str = str.replace(chars_regex, function(s, b, lbs, a16, b16, c8, dctrl, eslsh) { if (lbs) { return s; } var code = b ? 8 : a16 ? parseInt(a16, 16) : b16 ? parseInt(b16, 16) : c8 ? parseInt(c8, 8) : dctrl ? CTRL.indexOf(dctrl) : eslsh ? SLSH[eslsh] : undefined; var c = String.fromCharCode(code); // Escape special regex characters. if (/[\[\]{}\^$.|?*+()]/.test(c)) { c = '\\' + c; } return c; }); return str; }; /** * turns class into tokens * reads str until it encounters a ] not preceeded by a \ * * @param {String} str * @param {String} regexpStr * @return {Array.<Array.<Object>, Number>} */ exports.tokenizeClass = function(str, regexpStr) { var tokens = [] , regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?(.)/g , rs, c ; while ((rs = regexp.exec(str)) != null) { if (rs[1]) { tokens.push(sets.words()); } else if (rs[2]) { tokens.push(sets.ints()); } else if (rs[3]) { tokens.push(sets.whitespace()); } else if (rs[4]) { tokens.push(sets.notWords()); } else if (rs[5]) { tokens.push(sets.notInts()); } else if (rs[6]) { tokens.push(sets.notWhitespace()); } else if (rs[7]) { tokens.push({ type: types.RANGE , from: (rs[8] || rs[9]).charCodeAt(0) , to: rs[10].charCodeAt(0) }); } else if (c = rs[12]) { tokens.push({ type: types.CHAR , value: c.charCodeAt(0) }); } else { return [tokens, regexp.lastIndex]; } } exports.error(regexpStr, 'Unterminated character class'); }; /** * Shortcut to throw errors. * * @param {String} regexp * @param {String} msg */ exports.error = function(regexp, msg) { throw new SyntaxError('Invalid regular expression: /' + regexp + '/: ' + msg); }; },{"./sets":150,"./types":151}],"json-schema-faker":[function(require,module,exports){ module.exports = require('../lib/jsf') .extend('faker', function() { try { return require('faker/locale/nep'); } catch (e) { return null; } }); },{"../lib/jsf":1,"faker/locale/nep":142}]},{},["json-schema-faker"])("json-schema-faker") });
/*! Copyright (c) 2011 Piotr Rochala (http://rocha.la) * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * * Version: 0.5.0 * */ (function(d){jQuery.fn.extend({slimScroll:function(o){var a=ops=d.extend({wheelStep:20,width:"auto",height:"250px",size:"7px",color:"#000",position:"right",distance:"1px",start:"top",opacity:0.4,alwaysVisible:!1,railVisible:!1,railColor:"#333",railOpacity:"0.2",railClass:"slimScrollRail",barClass:"slimScrollBar",wrapperClass:"slimScrollDiv",allowPageScroll:!1,scroll:0},o);this.each(function(){function h(a,d,e){var f=a;d&&(f=parseInt(c.css("top"))+a*B/100*c.outerHeight(),d=b.outerHeight()-c.outerHeight(), f=Math.min(Math.max(f,0),d),c.css({top:f+"px"}));k=parseInt(c.css("top"))/(b.outerHeight()-c.outerHeight());f=k*(b[0].scrollHeight-b.outerHeight());e&&(f=a,a=f/b[0].scrollHeight*b.outerHeight(),c.css({top:a+"px"}));b.scrollTop(f);p();i()}function w(){q=Math.max(b.outerHeight()/b[0].scrollHeight*b.outerHeight(),o);c.css({height:q+"px"})}function p(){w();clearTimeout(x);l=C&&k==~~k;q>=b.outerHeight()?l=!0:(c.stop(!0,!0).fadeIn("fast"),y&&g.stop(!0,!0).fadeIn("fast"))}function i(){m||(x=setTimeout(function(){!r&& !s&&(c.fadeOut("slow"),g.fadeOut("slow"))},1E3))}var t,r,s,x,q,k,o=30,l=!1,B=parseInt(a.wheelStep),j=a.width,z=a.height,e=a.size,D=a.color,E=a.position,A=a.distance,u=a.start,F=a.opacity,m=a.alwaysVisible,y=a.railVisible,G=a.railColor,H=a.railOpacity,C=a.allowPageScroll,n=a.scroll,b=d(this);if(b.parent().hasClass("slimScrollDiv"))n&&(c=b.parent().find(".slimScrollBar"),g=b.parent().find(".slimScrollRail"),h(b.scrollTop()+parseInt(n),!1,!0));else{n=d("<div></div>").addClass(a.wrapperClass).css({position:"relative", overflow:"hidden",width:j,height:z});b.css({overflow:"hidden",width:j,height:z});var g=d("<div></div>").addClass(a.railClass).css({width:e,height:"100%",position:"absolute",top:0,display:m&&y?"block":"none","border-radius":e,background:G,opacity:H,zIndex:90}),c=d("<div></div>").addClass(a.barClass).css({background:D,width:e,position:"absolute",top:0,opacity:F,display:m?"block":"none","border-radius":e,BorderRadius:e,MozBorderRadius:e,WebkitBorderRadius:e,zIndex:99}),j="right"==E?{right:A}:{left:A}; g.css(j);c.css(j);b.wrap(n);b.parent().append(c);b.parent().append(g);c.draggable({axis:"y",containment:"parent",start:function(){s=!0},stop:function(){s=!1;i()},drag:function(){h(0,d(this).position().top,!1)}});g.hover(function(){p()},function(){i()});c.hover(function(){r=!0},function(){r=!1});b.hover(function(){t=!0;p();i()},function(){t=!1;i()});var v=function(a){if(t){var a=a||window.event,b=0;a.wheelDelta&&(b=-a.wheelDelta/120);a.detail&&(b=a.detail/3);h(b,!0);a.preventDefault&&!l&&a.preventDefault(); l||(a.returnValue=!1)}};(function(){window.addEventListener?(this.addEventListener("DOMMouseScroll",v,!1),this.addEventListener("mousewheel",v,!1)):document.attachEvent("onmousewheel",v)})();w();"bottom"==u?(c.css({top:b.outerHeight()-c.outerHeight()}),h(0,!0)):"object"==typeof u&&(h(d(u).position().top,null,!0),m||c.hide())}});return this}});jQuery.fn.extend({slimscroll:jQuery.fn.slimScroll})})(jQuery);
/** * @fileoverview Warn when using template string syntax in regular strings * @author Jeroen Engels */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { docs: { description: "disallow template literal placeholder syntax in regular strings", category: "Possible Errors", recommended: false }, schema: [] }, create(context) { const regex = /\$\{[^}]+\}/; return { Literal(node) { if (typeof node.value === "string" && regex.test(node.value)) { context.report({ node, message: "Unexpected template string expression." }); } } }; } };
define(["require", "exports", "module", "program"], function(require, exports, module) { exports.program = function () { return require('program'); }; });
[foo.foo, foo.bar] = [1, 2]; ;
export { default } from './component';
/** * @license AngularJS v1.3.0-build.2711+sha.facd904 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) {'use strict'; var $sanitizeMinErr = angular.$$minErr('$sanitize'); /** * @ngdoc module * @name ngSanitize * @description * * # ngSanitize * * The `ngSanitize` module provides functionality to sanitize HTML. * * * <div doc-module-components="ngSanitize"></div> * * See {@link ngSanitize.$sanitize `$sanitize`} for usage. */ /* * HTML Parser By Misko Hevery (misko@hevery.com) * based on: HTML Parser By John Resig (ejohn.org) * Original code by Erik Arvidsson, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js * * // Use like so: * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * */ /** * @ngdoc service * @name $sanitize * @function * * @description * The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are * then serialized back to properly escaped html string. This means that no unsafe input can make * it into the returned string, however, since our parser is more strict than a typical browser * parser, it's possible that some obscure input, which would be recognized as valid HTML by a * browser, won't make it through the sanitizer. * The whitelist is configured using the functions `aHrefSanitizationWhitelist` and * `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider `$compileProvider`}. * * @param {string} html Html input. * @returns {string} Sanitized html. * * @example <example module="ngSanitize" deps="angular-sanitize.js"> <file name="index.html"> <script> function Ctrl($scope, $sce) { $scope.snippet = '<p style="color:blue">an html\n' + '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' + 'snippet</p>'; $scope.deliberatelyTrustDangerousSnippet = function() { return $sce.trustAsHtml($scope.snippet); }; } </script> <div ng-controller="Ctrl"> Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> <table> <tr> <td>Directive</td> <td>How</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="bind-html-with-sanitize"> <td>ng-bind-html</td> <td>Automatically uses $sanitize</td> <td><pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng-bind-html="snippet"></div></td> </tr> <tr id="bind-html-with-trust"> <td>ng-bind-html</td> <td>Bypass $sanitize by explicitly trusting the dangerous value</td> <td> <pre>&lt;div ng-bind-html="deliberatelyTrustDangerousSnippet()"&gt; &lt;/div&gt;</pre> </td> <td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td> </tr> <tr id="bind-default"> <td>ng-bind</td> <td>Automatically escapes</td> <td><pre>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng-bind="snippet"></div></td> </tr> </table> </div> </file> <file name="protractor.js" type="protractor"> it('should sanitize the html snippet by default', function() { expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()). toBe('<p>an html\n<em>click here</em>\nsnippet</p>'); }); it('should inline raw snippet if bound to a trusted value', function() { expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()). toBe("<p style=\"color:blue\">an html\n" + "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + "snippet</p>"); }); it('should escape snippet without any filter', function() { expect(element(by.css('#bind-default div')).getInnerHtml()). toBe("&lt;p style=\"color:blue\"&gt;an html\n" + "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" + "snippet&lt;/p&gt;"); }); it('should update', function() { element(by.model('snippet')).clear(); element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>'); expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()). toBe('new <b>text</b>'); expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe( 'new <b onclick="alert(1)">text</b>'); expect(element(by.css('#bind-default div')).getInnerHtml()).toBe( "new &lt;b onclick=\"alert(1)\"&gt;text&lt;/b&gt;"); }); </file> </example> */ function $SanitizeProvider() { this.$get = ['$$sanitizeUri', function($$sanitizeUri) { return function(html) { var buf = []; htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) { return !/^unsafe/.test($$sanitizeUri(uri, isImage)); })); return buf.join(''); }; }]; } function sanitizeText(chars) { var buf = []; var writer = htmlSanitizeWriter(buf, angular.noop); writer.chars(chars); return buf.join(''); } // Regular Expressions for parsing tags and attributes var START_TAG_REGEXP = /^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/, END_TAG_REGEXP = /^<\s*\/\s*([\w:-]+)[^>]*>/, ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g, BEGIN_TAG_REGEXP = /^</, BEGING_END_TAGE_REGEXP = /^<\s*\//, COMMENT_REGEXP = /<!--(.*?)-->/g, DOCTYPE_REGEXP = /<!DOCTYPE([^>]*?)>/i, CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g, SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g, // Match everything outside of normal chars and " (quote character) NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; // Good source of info about elements and attributes // http://dev.w3.org/html5/spec/Overview.html#semantics // http://simon.html5.org/html-elements // Safe Void Elements - HTML5 // http://dev.w3.org/html5/spec/Overview.html#void-elements var voidElements = makeMap("area,br,col,hr,img,wbr"); // Elements that you can, intentionally, leave open (and which close themselves) // http://dev.w3.org/html5/spec/Overview.html#optional-tags var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"), optionalEndTagInlineElements = makeMap("rp,rt"), optionalEndTagElements = angular.extend({}, optionalEndTagInlineElements, optionalEndTagBlockElements); // Safe Block Elements - HTML5 var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article," + "aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," + "h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul")); // Inline Elements - HTML5 var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b," + "bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," + "samp,small,span,strike,strong,sub,sup,time,tt,u,var")); // Special Elements (can contain anything) var specialElements = makeMap("script,style"); var validElements = angular.extend({}, voidElements, blockElements, inlineElements, optionalEndTagElements); //Attributes that have href and hence need to be sanitized var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap"); var validAttrs = angular.extend({}, uriAttrs, makeMap( 'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+ 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+ 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+ 'scope,scrolling,shape,size,span,start,summary,target,title,type,'+ 'valign,value,vspace,width')); function makeMap(str) { var obj = {}, items = str.split(','), i; for (i = 0; i < items.length; i++) obj[items[i]] = true; return obj; } /** * @example * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * * @param {string} html string * @param {object} handler */ function htmlParser( html, handler ) { var index, chars, match, stack = [], last = html; stack.last = function() { return stack[ stack.length - 1 ]; }; while ( html ) { chars = true; // Make sure we're not in a script or style element if ( !stack.last() || !specialElements[ stack.last() ] ) { // Comment if ( html.indexOf("<!--") === 0 ) { // comments containing -- are not allowed unless they terminate the comment index = html.indexOf("--", 4); if ( index >= 0 && html.lastIndexOf("-->", index) === index) { if (handler.comment) handler.comment( html.substring( 4, index ) ); html = html.substring( index + 3 ); chars = false; } // DOCTYPE } else if ( DOCTYPE_REGEXP.test(html) ) { match = html.match( DOCTYPE_REGEXP ); if ( match ) { html = html.replace( match[0], ''); chars = false; } // end tag } else if ( BEGING_END_TAGE_REGEXP.test(html) ) { match = html.match( END_TAG_REGEXP ); if ( match ) { html = html.substring( match[0].length ); match[0].replace( END_TAG_REGEXP, parseEndTag ); chars = false; } // start tag } else if ( BEGIN_TAG_REGEXP.test(html) ) { match = html.match( START_TAG_REGEXP ); if ( match ) { html = html.substring( match[0].length ); match[0].replace( START_TAG_REGEXP, parseStartTag ); chars = false; } } if ( chars ) { index = html.indexOf("<"); var text = index < 0 ? html : html.substring( 0, index ); html = index < 0 ? "" : html.substring( index ); if (handler.chars) handler.chars( decodeEntities(text) ); } } else { html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), function(all, text){ text = text.replace(COMMENT_REGEXP, "$1").replace(CDATA_REGEXP, "$1"); if (handler.chars) handler.chars( decodeEntities(text) ); return ""; }); parseEndTag( "", stack.last() ); } if ( html == last ) { throw $sanitizeMinErr('badparse', "The sanitizer was unable to parse the following block " + "of html: {0}", html); } last = html; } // Clean up any remaining tags parseEndTag(); function parseStartTag( tag, tagName, rest, unary ) { tagName = angular.lowercase(tagName); if ( blockElements[ tagName ] ) { while ( stack.last() && inlineElements[ stack.last() ] ) { parseEndTag( "", stack.last() ); } } if ( optionalEndTagElements[ tagName ] && stack.last() == tagName ) { parseEndTag( "", tagName ); } unary = voidElements[ tagName ] || !!unary; if ( !unary ) stack.push( tagName ); var attrs = {}; rest.replace(ATTR_REGEXP, function(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) { var value = doubleQuotedValue || singleQuotedValue || unquotedValue || ''; attrs[name] = decodeEntities(value); }); if (handler.start) handler.start( tagName, attrs, unary ); } function parseEndTag( tag, tagName ) { var pos = 0, i; tagName = angular.lowercase(tagName); if ( tagName ) // Find the closest opened tag of the same type for ( pos = stack.length - 1; pos >= 0; pos-- ) if ( stack[ pos ] == tagName ) break; if ( pos >= 0 ) { // Close all the open elements, up the stack for ( i = stack.length - 1; i >= pos; i-- ) if (handler.end) handler.end( stack[ i ] ); // Remove the open elements from the stack stack.length = pos; } } } var hiddenPre=document.createElement("pre"); var spaceRe = /^(\s*)([\s\S]*?)(\s*)$/; /** * decodes all entities into regular string * @param value * @returns {string} A string with decoded entities. */ function decodeEntities(value) { if (!value) { return ''; } // Note: IE8 does not preserve spaces at the start/end of innerHTML // so we must capture them and reattach them afterward var parts = spaceRe.exec(value); var spaceBefore = parts[1]; var spaceAfter = parts[3]; var content = parts[2]; if (content) { hiddenPre.innerHTML=content.replace(/</g,"&lt;"); // innerText depends on styling as it doesn't display hidden elements. // Therefore, it's better to use textContent not to cause unnecessary // reflows. However, IE<9 don't support textContent so the innerText // fallback is necessary. content = 'textContent' in hiddenPre ? hiddenPre.textContent : hiddenPre.innerText; } return spaceBefore + content + spaceAfter; } /** * Escapes all potentially dangerous characters, so that the * resulting string can be safely inserted into attribute or * element text. * @param value * @returns {string} escaped text */ function encodeEntities(value) { return value. replace(/&/g, '&amp;'). replace(SURROGATE_PAIR_REGEXP, function (value) { var hi = value.charCodeAt(0); var low = value.charCodeAt(1); return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';'; }). replace(NON_ALPHANUMERIC_REGEXP, function(value){ // unsafe chars are: \u0000-\u001f \u007f-\u009f \u00ad \u0600-\u0604 \u070f \u17b4 \u17b5 \u200c-\u200f \u2028-\u202f \u2060-\u206f \ufeff \ufff0-\uffff from jslint.com/lint.html // decimal values are: 0-31, 127-159, 173, 1536-1540, 1807, 6068, 6069, 8204-8207, 8232-8239, 8288-8303, 65279, 65520-65535 var c = value.charCodeAt(0); // if unsafe character encode if(c <= 159 || c == 173 || (c >= 1536 && c <= 1540) || c == 1807 || c == 6068 || c == 6069 || (c >= 8204 && c <= 8207) || (c >= 8232 && c <= 8239) || (c >= 8288 && c <= 8303) || c == 65279 || (c >= 65520 && c <= 65535)) return '&#' + c + ';'; return value; // avoids multilingual issues }). replace(/</g, '&lt;'). replace(/>/g, '&gt;'); } var trim = (function() { // native trim is way faster: http://jsperf.com/angular-trim-test // but IE doesn't have it... :-( // TODO: we should move this into IE/ES5 polyfill if (!String.prototype.trim) { return function(value) { return angular.isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value; }; } return function(value) { return angular.isString(value) ? value.trim() : value; }; })(); // Custom logic for accepting certain style options only - textAngular // Currently allows only the color attribute, all other attributes should be easily done through classes. function validStyles(styleAttr){ var result = ''; var styleArray = styleAttr.split(';'); angular.forEach(styleArray, function(value){ var v = value.split(':'); if(v.length == 2){ var key = trim(angular.lowercase(v[0])); var value = trim(angular.lowercase(v[1])); if( key === 'color' && ( value.match(/^rgb\([0-9%,\. ]*\)$/i) || value.match(/^rgba\([0-9%,\. ]*\)$/i) || value.match(/^hsl\([0-9%,\. ]*\)$/i) || value.match(/^hsla\([0-9%,\. ]*\)$/i) || value.match(/^#[0-9a-f]{3,6}$/i) || value.match(/^[a-z]*$/i) ) || key === 'text-align' && ( value === 'left' || value === 'right' || value === 'center' || value === 'justify' ) || key === 'float' && ( value === 'left' || value === 'right' || value === 'none' ) || (key === 'width' || key === 'height') && ( value.match(/[0-9\.]*(px|em|rem|%)/) ) ) result += key + ': ' + value + ';'; } }); return result; } // this function is used to manually allow specific attributes on specific tags with certain prerequisites function validCustomTag(tag, attrs, lkey, value){ // catch the div placeholder for the iframe replacement if (tag === 'img' && attrs['ta-insert-video']){ if(lkey === 'ta-insert-video' || lkey === 'allowfullscreen' || lkey === 'frameborder' || (lkey === 'contenteditble' && value === 'false')) return true; } return false; } /** * create an HTML/XML writer which writes to buffer * @param {Array} buf use buf.jain('') to get out sanitized html string * @returns {object} in the form of { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * } */ function htmlSanitizeWriter(buf, uriValidator){ var ignore = false; var out = angular.bind(buf, buf.push); return { start: function(tag, attrs, unary){ tag = angular.lowercase(tag); if (!ignore && specialElements[tag]) { ignore = tag; } if (!ignore && validElements[tag] === true) { out('<'); out(tag); angular.forEach(attrs, function(value, key){ var lkey=angular.lowercase(key); var isImage=(tag === 'img' && lkey === 'src') || (lkey === 'background'); if ((lkey === 'style' && (value = validStyles(value)) !== '') || validCustomTag(tag, attrs, lkey, value) || validAttrs[lkey] === true && (uriAttrs[lkey] !== true || uriValidator(value, isImage))) { out(' '); out(key); out('="'); out(encodeEntities(value)); out('"'); } }); out(unary ? '/>' : '>'); } }, end: function(tag){ tag = angular.lowercase(tag); if (!ignore && validElements[tag] === true) { out('</'); out(tag); out('>'); } if (tag == ignore) { ignore = false; } }, chars: function(chars){ if (!ignore) { out(encodeEntities(chars)); } } }; } // define ngSanitize module and register $sanitize service angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider); /* global sanitizeText: false */ /** * @ngdoc filter * @name linky * @function * * @description * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and * plain email address links. * * Requires the {@link ngSanitize `ngSanitize`} module to be installed. * * @param {string} text Input text. * @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in. * @returns {string} Html-linkified text. * * @usage <span ng-bind-html="linky_expression | linky"></span> * * @example <example module="ngSanitize" deps="angular-sanitize.js"> <file name="index.html"> <script> function Ctrl($scope) { $scope.snippet = 'Pretty text with some links:\n'+ 'http://angularjs.org/,\n'+ 'mailto:us@somewhere.org,\n'+ 'another@somewhere.org,\n'+ 'and one more: ftp://127.0.0.1/.'; $scope.snippetWithTarget = 'http://angularjs.org/'; } </script> <div ng-controller="Ctrl"> Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> <table> <tr> <td>Filter</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="linky-filter"> <td>linky filter</td> <td> <pre>&lt;div ng-bind-html="snippet | linky"&gt;<br>&lt;/div&gt;</pre> </td> <td> <div ng-bind-html="snippet | linky"></div> </td> </tr> <tr id="linky-target"> <td>linky target</td> <td> <pre>&lt;div ng-bind-html="snippetWithTarget | linky:'_blank'"&gt;<br>&lt;/div&gt;</pre> </td> <td> <div ng-bind-html="snippetWithTarget | linky:'_blank'"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng-bind="snippet"&gt;<br>&lt;/div&gt;</pre></td> <td><div ng-bind="snippet"></div></td> </tr> </table> </file> <file name="protractor.js" type="protractor"> it('should linkify the snippet with urls', function() { expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' + 'another@somewhere.org, and one more: ftp://127.0.0.1/.'); expect(element.all(by.css('#linky-filter a')).count()).toEqual(4); }); it('should not linkify snippet without the linky filter', function() { expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()). toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' + 'another@somewhere.org, and one more: ftp://127.0.0.1/.'); expect(element.all(by.css('#escaped-html a')).count()).toEqual(0); }); it('should update', function() { element(by.model('snippet')).clear(); element(by.model('snippet')).sendKeys('new http://link.'); expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). toBe('new http://link.'); expect(element.all(by.css('#linky-filter a')).count()).toEqual(1); expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()) .toBe('new http://link.'); }); it('should work with the target property', function() { expect(element(by.id('linky-target')). element(by.binding("snippetWithTarget | linky:'_blank'")).getText()). toBe('http://angularjs.org/'); expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank'); }); </file> </example> */ angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) { var LINKY_URL_REGEXP = /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>]/, MAILTO_REGEXP = /^mailto:/; return function(text, target) { if (!text) return text; var match; var raw = text; var html = []; var url; var i; while ((match = raw.match(LINKY_URL_REGEXP))) { // We can not end in these as they are sometimes found at the end of the sentence url = match[0]; // if we did not match ftp/http/mailto then assume mailto if (match[2] == match[3]) url = 'mailto:' + url; i = match.index; addText(raw.substr(0, i)); addLink(url, match[0].replace(MAILTO_REGEXP, '')); raw = raw.substring(i + match[0].length); } addText(raw); return $sanitize(html.join('')); function addText(text) { if (!text) { return; } html.push(sanitizeText(text)); } function addLink(url, text) { html.push('<a '); if (angular.isDefined(target)) { html.push('target="'); html.push(target); html.push('" '); } html.push('href="'); html.push(url); html.push('">'); addText(text); html.push('</a>'); } }; }]); })(window, window.angular);
YUI.add('node-scroll-info', function (Y, NAME) { /*jshint onevar:false */ /** Provides the ScrollInfo Node plugin, which exposes convenient events and methods related to scrolling. @module node-scroll-info @since 3.7.0 **/ /** Provides convenient events and methods related to scrolling. This could be used, for example, to implement infinite scrolling, or to lazy-load content based on the current scroll position. ### Example var body = Y.one('body'); body.plug(Y.Plugin.ScrollInfo); body.scrollInfo.on('scrollToBottom', function (e) { // Load more content when the user scrolls to the bottom of the page. }); @class Plugin.ScrollInfo @extends Plugin.Base @since 3.7.0 **/ var doc = Y.config.doc, win = Y.config.win; /** Fired when the user scrolls within the host node. This event (like all scroll events exposed by ScrollInfo) is throttled and fired only after the number of milliseconds specified by the `scrollDelay` attribute have passed in order to prevent thrashing. This event passes along the event facade for the standard DOM `scroll` event and mixes in the following additional properties. @event scroll @param {Boolean} atBottom Whether the current scroll position is at the bottom of the scrollable region. @param {Boolean} atLeft Whether the current scroll position is at the extreme left of the scrollable region. @param {Boolean} atRight Whether the current scroll position is at the extreme right of the scrollable region. @param {Boolean} atTop Whether the current scroll position is at the top of the scrollable region. @param {Boolean} isScrollDown `true` if the user scrolled down. @param {Boolean} isScrollLeft `true` if the user scrolled left. @param {Boolean} isScrollRight `true` if the user scrolled right. @param {Boolean} isScrollUp `true` if the user scrolled up. @param {Number} scrollBottom Y value of the bottom-most onscreen pixel of the scrollable region. @param {Number} scrollHeight Total height in pixels of the scrollable region, including offscreen pixels. @param {Number} scrollLeft X value of the left-most onscreen pixel of the scrollable region. @param {Number} scrollRight X value of the right-most onscreen pixel of the scrollable region. @param {Number} scrollTop Y value of the top-most onscreen pixel of the scrollable region. @param {Number} scrollWidth Total width in pixels of the scrollable region, including offscreen pixels. @see scrollDelay @see scrollMargin **/ var EVT_SCROLL = 'scroll', /** Fired when the user scrolls down within the host node. This event provides the same event facade as the `scroll` event. See that event for details. @event scrollDown @see scroll **/ EVT_SCROLL_DOWN = 'scrollDown', /** Fired when the user scrolls left within the host node. This event provides the same event facade as the `scroll` event. See that event for details. @event scrollLeft @see scroll **/ EVT_SCROLL_LEFT = 'scrollLeft', /** Fired when the user scrolls right within the host node. This event provides the same event facade as the `scroll` event. See that event for details. @event scrollRight @see scroll **/ EVT_SCROLL_RIGHT = 'scrollRight', /** Fired when the user scrolls up within the host node. This event provides the same event facade as the `scroll` event. See that event for details. @event scrollUp @see scroll **/ EVT_SCROLL_UP = 'scrollUp', /** Fired when the user scrolls to the bottom of the scrollable region within the host node. This event provides the same event facade as the `scroll` event. See that event for details. @event scrollToBottom @see scroll **/ EVT_SCROLL_TO_BOTTOM = 'scrollToBottom', /** Fired when the user scrolls to the extreme left of the scrollable region within the host node. This event provides the same event facade as the `scroll` event. See that event for details. @event scrollToLeft @see scroll **/ EVT_SCROLL_TO_LEFT = 'scrollToLeft', /** Fired when the user scrolls to the extreme right of the scrollable region within the host node. This event provides the same event facade as the `scroll` event. See that event for details. @event scrollToRight @see scroll **/ EVT_SCROLL_TO_RIGHT = 'scrollToRight', /** Fired when the user scrolls to the top of the scrollable region within the host node. This event provides the same event facade as the `scroll` event. See that event for details. @event scrollToTop @see scroll **/ EVT_SCROLL_TO_TOP = 'scrollToTop'; Y.Plugin.ScrollInfo = Y.Base.create('scrollInfoPlugin', Y.Plugin.Base, [], { // -- Protected Properties ------------------------------------------------- /** Height of the visible region of the host node in pixels. If the host node is the body, this will be the same as `_winHeight`. @property {Number} _height @protected **/ /** Whether or not the host node is the `<body>` element. @property {Boolean} _hostIsBody @protected **/ /** Width of the visible region of the host node in pixels. If the host node is the body, this will be the same as `_winWidth`. @property {Number} _width @protected **/ /** Height of the viewport in pixels. @property {Number} _winHeight @protected **/ /** Width of the viewport in pixels. @property {Number} _winWidth @protected **/ // -- Lifecycle Methods ---------------------------------------------------- initializer: function (config) { // Cache for quicker lookups in the critical path. this._host = config.host; this._hostIsBody = this._host.get('nodeName').toLowerCase() === 'body'; this._scrollDelay = this.get('scrollDelay'); this._scrollMargin = this.get('scrollMargin'); this._scrollNode = this._getScrollNode(); this.refreshDimensions(); this._lastScroll = this.getScrollInfo(); this._bind(); }, destructor: function () { new Y.EventHandle(this._events).detach(); this._events = null; }, // -- Public Methods ------------------------------------------------------- /** Returns a NodeList containing all offscreen nodes inside the host node that match the given CSS selector. An offscreen node is any node that is entirely outside the visible (onscreen) region of the host node based on the current scroll location. @method getOffscreenNodes @param {String} [selector] CSS selector. If omitted, all offscreen nodes will be returned. @param {Number} [margin] Additional margin in pixels beyond the actual onscreen region that should be considered "onscreen" for the purposes of this query. Defaults to the value of the `scrollMargin` attribute. @return {NodeList} Offscreen nodes matching _selector_. @see scrollMargin **/ getOffscreenNodes: function (selector, margin) { if (typeof margin === 'undefined') { margin = this._scrollMargin; } var elements = Y.Selector.query(selector || '*', this._host._node); return new Y.NodeList(Y.Array.filter(elements, function (el) { return !this._isElementOnscreen(el, margin); }, this)); }, /** Returns a NodeList containing all onscreen nodes inside the host node that match the given CSS selector. An onscreen node is any node that is fully or partially within the visible (onscreen) region of the host node based on the current scroll location. @method getOnscreenNodes @param {String} [selector] CSS selector. If omitted, all onscreen nodes will be returned. @param {Number} [margin] Additional margin in pixels beyond the actual onscreen region that should be considered "onscreen" for the purposes of this query. Defaults to the value of the `scrollMargin` attribute. @return {NodeList} Onscreen nodes matching _selector_. @see scrollMargin **/ getOnscreenNodes: function (selector, margin) { if (typeof margin === 'undefined') { margin = this._scrollMargin; } var elements = Y.Selector.query(selector || '*', this._host._node); return new Y.NodeList(Y.Array.filter(elements, function (el) { return this._isElementOnscreen(el, margin); }, this)); }, /** Returns an object hash containing information about the current scroll position of the host node. This is the same information that's mixed into the event facade of the `scroll` event and other scroll-related events. @method getScrollInfo @return {Object} Object hash containing information about the current scroll position. See the `scroll` event for details on what properties this object contains. @see scroll **/ getScrollInfo: function () { var domNode = this._scrollNode, lastScroll = this._lastScroll, margin = this._scrollMargin, scrollLeft = domNode.scrollLeft, scrollHeight = domNode.scrollHeight, scrollTop = domNode.scrollTop, scrollWidth = domNode.scrollWidth, scrollBottom = scrollTop + this._height, scrollRight = scrollLeft + this._width; return { atBottom: scrollBottom > (scrollHeight - margin), atLeft : scrollLeft < margin, atRight : scrollRight > (scrollWidth - margin), atTop : scrollTop < margin, isScrollDown : lastScroll && scrollTop > lastScroll.scrollTop, isScrollLeft : lastScroll && scrollLeft < lastScroll.scrollLeft, isScrollRight: lastScroll && scrollLeft > lastScroll.scrollLeft, isScrollUp : lastScroll && scrollTop < lastScroll.scrollTop, scrollBottom: scrollBottom, scrollHeight: scrollHeight, scrollLeft : scrollLeft, scrollRight : scrollRight, scrollTop : scrollTop, scrollWidth : scrollWidth }; }, /** Returns `true` if _node_ is at least partially onscreen within the host node, `false` otherwise. @method isNodeOnscreen @param {HTMLElement|Node|String} node Node or selector to check. @param {Number} [margin] Additional margin in pixels beyond the actual onscreen region that should be considered "onscreen" for the purposes of this query. Defaults to the value of the `scrollMargin` attribute. @return {Boolean} `true` if _node_ is at least partially onscreen within the host node, `false` otherwise. @since 3.11.0 **/ isNodeOnscreen: function (node, margin) { node = Y.one(node); return !!(node && this._isElementOnscreen(node._node, margin)); }, /** Refreshes cached position, height, and width dimensions for the host node. If the host node is the body, then the viewport height and width will be used. This info is cached to improve performance during scroll events, since it's expensive to touch the DOM for these values. Dimensions are automatically refreshed whenever the browser is resized, but if you change the dimensions or position of the host node in JS, you may need to call `refreshDimensions()` manually to cache the new dimensions. @method refreshDimensions **/ refreshDimensions: function () { var docEl = doc.documentElement; // On iOS devices, documentElement.clientHeight/Width aren't reliable, // but window.innerHeight/Width are. The dom-screen module's viewport // size methods don't account for this, which is why we do it here. if (Y.UA.ios) { this._winHeight = win.innerHeight; this._winWidth = win.innerWidth; } else { this._winHeight = docEl.clientHeight; this._winWidth = docEl.clientWidth; } if (this._hostIsBody) { this._height = this._winHeight; this._width = this._winWidth; } else { this._height = this._scrollNode.clientHeight; this._width = this._scrollNode.clientWidth; } this._refreshHostBoundingRect(); }, // -- Protected Methods ---------------------------------------------------- /** Binds event handlers. @method _bind @protected **/ _bind: function () { var winNode = Y.one('win'); this._events = [ this.after({ scrollDelayChange : this._afterScrollDelayChange, scrollMarginChange: this._afterScrollMarginChange }), winNode.on('windowresize', this._afterResize, this) ]; // If the host node is the body, listen for the scroll event on the // window, since <body> doesn't have a scroll event. if (this._hostIsBody) { this._events.push(winNode.after('scroll', this._afterHostScroll, this)); } else { // The host node is not the body, but we still need to listen for // window scroll events so we can determine whether nodes are // onscreen. this._events.push( winNode.after('scroll', this._afterWindowScroll, this), this._host.after('scroll', this._afterHostScroll, this) ); } }, /** Returns the DOM node that should be used to lookup scroll coordinates. In some browsers, the `<body>` element doesn't return scroll coordinates, and the documentElement must be used instead; this method takes care of determining which node should be used. @method _getScrollNode @return {HTMLElement} DOM node. @protected **/ _getScrollNode: function () { // WebKit returns scroll coordinates on the body element, but other // browsers don't, so we have to use the documentElement. return this._hostIsBody && !Y.UA.webkit ? doc.documentElement : Y.Node.getDOMNode(this._host); }, /** Underlying element-based implementation for `isNodeOnscreen()`. @method _isElementOnscreen @param {HTMLElement} el HTML element. @param {Number} [margin] Additional margin in pixels beyond the actual onscreen region that should be considered "onscreen" for the purposes of this query. Defaults to the value of the `scrollMargin` attribute. @return {Boolean} `true` if _el_ is at least partially onscreen within the host node, `false` otherwise. @protected @since 3.11.0 **/ _isElementOnscreen: function (el, margin) { var hostRect = this._hostRect, rect = el.getBoundingClientRect(); if (typeof margin === 'undefined') { margin = this._scrollMargin; } // Determine whether any part of _el_ is within the visible region of // the host element or the specified margin around the visible region of // the host element. return !(rect.top > hostRect.bottom + margin || rect.bottom < hostRect.top - margin || rect.right < hostRect.left - margin || rect.left > hostRect.right + margin); }, /** Caches the bounding rect of the host node. If the host node is the body, the bounding rect will be faked to represent the dimensions of the viewport, since the actual body dimensions may extend beyond the viewport and we only care about the visible region. @method _refreshHostBoundingRect @protected **/ _refreshHostBoundingRect: function () { var winHeight = this._winHeight, winWidth = this._winWidth, hostRect; if (this._hostIsBody) { hostRect = { bottom: winHeight, height: winHeight, left : 0, right : winWidth, top : 0, width : winWidth }; this._isHostOnscreen = true; } else { hostRect = this._scrollNode.getBoundingClientRect(); } this._hostRect = hostRect; }, /** Mixes detailed scroll information into the given DOM `scroll` event facade and fires appropriate local events. @method _triggerScroll @param {EventFacade} e Event facade from the DOM `scroll` event. @protected **/ _triggerScroll: function (e) { var info = this.getScrollInfo(), facade = Y.merge(e, info), lastScroll = this._lastScroll; this._lastScroll = info; this.fire(EVT_SCROLL, facade); if (info.isScrollLeft) { this.fire(EVT_SCROLL_LEFT, facade); } else if (info.isScrollRight) { this.fire(EVT_SCROLL_RIGHT, facade); } if (info.isScrollUp) { this.fire(EVT_SCROLL_UP, facade); } else if (info.isScrollDown) { this.fire(EVT_SCROLL_DOWN, facade); } if (info.atBottom && (!lastScroll.atBottom || info.scrollHeight > lastScroll.scrollHeight)) { this.fire(EVT_SCROLL_TO_BOTTOM, facade); } if (info.atLeft && !lastScroll.atLeft) { this.fire(EVT_SCROLL_TO_LEFT, facade); } if (info.atRight && (!lastScroll.atRight || info.scrollWidth > lastScroll.scrollWidth)) { this.fire(EVT_SCROLL_TO_RIGHT, facade); } if (info.atTop && !lastScroll.atTop) { this.fire(EVT_SCROLL_TO_TOP, facade); } }, // -- Protected Event Handlers --------------------------------------------- /** Handles DOM `scroll` events on the host node. @method _afterHostScroll @param {EventFacade} e @protected **/ _afterHostScroll: function (e) { var self = this; clearTimeout(this._scrollTimeout); this._scrollTimeout = setTimeout(function () { self._triggerScroll(e); }, this._scrollDelay); }, /** Handles browser resize events. @method _afterResize @protected **/ _afterResize: function () { this.refreshDimensions(); }, /** Caches the `scrollDelay` value after that attribute changes to allow quicker lookups in critical path code. @method _afterScrollDelayChange @param {EventFacade} e @protected **/ _afterScrollDelayChange: function (e) { this._scrollDelay = e.newVal; }, /** Caches the `scrollMargin` value after that attribute changes to allow quicker lookups in critical path code. @method _afterScrollMarginChange @param {EventFacade} e @protected **/ _afterScrollMarginChange: function (e) { this._scrollMargin = e.newVal; }, /** Handles DOM `scroll` events on the window. @method _afterWindowScroll @param {EventFacade} e @protected **/ _afterWindowScroll: function () { this._refreshHostBoundingRect(); } }, { NS: 'scrollInfo', ATTRS: { /** Number of milliseconds to wait after a native `scroll` event before firing local scroll events. If another native scroll event occurs during this time, previous events will be ignored. This ensures that we don't fire thousands of events when the user is scrolling quickly. @attribute scrollDelay @type Number @default 50 **/ scrollDelay: { value: 50 }, /** Additional margin in pixels beyond the onscreen region of the host node that should be considered "onscreen". For example, if set to 50, then a `scrollToBottom` event would be fired when the user scrolls to within 50 pixels of the bottom of the scrollable region, even if they don't actually scroll completely to the very bottom pixel. This margin also applies to the `getOffscreenNodes()` and `getOnscreenNodes()` methods by default. @attribute scrollMargin @type Number @default 50 **/ scrollMargin: { value: 50 } } }); }, '@VERSION@', {"requires": ["array-extras", "base-build", "event-resize", "node-pluginhost", "plugin", "selector"]});
/** * angular-strap * @version v2.2.3 - 2015-05-20 * @link http://mgcrea.github.io/angular-strap * @author Olivier Louvignes <olivier@mg-crea.com> (https://github.com/mgcrea) * @license MIT License, http://www.opensource.org/licenses/MIT */ 'use strict'; angular.module('mgcrea.ngStrap.timepicker', [ 'mgcrea.ngStrap.helpers.dateParser', 'mgcrea.ngStrap.helpers.dateFormatter', 'mgcrea.ngStrap.tooltip' ]).provider('$timepicker', function() { var defaults = this.defaults = { animation: 'am-fade', prefixClass: 'timepicker', placement: 'bottom-left', template: 'timepicker/timepicker.tpl.html', trigger: 'focus', container: false, keyboard: true, html: false, delay: 0, useNative: true, timeType: 'date', timeFormat: 'shortTime', timezone: null, modelTimeFormat: null, autoclose: false, minTime: -Infinity, maxTime: +Infinity, length: 5, hourStep: 1, minuteStep: 5, secondStep: 5, roundDisplay: false, iconUp: 'glyphicon glyphicon-chevron-up', iconDown: 'glyphicon glyphicon-chevron-down', arrowBehavior: 'pager' }; this.$get = [ '$window', '$document', '$rootScope', '$sce', '$dateFormatter', '$tooltip', '$timeout', function($window, $document, $rootScope, $sce, $dateFormatter, $tooltip, $timeout) { var bodyEl = angular.element($window.document.body); var isNative = /(ip(a|o)d|iphone|android)/gi.test($window.navigator.userAgent); var isTouch = 'createTouch' in $window.document && isNative; if (!defaults.lang) defaults.lang = $dateFormatter.getDefaultLocale(); function timepickerFactory(element, controller, config) { var $timepicker = $tooltip(element, angular.extend({}, defaults, config)); var parentScope = config.scope; var options = $timepicker.$options; var scope = $timepicker.$scope; var lang = options.lang; var formatDate = function(date, format, timezone) { return $dateFormatter.formatDate(date, format, lang, timezone); }; function floorMinutes(time) { var coeff = 1e3 * 60 * options.minuteStep; return new Date(Math.floor(time.getTime() / coeff) * coeff); } var selectedIndex = 0; var defaultDate = options.roundDisplay ? floorMinutes(new Date()) : new Date(); var startDate = controller.$dateValue || defaultDate; var viewDate = { hour: startDate.getHours(), meridian: startDate.getHours() < 12, minute: startDate.getMinutes(), second: startDate.getSeconds(), millisecond: startDate.getMilliseconds() }; var format = $dateFormatter.getDatetimeFormat(options.timeFormat, lang); var hoursFormat = $dateFormatter.hoursFormat(format), timeSeparator = $dateFormatter.timeSeparator(format), minutesFormat = $dateFormatter.minutesFormat(format), secondsFormat = $dateFormatter.secondsFormat(format), showSeconds = $dateFormatter.showSeconds(format), showAM = $dateFormatter.showAM(format); scope.$iconUp = options.iconUp; scope.$iconDown = options.iconDown; scope.$select = function(date, index) { $timepicker.select(date, index); }; scope.$moveIndex = function(value, index) { $timepicker.$moveIndex(value, index); }; scope.$switchMeridian = function(date) { $timepicker.switchMeridian(date); }; $timepicker.update = function(date) { if (angular.isDate(date) && !isNaN(date.getTime())) { $timepicker.$date = date; angular.extend(viewDate, { hour: date.getHours(), minute: date.getMinutes(), second: date.getSeconds(), millisecond: date.getMilliseconds() }); $timepicker.$build(); } else if (!$timepicker.$isBuilt) { $timepicker.$build(); } }; $timepicker.select = function(date, index, keep) { if (!controller.$dateValue || isNaN(controller.$dateValue.getTime())) controller.$dateValue = new Date(1970, 0, 1); if (!angular.isDate(date)) date = new Date(date); if (index === 0) controller.$dateValue.setHours(date.getHours()); else if (index === 1) controller.$dateValue.setMinutes(date.getMinutes()); else if (index === 2) controller.$dateValue.setSeconds(date.getSeconds()); controller.$setViewValue(angular.copy(controller.$dateValue)); controller.$render(); if (options.autoclose && !keep) { $timeout(function() { $timepicker.hide(true); }); } }; $timepicker.switchMeridian = function(date) { if (!controller.$dateValue || isNaN(controller.$dateValue.getTime())) { return; } var hours = (date || controller.$dateValue).getHours(); controller.$dateValue.setHours(hours < 12 ? hours + 12 : hours - 12); controller.$setViewValue(angular.copy(controller.$dateValue)); controller.$render(); }; $timepicker.$build = function() { var i, midIndex = scope.midIndex = parseInt(options.length / 2, 10); var hours = [], hour; for (i = 0; i < options.length; i++) { hour = new Date(1970, 0, 1, viewDate.hour - (midIndex - i) * options.hourStep); hours.push({ date: hour, label: formatDate(hour, hoursFormat), selected: $timepicker.$date && $timepicker.$isSelected(hour, 0), disabled: $timepicker.$isDisabled(hour, 0) }); } var minutes = [], minute; for (i = 0; i < options.length; i++) { minute = new Date(1970, 0, 1, 0, viewDate.minute - (midIndex - i) * options.minuteStep); minutes.push({ date: minute, label: formatDate(minute, minutesFormat), selected: $timepicker.$date && $timepicker.$isSelected(minute, 1), disabled: $timepicker.$isDisabled(minute, 1) }); } var seconds = [], second; for (i = 0; i < options.length; i++) { second = new Date(1970, 0, 1, 0, 0, viewDate.second - (midIndex - i) * options.secondStep); seconds.push({ date: second, label: formatDate(second, secondsFormat), selected: $timepicker.$date && $timepicker.$isSelected(second, 2), disabled: $timepicker.$isDisabled(second, 2) }); } var rows = []; for (i = 0; i < options.length; i++) { if (showSeconds) { rows.push([ hours[i], minutes[i], seconds[i] ]); } else { rows.push([ hours[i], minutes[i] ]); } } scope.rows = rows; scope.showSeconds = showSeconds; scope.showAM = showAM; scope.isAM = ($timepicker.$date || hours[midIndex].date).getHours() < 12; scope.timeSeparator = timeSeparator; $timepicker.$isBuilt = true; }; $timepicker.$isSelected = function(date, index) { if (!$timepicker.$date) return false; else if (index === 0) { return date.getHours() === $timepicker.$date.getHours(); } else if (index === 1) { return date.getMinutes() === $timepicker.$date.getMinutes(); } else if (index === 2) { return date.getSeconds() === $timepicker.$date.getSeconds(); } }; $timepicker.$isDisabled = function(date, index) { var selectedTime; if (index === 0) { selectedTime = date.getTime() + viewDate.minute * 6e4 + viewDate.second * 1e3; } else if (index === 1) { selectedTime = date.getTime() + viewDate.hour * 36e5 + viewDate.second * 1e3; } else if (index === 2) { selectedTime = date.getTime() + viewDate.hour * 36e5 + viewDate.minute * 6e4; } return selectedTime < options.minTime * 1 || selectedTime > options.maxTime * 1; }; scope.$arrowAction = function(value, index) { if (options.arrowBehavior === 'picker') { $timepicker.$setTimeByStep(value, index); } else { $timepicker.$moveIndex(value, index); } }; $timepicker.$setTimeByStep = function(value, index) { var newDate = new Date($timepicker.$date); var hours = newDate.getHours(), hoursLength = formatDate(newDate, hoursFormat).length; var minutes = newDate.getMinutes(), minutesLength = formatDate(newDate, minutesFormat).length; var seconds = newDate.getSeconds(), secondsLength = formatDate(newDate, secondsFormat).length; if (index === 0) { newDate.setHours(hours - parseInt(options.hourStep, 10) * value); } else if (index === 1) { newDate.setMinutes(minutes - parseInt(options.minuteStep, 10) * value); } else if (index === 2) { newDate.setSeconds(seconds - parseInt(options.secondStep, 10) * value); } $timepicker.select(newDate, index, true); }; $timepicker.$moveIndex = function(value, index) { var targetDate; if (index === 0) { targetDate = new Date(1970, 0, 1, viewDate.hour + value * options.length, viewDate.minute, viewDate.second); angular.extend(viewDate, { hour: targetDate.getHours() }); } else if (index === 1) { targetDate = new Date(1970, 0, 1, viewDate.hour, viewDate.minute + value * options.length * options.minuteStep, viewDate.second); angular.extend(viewDate, { minute: targetDate.getMinutes() }); } else if (index === 2) { targetDate = new Date(1970, 0, 1, viewDate.hour, viewDate.minute, viewDate.second + value * options.length * options.secondStep); angular.extend(viewDate, { second: targetDate.getSeconds() }); } $timepicker.$build(); }; $timepicker.$onMouseDown = function(evt) { if (evt.target.nodeName.toLowerCase() !== 'input') evt.preventDefault(); evt.stopPropagation(); if (isTouch) { var targetEl = angular.element(evt.target); if (targetEl[0].nodeName.toLowerCase() !== 'button') { targetEl = targetEl.parent(); } targetEl.triggerHandler('click'); } }; $timepicker.$onKeyDown = function(evt) { if (!/(38|37|39|40|13)/.test(evt.keyCode) || evt.shiftKey || evt.altKey) return; evt.preventDefault(); evt.stopPropagation(); if (evt.keyCode === 13) return $timepicker.hide(true); var newDate = new Date($timepicker.$date); var hours = newDate.getHours(), hoursLength = formatDate(newDate, hoursFormat).length; var minutes = newDate.getMinutes(), minutesLength = formatDate(newDate, minutesFormat).length; var seconds = newDate.getSeconds(), secondsLength = formatDate(newDate, secondsFormat).length; var sepLength = 1; var lateralMove = /(37|39)/.test(evt.keyCode); var count = 2 + showSeconds * 1 + showAM * 1; if (lateralMove) { if (evt.keyCode === 37) selectedIndex = selectedIndex < 1 ? count - 1 : selectedIndex - 1; else if (evt.keyCode === 39) selectedIndex = selectedIndex < count - 1 ? selectedIndex + 1 : 0; } var selectRange = [ 0, hoursLength ]; var incr = 0; if (evt.keyCode === 38) incr = -1; if (evt.keyCode === 40) incr = +1; var isSeconds = selectedIndex === 2 && showSeconds; var isMeridian = selectedIndex === 2 && !showSeconds || selectedIndex === 3 && showSeconds; if (selectedIndex === 0) { newDate.setHours(hours + incr * parseInt(options.hourStep, 10)); hoursLength = formatDate(newDate, hoursFormat).length; selectRange = [ 0, hoursLength ]; } else if (selectedIndex === 1) { newDate.setMinutes(minutes + incr * parseInt(options.minuteStep, 10)); minutesLength = formatDate(newDate, minutesFormat).length; selectRange = [ hoursLength + sepLength, minutesLength ]; } else if (isSeconds) { newDate.setSeconds(seconds + incr * parseInt(options.secondStep, 10)); secondsLength = formatDate(newDate, secondsFormat).length; selectRange = [ hoursLength + sepLength + minutesLength + sepLength, secondsLength ]; } else if (isMeridian) { if (!lateralMove) $timepicker.switchMeridian(); selectRange = [ hoursLength + sepLength + minutesLength + sepLength + (secondsLength + sepLength) * showSeconds, 2 ]; } $timepicker.select(newDate, selectedIndex, true); createSelection(selectRange[0], selectRange[1]); parentScope.$digest(); }; function createSelection(start, length) { var end = start + length; if (element[0].createTextRange) { var selRange = element[0].createTextRange(); selRange.collapse(true); selRange.moveStart('character', start); selRange.moveEnd('character', end); selRange.select(); } else if (element[0].setSelectionRange) { element[0].setSelectionRange(start, end); } else if (angular.isUndefined(element[0].selectionStart)) { element[0].selectionStart = start; element[0].selectionEnd = end; } } function focusElement() { element[0].focus(); } var _init = $timepicker.init; $timepicker.init = function() { if (isNative && options.useNative) { element.prop('type', 'time'); element.css('-webkit-appearance', 'textfield'); return; } else if (isTouch) { element.prop('type', 'text'); element.attr('readonly', 'true'); element.on('click', focusElement); } _init(); }; var _destroy = $timepicker.destroy; $timepicker.destroy = function() { if (isNative && options.useNative) { element.off('click', focusElement); } _destroy(); }; var _show = $timepicker.show; $timepicker.show = function() { _show(); $timeout(function() { $timepicker.$element.on(isTouch ? 'touchstart' : 'mousedown', $timepicker.$onMouseDown); if (options.keyboard) { element.on('keydown', $timepicker.$onKeyDown); } }, 0, false); }; var _hide = $timepicker.hide; $timepicker.hide = function(blur) { if (!$timepicker.$isShown) return; $timepicker.$element.off(isTouch ? 'touchstart' : 'mousedown', $timepicker.$onMouseDown); if (options.keyboard) { element.off('keydown', $timepicker.$onKeyDown); } _hide(blur); }; return $timepicker; } timepickerFactory.defaults = defaults; return timepickerFactory; } ]; }).directive('bsTimepicker', [ '$window', '$parse', '$q', '$dateFormatter', '$dateParser', '$timepicker', function($window, $parse, $q, $dateFormatter, $dateParser, $timepicker) { var defaults = $timepicker.defaults; var isNative = /(ip(a|o)d|iphone|android)/gi.test($window.navigator.userAgent); var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout; return { restrict: 'EAC', require: 'ngModel', link: function postLink(scope, element, attr, controller) { var options = { scope: scope, controller: controller }; angular.forEach([ 'placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'autoclose', 'timeType', 'timeFormat', 'timezone', 'modelTimeFormat', 'useNative', 'hourStep', 'minuteStep', 'secondStep', 'length', 'arrowBehavior', 'iconUp', 'iconDown', 'roundDisplay', 'id', 'prefixClass', 'prefixEvent' ], function(key) { if (angular.isDefined(attr[key])) options[key] = attr[key]; }); var falseValueRegExp = /^(false|0|)$/i; angular.forEach([ 'html', 'container', 'autoclose', 'useNative', 'roundDisplay' ], function(key) { if (angular.isDefined(attr[key]) && falseValueRegExp.test(attr[key])) options[key] = false; }); attr.bsShow && scope.$watch(attr.bsShow, function(newValue, oldValue) { if (!timepicker || !angular.isDefined(newValue)) return; if (angular.isString(newValue)) newValue = !!newValue.match(/true|,?(timepicker),?/i); newValue === true ? timepicker.show() : timepicker.hide(); }); if (isNative && (options.useNative || defaults.useNative)) options.timeFormat = 'HH:mm'; var timepicker = $timepicker(element, controller, options); options = timepicker.$options; var lang = options.lang; var formatDate = function(date, format, timezone) { return $dateFormatter.formatDate(date, format, lang, timezone); }; var dateParser = $dateParser({ format: options.timeFormat, lang: lang }); angular.forEach([ 'minTime', 'maxTime' ], function(key) { angular.isDefined(attr[key]) && attr.$observe(key, function(newValue) { timepicker.$options[key] = dateParser.getTimeForAttribute(key, newValue); !isNaN(timepicker.$options[key]) && timepicker.$build(); validateAgainstMinMaxTime(controller.$dateValue); }); }); scope.$watch(attr.ngModel, function(newValue, oldValue) { timepicker.update(controller.$dateValue); }, true); function validateAgainstMinMaxTime(parsedTime) { if (!angular.isDate(parsedTime)) return; var isMinValid = isNaN(options.minTime) || new Date(parsedTime.getTime()).setFullYear(1970, 0, 1) >= options.minTime; var isMaxValid = isNaN(options.maxTime) || new Date(parsedTime.getTime()).setFullYear(1970, 0, 1) <= options.maxTime; var isValid = isMinValid && isMaxValid; controller.$setValidity('date', isValid); controller.$setValidity('min', isMinValid); controller.$setValidity('max', isMaxValid); if (!isValid) { return; } controller.$dateValue = parsedTime; } controller.$parsers.unshift(function(viewValue) { var date; if (!viewValue) { controller.$setValidity('date', true); return null; } var parsedTime = angular.isDate(viewValue) ? viewValue : dateParser.parse(viewValue, controller.$dateValue); if (!parsedTime || isNaN(parsedTime.getTime())) { controller.$setValidity('date', false); return; } else { validateAgainstMinMaxTime(parsedTime); } if (options.timeType === 'string') { date = dateParser.timezoneOffsetAdjust(parsedTime, options.timezone, true); return formatDate(date, options.modelTimeFormat || options.timeFormat); } date = dateParser.timezoneOffsetAdjust(controller.$dateValue, options.timezone, true); if (options.timeType === 'number') { return date.getTime(); } else if (options.timeType === 'unix') { return date.getTime() / 1e3; } else if (options.timeType === 'iso') { return date.toISOString(); } else { return new Date(date); } }); controller.$formatters.push(function(modelValue) { var date; if (angular.isUndefined(modelValue) || modelValue === null) { date = NaN; } else if (angular.isDate(modelValue)) { date = modelValue; } else if (options.timeType === 'string') { date = dateParser.parse(modelValue, null, options.modelTimeFormat); } else if (options.timeType === 'unix') { date = new Date(modelValue * 1e3); } else { date = new Date(modelValue); } controller.$dateValue = dateParser.timezoneOffsetAdjust(date, options.timezone); return getTimeFormattedString(); }); controller.$render = function() { element.val(getTimeFormattedString()); }; function getTimeFormattedString() { return !controller.$dateValue || isNaN(controller.$dateValue.getTime()) ? '' : formatDate(controller.$dateValue, options.timeFormat); } scope.$on('$destroy', function() { if (timepicker) timepicker.destroy(); options = null; timepicker = null; }); } }; } ]);
var SourceMapConsumer = require('source-map').SourceMapConsumer; var fs = require('fs'); var path = require('path'); var http = require('http'); var https = require('https'); var url = require('url'); var override = require('../utils/object.js').override; var MAP_MARKER = /\/\*# sourceMappingURL=(\S+) \*\//; var REMOTE_RESOURCE = /^(https?:)?\/\//; var DATA_URI = /^data:(\S*?)?(;charset=[^;]+)?(;[^,]+?)?,(.+)/; var unescape = global.unescape; function InputSourceMapStore(outerContext) { this.options = outerContext.options; this.errors = outerContext.errors; this.warnings = outerContext.warnings; this.sourceTracker = outerContext.sourceTracker; this.timeout = this.options.inliner.timeout; this.requestOptions = this.options.inliner.request; this.localOnly = outerContext.localOnly; this.relativeTo = outerContext.options.target || process.cwd(); this.maps = {}; this.sourcesContent = {}; } function fromString(self, _, whenDone) { self.trackLoaded(undefined, undefined, self.options.sourceMap); return whenDone(); } function fromSource(self, data, whenDone, context) { var nextAt = 0; function proceedToNext() { context.cursor += nextAt + 1; fromSource(self, data, whenDone, context); } while (context.cursor < data.length) { var fragment = data.substring(context.cursor); var markerStartMatch = self.sourceTracker.nextStart(fragment) || { index: -1 }; var markerEndMatch = self.sourceTracker.nextEnd(fragment) || { index: -1 }; var mapMatch = MAP_MARKER.exec(fragment) || { index: -1 }; var sourceMapFile = mapMatch[1]; nextAt = data.length; if (markerStartMatch.index > -1) nextAt = markerStartMatch.index; if (markerEndMatch.index > -1 && markerEndMatch.index < nextAt) nextAt = markerEndMatch.index; if (mapMatch.index > -1 && mapMatch.index < nextAt) nextAt = mapMatch.index; if (nextAt == data.length) break; if (nextAt == markerStartMatch.index) { context.files.push(markerStartMatch.filename); } else if (nextAt == markerEndMatch.index) { context.files.pop(); } else if (nextAt == mapMatch.index) { var isRemote = /^https?:\/\//.test(sourceMapFile) || /^\/\//.test(sourceMapFile); var isDataUri = DATA_URI.test(sourceMapFile); if (isRemote) { return fetchMapFile(self, sourceMapFile, context, proceedToNext); } else { var sourceFile = context.files[context.files.length - 1]; var sourceMapPath, sourceMapData; var sourceDir = sourceFile ? path.dirname(sourceFile) : self.options.relativeTo; if (isDataUri) { // source map's path is the same as the source file it comes from sourceMapPath = path.resolve(self.options.root, sourceFile || ''); sourceMapData = fromDataUri(sourceMapFile); } else { sourceMapPath = path.resolve(self.options.root, path.join(sourceDir || '', sourceMapFile)); sourceMapData = fs.readFileSync(sourceMapPath, 'utf-8'); } self.trackLoaded(sourceFile || undefined, sourceMapPath, sourceMapData); } } context.cursor += nextAt + 1; } return whenDone(); } function fromDataUri(uriString) { var match = DATA_URI.exec(uriString); var charset = match[2] ? match[2].split(/[=;]/)[2] : 'us-ascii'; var encoding = match[3] ? match[3].split(';')[1] : 'utf8'; var data = encoding == 'utf8' ? unescape(match[4]) : match[4]; var buffer = new Buffer(data, encoding); buffer.charset = charset; return buffer.toString(); } function fetchMapFile(self, sourceUrl, context, done) { fetch(self, sourceUrl, function (data) { self.trackLoaded(context.files[context.files.length - 1] || undefined, sourceUrl, data); done(); }, function (message) { context.errors.push('Broken source map at "' + sourceUrl + '" - ' + message); return done(); }); } function fetch(self, path, onSuccess, onFailure) { var protocol = path.indexOf('https') === 0 ? https : http; var requestOptions = override(url.parse(path), self.requestOptions); var errorHandled = false; protocol .get(requestOptions, function (res) { if (res.statusCode < 200 || res.statusCode > 299) return onFailure(res.statusCode); var chunks = []; res.on('data', function (chunk) { chunks.push(chunk.toString()); }); res.on('end', function () { onSuccess(chunks.join('')); }); }) .on('error', function (res) { if (errorHandled) return; onFailure(res.message); errorHandled = true; }) .on('timeout', function () { if (errorHandled) return; onFailure('timeout'); errorHandled = true; }) .setTimeout(self.timeout); } function originalPositionIn(trackedSource, line, column, token, allowNFallbacks) { var originalPosition; var maxRange = token.length; var position = { line: line, column: column + maxRange }; while (maxRange-- > 0) { position.column--; originalPosition = trackedSource.data.originalPositionFor(position); if (originalPosition) break; } if (originalPosition.line === null && line > 1 && allowNFallbacks > 0) return originalPositionIn(trackedSource, line - 1, column, token, allowNFallbacks - 1); if (trackedSource.path && originalPosition.source) { originalPosition.source = REMOTE_RESOURCE.test(trackedSource.path) ? url.resolve(trackedSource.path, originalPosition.source) : path.join(trackedSource.path, originalPosition.source); originalPosition.sourceResolved = true; } return originalPosition; } function trackContentSources(self, sourceFile) { var consumer = self.maps[sourceFile].data; var isRemote = REMOTE_RESOURCE.test(sourceFile); var sourcesMapping = {}; consumer.sources.forEach(function (file, index) { var uniquePath = isRemote ? url.resolve(path.dirname(sourceFile), file) : path.relative(self.relativeTo, path.resolve(path.dirname(sourceFile), file)); sourcesMapping[uniquePath] = consumer.sourcesContent && consumer.sourcesContent[index]; }); self.sourcesContent[sourceFile] = sourcesMapping; } function _resolveSources(self, remaining, whenDone) { function processNext() { return _resolveSources(self, remaining, whenDone); } if (remaining.length === 0) return whenDone(); var current = remaining.shift(); var sourceFile = current[0]; var originalFile = current[1]; var isRemote = REMOTE_RESOURCE.test(sourceFile); if (isRemote && self.localOnly) { self.warnings.push('No callback given to `#minify` method, cannot fetch a remote file from "' + originalFile + '"'); return processNext(); } if (isRemote) { fetch(self, originalFile, function (data) { self.sourcesContent[sourceFile][originalFile] = data; processNext(); }, function (message) { self.warnings.push('Broken original source file at "' + originalFile + '" - ' + message); processNext(); }); } else { var fullPath = path.join(self.options.root, originalFile); if (fs.existsSync(fullPath)) self.sourcesContent[sourceFile][originalFile] = fs.readFileSync(fullPath, 'utf-8'); else self.warnings.push('Missing original source file at "' + fullPath + '".'); return processNext(); } } InputSourceMapStore.prototype.track = function (data, whenDone) { return typeof this.options.sourceMap == 'string' ? fromString(this, data, whenDone) : fromSource(this, data, whenDone, { files: [], cursor: 0, errors: this.errors }); }; InputSourceMapStore.prototype.trackLoaded = function (sourcePath, mapPath, mapData) { var relativeTo = this.options.explicitTarget ? this.options.target : this.options.root; var isRemote = REMOTE_RESOURCE.test(sourcePath); if (mapPath) { mapPath = isRemote ? path.dirname(mapPath) : path.dirname(path.relative(relativeTo, mapPath)); } this.maps[sourcePath] = { path: mapPath, data: new SourceMapConsumer(mapData) }; trackContentSources(this, sourcePath); }; InputSourceMapStore.prototype.isTracking = function (source) { return !!this.maps[source]; }; InputSourceMapStore.prototype.originalPositionFor = function (sourceInfo, token, allowNFallbacks) { return originalPositionIn(this.maps[sourceInfo.source], sourceInfo.line, sourceInfo.column, token, allowNFallbacks); }; InputSourceMapStore.prototype.sourcesContentFor = function (contextSource) { return this.sourcesContent[contextSource]; }; InputSourceMapStore.prototype.resolveSources = function (whenDone) { var toResolve = []; for (var sourceFile in this.sourcesContent) { var contents = this.sourcesContent[sourceFile]; for (var originalFile in contents) { if (!contents[originalFile]) toResolve.push([sourceFile, originalFile]); } } return _resolveSources(this, toResolve, whenDone); }; module.exports = InputSourceMapStore;
(function(e){e.fn.datepicker.dates.lt={days:["Sekmadienis","Pirmadienis","Antradienis","Trečiadienis","Ketvirtadienis","Penktadienis","Šeštadienis","Sekmadienis"],daysShort:["S","Pr","A","T","K","Pn","Š","S"],daysMin:["Sk","Pr","An","Tr","Ke","Pn","Št","Sk"],months:["Sausis","Vasaris","Kovas","Balandis","Gegužė","Birželis","Liepa","Rugpjūtis","Rugsėjis","Spalis","Lapkritis","Gruodis"],monthsShort:["Sau","Vas","Kov","Bal","Geg","Bir","Lie","Rugp","Rugs","Spa","Lap","Gru"],today:"Šiandien",weekStart:1}})(jQuery);
/** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * @deprecated use Observable.from or Observable.of * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { var len = array.length; isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < len) { observer.onNext(array[i]); self(i + 1); } else { observer.onCompleted(); } }); }); };
(function() { if (typeof self === 'undefined' || !self.Prism || !self.document) { return; } Prism.hooks.add('complete', function (env) { if (!env.code) { return; } // Works only for <code> wrapped inside <pre> (not inline). var pre = env.element.parentNode; var clsReg = /\s*\bcommand-line\b\s*/; if ( !pre || !/pre/i.test(pre.nodeName) || // Abort only if neither the <pre> nor the <code> have the class (!clsReg.test(pre.className) && !clsReg.test(env.element.className)) ) { return; } if (env.element.querySelector('.command-line-prompt')) { // Abort if prompt already exists. return; } if (clsReg.test(env.element.className)) { // Remove the class "command-line" from the <code> env.element.className = env.element.className.replace(clsReg, ''); } if (!clsReg.test(pre.className)) { // Add the class "command-line" to the <pre> pre.className += ' command-line'; } var getAttribute = function(key, defaultValue) { return (pre.getAttribute(key) || defaultValue).replace(/"/g, '&quot'); }; // Create the "rows" that will become the command-line prompts. -- cwells var lines = new Array(1 + env.code.split('\n').length); var promptText = getAttribute('data-prompt', ''); if (promptText !== '') { lines = lines.join('<span data-prompt="' + promptText + '"></span>'); } else { var user = getAttribute('data-user', 'user'); var host = getAttribute('data-host', 'localhost'); lines = lines.join('<span data-user="' + user + '" data-host="' + host + '"></span>'); } // Create the wrapper element. -- cwells var prompt = document.createElement('span'); prompt.className = 'command-line-prompt'; prompt.innerHTML = lines; // Mark the output lines so they can be styled differently (no prompt). -- cwells var outputSections = pre.getAttribute('data-output') || ''; outputSections = outputSections.split(','); for (var i = 0; i < outputSections.length; i++) { var outputRange = outputSections[i].split('-'); var outputStart = parseInt(outputRange[0]); var outputEnd = outputStart; // Default: end at the first line when it's not an actual range. -- cwells if (outputRange.length === 2) { outputEnd = parseInt(outputRange[1]); } if (!isNaN(outputStart) && !isNaN(outputEnd)) { for (var j = outputStart; j <= outputEnd && j <= prompt.children.length; j++) { var node = prompt.children[j - 1]; node.removeAttribute('data-user'); node.removeAttribute('data-host'); node.removeAttribute('data-prompt'); } } } env.element.innerHTML = prompt.outerHTML + env.element.innerHTML; }); }());
/* * /MathJax/jax/output/HTML-CSS/fonts/STIX/General/Regular/AlphaPresentForms.js * * Copyright (c) 2009-2013 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS.STIXGeneral,{64256:[683,0,605,20,655],64257:[683,0,558,32,523],64258:[683,0,556,31,522],64259:[683,0,832,20,797],64260:[683,0,830,20,796]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/General/Regular/AlphaPresentForms.js");
let createBlakeHash; if (process.env.NODE_ENV === "test") { // Node 10.x errors when trying to import the native blake-hash during unit // test. As far as I (matheusd) can see, this only happens during test, and // isn't triggered in runtime, even if the native module does run. So for the // moment, I'm resorting to running the js version during tests. Ideally, this // needs to be solved in the upstream blake-hash so that we can also use the // native version in tests. createBlakeHash = require("blake-hash/js"); } else { createBlakeHash = require("blake-hash"); } export const blake256 = (buffer) => { let b = buffer; if (buffer instanceof Uint8Array) { // This case happens when this function runs in the preload script with // renderer provided data. b = Buffer.from(buffer); } return createBlakeHash("blake256").update(b).digest(); };
class Events { constructor(httpRequest, jwt, gcalBaseUrl) { if (httpRequest === undefined || jwt === undefined || gcalBaseUrl === undefined) { throw new Error('Events constructor: Missing arguments'); } this._httpRequest = httpRequest; this._JWT = jwt; this._gcalBaseUrl = gcalBaseUrl; } _returnPromiseWithError(errorMsg) { return new Promise((resolve, reject) => { let err = new Error(errorMsg); reject(err); }); } _checkCalendarId(calendarId, errorOrigin) { if (calendarId === undefined || calendarId == '') { let errorObject = { origin: errorOrigin, error: 'Missing calendarId argument; Check if defined in params and Settings file' }; return this._returnPromiseWithError(JSON.stringify(errorObject)); } } _checkCalendarAndEventId(calendarId, eventId, errorOrigin) { if (calendarId === undefined || calendarId == '') { let errorObject = { origin: errorOrigin, error: 'Missing calendarId argument; Check if defined in params and Settings file' }; return this._returnPromiseWithError(JSON.stringify(errorObject)); } if (undefined === eventId) { let errorObject = { origin: errorOrigin, error: 'Missing eventId argument' } return this._returnPromiseWithError(JSON.stringify(errorObject)); } } _checkErrorResponse(expectedStatusCode, actualStatusCode, respBody, actualStatusMessage) { if (actualStatusCode !== expectedStatusCode) { let statusMsg = (actualStatusMessage === '' || actualStatusMessage === undefined) ? '' : '(' + actualStatusMessage + ')'; let errorObject = { statusCode: `${actualStatusCode}${statusMsg}`, errorBody: respBody }; // let errorMessage = '{ "statusCode": "' + actualStatusCode + statusMsg + '", "errorBody":' + JSON.stringify(respBody) + ' }'; throw new Error(JSON.stringify(errorObject)); } } _tryParseJSON(stringToParse) { try { return JSON.parse(stringToParse); } catch (e) { return stringToParse; } } /** Deletes an event on the calendar specified. Returns promise with success msg if success * * @param {string} calendarId - Calendar identifier * @param {string} eventId - EventId specifying event to delete * @param {bool} params.sendNotifications (optional) - Whether to send notifications about the deletion of the event. */ delete(calendarId, eventId, params) { let checkResult = this._checkCalendarAndEventId(calendarId, eventId, 'Events.delete'); if (undefined !== checkResult) { return checkResult; } return this._httpRequest.delete(`${this._gcalBaseUrl}${calendarId}/events/${eventId}`, params, this._JWT) .then(resp => { this._checkErrorResponse(204, resp.statusCode, resp.body, resp.statusMessage); let status = resp.statusCode; return { eventId: eventId, statusCode: status, statusMessage: resp.statusMessage, message: 'Event deleted successfully' }; }) .catch(err => { let error = { origin: 'Events.delete', error: this._tryParseJSON(err.message) // return as object if JSON, string if not parsable }; throw new Error(JSON.stringify(error)); }); } /** Returns a promise that list all events on calendar during selected period * * @param {string} calendarId - Calendar identifier * @param {datetime} params.timeMin (optional) - start datetime of event in 2016-04-29T14:00:00+08:00 RFC3339 format * @param {datetime} params.timeMax (optional) - end datetime of event in 2016-04-29T18:00:00+08:00 RFC3339 format * @param {string} params.q (optional) - Free text search terms to find events that match these terms in any field, except for extended properties. */ get(calendarId, eventId, params) { let checkResult = this._checkCalendarAndEventId(calendarId, eventId, 'Events.get'); if (undefined !== checkResult) { return checkResult; } return this._httpRequest.get(`${this._gcalBaseUrl}${calendarId}/events/${eventId}`, params, this._JWT) .then(resp => { this._checkErrorResponse(200, resp.statusCode, resp.body, resp.statusMessage); let body = typeof resp.body === 'string' ? JSON.parse(resp.body) : resp.body; return body; }).catch(err => { let error = { origin: 'Events.get', error: this._tryParseJSON(err.message) // return as object if JSON, string if not parsable }; throw new Error(JSON.stringify(error)); }); } /** Insert an event on the calendar specified. Returns promise of details of event created within response body from google * * @param {string} calendarId - Calendar identifier * @param {string} params.summary - Event title to be specified in calendar event summary. Free-text * @param {nested object} params.start - start.dateTime defines start datetime of event in 2016-04-29T14:00:00+08:00 RFC3339 format * @param {nested object} params.end - end.dateTime defines end datetime of event in 2016-04-29T18:00:00+08:00 RFC3339 format * @param {string} params.location (optional) - Location description of event. Free-text * @param {string} params.description (optional) - Description of event. * @param {string} params.status (optional) - Event status - confirmed, tentative, cancelled; tentative for all queuing * @param {string} params.colorId (optional) - Color of the event */ insert(calendarId, params, query) { let checkResult = this._checkCalendarId(calendarId, 'Events.insert'); if (undefined !== checkResult) { return checkResult; } return this._httpRequest.post(`${this._gcalBaseUrl}${calendarId}/events`, params, this._JWT, query) .then(resp => { this._checkErrorResponse(200, resp.statusCode, resp.body, resp.statusMessage); let body = typeof resp.body === 'string' ? JSON.parse(resp.body) : resp.body; return body; }) .catch(err => { let error = { origin: 'Events.insert', error: this._tryParseJSON(err.message) }; throw new Error(JSON.stringify(error)); }); } /** Returns instances of the specified recurring event. * * @param {string} calendarId - Calendar identifier * @param {string} eventId - EventId specifying event to delete */ instances(calendarId, eventId, params) { let checkResult = this._checkCalendarId(calendarId, 'Events.instances'); if (undefined !== checkResult) { return checkResult; } return this._httpRequest.get(`${this._gcalBaseUrl}${calendarId}/events/${eventId}/instances`, params, this._JWT) .then(resp => { this._checkErrorResponse(200, resp.statusCode, resp.body, resp.statusMessage); let body = typeof resp.body === 'string' ? JSON.parse(resp.body) : resp.body; return body.items; }) .catch(err => { let error = { origin: 'Events.instances', error: this._tryParseJSON(err.message) // return as object if JSON, string if not parsable }; throw new Error(JSON.stringify(error)); }); } /** Returns a promise that list all events on calendar during selected period * * @param {string} calendarId - Calendar identifier * @param {datetime} params.timeMin (optional) - start datetime of event in 2016-04-29T14:00:00+08:00 RFC3339 format * @param {datetime} params.timeMax (optional) - end datetime of event in 2016-04-29T18:00:00+08:00 RFC3339 format * @param {string} params.q (optional) - Free text search terms to find events that match these terms in any field, except for extended properties. */ list(calendarId, params) { let checkResult = this._checkCalendarId(calendarId, 'Events.list'); if (undefined !== checkResult) { return checkResult; } return this._httpRequest.get(`${this._gcalBaseUrl}${calendarId}/events`, params, this._JWT) .then(resp => { this._checkErrorResponse(200, resp.statusCode, resp.body, resp.statusMessage); let body = typeof resp.body === 'string' ? JSON.parse(resp.body) : resp.body; return body.items; }).catch(err => { let error = { origin: 'Events.list', error: this._tryParseJSON(err.message) // return as object if JSON, string if not parsable }; throw new Error(JSON.stringify(error)); }); } /** Moves an event to another calendar, i.e. changes an event's organizer. * Returns updated event object of moved object when successful. * * @param {string} calendarId - Calendar identifier * @param {string} eventId - EventId specifying event to move * @param {string} params.destination - Destination CalendarId to move event to */ move(calendarId, eventId, params) { let checkResult = this._checkCalendarAndEventId(calendarId, eventId, 'Events.move'); if (undefined !== checkResult) { return checkResult; } if (undefined === params.destination) { return this._returnPromiseWithError('Events.move: Missing destination CalendarId argument'); } return this._httpRequest.postWithQueryString(`https://www.googleapis.com/calendar/v3/calendars/${calendarId}/events/${eventId}/move`, params, this._JWT) .then(resp => { this._checkErrorResponse(200, resp.statusCode, resp.body, resp.statusMessage); let body = typeof resp.body === 'string' ? JSON.parse(resp.body) : resp.body; return body; }) .catch(err => { let error = { origin: 'Events.move', error: this._tryParseJSON(err.message) // return as object if JSON, string if not parsable }; throw new Error(JSON.stringify(error)); }); } /** Creates an event based on a simple text string. * * @param {string} calendarId - Calendar identifier * @param {string} params.text - The text describing the event to be created. */ quickAdd(calendarId, params) { let checkResult = this._checkCalendarId(calendarId, 'Events.quickAdd'); if (undefined !== checkResult) { return checkResult; } if (undefined === params.text) { return this._returnPromiseWithError('Events.quickAdd: Missing text in required query parameters'); } return this._httpRequest.postWithQueryString(`${this._gcalBaseUrl}${calendarId}/events/quickAdd`, params, this._JWT) .then(resp => { this._checkErrorResponse(200, resp.statusCode, resp.body, resp.statusMessage); let body = typeof resp.body === 'string' ? JSON.parse(resp.body) : resp.body; return body; }) .catch(err => { let error = { origin: 'Events.quickAdd', error: this._tryParseJSON(err.message) // return as object if JSON, string if not parsable }; throw new Error(JSON.stringify(error)); }); } /** Patches an event on the calendar specified. Returns promise of details of patched event * * @param {string} calendarId - Calendar identifier * @param {string} eventId - EventId specifying event to update */ patch(calendarId, eventId, params, query) { let checkResult = this._checkCalendarAndEventId(calendarId, eventId, 'Events.patch'); if (undefined !== checkResult) { return checkResult; } return this._httpRequest.patch(`${this._gcalBaseUrl}${calendarId}/events/${eventId}`, params, this._JWT, query) .then(resp => { this._checkErrorResponse(200, resp.statusCode, resp.body, resp.statusMessage); let body = typeof resp.body === 'string' ? JSON.parse(resp.body) : resp.body; return body; }) .catch(err => { let error = { origin: 'Events.patch', error: this._tryParseJSON(err.message) // return as object if JSON, string if not parsable }; throw new Error(JSON.stringify(error)); }); } /** Updates an event on the calendar specified. Returns promise of details of updated event * * @param {string} calendarId - Calendar identifier * @param {string} eventId - EventId specifying event to update */ update(calendarId, eventId, params, query) { let checkResult = this._checkCalendarAndEventId(calendarId, eventId, 'Events.update'); if (undefined !== checkResult) { return checkResult; } return this._httpRequest.put(`${this._gcalBaseUrl}${calendarId}/events/${eventId}`, params, this._JWT, query) .then(resp => { this._checkErrorResponse(200, resp.statusCode, resp.body, resp.statusMessage); let body = typeof resp.body === 'string' ? JSON.parse(resp.body) : resp.body; return body; }) .catch(err => { let error = { origin: 'Events.update', error: this._tryParseJSON(err.message) // return as object if JSON, string if not parsable }; throw new Error(JSON.stringify(error)); }); } /** Watch for changes to Events resources * * @param {string} calendarId - Calendar identifier */ watch(calendarId, params, query) { let checkResult = this._checkCalendarId(calendarId, 'Events.watch'); if (undefined !== checkResult) { return checkResult; } return this._httpRequest.post(`${this._gcalBaseUrl}${calendarId}/events/watch`, params, this._JWT, query) .then(resp => { this._checkErrorResponse(200, resp.statusCode, resp.body, resp.statusMessage); let body = typeof resp.body === 'string' ? JSON.parse(resp.body) : resp.body; return body; }) .catch(err => { let error = { origin: 'Events.watch', error: this._tryParseJSON(err.message) // return as object if JSON, string if not parsable }; throw new Error(JSON.stringify(error)); }); } } module.exports = Events;
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require('@angular/core'); var router_1 = require('@angular/router'); var modules_js_1 = require('@sys/modules.js'); var list_component_js_1 = require('./list.component.js'); var invoices_table_component_js_1 = require('./table/invoices-table.component.js'); var view_module_js_1 = require('./../view/view.module.js'); var edit_module_js_1 = require('./../edit/edit.module.js'); var ListModule = (function () { function ListModule() { } ListModule = __decorate([ core_1.NgModule({ imports: [ router_1.RouterModule.forChild([{ path: 'List', component: list_component_js_1.ListComponent }]), modules_js_1.SysModules, view_module_js_1.ViewModule, edit_module_js_1.EditModule ], declarations: [ list_component_js_1.ListComponent, invoices_table_component_js_1.InvoicesTableComponent, ], exports: [list_component_js_1.ListComponent] }), __metadata('design:paramtypes', []) ], ListModule); return ListModule; }()); exports.ListModule = ListModule;
(function(scope) { // Interface. scope.Elements = { buildIcon: buildIcon, buildSpan: buildSpan, buildSymbols: buildSymbols }; // Create an icon to go on the name list. function buildIcon(iconName) { return $('<i/>') .addClass('fa fa-' + iconName); } // Create a span element with the specified class. function buildSpan(className) { return $('<span/>') .addClass(className); } // Build Font Awesome symbols. function buildSymbols(artist) { var symbolElement = buildSpan('artist-symbols'); var standbyFlag = !artist.seatedLast && (artist.standbyDays && artist.standbyDays.length >= 2); if (artist.lotteryOrder > 0) { symbolElement.append(buildIcon('check').attr('title', 'Picked For Lottery')); } if (artist.standbyOrder > 0) { symbolElement.append(buildIcon('clock-o').attr('title', 'On Standby')); } if (artist.tableNumber) { symbolElement.append(buildIcon('sign-in').attr('title', 'Signed In')); } if (standbyFlag) { symbolElement.append(buildIcon('exclamation attention').attr('title', 'This artist has been on standby for at least two days.')); } return symbolElement; } })(window);
(function(){ "use strict"; /*<*/ var UNDEF, WIN = window, NUMBER = Number, TRUE = true, FALSE = false, /** Aliased methods/properties */ each = [].forEach, /** Lengthy/repeated method names. */ query = "querySelector", queryAll = query+"All", /** Appropriate event types for interacting with document's content */ pointStart = "mousedown", /*>*/ /** * Basic class for managing a tabbed interface. * * No attempt is made to arrange the targeted container into any tab-like structure. That is, it's assumed the affected * element is already marked-up and styled to resemble a sequence of content blocks preceded by a navigation element. * In essence, this class is primarily responsible for toggling CSS classes for hiding/exposing content, and assigning * the event listeners responsible for doing so. * * @param {HTMLElement} el - The node that encloses both the navigation element and the container holding each panel of tabbed content. * @param {Object} opts - Supplementary hash of options * @param {String} opts.activeClass - CSS class applied to active tab and associated nav item. Defaults to "active". * @param {Boolean} opts.autoHeight - If set, will automatically set the height of the `panels` node to fit the height of the selected tab. * @param {String|HTMLElement} opts.nav - A selector matching an element within `el`, or an explicit reference to a DOM element. * @param {String|HTMLElement} opts.panel - As with opts.nav, but specifies the element enclosing each region of content to display/hide. * @constructor */ Tabs = function(el, opts){ var THIS = this, /** Resolve any options that we were handed */ opts = opts || {}, activeClass = opts.activeClass || "active", /** Enable automatic scaling of container's height */ autoHeight = opts.autoHeight, autoHeight = UNDEF === autoHeight ? TRUE : autoHeight, /** Navigation container: allow both nodes and selector strings to be passed in */ nav = opts.nav, nav = UNDEF === nav ? el.firstElementChild : nav, nav = "string" === typeof nav ? el[ query ](nav) : nav, /** Element enclosing each panel of tabbed content */ panelsNode = opts.panels, panelsNode = UNDEF === panelsNode ? nav.nextElementSibling : panelsNode, panelsNode = "string" === typeof panelsNode ? el[ query ](panelsNode) : panelsNode, /** Actual list of panels, expressed as a live HTMLCollection */ panels = panelsNode.children, /** Similarly, change nav to point to its immediate descendants for quicker lookup */ nav = nav.children, /** Index of the currently-active panel */ active, /** Method for fitting the container's height to that of the currently-selected panel. */ fit = function(){ panelsNode.style.height = panels[active].scrollHeight + "px"; }; /** Define property getter/setters */ Object.defineProperties(THIS, { /** Read-only properties */ node: {get: function(){ return el; }}, nav: {get: function(){ return nav; }}, panels: {get: function(){ return panels; }}, /** Writable properties */ active:{ get: function(){ return active; }, set: function(i){ /** Make sure we're being assigned a valid numeric value. */ if(i !== active && !NUMBER.isNaN(i = parseInt(+i))){ active = i; /** Remove the "active-class" from the previous elements. */ each.call(el[ queryAll ]("."+activeClass), function(o){ o.classList.remove(activeClass); }); if(autoHeight) fit(); /** Reapply the "active class" to our newly-selected elements. */ nav[i].classList .add(activeClass); panels[i].classList .add(activeClass); } } } }); /** Attach event listeners */ each.call(nav, function(o, index){ o.addEventListener(pointStart, function(e){ THIS.active = index; e.preventDefault(); return FALSE; }); }); /** Set the active/initial panel */ THIS.active = opts.active || 0; /** Expose some internal functions as instance methods */ THIS.fit = fit; }; /** Polyfills */ NUMBER.isNaN = NUMBER.isNaN || function(i){ return "number" === typeof i && i !== i; } /** Export */ WIN.Tabs = Tabs; }());
import assert from 'power-assert'; import {resolve} from './downUp'; import {migrations} from '../test/fixtures'; describe('strategies/downUp.js', () => { it('ignores wrong order', () => { const current = [migrations[0], migrations[4], migrations[2]]; const target = [migrations[0], migrations[2], migrations[4]]; assert.deepEqual(resolve(target, current), []); }); it('removes excessive migrations', () => { const current = [migrations[0], migrations[4], migrations[2], migrations[3]]; const target = [migrations[0], migrations[2], migrations[4]]; assert.deepEqual(resolve(target, current), [ {migration: migrations[3], direction: 'down'}, ]); }); it('applies missing migrations', () => { const current = [migrations[0], migrations[4], migrations[2]]; const target = [migrations[0], migrations[2], migrations[4], migrations[3]]; assert.deepEqual(resolve(target, current), [ {migration: migrations[3], direction: 'up'}, ]); }); it('works with mixed excessive/missing migrations in any order', () => { const current = [migrations[0], migrations[2]]; const target = [migrations[4], migrations[3], migrations[0]]; assert.deepEqual(resolve(target, current), [ {migration: migrations[2], direction: 'down'}, {migration: migrations[4], direction: 'up'}, {migration: migrations[3], direction: 'up'}, ]); }); });
angular.module('weather.location.directive', [ 'weather.service', 'weather.location.template' ]).directive('weatherLocation', function(){ return { restrict: 'E', templateUrl: 'weather/location', controller: WeatherLocationController, scope: { location: '=current' } }; }); WeatherLocationController.$inject = [ '$scope', WEATHER_SERVICE]; function WeatherLocationController($scope, weather){ weather.getForecast($scope.location.id) .then(function(forecast){ $scope.forecast = forecast; }); }
var ffi = require('ffi'), ref = require('ref'), RefArray = require('ref-array'), Struct = require('ref-struct'), Union = require('ref-union'), _library = require('./../'); loadDependentSymbols(); _library._preload['php_strlcpy'] = [function () { _library.php_strlcpy = ['ulong', [ref.refType('char'), ref.refType('char'), 'ulong']]; _library._functions['php_strlcpy'] = _library.php_strlcpy; }]; _library._preload['php_strlcat'] = [function () { _library.php_strlcat = ['ulong', [ref.refType('char'), ref.refType('char'), 'ulong']]; _library._functions['php_strlcat'] = _library.php_strlcat; }]; _library._preload['php_write'] = [function () { _library.php_write = ['int', [ref.refType('void'), 'uint']]; _library._functions['php_write'] = _library.php_write; }]; _library._preload['php_get_module_initialized'] = [function () { _library.php_get_module_initialized = ['int', []]; _library._functions['php_get_module_initialized'] = _library.php_get_module_initialized; }]; _library._preload['php_log_err'] = [function () { _library.php_log_err = ['void', [ref.refType('char')]]; _library._functions['php_log_err'] = _library.php_log_err; }]; _library._preload['php_verror'] = [function () { _library.php_verror = ['void', [ref.refType('char'), ref.refType('char'), 'int', ref.refType('char'), ref.refType('void')]]; _library._functions['php_verror'] = _library.php_verror; }]; _library._preload['php_register_internal_extensions'] = [function () { _library.php_register_internal_extensions = ['int', []]; _library._functions['php_register_internal_extensions'] = _library.php_register_internal_extensions; }]; _library._preload['php_mergesort'] = ['int (const void *, const void *)', function () { _library.php_mergesort = ['int', [ref.refType('void'), 'ulong', 'ulong', ffi.Function('int', [ref.refType('void'), ref.refType('void')])]]; _library._functions['php_mergesort'] = _library.php_mergesort; }]; _library._preload['php_com_initialize'] = [function () { _library.php_com_initialize = ['void', []]; _library._functions['php_com_initialize'] = _library.php_com_initialize; }]; _library._preload['php_get_current_user'] = [function () { _library.php_get_current_user = [ref.refType('char'), []]; _library._functions['php_get_current_user'] = _library.php_get_current_user; }]; function loadDependentSymbols() { }
/** * Common utilities * @module glMatrix */ // Configuration Constants export var EPSILON = 0.000001; export var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; export var RANDOM = Math.random; /** * Sets the type of array used when creating new vectors and matrices * * @param {Float32ArrayConstructor | ArrayConstructor} type Array type, such as Float32Array or Array */ export function setMatrixArrayType(type) { ARRAY_TYPE = type; } var degree = Math.PI / 180; /** * Convert Degree To Radian * * @param {Number} a Angle in Degrees */ export function toRadian(a) { return a * degree; } /** * Tests whether or not the arguments have approximately the same value, within an absolute * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less * than or equal to 1.0, and a relative tolerance is used for larger values) * * @param {Number} a The first number to test. * @param {Number} b The second number to test. * @returns {Boolean} True if the numbers are approximately equal, false otherwise. */ export function equals(a, b) { return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b)); } if (!Math.hypot) Math.hypot = function () { var y = 0, i = arguments.length; while (i--) { y += arguments[i] * arguments[i]; } return Math.sqrt(y); };
/** * AppBuilder3 * Copyright (c) 2017 Callan Peter Milne * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ (function (angular) { "use strict"; const AppBuilder3 = angular.module("AppBuilder3"); AppBuilder3.factory("JsonSchema", JsonSchemaFactory); JsonSchemaFactory.$inject = ["fetchSchema", "$timeout"]; function JsonSchemaFactory ( fetchSchema, $timeout) { class JsonSchema { static get LOADING () { return "LOADING"; } static load (url) { return new Promise((resolve, reject) => { fetchSchema(url) .then(res => { let jsonSchema; let data = res.data; let jsonString = JSON.stringify(data, undefined, " "); let subrefs = jsonString.match(/\"\$ref\"\: \"(.+)/gm); if (!subrefs) { resolve(new JsonSchema(res.data)); return; } let schemas = []; let subrefUrls = subrefs.map(v => { return v.substr(9).substr(0,v.length-10); }); subrefUrls.forEach(url => { schemas.push(fetchSchema(url)); }); Promise.all(schemas) .then(() => { resolve(new JsonSchema(res.data)); }) .catch(err => { reject(err); }); }); }); } constructor (d) { d = d || {}; this._d = d; this.id = d.id; this.$schema = d.$schema; this.description = d.description; this.type = d.type; this.additionalProperties = d.additionalProperties; this.required = d.required; this.properties = {}; hydrate(this, d.properties); } get name () { return this.id.split(/\//g).slice(-1)[0]; } forEachProp (fn) { Object.keys(this.properties).forEach(k => { let v = this.properties[k]; fn(k, v); }); } } return JsonSchema; function hydrate (jsonSchema, properties) { if (!properties) { return; } Object.keys(properties).forEach(k => { let v = properties[k]; let isArray = "array" === v.type; let ref = v.$ref || isArray && v.items.$ref; if (!ref) { jsonSchema.properties[k] = v; return; } if ("array" === v.type) { v.items = JsonSchema.LOADING; jsonSchema.properties[k] = v; } else { jsonSchema.properties[k] = JsonSchema.LOADING; } fetchSchema(ref) .then(res => { $timeout(function () { let schema = new JsonSchema(res.data); if (isArray) { console.log(res); jsonSchema.properties[k].items = schema; return; } jsonSchema.properties[k] = schema; }); }) .catch(err => { console.log(`failed to fetch ref ${ref}:`); console.log(err); }); }); } } })(angular);
var gulp = require('gulp'); var concat = require('gulp-concat'); var minify = require('gulp-minify'); gulp.task('build', function () { gulp.src([ 'node_modules/corslite/corslite.js', 'L.UTFGrid.js','L.UTFGridCanvas.js' ]) .pipe(concat('L.UTFGrid.js')) .pipe(minify({noSource: true})) .pipe(gulp.dest('./')) }); gulp.task('watch', function () { gulp.watch(['L.UTFGrid.js','L.UTFGridCanvas.js'], ['build']); }); gulp.task('default', ['build', 'watch']);
'use strict' var React = require('react') var searchBar = React.createClass({ propTypes: { onQuerySubmit: React.PropTypes.func.isRequired }, getInitialState: function () { return {queryBatchNumber: ''} }, handleInputChange: function (e) { this.setState({queryBatchNumber: e.target.value}) }, handleSubmit: function (e) { e.preventDefault() this.setState({queryBatchNumber: this.state.queryBatchNumber}) var queryBatchNumber = this.state.queryBatchNumber if (!queryBatchNumber) { return } this.props.onQuerySubmit({queryBatchNumber: queryBatchNumber}) this.setState({queryBatchNumber: ''}) }, render: function () { return ( <div> <form className='search-bar' onSubmit={this.handleSubmit}> <input id='batchsearch-search-input' type='text' placeholder='Batch Number' value={this.state.queryBatchNumber} onChange={this.handleInputChange} /> <input id='batchsearch-input-button' type='submit' value='Check' txt='Check' /> </form> </div> ) } }) module.exports = searchBar
require('babel-core/register') require('json5/lib/require') var path = require('path') var JSON5 = require('json5') var tap = require('tap') var test = tap.test var deref = require('../src/index.js').default var slashPointer = require('../src/util.js').slashPointer deref.setJsonParser(JSON5.parse) function fileUrl(str) { var pathName = path.resolve(str).replace(/\\/g, '/'); if (pathName[0] !== '/') pathName = '/' + pathName return encodeURI('file://' + pathName) } var list = { indirect: (t, output) => { // t.deepEqual(output, expected) t.end() }, // toParent: (t, output) => { // t.end() // }, // toSelf: (t, output) => { // t.end() // }, } const basePath = path.resolve(__dirname, './json5/circular/') const baseURL = fileUrl(basePath) const name = 'indirect' const input = require(`./json5/circular/${name}.json5`) deref(input, { failOnMissing:true, skipCircular: true }) .then(output => { debugger console.log(output); }) // test('circular references', t => { // Promise.all( // Object.getOwnPropertyNames(list).map(name => { // debugger // return test(name, t => { // t.plan(1) // const input = require(`./json5/circular/${name}.json5`) // // const expected = require(`./json5/temp/${name}.expected.json5`) // debugger // deref(input, { // failOnMissing:true, // baseURI: baseURI + name, // jsonParser: JSON5.parse, // }) // .then(output => { // debugger // list[name](t, output) // // t.deepEqual(output, expected) // // t.end() // }) // .catch(t.threw) // // .catch(err => { // // console.log(err); // // return t.threw(err) // // }) // }) // }) // ).then(t.end) // // // // t.test('with failOnMissing', t => { // // Promise.all( // // Object.getOwnPropertyNames(cases).map(name => { // // return t.test(name, t => { // // t.plan(1) // // const input = require(`./json5/temp/error_${name}.json5`) // // deref(input, { // // failOnMissing:true, // // baseURI: baseURI + name, // // jsonParser: JSON5.parse, // // }) // // .then(output => t.fail('should not resolve') ) // // .catch(err => t.pass('rejected ok') ) // // // // }) // // }) // // ).then(t.end) // // }) // // // // t.test('without failOnMissing', t => { // // Promise.all( // // Object.getOwnPropertyNames(cases).map(name => { // // return t.test(name, t => { // // t.plan(1) // // const input = require(`./json5/temp/error_${name}.json5`) // // const expected = require(`./json5/temp/error_${name}.expected.json5`) // // debugger // // deref(input, { // // failOnMissing:false, // // baseURI: baseURI + name, // // jsonParser: JSON5.parse, // // }) // // .then(output => { // // debugger // // t.deepEqual(output, expected) // // }) // // .catch(err => t.fail('should resolve') ) // // // // }) // // }) // // ).then(t.end) // // }) // // t.end() // // })
var first_id = 0; // Auto-incrementing sequence field. // From http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/ function hook_init(config) { this.log({ message: '[serial_id] Initializing' }); this.db.get('counters').insert({ collection: 'issues', seq: first_id }); // See https://github.com/Automattic/monk/issues/72 this.db.get('issues').id = function (s) { return s; }; } function hook_orm_models(orm_models) { var issue_model = orm_models.issue; if (issue_model) { this.log({ message: '[serial_id] Patching issue ORM model' }); issue_model._id = Number; } } function get_auto_increment_id(req, collection, callback) { req.log({ message: '[serial_id] Acquiring serial id', collection: collection }); return req.db.get('counters').findAndModify({ collection: collection }, { $inc: { seq: 1 } }, { upsert: true, new: true }, function (err, doc) { if (err) { req.log({ message: 'serial_id::get_auto_increment_id: findAndModify failed', err: err, collection: collection }); err = { code: 500, message: 'Internal error' }; } return callback(err, doc ? doc.seq : null); }); } // Serial id generator, for when the backend doesn't provide them. function hook_create(req, res, next) { this.log({ message: '[serial_id] Assigning serial id to new issue' }); return get_auto_increment_id(req, 'issue', function (err, id) { req.body._id = id; return next(); }); } module.exports.hooks = { init: hook_init, orm_models: hook_orm_models, create: hook_create };
'use strict'; var promise = require('./promise'); var blessed = require('./private/blessed'); var trampoline = require('./private/trampoline'); var util = require('./private/util'); // # Series // A subclass of [`Promise`](./promise.js.html) that makes it easier // to interact with promises-for-arrays. Thus, a `Series` promise is expected to // be fulfilled with an array. // The instance methods listed below all return promises. Unless noted otherwise // they'll return a new `Series` promise. If the original promise is fulfilled // with a value other than an array, the returned promise will (unless noted // otherwise), be fulfilled with a new, empty array. If the original promise // is rejected, the returned promise will be rejected with the same reason. // Iterator callbacks are called with items from the array. No other arguments // are passed. The callbacks may return a value or a `Promise` instance. // `thenables` are *not* assimilated. // Parallelization controls the number of pending promises (as returned by // an iterator callback) an operation is waiting on. Per operation no new // callbacks are invoked when this number reaches the maximum concurrency. function Series(executor) { if (typeof executor !== 'function') { throw new TypeError(); } if (!(this instanceof Series)) { return new Series(executor); } if (executor !== blessed.be) { blessed.be(this, executor, true); } } // Besides instance methods, the following class methods are inherited from // `Promise`: // * `Series.isInstance()` // * `Series.from()` // * `Series.rejected()` // * `Series.all()` // * `Series.any()` // * `Series.some()` // * `Series.join()` // * `Series.denodeify()` exports.Series = blessed.extended(Series); function nextTurn(func, value) { trampoline.nextTurn({ resolve: function() { func(value); } }); } function produceValue(promiseOrValue) { if (promise.Promise.isInstance(promiseOrValue)) { return promiseOrValue.inspectState().value; } else { return promiseOrValue; } } function invokeCancel(promiseOrValue) { if (promise.Promise.isInstance(promiseOrValue)) { promiseOrValue.cancel(); } } function prepForSort(iterator) { var index = 0; return function(item) { var wrapped = { sourceIndex: index++ }; var result = iterator(item); if (promise.Promise.isInstance(result)) { return result.then(function(sortValue) { wrapped.sortValue = sortValue; return wrapped; }); } else { wrapped.sortValue = result; return wrapped; } }; } function sortInstructions(a, b) { return a.sortValue < b.sortValue ? -1 : 1; } // ## Series#map(iterator) // Maps each value in the array using `iterator`, eventually resulting in an // array with the returned (promise fulfillment) values. Series.prototype.map = function(iterator) { return this.mapParallel(1, iterator); }; // ## Series#mapParallel(maxConcurrent, iterator) // See `Series#map(iterator)`. // (You may notice all other operations build on top of this method.) Series.prototype.mapParallel = function(maxConcurrent, iterator) { return util.guardArray(this, [], function(arr) { if (typeof maxConcurrent !== 'number') { throw new TypeError('Missing max concurrency number.'); } if (typeof iterator !== 'function') { throw new TypeError('Missing iterator function.'); } return new Series(function(resolve, reject) { var index = 0, stopAt = arr.length; var acc = new Array(stopAt); var reachedEnd = false; var running = 0; function oneCompleted() { running--; runConcurrent(); } function oneFailed(reason) { reachedEnd = true; running = -1; reject(reason); } function runConcurrent() { if (reachedEnd) { if (running === 0) { resolve(acc.map(produceValue)); } return; } if (running >= maxConcurrent) { return; } try { running++; var result = acc[index] = iterator(arr[index]); index++; reachedEnd = reachedEnd || index === stopAt; if (promise.Promise.isInstance(result)) { result.then(oneCompleted, oneFailed); } else { oneCompleted(); } runConcurrent(); } catch (error) { oneFailed(error); } } nextTurn(runConcurrent); return function() { reachedEnd = true; running = -1; acc.forEach(invokeCancel); }; }); }); }; // ## Series#each(iterator) // Iterates over each item in the array. Returns a // `Promise` that is fulfilled with `undefined` when the iteration // has completed. Series.prototype.each = function(iterator) { return this.mapParallel(1, iterator) .then(util.makeUndefined).to(promise.Promise); }; // ## Series#eachParallel(maxConcurrent, iterator) // See `Series#each(iterator)`. Series.prototype.eachParallel = function(maxConcurrent, iterator) { return this.mapParallel(maxConcurrent, iterator) .then(util.makeUndefined).to(promise.Promise); }; // ## Series#filter(iterator) // Filters the array, eventually resulting in an array containing the items for // which `iterator` returned a truey (promise fulfillment) value. Series.prototype.filter = function(iterator) { return this.mapParallel(1, util.skipIfFalsy(iterator)) .then(util.removeSkipped); }; // ## Series#filterParallel(maxConcurrent, iterator) // See `Series#filter(iterator)`. // The resulting array retains the order of the original array. Series.prototype.filterParallel = function(maxConcurrent, iterator) { return this.mapParallel(maxConcurrent, util.skipIfFalsy(iterator)) .then(util.removeSkipped); }; // ## Series#filterOut(iterator) // Filters the array, eventually resulting in an array containing the items for // which `iterator` returned a falsey (promise fulfillment) value. Series.prototype.filterOut = function(iterator) { return this.mapParallel(1, util.skipIfTruthy(iterator)) .then(util.removeSkipped); }; // ## Series#filterOutParallel(maxConcurrent, iterator) // See `Series#filterOut(iterator)`. // The resulting array retains the order of the original array. Series.prototype.filterOutParallel = function(maxConcurrent, iterator) { return this.mapParallel(maxConcurrent, util.skipIfTruthy(iterator)) .then(util.removeSkipped); }; // ## Series#concat(iterator) // Iterates over each item in the array, eventually resulting in an flattened // array containing the returned (promise fulfillment) values. Series.prototype.concat = function(iterator) { return this.mapParallel(1, iterator).then(util.flatten); }; // ## Series#concatParallel(maxConcurrent, iterator) // See `Series#concat(iterator)`. // The items in the resulting array are ordered by when the iterator that // returned them was invoked, not when its returned promise fulfilled. Series.prototype.concatParallel = function(maxConcurrent, iterator) { return this.mapParallel(maxConcurrent, iterator).then(util.flatten); }; // ## Series#foldl(initialValue, iterator) // Folds the array into another value, starting with the first item. At each // stage, `iterator` is called with the result of the folding operation at that // point, and an item from the array. Returns a `Promise` instance for the // result of the folding operation. // Unlike `Array#reduce()` the initial value must be passed as the first // argument. `initialValue` may be a promise, `iterator` won't be called until // `initialValue` has fulfilled. If it rejects, the returned promise is rejected // with the same reason. // This method has no parallel equivalent. Use `Series#mapParallel()` to collect // values concurrently, and then use this method with a synchronous iterator. Series.prototype.foldl = function(initialValue, iterator) { return util.guardArray(this, initialValue, function(arr) { return new promise.Promise(function(resolve, reject) { var index = 0, stopAt = arr.length; var reachedEnd = false; var currentPromise; function applyIterator(value) { if (reachedEnd) { resolve(value); return; } try { value = iterator(value, arr[index]); index++; reachedEnd = reachedEnd || index === stopAt; if (promise.Promise.isInstance(value)) { currentPromise = value; value.then(applyIterator, reject); } else { applyIterator(value); } } catch (error) { reject(error); } } if (promise.Promise.isInstance(initialValue)) { currentPromise = initialValue.then(applyIterator, reject); } else { nextTurn(applyIterator, initialValue); } return function() { if (currentPromise) { currentPromise.cancel(); } reachedEnd = true; }; }); }).to(promise.Promise); }; // ## Series#foldr(initialValue, iterator) // Like `Series#foldl()`, but starts with the last item in the array. Series.prototype.foldr = function(initialValue, iterator) { return util.guardArray(this, initialValue, function(arr) { return new promise.Promise(function(resolve, reject) { var index = arr.length - 1; var reachedEnd = false; var currentPromise; function applyIterator(value) { if (reachedEnd) { resolve(value); return; } try { value = iterator(value, arr[index]); index--; reachedEnd = reachedEnd || index < 0; if (promise.Promise.isInstance(value)) { currentPromise = value; value.then(applyIterator, reject); } else { applyIterator(value); } } catch (error) { reject(error); } } if (promise.Promise.isInstance(initialValue)) { currentPromise = initialValue.then(applyIterator, reject); } else { nextTurn(applyIterator, initialValue); } return function() { if (currentPromise) { currentPromise.cancel(); } reachedEnd = true; }; }); }).to(promise.Promise); }; // ## Series#detect(iterator) // Iterates over the array, returning a `Promise` instance that will be // fulfilled with the item for which `iterator` first returned a truey // (promise fulfillment) value. If no match is found, the promise will be // fulfilled with `undefined`. // Iteration is stopped when the promise is fulfilled. Series.prototype.detect = function(iterator) { return this.detectParallel(1, iterator); }; // ## Series#detectParallel(maxConcurrent, iterator) // See `Series#detect(iterator)`. Each promise returned by the iterator is // racing the other promises to fulfill with a truey value first. The returned // promise will be fulfilled with the item for which that promise was returned // from `iterator`. Series.prototype.detectParallel = function(maxConcurrent, iterator) { return this.mapParallel(maxConcurrent, util.shortcutDetect(iterator)) .to(promise.Promise) .then(util.makeUndefined, util.extractShortcutValue); }; // ## Series#some(iterator) // Iterates over the array, returning a `Promise` instance that will be // fulfilled with `true` if an iterator returns a truey (promise fulfillment) // value, or `false` if no iterator does so. // Iteration is stopped when the promise is fulfilled. Series.prototype.some = function(iterator) { return this.someParallel(1, iterator); }; // ## Series#someParallel(maxConcurrent, iterator) // See `Series#some(iterator)`. Series.prototype.someParallel = function(maxConcurrent, iterator) { return this.mapParallel(maxConcurrent, util.shortcutSome(iterator)) .to(promise.Promise) .then(util.strictlyTrue, util.extractShortcutValue); }; // ## Series#every(iterator) // Iterates over the array, returning a `Promise` instance that will be // fulfilled with `true` if all iterations return a truey (promise fulfillment) // value, or `false` when the an iteration does not. // Iteration is stopped when the promise is fulfilled. Series.prototype.every = function(iterator) { return this.everyParallel(1, iterator); }; // ## Series#everyParallel(maxConcurrent, iterator) // See `Series#every(iterator)`. Series.prototype.everyParallel = function(maxConcurrent, iterator) { return this.mapParallel(maxConcurrent, util.shortcutNotEvery(iterator)) .to(promise.Promise) .then(util.makeTrue, util.extractShortcutValue); }; // ## Series#sortBy(iterator) // Sorts the array, using `iterator` to map each item to a sort value. // Relies on `Array#sort(compareFunction)`, with each sort value being passed // to the compare function: // function compareFunction(a, b) { // return a < b ? -1 : 1; // } // Eventually modifies and returns the original array. Series.prototype.sortBy = function(iterator) { return this.sortByParallel(1, iterator); }; // ## Series#sortByParallel(maxConcurrent, iterator) // See `Series#sortBy(iterator)`. Series.prototype.sortByParallel = function(maxConcurrent, iterator) { var self = this; return self.then(function(arr) { if (!Array.isArray(arr) || arr.length === 0) { return arr; } return self.mapParallel(maxConcurrent, prepForSort(iterator)) .then(function(instructions) { instructions.sort(sortInstructions); var copy = arr.slice(); for (var i = 0, l = arr.length; i < l; i++) { arr[i] = copy[instructions[i].sourceIndex]; } return arr; }); }); };
import React from 'react'; import { storiesOf, action } from '@kadira/storybook'; import { withKnobs, text, boolean, number, object } from '@kadira/storybook-addon-knobs'; import { setComposerStub } from 'react-komposer'; import Home from '../home.jsx'; storiesOf('core.Home', module) .addDecorator(withKnobs) .add('default view', () => { return ( <Home /> ); });
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ sap.ui.define(['sap/ui/core/Control'], function(Control) { "use strict"; /** * Constructor for a new BlockLayoutCell. * * @param {string} [sId] ID for the new control, generated automatically if no ID is given * @param {object} [mSettings] Initial settings for the new control * * @class * The BlockLayoutCell is used as an aggregation of the BlockLayoutRow. It contains Controls. * The BlockLayoutCell should be used only as aggregation of the BlockLayoutRow. * @extends sap.ui.core.Control * * @author SAP SE * @version 1.38.4 * * @constructor * @public * @since 1.34 * @alias sap.ui.layout.BlockLayoutCell * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var BlockLayoutCell = Control.extend("sap.ui.layout.BlockLayoutCell", { metadata : { library : "sap.ui.layout", properties : { /** * Defines the title of the cell */ title: { type: "string", group: "Appearance", defaultValue: null }, /** * Defines the alignment of the cell title */ titleAlignment: { type: "sap.ui.core.HorizontalAlign", group: "Appearance", defaultValue: "Begin" }, /** * Defines the aria level of the title * This information is e.g. used by assistive technologies like screenreaders to create a hierarchical site map for faster navigation. */ titleLevel: { type: "sap.ui.core.TitleLevel", group: "Appearance", defaultValue: "Auto"}, /** * Defines the width of the cell. Depending on the context of the cell - whether it's in scrollable, * or non scrollable row, this property is interpreted in two different ways. * If the cell is placed inside a scrollable row - this property defines the width of the cell in * percentages. If no value is provided - the default is 40%. * If the cell is placed inside a non scrollable row - this property defines the grow factor of the cell * compared to the whole row. * <b>For example:</b> If you have 2 cells, each with width of 1, this means that they should be of equal size, * and they need to fill the whole row. This results in 50% width for each cell. If you have 2 cells, * one with width of 1, the other with width of 3, this means that the whole row width is 4, so the first * cell will have a width of 25%, the second - 75%. * According to the visual guidelines, it is suggested that you only use 25%, 50%, 75% or 100% cells in * you applications. For example, 12,5% width is not desirable (1 cell with width 1, and another with width 7) */ width: { type: "int", group: "Appearance", defaultValue: 0 } }, defaultAggregation : "content", aggregations : { /** * The content to be included inside the cell */ content: {type : "sap.ui.core.Control", multiple : true, singularName : "content"} } }}); /** * When the width is set, the cell needs to notify the parent row if it's in scrollable mode * to update the other cells as well. * @param The width of the cell * @returns {BlockLayoutCell} */ BlockLayoutCell.prototype.setWidth = function (width) { this.setProperty("width", width); if (!this._getParentRowScrollable()) { var parent = this.getParent(); if (parent) { parent._checkGuidelinesAndUpdateCells(); } } return this; }; /** * This method is called from the BlockLayoutRow, when a new cell is added, removed, or when a given cell in the row * changes its width. Then the whole row gets updated again. * @private */ BlockLayoutCell.prototype._clearState = function () { this._parentRowScrollable = false; this._differentSBreakpointSize = false; }; BlockLayoutCell.prototype._setDifferentSBreakpointSize = function (different, ratio) { this._differentSBreakpointSize = different; this._widthToRowWidthRatio = ratio; }; BlockLayoutCell.prototype._getDifferentSBreakpointSize = function () { return this._differentSBreakpointSize; }; BlockLayoutCell.prototype._getWidthToRowWidthRatio = function () { return this._widthToRowWidthRatio; }; BlockLayoutCell.prototype._setParentRowScrollable = function (scrollable) { this._parentRowScrollable = scrollable; }; BlockLayoutCell.prototype._getParentRowScrollable = function () { return this._parentRowScrollable; }; return BlockLayoutCell; }, /* bExport= */ true);
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. JavaScript code in this file should be added after the last require_* statement. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require_tree . //= require base
// $Id: turtle.js 138 2010-04-27 11:15:12Z keknehv $ function Turtle (canvas, turtle) { if (canvas && canvas.getContext) { this.wait = 100; this.c = canvas.getContext('2d'); this.canvas = canvas this._top = canvas.offsetTop; this._left = canvas.offsetLeft; this.max_x = canvas.width; this.max_y = canvas.height; this.c.lineCap = "round"; this.turtle = turtle; this.sprite = document.getElementById('sprite'); //this.sprite = document.getElementById('sprite') //.getSVGDocument() //.getElementById('sprite'); this.visible = true; this.undobuffer = []; this.redobuffer = []; this.setup(); } } Turtle.prototype.savestate = function() { // if (this.undobuffer.length > 23) { // this.undobuffer.shift(); // } // this.undobuffer.push(this.getstate()); // // this.redobuffer = []; } Turtle.prototype.getstate = function() { // img = this.c.getImageData(0,0,this.max_x,this.max_y); // return {"x":this.x,"y":this.y,"angle":this.angle,"img":img}; } Turtle.prototype.setstate = function(state) { // this.x = state.x; // this.y = state.y; // this.angle = state.angle; // this.clean_(); // this.c.putImageData(state.img,0,0); // this.update(); // } Turtle.prototype.undo = function() { if (this.undobuffer.length > 0) { prev = this.undobuffer.pop(); curr = this.getstate(); this.setstate(prev); this.redobuffer.push(curr); } else { // Warning } } Turtle.prototype.redo = function() { if (this.redobuffer.length > 0) { next = this.redobuffer.pop(); curr = this.getstate(); this.setstate(next); this.undobuffer.push(curr); } else { // Warning } } Turtle.prototype.hideturtle = function() { this.visible = false; this.update(); } Turtle.prototype.showturtle = function() { this.visible = true; this.update(); } Turtle.prototype.update = function() { if (this.visible && this.x >=0 && this.y >= 0 && this.x <= this.max_x && this.y <= this.max_y) { this.turtle.style.left = parseInt(this._left + this.x-5) + "px"; this.turtle.style.top = parseInt(this._top + this.y-10) + "px"; this.sprite.setAttribute('transform','rotate('+(this.angle)+' 10 10)'); } else { this.turtle.style.left = "-20px"; this.turtle.style.top = "-100px"; } //if (this.active = false) {alert('inativo');} } Turtle.prototype.start = function(){}; Turtle.prototype.stop = function(){}; Turtle.prototype.finish = function(){ //alert('fim'); }; Turtle.prototype.setxy = function(x,y) { this.savestate(); this.x = x; this.y = y; this.update(); } Turtle.prototype.setx = function(x) { this.savestate(); this.x = x; this.update(); } Turtle.prototype.sety = function(y) { this.savestate(); this.y = y; this.update(); } Turtle.prototype.setheading = function(h) { this.savestate(); this.angle = (270+h) % 360; this.update(); } Turtle.prototype.penwidth = function(w) { this.savestate(); this.penwidth_(w); } Turtle.prototype.penwidth_ = function(w) {; this.c.lineWidth=w; } Turtle.prototype.color = function (args) { this.savestate(); this.color_(args) } Turtle.prototype.color_ = function (args) { this.c.strokeStyle = "rgb("+parseInt(args[0])+","+parseInt(args[1])+","+parseInt(args[2])+")"; } Turtle.prototype.arc = function (radius, angle) { this.savestate(); if (this.pen) { this.c.beginPath(); this.c.arc(this.x,this.y, radius, this.radians(), ((this.angle+angle)%360)/180*Math.PI,false); this.c.stroke(); } } Turtle.prototype.arc_point = function (radius, angle) { if (this.pen) { this.c.beginPath(); this.c.arc(this.x,this.y, radius, ((this.angle+angle)%360)/180*Math.PI, ((this.angle+angle+1)%360)/180*Math.PI,false); this.c.stroke(); } } Turtle.prototype.circle = function (radius) { this.savestate(); if (this.pen) { this.c.beginPath(); this.c.arc(this.x,this.y, radius, 0, 2*Math.PI,false); this.c.stroke(); } } Turtle.prototype.forward = function (d) { this.savestate(); this.crawl(d); } Turtle.prototype.crawl = function (d) { this.c.beginPath(); this.c.moveTo(this.x,this.y); var newx = this.x + d * Math.cos(this.radians()); var newy = this.y + d * Math.sin(this.radians()); if (this.pen) { this.c.lineTo(newx,newy); //alert('sending /draw?x='+~~(newx-250)+'&y='+~~(newy-200)); $.get( '/draw?x='+(~~newx-250)+'&y='+(~~newy-200), function( data ) { // passing parameters now }); } else { this.c.moveTo(newx,newy); } this.c.stroke(); // this only works in opera :( this.sleep(); this.x = newx; this.y = newy; this.update(); } Turtle.prototype.backward = function (d) { this.forward(-d); } Turtle.prototype.right = function(angle) { $("#turtle").css("transform","rotate(" + (this.angle + angle+90) + "deg)"); this.savestate(); this.angle = (this.angle + angle) % 360; this.update(); } Turtle.prototype.left = function(angle) { $("#turtle").css("transform","rotate(" + (this.angle + angle-90) + "deg)"); this.savestate(); this.right(-angle); } Turtle.prototype.penup = function() { this.savestate(); this.pen = false; } Turtle.prototype.pendown = function() { this.savestate(); this.pen = true; } Turtle.prototype.radians = function() { return this.angle / 180 * Math.PI; } Turtle.prototype.clean = function() { this.savestate(); this.clean_; } Turtle.prototype.clean_ = function() { old = this.c.fillStyle this.c.fillStyle = "rgb(238,238,238)"; this.c.fillRect(0,0,this.max_x,this.max_y); this.c.fillStyle = old; } Turtle.prototype.clearscreen = function() { this.savestate(); this.clean_(); this.home_(); } Turtle.prototype.reset = function() { this.clean_(); this.setup(); $("#turtle").css("transform","rotate(0deg)"); this.undobuffer = []; this.redobuffer = []; } Turtle.prototype.home = function () { this.savestate(); this.home_(); } Turtle.prototype.home_ = function() { this.x = this.max_x/2; this.y = this.max_y/2; this.angle = 270; this.update(); $("#turtle").css("transform","rotate(0deg)"); } Turtle.prototype.setup = function() { this.home_(); this.penwidth_(1); this.color_([0,0,0]); this.pen = true; } Turtle.prototype.paint = function () {} function DelayCommand (that,fun,args) { this.that = that; this.fun = fun; this.args = args; } DelayCommand.prototype.call = function (that) { return this.fun.apply(this.that,this.args); } function DelayTurtle (canvas, sprite, speed, draw_bits) { this.turtle = new Turtle(canvas, sprite); this.pipeline = null; this.active = false; this.halt = false; this.speed = speed this.drawbits = (draw_bits == false) ? false : true; this.turtle.visible = speed == 25; } DelayTurtle.prototype.start = function(){this.active = true; this.halt = false; this.pipeline = new Array(); this.paint();}; DelayTurtle.prototype.finish = function(){this.active = false;}; DelayTurtle.prototype.stop = function(){this.halt = true;}; DelayTurtle.prototype.paint = function() { if (!this.halt) { var redraw = this.active; if (this.pipeline.length > 0) { var c = 0; do { var fun = this.pipeline.shift(); fun.call() redraw = true; c++; } while (this.speed <= 1 && c< 10 && this.pipeline.length >0) } if (redraw) { var that = this; setTimeout(function(){that.paint.call(that)},this.speed); } } } DelayTurtle.prototype.addCommand = function (fun, args) { this.pipeline.push(new DelayCommand(this.turtle, fun, args)); } // There must be a nicer way to do this DelayTurtle.prototype.forward = function(d) { if (this.drawbits) { var l = Math.abs(d); var s = l/d; this.savestate(); for (var c = 0; c < l; c++ ) { this.addCommand(this.turtle.crawl,[s]) } } else { this.addCommand(this.turtle.forward,[d]); } }; DelayTurtle.prototype.backward = function(d) { this.forward(-d)}; DelayTurtle.prototype.showturtle = function() { this.addCommand(this.turtle.showturtle,arguments)}; DelayTurtle.prototype.hideturtle = function() { this.addCommand(this.turtle.hideturtle,arguments)}; DelayTurtle.prototype.right = function() { this.addCommand(this.turtle.right,arguments)}; DelayTurtle.prototype.left = function() { this.addCommand(this.turtle.left,arguments)}; DelayTurtle.prototype.reset = function() { this.addCommand(this.turtle.reset,arguments)}; DelayTurtle.prototype.clean = function() { this.addCommand(this.turtle.clean,arguments)}; DelayTurtle.prototype.clearscreen = function() { this.addCommand(this.turtle.clearscreen,arguments)}; DelayTurtle.prototype.penup = function() { this.addCommand(this.turtle.penup,arguments)}; DelayTurtle.prototype.pendown = function() { this.addCommand(this.turtle.pendown,arguments)}; DelayTurtle.prototype.penwidth = function() { this.addCommand(this.turtle.penwidth,arguments)}; DelayTurtle.prototype.color = function() { this.addCommand(this.turtle.color,arguments)}; DelayTurtle.prototype.savestate = function() { this.addCommand(this.turtle.savestate,arguments)}; DelayTurtle.prototype.redo = function() { this.addCommand(this.turtle.redo,arguments)}; DelayTurtle.prototype.undo = function() { this.addCommand(this.turtle.undo,arguments)}; DelayTurtle.prototype.arc = function(radius, angle) { if (this.drawbits) { var end = (360+angle) % 360 ; this.savestate(); for (var c = 0; c <= end; c++ ) { this.addCommand(this.turtle.arc_point,[radius,c]) } } else { this.addCommand(this.turtle.arc,[radius,angle]) } }; DelayTurtle.prototype.circle = function(radius) { if (this.drawbits) { this.savestate(); for (var c = 0; c < 360; c++ ) { this.addCommand(this.turtle.arc_point,[radius,c]) } } else { this.addCommand(this.turtle.circle,[radius]) } }; DelayTurtle.prototype.setxy = function() { this.addCommand(this.turtle.setxy,arguments)}; DelayTurtle.prototype.setx = function() { this.addCommand(this.turtle.setx,arguments)}; DelayTurtle.prototype.sety = function() { this.addCommand(this.turtle.sety,arguments)}; DelayTurtle.prototype.setheading = function() { this.addCommand(this.turtle.setheading,arguments)}; DelayTurtle.prototype.home = function() { this.addCommand(this.turtle.home,arguments)};
/* eslint-disable no-console */ const fs = require("fs/promises"); const path = require("path"); const util = require("util"); const cp = require("child_process"); const chokidar = require("chokidar"); const exec = util.promisify(cp.exec); exports.logResult = result => { for (const error of result.errors) { console.error(error.message); } for (const warning of result.warnings) { if (warning.text !== "Unsupported source map comment") { console.warn(warning.text, warning.location); } } }; const rpnp = /^pnp:/; exports.watch = async (build, entry, project, onRebuild) => { const absEntry = path.join(process.cwd(), entry); const projectPath = path.join(path.dirname(__dirname), project); function getInputs(result) { const values = Object.keys(result.metafile.inputs); const ret = []; for (let val of values) { if (val.startsWith("pnp:")) { val = val.replace(rpnp, ""); if (!val.includes(".yarn")) { ret.push(val); } } else { if (!path.isAbsolute(val)) { val = path.join(projectPath, val); } ret.push(val); } } return Array.from(new Set(ret)); } const now = Date.now(); const result = await build(); console.log("built", absEntry, Date.now() - now, "ms"); let awaitingBuildP = null; let watchedPaths = getInputs(result); const watcher = chokidar.watch(watchedPaths, { persistent: true, ignoreInitial: true, }); watcher.on("all", async eventName => { console.log("rebuilding", absEntry); if (awaitingBuildP) { try { await awaitingBuildP; } catch {} } const now = Date.now(); awaitingBuildP = build(); try { const result = await awaitingBuildP; console.log("rebuilt", absEntry, Date.now() - now, "ms"); if (!result.errors.length) { const newWatchedPaths = getInputs(result); const diff = exports.diffPaths(watchedPaths, newWatchedPaths); if (diff.pathsToRemove.length) watcher.unwatch(diff.pathsToRemove); if (diff.pathsToAdd.length) watcher.add(diff.pathsToAdd); watchedPaths = newWatchedPaths; if (onRebuild) { onRebuild(); } } } catch (e) { console.error(e.message); } }); if (!result.errors.length && onRebuild) { onRebuild(); } }; exports.diffPaths = (oldPaths, newPaths) => { const pathsToRemove = []; const pathsToAdd = []; const oldPathsSet = new Set(oldPaths); const newPathsSet = new Set(newPaths); for (const oldPath of oldPaths) { if (!newPathsSet.has(oldPath)) { pathsToRemove.push(oldPath); } } for (const newPath of newPaths) { if (!oldPathsSet.has(newPath)) { pathsToAdd.push(newPath); } } return { pathsToRemove, pathsToAdd }; }; exports.gitRevision = () => { return exec("git rev-parse HEAD").then(v => v.stdout.trim()); }; exports.gitRevisionSync = () => { return cp.execSync("git rev-parse HEAD", { encoding: "utf-8" }).trim(); }; exports.performReplacements = function (contents, values) { const rvar = /\$([a-zA-Z_][a-zA-Z0-9_]*)\b/g; return contents.replace(rvar, (_m, valName) => { if (values[valName] === undefined) { throw new Error("$" + valName + " is not defined"); } return values[valName]; }); }; exports.copyWithReplacements = async function ({ src, binary, values, dst }) { src = path.join(process.cwd(), src); dst = path.join(process.cwd(), dst); const fileContents = await fs.readFile(src, binary ? null : "utf-8"); const contents = values ? exports.performReplacements(fileContents, values) : fileContents; await fs.writeFile(dst, contents, binary ? null : "utf-8"); }; exports.vendorResolverPlugin = function (basePath, vendorPath) { const expr = /vendor\/(.+)/; return { name: "vendor-resolver-plugin", setup: function ({ onResolve }) { onResolve({ filter: expr }, async args => { const name = expr.exec(args.path)[1]; const fullPath = path.join(basePath, vendorPath || "vendor", name + ".js"); return { path: fullPath, }; }); }, }; };
/* --- Day 16: Aunt Sue --- Your Aunt Sue has given you a wonderful gift, and you'd like to send her a thank you card. However, there's a small problem: she signed it "From, Aunt Sue". You have 500 Aunts named "Sue". So, to avoid sending the card to the wrong person, you need to figure out which Aunt Sue (which you conveniently number 1 to 500, for sanity) gave you the gift. You open the present and, as luck would have it, good ol' Aunt Sue got you a My First Crime Scene Analysis Machine! Just what you wanted. Or needed, as the case may be. The My First Crime Scene Analysis Machine (MFCSAM for short) can detect a few specific compounds in a given sample, as well as how many distinct kinds of those compounds there are. According to the instructions, these are what the MFCSAM can detect: - children, by human DNA age analysis. - cats. It doesn't differentiate individual breeds. - Several seemingly random breeds of dog: samoyeds, pomeranians, akitas, and vizslas. - goldfish. No other kinds of fish. - trees, all in one group. - cars, presumably by exhaust or gasoline or something. - perfumes, which is handy, since many of your Aunts Sue wear a few kinds. In fact, many of your Aunts Sue have many of these. You put the wrapping from the gift into the MFCSAM. It beeps inquisitively at you a few times and then prints out a message on ticker tape: children: 3 cats: 7 samoyeds: 2 pomeranians: 3 akitas: 0 vizslas: 0 goldfish: 5 trees: 3 cars: 2 perfumes: 1 You make a list of the things you can remember about each Aunt Sue. Things missing from your list aren't zero - you simply don't remember the value. What is the number of the Sue that got you the gift? */ const MFCSAM_RESULT = { children: 3, cats: 7, samoyeds: 2, pomeranians: 3, akitas: 0, vizslas: 0, goldfish: 5, trees: 3, cars: 2, perfumes: 1 }; export default function soltion(input) { return input.trim() .split('\n') .map(line => { const [, id, items] = line.match(/Sue (\d+): (.*)/); const signs = {}; items.split(',') .forEach(sign => { const [key, value] = sign.split(':').map(i => i.trim()); signs[key] = Number(value); }); return { id, signs }; }) .reduce((a, i) => { const signs = i.signs; if (Object.keys(signs).every(key => signs[key] == MFCSAM_RESULT[key])) { return i.id; } return a; }); };
const path = require('path') const fs = require('fs') const fse = require('fs-extra') const { log } = require('./logger') const appPaths = require('../app-paths') function getStoreFlagPath(storeIndexPath) { return path.join(path.parse(storeIndexPath).dir, 'store-flag.d.ts') } function isInstalled (mode) { const { isInstalled } = require(`../modes/${mode}/${mode}-installation`) return isInstalled() } module.exports = function regenerateTypesFeatureFlags(quasarConf) { // Flags must be available even in pure JS codebases, // because boot and configure wrappers functions files will // provide autocomplete based on them also to JS users // Flags files should be copied over, for every enabled mode, // every time `quasar dev` and `quasar build` are run: // this automatize the upgrade for existing codebases for (const feature of [ 'pwa', 'cordova', 'capacitor', 'ssr', 'store', 'bex' ]) { const [isFeatureInstalled, sourceFlagPath, destFlagPath] = feature === 'store' ? [ quasarConf.store, appPaths.resolve.cli('templates/store/store-flag.d.ts'), appPaths.resolve.app(getStoreFlagPath(quasarConf.sourceFiles.store)) ] : [ isInstalled(feature), appPaths.resolve.cli(`templates/${feature}/${feature}-flag.d.ts`), appPaths.resolve[feature](`${feature}-flag.d.ts`) ] if (isFeatureInstalled && !fs.existsSync(destFlagPath)) { fse.copySync(sourceFlagPath, destFlagPath) log(`'${feature}' feature flag was missing and has been regenerated`) } } }
import { mix } from './objects'; /** * Execute an AJAX request. * * @param {string} method The HTTP method to use. * @param {string} url The URL to send teh request to. * @param {object=} params Key-value paris of query string parameters. * @param {*=} data The request body. * @param {headers=} headers Any headers to set. * @returns {Promise} */ function http({ method, url, params, data, headers }) { return new Promise((resolve, reject) => { let client = new XMLHttpRequest(); let uri = url; if(params) { let queryString = ''; for(let key in params) { if(!params.hasOwnProperty(key)) continue; let symbol = queryString ? '&' : '?'; let s = `${symbol}${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`; queryString += s; } uri += queryString; } client.open(method, uri); if(headers) { for(let key in headers) { if(headers.hasOwnProperty(key)) { let value = headers[key]; client.setRequestHeader(key, value); } } } if(data && (method == 'POST' || method == 'PUT')) { client.send(data); } else { client.send(); } client.onload = function() { if(this.status >= 200 && this.status < 300) { resolve({ status: this.status, body: this.response }); } else { reject({ status: this.status, body: this.response }); } }; client.onerror = function() { reject({ status: this.status, body: this.response }) }; }) } /** * Executes a GET request to the specified location. * * @param {string} url The URL to send the request to. * @param {object=} config The full configuration options. * @returns {Promise} */ http['get'] = (url, config = {}) => http(mix({ url, method: 'GET' }, config)); /** * Executes a POST request to the specified location. * * @param {string} url The URL to send the request to. * @param {*=} data The request body. * @param {object=} config The full configuration options. * @returns {Promise} */ http['post'] = (url, data, config = {}) => http(mix({ url, data, method: 'POST' }, config)); export default http;
var app = { imports: {} }; app.imports = { $ : require('browserify-zepto'), _ : require('underscore'), Backbone : require('backbone') }; app.imports.Backbone.$ = app.imports.$; console.log('Hello World!');
// All code points in the Tamil block as per Unicode v5.1.0: [ 0xB80, 0xB81, 0xB82, 0xB83, 0xB84, 0xB85, 0xB86, 0xB87, 0xB88, 0xB89, 0xB8A, 0xB8B, 0xB8C, 0xB8D, 0xB8E, 0xB8F, 0xB90, 0xB91, 0xB92, 0xB93, 0xB94, 0xB95, 0xB96, 0xB97, 0xB98, 0xB99, 0xB9A, 0xB9B, 0xB9C, 0xB9D, 0xB9E, 0xB9F, 0xBA0, 0xBA1, 0xBA2, 0xBA3, 0xBA4, 0xBA5, 0xBA6, 0xBA7, 0xBA8, 0xBA9, 0xBAA, 0xBAB, 0xBAC, 0xBAD, 0xBAE, 0xBAF, 0xBB0, 0xBB1, 0xBB2, 0xBB3, 0xBB4, 0xBB5, 0xBB6, 0xBB7, 0xBB8, 0xBB9, 0xBBA, 0xBBB, 0xBBC, 0xBBD, 0xBBE, 0xBBF, 0xBC0, 0xBC1, 0xBC2, 0xBC3, 0xBC4, 0xBC5, 0xBC6, 0xBC7, 0xBC8, 0xBC9, 0xBCA, 0xBCB, 0xBCC, 0xBCD, 0xBCE, 0xBCF, 0xBD0, 0xBD1, 0xBD2, 0xBD3, 0xBD4, 0xBD5, 0xBD6, 0xBD7, 0xBD8, 0xBD9, 0xBDA, 0xBDB, 0xBDC, 0xBDD, 0xBDE, 0xBDF, 0xBE0, 0xBE1, 0xBE2, 0xBE3, 0xBE4, 0xBE5, 0xBE6, 0xBE7, 0xBE8, 0xBE9, 0xBEA, 0xBEB, 0xBEC, 0xBED, 0xBEE, 0xBEF, 0xBF0, 0xBF1, 0xBF2, 0xBF3, 0xBF4, 0xBF5, 0xBF6, 0xBF7, 0xBF8, 0xBF9, 0xBFA, 0xBFB, 0xBFC, 0xBFD, 0xBFE, 0xBFF ];
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ var exec = require('cordova/exec'); /** * Provides access to the vibration mechanism on the device. */ module.exports = { /** * Vibrates the device for a given amount of time or for a given pattern or immediately cancels any ongoing vibrations (depending on the parameter). * * @param {Integer} param The number of milliseconds to vibrate (if 0, cancels vibration) * * * @param {Array of Integer} param Pattern with which to vibrate the device. * Pass in an array of integers that * are the durations for which to * turn on or off the vibrator in * milliseconds. The FIRST value * indicates the * number of milliseconds for which * to keep the vibrator ON before * turning it off. The NEXT value indicates the * number of milliseconds for which * to keep the vibrator OFF before * turning it on. Subsequent values * alternate between durations in * milliseconds to turn the vibrator * off or to turn the vibrator on. * (if empty, cancels vibration) */ vibrate: function(param) { /* Aligning with w3c spec */ //vibrate if ((typeof param == 'number') && param != 0) exec(null, null, "Vibration", "vibrate", [param]); //vibrate with array ( i.e. vibrate([3000]) ) else if ((typeof param == 'object') && param.length == 1) { //cancel if vibrate([0]) if (param[0] == 0) exec(null, null, "Vibration", "cancelVibration", []); //else vibrate else exec(null, null, "Vibration", "vibrate", [param[0]]); } //vibrate with a pattern else if ((typeof param == 'object') && param.length > 1) { var repeat = -1; //no repeat exec(null, null, "Vibration", "vibrateWithPattern", [param, repeat]); } //cancel vibration (param = 0 or []) else exec(null, null, "Vibration", "cancelVibration", []); return true; }, /** * Vibrates the device with a given pattern. * * @param {Array of Integer} pattern Pattern with which to vibrate the device. * Pass in an array of integers that * are the durations for which to * turn on or off the vibrator in * milliseconds. The first value * indicates the number of milliseconds * to wait before turning the vibrator * on. The next value indicates the * number of milliseconds for which * to keep the vibrator on before * turning it off. Subsequent values * alternate between durations in * milliseconds to turn the vibrator * off or to turn the vibrator on. * * @param {Integer} repeat Optional index into the pattern array at which * to start repeating (will repeat until canceled), * or -1 for no repetition (default). */ vibrateWithPattern: function(pattern, repeat) { repeat = (typeof repeat !== "undefined") ? repeat : -1; pattern.unshift(0); //add a 0 at beginning for backwards compatibility from w3c spec exec(null, null, "Vibration", "vibrateWithPattern", [pattern, repeat]); }, /** * Immediately cancels any currently running vibration. */ cancelVibration: function() { exec(null, null, "Vibration", "cancelVibration", []); } };
/** * Copyright 2012-2019, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; module.exports = { moduleType: 'locale', name: 'es', dictionary: { 'Autoscale': 'Autoescalar', // components/modebar/buttons.js:139 'Box Select': 'Seleccionar Caja', // components/modebar/buttons.js:103 'Click to enter Colorscale title': 'Introducir el título de la Escala de Color', // plots/plots.js:303 'Click to enter Component A title': 'Introducir el título del Componente A', // plots/ternary/ternary.js:392 'Click to enter Component B title': 'Introducir el título del Componente B', // plots/ternary/ternary.js:406 'Click to enter Component C title': 'Introducir el título del Componente C', // plots/ternary/ternary.js:417 'Click to enter Plot title': 'Introducir el título de la Gráfica', // plot_api/plot_api.js:579 'Click to enter X axis title': 'Introducir el título del eje X', // plots/plots.js:301 'Click to enter Y axis title': 'Introducir el título del eje Y', // plots/plots.js:302 'Click to enter radial axis title': 'Introducir el título del eje radial', 'Compare data on hover': 'Comparar datos al pasar por encima', // components/modebar/buttons.js:167 'Double-click on legend to isolate one trace': 'Haga doble-clic en la leyenda para aislar una traza', // components/legend/handle_click.js:90 'Double-click to zoom back out': 'Haga doble-clic para restaurar la escala', // plots/cartesian/dragbox.js:335 'Download plot as a png': 'Descargar gráfica como png', // components/modebar/buttons.js:52 'Edit in Chart Studio': 'Editar en Chart Studio', // components/modebar/buttons.js:76 'IE only supports svg. Changing format to svg.': 'IE solo soporta svg. Cambiando formato a svg.', // components/modebar/buttons.js:60 'Lasso Select': 'Seleccionar con lazo', // components/modebar/buttons.js:112 'Orbital rotation': 'Rotación esférica', // components/modebar/buttons.js:279 'Pan': 'Modo Panorámica', // components/modebar/buttons.js:94 'Produced with Plotly': 'Hecho con Plotly', // components/modebar/modebar.js:256 'Reset': 'Reiniciar', // components/modebar/buttons.js:431 'Reset axes': 'Reiniciar ejes', // components/modebar/buttons.js:148 'Reset camera to default': 'Restaurar cámara predeterminada', // components/modebar/buttons.js:313 'Reset camera to last save': 'Restaurar anterior cámara', // components/modebar/buttons.js:321 'Reset view': 'Restaurar vista', // components/modebar/buttons.js:582 'Reset views': 'Restaurar vistas', // components/modebar/buttons.js:528 'Show closest data on hover': 'Mostrar el dato más cercano al pasar por encima', // components/modebar/buttons.js:157 'Snapshot succeeded': 'La captura de la instantánea finalizó correctamente', // components/modebar/buttons.js:66 'Sorry, there was a problem downloading your snapshot!': '¡La descarga de la instantánea falló!', // components/modebar/buttons.js:69 'Taking snapshot - this may take a few seconds': 'Capturando una instantánea - podría tardar unos segundos', // components/modebar/buttons.js:57 'Toggle Spike Lines': 'Mostrar/Ocultar Guías', // components/modebar/buttons.js:547 'Toggle show closest data on hover': 'Activar/Desactivar mostrar el dato más cercano al pasar por encima', // components/modebar/buttons.js:352 'Turntable rotation': 'Rotación plana', // components/modebar/buttons.js:288 'Zoom': 'Modo Ampliar/Reducir', // components/modebar/buttons.js:85 'Zoom in': 'Ampliar', // components/modebar/buttons.js:121 'Zoom out': 'Reducir', // components/modebar/buttons.js:130 'close:': 'cierre:', // traces/ohlc/transform.js:139 'high:': 'alza:', // traces/ohlc/transform.js:137 'incoming flow count:': 'flujo de entrada:', // traces/sankey/plot.js:142 'kde:': 'edp:', // traces/violin/calc.js:73 'lat:': 'lat:', // traces/scattergeo/calc.js:48 'lon:': 'lon:', // traces/scattergeo/calc.js:49 'low:': 'baja:', // traces/ohlc/transform.js:138 'lower fence:': 'límite inferior:', // traces/box/calc.js:134 'max:': 'máx:', // traces/box/calc.js:132 'mean ± σ:': 'media ± σ:', // traces/box/calc.js:133 'mean:': 'media:', // traces/box/calc.js:133 'median:': 'mediana:', // traces/box/calc.js:128 'min:': 'mín:', // traces/box/calc.js:129 'new text': 'nuevo texto', 'open:': 'apertura:', // traces/ohlc/transform.js:136 'outgoing flow count:': 'flujo de salida:', // traces/sankey/plot.js:143 'q1:': 'q1:', // traces/box/calc.js:130 'q3:': 'q3:', // traces/box/calc.js:131 'source:': 'fuente:', // traces/sankey/plot.js:140 'target:': 'destino:', // traces/sankey/plot.js:141 'trace': 'traza', // plots/plots.js:305 'upper fence:': 'límite superior:' // traces/box/calc.js:135 }, format: { days: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'], shortDays: ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'], months: [ 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre' ], shortMonths: [ 'Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic' ], date: '%d/%m/%Y', decimal: ',', thousands: ' ' } };
import BaseModel, { jsonSchemaModel } from '../base'; @jsonSchemaModel({ title: 'Watcher' }) export default class Watcher extends BaseModel { watch() { throw new Error('Not Implemented'); } }
(function() { 'use strict'; angular .module('kcmDashboardApp.kcm-menu') .directive('kcmMenu', kcmMenu); function kcmMenu() { return { restrict: 'E', templateUrl: 'scripts/shared/kcm-menu/kcm-menu.directive.html' }; } })();