code
stringlengths
2
1.05M
/** * Function bind polyfill * https://github.com/ariya/phantomjs/issues/10522 */ if (!Function.prototype.bind) { Function.prototype.bind = function (context /* ...args */) { var fn = this; var args = Array.prototype.slice.call(arguments, 1); if (typeof(fn) !== "function") { throw new TypeError("Function.prototype.bind - context must be a valid function"); } return function () { return fn.apply(context, args.concat(Array.prototype.slice.call(arguments))); }; }; }
/** * Initialize the state for the It's A Trap script. */ (() => { 'use strict'; /** * The ItsATrap state data. * @typedef {object} ItsATrapState * @property {object} noticedTraps * The set of IDs for traps that have been noticed by passive perception. * @property {string} theme * The name of the TrapTheme currently being used. */ state.ItsATrap = state.ItsATrap || {}; _.defaults(state.ItsATrap, { noticedTraps: {}, userOptions: {} }); _.defaults(state.ItsATrap.userOptions, { revealTrapsToMap: false, announcer: 'Admiral Ackbar' }); // Set the theme from the useroptions. let useroptions = globalconfig && globalconfig.itsatrap; if(useroptions) { state.ItsATrap.userOptions = { revealTrapsToMap: useroptions.revealTrapsToMap === 'true' || false, announcer: useroptions.announcer || 'Admiral Ackbar' }; } })(); /** * The main interface and bootstrap script for It's A Trap. */ var ItsATrap = (() => { 'use strict'; const REMOTE_ACTIVATE_CMD = '!itsATrapRemoteActivate'; // The collection of registered TrapThemes keyed by name. let trapThemes = {}; // The installed trap theme that is being used. let curTheme = 'default'; /** * Activates a trap. * @param {Graphic} trap * @param {Graphic} [activatingVictim] * The victim that triggered the trap. */ function activateTrap(trap, activatingVictim) { let theme = getTheme(); // Apply the trap's effects to any victims in its area and to the // activating victim, using the configured trap theme. let victims = getTrapVictims(trap, activatingVictim); if(victims.length > 0) _.each(victims, victim => { let effect = new TrapEffect(trap, victim); theme.activateEffect(effect); }); else { // In the absence of any victims, activate the trap with the default // theme, which will only display the trap's message. let defaultTheme = trapThemes['default']; let effect = new TrapEffect(trap); defaultTheme.activateEffect(effect); } } /** * Checks if a token passively searched for any traps during its last * movement. * @private * @param {TrapTheme} theme * @param {Graphic} token */ function _checkPassiveSearch(theme, token) { if(theme.passiveSearch && theme.passiveSearch !== _.noop) { _.chain(getSearchableTraps(token)) .filter(trap => { // Only search for traps that are close enough to be spotted. let effect = new TrapEffect(trap, token); let dist = getSearchDistance(token, trap); let searchDist = trap.get('aura2_radius') || effect.searchDist; return (!searchDist || dist < searchDist); }) .each(trap => { theme.passiveSearch(trap, token); }); } } /** * Checks if a token activated or passively spotted any traps during * its last movement. * @private * @param {Graphic} token */ function _checkTrapInteractions(token) { // Objects on the GM layer don't set off traps. if(token.get("layer") === "objects") { try { let theme = getTheme(); if(!theme) { log('ERROR - It\'s A Trap!: TrapTheme does not exist - ' + curTheme + '. Using default TrapTheme.'); theme = trapThemes['default']; } // Did the character set off a trap? _checkTrapActivations(theme, token); // If the theme has passive searching, do a passive search for traps. _checkPassiveSearch(theme, token); } catch(err) { log('ERROR - It\'s A Trap!: ' + err.message); log(err.stack); } } } /** * Checks if a token activated any traps during its last movement. * @private * @param {TrapTheme} theme * @param {Graphic} token */ function _checkTrapActivations(theme, token) { let collisions = getTrapCollisions(token); _.find(collisions, collision => { let trap = collision.other; // Skip if the trap is disabled. if(trap.get('status_interdiction')) return false; let trapEffect = (new TrapEffect(trap, token)).json; trapEffect.stopAt = trapEffect.stopAt || 'center'; // Figure out where to stop the token. if(trapEffect.stopAt === 'edge' && !trapEffect.gmOnly) { let x = collision.pt[0]; let y = collision.pt[1]; token.set("lastmove",""); token.set("left", x); token.set("top", y); } else if(trapEffect.stopAt === 'center' && !trapEffect.gmOnly) { let x = trap.get("left"); let y = trap.get("top"); token.set("lastmove",""); token.set("left", x); token.set("top", y); } // Apply the trap's effects to any victims in its area. if(collision.triggeredByPath) activateTrap(trap); else activateTrap(trap, token); // Stop activating traps if this trap stopped the token. return (trapEffect.stopAt !== 'none'); }); } /** * Gets the point for a token. * @private * @param {Graphic} token * @return {vec3} */ function _getPt(token) { return [token.get('left'), token.get('top'), 1]; } /** * Gets all the traps that a token has line-of-sight to, with no limit for * range. Line-of-sight is blocked by paths on the dynamic lighting layer. * @param {Graphic} charToken * @return {Graphic[]} * The list of traps that charToken has line-of-sight to. */ function getSearchableTraps(charToken) { let pageId = charToken.get('_pageid'); let traps = getTrapsOnPage(pageId); return LineOfSight.filterTokens(charToken, traps); } /** * Gets the distance between two tokens in their page's units. * @param {Graphic} token1 * @param {Graphic} token2 * @return {number} */ function getSearchDistance(token1, token2) { let p1 = _getPt(token1); let p2 = _getPt(token2); let r1 = token1.get('width')/2; let r2 = token2.get('width')/2; let page = getObj('page', token1.get('_pageid')); let scale = page.get('scale_number'); let pixelDist = Math.max(0, VecMath.dist(p1, p2) - r1 - r2); return pixelDist/70*scale; } /** * Gets the theme currently being used to interpret TrapEffects spawned * when a character activates a trap. * @return {TrapTheme} */ function getTheme() { return trapThemes[curTheme]; } /** * Returns the list of all traps a token would collide with during its last * movement. The traps are sorted in the order that the token will collide * with them. * @param {Graphic} token * @return {TokenCollisions.Collision[]} */ function getTrapCollisions(token) { let pageId = token.get('_pageid'); let traps = getTrapsOnPage(pageId); // A llambda to test if a token is flying. let isFlying = x => { return x.get("status_fluffy-wing"); }; let pathsToTraps = {}; // Some traps don't affect flying tokens. traps = _.chain(traps) .filter(trap => { return !isFlying(token) || isFlying(trap); }) // Use paths for collisions if trigger paths are set. .map(trap => { let effect = new TrapEffect(trap); if(effect.triggerPaths) { return _.map(effect.triggerPaths, id => { if(pathsToTraps[id]) pathsToTraps[id].push(trap); else pathsToTraps[id] = [trap]; return getObj('path', id) || trap; }); } else return trap; }) .flatten() .value(); // Get the collisions. return _.chain(TokenCollisions.getCollisions(token, traps, {detailed: true})) .map(collision => { // Convert path collisions back into trap token collisions. if(collision.other.get('_type') === 'path') { let pathId = collision.other.get('_id'); return _.map(pathsToTraps[pathId], trap => { return { token: collision.token, other: trap, pt: collision.pt, dist: collision.dist, triggeredByPath: true }; }); } else return collision; }) .flatten() .value(); } /** * Gets the list of all the traps on the specified page. * @param {string} pageId * @return {Graphic[]} */ function getTrapsOnPage(pageId) { return findObjs({ _pageid: pageId, _type: "graphic", status_cobweb: true, layer: "gmlayer" }); } /** * Gets the list of victims within an activated trap's area of effect. * @param {Graphic} trap * @param {Graphic} triggerVictim * @return {Graphic[]} */ function getTrapVictims(trap, triggerVictim) { let range = trap.get('aura1_radius'); let pageId = trap.get('_pageid'); let victims = [triggerVictim]; if(range !== '') { let otherTokens = findObjs({ _pageid: pageId, _type: 'graphic', layer: 'objects' }); let pageScale = getObj('page', pageId).get('scale_number'); range *= 70/pageScale; let squareArea = trap.get('aura1_square'); victims = victims.concat(LineOfSight.filterTokens(trap, otherTokens, range, squareArea)); } return _.chain(victims) .unique() .compact() .value(); } /** * Marks a trap with a circle and a ping. * @private * @param {Graphic} trap */ function _markTrap(trap) { let radius = trap.get('width')/2; let x = trap.get('left'); let y = trap.get('top'); let pageId = trap.get('_pageid'); // Circle the trap's trigger area. let circle = new PathMath.Circle([x, y, 1], radius); circle.render(pageId, 'objects', { stroke: '#ffff00', // yellow stroke_width: 5 }); sendPing(x, y, pageId); } /** * Marks a trap as being noticed by a character's passive search. * @param {Graphic} trap * @param {string} noticeMessage A message to display when the trap is noticed. * @return {boolean} * true if the trap has not been noticed yet. */ function noticeTrap(trap, noticeMessage) { let id = trap.get('_id'); let effect = new TrapEffect(trap); let announcer = state.ItsATrap.userOptions.announcer; if(!state.ItsATrap.noticedTraps[id]) { state.ItsATrap.noticedTraps[id] = true; sendChat(announcer, noticeMessage); if(effect.revealWhenSpotted) revealTrap(trap); else _markTrap(trap); return true; } else return false; } /** * Registers a TrapTheme. * @param {TrapTheme} theme */ function registerTheme(theme) { log('It\'s A Trap!: Registered TrapTheme - ' + theme.name + '.'); trapThemes[theme.name] = theme; curTheme = theme.name; } /** * Reveals a trap to the objects or map layer. * @param {Graphic} trap */ function revealTrap(trap) { let effect = new TrapEffect(trap); if(effect.revealLayer === 'objects') { trap.set('layer', 'objects'); toBack(trap); } else { trap.set('layer', 'map'); toFront(trap); } sendPing(trap.get('left'), trap.get('top'), trap.get('_pageid')); } /** * Removes a trap from the state's collection of noticed traps. * @private * @param {Graphic} trap */ function _unNoticeTrap(trap) { let id = trap.get('_id'); if(state.ItsATrap.noticedTraps[id]) delete state.ItsATrap.noticedTraps[id]; } // Create macro for the remote activation command. on('ready', () => { let numRetries = 3; let interval = setInterval(() => { let theme = getTheme(); if(theme) { log(`☒☠☒ Initialized It's A Trap! using theme '${getTheme().name}' ☒☠☒`); clearInterval(interval); } else if(numRetries > 0) numRetries--; else clearInterval(interval); }, 1000); }); // Handle macro commands. on('chat:message', msg => { try { if(msg.content === REMOTE_ACTIVATE_CMD) { let theme = getTheme(); _.each(msg.selected, item => { let trap = getObj('graphic', item._id); activateTrap(trap); }); } } catch(err) { log(`It's A Trap ERROR: ${err.msg}`); log(err.stack); } }); /** * When a graphic on the objects layer moves, run the script to see if it * passed through any traps. */ on("change:graphic:lastmove", function(token) { try { // Check for trap interactions if the token isn't also a trap. if(!token.get('status_cobweb')) _checkTrapInteractions(token); } catch(err) { log(`It's A Trap ERROR: ${err.msg}`); log(err.stack); } }); // If a trap is moved back to the GM layer, remove it from the set of noticed traps. on('change:graphic:layer', token => { if(token.get('layer') === 'gmlayer') _unNoticeTrap(token); }); // When a trap's token is destroyed, remove it from the set of noticed traps. on('destroy:graphic', function(token) { _unNoticeTrap(token); }); return { activateTrap, getSearchDistance, getTheme, getTrapCollisions, getTrapsOnPage, noticeTrap, registerTheme, revealTrap, REMOTE_ACTIVATE_CMD }; })(); /** * The configured JSON properties of a trap. This can be extended to add * additional properties for system-specific themes. */ var TrapEffect = (() => { 'use strict'; const DEFAULT_FX = { maxParticles: 100, emissionRate: 3, size: 35, sizeRandom: 15, lifeSpan: 10, lifeSpanRandom: 3, speed: 3, speedRandom: 1.5, gravity: {x: 0.01, y: 0.01}, angle: 0, angleRandom: 180, duration: -1, startColour: [220, 35, 0, 1], startColourRandom: [62, 0, 0, 0.25], endColour: [220, 35, 0, 0], endColourRandom:[60, 60, 60, 0] }; return class TrapEffect { /** * An API chat command that will be executed when the trap is activated. * If the constants TRAP_ID and VICTIM_ID are provided, * they will be replaced by the IDs for the trap token and the token for * the trap's victim, respectively in the API chat command message. * @type {string} */ get api() { return this._effect.api; } /** * Specifications for an AreasOfEffect script graphic that is spawned * when a trap is triggered. * @typedef {object} TrapEffect.AreaOfEffect * @property {String} name The name of the AoE effect. * @property {vec2} [direction] The direction of the effect. If omitted, * it will be extended toward the triggering token. */ /** * JSON defining a graphic to spawn with the AreasOfEffect script if * it is installed and the trap is triggered. * @type {TrapEffect.AreaOfEffect} */ get areaOfEffect() { return this._effect.areaOfEffect; } /** * Configuration for special FX that are created when the trap activates. * @type {object} * @property {(string | FxJsonDefinition)} name * Either the name of the FX that is created * (built-in or user-made), or a custom FX JSON defintion. * @property {vec2} offset * The offset of the special FX, in units from the trap's token. * @property {vec2} direction * For beam-like FX, this specifies the vector for the FX's * direction. If left blank, it will fire towards the token * that activated the trap. */ get fx() { return this._effect.fx; } /** * Whether the trap should only be announced to the GM when it is activated. * @type {boolean} */ get gmOnly() { return this._effect.gmOnly; } /** * Gets a copy of the trap's JSON properties. * @readonly * @type {object} */ get json() { return _.clone(this._effect); } /** * JSON defining options to produce an explosion/implosion effect with * the KABOOM script. * @type {object} */ get kaboom() { return this._effect.kaboom; } /** * The flavor message displayed when the trap is activated. If left * blank, a default message will be generated based on the name of the * trap's token. * @type {string} */ get message() { return this._effect.message || this._createDefaultTrapMessage(); } /** * The trap's name. * @type {string} */ get name() { return this._trap.get('name'); } /** * Secret notes for the GM. * @type {string} */ get notes() { return this._effect.notes; } /** * The layer that the trap gets revealed to. * @type {string} */ get revealLayer() { return this._effect.revealLayer; } /** * Whether the trap is revealed when it is spotted. * @type {boolean} */ get revealWhenSpotted() { return this._effect.revealWhenSpotted; } /** * The name of a sound played when the trap is activated. * @type {string} */ get sound() { return this._effect.sound; } /** * This is where the trap stops the token. * If "edge", then the token is stopped at the trap's edge. * If "center", then the token is stopped at the trap's center. * If "none", the token is not stopped by the trap. * @type {string} */ get stopAt() { return this._effect.stopAt; } /** * Command arguments for integration with the TokenMod script by The Aaron. * @type {string} */ get tokenMod() { return this._effect.tokenMod; } /** * The trap this TrapEffect represents. * @type {Graphic} */ get trap() { return this._trap; } /** * The ID of the trap. * @type {uuid} */ get trapId() { return this._trap.get('_id'); } /** * A list of path IDs defining an area that triggers this trap. * @type {string[]} */ get triggerPaths() { return this._effect.triggerPaths; } /** * A list of names or IDs for traps that will also be triggered when this * trap is activated. * @type {string[]} */ get triggers() { return this._effect.triggers; } /** * The name for the trap/secret's type displayed in automated messages. * @type {string} */ get type() { return this._effect.type; } /** * The victim who activated the trap. * @type {Graphic} */ get victim() { return this._victim; } /** * The ID of the trap's victim. * @type {uuid} */ get victimId() { return this._victim && this._victim.get('_id'); } /** * @param {Graphic} trap * The trap's token. * @param {Graphic} [victim] * The token for the character that activated the trap. */ constructor(trap, victim) { let effect = {}; // URI-escape the notes and remove the HTML elements. let notes = trap.get('gmnotes'); try { notes = decodeURIComponent(notes).trim(); } catch(err) { notes = unescape(notes).trim(); } if(notes) { try { notes = notes.split(/<[/]?.+?>/g).join(''); effect = JSON.parse(notes); } catch(err) { effect.message = 'ERROR: invalid TrapEffect JSON.'; } } this._effect = effect; this._trap = trap; this._victim = victim; } /** * Activates the traps that are triggered by this trap. */ activateTriggers() { let triggers = this.triggers; if(triggers) { let otherTraps = ItsATrap.getTrapsOnPage(this._trap.get('_pageid')); let triggeredTraps = _.filter(otherTraps, trap => { // Skip if the trap is disabled. if(trap.get('status_interdiction')) return false; return triggers.indexOf(trap.get('name')) !== -1 || triggers.indexOf(trap.get('_id')) !== -1; }); _.each(triggeredTraps, trap => { ItsATrap.activateTrap(trap); }); } } /** * Announces the activated trap. * This should be called by TrapThemes to inform everyone about a trap * that has been triggered and its results. Fancy HTML formatting for * the message is encouraged. If the trap's effect has gmOnly set, * then the message will only be shown to the GM. * This also takes care of playing the trap's sound, FX, and API command, * they are provided. * @param {string} [message] * The message for the trap results displayed in the chat. If * omitted, then the trap's raw message will be displayed. */ announce(message) { message = message || this.message; let announcer = state.ItsATrap.userOptions.announcer; // Display the message to everyone, unless it's a secret. if(this.gmOnly) { message = '/w gm ' + message; sendChat(announcer, message); // Whisper any secret notes to the GM. if(this.notes) sendChat(announcer, '/w gm Trap Notes:<br/>' + this.notes); } else { sendChat(announcer, message); // Whisper any secret notes to the GM. if(this.notes) sendChat(announcer, '/w gm Trap Notes:<br/>' + this.notes); // Reveal the trap if it's set to become visible. if(this.trap.get('status_bleeding-eye')) ItsATrap.revealTrap(this.trap); // Produce special outputs if it has any. this.playSound(); this.playFX(); this.playAreaOfEffect(); this.playKaboom(); this.playTokenMod(); this.playApi(); // Allow traps to trigger each other using the 'triggers' property. this.activateTriggers(); } } /** * Creates a default message for the trap. * @private * @return {string} */ _createDefaultTrapMessage() { if(this.victim) { if(this.name) return `${this.victim.get('name')} set off a trap: ${this.name}!`; else return `${this.victim.get('name')} set off a trap!`; } else { if(this.name) return `${this.name} was activated!`; else return `A trap was activated!`; } } /** * Executes the trap's API chat command if it has one. */ playApi() { let api = this.api; if(api) { api = api.split('TRAP_ID').join(this.trapId); api = api.split('VICTIM_ID').join(this.victimId); sendChat('ItsATrap-api', api); } } /** * Spawns the AreasOfEffect graphic for this trap. If AreasOfEffect is * not installed, then this has no effect. */ playAreaOfEffect() { if(typeof AreasOfEffect !== 'undefined' && this.areaOfEffect) { let direction = (this.areaOfEffect.direction && VecMath.scale(this.areaOfEffect.direction, 70)) || (() => { if(this._victim) return [ this._victim.get('left') - this._trap.get('left'), this._victim.get('top') - this._trap.get('top') ]; else return [0, 0]; })(); direction[2] = 0; let p1 = [this._trap.get('left'), this._trap.get('top'), 1]; let p2 = VecMath.add(p1, direction); if(VecMath.dist(p1, p2) > 0) { let segments = [[p1, p2]]; let pathJson = PathMath.segmentsToPath(segments); let path = createObj('path', _.extend(pathJson, { _pageid: this._trap.get('_pageid'), layer: 'objects', stroke: '#ff0000' })); let aoeGraphic = AreasOfEffect.applyEffect('', this.areaOfEffect.name, path); aoeGraphic.set('layer', 'map'); toFront(aoeGraphic); } } } /** * Spawns built-in or custom FX for an activated trap. */ playFX() { var pageId = this._trap.get('_pageid'); if(this.fx) { var offset = this.fx.offset || [0, 0]; var origin = [ this._trap.get('left') + offset[0]*70, this._trap.get('top') + offset[1]*70 ]; var direction = this.fx.direction || (() => { if(this._victim) return [ this._victim.get('left') - origin[0], this._victim.get('top') - origin[1] ]; else return [ 0, 1 ]; })(); this._playFXNamed(this.fx.name, pageId, origin, direction); } } /** * Play FX using a named effect. * @private * @param {string} name * @param {uuid} pageId * @param {vec2} origin * @param {vec2} direction */ _playFXNamed(name, pageId, origin, direction) { let x = origin[0]; let y = origin[1]; let fx = name; let isBeamLike = false; var custFx = findObjs({ _type: 'custfx', name: name })[0]; if(custFx) { fx = custFx.get('_id'); isBeamLike = custFx.get('definition').angle === -1; } else isBeamLike = !!_.find(['beam-', 'breath-', 'splatter-'], type => { return name.startsWith(type); }); if(isBeamLike) { let p1 = { x: x, y: y }; let p2 = { x: x + direction[0], y: y + direction[1] }; spawnFxBetweenPoints(p1, p2, fx, pageId); } else spawnFx(x, y, fx, pageId); } /** * Produces an explosion/implosion effect with the KABOOM script. */ playKaboom() { if(typeof KABOOM !== 'undefined' && this.kaboom) { let center = [this.trap.get('left'), this.trap.get('top')]; let options = { effectPower: this.kaboom.power, effectRadius: this.kaboom.radius, type: this.kaboom.type, scatter: this.kaboom.scatter }; KABOOM.NOW(options, center); } } /** * Plays a TrapEffect's sound, if it has one. */ playSound() { if(this.sound) { var sound = findObjs({ _type: 'jukeboxtrack', title: this.sound })[0]; if(sound) { sound.set('playing', true); sound.set('softstop', false); } else { let msg = 'Could not find sound "' + this.sound + '".'; sendChat('ItsATrap-api', msg); } } } /** * Invokes TokenMod on the victim's token. */ playTokenMod() { if(typeof TokenMod !== 'undefined' && this.tokenMod && this._victim) { let victimId = this._victim.get('id'); let command = '!token-mod ' + this.tokenMod + ' --ids ' + victimId; // Since playerIsGM fails for the player ID "API", we'll need to // temporarily switch TokenMod's playersCanUse_ids option to true. if(!TrapEffect.tokenModTimeout) { let temp = state.TokenMod.playersCanUse_ids; TrapEffect.tokenModTimeout = setTimeout(() => { state.TokenMod.playersCanUse_ids = temp; TrapEffect.tokenModTimeout = undefined; }, 1000); } state.TokenMod.playersCanUse_ids = true; sendChat('It\'s A Trap', command); } } }; })(); /** * A small library for checking if a token has line of sight to other tokens. */ var LineOfSight = (() => { 'use strict'; /** * Gets the point for a token. * @private * @param {Graphic} token * @return {vec3} */ function _getPt(token) { return [token.get('left'), token.get('top'), 1]; } return class LineOfSight { /** * Gets the tokens that a token has line of sight to. * @private * @param {Graphic} token * @param {Graphic[]} otherTokens * @param {number} [range=Infinity] * The line-of-sight range in pixels. * @param {boolean} [isSquareRange=false] * @return {Graphic[]} */ static filterTokens(token, otherTokens, range, isSquareRange) { if(_.isUndefined(range)) range = Infinity; let pageId = token.get('_pageid'); let tokenPt = _getPt(token); let tokenRW = token.get('width')/2-1; let tokenRH = token.get('height')/2-1; let wallPaths = findObjs({ _type: 'path', _pageid: pageId, layer: 'walls' }); let wallSegments = PathMath.toSegments(wallPaths); return _.filter(otherTokens, other => { let otherPt = _getPt(other); let otherRW = other.get('width')/2; let otherRH = other.get('height')/2; // Skip tokens that are out of range. if(isSquareRange && ( Math.abs(tokenPt[0]-otherPt[0]) >= range + otherRW + tokenRW || Math.abs(tokenPt[1]-otherPt[1]) >= range + otherRH + tokenRH)) return false; else if(!isSquareRange && VecMath.dist(tokenPt, otherPt) >= range + tokenRW + otherRW) return false; let segToOther = [tokenPt, otherPt]; return !_.find(wallSegments, wallSeg => { return PathMath.segmentIntersection(segToOther, wallSeg); }); }); } }; })(); /** * A module that presents a wizard for setting up traps instead of * hand-crafting the JSON for them. */ var ItsATrapCreationWizard = (() => { 'use strict'; const DISPLAY_WIZARD_CMD = '!ItsATrap_trapCreationWizard_showMenu'; const MODIFY_CORE_PROPERTY_CMD = '!ItsATrap_trapCreationWizard_modifyTrapCore'; const MODIFY_THEME_PROPERTY_CMD = '!ItsATrap_trapCreationWizard_modifyTrapTheme'; const MENU_CSS = { 'optionsTable': { 'width': '100%' }, 'menu': { 'background': '#fff', 'border': 'solid 1px #000', 'border-radius': '5px', 'font-weight': 'bold', 'margin-bottom': '1em', 'overflow': 'hidden' }, 'menuBody': { 'padding': '5px', 'text-align': 'center' }, 'menuHeader': { 'background': '#000', 'color': '#fff', 'text-align': 'center' } }; // The last trap that was edited in the wizard. let curTrap; /** * Displays the menu for setting up a trap. * @param {string} who * @param {string} playerid * @param {Graphic} trapToken */ function displayWizard(who, playerId, trapToken) { curTrap = trapToken; let content = new HtmlBuilder('div'); // Core properties content.append('h4', 'Core properties'); let coreProperties = getCoreProperties(trapToken); content.append(_displayWizardProperties(MODIFY_CORE_PROPERTY_CMD, coreProperties)); // Shape properties content.append('h4', 'Shape properties', { style: { 'margin-top' : '2em' } }); let shapeProperties = getShapeProperties(trapToken); content.append(_displayWizardProperties(MODIFY_CORE_PROPERTY_CMD, shapeProperties)); // Trigger properties content.append('h4', 'Trigger properties', { style: { 'margin-top' : '2em' } }); let triggerProperties = getTriggerProperties(trapToken); content.append(_displayWizardProperties(MODIFY_CORE_PROPERTY_CMD, triggerProperties)); // Reveal properties content.append('h4', 'Reveal properties', { style: { 'margin-top' : '2em' } }); let revealProperties = getRevealProperties(trapToken); content.append(_displayWizardProperties(MODIFY_CORE_PROPERTY_CMD, revealProperties)); // Special properties content.append('h4', 'Special properties', { style: { 'margin-top' : '2em' } }); let specialProperties = getSpecialProperties(trapToken); content.append(_displayWizardProperties(MODIFY_CORE_PROPERTY_CMD, specialProperties)); // Theme properties let theme = ItsATrap.getTheme(); if(theme.getThemeProperties) { content.append('h4', 'Theme-specific properties', { style: { 'margin-top' : '2em' } }); let properties = theme.getThemeProperties(trapToken); content.append(_displayWizardProperties(MODIFY_THEME_PROPERTY_CMD, properties)); } // Remote activate button content.append('div', `[Activate Trap](${ItsATrap.REMOTE_ACTIVATE_CMD})`, { style: { 'margin-top' : '2em' } }); let menu = _showMenuPanel('Trap Configuration', content); _whisper(who, menu.toString(MENU_CSS)); trapToken.set('status_cobweb', true); } /** * Creates the table for a list of trap properties. * @private */ function _displayWizardProperties(modificationCommand, properties) { let table = new HtmlBuilder('table'); _.each(properties, prop => { let row = table.append('tr', undefined, { title: prop.desc }); // Construct the list of parameter prompts. let params = []; let paramProperties = prop.properties || [prop]; _.each(paramProperties, item => { let options = ''; if(item.options) options = '|' + item.options.join('|'); params.push(`?{${item.name} ${item.desc} ${options}}`); }); row.append('td', `[${prop.name}](${modificationCommand} ${prop.id}&&${params.join('&&')})`, { style: { 'font-size': '0.8em' } }); row.append('td', `${prop.value || ''}`, { style: { 'font-size': '0.8em' } }); }); return table; } /** * Fixes msg.who. * @param {string} who * @return {string} */ function _fixWho(who) { return who.replace(/\(GM\)/, '').trim(); } /** * Gets a list of the core trap properties for a trap token. * @param {Graphic} token * @return {object[]} */ function getCoreProperties(trapToken) { let trapEffect = (new TrapEffect(trapToken)).json; let LPAREN = '&#40;'; let RPAREN = '&#41;'; let LBRACE = '&#91;'; let RBRACE = '&#93;'; return [ { id: 'name', name: 'Name', desc: 'The name of the trap', value: trapToken.get('name') }, { id: 'type', name: 'Type', desc: 'Is this a trap, or some other hidden secret?', value: trapEffect.type || 'trap' }, { id: 'message', name: 'Message', desc: 'The message displayed when the trap is activated.', value: trapEffect.message }, { id: 'disabled', name: 'Disabled', desc: 'A disabled trap will not activate when triggered, but can still be spotted with passive perception.', value: trapToken.get('status_interdiction') ? 'yes' : 'no', options: ['yes', 'no'] }, { id: 'gmOnly', name: 'GM Only', desc: 'When the trap is activated, should its results only be displayed to the GM?', value: trapEffect.gmOnly ? 'yes' : 'no', options: ['yes', 'no'] }, { id: 'notes', name: 'GM Notes', desc: 'Additional secret notes shown only to the GM when the trap is activated.', value: trapEffect.notes } ]; } /** * Gets a list of the core trap properties for a trap token dealing * with revealing the trap. * @param {Graphic} token * @return {object[]} */ function getRevealProperties(trapToken) { let trapEffect = (new TrapEffect(trapToken)).json; let LPAREN = '&#40;'; let RPAREN = '&#41;'; let LBRACE = '&#91;'; let RBRACE = '&#93;'; return [ { id: 'searchDist', name: 'Max Search Distance', desc: 'How far away can characters passively search for this trap?', value: trapToken.get('aura2_radius') || trapEffect.searchDist }, { id: 'revealToPlayers', name: 'When Activated', desc: 'Should this trap be revealed to the players when it is activated?', value: trapToken.get('status_bleeding-eye') ? 'yes' : 'no', options: ['yes', 'no'] }, { id: 'revealWhenSpotted', name: 'When Spotted', desc: 'Should this trap be revealed to the players when a character notices it by passive searching?', value: trapEffect.revealWhenSpotted ? 'yes' : 'no', options: ['yes', 'no'] }, { id: 'revealLayer', name: 'Layer', desc: 'When this trap is revealed, which layer is it revealed on?', value: trapEffect.revealLayer || 'map', options: ['map', 'objects'] } ]; } /** * Gets a list of the core trap properties for a trap token defining * the shape of the trap. * @param {Graphic} token * @return {object[]} */ function getShapeProperties(trapToken) { let trapEffect = (new TrapEffect(trapToken)).json; let LPAREN = '&#40;'; let RPAREN = '&#41;'; let LBRACE = '&#91;'; let RBRACE = '&#93;'; return [ { id: 'flying', name: 'Affects Flying Tokens', desc: 'Should this trap affect flying tokens ' + LPAREN + 'fluffy-wing status ' + RPAREN + '?', value: trapToken.get('status_fluffy-wing') ? 'yes' : 'no', options: ['yes', 'no'] }, { id: 'effectDistance', name: 'Blast distance', desc: 'How far away can the trap affect other tokens?', value: trapToken.get('aura1_radius') || 0 }, { id: 'stopAt', name: 'Stops Tokens At', desc: 'Does this trap stop tokens that pass through its trigger area?', value: trapEffect.stopAt, options: ['center', 'edge', 'none'] }, { id: 'effectShape', name: 'Trap shape', desc: 'Is the shape of the trap\'s effect circular or square?', value: trapToken.get('aura1_square') ? 'square' : 'circle', options: [ 'circle', 'square' ] }, ]; } /** * Gets a list of the core trap properties for a trap token dealing * with special side effects such as FX, sound, and API commands. * @param {Graphic} token * @return {object[]} */ function getSpecialProperties(trapToken) { let trapEffect = (new TrapEffect(trapToken)).json; let LPAREN = '&#40;'; let RPAREN = '&#41;'; let LBRACE = '&#91;'; let RBRACE = '&#93;'; return _.compact([ { id: 'api', name: 'API Command', desc: 'An API command which the trap runs when it is activated. The constants TRAP_ID and VICTIM_ID will be replaced by the object IDs for the trap and victim.', value: trapEffect.api }, // Requires AreasOfEffect script. (() => { if(typeof AreasOfEffect !== 'undefined') return { id: 'areaOfEffect', name: 'Areas of Effect script', desc: 'Specifies an AoE graphic to be spawned by the trap.', value: (() => { let aoe = trapEffect.areaOfEffect; if(aoe) { let result = aoe.name; if(aoe.direction) result += '; Direction: ' + aoe.direction; return result; } else return 'None'; })(), properties: [ { id: 'name', name: 'AoE Name', desc: 'The name of the saved AreasOfEffect effect.', }, { id: 'direction', name: 'AoE Direction', desc: 'The direction of the AoE effect. Optional. If omitted, then the effect will be directed toward affected tokens. Format: ' + LBRACE + 'X,Y' + RBRACE } ] }; })(), { id: 'fx', name: 'Special FX', desc: 'What special FX are displayed when the trap is activated?', value: (() => { let fx = trapEffect.fx; if(fx) { let result = fx.name; if(fx.offset) result += '; Offset: ' + fx.offset; if(fx.direction) result += '; Direction: ' + fx.direction; return result; } else return 'None'; })(), properties: [ { id: 'name', name: 'FX Name', desc: 'The name of the special FX.' }, { id: 'offset', name: 'FX Offset', desc: 'The offset ' + LPAREN + 'in units' + RPAREN + ' of the special FX from the trap\'s center. Format: ' + LBRACE + 'X,Y' + RBRACE }, { id: 'direction', name: 'FX Direction', desc: 'The directional vector for the special FX ' + LPAREN + 'Leave blank to direct it towards characters' + RPAREN + '. Format: ' + LBRACE + 'X,Y' + RBRACE } ] }, // Requires KABOOM script by PaprikaCC (Bodin Punyaprateep). (() => { if(typeof KABOOM !== 'undefined') return { id: 'kaboom', name: 'KABOOM script', desc: 'An explosion/implosion generated by the trap with the KABOOM script by PaprikaCC.', value: (() => { let props = trapEffect.kaboom; if(props) { let result = props.power + ' ' + props.radius + ' ' + (props.type || 'default'); if(props.scatter) result += ' ' + 'scatter'; return result; } else return 'None'; })(), properties: [ { id: 'power', name: 'Power', desc: 'The power of the KABOOM effect.' }, { id: 'radius', name: 'Radius', desc: 'The radius of the KABOOM effect.' }, { id: 'type', name: 'FX Type', desc: 'The type of element to use for the KABOOM FX.' }, { id: 'scatter', name: 'Scatter', desc: 'Whether to apply scattering to tokens affected by the KABOOM effect.', options: ['no', 'yes'] } ] }; })(), { id: 'sound', name: 'Sound', desc: 'A sound from your jukebox that will play when the trap is activated.', value: trapEffect.sound }, (() => { if(typeof TokenMod !== 'undefined') return { id: 'tokenMod', name: 'TokenMod script', desc: 'Modify affected tokens with the TokenMod script by The Aaron.', value: trapEffect.tokenMod }; })() ]); } /** * Gets a list of the core trap properties for a trap token. * @param {Graphic} token * @return {object[]} */ function getTriggerProperties(trapToken) { let trapEffect = (new TrapEffect(trapToken)).json; let LPAREN = '&#40;'; let RPAREN = '&#41;'; let LBRACE = '&#91;'; let RBRACE = '&#93;'; return [ { id: 'triggerPaths', name: 'Set Trigger', desc: 'To set paths, you must also select the paths that trigger the trap.', value: trapEffect.triggerPaths || 'self', options: ['self', 'paths'] }, { id: 'triggers', name: 'Other Traps Triggered', desc: 'A list of the names or token IDs for other traps that are triggered when this trap is activated.', value: (() => { let triggers = trapEffect.triggers; if(_.isString(triggers)) triggers = [triggers]; if(triggers) return triggers.join(', '); else return undefined; })() } ]; } /** * Changes a property for a trap. * @param {Graphic} trapToken * @param {Array} argv * @param {(Graphic|Path)[]} selected */ function modifyTrapProperty(trapToken, argv, selected) { let trapEffect = (new TrapEffect(trapToken)).json; let prop = argv[0]; let params = argv.slice(1); if(prop === 'name') trapToken.set('name', params[0]); if(prop === 'type') trapEffect.type = params[0]; if(prop === 'api') trapEffect.api = params[0]; if(prop === 'areaOfEffect') if(params[0]) { trapEffect.areaOfEffect = {}; trapEffect.areaOfEffect.name = params[0]; try { trapEffect.areaOfEffect.direction = JSON.parse(params[1]); } catch(err) {} } else trapEffect.areaOfEffect = undefined; if(prop === 'disabled') trapToken.set('status_interdiction', params[0] === 'yes'); if(prop === 'effectDistance') trapToken.set('aura1_radius', parseInt(params[0])); if(prop === 'effectShape') trapToken.set('aura1_square', params[0] === 'square'); if(prop === 'flying') trapToken.set('status_fluffy-wing', params[0] === 'yes'); if(prop === 'fx') { if(params[0]) { trapEffect.fx = {}; trapEffect.fx.name = params[0]; try { trapEffect.fx.offset = JSON.parse(params[1]); } catch(err) {} try { trapEffect.fx.direction = JSON.parse(params[2]); } catch(err) {} } else trapEffect.fx = undefined; } if(prop === 'gmOnly') trapEffect.gmOnly = params[0] === 'yes'; if(prop === 'kaboom') if(params[0]) trapEffect.kaboom = { power: parseInt(params[0]), radius: parseInt(params[1]), type: params[2] || undefined, scatter: params[3] === 'yes' }; else trapEffect.kaboom = undefined; if(prop === 'message') trapEffect.message = params[0]; if(prop === 'notes') trapEffect.notes = params[0]; if(prop === 'revealLayer') trapEffect.revealLayer = params[0]; if(prop === 'revealToPlayers') trapToken.set('status_bleeding-eye', params[0] === 'yes'); if(prop === 'revealWhenSpotted') trapEffect.revealWhenSpotted = params[0] === 'yes'; if(prop === 'searchDist') trapToken.set('aura2_radius', parseInt(params[0])); if(prop === 'sound') trapEffect.sound = params[0]; if(prop === 'stopAt') trapEffect.stopAt = params[0]; if(prop === 'tokenMod') trapEffect.tokenMod = params[0]; if(prop === 'triggers') trapEffect.triggers = _.map(params[0].split(','), trigger => { return trigger.trim(); }); if(prop === 'triggerPaths') if(params[0] === 'paths' && selected) trapEffect.triggerPaths = _.map(selected, path => { return path.get('_id'); }); else trapEffect.triggerPaths = undefined; trapToken.set('gmnotes', JSON.stringify(trapEffect)); } /** * Displays one of the script's menus. * @param {string} header * @param {(string|HtmlBuilder)} content * @return {HtmlBuilder} */ function _showMenuPanel(header, content) { let menu = new HtmlBuilder('.menu'); menu.append('.menuHeader', header); menu.append('.menuBody', content); return menu; } /** * @private * Whispers a Marching Order message to someone. */ function _whisper(who, msg) { sendChat('Its A Trap! script', '/w "' + _fixWho(who) + '" ' + msg); } on('ready', () => { let macro = findObjs({ _type: 'macro', name: 'ItsATrap_trapCreationWizard' })[0]; if(!macro) { let players = findObjs({ _type: 'player' }); let gms = _.filter(players, player => { return playerIsGM(player.get('_id')); }); _.each(gms, gm => { createObj('macro', { _playerid: gm.get('_id'), name: 'ItsATrap_trapCreationWizard', action: DISPLAY_WIZARD_CMD, istokenaction: true }); }); } }); on('chat:message', msg => { try { // Get the selected tokens/paths if any. let selected; if(msg.selected) { selected = _.map(msg.selected, sel => { return getObj(sel._type, sel._id); }); } if(msg.content.startsWith(DISPLAY_WIZARD_CMD)) { let trapToken = getObj('graphic', msg.selected[0]._id); displayWizard(msg.who, msg.playerId, trapToken); } if(msg.content.startsWith(MODIFY_CORE_PROPERTY_CMD)) { let params = msg.content.replace(MODIFY_CORE_PROPERTY_CMD + ' ', '').split('&&'); modifyTrapProperty(curTrap, params, selected); displayWizard(msg.who, msg.playerId, curTrap); } if(msg.content.startsWith(MODIFY_THEME_PROPERTY_CMD)) { let params = msg.content.replace(MODIFY_THEME_PROPERTY_CMD + ' ', '').split('&&'); let theme = ItsATrap.getTheme(); theme.modifyTrapProperty(curTrap, params, selected); displayWizard(msg.who, msg.playerId, curTrap); } } catch(err) { log('ItsATrapCreationWizard: ' + err.message); log(err.stack); } }); return { displayWizard, DISPLAY_WIZARD_CMD, MODIFY_CORE_PROPERTY_CMD, MODIFY_THEME_PROPERTY_CMD }; })(); /** * Base class for trap themes: System-specific strategies for handling * automation of trap activation results and passive searching. * @abstract */ var TrapTheme = (() => { 'use strict'; /** * The name of the theme used to register it. * @type {string} */ return class TrapTheme { /** * A sample CSS object for trap HTML messages created with HTML Builder. */ static get css() { return { 'bold': { 'font-weight': 'bold' }, 'critFail': { 'border': '2px solid #B31515' }, 'critSuccess': { 'border': '2px solid #3FB315' }, 'hit': { 'color': '#f00', 'font-weight': 'bold' }, 'miss': { 'color': '#620', 'font-weight': 'bold' }, 'paddedRow': { 'padding': '1px 1em' }, 'rollResult': { 'background-color': '#FEF68E', 'cursor': 'help', 'font-size': '1.1em', 'font-weight': 'bold', 'padding': '0 3px' }, 'trapMessage': { 'background-color': '#ccc', 'font-style': 'italic' }, 'trapTable': { 'background-color': '#fff', 'border': 'solid 1px #000', 'border-collapse': 'separate', 'border-radius': '10px', 'overflow': 'hidden', 'width': '100%' }, 'trapTableHead': { 'background-color': '#000', 'color': '#fff', 'font-weight': 'bold' } }; } get name() { throw new Error('Not implemented.'); } /** * Activates a TrapEffect by displaying the trap's message and * automating any system specific trap mechanics for it. * @abstract * @param {TrapEffect} effect */ activateEffect(effect) { throw new Error('Not implemented.'); } /** * Attempts to force a calculated attribute to be corrected by * setting it. * @param {Character} character * @param {string} attr */ static forceAttrCalculation(character, attr) { // Attempt to force the calculation of the save modifier by setting it. createObj('attribute', { _characterid: character.get('_id'), name: attr, current: -9999 }); // Then try again. return CharSheetUtils.getSheetAttr(character, attr) .then(result => { if(_.isNumber(result)) return result; else log('Could not calculate attribute: ' + attr + ' - ' + result); }); } /** * Asynchronously gets the value of a character sheet attribute. * @param {Character} character * @param {string} attr * @return {Promise<number>} * Contains the value of the attribute. */ static getSheetAttr(character, attr) { if(attr.includes('/')) return CharSheetUtils.getSheetRepeatingAttr(character, attr); else { let rollExpr = '@{' + character.get('name') + '|' + attr + '}'; return CharSheetUtils.rollAsync(rollExpr) .then((roll) => { if(roll) return roll.total; else throw new Error('Could not resolve roll expression: ' + rollExpr); }) .then(value => { if(_.isNumber(value)) return value; // If the attribute is autocalculated, but could its current value // could not be resolved, try to force it to calculate its value as a // last-ditch effort. else return TrapTheme.forceAttrCalculation(character, attr); }); } } /** * Asynchronously gets the value of a character sheet attribute from a * repeating row. * @param {Character} character * @param {string} attr * Here, attr has the format "sectionName/nameFieldName/nameFieldValue/valueFieldName". * For example: "skills/name/perception/total" * @return {Promise<number>} * Contains the value of the attribute. */ static getSheetRepeatingAttr(character, attr) { let parts = attr.split('/'); let sectionName = parts[0]; let nameFieldName = parts[1]; let nameFieldValue = parts[2].toLowerCase(); let valueFieldName = parts[3]; log(parts); // Find the row with the given name. return CharSheetUtils.getSheetRepeatingRow(character, sectionName, rowAttrs => { let nameField = rowAttrs[nameFieldName]; return nameField.get('current').toLowerCase().trim() === nameFieldValue; }) // Get the current value of that row. .then(rowAttrs => { let valueField = rowAttrs[valueFieldName]; return valueField.get('current'); }); } /** * Gets the map of attributes inside of a repeating section row. * @param {Character} character * @param {string} section * The name of the repeating section. * @param {func} rowFilter * A filter function to find the correct row. The argument passed to it is a * map of attribute names (without the repeating section ID part - e.g. "name" * instead of "repeating_skills_-123abc_name") to their actual attributes in * the current row being filtered. The function should return true iff it is * the correct row we're looking for. * @return {Promise<any>} * Contains the map of attributes. */ static getSheetRepeatingRow(character, section, rowFilter) { // Get all attributes in this section and group them by row. let attrs = findObjs({ _type: 'attribute', _characterid: character.get('_id') }); // Group the attributes by row. let rows = {}; _.each(attrs, attr => { let regex = new RegExp(`repeating_${section}_(-([0-9a-zA-Z\-_](?!_storage))+?|\$\d+?)_([0-9a-zA-Z\-_]+)`); let match = attr.get('name').match(regex); if(match) { let rowId = match[1]; let attrName = match[3]; if(!rows[rowId]) rows[rowId] = {}; rows[rowId][attrName] = attr; } }); // Find the row that matches our filter. return Promise.resolve(_.find(rows, rowAttrs => { return rowFilter(rowAttrs); })); } /** * Gets a list of a trap's theme-specific configured properties. * @param {Graphic} trap * @return {TrapProperty[]} */ getThemeProperties(trap) { return []; } /** * Displays the message to notice a trap. * @param {Character} character * @param {Graphic} trap */ static htmlNoticeTrap(character, trap) { let content = new HtmlBuilder(); let effect = new TrapEffect(trap, character); content.append('.paddedRow trapMessage', character.get('name') + ' notices a ' + (effect.type || 'trap') + ':'); content.append('.paddedRow', trap.get('name')); return TrapTheme.htmlTable(content, '#000', effect); } /** * Sends an HTML-stylized message about a noticed trap. * @param {(HtmlBuilder|string)} content * @param {string} borderColor * @param {TrapEffect} [effect] * @return {HtmlBuilder} */ static htmlTable(content, borderColor, effect) { let type = (effect && effect.type) || 'trap'; let table = new HtmlBuilder('table.trapTable', '', { style: { 'border-color': borderColor } }); table.append('thead.trapTableHead', '', { style: { 'background-color': borderColor } }).append('th', 'IT\'S A ' + type.toUpperCase() + '!!!'); table.append('tbody').append('tr').append('td', content, { style: { 'padding': '0' } }); return table; } /** * Changes a theme-specific property for a trap. * @param {Graphic} trapToken * @param {Array} params */ modifyTrapProperty(trapToken, argv) { // Default implementation: Do nothing. } /** * The system-specific behavior for a character passively noticing a trap. * @abstract * @param {Graphic} trap * The trap's token. * @param {Graphic} charToken * The character's token. */ passiveSearch(trap, charToken) { throw new Error('Not implemented.'); } /** * Asynchronously rolls a dice roll expression and returns the result's total in * a callback. The result is undefined if an invalid expression is given. * @param {string} expr * @return {Promise<int>} */ static rollAsync(expr) { return new Promise((resolve, reject) => { sendChat('TrapTheme', '/w gm [[' + expr + ']]', (msg) => { try { let results = msg[0].inlinerolls[0].results; resolve(results); } catch(err) { reject(err); } }); }); } }; })(); /** * A base class for trap themes using the D20 system (D&D 3.5, 4E, 5E, Pathfinder, etc.) * @abstract */ var D20TrapTheme = (() => { 'use strict'; return class D20TrapTheme extends TrapTheme { /** * @inheritdoc */ activateEffect(effect) { let character = getObj('character', effect.victim.get('represents')); let effectResults = effect.json; // Automate trap attack/save mechanics. Promise.resolve() .then(() => { effectResults.character = character; if(character) { if(effectResults.attack) return this._doTrapAttack(character, effectResults); else if(effectResults.save && effectResults.saveDC) return this._doTrapSave(character, effectResults); } return effectResults; }) .then(effectResults => { let html = D20TrapTheme.htmlTrapActivation(effectResults); effect.announce(html.toString(TrapTheme.css)); }) .catch(err => { sendChat('TrapTheme: ' + this.name, '/w gm ' + err.message); log(err.stack); }); } /** * Does a trap's attack roll. * @private */ _doTrapAttack(character, effectResults) { return Promise.all([ this.getAC(character), CharSheetUtils.rollAsync('1d20 + ' + effectResults.attack) ]) .then(tuple => { let ac = tuple[0]; let atkRoll = tuple[1]; ac = ac || 10; effectResults.ac = ac; effectResults.roll = atkRoll; effectResults.trapHit = atkRoll.total >= ac; return effectResults; }); } /** * Does a trap's save. * @private */ _doTrapSave(character, effectResults) { return this.getSaveBonus(character, effectResults.save) .then(saveBonus => { saveBonus = saveBonus || 0; effectResults.saveBonus = saveBonus; return CharSheetUtils.rollAsync('1d20 + ' + saveBonus); }) .then((saveRoll) => { effectResults.roll = saveRoll; effectResults.trapHit = saveRoll.total < effectResults.saveDC; return effectResults; }); } /** * Gets a character's AC. * @abstract * @param {Character} character * @return {Promise<int>} */ getAC(character) { throw new Error('Not implemented.'); } /** * Gets a character's passive wisdom (Perception). * @abstract * @param {Character} character * @return {Promise<int>} */ getPassivePerception(character) { throw new Error('Not implemented.'); } /** * Gets a character's saving throw bonus. * @abstract * @param {Character} character * @return {Promise<int>} */ getSaveBonus(character, saveName) { throw new Error('Not implemented.'); } /** * @inheritdoc */ getThemeProperties(trapToken) { let trapEffect = (new TrapEffect(trapToken)).json; let LPAREN = '&#40;'; let RPAREN = '&#41;'; let LBRACE = '&#91;'; let RBRACE = '&#93;'; return [ { id: 'attack', name: 'Attack Bonus', desc: `The trap's attack roll bonus vs AC.`, value: trapEffect.attack }, { id: 'damage', name: 'Damage', desc: `The dice roll expression for the trap's damage.`, value: trapEffect.damage }, { id: 'hideSave', name: 'Hide Save Result', desc: 'Show the Saving Throw result only to the GM?', value: trapEffect.hideSave ? 'yes' : 'no', options: ['yes', 'no'] }, { id: 'missHalf', name: 'Miss - Half Damage', desc: 'Does the trap deal half damage on a miss?', value: trapEffect.missHalf ? 'yes' : 'no', options: ['yes', 'no'] }, { id: 'save', name: 'Saving Throw', desc: 'The type of saving throw used by the trap.', value: trapEffect.save, options: [ 'none', 'str', 'dex', 'con', 'int', 'wis', 'cha' ] }, { id: 'saveDC', name: 'Saving Throw DC', desc: `The DC for the trap's saving throw.`, value: trapEffect.saveDC }, { id: 'spotDC', name: 'Spot DC', desc: 'The skill check DC to spot the trap.', value: trapEffect.spotDC } ]; } /** * Produces HTML for a faked inline roll result for d20 systems. * @param {int} result * @param {string} tooltip * @return {HtmlBuilder} */ static htmlRollResult(result, tooltip) { let d20 = result.rolls[0].results[0].v; let clazzes = ['rollResult']; if(d20 === 20) clazzes.push('critSuccess'); if(d20 === 1) clazzes.push('critFail'); return new HtmlBuilder('span.' + clazzes.join(' '), result.total, { title: tooltip }); } /** * Produces the HTML for a trap activation message for most d20 systems. * @param {object} effectResults * @return {HtmlBuilder} */ static htmlTrapActivation(effectResults) { let content = new HtmlBuilder('div'); // Add the flavor message. content.append('.paddedRow trapMessage', effectResults.message); if(effectResults.character) { var row = content.append('.paddedRow'); row.append('span.bold', 'Target:'); row.append('span', effectResults.character.get('name')); // Add the attack roll message. if(effectResults.attack) { let rollResult = D20TrapTheme.htmlRollResult(effectResults.roll, '1d20 + ' + effectResults.attack); content.append('.paddedRow') .append('span.bold', 'Attack roll:') .append('span', rollResult) .append('span', ' vs AC ' + effectResults.ac); } // Add the saving throw message. if(effectResults.save) { let rollResult = D20TrapTheme.htmlRollResult(effectResults.roll, '1d20 + ' + effectResults.saveBonus); let saveMsg = new HtmlBuilder('.paddedRow'); saveMsg.append('span.bold', effectResults.save.toUpperCase() + ' save:'); saveMsg.append('span', rollResult); saveMsg.append('span', ' vs DC ' + effectResults.saveDC); // If the save result is a secret, whisper it to the GM. if(effectResults.hideSave) sendChat('Admiral Ackbar', '/w gm ' + saveMsg.toString(TrapTheme.css)); else content.append(saveMsg); } // Add the hit/miss message. if(effectResults.trapHit === 'AC unknown') { content.append('.paddedRow', 'AC could not be determined with the current version of your character sheet. For the time being, please resolve the attack against AC manually.'); if(effectResults.damage) content.append('.paddedRow', 'Damage: [[' + effectResults.damage + ']]'); } else if(effectResults.trapHit) { let row = content.append('.paddedRow'); row.append('span.hit', 'HIT! '); if(effectResults.damage) row.append('span', 'Damage: [[' + effectResults.damage + ']]'); else row.append('span', 'You fall prey to the ' + (effectResults.type || 'trap') + '\'s effects!'); } else { let row = content.append('.paddedRow'); row.append('span.miss', 'MISS! '); if(effectResults.damage && effectResults.missHalf) row.append('span', 'Half damage: [[floor((' + effectResults.damage + ')/2)]].'); } } return TrapTheme.htmlTable(content, '#a22', effectResults); } /** * @inheritdoc */ modifyTrapProperty(trapToken, argv) { let trapEffect = (new TrapEffect(trapToken)).json; let prop = argv[0]; let params = argv.slice(1); log(prop); log(params); if(prop === 'attack') trapEffect.attack = parseInt(params[0]); if(prop === 'damage') trapEffect.damage = params[0]; if(prop === 'hideSave') trapEffect.hideSave = params[0] === 'yes'; if(prop === 'missHalf') trapEffect.missHalf = params[0] === 'yes'; if(prop === 'save') trapEffect.save = params[0] === 'none' ? undefined : params[0]; if(prop === 'saveDC') trapEffect.saveDC = parseInt(params[0]); if(prop === 'spotDC') trapEffect.spotDC = parseInt(params[0]); trapToken.set('gmnotes', JSON.stringify(trapEffect)); } /** * @inheritdoc */ passiveSearch(trap, charToken) { let effect = (new TrapEffect(trap, charToken)).json; let character = getObj('character', charToken.get('represents')); // Only do passive search for traps that have a spotDC. if(effect.spotDC && character) { // If the character's passive perception beats the spot DC, then // display a message and mark the trap's trigger area. return this.getPassivePerception(character) .then(passWis => { if(passWis >= effect.spotDC) { let html = TrapTheme.htmlNoticeTrap(character, trap); ItsATrap.noticeTrap(trap, html.toString(TrapTheme.css)); } }) .catch(err => { sendChat('Trap theme: ' + this.name, '/w gm ' + err.message); log(err.stack); }); } } }; })(); /** * Base class for TrapThemes using D&D 4E-ish rules. * @abstract */ var D20TrapTheme4E = (() => { 'use strict'; return class D20TrapTheme4E extends D20TrapTheme { /** * @inheritdoc */ activateEffect(effect) { let character = getObj('character', effect.victim.get('represents')); let effectResult = effect.json; Promise.resolve() .then(() => { effectResult.character = character; // Automate trap attack mechanics. if(character && effectResult.defense && effectResult.attack) { return Promise.all([ this.getDefense(character, effectResult.defense), CharSheetUtils.rollAsync('1d20 + ' + effectResult.attack) ]) .then(tuple => { let defenseValue = tuple[0]; let attackRoll = tuple[1]; defenseValue = defenseValue || 0; effectResult.defenseValue = defenseValue; effectResult.roll = attackRoll; effectResult.trapHit = attackRoll.total >= defenseValue; return effectResult; }); } return effectResult; }) .then(effectResult => { let html = D20TrapTheme4E.htmlTrapActivation(effectResult); effect.announce(html.toString(TrapTheme.css)); }) .catch(err => { sendChat('Trap theme: ' + this.name, '/w gm ' + err.message); log(err.stack); }); } /** * Gets the value for one of a character's defenses. * @param {Character} character * @param {string} defenseName * @return {Promise<int>} */ getDefense(character, defenseName) { throw new Error('Not implemented.'); } /** * @inheritdoc */ getThemeProperties(trapToken) { let trapEffect = (new TrapEffect(trapToken)).json; return [ { id: 'attack', name: 'Attack Bonus', desc: `The trap's attack roll bonus vs AC.`, value: trapEffect.attack }, { id: 'damage', name: 'Damage', desc: `The dice roll expression for the trap's damage.`, value: trapEffect.damage }, { id: 'defense', name: 'Defense', desc: `The defense targeted by the trap's attack.`, value: trapEffect.defense, options: [ 'none', 'ac', 'fort', 'ref', 'will' ] }, { id: 'missHalf', name: 'Miss - Half Damage', desc: 'Does the trap deal half damage on a miss?', value: trapEffect.missHalf ? 'yes' : 'no', options: ['yes', 'no'] }, { id: 'spotDC', name: 'Spot DC', desc: 'The skill check DC to spot the trap.', value: trapEffect.spotDC } ]; } /** * Creates the HTML for an activated trap's result. * @param {object} effectResult * @return {HtmlBuilder} */ static htmlTrapActivation(effectResult) { let content = new HtmlBuilder('div'); // Add the flavor message. content.append('.paddedRow trapMessage', effectResult.message); if(effectResult.character) { // Add the attack roll message. if(_.isNumber(effectResult.attack)) { let rollHtml = D20TrapTheme.htmlRollResult(effectResult.roll, '1d20 + ' + effectResult.attack); let row = content.append('.paddedRow'); row.append('span.bold', 'Attack roll: '); row.append('span', rollHtml + ' vs ' + effectResult.defense + ' ' + effectResult.defenseValue); } // Add the hit/miss message. if(effectResult.trapHit) { let row = content.append('.paddedRow'); row.append('span.hit', 'HIT! '); if(effectResult.damage) row.append('span', 'Damage: [[' + effectResult.damage + ']]'); else row.append('span', effectResult.character.get('name') + ' falls prey to the trap\'s effects!'); } else { let row = content.append('.paddedRow'); row.append('span.miss', 'MISS! '); if(effectResult.damage && effectResult.missHalf) row.append('span', 'Half damage: [[floor((' + effectResult.damage + ')/2)]].'); } } return TrapTheme.htmlTable(content, '#a22', effectResult); } /** * @inheritdoc */ modifyTrapProperty(trapToken, argv) { let trapEffect = (new TrapEffect(trapToken)).json; let prop = argv[0]; let params = argv.slice(1); if(prop === 'attack') trapEffect.attack = parseInt(params[0]); if(prop === 'damage') trapEffect.damage = params[0]; if(prop === 'defense') trapEffect.defense = params[0] === 'none' ? undefined : params[0]; if(prop === 'missHalf') trapEffect.missHalf = params[0] === 'yes'; if(prop === 'spotDC') trapEffect.spotDC = parseInt(params[0]); trapToken.set('gmnotes', JSON.stringify(trapEffect)); } }; })(); /** * The default system-agnostic Admiral Ackbar theme. * @implements TrapTheme */ (() => { 'use strict'; class DefaultTheme { /** * @inheritdoc */ get name() { return 'default'; } /** * @inheritdoc */ activateEffect(effect) { let content = new HtmlBuilder('div'); var row = content.append('.paddedRow'); if(effect.victim) { row.append('span.bold', 'Target:'); row.append('span', effect.victim.get('name')); } content.append('.paddedRow', effect.message); let table = TrapTheme.htmlTable(content, '#a22', effect); let tableView = table.toString(TrapTheme.css); effect.announce(tableView); } /** * @inheritdoc */ passiveSearch(trap, charToken) { // Do nothing. } } ItsATrap.registerTheme(new DefaultTheme()); })();
import * as angular from 'angular' import * as angularMaterial from 'angular-material' const raiz = "./componentes/portada/lista-tareas/" const nombreComponente = 'filaTarea' const nombreFichero = 'fila-tarea' angular.module(nombreComponente, ['ngMaterial']) .component(nombreComponente, { templateUrl: `${raiz}${nombreFichero}/${nombreFichero}.html`, bindings: { tarea: '=' } }) export default nombreComponente
import { rgba } from 'polished'; export const getLinkStyles = theme => ({ color: theme.color.control.base, textShadow: `0 0 ${theme.shadowLength}px ` + rgba(theme.color.control.base, theme.alpha), transition: `color ${theme.animTime}ms ease-out`, textDecoration: 'none', cursor: 'pointer', '&:hover': { color: theme.color.control.light } }); export default theme => ({ root: getLinkStyles(theme) });
version https://git-lfs.github.com/spec/v1 oid sha256:4227ea60d439f0000142654edfddbca6030cf1c07d460a347957446c22226705 size 2934
// 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. 'use strict'; const common = require('../common'); const assert = require('assert'); const http = require('http'); const bufferSize = 5 * 1024 * 1024; let measuredSize = 0; const buffer = Buffer.allocUnsafe(bufferSize); for (let i = 0; i < buffer.length; i++) { buffer[i] = i % 256; } const server = http.Server(function(req, res) { server.close(); let i = 0; req.on('data', (d) => { measuredSize += d.length; for (let j = 0; j < d.length; j++) { assert.strictEqual(buffer[i], d[j]); i++; } }); req.on('end', common.mustCall(() => { assert.strictEqual(bufferSize, measuredSize); res.writeHead(200); res.write('thanks'); res.end(); })); }); server.listen(0, common.mustCall(() => { const req = http.request({ port: server.address().port, method: 'POST', path: '/', headers: { 'content-length': buffer.length } }, common.mustCall((res) => { res.setEncoding('utf8'); let data = ''; res.on('data', (chunk) => data += chunk); res.on('end', common.mustCall(() => { assert.strictEqual('thanks', data); })); })); req.end(buffer); }));
function render() { return <div> {/* child */} </div>; }
'use strict'; var fs = require('fs'); var path = require('path'); var deprecate = require('../utilities/deprecate'); var assign = require('lodash-node/modern/objects/assign'); function Addon(project) { this.project = project; } Addon.__proto__ = require('./core-object'); Addon.prototype.constructor = Addon; function unwatchedTree(dir) { return { read: function() { return dir; }, cleanup: function() { } }; } Addon.prototype.treePaths = { app: 'app', styles: 'app/styles', templates: 'app/templates', vendor: 'vendor' }; Addon.prototype.treeFor = function treeFor(name) { var treePath = path.join(this._root, this.treePaths[name]); if (fs.existsSync(treePath)) { return unwatchedTree(treePath); } }; Addon.resolvePath = function(addon) { var addonMain; deprecate(addon.pkg.name + ' is using the deprecated ember-addon-main definition. It should be updated to {\'ember-addon\': {\'main\': \'' + addon.pkg['ember-addon-main'] + '\'}}', addon.pkg['ember-addon-main']); addonMain = addon.pkg['ember-addon-main'] || addon.pkg['ember-addon'].main || 'index.js'; // Resolve will fail unless it has an extension if(!path.extname(addonMain)) { addonMain += '.js'; } return path.resolve(addon.path, addonMain); }; Addon.lookup = function(addon) { var Constructor, addonModule, modulePath, moduleDir; modulePath = Addon.resolvePath(addon); moduleDir = path.dirname(modulePath); if (fs.existsSync(modulePath)) { addonModule = require(modulePath); if (typeof addonModule === 'function') { Constructor = addonModule; Constructor.prototype._root = moduleDir; } else { Constructor = Addon.extend(assign(addonModule, { _root: moduleDir })); } } else { Constructor = Addon.extend({ name: '(generated ' + addon.pkg.name + ' addon)', _root: moduleDir }); } return Constructor; }; module.exports = Addon;
module.exports = function calcAtRulePatternPriority(pattern, node) { // 0 — it pattern doesn't match // 1 — pattern without `name` and `hasBlock` // 10010 — pattern match `hasBlock` // 10100 — pattern match `name` // 20110 — pattern match `name` and `hasBlock` // 21100 — patter match `name` and `parameter` // 31110 — patter match `name`, `parameter`, and `hasBlock` let priority = 0; // match `hasBlock` if (pattern.hasOwnProperty('hasBlock') && node.hasBlock === pattern.hasBlock) { priority += 10; priority += 10000; } // match `name` if (pattern.hasOwnProperty('name') && node.name === pattern.name) { priority += 100; priority += 10000; } // match `name` if (pattern.hasOwnProperty('parameter') && pattern.parameter.test(node.parameter)) { priority += 1100; priority += 10000; } // doesn't have `name` and `hasBlock` if ( !pattern.hasOwnProperty('hasBlock') && !pattern.hasOwnProperty('name') && !pattern.hasOwnProperty('paremeter') ) { priority = 1; } // patter has `name` and `hasBlock`, but it doesn't match both properties if (pattern.hasOwnProperty('hasBlock') && pattern.hasOwnProperty('name') && priority < 20000) { priority = 0; } // patter has `name` and `parameter`, but it doesn't match both properties if (pattern.hasOwnProperty('name') && pattern.hasOwnProperty('parameter') && priority < 21100) { priority = 0; } // patter has `name`, `parameter`, and `hasBlock`, but it doesn't match all properties if ( pattern.hasOwnProperty('name') && pattern.hasOwnProperty('parameter') && pattern.hasOwnProperty('hasBlock') && priority < 30000 ) { priority = 0; } return priority; };
// Legacy package export for non-esm environments require('./_interopReexport')(module.exports, require('./lib/_exports/_internal'))
'use strict'; var should = require('chai').should(); var Node = require('../lib/node'); var chainData = require('./data/chain.json'); var Block = require('../lib/block'); var async = require('async'); var memdown = require('memdown'); describe('P2P Integration test', function() { var node1; var node2; var node1ErrorCount = 0; var node2ErrorCount = 0; var blocks = []; function createNode1(callback) { var configuration = { consensus: { type: 'simple', builder: true, genesisOptions: { timestamp: new Date('2015-03-16') } }, db: { type: 'simple', store: memdown }, network: { name: 'chainlib', pubkeyhash: 0x1c, privatekey: 0x1e, scripthash: 0x28, xpubkey: 0x02e8de8f, xprivkey: 0x02e8da54, networkMagic: 0x0c110907, port: 7333 }, p2p: { addrs: [ { ip: { v4: '127.0.0.1' }, port: 7334 } ], dnsSeed: false } }; return new Node(configuration); } function createNode2(callback) { var configuration = { consensus: { type: 'simple', builder: true, genesisOptions: { timestamp: new Date('2015-03-16') } }, db: { type: 'simple', store: memdown }, network: { name: 'chainlib', pubkeyhash: 0x1c, privatekey: 0x1e, scripthash: 0x28, xpubkey: 0x02e8de8f, xprivkey: 0x02e8da54, networkMagic: 0x0c110907, port: 7334 }, p2p: { addrs: [ { ip: { v4: '127.0.0.1' }, port: 7333 } ], dnsSeed: false } }; return new Node(configuration); } before(function(done) { var node1Ready = false; var node2Ready = false; node1 = createNode1(); node1.on('ready', function() { node1.p2p.ignoreTransactions = false; node1Ready = true; if(node2Ready) { done(); } }); node1.on('error', function(err) { node1ErrorCount++; console.log('node1 error:', err); }); node2 = createNode2(); node2.on('ready', function() { node2.p2p.ignoreTransactions = false; node2Ready = true; if(node1Ready) { done(); } }); node2.on('error', function(err) { node2ErrorCount++; console.log('node2 error:', err); }); }); after(function(done) { node1.p2p.pool.disconnect(); node1.p2p.pool.server.close(function() { node2.p2p.pool.disconnect(); node2.p2p.pool.server.close(done); }); }); it('should not have any errors starting up', function() { node1ErrorCount.should.equal(0); node2ErrorCount.should.equal(0); blocks.push(node1.chain.tip); }); it('node1 should create a transaction and node2 should receive it', function(done) { var txid; node1.put('key1', 'value1a', function(err, hash) { txid = hash; should.not.exist(err); }); node2.p2p.pool.once('peertx', function(peer, message) { should.exist(message.transaction); message.transaction.hash.should.equal(txid); done(); }); }); it('when the next block is built, then the key should be queryable by node2', function(done) { node2.chain.on('addblock', function(block) { blocks.push(block); setImmediate(function() { node2.get('key1', function(err, value) { should.not.exist(err); value.should.equal('value1a'); done(); }); }); }); }); }); describe('P2P Syncing', function() { var node1; var node2; var node1ErrorCount = 0; var node2ErrorCount = 0; var genesis = new Block(chainData[0]); var blocks = []; function createNode1(callback) { var configuration = { genesis: genesis, consensus: { type: 'simple', builder: false }, db: { type: 'simple', store: memdown }, network: { name: 'chainlib', pubkeyhash: 0x1c, privatekey: 0x1e, scripthash: 0x28, xpubkey: 0x02e8de8f, xprivkey: 0x02e8da54, networkMagic: 0x0c110907, port: 7333 }, p2p: { addrs: [ { ip: { v4: '127.0.0.1' }, port: 7334 } ], dnsSeed: false } }; return new Node(configuration); } function createNode2(callback) { var configuration = { genesis: genesis, consensus: { type: 'simple', builder: false }, db: { type: 'simple', store: memdown }, network: { name: 'chainlib', pubkeyhash: 0x1c, privatekey: 0x1e, scripthash: 0x28, xpubkey: 0x02e8de8f, xprivkey: 0x02e8da54, networkMagic: 0x0c110907, port: 7334 }, p2p: { maxBlocks: 2, syncInterval: 500, addrs: [ { ip: { v4: '127.0.0.1' }, port: 7333 } ], dnsSeed: false } }; return new Node(configuration); } before(function(done) { node1 = createNode1(); node1.chain.on('ready', function() { done(); }); node1.on('error', function(err) { node1ErrorCount++; }); }); after(function(done) { node1.p2p.pool.disconnect(); node1.p2p.pool.server.close(function() { node2.p2p.pool.disconnect(); node2.p2p.pool.server.close(done); }); }); it('should add blocks to node1', function(done) { async.eachSeries(chainData, function(data, next) { if(data.prevHash === null) { // Skip genesis block return next(); } node1.chain.addBlock(new Block(data), function(err) { should.not.exist(err); next(); }); }, done); }); it('should create node2', function(done) { node2 = createNode2(); node2.on('ready', function() { done(); }); node2.on('error', function(err) { node2ErrorCount++; console.log('node2 error:', err); }); }); it('node2 should download all blocks', function(done) { var count = 0; node2.chain.on('addblock', function(block) { count++; console.log('added ' + block.hash); if(count === chainData.length - 1) { done(); } }); }); });
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'pagebreak', 'eo', { alt: 'Paĝavanco', toolbar: 'Enmeti Paĝavancon por Presado' });
// steals the 3 things neded if ( window.location.search.indexOf("DIST=1") > -1 ) { steal("can/util/jquery/jquery.1.8.1.js").then("can/dist/edge/can.jquery.js"); } else { steal( 'can/model', 'can/control/route', 'can/view/ejs' ).then( 'can/util/exports.js' ); }
/* Dashicons Picker */ (function($) { $.fn.dashiconsPicker = function( options ) { var icons = [ "menu", "site", "gauge", "admin-dashboard", "admin-post", "admin-media", "admin-links", "admin-page", "admin-comments", "admin-appearance", "admin-plugins", "admin-users", "admin-tools", "admin-settings", "admin-site", "admin-generic", "admin-collapse", "welcome-write-blog", "welcome-add-page", "welcome-view-site", "welcome-widgets-menus", "welcome-comments", "welcome-learn-more", "format-aside", "format-image", "format-gallery", "format-video", "format-status", "format-quote", "format-chat", "format-audio", "camera2", "images-alt1", "images-alt2", "video-alt1", "video-alt2", "video-alt3", "imgedit-crop", "imgedit-rleft", "imgedit-rright", "imgedit-flipv", "imgedit-fliph", "imgedit-undo", "imgedit-redo", "align-left", "align-right", "align-center", "align-none", "lock", "calendar", "visibility", "post-status", "tinymce-bold", "tinymce-italic", "tinymce-ul", "tinymce-ol", "tinymce-quote", "tinymce-alignleft", "tinymce-aligncenter", "tinymce-alignright", "tinymce-insertmore", "tinymce-spellcheck", "tinymce-distractionfree", "tinymce-kitchensink", "tinymce-underline", "tinymce-justify", "tinymce-textcolor", "tinymce-word", "tinymce-plaintext", "tinymce-removeformatting", "tinymce-video", "tinymce-customchar", "tinymce-outdent", "tinymce-indent", "tinymce-help", "tinymce-strikethrough", "tinymce-unlink", "tinymce-rtl", "editor-contract", "editor-break", "editor-code", "editor-paragraph", "arr-up", "arr-down", "arr-right", "arr-left", "sort", "leftright", "list-view", "exerpt-view", "external", "randomize", "share", "share2", "share3", "twitter1", "twitter2", "rss", "facebook1", "facebook2", "jobs-developers", "jobs-designers", "jobs-migration", "jobs-performance", "wordpress", "pressthis", "update", "screenoptions", "cart", "feedback", "cloud", "lock", "backup", "arrow-down", "arrow-up", "tag", "category", "yes", "no", "plus-small", "xit", "marker", "star-filled", "star-empty", "flag", "location", "location-alt", "vault", "search", "slides", "analytics", "piechart", "bargraph", "bargraph2", "bargraph3", "groups", "products", "awards", "forms", "portfolio", "microphone", "media-archive", "media-audio", "media-code", "media-default", "media-document", "media-interactive", "media-spreadsheet", "media-text", "media-video", "playlist-audio", "playlist-video", "universal-access", "universal-access-alt", "tickets", "nametag", "clipboard", "heart", "megaphone", "schedule", "archive", "tagcloud", "text", "plus-alt" ]; return this.each( function() { var $button = $(this); $button.on('click.dashiconsPicker', function() { createPopup($button); }); function createPopup($button) { $target = $($button.data('target')); $popup = $('<div class="dashicon-picker-container"> \ <div class="dashicon-picker-control" /> \ <ul class="dashicon-picker-list" /> \ </div>') .css({ 'top': $button.offset().top, 'left': $button.offset().left }); var $list = $popup.find('.dashicon-picker-list'); for (var i in icons) { $list.append('<li data-icon="'+icons[i]+'"><a href="#" title="'+icons[i]+'"><span class="dashicons dashicons-'+icons[i]+'"></span></a></li>'); }; $('a', $list).click(function(e) { e.preventDefault(); var title = $(this).attr("title"); $target.val("dashicons-"+title); removePopup(); }); var $control = $popup.find('.dashicon-picker-control'); $control.html('<a data-direction="back" href="#"><span class="dashicons dashicons-arrow-left-alt2"></span></a> \ <input type="text" class="" placeholder="Search" /> \ <a data-direction="forward" href="#"><span class="dashicons dashicons-arrow-right-alt2"></span></a>'); $('a', $control).click(function(e) { e.preventDefault(); if ($(this).data('direction') === 'back') { //move last 25 elements to front $('li:gt(' + (icons.length - 26) + ')', $list).each(function() { $(this).prependTo($list); }); } else { //move first 25 elements to the end $('li:lt(25)', $list).each(function() { $(this).appendTo($list); }); } }); $popup.appendTo('body').show(); $('input', $control).on('keyup', function(e) { var search = $(this).val(); if (search === '') { //show all again $('li:lt(25)', $list).show(); } else { $('li', $list).each(function() { if ($(this).data('icon').toLowerCase().indexOf(search.toLowerCase()) !== -1) { $(this).show(); } else { $(this).hide(); } }); } }); $(document).mouseup(function (e){ if (!$popup.is(e.target) && $popup.has(e.target).length === 0) { removePopup(); } }); } function removePopup(){ $(".dashicon-picker-container").remove(); } }); } $(function() { $('.dashicons-picker').dashiconsPicker(); }); }(jQuery));
/*! * jQuery JavaScript Library v2.1.1 -dimensions,-effects,-effects/Tween,-effects/animatedSelector,-event-alias,-css/hiddenVisibleSelectors * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-09-28T03:12Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper window is present, // execute the factory and get jQuery // For environments that do not inherently posses a window with a document // (such as Node.js), expose a jQuery-making factory as module.exports // This accentuates the need for the creation of a real window // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ // var arr = []; var slice = arr.slice; var concat = arr.concat; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var support = {}; var // Use the correct document accordingly with window argument (sandbox) document = window.document, version = "2.1.1 -dimensions,-effects,-effects/Tween,-effects/animatedSelector,-event-alias,-css/hiddenVisibleSelectors", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Support: Android<4.1 // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return just the one element from the set ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return all the elements in a clean array slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } if ( obj.constructor && !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, type: function( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android < 4.0, iOS < 6 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Support: Android<4.1 trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their new values if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: Date.now, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } /* * Optional (non-Sizzle) selector module for custom builds. * * Note that this DOES NOT SUPPORT many documented jQuery * features in exchange for its smaller size: * * Attribute not equal selector * Positional selectors (:first; :eq(n); :odd; etc.) * Type selectors (:input; :checkbox; :button; etc.) * State-based selectors (:animated; :visible; :hidden; etc.) * :has(selector) * :not(complex selector) * custom selectors via Sizzle extensions * Leading combinators (e.g., $collection.find("> *")) * Reliable functionality on XML fragments * Requiring all parts of a selector to match elements under context * (e.g., $div.find("div > *") now matches children of $div) * Matching against non-elements * Reliable sorting of disconnected nodes * querySelectorAll bug fixes (e.g., unreliable :focus on WebKit) * * If any of these are unacceptable tradeoffs, either use Sizzle or * customize this stub for the project's specific needs. */ var docElem = window.document.documentElement, selector_hasDuplicate, matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector, selector_sortOrder = function( a, b ) { // Flag for duplicate removal if ( a === b ) { selector_hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 ) { // Choose the first element that is related to our document if ( a === document || jQuery.contains(document, a) ) { return -1; } if ( b === document || jQuery.contains(document, b) ) { return 1; } // Maintain original order return 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; }; jQuery.extend({ find: function( selector, context, results, seed ) { var elem, nodeType, i = 0; results = results || []; context = context || document; // Same basic safeguard as Sizzle if ( !selector || typeof selector !== "string" ) { return results; } // Early return if context is not an element or document if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( seed ) { while ( (elem = seed[i++]) ) { if ( jQuery.find.matchesSelector(elem, selector) ) { results.push( elem ); } } } else { jQuery.merge( results, context.querySelectorAll(selector) ); } return results; }, unique: function( results ) { var elem, duplicates = [], i = 0, j = 0; selector_hasDuplicate = false; results.sort( selector_sortOrder ); if ( selector_hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }, text: function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += jQuery.text( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements return elem.textContent; } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }, contains: function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && adown.contains(bup) ); }, isXMLDoc: function( elem ) { return (elem.ownerDocument || elem).documentElement.nodeName !== "HTML"; }, expr: { attrHandle: {}, match: { bool: /^(?:checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped)$/i, needsContext: /^[\x20\t\r\n\f]*[>+~]/ } } }); jQuery.extend( jQuery.find, { matches: function( expr, elements ) { return jQuery.find( expr, null, null, elements ); }, matchesSelector: function( elem, expr ) { return matches.call( elem, expr ); }, attr: function( elem, name ) { return elem.getAttribute( name ); } }); var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }; jQuery.fn.extend({ find: function( selector ) { var i, len = this.length, ret = [], self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } }); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.extend({ dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); jQuery.fn.extend({ has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); var rnotwhite = (/\S+/g); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend({ // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); jQuery( document ).off( "ready" ); } } }); /** * The ready event handler and self cleanup method */ function completed() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Kick off the DOM ready check even if the user does not jQuery.ready.promise(); // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : len ? fn( elems[0], key ) : emptyGet; }; /** * Determines whether an object can have data */ jQuery.acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any /* jshint -W018 */ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { // Support: Android < 4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Math.random(); } Data.uid = 1; Data.accepts = jQuery.acceptData; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android < 4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase(key) ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; var data_priv = new Data(); var data_user = new Data(); /* Implementation Summary 1. Enforce API surface and semantic compatibility with 1.9.x branch 2. Improve the module's maintainability by reducing the storage paths to a single mechanism. 3. Use the same single mechanism to support "private" and "user" data. 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) 5. Avoid exposing implementation details on user objects (eg. expando properties) 6. Provide a clear path for implementation upgrade to WeakMap in 2014 */ var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE11+ // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", key ] ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); }; var rcheckableType = (/^(?:checkbox|radio)$/i); (function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); // #11217 - WebKit loses check when the name is after the checked attribute // Support: Windows Web Apps (WWA) // `name` and `type` need .setAttribute for WWA input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Make sure textarea (and checkbox) defaultValue is properly cloned // Support: IE9-IE11+ div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; })(); var strundefined = typeof undefined; support.focusinBubbles = "onfocusin" in window; var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && jQuery.acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = slice.call( arguments ), handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome < 28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: Android < 4.0 src.returnValue === false ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && e.stopImmediatePropagation ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // Support: Chrome 15+ jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // Create "bubbling" focus and blur events // Support: Firefox, Chrome, Safari if ( !support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } data_priv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); data_priv.remove( doc, fix ); } else { data_priv.access( doc, fix, attaches ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE 9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE 9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Support: IE >= 9 function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Support: IE >= 9 // Fix Cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Fixes #12346 // Support: Webkit, IE tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, type, key, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( jQuery.acceptData( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each(function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } }); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because push.apply(_, arraylike) throws push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); var iframe, elemdisplay = {}; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var style, elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? // Use of this method is a temporary fix (more like optmization) until something better comes along, // since it was removed from specification and supported only in FF style.display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = iframe[ 0 ].contentDocument; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } var rmargin = (/^margin/); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); }; function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // Support: IE9 // getPropertyValue is only needed for .css('filter') in IE9, see #12537 if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; } if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // Support: iOS < 6 // A tribute to the "awesome hack by Dean Edwards" // iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret !== undefined ? // Support: IE // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due to missing dependency), // remove it. // Since there are no other hooks for marginRight, remove the whole object. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return (this.get = hookFn).apply( this, arguments ); } }; } (function() { var pixelPositionVal, boxSizingReliableVal, docElem = document.documentElement, container = document.createElement( "div" ), div = document.createElement( "div" ); if ( !div.style ) { return; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; container.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;" + "position:absolute"; container.appendChild( div ); // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computePixelPositionAndBoxSizingReliable() { div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" + "box-sizing:border-box;display:block;margin-top:1%;top:1%;" + "border:1px;padding:1px;width:4px;position:absolute"; div.innerHTML = ""; docElem.appendChild( container ); var divStyle = window.getComputedStyle( div, null ); pixelPositionVal = divStyle.top !== "1%"; boxSizingReliableVal = divStyle.width === "4px"; docElem.removeChild( container ); } // Support: node.js jsdom // Don't assume that getComputedStyle is a property of the global object if ( window.getComputedStyle ) { jQuery.extend( support, { pixelPosition: function() { // This test is executed only once but we still do memoizing // since we can use the boxSizingReliable pre-computing. // No need to check if the test was already performed, though. computePixelPositionAndBoxSizingReliable(); return pixelPositionVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computePixelPositionAndBoxSizingReliable(); } return boxSizingReliableVal; }, reliableMarginRight: function() { // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // This support function is only executed once so no memoizing is needed. var ret, marginDiv = div.appendChild( document.createElement( "div" ) ); // Reset CSS: box-sizing; display; margin; border; padding marginDiv.style.cssText = div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" + "box-sizing:content-box;display:block;margin:0;border:0;padding:0"; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; docElem.appendChild( container ); ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight ); docElem.removeChild( container ); return ret; } }); } })(); // A method for quickly swapping in/out CSS properties to get correct calculations. jQuery.swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; var // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ), rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ), cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name[0].toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = data_priv.get( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } else { hidden = isHidden( elem ); if ( display !== "none" || !hidden ) { data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set. See: #7116 if ( value == null || value !== value ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifying setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { style[ name ] = value; } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); // Support: Android 2.3 jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } ); // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); jQuery.fn.extend({ css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }; (function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: iOS 5.1, Android 4.x, Android 2.3 // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) support.checkOn = input.value !== ""; // Must access the parent to make an option select properly // Support: IE9, IE10 support.optSelected = opt.selected; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Check if an input maintains its value after becoming a radio // Support: IE9, IE10 input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; })(); var nodeHook, boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend({ attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); } }); jQuery.extend({ attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && jQuery.nodeName( elem, "input" ) ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle; if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ name ]; attrHandle[ name ] = ret; ret = getter( elem, name, isXML ) != null ? name.toLowerCase() : null; attrHandle[ name ] = handle; } return ret; }; }); var rfocusable = /^(?:input|select|textarea|button)$/i; jQuery.fn.extend({ prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); } }); jQuery.extend({ propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); // Support: IE9+ // Selectedness for an option in an optgroup can be inaccurate if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); var rclass = /[\t\r\n\f]/g; jQuery.fn.extend({ addClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, proceed = typeof value === "string" && value, i = 0, len = this.length; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, proceed = arguments.length === 0 || typeof value === "string" && value, i = 0, len = this.length; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // only assign if different to avoid unneeded rendering. finalValue = value ? jQuery.trim( cur ) : ""; if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === strundefined || type === "boolean" ) { if ( this.className ) { // store className if set data_priv.set( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; } }); var rreturn = /\r/g; jQuery.fn.extend({ val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE10-11+ // option.text throws exceptions (#14686, #14858) jQuery.trim( jQuery.text( elem ) ); } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // IE6-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( option.value, values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); // Return jQuery for attributes-only inclusion jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var nonce = jQuery.now(); var rquery = (/\?/); // Support: Android 2.3 // Workaround failure to string-cast null input jQuery.parseJSON = function( data ) { return JSON.parse( data + "" ); }; // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data, "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ) .replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + nonce++ ) : // Otherwise add one to the end cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; }); jQuery._evalUrl = function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); }; jQuery.fn.extend({ wrapAll: function( html ) { var wrap; if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapAll( html.call(this, i) ); }); } if ( this[ 0 ] ) { // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map(function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function( i ) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); }) .map(function( i, elem ) { var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); jQuery.ajaxSettings.xhr = function() { try { return new XMLHttpRequest(); } catch( e ) {} }; var xhrId = 0, xhrCallbacks = {}, xhrSuccessStatus = { // file protocol always yields status code 0, assume 200 0: 200, // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); // Support: IE9 // Open requests must be manually aborted on unload (#5280) if ( window.ActiveXObject ) { jQuery( window ).on( "unload", function() { for ( var key in xhrCallbacks ) { xhrCallbacks[ key ](); } }); } support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport(function( options ) { var callback; // Cross domain only allowed if supported through XMLHttpRequest if ( support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, xhr = options.xhr(), id = ++xhrId; xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { delete xhrCallbacks[ id ]; callback = xhr.onload = xhr.onerror = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { complete( // file: protocol always yields status 0; see #8605, #14207 xhr.status, xhr.statusText ); } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE9 // Accessing binary-data responseText throws an exception // (#11426) typeof xhr.responseText === "string" ? { text: xhr.responseText } : undefined, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); xhr.onerror = callback("error"); // Create the abort callback callback = xhrCallbacks[ id ] = callback("abort"); try { // Do send the request (this may raise an exception) xhr.send( options.hasContent && options.data || null ); } catch ( e ) { // #14683: Only rethrow if this hasn't been notified as an error yet if ( callback ) { throw e; } } }, abort: function() { if ( callback ) { callback(); } } }; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery("<script>").prop({ async: true, charset: s.scriptCharset, src: s.url }).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; // Keep a copy of the old load method var _load = jQuery.fn.load; /** * Load a url into a page */ jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = jQuery.trim( url.slice( off ) ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; var docElem = window.document.documentElement; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; } jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf("auto") > -1; // Need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ offset: function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, elem = this[ 0 ], box = { top: 0, left: 0 }, doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // We assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : window.pageXOffset, top ? val : window.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); }); // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a global if an // AMD loader is present. jQuery is a special case. For more information, see // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; }); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in // AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( typeof noGlobal === strundefined ) { window.jQuery = window.$ = jQuery; } return jQuery; }));
/** * Description : This is a test suite that tests an LRS endpoint based on the testing requirements document * found at https://github.com/adlnet/xAPI_LRS_Test/blob/master/TestingRequirements.md * * https://github.com/adlnet/xAPI_LRS_Test/blob/master/TestingRequirements.md * */ (function (module) { "use strict"; // defines overwriting data var INVALID_LANGUAGE = {a12345678: 'should error'}; var INVALID_DESCRIPTION_LANGUAGE = {description: INVALID_LANGUAGE}; var INVALID_DISPLAY_LANGUAGE = {display: INVALID_LANGUAGE}; var INVALID_NAME_LANGUAGE = {name: INVALID_LANGUAGE}; // configures tests module.exports.config = function () { return [ { /** XAPI-00121, Data 4.2 Language Maps * A Language Map follows RFC 5646. The LRS rejects with 400 a statement using a Language Map which doesn’t not validate to RFC 5646. */ name: 'A Language Map follows RFC5646 (Format, Data 4.2.s1, RFC5646, XAPI-00121)', config: [ { name: 'statement verb "display" language map invalid', templates: [ {statement: '{{statements.verb}}'}, {verb: '{{verbs.no_display}}'}, INVALID_DISPLAY_LANGUAGE ], expect: [400] }, { name: 'statement object "name" language map invalid', templates: [ {statement: '{{statements.object_activity}}'}, {object: '{{activities.no_languages}}'}, {definition: INVALID_NAME_LANGUAGE} ], expect: [400] }, { name: 'statement object "description" language map invalid', templates: [ {statement: '{{statements.object_activity}}'}, {object: '{{activities.no_languages}}'}, {definition: INVALID_DESCRIPTION_LANGUAGE} ], expect: [400] }, { name: 'statement attachment "display" language map invalid', templates: [ {statement: '{{statements.attachment}}'}, { attachments: [ { 'usageType': 'http://example.com/attachment-usage/test', 'display': INVALID_LANGUAGE, 'contentType': 'text/plain; charset=ascii', 'length': 27, 'sha2': '495395e777cd98da653df9615d09c0fd6bb2f8d4788394cd53c56a3bfdcd848a', 'fileUrl': 'http://over.there.com/file.txt' } ] } ], expect: [400] }, { name: 'statement attachment "description" language map invalid', templates: [ {statement: '{{statements.attachment}}'}, { attachments: [ { 'usageType': 'http://example.com/attachment-usage/test', 'display': {'en-US': 'A test attachment'}, 'description': INVALID_LANGUAGE, 'contentType': 'text/plain; charset=ascii', 'length': 27, 'sha2': '495395e777cd98da653df9615d09c0fd6bb2f8d4788394cd53c56a3bfdcd848a', 'fileUrl': 'http://over.there.com/file.txt' } ] } ], expect: [400] }, { name: 'statement substatement verb "display" language map invalid', templates: [ {statement: '{{statements.object_substatement}}'}, {object: '{{substatements.verb}}'}, {verb: '{{verbs.no_display}}'}, INVALID_DISPLAY_LANGUAGE ], expect: [400] }, { name: 'statement substatement activity "name" language map invalid', templates: [ {statement: '{{statements.object_substatement}}'}, {object: '{{substatements.activity}}'}, {object: '{{activities.no_languages}}'}, {definition: INVALID_NAME_LANGUAGE} ], expect: [400] }, { name: 'statement substatement activity "description" language map invalid', templates: [ {statement: '{{statements.object_substatement}}'}, {object: '{{substatements.activity}}'}, {object: '{{activities.no_languages}}'}, {definition: INVALID_DESCRIPTION_LANGUAGE} ], expect: [400] } ] } ]; }; }(module));
// Javascripts here
var gulp = require('gulp'); var concat = require('gulp-concat'); var minify = require('gulp-minify'); var insert = require('gulp-insert'); gulp.task('default', function() { var src = [ 'app/models/base.js', 'app/models/inflection.js', 'app/models/i18n.js', 'app/models/error.js', 'app/models/class.js', 'app/models/association.js', 'app/models/validation.js', 'app/models/validator.js', 'app/models/patch_object.js', 'app/models/patch_string.js', 'app/models/patch_date.js', 'app/models/patch_number.js', 'app/models/patch_boolean.js' ] gulp .src(src) .pipe(concat('xktta.js')) .pipe(insert.prepend("'use strict';\n\n")) .pipe(insert.prepend(";(function(window){\n")) .pipe(insert.prepend(" */\n")) .pipe(insert.prepend(" * Copyright (c) 2015 Marcelo Junior\n")) .pipe(insert.prepend(" *\n")) .pipe(insert.prepend(" * http://juniormesquitadandao.github.io/xktta\n")) .pipe(insert.prepend("/*! Xktta - v1.0\n")) .pipe(insert.append('\nwindow.Xktta = Xktta;\n')) .pipe(insert.append("})(window);\n")) .pipe(minify({ ext:{ src:'.js', min:'.min.js' } })) .pipe(gulp.dest('')); gulp .src(src) .pipe(concat('xktta.js')) .pipe(insert.prepend("'use strict';\n\n")) .pipe(insert.prepend(";(function(){\n")) .pipe(insert.append('\nmodule.exports = Xktta;\n')) .pipe(insert.append("})();\n")) .pipe(gulp.dest('temp')); });
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'undo', 'lt', { redo: 'Atstatyti', undo: 'Atšaukti' });
/*! JSZipUtils - A collection of cross-browser utilities to go along with JSZip. <http://stuk.github.io/jszip-utils> (c) 2014 Stuart Knightley, David Duponchel Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip-utils/master/LICENSE.markdown. */
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import * as React from 'react'; import clsx from 'clsx'; import PropTypes from 'prop-types'; import NativeSelectInput from './NativeSelectInput'; import formControlState from '../FormControl/formControlState'; import useFormControl from '../FormControl/useFormControl'; import ArrowDropDownIcon from '../internal/svg-icons/ArrowDropDown'; import Input from '../Input'; import useThemeProps from '../styles/useThemeProps'; import { jsx as _jsx } from "react/jsx-runtime"; var defaultInput = /*#__PURE__*/_jsx(Input, {}); /** * An alternative to `<Select native />` with a much smaller bundle size footprint. */ var NativeSelect = /*#__PURE__*/React.forwardRef(function NativeSelect(inProps, ref) { var props = useThemeProps({ name: 'MuiNativeSelect', props: inProps }); var className = props.className, children = props.children, classes = props.classes, _props$IconComponent = props.IconComponent, IconComponent = _props$IconComponent === void 0 ? ArrowDropDownIcon : _props$IconComponent, _props$input = props.input, input = _props$input === void 0 ? defaultInput : _props$input, inputProps = props.inputProps, variant = props.variant, other = _objectWithoutProperties(props, ["className", "children", "classes", "IconComponent", "input", "inputProps", "variant"]); var muiFormControl = useFormControl(); var fcs = formControlState({ props: props, muiFormControl: muiFormControl, states: ['variant'] }); return /*#__PURE__*/React.cloneElement(input, _extends({ // Most of the logic is implemented in `NativeSelectInput`. // The `Select` component is a simple API wrapper to expose something better to play with. inputComponent: NativeSelectInput, inputProps: _extends({ children: children, classes: classes, IconComponent: IconComponent, variant: fcs.variant, type: undefined }, inputProps, input ? input.props.inputProps : {}), ref: ref }, other, { className: clsx(className, input.props.className) })); }); process.env.NODE_ENV !== "production" ? NativeSelect.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * The option elements to populate the select with. * Can be some `<option>` elements. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * The icon that displays the arrow. * @default ArrowDropDownIcon */ IconComponent: PropTypes.elementType, /** * An `Input` element; does not have to be a material-ui specific `Input`. * @default <Input /> */ input: PropTypes.element, /** * <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes">Attributes</a> applied to the `select` element. */ inputProps: PropTypes.object, /** * Callback fired when a menu item is selected. * * @param {object} event The event source of the callback. * You can pull out the new value by accessing `event.target.value` (string). */ onChange: PropTypes.func, /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: PropTypes.object, /** * The `input` value. The DOM API casts this to a string. */ value: PropTypes.any, /** * The variant to use. */ variant: PropTypes.oneOf(['filled', 'outlined', 'standard']) } : void 0; NativeSelect.muiName = 'Select'; export default NativeSelect;
describe('ReferenceField', function() { var choiceDirective = require('../../../../ng-admin/Crud/field/maChoiceField'); var referenceDirective = require('../../../../ng-admin/Crud/field/maReferenceField'); var ReferenceField = require('admin-config/lib/Field/ReferenceField'); var mixins = require('../../../mock/mixins'); var DataStore = require('admin-config/lib/DataStore/DataStore'); var $compile, $timeout, scope; const directiveUsage = ` <ma-reference-field entry="entry" field="field" value="value" datastore="datastore"> </ma-reference-field>`; angular.module('myTestingApp', ['ui.select', 'testapp_DataStore']) .filter('translate', () => text => text) .directive('maChoiceField', choiceDirective) .directive('maReferenceField', referenceDirective); beforeEach(function() { angular.mock.module(function($provide) { $provide.service('ReferenceRefresher', function($q) { this.refresh = jasmine.createSpy('refresh').and.callFake(function() { return mixins.buildPromise([ { value: 1, label: 'foo' }, { value: 2, label: 'bar' }, { value: 3, label: 'qux' } ]); }); }); }); }); beforeEach(angular.mock.module('myTestingApp')); var MockedReferenceRefresher; beforeEach(inject(function (_$compile_, _$rootScope_, _$timeout_, ReferenceRefresher) { $compile = _$compile_; $timeout = _$timeout_; scope = _$rootScope_; MockedReferenceRefresher = ReferenceRefresher; })); beforeEach(function() { scope.datastore = new DataStore(); scope.field = new ReferenceField('post_id') .targetField({ name: () => 'name' }) .targetEntity({ identifier: () => { return { name: () => 'id' }; } }) .remoteComplete(true, { refreshDelay: 500 }); }); it('should be an ui-select field', function() { var element = $compile(directiveUsage)(scope); scope.$digest(); var uiSelect = element[0].querySelector('.ui-select-container'); expect(uiSelect).toBeTruthy(); }); it('should call remote API when inputting first characters', function () { var element = $compile(directiveUsage)(scope); scope.$digest(); var uiSelect = angular.element(element[0].querySelector('.ui-select-container')).controller('uiSelect'); var choices = angular.element(element[0].querySelector('.ui-select-choices')); uiSelect.refresh(element.attr('refresh')); $timeout.flush(); scope.$digest(); expect(MockedReferenceRefresher.refresh).toHaveBeenCalled(); expect(angular.toJson(uiSelect.items)).toEqual(angular.toJson([ { value: 1, label: 'foo' }, { value: 2, label: 'bar' }, { value: 3, label: 'qux' } ])); }); it('should be pre-filled with related label at initialization', function () { scope.value = 2; var element = $compile(directiveUsage)(scope); scope.$digest(); $timeout.flush(); var uiSelect = angular.element(element[0].querySelector('.ui-select-match-text')); expect(uiSelect.text()).toBe('bar'); }); it('should get all choices loaded at initialization if refreshDelay is null', function() { scope.field.remoteComplete(true, { refreshDelay: null }); var element = $compile(directiveUsage)(scope); $timeout.flush(); scope.$digest(); var uiSelect = angular.element(element[0].querySelector('.ui-select-container')).controller('uiSelect'); expect(MockedReferenceRefresher.refresh).toHaveBeenCalled(); expect(uiSelect.items).toEqual([ { value: 1, label: 'foo' }, { value: 2, label: 'bar' }, { value: 3, label: 'qux' } ]); }); });
asynctest( 'browser.AutoCompleteTest', [ 'ephox.agar.api.Chain', 'ephox.agar.api.FocusTools', 'ephox.agar.api.GeneralSteps', 'ephox.agar.api.Keyboard', 'ephox.agar.api.Keys', 'ephox.agar.api.Pipeline', 'ephox.agar.api.UiControls', 'ephox.agar.api.UiFinder', 'ephox.mcagar.api.TinyActions', 'ephox.mcagar.api.TinyApis', 'ephox.mcagar.api.TinyDom', 'ephox.mcagar.api.TinyLoader', 'tinymce.plugins.contextmenu.Plugin', 'tinymce.plugins.image.Plugin', 'tinymce.plugins.link.Plugin', 'tinymce.plugins.paste.Plugin', 'tinymce.plugins.table.Plugin', 'tinymce.plugins.textpattern.Plugin', 'tinymce.themes.inlite.Theme', 'tinymce.themes.inlite.test.Toolbar' ], function ( Chain, FocusTools, GeneralSteps, Keyboard, Keys, Pipeline, UiControls, UiFinder, TinyActions, TinyApis, TinyDom, TinyLoader, ContextMenuPlugin, ImagePlugin, LinkPlugin, PastePlugin, TablePlugin, TextpatternPlugin, Theme, Toolbar ) { var success = arguments[arguments.length - 2]; var failure = arguments[arguments.length - 1]; ImagePlugin(); LinkPlugin(); PastePlugin(); ContextMenuPlugin(); TablePlugin(); TextpatternPlugin(); Theme(); var cKeyStroke = function (keyvalue, modifiers) { return Chain.op(function (dispatcher) { Keyboard.keystroke(keyvalue, modifiers, dispatcher); }); }; var sSetupLinkableContent = function (tinyApis) { return GeneralSteps.sequence([ tinyApis.sSetContent( '<h1 id="a">abc</h1>' + '<h2 id="b">abcd</h2>' + '<h3 id="c">abce</h3>' ), tinyApis.sSetSelection([0, 0], 0, [0, 0], 1) ]); }; var sSelectAutoCompleteLink = function (tinyApis, url) { return Chain.asStep({}, [ Chain.fromParent(Toolbar.cWaitForToolbar, [ Toolbar.cClickButton('Insert/Edit link') ]), Chain.fromParent(UiFinder.cFindIn('input'), [ UiControls.cSetValue(url), cKeyStroke(Keys.space(), {}), cKeyStroke(Keys.down(), {}) ]), Chain.inject(TinyDom.fromDom(document)), Chain.fromParent(FocusTools.cGetFocused, [ cKeyStroke(Keys.down(), {}), cKeyStroke(Keys.enter(), {}) ]), Chain.fromParent(Toolbar.cWaitForToolbar, [ Toolbar.cClickButton('Ok') ]) ]); }; TinyLoader.setup(function (editor, onSuccess, onFailure) { var tinyApis = TinyApis(editor); var tinyActions = TinyActions(editor); Pipeline.async({}, [ tinyApis.sFocus, sSetupLinkableContent(tinyApis), tinyActions.sContentKeystroke(Keys.space(), {}), sSelectAutoCompleteLink(tinyApis, 'a'), tinyApis.sAssertContent( '<h1 id="a"><a href="#b">a</a>bc</h1>\n' + '<h2 id="b">abcd</h2>\n' + '<h3 id="c">abce</h3>' ) ], onSuccess, onFailure); }, { theme: 'inlite', plugins: 'image table link paste contextmenu textpattern', insert_toolbar: 'quickimage media quicktable', selection_toolbar: 'bold italic | quicklink h1 h2 blockquote', inline: true, skin_url: '/project/src/skins/lightgray/dist/lightgray' }, success, failure); } );
# Phần 5.Các loại phương tiện truyền dẫn trong LANs. ================================================= 1.
/** * @license * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ // @version 0.5.0 if (typeof WeakMap === "undefined") { (function() { var defineProperty = Object.defineProperty; var counter = Date.now() % 1e9; var WeakMap = function() { this.name = "__st" + (Math.random() * 1e9 >>> 0) + (counter++ + "__"); }; WeakMap.prototype = { set: function(key, value) { var entry = key[this.name]; if (entry && entry[0] === key) entry[1] = value; else defineProperty(key, this.name, { value: [ key, value ], writable: true }); return this; }, get: function(key) { var entry; return (entry = key[this.name]) && entry[0] === key ? entry[1] : undefined; }, "delete": function(key) { var entry = key[this.name]; if (!entry) return false; var hasValue = entry[0] === key; entry[0] = entry[1] = undefined; return hasValue; }, has: function(key) { var entry = key[this.name]; if (!entry) return false; return entry[0] === key; } }; window.WeakMap = WeakMap; })(); } (function(global) { var registrationsTable = new WeakMap(); var setImmediate = window.msSetImmediate; if (!setImmediate) { var setImmediateQueue = []; var sentinel = String(Math.random()); window.addEventListener("message", function(e) { if (e.data === sentinel) { var queue = setImmediateQueue; setImmediateQueue = []; queue.forEach(function(func) { func(); }); } }); setImmediate = function(func) { setImmediateQueue.push(func); window.postMessage(sentinel, "*"); }; } var isScheduled = false; var scheduledObservers = []; function scheduleCallback(observer) { scheduledObservers.push(observer); if (!isScheduled) { isScheduled = true; setImmediate(dispatchCallbacks); } } function wrapIfNeeded(node) { return window.ShadowDOMPolyfill && window.ShadowDOMPolyfill.wrapIfNeeded(node) || node; } function dispatchCallbacks() { isScheduled = false; var observers = scheduledObservers; scheduledObservers = []; observers.sort(function(o1, o2) { return o1.uid_ - o2.uid_; }); var anyNonEmpty = false; observers.forEach(function(observer) { var queue = observer.takeRecords(); removeTransientObserversFor(observer); if (queue.length) { observer.callback_(queue, observer); anyNonEmpty = true; } }); if (anyNonEmpty) dispatchCallbacks(); } function removeTransientObserversFor(observer) { observer.nodes_.forEach(function(node) { var registrations = registrationsTable.get(node); if (!registrations) return; registrations.forEach(function(registration) { if (registration.observer === observer) registration.removeTransientObservers(); }); }); } function forEachAncestorAndObserverEnqueueRecord(target, callback) { for (var node = target; node; node = node.parentNode) { var registrations = registrationsTable.get(node); if (registrations) { for (var j = 0; j < registrations.length; j++) { var registration = registrations[j]; var options = registration.options; if (node !== target && !options.subtree) continue; var record = callback(options); if (record) registration.enqueue(record); } } } } var uidCounter = 0; function JsMutationObserver(callback) { this.callback_ = callback; this.nodes_ = []; this.records_ = []; this.uid_ = ++uidCounter; } JsMutationObserver.prototype = { observe: function(target, options) { target = wrapIfNeeded(target); if (!options.childList && !options.attributes && !options.characterData || options.attributeOldValue && !options.attributes || options.attributeFilter && options.attributeFilter.length && !options.attributes || options.characterDataOldValue && !options.characterData) { throw new SyntaxError(); } var registrations = registrationsTable.get(target); if (!registrations) registrationsTable.set(target, registrations = []); var registration; for (var i = 0; i < registrations.length; i++) { if (registrations[i].observer === this) { registration = registrations[i]; registration.removeListeners(); registration.options = options; break; } } if (!registration) { registration = new Registration(this, target, options); registrations.push(registration); this.nodes_.push(target); } registration.addListeners(); }, disconnect: function() { this.nodes_.forEach(function(node) { var registrations = registrationsTable.get(node); for (var i = 0; i < registrations.length; i++) { var registration = registrations[i]; if (registration.observer === this) { registration.removeListeners(); registrations.splice(i, 1); break; } } }, this); this.records_ = []; }, takeRecords: function() { var copyOfRecords = this.records_; this.records_ = []; return copyOfRecords; } }; function MutationRecord(type, target) { this.type = type; this.target = target; this.addedNodes = []; this.removedNodes = []; this.previousSibling = null; this.nextSibling = null; this.attributeName = null; this.attributeNamespace = null; this.oldValue = null; } function copyMutationRecord(original) { var record = new MutationRecord(original.type, original.target); record.addedNodes = original.addedNodes.slice(); record.removedNodes = original.removedNodes.slice(); record.previousSibling = original.previousSibling; record.nextSibling = original.nextSibling; record.attributeName = original.attributeName; record.attributeNamespace = original.attributeNamespace; record.oldValue = original.oldValue; return record; } var currentRecord, recordWithOldValue; function getRecord(type, target) { return currentRecord = new MutationRecord(type, target); } function getRecordWithOldValue(oldValue) { if (recordWithOldValue) return recordWithOldValue; recordWithOldValue = copyMutationRecord(currentRecord); recordWithOldValue.oldValue = oldValue; return recordWithOldValue; } function clearRecords() { currentRecord = recordWithOldValue = undefined; } function recordRepresentsCurrentMutation(record) { return record === recordWithOldValue || record === currentRecord; } function selectRecord(lastRecord, newRecord) { if (lastRecord === newRecord) return lastRecord; if (recordWithOldValue && recordRepresentsCurrentMutation(lastRecord)) return recordWithOldValue; return null; } function Registration(observer, target, options) { this.observer = observer; this.target = target; this.options = options; this.transientObservedNodes = []; } Registration.prototype = { enqueue: function(record) { var records = this.observer.records_; var length = records.length; if (records.length > 0) { var lastRecord = records[length - 1]; var recordToReplaceLast = selectRecord(lastRecord, record); if (recordToReplaceLast) { records[length - 1] = recordToReplaceLast; return; } } else { scheduleCallback(this.observer); } records[length] = record; }, addListeners: function() { this.addListeners_(this.target); }, addListeners_: function(node) { var options = this.options; if (options.attributes) node.addEventListener("DOMAttrModified", this, true); if (options.characterData) node.addEventListener("DOMCharacterDataModified", this, true); if (options.childList) node.addEventListener("DOMNodeInserted", this, true); if (options.childList || options.subtree) node.addEventListener("DOMNodeRemoved", this, true); }, removeListeners: function() { this.removeListeners_(this.target); }, removeListeners_: function(node) { var options = this.options; if (options.attributes) node.removeEventListener("DOMAttrModified", this, true); if (options.characterData) node.removeEventListener("DOMCharacterDataModified", this, true); if (options.childList) node.removeEventListener("DOMNodeInserted", this, true); if (options.childList || options.subtree) node.removeEventListener("DOMNodeRemoved", this, true); }, addTransientObserver: function(node) { if (node === this.target) return; this.addListeners_(node); this.transientObservedNodes.push(node); var registrations = registrationsTable.get(node); if (!registrations) registrationsTable.set(node, registrations = []); registrations.push(this); }, removeTransientObservers: function() { var transientObservedNodes = this.transientObservedNodes; this.transientObservedNodes = []; transientObservedNodes.forEach(function(node) { this.removeListeners_(node); var registrations = registrationsTable.get(node); for (var i = 0; i < registrations.length; i++) { if (registrations[i] === this) { registrations.splice(i, 1); break; } } }, this); }, handleEvent: function(e) { e.stopImmediatePropagation(); switch (e.type) { case "DOMAttrModified": var name = e.attrName; var namespace = e.relatedNode.namespaceURI; var target = e.target; var record = new getRecord("attributes", target); record.attributeName = name; record.attributeNamespace = namespace; var oldValue = e.attrChange === MutationEvent.ADDITION ? null : e.prevValue; forEachAncestorAndObserverEnqueueRecord(target, function(options) { if (!options.attributes) return; if (options.attributeFilter && options.attributeFilter.length && options.attributeFilter.indexOf(name) === -1 && options.attributeFilter.indexOf(namespace) === -1) { return; } if (options.attributeOldValue) return getRecordWithOldValue(oldValue); return record; }); break; case "DOMCharacterDataModified": var target = e.target; var record = getRecord("characterData", target); var oldValue = e.prevValue; forEachAncestorAndObserverEnqueueRecord(target, function(options) { if (!options.characterData) return; if (options.characterDataOldValue) return getRecordWithOldValue(oldValue); return record; }); break; case "DOMNodeRemoved": this.addTransientObserver(e.target); case "DOMNodeInserted": var target = e.relatedNode; var changedNode = e.target; var addedNodes, removedNodes; if (e.type === "DOMNodeInserted") { addedNodes = [ changedNode ]; removedNodes = []; } else { addedNodes = []; removedNodes = [ changedNode ]; } var previousSibling = changedNode.previousSibling; var nextSibling = changedNode.nextSibling; var record = getRecord("childList", target); record.addedNodes = addedNodes; record.removedNodes = removedNodes; record.previousSibling = previousSibling; record.nextSibling = nextSibling; forEachAncestorAndObserverEnqueueRecord(target, function(options) { if (!options.childList) return; return record; }); } clearRecords(); } }; global.JsMutationObserver = JsMutationObserver; if (!global.MutationObserver) global.MutationObserver = JsMutationObserver; })(this); window.CustomElements = window.CustomElements || { flags: {} }; (function(scope) { var flags = scope.flags; var modules = []; var addModule = function(module) { modules.push(module); }; var initializeModules = function() { modules.forEach(function(module) { module(scope); }); }; scope.addModule = addModule; scope.initializeModules = initializeModules; scope.hasNative = Boolean(document.registerElement); scope.useNative = !flags.register && scope.hasNative && !window.ShadowDOMPolyfill && (!window.HTMLImports || HTMLImports.useNative); })(CustomElements); CustomElements.addModule(function(scope) { var IMPORT_LINK_TYPE = window.HTMLImports ? HTMLImports.IMPORT_LINK_TYPE : "none"; function forSubtree(node, cb) { findAllElements(node, function(e) { if (cb(e)) { return true; } forRoots(e, cb); }); forRoots(node, cb); } function findAllElements(node, find, data) { var e = node.firstElementChild; if (!e) { e = node.firstChild; while (e && e.nodeType !== Node.ELEMENT_NODE) { e = e.nextSibling; } } while (e) { if (find(e, data) !== true) { findAllElements(e, find, data); } e = e.nextElementSibling; } return null; } function forRoots(node, cb) { var root = node.shadowRoot; while (root) { forSubtree(root, cb); root = root.olderShadowRoot; } } var processingDocuments; function forDocumentTree(doc, cb) { processingDocuments = []; _forDocumentTree(doc, cb); processingDocuments = null; } function _forDocumentTree(doc, cb) { doc = wrap(doc); if (processingDocuments.indexOf(doc) >= 0) { return; } processingDocuments.push(doc); var imports = doc.querySelectorAll("link[rel=" + IMPORT_LINK_TYPE + "]"); for (var i = 0, l = imports.length, n; i < l && (n = imports[i]); i++) { if (n.import) { _forDocumentTree(n.import, cb); } } cb(doc); } scope.forDocumentTree = forDocumentTree; scope.forSubtree = forSubtree; }); CustomElements.addModule(function(scope) { var flags = scope.flags; var forSubtree = scope.forSubtree; var forDocumentTree = scope.forDocumentTree; function addedNode(node) { return added(node) || addedSubtree(node); } function added(node) { if (scope.upgrade(node)) { return true; } attached(node); } function addedSubtree(node) { forSubtree(node, function(e) { if (added(e)) { return true; } }); } function attachedNode(node) { attached(node); if (inDocument(node)) { forSubtree(node, function(e) { attached(e); }); } } var hasPolyfillMutations = !window.MutationObserver || window.MutationObserver === window.JsMutationObserver; scope.hasPolyfillMutations = hasPolyfillMutations; var isPendingMutations = false; var pendingMutations = []; function deferMutation(fn) { pendingMutations.push(fn); if (!isPendingMutations) { isPendingMutations = true; setTimeout(takeMutations); } } function takeMutations() { isPendingMutations = false; var $p = pendingMutations; for (var i = 0, l = $p.length, p; i < l && (p = $p[i]); i++) { p(); } pendingMutations = []; } function attached(element) { if (hasPolyfillMutations) { deferMutation(function() { _attached(element); }); } else { _attached(element); } } function _attached(element) { if (element.__upgraded__ && (element.attachedCallback || element.detachedCallback)) { if (!element.__attached && inDocument(element)) { element.__attached = true; if (element.attachedCallback) { element.attachedCallback(); } } } } function detachedNode(node) { detached(node); forSubtree(node, function(e) { detached(e); }); } function detached(element) { if (hasPolyfillMutations) { deferMutation(function() { _detached(element); }); } else { _detached(element); } } function _detached(element) { if (element.__upgraded__ && (element.attachedCallback || element.detachedCallback)) { if (element.__attached && !inDocument(element)) { element.__attached = false; if (element.detachedCallback) { element.detachedCallback(); } } } } function inDocument(element) { var p = element; var doc = wrap(document); while (p) { if (p == doc) { return true; } p = p.parentNode || p.host; } } function watchShadow(node) { if (node.shadowRoot && !node.shadowRoot.__watched) { flags.dom && console.log("watching shadow-root for: ", node.localName); var root = node.shadowRoot; while (root) { observe(root); root = root.olderShadowRoot; } } } function handler(mutations) { if (flags.dom) { var mx = mutations[0]; if (mx && mx.type === "childList" && mx.addedNodes) { if (mx.addedNodes) { var d = mx.addedNodes[0]; while (d && d !== document && !d.host) { d = d.parentNode; } var u = d && (d.URL || d._URL || d.host && d.host.localName) || ""; u = u.split("/?").shift().split("/").pop(); } } console.group("mutations (%d) [%s]", mutations.length, u || ""); } mutations.forEach(function(mx) { if (mx.type === "childList") { forEach(mx.addedNodes, function(n) { if (!n.localName) { return; } addedNode(n); }); forEach(mx.removedNodes, function(n) { if (!n.localName) { return; } detachedNode(n); }); } }); flags.dom && console.groupEnd(); } function takeRecords(node) { node = wrap(node); if (!node) { node = wrap(document); } while (node.parentNode) { node = node.parentNode; } var observer = node.__observer; if (observer) { handler(observer.takeRecords()); takeMutations(); } } var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach); function observe(inRoot) { if (inRoot.__observer) { return; } var observer = new MutationObserver(handler); observer.observe(inRoot, { childList: true, subtree: true }); inRoot.__observer = observer; } function upgradeDocument(doc) { doc = wrap(doc); flags.dom && console.group("upgradeDocument: ", doc.baseURI.split("/").pop()); addedNode(doc); observe(doc); flags.dom && console.groupEnd(); } function upgradeDocumentTree(doc) { forDocumentTree(doc, upgradeDocument); } var originalCreateShadowRoot = Element.prototype.createShadowRoot; Element.prototype.createShadowRoot = function() { var root = originalCreateShadowRoot.call(this); CustomElements.watchShadow(this); return root; }; scope.watchShadow = watchShadow; scope.upgradeDocumentTree = upgradeDocumentTree; scope.upgradeSubtree = addedSubtree; scope.upgradeAll = addedNode; scope.attachedNode = attachedNode; scope.takeRecords = takeRecords; }); CustomElements.addModule(function(scope) { var flags = scope.flags; function upgrade(node) { if (!node.__upgraded__ && node.nodeType === Node.ELEMENT_NODE) { var is = node.getAttribute("is"); var definition = scope.getRegisteredDefinition(is || node.localName); if (definition) { if (is && definition.tag == node.localName) { return upgradeWithDefinition(node, definition); } else if (!is && !definition.extends) { return upgradeWithDefinition(node, definition); } } } } function upgradeWithDefinition(element, definition) { flags.upgrade && console.group("upgrade:", element.localName); if (definition.is) { element.setAttribute("is", definition.is); } implementPrototype(element, definition); element.__upgraded__ = true; created(element); scope.attachedNode(element); scope.upgradeSubtree(element); flags.upgrade && console.groupEnd(); return element; } function implementPrototype(element, definition) { if (Object.__proto__) { element.__proto__ = definition.prototype; } else { customMixin(element, definition.prototype, definition.native); element.__proto__ = definition.prototype; } } function customMixin(inTarget, inSrc, inNative) { var used = {}; var p = inSrc; while (p !== inNative && p !== HTMLElement.prototype) { var keys = Object.getOwnPropertyNames(p); for (var i = 0, k; k = keys[i]; i++) { if (!used[k]) { Object.defineProperty(inTarget, k, Object.getOwnPropertyDescriptor(p, k)); used[k] = 1; } } p = Object.getPrototypeOf(p); } } function created(element) { if (element.createdCallback) { element.createdCallback(); } } scope.upgrade = upgrade; scope.upgradeWithDefinition = upgradeWithDefinition; scope.implementPrototype = implementPrototype; }); CustomElements.addModule(function(scope) { var upgradeDocumentTree = scope.upgradeDocumentTree; var upgrade = scope.upgrade; var upgradeWithDefinition = scope.upgradeWithDefinition; var implementPrototype = scope.implementPrototype; var useNative = scope.useNative; function register(name, options) { var definition = options || {}; if (!name) { throw new Error("document.registerElement: first argument `name` must not be empty"); } if (name.indexOf("-") < 0) { throw new Error("document.registerElement: first argument ('name') must contain a dash ('-'). Argument provided was '" + String(name) + "'."); } if (isReservedTag(name)) { throw new Error("Failed to execute 'registerElement' on 'Document': Registration failed for type '" + String(name) + "'. The type name is invalid."); } if (getRegisteredDefinition(name)) { throw new Error("DuplicateDefinitionError: a type with name '" + String(name) + "' is already registered"); } if (!definition.prototype) { definition.prototype = Object.create(HTMLElement.prototype); } definition.__name = name.toLowerCase(); definition.lifecycle = definition.lifecycle || {}; definition.ancestry = ancestry(definition.extends); resolveTagName(definition); resolvePrototypeChain(definition); overrideAttributeApi(definition.prototype); registerDefinition(definition.__name, definition); definition.ctor = generateConstructor(definition); definition.ctor.prototype = definition.prototype; definition.prototype.constructor = definition.ctor; if (scope.ready) { upgradeDocumentTree(document); } return definition.ctor; } function overrideAttributeApi(prototype) { if (prototype.setAttribute._polyfilled) { return; } var setAttribute = prototype.setAttribute; prototype.setAttribute = function(name, value) { changeAttribute.call(this, name, value, setAttribute); }; var removeAttribute = prototype.removeAttribute; prototype.removeAttribute = function(name) { changeAttribute.call(this, name, null, removeAttribute); }; prototype.setAttribute._polyfilled = true; } function changeAttribute(name, value, operation) { name = name.toLowerCase(); var oldValue = this.getAttribute(name); operation.apply(this, arguments); var newValue = this.getAttribute(name); if (this.attributeChangedCallback && newValue !== oldValue) { this.attributeChangedCallback(name, oldValue, newValue); } } function isReservedTag(name) { for (var i = 0; i < reservedTagList.length; i++) { if (name === reservedTagList[i]) { return true; } } } var reservedTagList = [ "annotation-xml", "color-profile", "font-face", "font-face-src", "font-face-uri", "font-face-format", "font-face-name", "missing-glyph" ]; function ancestry(extnds) { var extendee = getRegisteredDefinition(extnds); if (extendee) { return ancestry(extendee.extends).concat([ extendee ]); } return []; } function resolveTagName(definition) { var baseTag = definition.extends; for (var i = 0, a; a = definition.ancestry[i]; i++) { baseTag = a.is && a.tag; } definition.tag = baseTag || definition.__name; if (baseTag) { definition.is = definition.__name; } } function resolvePrototypeChain(definition) { if (!Object.__proto__) { var nativePrototype = HTMLElement.prototype; if (definition.is) { var inst = document.createElement(definition.tag); var expectedPrototype = Object.getPrototypeOf(inst); if (expectedPrototype === definition.prototype) { nativePrototype = expectedPrototype; } } var proto = definition.prototype, ancestor; while (proto && proto !== nativePrototype) { ancestor = Object.getPrototypeOf(proto); proto.__proto__ = ancestor; proto = ancestor; } definition.native = nativePrototype; } } function instantiate(definition) { return upgradeWithDefinition(domCreateElement(definition.tag), definition); } var registry = {}; function getRegisteredDefinition(name) { if (name) { return registry[name.toLowerCase()]; } } function registerDefinition(name, definition) { registry[name] = definition; } function generateConstructor(definition) { return function() { return instantiate(definition); }; } var HTML_NAMESPACE = "http://www.w3.org/1999/xhtml"; function createElementNS(namespace, tag, typeExtension) { if (namespace === HTML_NAMESPACE) { return createElement(tag, typeExtension); } else { return domCreateElementNS(namespace, tag); } } function createElement(tag, typeExtension) { var definition = getRegisteredDefinition(typeExtension || tag); if (definition) { if (tag == definition.tag && typeExtension == definition.is) { return new definition.ctor(); } if (!typeExtension && !definition.is) { return new definition.ctor(); } } var element; if (typeExtension) { element = createElement(tag); element.setAttribute("is", typeExtension); return element; } element = domCreateElement(tag); if (tag.indexOf("-") >= 0) { implementPrototype(element, HTMLElement); } return element; } function cloneNode(deep) { var n = domCloneNode.call(this, deep); upgrade(n); return n; } var domCreateElement = document.createElement.bind(document); var domCreateElementNS = document.createElementNS.bind(document); var domCloneNode = Node.prototype.cloneNode; var isInstance; if (!Object.__proto__ && !useNative) { isInstance = function(obj, ctor) { var p = obj; while (p) { if (p === ctor.prototype) { return true; } p = p.__proto__; } return false; }; } else { isInstance = function(obj, base) { return obj instanceof base; }; } document.registerElement = register; document.createElement = createElement; document.createElementNS = createElementNS; Node.prototype.cloneNode = cloneNode; scope.registry = registry; scope.instanceof = isInstance; scope.reservedTagList = reservedTagList; scope.getRegisteredDefinition = getRegisteredDefinition; document.register = document.registerElement; }); (function(scope) { var useNative = scope.useNative; var initializeModules = scope.initializeModules; if (useNative) { var nop = function() {}; scope.watchShadow = nop; scope.upgradeAll = nop; scope.upgradeDocumentTree = nop; scope.takeRecords = nop; scope.instanceof = function(obj, base) { return obj instanceof base; }; } else { initializeModules(); } var upgradeDocumentTree = scope.upgradeDocumentTree; if (!window.wrap) { if (window.ShadowDOMPolyfill) { window.wrap = ShadowDOMPolyfill.wrapIfNeeded; window.unwrap = ShadowDOMPolyfill.unwrapIfNeeded; } else { window.wrap = window.unwrap = function(node) { return node; }; } } function bootstrap() { upgradeDocumentTree(wrap(document)); if (window.HTMLImports) { HTMLImports.__importsParsingHook = function(elt) { upgradeDocumentTree(wrap(elt.import)); }; } CustomElements.ready = true; setTimeout(function() { CustomElements.readyTime = Date.now(); if (window.HTMLImports) { CustomElements.elapsed = CustomElements.readyTime - HTMLImports.readyTime; } document.dispatchEvent(new CustomEvent("WebComponentsReady", { bubbles: true })); }); } if (typeof window.CustomEvent !== "function") { window.CustomEvent = function(inType, params) { params = params || {}; var e = document.createEvent("CustomEvent"); e.initCustomEvent(inType, Boolean(params.bubbles), Boolean(params.cancelable), params.detail); return e; }; window.CustomEvent.prototype = window.Event.prototype; } if (document.readyState === "complete" || scope.flags.eager) { bootstrap(); } else if (document.readyState === "interactive" && !window.attachEvent && (!window.HTMLImports || window.HTMLImports.ready)) { bootstrap(); } else { var loadEvent = window.HTMLImports && !HTMLImports.ready ? "HTMLImportsLoaded" : "DOMContentLoaded"; window.addEventListener(loadEvent, bootstrap); } })(window.CustomElements);
// Invoke 'strict' JavaScript mode 'use strict'; // Create the 'articles' module angular.module('dashboards', ['ui.directives','720kb.datepicker','ui.timepicker','ngDialog','angular-svg-round-progress']);
YUI.add('aui-datatable-edit', function (A, NAME) { /** * The Datatable Component * * @module aui-datatable * @submodule aui-datatable-edit */ var Lang = A.Lang, AArray = A.Array, isArray = Lang.isArray, isBoolean = Lang.isBoolean, isFunction = Lang.isFunction, isObject = Lang.isObject, isString = Lang.isString, isValue = Lang.isValue, LString = Lang.String, DataType = A.DataType, isBaseEditor = function(val) { return (val instanceof A.BaseCellEditor); }, WidgetStdMod = A.WidgetStdMod, AgetClassName = A.getClassName, REGEX_BR = /<br\s*\/?>/gi, REGEX_NL = /[\r\n]/g, CSS_CELLEDITOR_EDIT = AgetClassName('celleditor', 'edit'), CSS_CELLEDITOR_EDIT_ADD_OPTION = AgetClassName('celleditor', 'edit', 'add', 'option'), CSS_CELLEDITOR_EDIT_DD_HANDLE = AgetClassName('celleditor', 'edit', 'dd', 'handle'), CSS_CELLEDITOR_EDIT_DELETE_OPTION = AgetClassName('celleditor', 'edit', 'delete', 'option'), CSS_CELLEDITOR_EDIT_HIDE_OPTION = AgetClassName('celleditor', 'edit', 'hide', 'option'), CSS_CELLEDITOR_EDIT_INPUT_NAME = AgetClassName('celleditor', 'edit', 'input', 'name'), CSS_CELLEDITOR_EDIT_INPUT_VALUE = AgetClassName('celleditor', 'edit', 'input', 'value'), CSS_CELLEDITOR_EDIT_LABEL = AgetClassName('celleditor', 'edit', 'label'), CSS_CELLEDITOR_EDIT_LINK = AgetClassName('celleditor', 'edit', 'link'), CSS_CELLEDITOR_EDIT_OPTION_ROW = AgetClassName('celleditor', 'edit', 'option', 'row'), CSS_CELLEDITOR_ELEMENT = AgetClassName('celleditor', 'element'), CSS_CELLEDITOR_OPTION = AgetClassName('celleditor', 'option'), CSS_DATATABLE_EDITABLE = AgetClassName('datatable', 'editable'), CSS_ICON = AgetClassName('icon'), CSS_ICON_GRIP_DOTTED_VERTICAL = AgetClassName('icon', 'grip', 'dotted', 'vertical'), TPL_BR = '<br/>'; /** * An extension for A.DataTable to support Cell Editing. * * @class A.DataTable.CellEditorSupport * @param {Object} config Object literal specifying widget configuration * properties. * @constructor */ var CellEditorSupport = function() {}; /** * Static property provides a string to identify the class. * * @property NAME * @type String * @static */ CellEditorSupport.NAME = 'dataTableCellEditorSupport'; /** * TODO. Wanna help? Please send a Pull Request. * * @property EDITOR_ZINDEX * @default 9999 * @type Number * @static */ CellEditorSupport.EDITOR_ZINDEX = 9999; /** * Static property used to define the default attribute * configuration for the CellEditorSupport. * * @property ATTRS * @type Object * @static */ CellEditorSupport.ATTRS = { /** * TODO. Wanna help? Please send a Pull Request. * * @attribute editEvent * @default 'click' * @type String */ editEvent: { setter: '_setEditEvent', validator: isString, value: 'click' } }; A.mix(CellEditorSupport.prototype, { /** * Construction logic executed during CellEditorSupport instantiation. * Lifecycle. * * @method initializer * @protected */ initializer: function() { var instance = this, editEvent = instance.get('editEvent'); instance.CLASS_NAMES_CELL_EDITOR_SUPPORT = { cell: instance.getClassName('cell'), readOnly: instance.getClassName('read', 'only') }; instance.after('render', instance._afterCellEditorSupportRender); instance.delegate(editEvent, instance._onEditCell, '.' + instance.CLASS_NAMES_CELL_EDITOR_SUPPORT.cell, instance); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method getEditor * @param record * @param column */ getEditor: function(record, column) { var instance = this, columnEditor = column.editor, recordEditor = record.get('editor'); if (columnEditor === false || recordEditor === false) { return null; } return recordEditor || columnEditor; }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _afterCellEditorSupportRender * @protected */ _afterCellEditorSupportRender: function() { var instance = this; instance._syncModelsReadOnlyUI(); instance.body.after(A.bind(instance._syncModelsReadOnlyUI, instance), instance.body, 'render'); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _onEditCell * @param event * @protected */ _onEditCell: function(event) { var instance = this, activeCell = instance.get('activeCell'), alignNode = event.alignNode || activeCell, column = instance.getColumn(alignNode), record = instance.getRecord(alignNode), editor = instance.getEditor(record, column); if (isBaseEditor(editor) && !record.get('readOnly')) { if (!editor.get('rendered')) { editor.on({ visibleChange: A.bind(instance._onEditorVisibleChange, instance), save: A.bind(instance._onEditorSave, instance) }); editor.set('zIndex', CellEditorSupport.EDITOR_ZINDEX); editor.render(); } editor.set('value', record.get(column.key)); editor.show().move(alignNode.getXY()); } }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _onEditorSave * @param event * @protected */ _onEditorSave: function(event) { var instance = this, editor = event.currentTarget, column = instance.getActiveColumn(), record = instance.getActiveRecord(); editor.set('value', event.newVal); // TODO: Memorize the activeCell coordinates to set the focus on it // instead instance.set('activeCell', instance.get('activeCell')); record.set(column.key, event.newVal); // TODO: Sync highlight frames UI instead? if (instance.highlight) { instance.highlight.clear(); } }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _onEditorVisibleChange * @param event * @protected */ _onEditorVisibleChange: function(event) { var instance = this, editor = event.currentTarget; if (event.newVal) { editor._syncFocus(); } }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _syncModelReadOnlyUI * @param model * @protected */ _syncModelReadOnlyUI: function(model) { var instance = this, row = instance.getRow(model); row.toggleClass(instance.CLASS_NAMES_CELL_EDITOR_SUPPORT['readOnly'], model.get('readOnly') === true); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _syncModelsReadOnlyUI * @protected */ _syncModelsReadOnlyUI: function() { var instance = this; instance.get('data').each(function(model) { instance._syncModelReadOnlyUI(model); }); }, // Deprecated methods // Use getEditor /** * TODO. Wanna help? Please send a Pull Request. * * @method getCellEditor */ getCellEditor: function() { return this.getEditor.apply(this, arguments); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method getRecordColumnValue * @param record * @param column */ getRecordColumnValue: function(record, column) { return record.get(column.key); } }); A.DataTable.CellEditorSupport = CellEditorSupport; A.Base.mix(A.DataTable, [CellEditorSupport]); /** * Abstract class BaseCellEditor. * * @class A.BaseCellEditor * @extends Overlay * @param {Object} config Object literal specifying widget configuration * properties. * @constructor */ var BaseCellEditor = A.Component.create({ /** * Static property provides a string to identify the class. * * @property NAME * @type String * @static */ NAME: 'baseCellEditor', /** * Static property used to define the default attribute * configuration for the BaseCellEditor. * * @property ATTRS * @type Object * @static */ ATTRS: { /** * TODO. Wanna help? Please send a Pull Request. * * @attribute editable * @default false * @type Boolean */ editable: { value: false, validator: isBoolean }, /** * TODO. Wanna help? Please send a Pull Request. * * @attribute elementName * @default 'value' * @type String */ elementName: { value: 'value', validator: isString }, /** * TODO. Wanna help? Please send a Pull Request. * * @attribute footerContent * @default '' * @type String */ footerContent: { value: '' }, /** * TODO. Wanna help? Please send a Pull Request. * * @attribute hideOnSave * @default true * @type Boolean */ hideOnSave: { value: true, validator: isBoolean }, /** * TODO. Wanna help? Please send a Pull Request. * * @attribute inputFormatter * @type Function */ inputFormatter: { value: function(val) { if (isString(val)) { val = val.replace(REGEX_NL, TPL_BR); } return val; } }, /** * TODO. Wanna help? Please send a Pull Request. * * @attribute outputFormatter * @type Function */ outputFormatter: { value: function(val) { var instance = this; if (isString(val)) { if (instance.get('unescapeValue')) { val = LString.unescapeEntities(val); } val = val.replace(REGEX_BR, 'n'); } return val; } }, /** * TODO. Wanna help? Please send a Pull Request. * * @attribute showToolbar * @default true * @type Boolean */ showToolbar: { value: true, validator: isBoolean }, /** * Collection of strings used to label elements of the UI. * * @attribute strings * @type Object */ strings: { value: { edit: 'Edit', save: 'Save', cancel: 'Cancel' } }, /** * TODO. Wanna help? Please send a Pull Request. * * @attribute tabIndex * @default 1 * @type Number */ tabIndex: { value: 1 }, /** * TODO. Wanna help? Please send a Pull Request. * * @attribute toolbar * @default null * @type Object */ toolbar: { setter: '_setToolbar', validator: isObject, value: null }, /** * TODO. Wanna help? Please send a Pull Request. * * @attribute unescapeValue * @default true * @type Boolean */ unescapeValue: { value: true, validator: isBoolean }, /** * TODO. Wanna help? Please send a Pull Request. * * @attribute validator * @default null * @type Object */ validator: { setter: '_setValidator', validator: isObject, value: null }, /** * TODO. Wanna help? Please send a Pull Request. * * @attribute value * @default '' * @type String */ value: { value: '' }, /** * TODO. Wanna help? Please send a Pull Request. * * @attribute visible * @default false * @type Boolean */ visible: { value: false } }, /** * Static property used to define which component it extends. * * @property EXTENDS * @type Object * @static */ EXTENDS: A.Overlay, /** * TODO. Wanna help? Please send a Pull Request. * * @property UI_ATTRS * @type Array * @static */ UI_ATTRS: ['editable', 'showToolbar', 'value'], prototype: { CONTENT_TEMPLATE: '<form></form>', ELEMENT_TEMPLATE: null, elements: null, validator: null, _hDocMouseDownEv: null, /** * Construction logic executed during BaseCellEditor instantiation. * Lifecycle. * * @method initializer * @protected */ initializer: function(config) { var instance = this; instance._initEvents(); }, /** * TODO. Wanna help? Please send a Pull Request. Lifecycle. * * @method destructor * @protected */ destructor: function() { var instance = this; var hDocMouseDown = instance._hDocMouseDownEv; var toolbar = instance.toolbar; var validator = instance.validator; if (hDocMouseDown) { hDocMouseDown.detach(); } if (toolbar) { toolbar.destroy(); } if (validator) { validator.destroy(); } }, /** * Bind the events on the BaseCellEditor UI. Lifecycle. * * @method bindUI * @protected */ bindUI: function() { var instance = this; instance.get('boundingBox').on('key', A.bind(instance._onEscKey, instance), 'down:27'); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method formatValue * @param formatter * @param val */ formatValue: function(formatter, val) { var instance = this; if (isFunction(formatter)) { val = formatter.call(instance, val); } return val; }, /** * TODO. Wanna help? Please send a Pull Request. * * @method getValue */ getValue: function() { var instance = this; return instance.formatValue( instance.get('inputFormatter'), instance.getElementsValue() ); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _initEvents * @protected */ _initEvents: function() { var instance = this; instance.publish({ cancel: { defaultFn: instance._defCancelFn }, initEdit: { defaultFn: instance._defInitEditFn, fireOnce: true }, initValidator: { defaultFn: instance._defInitValidatorFn, fireOnce: true }, initToolbar: { defaultFn: instance._defInitToolbarFn, fireOnce: true }, save: { defaultFn: instance._defSaveFn } }); instance.after({ render: instance._afterRender, visibleChange: A.debounce(instance._debounceVisibleChange, 350, instance) }); instance.on({ 'form-validator:submit': A.bind(instance._onSubmit, instance) }); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _afterRender * @protected */ _afterRender: function() { var instance = this; instance._handleInitValidatorEvent(); instance._handleInitToolbarEvent(); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _defCancelFn * @param event * @protected */ _defCancelFn: function(event) { var instance = this; instance.hide(); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _defInitValidatorFn * @param event * @protected */ _defInitValidatorFn: function(event) { var instance = this; instance.validator = new A.FormValidator( instance.get('validator') ); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _defInitToolbarFn * @param event * @protected */ _defInitToolbarFn: function(event) { var instance = this; var editable = instance.get('editable'); instance.toolbar = new A.Toolbar( instance.get('toolbar') ).render(instance.footerNode); if (editable) { instance._uiSetEditable(editable); } }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _defSaveFn * @param event * @protected */ _defSaveFn: function(event) { var instance = this; if (instance.get('hideOnSave')) { instance.hide(); } }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _debounceVisibleChange * @param event * @protected */ _debounceVisibleChange: function(event) { var instance = this; var hDocMouseDown = instance._hDocMouseDownEv; if (event.newVal) { if (!hDocMouseDown) { instance._hDocMouseDownEv = A.getDoc().on('mousedown', A.bind(instance._onDocMouseDownExt, instance)); } } else if (hDocMouseDown) { hDocMouseDown.detach(); instance._hDocMouseDownEv = null; } }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _handleCancelEvent * @protected */ _handleCancelEvent: function() { var instance = this; instance.fire('cancel'); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _handleEditEvent * @protected */ _handleEditEvent: function() { var instance = this; instance.fire('edit'); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _handleInitEditEvent * @protected */ _handleInitEditEvent: function() { var instance = this; if (instance.get('rendered')) { this.fire('initEdit'); } }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _handleInitValidatorEvent * @protected */ _handleInitValidatorEvent: function() { var instance = this; if (instance.get('rendered')) { this.fire('initValidator'); } }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _handleInitToolbarEvent * @protected */ _handleInitToolbarEvent: function() { var instance = this; if (instance.get('rendered') && instance.get('showToolbar')) { this.fire('initToolbar'); } }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _handleSaveEvent * @protected */ _handleSaveEvent: function() { var instance = this; if (!instance.validator.hasErrors()) { instance.fire('save', { newVal: instance.getValue(), prevVal: instance.get('value') }); } }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _onDocMouseDownExt * @param event * @protected */ _onDocMouseDownExt: function(event) { var instance = this; var boundingBox = instance.get('boundingBox'); if (!boundingBox.contains(event.target)) { instance.set('visible', false); } }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _onEscKey * @param event * @protected */ _onEscKey: function(event) { var instance = this; instance.hide(); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _onSubmit * @param event * @protected */ _onSubmit: function(event) { var instance = this; var validator = event.validator; if (validator) { validator.formEvent.halt(); } }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _setToolbar * @param val * @protected */ _setToolbar: function(val) { var instance = this; var strings = instance.getStrings(); return A.merge({ activeState: false, children: [ [ { on: { click: A.bind(instance._handleSaveEvent, instance) }, label: strings['save'], icon: 'icon-ok-sign' }, { on: { click: A.bind(instance._handleCancelEvent, instance) }, label: strings['cancel'] } ] ] }, val); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _setValidator * @param val * @protected */ _setValidator: function(val) { var instance = this; return A.merge({ boundingBox: instance.get('contentBox'), bubbleTargets: instance }, val ); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _uiSetShowToolbar * @param val * @protected */ _uiSetShowToolbar: function(val) { var instance = this; var footerNode = instance.footerNode; if (val) { footerNode.show(); } else { footerNode.hide(); } instance._handleInitToolbarEvent(); }, /** * TODO. Wanna help? Please send a Pull Request. * * NOTE FOR DEVELOPERS: Yoy *may* want to replace the methods from * this section on your implementation. * * @method getElementsValue */ getElementsValue: function() { var instance = this; var elements = instance.elements; if (elements) { return elements.get('value'); } return ''; }, /** * Render the BaseCellEditor component instance. Lifecycle. * * @method renderUI * @protected */ renderUI: function() { var instance = this; if (instance.ELEMENT_TEMPLATE) { instance.elements = A.Node.create(instance.ELEMENT_TEMPLATE); instance._syncElementsName(); instance.setStdModContent(WidgetStdMod.BODY, instance.elements); } }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _defInitEditFn * @param event * @protected */ _defInitEditFn: function(event) {}, /** * TODO. Wanna help? Please send a Pull Request. * * @method _syncElementsFocus * @protected */ _syncElementsFocus: function() { var instance = this; instance.elements.selectText(); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _syncElementsName * @protected */ _syncElementsName: function() { var instance = this; instance.elements.setAttribute( 'name', instance.get('elementName') ); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _syncFocus * @protected */ _syncFocus: function() { var instance = this; A.later(0, instance, instance._syncElementsFocus); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _uiSetEditable * @param val * @protected */ _uiSetEditable: function(val) { var instance = this; var toolbar = instance.toolbar; if (instance.get('rendered') && toolbar) { if (val) { toolbar.add( [ { icon: 'icon-edit', label: instance.getString('edit'), on: { click: A.bind(instance._handleEditEvent, instance) } } ], 1 ); } else { toolbar.remove(1); } } }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _uiSetValue * @param val * @protected */ _uiSetValue: function(val) { var instance = this; var elements = instance.elements; if (elements) { elements.val( instance.formatValue(instance.get('outputFormatter'), val) ); } } } }); A.BaseCellEditor = BaseCellEditor; /** * Abstract class BaseOptionsCellEditor for options attribute support. * * @class A.BaseOptionsCellEditor * @extends A.BaseCellEditor * @param {Object} config Object literal specifying widget configuration * properties. * @constructor */ var BaseOptionsCellEditor = A.Component.create({ /** * Static property provides a string to identify the class. * * @property NAME * @type String * @static */ NAME: 'optionsCellEditor', /** * Static property used to define the default attribute * configuration for the BaseOptionsCellEditor. * * @property ATTRS * @type Object * @static */ ATTRS: { /** * TODO. Wanna help? Please send a Pull Request. * * @attribute inputFormatter * @default null */ inputFormatter: { value: null }, /** * TODO. Wanna help? Please send a Pull Request. * * @attribute options * @default {} * @type Object */ options: { setter: '_setOptions', value: {}, validator: isObject }, /** * TODO. Wanna help? Please send a Pull Request. * * @attribute outputFormatter * @default null */ outputFormatter: { value: null }, /** * TODO. Wanna help? Please send a Pull Request. * * @attribute selectedAttrName * @default 'selected' * @type String */ selectedAttrName: { value: 'selected', validator: isString }, /** * Collection of strings used to label elements of the UI. * * @attribute strings * @type Object */ strings: { value: { add: 'Add', cancel: 'Cancel', addOption: 'Add option', edit: 'Edit options', editOptions: 'Edit option(s)', name: 'Name', remove: 'Remove', save: 'Save', stopEditing: 'Stop editing', value: 'Value' } } }, /** * Static property used to define which component it extends. * * @property EXTENDS * @type Object * @static */ EXTENDS: A.BaseCellEditor, /** * TODO. Wanna help? Please send a Pull Request. * * @property UI_ATTRS * @type Array * @static */ UI_ATTRS: ['options'], prototype: { EDIT_TEMPLATE: '<div class="' + CSS_CELLEDITOR_EDIT + '"></div>', EDIT_OPTION_ROW_TEMPLATE: '<div class="' + CSS_CELLEDITOR_EDIT_OPTION_ROW + '">' + '<span class="' + [ CSS_CELLEDITOR_EDIT_DD_HANDLE, CSS_ICON, CSS_ICON_GRIP_DOTTED_VERTICAL].join(' ') + '"></span>' + '<input class="' + CSS_CELLEDITOR_EDIT_INPUT_NAME + '" size="7" placeholder="{titleName}" title="{titleName}" type="text" value="{valueName}" /> ' + '<input class="' + CSS_CELLEDITOR_EDIT_INPUT_VALUE + '" size="7" placeholder="{titleValue}" title="{titleValue}" type="text" value="{valueValue}" /> ' + '<a class="' + [ CSS_CELLEDITOR_EDIT_LINK, CSS_CELLEDITOR_EDIT_DELETE_OPTION].join(' ') + '" href="javascript:void(0);">{remove}</a> ' + '</div>', EDIT_ADD_LINK_TEMPLATE: '<a class="' + [CSS_CELLEDITOR_EDIT_LINK, CSS_CELLEDITOR_EDIT_ADD_OPTION].join( ' ') + '" href="javascript:void(0);">{addOption}</a> ', EDIT_LABEL_TEMPLATE: '<div class="' + CSS_CELLEDITOR_EDIT_LABEL + '">{editOptions}</div>', editContainer: null, editSortable: null, options: null, /** * Construction logic executed during BaseOptionsCellEditor * instantiation. Lifecycle. * * @method initializer * @protected */ initializer: function() { var instance = this; instance.on('edit', instance._onEditEvent); instance.on('save', instance._onSave); instance.after('initToolbar', instance._afterInitToolbar); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method addNewOption * @param name * @param value */ addNewOption: function(name, value) { var instance = this; var addOptionLink = instance.editContainer.one('.' + CSS_CELLEDITOR_EDIT_ADD_OPTION); var newRow = A.Node.create( instance._createEditOption( name || '', value || '' ) ); addOptionLink.placeBefore(newRow); newRow.one('input').focus(); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method removeOption * @param optionRow */ removeOption: function(optionRow) { optionRow.remove(); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method saveOptions */ saveOptions: function() { var instance = this; var editContainer = instance.editContainer; if (editContainer) { var names = editContainer.all('.' + CSS_CELLEDITOR_EDIT_INPUT_NAME); var values = editContainer.all('.' + CSS_CELLEDITOR_EDIT_INPUT_VALUE); var options = {}; names.each(function(inputName, index) { var name = inputName.val(); var value = values.item(index).val(); options[value] = name; }); instance.set('options', options); instance._uiSetValue( instance.get('value') ); instance.toggleEdit(); } }, /** * TODO. Wanna help? Please send a Pull Request. * * @method toggleEdit */ toggleEdit: function() { var instance = this; instance.editContainer.toggle(); }, /** * TODO. Wanna help? Please send a Pull Request. * TODO. Rewrite this method. * * @method _createOptions * @param val * @protected */ _createOptions: function(val) { var instance = this; var elements = instance.elements; var optionsBuffer = []; var wrappersBuffer = []; var optionTpl = instance.OPTION_TEMPLATE; var optionWrapperTpl = instance.OPTION_WRAPPER; A.each(val, function(oLabel, oValue) { var values = { id: A.guid(), label: oLabel, name: oValue, value: oValue }; if (optionTpl) { optionsBuffer.push(Lang.sub(optionTpl, values)); } if (optionWrapperTpl) { wrappersBuffer.push(Lang.sub(optionWrapperTpl, values)); } }); var options = A.NodeList.create(optionsBuffer.join('')); var wrappers = A.NodeList.create(wrappersBuffer.join('')); if (wrappers.size()) { wrappers.each(function(wrapper, i) { wrapper.prepend(options.item(i)); }); elements.setContent(wrappers); } else { elements.setContent(options); } instance.options = options; }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _createEditBuffer * @protected */ _createEditBuffer: function() { var instance = this; var strings = instance.getStrings(); var buffer = []; buffer.push( Lang.sub(instance.EDIT_LABEL_TEMPLATE, { editOptions: strings['editOptions'] }) ); A.each(instance.get('options'), function(name, value) { buffer.push(instance._createEditOption(name, value)); }); buffer.push( Lang.sub(instance.EDIT_ADD_LINK_TEMPLATE, { addOption: strings['addOption'] }) ); return buffer.join(''); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _createEditOption * @param name * @param value * @protected */ _createEditOption: function(name, value) { var instance = this; var strings = instance.getStrings(); return Lang.sub( instance.EDIT_OPTION_ROW_TEMPLATE, { remove: strings['remove'], titleName: strings['name'], titleValue: strings['value'], valueName: name, valueValue: value } ); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _defInitEditFn * @param event * @protected */ _defInitEditFn: function(event) { var instance = this; var editContainer = A.Node.create(instance.EDIT_TEMPLATE); editContainer.delegate('click', A.bind(instance._onEditLinkClickEvent, instance), '.' + CSS_CELLEDITOR_EDIT_LINK); editContainer.delegate('keydown', A.bind(instance._onEditKeyEvent, instance), 'input'); instance.editContainer = editContainer; instance.setStdModContent( WidgetStdMod.BODY, editContainer.hide(), WidgetStdMod.AFTER ); instance.editSortable = new A.Sortable({ container: editContainer, handles: ['.' + CSS_CELLEDITOR_EDIT_DD_HANDLE], nodes: '.' + CSS_CELLEDITOR_EDIT_OPTION_ROW, opacity: '.3' }).delegate.dd.plug(A.Plugin.DDConstrained, { constrain: editContainer, stickY: true }); instance._syncEditOptionsUI(); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _getSelectedOptions * @protected */ _getSelectedOptions: function() { var instance = this; var options = []; instance.options.each(function(option) { if (option.get(instance.get('selectedAttrName'))) { options.push(option); } }); return A.all(options); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _onEditEvent * @param event * @protected */ _onEditEvent: function(event) { var instance = this; instance._handleInitEditEvent(); instance.toggleEdit(); instance._syncEditOptionsUI(); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _onEditLinkClickEvent * @param event * @protected */ _onEditLinkClickEvent: function(event) { var instance = this; var currentTarget = event.currentTarget; if (currentTarget.test('.' + CSS_CELLEDITOR_EDIT_ADD_OPTION)) { instance.addNewOption(); } else if (currentTarget.test('.' + CSS_CELLEDITOR_EDIT_HIDE_OPTION)) { instance.toggleEdit(); } else if (currentTarget.test('.' + CSS_CELLEDITOR_EDIT_DELETE_OPTION)) { instance.removeOption( currentTarget.ancestor('.' + CSS_CELLEDITOR_EDIT_OPTION_ROW) ); } event.halt(); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _onEditKeyEvent * @param event * @protected */ _onEditKeyEvent: function(event) { var instance = this; var currentTarget = event.currentTarget; if (event.isKey('return')) { var nextInput = currentTarget.next('input'); if (nextInput) { nextInput.selectText(); } else { instance.addNewOption(); } event.halt(); } }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _onSave * @param event * @protected */ _onSave: function(event) { var instance = this; instance.saveOptions(); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _setOptions * @param val * @protected */ _setOptions: function(val) { var options = {}; if (isArray(val)) { AArray.each(val, function(value) { options[value] = value; }); } else if (isObject(val)) { options = val; } return options; }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _syncEditOptionsUI * @protected */ _syncEditOptionsUI: function() { var instance = this; instance.editContainer.setContent(instance._createEditBuffer()); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _uiSetOptions * @param val * @protected */ _uiSetOptions: function(val) { var instance = this; instance._createOptions(val); instance._uiSetValue(instance.get('value')); instance._syncElementsName(); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _uiSetValue * @param val * @protected */ _uiSetValue: function(val) { var instance = this; var options = instance.options; if (options && options.size()) { options.set(instance.get('selectedAttrName'), false); if (isValue(val)) { if (!isArray(val)) { val = String(val).split(','); } AArray.each(val, function(value) { options.filter('[value="' + Lang.trim(value) + '"]').set(instance.get( 'selectedAttrName'), true); }); } } return val; } } }); A.BaseOptionsCellEditor = BaseOptionsCellEditor; /** * TextCellEditor class. * * @class A.TextCellEditor * @extends A.BaseCellEditor * @param {Object} config Object literal specifying widget configuration * properties. * @constructor */ var TextCellEditor = A.Component.create({ /** * Static property provides a string to identify the class. * * @property NAME * @type String * @static */ NAME: 'textCellEditor', /** * Static property used to define which component it extends. * * @property EXTENDS * @type Object * @static */ EXTENDS: A.BaseCellEditor, prototype: { ELEMENT_TEMPLATE: '<input autocomplete="off" class="' + CSS_CELLEDITOR_ELEMENT + '" type="text" />' } }); A.TextCellEditor = TextCellEditor; /** * TextAreaCellEditor class. * * @class A.TextAreaCellEditor * @extends A.BaseCellEditor * @param {Object} config Object literal specifying widget configuration * properties. * @constructor */ var TextAreaCellEditor = A.Component.create({ /** * Static property provides a string to identify the class. * * @property NAME * @type String * @static */ NAME: 'textAreaCellEditor', /** * Static property used to define which component it extends. * * @property EXTENDS * @type Object * @static */ EXTENDS: A.BaseCellEditor, prototype: { ELEMENT_TEMPLATE: '<textarea class="' + CSS_CELLEDITOR_ELEMENT + '"></textarea>' } }); A.TextAreaCellEditor = TextAreaCellEditor; /** * DropDownCellEditor class. * * @class A.DropDownCellEditor * @extends A.BaseOptionsCellEditor * @param {Object} config Object literal specifying widget configuration * properties. * @constructor */ var DropDownCellEditor = A.Component.create({ /** * Static property provides a string to identify the class. * * @property NAME * @type String * @static */ NAME: 'dropDownCellEditor', /** * Static property used to define the default attribute * configuration for the DropDownCellEditor. * * @property ATTRS * @type Object * @static */ ATTRS: { /** * TODO. Wanna help? Please send a Pull Request. * * @attribute multiple * @default false * @type Boolean */ multiple: { value: false, validator: isBoolean } }, /** * Static property used to define which component it extends. * * @property EXTENDS * @type Object * @static */ EXTENDS: A.BaseOptionsCellEditor, /** * TODO. Wanna help? Please send a Pull Request. * * @property UI_ATTRS * @type Array * @static */ UI_ATTRS: ['multiple'], prototype: { ELEMENT_TEMPLATE: '<select class="' + CSS_CELLEDITOR_ELEMENT + '"></select>', OPTION_TEMPLATE: '<option value="{value}">{label}</option>', /** * TODO. Wanna help? Please send a Pull Request. * * @method getElementsValue */ getElementsValue: function() { var instance = this; if (instance.get('multiple')) { return instance._getSelectedOptions().get('value'); } return instance.elements.get('value'); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _syncElementsFocus * @protected */ _syncElementsFocus: function() { var instance = this; instance.elements.focus(); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _uiSetMultiple * @param val * @protected */ _uiSetMultiple: function(val) { var instance = this; var elements = instance.elements; if (val) { elements.setAttribute('multiple', 'multiple'); } else { elements.removeAttribute('multiple'); } } } }); A.DropDownCellEditor = DropDownCellEditor; /** * CheckboxCellEditor class. * * @class A.CheckboxCellEditor * @extends A.BaseOptionsCellEditor * @param {Object} config Object literal specifying widget configuration * properties. * @constructor */ var CheckboxCellEditor = A.Component.create({ /** * Static property provides a string to identify the class. * * @property NAME * @type String * @static */ NAME: 'checkboxCellEditor', /** * Static property used to define the default attribute * configuration for the CheckboxCellEditor. * * @property ATTRS * @type Object * @static */ ATTRS: { /** * TODO. Wanna help? Please send a Pull Request. * * @attribute selectedAttrName * @default 'checked' * @type String */ selectedAttrName: { value: 'checked' } }, /** * Static property used to define which component it extends. * * @property EXTENDS * @type Object * @static */ EXTENDS: A.BaseOptionsCellEditor, prototype: { ELEMENT_TEMPLATE: '<div class="' + CSS_CELLEDITOR_ELEMENT + '"></div>', OPTION_TEMPLATE: '<input class="' + CSS_CELLEDITOR_OPTION + '" id="{id}" name="{name}" type="checkbox" value="{value}"/>', OPTION_WRAPPER: '<label class="checkbox" for="{id}"> {label}</label>', /** * TODO. Wanna help? Please send a Pull Request. * * @method getElementsValue */ getElementsValue: function() { var instance = this; return instance._getSelectedOptions().get('value'); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _syncElementsFocus * @protected */ _syncElementsFocus: function() { var instance = this; var options = instance.options; if (options && options.size()) { options.item(0).focus(); } }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _syncElementsName * @protected */ _syncElementsName: function() { var instance = this; var options = instance.options; if (options) { options.setAttribute('name', instance.get('elementName')); } } } }); A.CheckboxCellEditor = CheckboxCellEditor; /** * RadioCellEditor class. * * @class A.RadioCellEditor * @extends A.CheckboxCellEditor * @param {Object} config Object literal specifying widget configuration * properties. * @constructor */ var RadioCellEditor = A.Component.create({ /** * Static property provides a string to identify the class. * * @property NAME * @type String * @static */ NAME: 'radioCellEditor', /** * Static property used to define which component it extends. * * @property EXTENDS * @type Object * @static */ EXTENDS: A.CheckboxCellEditor, prototype: { OPTION_TEMPLATE: '<input class="field-input-choice" id="{id}" name="{name}" type="radio" value="{value}"/>', OPTION_WRAPPER: '<label class="radio" for="{id}"> {label}</label>', /** * TODO. Wanna help? Please send a Pull Request. * * @method getElementsValue */ getElementsValue: function() { var instance = this; return instance._getSelectedOptions().get('value')[0]; } } }); A.RadioCellEditor = RadioCellEditor; /** * DateCellEditor class. * * @class A.DateCellEditor * @extends A.BaseCellEditor * @param {Object} config Object literal specifying widget configuration * properties. * @constructor */ var DateCellEditor = A.Component.create({ /** * Static property provides a string to identify the class. * * @property NAME * @type String * @static */ NAME: 'dateCellEditor', /** * Static property used to define which component it extends. * * @property EXTENDS * @type Object * @static */ EXTENDS: A.BaseCellEditor, /** * Static property used to define the default attribute * configuration for the DateCellEditor. * * @property ATTRS * @type Object * @static */ ATTRS: { /** * TODO. Wanna help? Please send a Pull Request. * * @attribute bodyContent * @default '' * @type String */ bodyContent: { value: '' }, /** * TODO. Wanna help? Please send a Pull Request. * * @attribute calendar * @default null * @type Object */ calendar: { setter: '_setCalendar', validator: isObject, value: null }, /** * TODO. Wanna help? Please send a Pull Request. * * @attribute dateFormat * @default '%Y-%m-%d' * @type String */ dateFormat: { value: '%Y-%m-%d', validator: isString }, /** * TODO. Wanna help? Please send a Pull Request. * * @attribute inputFormatter * @type Function */ inputFormatter: { value: function(val) { var instance = this, values = []; AArray.each(val, function(date, index) { values.push(instance.formatDate(date).toString()); }); return values; } }, /** * TODO. Wanna help? Please send a Pull Request. * * @attribute outputFormatter * @type Function */ outputFormatter: { value: function(val) { var instance = this, values = []; AArray.each(val, function(date, index) { values.push(DataType.Date.parse(instance.get('dateFormat'), date)); }); return values; } } }, prototype: { ELEMENT_TEMPLATE: '<input class="' + CSS_CELLEDITOR_ELEMENT + '" type="hidden" />', /** * Construction logic executed during DateCellEditor instantiation. * Lifecycle. * * @method initializer * @protected */ initializer: function() { var instance = this; instance.after('calendar:dateClick', A.bind(instance._afterDateSelect, instance)); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method getElementsValue */ getElementsValue: function() { var instance = this; return instance.calendar.get('selectedDates'); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method formatDate * @param date */ formatDate: function(date) { var instance = this, mask = instance.get('dateFormat'), locale = instance.get('locale'); return DataType.Date.format(date, { format: mask, locale: locale }); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _afterDateSelect * @param event * @protected */ _afterDateSelect: function(event) { var instance = this, selectedDates = instance.calendar.get('selectedDates'); instance.elements.val(AArray.invoke(selectedDates, 'getTime').join(',')); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _afterRender * @protected */ _afterRender: function() { var instance = this; A.DateCellEditor.superclass._afterRender.apply(instance, arguments); instance.calendar = new A.Calendar( instance.get('calendar') ).render(instance.bodyNode); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _setCalendar * @param val * @protected */ _setCalendar: function(val) { var instance = this; return A.merge({ bubbleTargets: instance }, val ); }, /** * TODO. Wanna help? Please send a Pull Request. * * @method _uiSetValue * @param val * @protected */ _uiSetValue: function(val) { var instance = this, calendar = instance.calendar, formatedValue; if (calendar) { if (!isArray(val)) { val = [val]; } formatedValue = instance.formatValue(instance.get('outputFormatter'), val); calendar._clearSelection(); if (formatedValue[0]) { calendar.set('date', formatedValue[0]); calendar.selectDates(formatedValue); } else { calendar.set('date', new Date()); } } } } }); A.DateCellEditor = DateCellEditor; }, '2.5.0', { "requires": [ "datatable-base", "calendar", "overlay", "sortable", "aui-datatype", "aui-toolbar", "aui-form-validator", "aui-datatable-core" ], "skinnable": true });
"use strict"; bmApp.controller('AdminDeleteBookCtrl', function ($scope, $routeParams, $location, BookDataService) { var isbn = $routeParams.isbn; $scope.book = BookDataService.getBookByIsbn(isbn); $scope.deleteBook = function(isbn) { BookDataService.deleteBookByIsbn(isbn); goToAdminListView(); }; $scope.cancel = function() { goToAdminListView(); }; var goToAdminListView = function() { $location.path('/admin/books'); }; });
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @generated SignedSource<<ff40aed3600a349a81c8d336ef25c383>> * @flow * @lightSyntaxTransform * @nogrep */ /* eslint-disable */ 'use strict'; /*:: import type { ConcreteRequest, Query } from 'relay-runtime'; export type RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery$variables = {| userId: string, |}; export type RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery$data = {| +user: ?{| +id: string, +name: ?string, |}, |}; export type RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery = {| variables: RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery$variables, response: RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery$data, |}; */ var node/*: ConcreteRequest*/ = (function(){ var v0 = [ { "defaultValue": null, "kind": "LocalArgument", "name": "userId" } ], v1 = [ { "kind": "Variable", "name": "id", "variableName": "userId" } ], v2 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, v3 = { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }; return { "fragment": { "argumentDefinitions": (v0/*: any*/), "kind": "Fragment", "metadata": null, "name": "RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery", "selections": [ { "alias": "user", "args": (v1/*: any*/), "concreteType": null, "kind": "LinkedField", "name": "node", "plural": false, "selections": [ (v2/*: any*/), (v3/*: any*/) ], "storageKey": null } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": (v0/*: any*/), "kind": "Operation", "name": "RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery", "selections": [ { "alias": "user", "args": (v1/*: any*/), "concreteType": null, "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "__typename", "storageKey": null }, (v2/*: any*/), (v3/*: any*/) ], "storageKey": null } ] }, "params": { "cacheID": "0731919b754e27166d990aec021f2e80", "id": null, "metadata": { "relayTestingSelectionTypeInfo": { "user": { "enumValues": null, "nullable": true, "plural": false, "type": "Node" }, "user.__typename": { "enumValues": null, "nullable": false, "plural": false, "type": "String" }, "user.id": { "enumValues": null, "nullable": false, "plural": false, "type": "ID" }, "user.name": { "enumValues": null, "nullable": true, "plural": false, "type": "String" } } }, "name": "RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery", "operationKind": "query", "text": "query RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery(\n $userId: ID!\n) {\n user: node(id: $userId) {\n __typename\n id\n name\n }\n}\n" } }; })(); if (__DEV__) { (node/*: any*/).hash = "dc18b1545e059ab74a8a0209a0c58b60"; } module.exports = ((node/*: any*/)/*: Query< RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery$variables, RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery$data, >*/);
"use strict"; /*! * Copyright 2016 The ANTLR Project. All rights reserved. * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. */ 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 __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ATNSimulator = void 0; const ATNConfigSet_1 = require("./ATNConfigSet"); const DFAState_1 = require("../dfa/DFAState"); const Decorators_1 = require("../Decorators"); const PredictionContext_1 = require("./PredictionContext"); let ATNSimulator = class ATNSimulator { constructor(atn) { this.atn = atn; } static get ERROR() { if (!ATNSimulator._ERROR) { ATNSimulator._ERROR = new DFAState_1.DFAState(new ATNConfigSet_1.ATNConfigSet()); ATNSimulator._ERROR.stateNumber = PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY; } return ATNSimulator._ERROR; } /** * Clear the DFA cache used by the current instance. Since the DFA cache may * be shared by multiple ATN simulators, this method may affect the * performance (but not accuracy) of other parsers which are being used * concurrently. * * @ if the current instance does not * support clearing the DFA. * * @since 4.3 */ clearDFA() { this.atn.clearDFA(); } }; __decorate([ Decorators_1.NotNull ], ATNSimulator.prototype, "atn", void 0); __decorate([ Decorators_1.NotNull ], ATNSimulator, "ERROR", null); ATNSimulator = __decorate([ __param(0, Decorators_1.NotNull) ], ATNSimulator); exports.ATNSimulator = ATNSimulator; (function (ATNSimulator) { const RULE_VARIANT_DELIMITER = "$"; const RULE_LF_VARIANT_MARKER = "$lf$"; const RULE_NOLF_VARIANT_MARKER = "$nolf$"; })(ATNSimulator = exports.ATNSimulator || (exports.ATNSimulator = {})); exports.ATNSimulator = ATNSimulator; //# sourceMappingURL=ATNSimulator.js.map
"use strict"; var $ = require("jquery"); var Plugin = require("../modules/Plugin"); var dubtrackfm = Object.create(Plugin); dubtrackfm.init("dubtrackfm", "Dubtrack.fm", new RegExp("dubtrack\\.fm", "i")); dubtrackfm.scrape = function () { var info = {}; var player = $("#player-controller"); var track = $(".infoContainer .currentSong", player).text(); if (player.length > 0 && track.indexOf(" - ") >= 0) { var trackArr = track.split(" - "); var percent = $(".progressBg", player).width() / $(".infoContainer", player).outerWidth(); info.artist = trackArr[0]; info.title = trackArr[1]; info.percent = percent; } return info; }; module.exports = dubtrackfm;
(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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.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 app;app=angular.module("focusOn",[]);app.directive("focusOn",function(){return function(scope,elem,attr){return scope.$on("focusOn",function(e,name){if(name===attr.focusOn){return elem[0].focus()}})}});app.factory("focus",["$rootScope","$timeout",function($rootScope,$timeout){return function(name){return $timeout(function(){return $rootScope.$broadcast("focusOn",name)})}}])},{}]},{},[1]);
'use strict'; var HelloFileSystem = require('../../../src/node/HelloFileSystem'); describe("HelloWorld", function() { it("hello() should say hello from file when called", function() { expect(HelloFileSystem.hello()).toEqual("hello"); }); });
function foo() { console.log(foobar) } foo()
;(function(){ 'use strict'; //Setting up route angular .module('<%= slugifiedPluralName %>') .config( Configuration ); /* @inject */ function Configuration($stateProvider) { // <%= humanizedPluralName %> state routing $stateProvider .state('list<%= classifiedPluralName %>', { url: '/<%= slugifiedPluralName %>', templateUrl: 'app/modules/<%= slugifiedPluralName %>/views/list-<%= slugifiedPluralName %>.client.view.html', controller: '<%= classifiedPluralName %>Controller', resolve: { resolvedList: resolvedList } }) .state('create<%= classifiedSingularName %>', { url: '/<%= slugifiedPluralName %>/create', templateUrl: 'app/modules/<%= slugifiedPluralName %>/views/create-<%= slugifiedSingularName %>.client.view.html', controller: '<%= classifiedPluralName %>CreateController' }) .state('view<%= classifiedSingularName %>', { url: '/<%= slugifiedPluralName %>/:<%= camelizedSingularName %>Id', templateUrl: 'app/modules/<%= slugifiedPluralName %>/views/view-<%= slugifiedSingularName %>.client.view.html', controller: '<%= classifiedPluralName %>DetailController', resolve: { resolvedDetail: resolvedDetail } }) .state('edit<%= classifiedSingularName %>', { url: '/<%= slugifiedPluralName %>/:<%= camelizedSingularName %>Id/edit', templateUrl: 'app/modules/<%= slugifiedPluralName %>/views/edit-<%= slugifiedSingularName %>.client.view.html', controller: '<%= classifiedPluralName %>DetailController', resolve: { resolvedDetail: resolvedDetail } }); //////////////// function resolvedDetail($stateParams, <%= classifiedPluralName %>){<% if(restangular){ %> return <%= classifiedPluralName %>.one($stateParams.<%= camelizedSingularName %>Id).get()<% } %><% if(http){ %> return <%= classifiedPluralName %>.one($stateParams.<%= camelizedSingularName %>Id)<% } %> .then( function ( response ){<% if(restangular){ %> return response;<% } %><% if(http){ %> return response.data;<% } %> }) } function resolvedList(<%= classifiedPluralName %>){<% if(restangular){ %> return <%= classifiedPluralName %>.getList()<% } %><% if(http){ %> return <%= classifiedPluralName %>.all()<% } %> .then( function ( response ){<% if(restangular){ %> return response;<% } %><% if(http){ %> return response.data;<% } %> }) } } }).call(this);
/*! * jQuery JavaScript Library v1.9.0 -effects,-dimensions * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-2-7 */ (function( window, undefined ) { "use strict"; var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.9.0 -effects,-dimensions", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler and self cleanup method DOMContentLoaded = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); } else if ( document.readyState === "complete" ) { // we're here because readyState === "complete" in oldIE // which is good enough for us to call the dom ready! document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Control if a given callback is in the list has: function( fn ) { return jQuery.inArray( fn, list ) > -1; }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function() { var support, all, a, select, opt, input, fragment, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Support tests won't run in some limited or non-browser environments all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; if ( !all || !a || !all.length ) { return {}; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; support = { // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // IE strips leading whitespace when .innerHTML is used leadingWhitespace: div.firstChild.nodeType === 3, // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: a.getAttribute("href") === "/a", // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.5/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) checkOn: !!input.value, // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Tests for enctype support on a form (#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: document.compatMode === "CSS1Compat", // Will be defined later deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<9 try { delete div.test; } catch( e ) { support.deleteExpando = false; } // Check if we can trust getAttribute("value") input = document.createElement("input"); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment = document.createDocumentFragment(); fragment.appendChild( input ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php for ( i in { submit: true, change: true, focusin: true }) { div.setAttribute( eventName = "on" + i, "t" ); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild( container ).appendChild( div ); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== "undefined" ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 body.style.zoom = 1; } body.removeChild( container ); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData( elem, name, data, pvt /* Internal Use Only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt /* For internal use only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) } else if ( jQuery.support.deleteExpando || cache != cache.window ) { delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data, false ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name, false ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[i].name; if ( !name.indexOf( "data-" ) ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return jQuery.access( this, function( value ) { if ( value === undefined ) { // Try to fetch any internally stored data first return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; } this.each(function() { jQuery.data( this, key, value ); }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } hooks.cur = fn; if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } // Toggle whole class name } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val, self = jQuery(this); if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { // In IE9+, Flash objects don't have .getAttribute (#12945) // Support: IE9+ if ( typeof elem.getAttribute !== "undefined" ) { ret = elem.getAttribute( name ); } // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( rboolean.test( name ) ) { // Set corresponding property to false for boolean attributes // Also clear defaultChecked/defaultSelected (if appropriate) for IE<8 if ( !getSetAttribute && ruseDefault.test( name ) ) { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } else { elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { var // Use .prop to determine if this attribute is understood as boolean prop = jQuery.prop( elem, name ), // Fetch it accordingly attr = typeof prop === "boolean" && elem.getAttribute( name ), detail = typeof prop === "boolean" ? getSetInput && getSetAttribute ? attr != null : // oldIE fabricates an empty string for missing boolean attributes // and conflates checked/selected into attroperties ruseDefault.test( name ) ? elem[ jQuery.camelCase( "default-" + name ) ] : !!attr : // fetch an attribute node for properties not recognized as boolean elem.getAttributeNode( name ); return detail && detail.value !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; // fix oldIE value attroperty if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return jQuery.nodeName( elem, "input" ) ? // Ignore the value *property* by using defaultValue elem.defaultValue : ret && ret.specified ? ret.value : undefined; }, set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ? ret.value : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) return name === "value" || value === elem.getAttribute( name ) ? value : undefined; } }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret == null ? undefined : ret; } }); }); // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, // Don't attach events to noData or text/comment nodes (but allow plain objects) elemData = elem.nodeType !== 3 && elem.nodeType !== 8 && jQuery._data( elem ); if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = event.type || event, namespaces = event.namespace ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); event.isTrigger = true; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur != this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } } }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== document.activeElement && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === document.activeElement && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, beforeunload: { postDispatch: function( event ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === "undefined" ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function( window, undefined ) { var i, cachedruns, Expr, getText, isXML, compile, hasDuplicate, outermostContext, // Local document vars setDocument, document, docElem, documentIsXML, rbuggyQSA, rbuggyMatches, matches, contains, sortOrder, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, support = {}, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Array methods arr = [], pop = arr.pop, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rsibling = /[\x20\t\r\n\f]*[+~]/, rnative = /\{\s*\[native code\]\s*\}/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g, funescape = function( _, escaped ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint return high !== high ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Use a stripped-down slice if we can't use a native one try { slice.call( docElem.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; for ( ; (elem = this[i]); i++ ) { results.push( elem ); } return results; }; } /** * For feature detection * @param {Function} fn The function to test for native support */ function isNative( fn ) { return rnative.test( fn + "" ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var cache, keys = []; return (cache = function( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); }); } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return fn( div ); } catch (e) { return false; } finally { // release memory in IE div = null; } } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( !documentIsXML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } // QSA path if ( support.qsa && !rbuggyQSA.test(selector) ) { old = true; nid = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, slice.call( newContext.querySelectorAll( newSelector ), 0 ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsXML = isXML( doc ); // Check if getElementsByTagName("*") returns only elements support.tagNameNoComments = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if attributes should be retrieved by attribute nodes support.attributes = assert(function( div ) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }); // Check if getElementsByClassName can be trusted support.getByClassName = assert(function( div ) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { return false; } // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }); // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID support.getByName = assert(function( div ) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore( div, docElem.firstChild ); // Test var pass = doc.getElementsByName && // buggy browsers will return fewer than the correct 2 doc.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 doc.getElementsByName( expando + 0 ).length; support.getIdNotName = !doc.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }); // IE6/7 return modified attributes Expr.attrHandle = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }) ? {} : { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }; // ID find and filter if ( support.getIdNotName ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && !documentIsXML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && !documentIsXML ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.tagNameNoComments ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { for ( ; (elem = results[i]); i++ ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Name Expr.find["NAME"] = support.getByName && function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }; // Class Expr.find["CLASS"] = support.getByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) { return context.getElementsByClassName( className ); } }; // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21), // no need to also add to buggyMatches since matches checks buggyQSA // A support test would require too much code (would include document ready) rbuggyQSA = [ ":focus" ]; if ( (support.qsa = isNative(doc.querySelectorAll)) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Opera 10-12/IE8 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<input type='hidden' i=''/>"; if ( div.querySelectorAll("[i^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = new RegExp( rbuggyMatches.join("|") ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { var compare; if ( a === b ) { hasDuplicate = true; return 0; } if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) { if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) { if ( a === doc || contains( preferredDoc, a ) ) { return -1; } if ( b === doc || contains( preferredDoc, b ) ) { return 1; } return 0; } return compare & 4 ? -1 : 1; } return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return ( ~b.sourceIndex || MAX_NEGATIVE ) - ( contains( preferredDoc, a ) && ~a.sourceIndex || MAX_NEGATIVE ); // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). hasDuplicate = false; [0, 0].sort( sortOrder ); support.detectDuplicates = hasDuplicate; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyQSA always contains :focus, so no need for an existence check if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { var val; // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } if ( !documentIsXML ) { name = name.toLowerCase(); } if ( (val = Expr.attrHandle[ name ]) ) { return val( elem ); } if ( documentIsXML || support.attributes ) { return elem.getAttribute( name ); } return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ? name : val && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], i = 1, j = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; function siblingCheck( a, b ) { var cur = a && b && a.nextSibling; for ( ; cur; cur = cur.nextSibling ) { if ( cur === b ) { return -1; } } return a ? 1 : -1; } // Returns a function to use in pseudos for input types function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } // Returns a function to use in pseudos for buttons function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } // Returns a function to use in pseudos for positionals function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[4] ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( runescape, funescape ).toLowerCase(); return function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.substr( result.length - check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifider if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsXML ? elem.getAttribute("xml:lang") || elem.getAttribute("lang") : elem.lang) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push( { value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) } ); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push( { value: matched, type: type, matches: match } ); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && combinator.dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Nested matchers should use non-integer dirruns dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { for ( j = 0; (matcher = elementMatchers[j]); j++ ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements // `i` starts as a string, so matchedCount would equal "00" if there are no elements matchedCount += i; if ( bySet && i !== matchedCount ) { for ( j = 0; (matcher = setMatchers[j]); j++ ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && !documentIsXML && Expr.relative[ tokens[1].type ] ) { context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching for ( i = matchExpr["needsContext"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, slice.call( seed, 0 ) ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, documentIsXML, results, rsibling.test( selector ) ); return results; } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Easy API for creating new setFilters function setFilters() {} Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // Initialize with the default document setDocument(); // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret, self; if ( typeof selector !== "string" ) { self = this; return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < self.length; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } ret = []; for ( i = 0; i < this.length; i++ ) { jQuery.find( selector, this[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( jQuery.unique( ret ) ); ret.selector = ( this.selector ? this.selector + " " : "" ) + selector; return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true) ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". rneedsContext.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { cur = this[i]; while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } cur = cur.parentNode; } } return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( this.length > 1 && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { return this.domManip( arguments, false, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, false, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function( value ) { var isFunc = jQuery.isFunction( value ); // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( !isFunc && typeof value !== "string" ) { value = jQuery( value ).not( this ).detach(); } return this.domManip( [ value ], true, function( elem ) { var next = this.nextSibling, parent = this.parentNode; if ( parent && this.nodeType === 1 || this.nodeType === 11 ) { jQuery( this ).remove(); if ( next ) { next.parentNode.insertBefore( elem, next ); } else { parent.appendChild( elem ); } } }); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, table ? self.html() : undefined ); } self.domManip( args, table, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery.ajax({ url: node.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { var attr = elem.getAttributeNode("type"); elem.type = ( attr && attr.specified ) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, data, e; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== "undefined" ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( manipulation_rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, srcElements, node, i, clone, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var contains, elem, tag, tmp, wrap, tbody, j, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var data, id, elem, type, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== "undefined" ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } } }); var curCSS, getStyles, iframe, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var elem, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && elem.style.display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else if ( !values[ index ] && !isHidden( elem ) ) { jQuery._data( elem, "olddisplay", jQuery.css( elem, "display" ) ); } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { var bool = typeof state === "boolean"; return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Exclude the following css properties to add px cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { getStyles = function( elem ) { return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, _computed ) { var left, rs, rsLeft, computed = _computed || getStyles( elem ), ret = computed ? computed[ name ] : undefined, style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // If not modified if ( status === 304 ) { isSuccess = true; statusText = "notmodified"; // If we have data } else { isSuccess = ajaxConvert( s, response ); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); } }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { var conv, conv2, current, tmp, converters = {}, i = 0, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ]; // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } // Convert to each sequential dataType, tolerating list modification for ( ; (current = dataTypes[++i]); ) { // There's only work to do if current dataType is non-auto if ( current !== "*" ) { // Convert response if prev dataType is non-auto and differs from current if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split(" "); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.splice( i--, 0, current ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s["throws"] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } // Update prev for next iteration prev = current; } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function() { // Abort all pending requests var key; for ( key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( err ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; xml = xhr.responseXML; responseHeaders = xhr.getAllResponseHeaders(); // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== "undefined" ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.documentElement; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.documentElement; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Limit scope pollution from any deprecated API // (function() { // })(); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window );
export class kendoToStringValueConverter { toView(value, format, language) { return kendo.toString(value, format, language); } } export class kendoParseDateValueConverter { toView(value, format, language) { return kendo.parseDate(value, format, language); } } export class kendoParseIntValueConverter { toView(value, language) { return kendo.parseInt(value, language); } } export class kendoParseFloatValueConverter { toView(value, language) { return kendo.parseFloat(value, language); } } export class kendoParseColorValueConverter { toView(value) { return kendo.parseColor(value); } } export class kendoStringifyValueConverter { toView(obj) { return kendo.stringify(obj); } } export class kendoFormatValueConverter { toView(value, ...params) { params.unshift(value); return kendo.format.apply(this, params); } }
/** * @license * Video.js 7.6.5 <http://videojs.com/> * Copyright Brightcove, Inc. <https://www.brightcove.com/> * Available under Apache License Version 2.0 * <https://github.com/videojs/video.js/blob/master/LICENSE> * * Includes vtt.js <https://github.com/mozilla/vtt.js> * Available under Apache License Version 2.0 * <https://github.com/mozilla/vtt.js/blob/master/LICENSE> */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('global/window'), require('global/document')) : typeof define === 'function' && define.amd ? define(['global/window', 'global/document'], factory) : (global = global || self, global.videojs = factory(global.window, global.document)); }(this, function (window$1, document) { window$1 = window$1 && window$1.hasOwnProperty('default') ? window$1['default'] : window$1; document = document && document.hasOwnProperty('default') ? document['default'] : document; var version = "7.6.5"; /** * @file create-logger.js * @module create-logger */ var history = []; /** * Log messages to the console and history based on the type of message * * @private * @param {string} type * The name of the console method to use. * * @param {Array} args * The arguments to be passed to the matching console method. */ var LogByTypeFactory = function LogByTypeFactory(name, log) { return function (type, level, args) { var lvl = log.levels[level]; var lvlRegExp = new RegExp("^(" + lvl + ")$"); if (type !== 'log') { // Add the type to the front of the message when it's not "log". args.unshift(type.toUpperCase() + ':'); } // Add console prefix after adding to history. args.unshift(name + ':'); // Add a clone of the args at this point to history. if (history) { history.push([].concat(args)); } // If there's no console then don't try to output messages, but they will // still be stored in history. if (!window$1.console) { return; } // Was setting these once outside of this function, but containing them // in the function makes it easier to test cases where console doesn't exist // when the module is executed. var fn = window$1.console[type]; if (!fn && type === 'debug') { // Certain browsers don't have support for console.debug. For those, we // should default to the closest comparable log. fn = window$1.console.info || window$1.console.log; } // Bail out if there's no console or if this type is not allowed by the // current logging level. if (!fn || !lvl || !lvlRegExp.test(type)) { return; } fn[Array.isArray(args) ? 'apply' : 'call'](window$1.console, args); }; }; function createLogger(name) { // This is the private tracking variable for logging level. var level = 'info'; // the curried logByType bound to the specific log and history var logByType; /** * Logs plain debug messages. Similar to `console.log`. * * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149) * of our JSDoc template, we cannot properly document this as both a function * and a namespace, so its function signature is documented here. * * #### Arguments * ##### *args * Mixed[] * * Any combination of values that could be passed to `console.log()`. * * #### Return Value * * `undefined` * * @namespace * @param {Mixed[]} args * One or more messages or objects that should be logged. */ var log = function log() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } logByType('log', level, args); }; // This is the logByType helper that the logging methods below use logByType = LogByTypeFactory(name, log); /** * Create a new sublogger which chains the old name to the new name. * * For example, doing `videojs.log.createLogger('player')` and then using that logger will log the following: * ```js * mylogger('foo'); * // > VIDEOJS: player: foo * ``` * * @param {string} name * The name to add call the new logger * @return {Object} */ log.createLogger = function (subname) { return createLogger(name + ': ' + subname); }; /** * Enumeration of available logging levels, where the keys are the level names * and the values are `|`-separated strings containing logging methods allowed * in that logging level. These strings are used to create a regular expression * matching the function name being called. * * Levels provided by Video.js are: * * - `off`: Matches no calls. Any value that can be cast to `false` will have * this effect. The most restrictive. * - `all`: Matches only Video.js-provided functions (`debug`, `log`, * `log.warn`, and `log.error`). * - `debug`: Matches `log.debug`, `log`, `log.warn`, and `log.error` calls. * - `info` (default): Matches `log`, `log.warn`, and `log.error` calls. * - `warn`: Matches `log.warn` and `log.error` calls. * - `error`: Matches only `log.error` calls. * * @type {Object} */ log.levels = { all: 'debug|log|warn|error', off: '', debug: 'debug|log|warn|error', info: 'log|warn|error', warn: 'warn|error', error: 'error', DEFAULT: level }; /** * Get or set the current logging level. * * If a string matching a key from {@link module:log.levels} is provided, acts * as a setter. * * @param {string} [lvl] * Pass a valid level to set a new logging level. * * @return {string} * The current logging level. */ log.level = function (lvl) { if (typeof lvl === 'string') { if (!log.levels.hasOwnProperty(lvl)) { throw new Error("\"" + lvl + "\" in not a valid log level"); } level = lvl; } return level; }; /** * Returns an array containing everything that has been logged to the history. * * This array is a shallow clone of the internal history record. However, its * contents are _not_ cloned; so, mutating objects inside this array will * mutate them in history. * * @return {Array} */ log.history = function () { return history ? [].concat(history) : []; }; /** * Allows you to filter the history by the given logger name * * @param {string} fname * The name to filter by * * @return {Array} * The filtered list to return */ log.history.filter = function (fname) { return (history || []).filter(function (historyItem) { // if the first item in each historyItem includes `fname`, then it's a match return new RegExp(".*" + fname + ".*").test(historyItem[0]); }); }; /** * Clears the internal history tracking, but does not prevent further history * tracking. */ log.history.clear = function () { if (history) { history.length = 0; } }; /** * Disable history tracking if it is currently enabled. */ log.history.disable = function () { if (history !== null) { history.length = 0; history = null; } }; /** * Enable history tracking if it is currently disabled. */ log.history.enable = function () { if (history === null) { history = []; } }; /** * Logs error messages. Similar to `console.error`. * * @param {Mixed[]} args * One or more messages or objects that should be logged as an error */ log.error = function () { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return logByType('error', level, args); }; /** * Logs warning messages. Similar to `console.warn`. * * @param {Mixed[]} args * One or more messages or objects that should be logged as a warning. */ log.warn = function () { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return logByType('warn', level, args); }; /** * Logs debug messages. Similar to `console.debug`, but may also act as a comparable * log if `console.debug` is not available * * @param {Mixed[]} args * One or more messages or objects that should be logged as debug. */ log.debug = function () { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return logByType('debug', level, args); }; return log; } /** * @file log.js * @module log */ var log = createLogger('VIDEOJS'); var createLogger$1 = log.createLogger; /** * @file obj.js * @module obj */ /** * @callback obj:EachCallback * * @param {Mixed} value * The current key for the object that is being iterated over. * * @param {string} key * The current key-value for object that is being iterated over */ /** * @callback obj:ReduceCallback * * @param {Mixed} accum * The value that is accumulating over the reduce loop. * * @param {Mixed} value * The current key for the object that is being iterated over. * * @param {string} key * The current key-value for object that is being iterated over * * @return {Mixed} * The new accumulated value. */ var toString = Object.prototype.toString; /** * Get the keys of an Object * * @param {Object} * The Object to get the keys from * * @return {string[]} * An array of the keys from the object. Returns an empty array if the * object passed in was invalid or had no keys. * * @private */ var keys = function keys(object) { return isObject(object) ? Object.keys(object) : []; }; /** * Array-like iteration for objects. * * @param {Object} object * The object to iterate over * * @param {obj:EachCallback} fn * The callback function which is called for each key in the object. */ function each(object, fn) { keys(object).forEach(function (key) { return fn(object[key], key); }); } /** * Array-like reduce for objects. * * @param {Object} object * The Object that you want to reduce. * * @param {Function} fn * A callback function which is called for each key in the object. It * receives the accumulated value and the per-iteration value and key * as arguments. * * @param {Mixed} [initial = 0] * Starting value * * @return {Mixed} * The final accumulated value. */ function reduce(object, fn, initial) { if (initial === void 0) { initial = 0; } return keys(object).reduce(function (accum, key) { return fn(accum, object[key], key); }, initial); } /** * Object.assign-style object shallow merge/extend. * * @param {Object} target * @param {Object} ...sources * @return {Object} */ function assign(target) { for (var _len = arguments.length, sources = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { sources[_key - 1] = arguments[_key]; } if (Object.assign) { return Object.assign.apply(Object, [target].concat(sources)); } sources.forEach(function (source) { if (!source) { return; } each(source, function (value, key) { target[key] = value; }); }); return target; } /** * Returns whether a value is an object of any kind - including DOM nodes, * arrays, regular expressions, etc. Not functions, though. * * This avoids the gotcha where using `typeof` on a `null` value * results in `'object'`. * * @param {Object} value * @return {boolean} */ function isObject(value) { return !!value && typeof value === 'object'; } /** * Returns whether an object appears to be a "plain" object - that is, a * direct instance of `Object`. * * @param {Object} value * @return {boolean} */ function isPlain(value) { return isObject(value) && toString.call(value) === '[object Object]' && value.constructor === Object; } /** * @file computed-style.js * @module computed-style */ /** * A safe getComputedStyle. * * This is needed because in Firefox, if the player is loaded in an iframe with * `display:none`, then `getComputedStyle` returns `null`, so, we do a * null-check to make sure that the player doesn't break in these cases. * * @function * @param {Element} el * The element you want the computed style of * * @param {string} prop * The property name you want * * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397 */ function computedStyle(el, prop) { if (!el || !prop) { return ''; } if (typeof window$1.getComputedStyle === 'function') { var computedStyleValue = window$1.getComputedStyle(el); return computedStyleValue ? computedStyleValue.getPropertyValue(prop) || computedStyleValue[prop] : ''; } return ''; } /** * @file dom.js * @module dom */ /** * Detect if a value is a string with any non-whitespace characters. * * @private * @param {string} str * The string to check * * @return {boolean} * Will be `true` if the string is non-blank, `false` otherwise. * */ function isNonBlankString(str) { return typeof str === 'string' && /\S/.test(str); } /** * Throws an error if the passed string has whitespace. This is used by * class methods to be relatively consistent with the classList API. * * @private * @param {string} str * The string to check for whitespace. * * @throws {Error} * Throws an error if there is whitespace in the string. */ function throwIfWhitespace(str) { if (/\s/.test(str)) { throw new Error('class has illegal whitespace characters'); } } /** * Produce a regular expression for matching a className within an elements className. * * @private * @param {string} className * The className to generate the RegExp for. * * @return {RegExp} * The RegExp that will check for a specific `className` in an elements * className. */ function classRegExp(className) { return new RegExp('(^|\\s)' + className + '($|\\s)'); } /** * Whether the current DOM interface appears to be real (i.e. not simulated). * * @return {boolean} * Will be `true` if the DOM appears to be real, `false` otherwise. */ function isReal() { // Both document and window will never be undefined thanks to `global`. return document === window$1.document; } /** * Determines, via duck typing, whether or not a value is a DOM element. * * @param {Mixed} value * The value to check. * * @return {boolean} * Will be `true` if the value is a DOM element, `false` otherwise. */ function isEl(value) { return isObject(value) && value.nodeType === 1; } /** * Determines if the current DOM is embedded in an iframe. * * @return {boolean} * Will be `true` if the DOM is embedded in an iframe, `false` * otherwise. */ function isInFrame() { // We need a try/catch here because Safari will throw errors when attempting // to get either `parent` or `self` try { return window$1.parent !== window$1.self; } catch (x) { return true; } } /** * Creates functions to query the DOM using a given method. * * @private * @param {string} method * The method to create the query with. * * @return {Function} * The query method */ function createQuerier(method) { return function (selector, context) { if (!isNonBlankString(selector)) { return document[method](null); } if (isNonBlankString(context)) { context = document.querySelector(context); } var ctx = isEl(context) ? context : document; return ctx[method] && ctx[method](selector); }; } /** * Creates an element and applies properties, attributes, and inserts content. * * @param {string} [tagName='div'] * Name of tag to be created. * * @param {Object} [properties={}] * Element properties to be applied. * * @param {Object} [attributes={}] * Element attributes to be applied. * * @param {module:dom~ContentDescriptor} content * A content descriptor object. * * @return {Element} * The element that was created. */ function createEl(tagName, properties, attributes, content) { if (tagName === void 0) { tagName = 'div'; } if (properties === void 0) { properties = {}; } if (attributes === void 0) { attributes = {}; } var el = document.createElement(tagName); Object.getOwnPropertyNames(properties).forEach(function (propName) { var val = properties[propName]; // See #2176 // We originally were accepting both properties and attributes in the // same object, but that doesn't work so well. if (propName.indexOf('aria-') !== -1 || propName === 'role' || propName === 'type') { log.warn('Setting attributes in the second argument of createEl()\n' + 'has been deprecated. Use the third argument instead.\n' + ("createEl(type, properties, attributes). Attempting to set " + propName + " to " + val + ".")); el.setAttribute(propName, val); // Handle textContent since it's not supported everywhere and we have a // method for it. } else if (propName === 'textContent') { textContent(el, val); } else { el[propName] = val; } }); Object.getOwnPropertyNames(attributes).forEach(function (attrName) { el.setAttribute(attrName, attributes[attrName]); }); if (content) { appendContent(el, content); } return el; } /** * Injects text into an element, replacing any existing contents entirely. * * @param {Element} el * The element to add text content into * * @param {string} text * The text content to add. * * @return {Element} * The element with added text content. */ function textContent(el, text) { if (typeof el.textContent === 'undefined') { el.innerText = text; } else { el.textContent = text; } return el; } /** * Insert an element as the first child node of another * * @param {Element} child * Element to insert * * @param {Element} parent * Element to insert child into */ function prependTo(child, parent) { if (parent.firstChild) { parent.insertBefore(child, parent.firstChild); } else { parent.appendChild(child); } } /** * Check if an element has a class name. * * @param {Element} element * Element to check * * @param {string} classToCheck * Class name to check for * * @return {boolean} * Will be `true` if the element has a class, `false` otherwise. * * @throws {Error} * Throws an error if `classToCheck` has white space. */ function hasClass(element, classToCheck) { throwIfWhitespace(classToCheck); if (element.classList) { return element.classList.contains(classToCheck); } return classRegExp(classToCheck).test(element.className); } /** * Add a class name to an element. * * @param {Element} element * Element to add class name to. * * @param {string} classToAdd * Class name to add. * * @return {Element} * The DOM element with the added class name. */ function addClass(element, classToAdd) { if (element.classList) { element.classList.add(classToAdd); // Don't need to `throwIfWhitespace` here because `hasElClass` will do it // in the case of classList not being supported. } else if (!hasClass(element, classToAdd)) { element.className = (element.className + ' ' + classToAdd).trim(); } return element; } /** * Remove a class name from an element. * * @param {Element} element * Element to remove a class name from. * * @param {string} classToRemove * Class name to remove * * @return {Element} * The DOM element with class name removed. */ function removeClass(element, classToRemove) { if (element.classList) { element.classList.remove(classToRemove); } else { throwIfWhitespace(classToRemove); element.className = element.className.split(/\s+/).filter(function (c) { return c !== classToRemove; }).join(' '); } return element; } /** * The callback definition for toggleClass. * * @callback module:dom~PredicateCallback * @param {Element} element * The DOM element of the Component. * * @param {string} classToToggle * The `className` that wants to be toggled * * @return {boolean|undefined} * If `true` is returned, the `classToToggle` will be added to the * `element`. If `false`, the `classToToggle` will be removed from * the `element`. If `undefined`, the callback will be ignored. */ /** * Adds or removes a class name to/from an element depending on an optional * condition or the presence/absence of the class name. * * @param {Element} element * The element to toggle a class name on. * * @param {string} classToToggle * The class that should be toggled. * * @param {boolean|module:dom~PredicateCallback} [predicate] * See the return value for {@link module:dom~PredicateCallback} * * @return {Element} * The element with a class that has been toggled. */ function toggleClass(element, classToToggle, predicate) { // This CANNOT use `classList` internally because IE11 does not support the // second parameter to the `classList.toggle()` method! Which is fine because // `classList` will be used by the add/remove functions. var has = hasClass(element, classToToggle); if (typeof predicate === 'function') { predicate = predicate(element, classToToggle); } if (typeof predicate !== 'boolean') { predicate = !has; } // If the necessary class operation matches the current state of the // element, no action is required. if (predicate === has) { return; } if (predicate) { addClass(element, classToToggle); } else { removeClass(element, classToToggle); } return element; } /** * Apply attributes to an HTML element. * * @param {Element} el * Element to add attributes to. * * @param {Object} [attributes] * Attributes to be applied. */ function setAttributes(el, attributes) { Object.getOwnPropertyNames(attributes).forEach(function (attrName) { var attrValue = attributes[attrName]; if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) { el.removeAttribute(attrName); } else { el.setAttribute(attrName, attrValue === true ? '' : attrValue); } }); } /** * Get an element's attribute values, as defined on the HTML tag. * * Attributes are not the same as properties. They're defined on the tag * or with setAttribute. * * @param {Element} tag * Element from which to get tag attributes. * * @return {Object} * All attributes of the element. Boolean attributes will be `true` or * `false`, others will be strings. */ function getAttributes(tag) { var obj = {}; // known boolean attributes // we can check for matching boolean properties, but not all browsers // and not all tags know about these attributes, so, we still want to check them manually var knownBooleans = ',' + 'autoplay,controls,playsinline,loop,muted,default,defaultMuted' + ','; if (tag && tag.attributes && tag.attributes.length > 0) { var attrs = tag.attributes; for (var i = attrs.length - 1; i >= 0; i--) { var attrName = attrs[i].name; var attrVal = attrs[i].value; // check for known booleans // the matching element property will return a value for typeof if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(',' + attrName + ',') !== -1) { // the value of an included boolean attribute is typically an empty // string ('') which would equal false if we just check for a false value. // we also don't want support bad code like autoplay='false' attrVal = attrVal !== null ? true : false; } obj[attrName] = attrVal; } } return obj; } /** * Get the value of an element's attribute. * * @param {Element} el * A DOM element. * * @param {string} attribute * Attribute to get the value of. * * @return {string} * The value of the attribute. */ function getAttribute(el, attribute) { return el.getAttribute(attribute); } /** * Set the value of an element's attribute. * * @param {Element} el * A DOM element. * * @param {string} attribute * Attribute to set. * * @param {string} value * Value to set the attribute to. */ function setAttribute(el, attribute, value) { el.setAttribute(attribute, value); } /** * Remove an element's attribute. * * @param {Element} el * A DOM element. * * @param {string} attribute * Attribute to remove. */ function removeAttribute(el, attribute) { el.removeAttribute(attribute); } /** * Attempt to block the ability to select text. */ function blockTextSelection() { document.body.focus(); document.onselectstart = function () { return false; }; } /** * Turn off text selection blocking. */ function unblockTextSelection() { document.onselectstart = function () { return true; }; } /** * Identical to the native `getBoundingClientRect` function, but ensures that * the method is supported at all (it is in all browsers we claim to support) * and that the element is in the DOM before continuing. * * This wrapper function also shims properties which are not provided by some * older browsers (namely, IE8). * * Additionally, some browsers do not support adding properties to a * `ClientRect`/`DOMRect` object; so, we shallow-copy it with the standard * properties (except `x` and `y` which are not widely supported). This helps * avoid implementations where keys are non-enumerable. * * @param {Element} el * Element whose `ClientRect` we want to calculate. * * @return {Object|undefined} * Always returns a plain object - or `undefined` if it cannot. */ function getBoundingClientRect(el) { if (el && el.getBoundingClientRect && el.parentNode) { var rect = el.getBoundingClientRect(); var result = {}; ['bottom', 'height', 'left', 'right', 'top', 'width'].forEach(function (k) { if (rect[k] !== undefined) { result[k] = rect[k]; } }); if (!result.height) { result.height = parseFloat(computedStyle(el, 'height')); } if (!result.width) { result.width = parseFloat(computedStyle(el, 'width')); } return result; } } /** * Represents the position of a DOM element on the page. * * @typedef {Object} module:dom~Position * * @property {number} left * Pixels to the left. * * @property {number} top * Pixels from the top. */ /** * Get the position of an element in the DOM. * * Uses `getBoundingClientRect` technique from John Resig. * * @see http://ejohn.org/blog/getboundingclientrect-is-awesome/ * * @param {Element} el * Element from which to get offset. * * @return {module:dom~Position} * The position of the element that was passed in. */ function findPosition(el) { var box; if (el.getBoundingClientRect && el.parentNode) { box = el.getBoundingClientRect(); } if (!box) { return { left: 0, top: 0 }; } var docEl = document.documentElement; var body = document.body; var clientLeft = docEl.clientLeft || body.clientLeft || 0; var scrollLeft = window$1.pageXOffset || body.scrollLeft; var left = box.left + scrollLeft - clientLeft; var clientTop = docEl.clientTop || body.clientTop || 0; var scrollTop = window$1.pageYOffset || body.scrollTop; var top = box.top + scrollTop - clientTop; // Android sometimes returns slightly off decimal values, so need to round return { left: Math.round(left), top: Math.round(top) }; } /** * Represents x and y coordinates for a DOM element or mouse pointer. * * @typedef {Object} module:dom~Coordinates * * @property {number} x * x coordinate in pixels * * @property {number} y * y coordinate in pixels */ /** * Get the pointer position within an element. * * The base on the coordinates are the bottom left of the element. * * @param {Element} el * Element on which to get the pointer position on. * * @param {EventTarget~Event} event * Event object. * * @return {module:dom~Coordinates} * A coordinates object corresponding to the mouse position. * */ function getPointerPosition(el, event) { var position = {}; var box = findPosition(el); var boxW = el.offsetWidth; var boxH = el.offsetHeight; var boxY = box.top; var boxX = box.left; var pageY = event.pageY; var pageX = event.pageX; if (event.changedTouches) { pageX = event.changedTouches[0].pageX; pageY = event.changedTouches[0].pageY; } position.y = Math.max(0, Math.min(1, (boxY - pageY + boxH) / boxH)); position.x = Math.max(0, Math.min(1, (pageX - boxX) / boxW)); return position; } /** * Determines, via duck typing, whether or not a value is a text node. * * @param {Mixed} value * Check if this value is a text node. * * @return {boolean} * Will be `true` if the value is a text node, `false` otherwise. */ function isTextNode(value) { return isObject(value) && value.nodeType === 3; } /** * Empties the contents of an element. * * @param {Element} el * The element to empty children from * * @return {Element} * The element with no children */ function emptyEl(el) { while (el.firstChild) { el.removeChild(el.firstChild); } return el; } /** * This is a mixed value that describes content to be injected into the DOM * via some method. It can be of the following types: * * Type | Description * -----------|------------- * `string` | The value will be normalized into a text node. * `Element` | The value will be accepted as-is. * `TextNode` | The value will be accepted as-is. * `Array` | A one-dimensional array of strings, elements, text nodes, or functions. These functions should return a string, element, or text node (any other return value, like an array, will be ignored). * `Function` | A function, which is expected to return a string, element, text node, or array - any of the other possible values described above. This means that a content descriptor could be a function that returns an array of functions, but those second-level functions must return strings, elements, or text nodes. * * @typedef {string|Element|TextNode|Array|Function} module:dom~ContentDescriptor */ /** * Normalizes content for eventual insertion into the DOM. * * This allows a wide range of content definition methods, but helps protect * from falling into the trap of simply writing to `innerHTML`, which could * be an XSS concern. * * The content for an element can be passed in multiple types and * combinations, whose behavior is as follows: * * @param {module:dom~ContentDescriptor} content * A content descriptor value. * * @return {Array} * All of the content that was passed in, normalized to an array of * elements or text nodes. */ function normalizeContent(content) { // First, invoke content if it is a function. If it produces an array, // that needs to happen before normalization. if (typeof content === 'function') { content = content(); } // Next up, normalize to an array, so one or many items can be normalized, // filtered, and returned. return (Array.isArray(content) ? content : [content]).map(function (value) { // First, invoke value if it is a function to produce a new value, // which will be subsequently normalized to a Node of some kind. if (typeof value === 'function') { value = value(); } if (isEl(value) || isTextNode(value)) { return value; } if (typeof value === 'string' && /\S/.test(value)) { return document.createTextNode(value); } }).filter(function (value) { return value; }); } /** * Normalizes and appends content to an element. * * @param {Element} el * Element to append normalized content to. * * @param {module:dom~ContentDescriptor} content * A content descriptor value. * * @return {Element} * The element with appended normalized content. */ function appendContent(el, content) { normalizeContent(content).forEach(function (node) { return el.appendChild(node); }); return el; } /** * Normalizes and inserts content into an element; this is identical to * `appendContent()`, except it empties the element first. * * @param {Element} el * Element to insert normalized content into. * * @param {module:dom~ContentDescriptor} content * A content descriptor value. * * @return {Element} * The element with inserted normalized content. */ function insertContent(el, content) { return appendContent(emptyEl(el), content); } /** * Check if an event was a single left click. * * @param {EventTarget~Event} event * Event object. * * @return {boolean} * Will be `true` if a single left click, `false` otherwise. */ function isSingleLeftClick(event) { // Note: if you create something draggable, be sure to // call it on both `mousedown` and `mousemove` event, // otherwise `mousedown` should be enough for a button if (event.button === undefined && event.buttons === undefined) { // Why do we need `buttons` ? // Because, middle mouse sometimes have this: // e.button === 0 and e.buttons === 4 // Furthermore, we want to prevent combination click, something like // HOLD middlemouse then left click, that would be // e.button === 0, e.buttons === 5 // just `button` is not gonna work // Alright, then what this block does ? // this is for chrome `simulate mobile devices` // I want to support this as well return true; } if (event.button === 0 && event.buttons === undefined) { // Touch screen, sometimes on some specific device, `buttons` // doesn't have anything (safari on ios, blackberry...) return true; } // `mouseup` event on a single left click has // `button` and `buttons` equal to 0 if (event.type === 'mouseup' && event.button === 0 && event.buttons === 0) { return true; } if (event.button !== 0 || event.buttons !== 1) { // This is the reason we have those if else block above // if any special case we can catch and let it slide // we do it above, when get to here, this definitely // is-not-left-click return false; } return true; } /** * Finds a single DOM element matching `selector` within the optional * `context` of another DOM element (defaulting to `document`). * * @param {string} selector * A valid CSS selector, which will be passed to `querySelector`. * * @param {Element|String} [context=document] * A DOM element within which to query. Can also be a selector * string in which case the first matching element will be used * as context. If missing (or no element matches selector), falls * back to `document`. * * @return {Element|null} * The element that was found or null. */ var $ = createQuerier('querySelector'); /** * Finds a all DOM elements matching `selector` within the optional * `context` of another DOM element (defaulting to `document`). * * @param {string} selector * A valid CSS selector, which will be passed to `querySelectorAll`. * * @param {Element|String} [context=document] * A DOM element within which to query. Can also be a selector * string in which case the first matching element will be used * as context. If missing (or no element matches selector), falls * back to `document`. * * @return {NodeList} * A element list of elements that were found. Will be empty if none * were found. * */ var $$ = createQuerier('querySelectorAll'); var Dom = /*#__PURE__*/Object.freeze({ isReal: isReal, isEl: isEl, isInFrame: isInFrame, createEl: createEl, textContent: textContent, prependTo: prependTo, hasClass: hasClass, addClass: addClass, removeClass: removeClass, toggleClass: toggleClass, setAttributes: setAttributes, getAttributes: getAttributes, getAttribute: getAttribute, setAttribute: setAttribute, removeAttribute: removeAttribute, blockTextSelection: blockTextSelection, unblockTextSelection: unblockTextSelection, getBoundingClientRect: getBoundingClientRect, findPosition: findPosition, getPointerPosition: getPointerPosition, isTextNode: isTextNode, emptyEl: emptyEl, normalizeContent: normalizeContent, appendContent: appendContent, insertContent: insertContent, isSingleLeftClick: isSingleLeftClick, $: $, $$: $$ }); /** * @file setup.js - Functions for setting up a player without * user interaction based on the data-setup `attribute` of the video tag. * * @module setup */ var _windowLoaded = false; var videojs; /** * Set up any tags that have a data-setup `attribute` when the player is started. */ var autoSetup = function autoSetup() { // Protect against breakage in non-browser environments and check global autoSetup option. if (!isReal() || videojs.options.autoSetup === false) { return; } var vids = Array.prototype.slice.call(document.getElementsByTagName('video')); var audios = Array.prototype.slice.call(document.getElementsByTagName('audio')); var divs = Array.prototype.slice.call(document.getElementsByTagName('video-js')); var mediaEls = vids.concat(audios, divs); // Check if any media elements exist if (mediaEls && mediaEls.length > 0) { for (var i = 0, e = mediaEls.length; i < e; i++) { var mediaEl = mediaEls[i]; // Check if element exists, has getAttribute func. if (mediaEl && mediaEl.getAttribute) { // Make sure this player hasn't already been set up. if (mediaEl.player === undefined) { var options = mediaEl.getAttribute('data-setup'); // Check if data-setup attr exists. // We only auto-setup if they've added the data-setup attr. if (options !== null) { // Create new video.js instance. videojs(mediaEl); } } // If getAttribute isn't defined, we need to wait for the DOM. } else { autoSetupTimeout(1); break; } } // No videos were found, so keep looping unless page is finished loading. } else if (!_windowLoaded) { autoSetupTimeout(1); } }; /** * Wait until the page is loaded before running autoSetup. This will be called in * autoSetup if `hasLoaded` returns false. * * @param {number} wait * How long to wait in ms * * @param {module:videojs} [vjs] * The videojs library function */ function autoSetupTimeout(wait, vjs) { if (vjs) { videojs = vjs; } window$1.setTimeout(autoSetup, wait); } /** * Used to set the internal tracking of window loaded state to true. * * @private */ function setWindowLoaded() { _windowLoaded = true; window$1.removeEventListener('load', setWindowLoaded); } if (isReal()) { if (document.readyState === 'complete') { setWindowLoaded(); } else { /** * Listen for the load event on window, and set _windowLoaded to true. * * We use a standard event listener here to avoid incrementing the GUID * before any players are created. * * @listens load */ window$1.addEventListener('load', setWindowLoaded); } } /** * @file stylesheet.js * @module stylesheet */ /** * Create a DOM syle element given a className for it. * * @param {string} className * The className to add to the created style element. * * @return {Element} * The element that was created. */ var createStyleElement = function createStyleElement(className) { var style = document.createElement('style'); style.className = className; return style; }; /** * Add text to a DOM element. * * @param {Element} el * The Element to add text content to. * * @param {string} content * The text to add to the element. */ var setTextContent = function setTextContent(el, content) { if (el.styleSheet) { el.styleSheet.cssText = content; } else { el.textContent = content; } }; /** * @file dom-data.js * @module dom-data */ /** * Element Data Store. * * Allows for binding data to an element without putting it directly on the * element. Ex. Event listeners are stored here. * (also from jsninja.com, slightly modified and updated for closure compiler) * * @type {Object} * @private */ var DomData = new WeakMap(); /** * @file guid.js * @module guid */ // Default value for GUIDs. This allows us to reset the GUID counter in tests. // // The initial GUID is 3 because some users have come to rely on the first // default player ID ending up as `vjs_video_3`. // // See: https://github.com/videojs/video.js/pull/6216 var _initialGuid = 3; /** * Unique ID for an element or function * * @type {Number} */ var _guid = _initialGuid; /** * Get a unique auto-incrementing ID by number that has not been returned before. * * @return {number} * A new unique ID. */ function newGUID() { return _guid++; } /** * @file events.js. An Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/) * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible) * This should work very similarly to jQuery's events, however it's based off the book version which isn't as * robust as jquery's, so there's probably some differences. * * @file events.js * @module events */ /** * Clean up the listener cache and dispatchers * * @param {Element|Object} elem * Element to clean up * * @param {string} type * Type of event to clean up */ function _cleanUpEvents(elem, type) { if (!DomData.has(elem)) { return; } var data = DomData.get(elem); // Remove the events of a particular type if there are none left if (data.handlers[type].length === 0) { delete data.handlers[type]; // data.handlers[type] = null; // Setting to null was causing an error with data.handlers // Remove the meta-handler from the element if (elem.removeEventListener) { elem.removeEventListener(type, data.dispatcher, false); } else if (elem.detachEvent) { elem.detachEvent('on' + type, data.dispatcher); } } // Remove the events object if there are no types left if (Object.getOwnPropertyNames(data.handlers).length <= 0) { delete data.handlers; delete data.dispatcher; delete data.disabled; } // Finally remove the element data if there is no data left if (Object.getOwnPropertyNames(data).length === 0) { DomData["delete"](elem); } } /** * Loops through an array of event types and calls the requested method for each type. * * @param {Function} fn * The event method we want to use. * * @param {Element|Object} elem * Element or object to bind listeners to * * @param {string} type * Type of event to bind to. * * @param {EventTarget~EventListener} callback * Event listener. */ function _handleMultipleEvents(fn, elem, types, callback) { types.forEach(function (type) { // Call the event method for each one of the types fn(elem, type, callback); }); } /** * Fix a native event to have standard property values * * @param {Object} event * Event object to fix. * * @return {Object} * Fixed event object. */ function fixEvent(event) { function returnTrue() { return true; } function returnFalse() { return false; } // Test if fixing up is needed // Used to check if !event.stopPropagation instead of isPropagationStopped // But native events return true for stopPropagation, but don't have // other expected methods like isPropagationStopped. Seems to be a problem // with the Javascript Ninja code. So we're just overriding all events now. if (!event || !event.isPropagationStopped) { var old = event || window$1.event; event = {}; // Clone the old object so that we can modify the values event = {}; // IE8 Doesn't like when you mess with native event properties // Firefox returns false for event.hasOwnProperty('type') and other props // which makes copying more difficult. // TODO: Probably best to create a whitelist of event props for (var key in old) { // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation // and webkitMovementX/Y if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation' && key !== 'webkitMovementX' && key !== 'webkitMovementY') { // Chrome 32+ warns if you try to copy deprecated returnValue, but // we still want to if preventDefault isn't supported (IE8). if (!(key === 'returnValue' && old.preventDefault)) { event[key] = old[key]; } } } // The event occurred on this element if (!event.target) { event.target = event.srcElement || document; } // Handle which other element the event is related to if (!event.relatedTarget) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Stop the default browser action event.preventDefault = function () { if (old.preventDefault) { old.preventDefault(); } event.returnValue = false; old.returnValue = false; event.defaultPrevented = true; }; event.defaultPrevented = false; // Stop the event from bubbling event.stopPropagation = function () { if (old.stopPropagation) { old.stopPropagation(); } event.cancelBubble = true; old.cancelBubble = true; event.isPropagationStopped = returnTrue; }; event.isPropagationStopped = returnFalse; // Stop the event from bubbling and executing other handlers event.stopImmediatePropagation = function () { if (old.stopImmediatePropagation) { old.stopImmediatePropagation(); } event.isImmediatePropagationStopped = returnTrue; event.stopPropagation(); }; event.isImmediatePropagationStopped = returnFalse; // Handle mouse position if (event.clientX !== null && event.clientX !== undefined) { var doc = document.documentElement; var body = document.body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Handle key presses event.which = event.charCode || event.keyCode; // Fix button for mouse clicks: // 0 == left; 1 == middle; 2 == right if (event.button !== null && event.button !== undefined) { // The following is disabled because it does not pass videojs-standard // and... yikes. /* eslint-disable */ event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0; /* eslint-enable */ } } // Returns fixed-up instance return event; } /** * Whether passive event listeners are supported */ var _supportsPassive = false; (function () { try { var opts = Object.defineProperty({}, 'passive', { get: function get() { _supportsPassive = true; } }); window$1.addEventListener('test', null, opts); window$1.removeEventListener('test', null, opts); } catch (e) {// disregard } })(); /** * Touch events Chrome expects to be passive */ var passiveEvents = ['touchstart', 'touchmove']; /** * Add an event listener to element * It stores the handler function in a separate cache object * and adds a generic handler to the element's event, * along with a unique id (guid) to the element. * * @param {Element|Object} elem * Element or object to bind listeners to * * @param {string|string[]} type * Type of event to bind to. * * @param {EventTarget~EventListener} fn * Event listener. */ function on(elem, type, fn) { if (Array.isArray(type)) { return _handleMultipleEvents(on, elem, type, fn); } if (!DomData.has(elem)) { DomData.set(elem, {}); } var data = DomData.get(elem); // We need a place to store all our handler data if (!data.handlers) { data.handlers = {}; } if (!data.handlers[type]) { data.handlers[type] = []; } if (!fn.guid) { fn.guid = newGUID(); } data.handlers[type].push(fn); if (!data.dispatcher) { data.disabled = false; data.dispatcher = function (event, hash) { if (data.disabled) { return; } event = fixEvent(event); var handlers = data.handlers[event.type]; if (handlers) { // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off. var handlersCopy = handlers.slice(0); for (var m = 0, n = handlersCopy.length; m < n; m++) { if (event.isImmediatePropagationStopped()) { break; } else { try { handlersCopy[m].call(elem, event, hash); } catch (e) { log.error(e); } } } } }; } if (data.handlers[type].length === 1) { if (elem.addEventListener) { var options = false; if (_supportsPassive && passiveEvents.indexOf(type) > -1) { options = { passive: true }; } elem.addEventListener(type, data.dispatcher, options); } else if (elem.attachEvent) { elem.attachEvent('on' + type, data.dispatcher); } } } /** * Removes event listeners from an element * * @param {Element|Object} elem * Object to remove listeners from. * * @param {string|string[]} [type] * Type of listener to remove. Don't include to remove all events from element. * * @param {EventTarget~EventListener} [fn] * Specific listener to remove. Don't include to remove listeners for an event * type. */ function off(elem, type, fn) { // Don't want to add a cache object through getElData if not needed if (!DomData.has(elem)) { return; } var data = DomData.get(elem); // If no events exist, nothing to unbind if (!data.handlers) { return; } if (Array.isArray(type)) { return _handleMultipleEvents(off, elem, type, fn); } // Utility function var removeType = function removeType(el, t) { data.handlers[t] = []; _cleanUpEvents(el, t); }; // Are we removing all bound events? if (type === undefined) { for (var t in data.handlers) { if (Object.prototype.hasOwnProperty.call(data.handlers || {}, t)) { removeType(elem, t); } } return; } var handlers = data.handlers[type]; // If no handlers exist, nothing to unbind if (!handlers) { return; } // If no listener was provided, remove all listeners for type if (!fn) { removeType(elem, type); return; } // We're only removing a single handler if (fn.guid) { for (var n = 0; n < handlers.length; n++) { if (handlers[n].guid === fn.guid) { handlers.splice(n--, 1); } } } _cleanUpEvents(elem, type); } /** * Trigger an event for an element * * @param {Element|Object} elem * Element to trigger an event on * * @param {EventTarget~Event|string} event * A string (the type) or an event object with a type attribute * * @param {Object} [hash] * data hash to pass along with the event * * @return {boolean|undefined} * Returns the opposite of `defaultPrevented` if default was * prevented. Otherwise, returns `undefined` */ function trigger(elem, event, hash) { // Fetches element data and a reference to the parent (for bubbling). // Don't want to add a data object to cache for every parent, // so checking hasElData first. var elemData = DomData.has(elem) ? DomData.get(elem) : {}; var parent = elem.parentNode || elem.ownerDocument; // type = event.type || event, // handler; // If an event name was passed as a string, creates an event out of it if (typeof event === 'string') { event = { type: event, target: elem }; } else if (!event.target) { event.target = elem; } // Normalizes the event properties. event = fixEvent(event); // If the passed element has a dispatcher, executes the established handlers. if (elemData.dispatcher) { elemData.dispatcher.call(elem, event, hash); } // Unless explicitly stopped or the event does not bubble (e.g. media events) // recursively calls this function to bubble the event up the DOM. if (parent && !event.isPropagationStopped() && event.bubbles === true) { trigger.call(null, parent, event, hash); // If at the top of the DOM, triggers the default action unless disabled. } else if (!parent && !event.defaultPrevented && event.target && event.target[event.type]) { if (!DomData.has(event.target)) { DomData.set(event.target, {}); } var targetData = DomData.get(event.target); // Checks if the target has a default action for this event. if (event.target[event.type]) { // Temporarily disables event dispatching on the target as we have already executed the handler. targetData.disabled = true; // Executes the default action. if (typeof event.target[event.type] === 'function') { event.target[event.type](); } // Re-enables event dispatching. targetData.disabled = false; } } // Inform the triggerer if the default was prevented by returning false return !event.defaultPrevented; } /** * Trigger a listener only once for an event. * * @param {Element|Object} elem * Element or object to bind to. * * @param {string|string[]} type * Name/type of event * * @param {Event~EventListener} fn * Event listener function */ function one(elem, type, fn) { if (Array.isArray(type)) { return _handleMultipleEvents(one, elem, type, fn); } var func = function func() { off(elem, type, func); fn.apply(this, arguments); }; // copy the guid to the new function so it can removed using the original function's ID func.guid = fn.guid = fn.guid || newGUID(); on(elem, type, func); } /** * Trigger a listener only once and then turn if off for all * configured events * * @param {Element|Object} elem * Element or object to bind to. * * @param {string|string[]} type * Name/type of event * * @param {Event~EventListener} fn * Event listener function */ function any(elem, type, fn) { var func = function func() { off(elem, type, func); fn.apply(this, arguments); }; // copy the guid to the new function so it can removed using the original function's ID func.guid = fn.guid = fn.guid || newGUID(); // multiple ons, but one off for everything on(elem, type, func); } var Events = /*#__PURE__*/Object.freeze({ fixEvent: fixEvent, on: on, off: off, trigger: trigger, one: one, any: any }); /** * @file fn.js * @module fn */ var UPDATE_REFRESH_INTERVAL = 30; /** * Bind (a.k.a proxy or context). A simple method for changing the context of * a function. * * It also stores a unique id on the function so it can be easily removed from * events. * * @function * @param {Mixed} context * The object to bind as scope. * * @param {Function} fn * The function to be bound to a scope. * * @param {number} [uid] * An optional unique ID for the function to be set * * @return {Function} * The new function that will be bound into the context given */ var bind = function bind(context, fn, uid) { // Make sure the function has a unique ID if (!fn.guid) { fn.guid = newGUID(); } // Create the new function that changes the context var bound = fn.bind(context); // Allow for the ability to individualize this function // Needed in the case where multiple objects might share the same prototype // IF both items add an event listener with the same function, then you try to remove just one // it will remove both because they both have the same guid. // when using this, you need to use the bind method when you remove the listener as well. // currently used in text tracks bound.guid = uid ? uid + '_' + fn.guid : fn.guid; return bound; }; /** * Wraps the given function, `fn`, with a new function that only invokes `fn` * at most once per every `wait` milliseconds. * * @function * @param {Function} fn * The function to be throttled. * * @param {number} wait * The number of milliseconds by which to throttle. * * @return {Function} */ var throttle = function throttle(fn, wait) { var last = window$1.performance.now(); var throttled = function throttled() { var now = window$1.performance.now(); if (now - last >= wait) { fn.apply(void 0, arguments); last = now; } }; return throttled; }; /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. * * Inspired by lodash and underscore implementations. * * @function * @param {Function} func * The function to wrap with debounce behavior. * * @param {number} wait * The number of milliseconds to wait after the last invocation. * * @param {boolean} [immediate] * Whether or not to invoke the function immediately upon creation. * * @param {Object} [context=window] * The "context" in which the debounced function should debounce. For * example, if this function should be tied to a Video.js player, * the player can be passed here. Alternatively, defaults to the * global `window` object. * * @return {Function} * A debounced function. */ var debounce = function debounce(func, wait, immediate, context) { if (context === void 0) { context = window$1; } var timeout; var cancel = function cancel() { context.clearTimeout(timeout); timeout = null; }; /* eslint-disable consistent-this */ var debounced = function debounced() { var self = this; var args = arguments; var _later = function later() { timeout = null; _later = null; if (!immediate) { func.apply(self, args); } }; if (!timeout && immediate) { func.apply(self, args); } context.clearTimeout(timeout); timeout = context.setTimeout(_later, wait); }; /* eslint-enable consistent-this */ debounced.cancel = cancel; return debounced; }; /** * @file src/js/event-target.js */ /** * `EventTarget` is a class that can have the same API as the DOM `EventTarget`. It * adds shorthand functions that wrap around lengthy functions. For example: * the `on` function is a wrapper around `addEventListener`. * * @see [EventTarget Spec]{@link https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget} * @class EventTarget */ var EventTarget = function EventTarget() {}; /** * A Custom DOM event. * * @typedef {Object} EventTarget~Event * @see [Properties]{@link https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent} */ /** * All event listeners should follow the following format. * * @callback EventTarget~EventListener * @this {EventTarget} * * @param {EventTarget~Event} event * the event that triggered this function * * @param {Object} [hash] * hash of data sent during the event */ /** * An object containing event names as keys and booleans as values. * * > NOTE: If an event name is set to a true value here {@link EventTarget#trigger} * will have extra functionality. See that function for more information. * * @property EventTarget.prototype.allowedEvents_ * @private */ EventTarget.prototype.allowedEvents_ = {}; /** * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a * function that will get called when an event with a certain name gets triggered. * * @param {string|string[]} type * An event name or an array of event names. * * @param {EventTarget~EventListener} fn * The function to call with `EventTarget`s */ EventTarget.prototype.on = function (type, fn) { // Remove the addEventListener alias before calling Events.on // so we don't get into an infinite type loop var ael = this.addEventListener; this.addEventListener = function () {}; on(this, type, fn); this.addEventListener = ael; }; /** * An alias of {@link EventTarget#on}. Allows `EventTarget` to mimic * the standard DOM API. * * @function * @see {@link EventTarget#on} */ EventTarget.prototype.addEventListener = EventTarget.prototype.on; /** * Removes an `event listener` for a specific event from an instance of `EventTarget`. * This makes it so that the `event listener` will no longer get called when the * named event happens. * * @param {string|string[]} type * An event name or an array of event names. * * @param {EventTarget~EventListener} fn * The function to remove. */ EventTarget.prototype.off = function (type, fn) { off(this, type, fn); }; /** * An alias of {@link EventTarget#off}. Allows `EventTarget` to mimic * the standard DOM API. * * @function * @see {@link EventTarget#off} */ EventTarget.prototype.removeEventListener = EventTarget.prototype.off; /** * This function will add an `event listener` that gets triggered only once. After the * first trigger it will get removed. This is like adding an `event listener` * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself. * * @param {string|string[]} type * An event name or an array of event names. * * @param {EventTarget~EventListener} fn * The function to be called once for each event name. */ EventTarget.prototype.one = function (type, fn) { // Remove the addEventListener aliasing Events.on // so we don't get into an infinite type loop var ael = this.addEventListener; this.addEventListener = function () {}; one(this, type, fn); this.addEventListener = ael; }; EventTarget.prototype.any = function (type, fn) { // Remove the addEventListener aliasing Events.on // so we don't get into an infinite type loop var ael = this.addEventListener; this.addEventListener = function () {}; any(this, type, fn); this.addEventListener = ael; }; /** * This function causes an event to happen. This will then cause any `event listeners` * that are waiting for that event, to get called. If there are no `event listeners` * for an event then nothing will happen. * * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`. * Trigger will also call the `on` + `uppercaseEventName` function. * * Example: * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call * `onClick` if it exists. * * @param {string|EventTarget~Event|Object} event * The name of the event, an `Event`, or an object with a key of type set to * an event name. */ EventTarget.prototype.trigger = function (event) { var type = event.type || event; // deprecation // In a future version we should default target to `this` // similar to how we default the target to `elem` in // `Events.trigger`. Right now the default `target` will be // `document` due to the `Event.fixEvent` call. if (typeof event === 'string') { event = { type: type }; } event = fixEvent(event); if (this.allowedEvents_[type] && this['on' + type]) { this['on' + type](event); } trigger(this, event); }; /** * An alias of {@link EventTarget#trigger}. Allows `EventTarget` to mimic * the standard DOM API. * * @function * @see {@link EventTarget#trigger} */ EventTarget.prototype.dispatchEvent = EventTarget.prototype.trigger; var EVENT_MAP; EventTarget.prototype.queueTrigger = function (event) { var _this = this; // only set up EVENT_MAP if it'll be used if (!EVENT_MAP) { EVENT_MAP = new Map(); } var type = event.type || event; var map = EVENT_MAP.get(this); if (!map) { map = new Map(); EVENT_MAP.set(this, map); } var oldTimeout = map.get(type); map["delete"](type); window$1.clearTimeout(oldTimeout); var timeout = window$1.setTimeout(function () { // if we cleared out all timeouts for the current target, delete its map if (map.size === 0) { map = null; EVENT_MAP["delete"](_this); } _this.trigger(event); }, 0); map.set(type, timeout); }; /** * @file mixins/evented.js * @module evented */ /** * Returns whether or not an object has had the evented mixin applied. * * @param {Object} object * An object to test. * * @return {boolean} * Whether or not the object appears to be evented. */ var isEvented = function isEvented(object) { return object instanceof EventTarget || !!object.eventBusEl_ && ['on', 'one', 'off', 'trigger'].every(function (k) { return typeof object[k] === 'function'; }); }; /** * Adds a callback to run after the evented mixin applied. * * @param {Object} object * An object to Add * @param {Function} callback * The callback to run. */ var addEventedCallback = function addEventedCallback(target, callback) { if (isEvented(target)) { callback(); } else { if (!target.eventedCallbacks) { target.eventedCallbacks = []; } target.eventedCallbacks.push(callback); } }; /** * Whether a value is a valid event type - non-empty string or array. * * @private * @param {string|Array} type * The type value to test. * * @return {boolean} * Whether or not the type is a valid event type. */ var isValidEventType = function isValidEventType(type) { return (// The regex here verifies that the `type` contains at least one non- // whitespace character. typeof type === 'string' && /\S/.test(type) || Array.isArray(type) && !!type.length ); }; /** * Validates a value to determine if it is a valid event target. Throws if not. * * @private * @throws {Error} * If the target does not appear to be a valid event target. * * @param {Object} target * The object to test. */ var validateTarget = function validateTarget(target) { if (!target.nodeName && !isEvented(target)) { throw new Error('Invalid target; must be a DOM node or evented object.'); } }; /** * Validates a value to determine if it is a valid event target. Throws if not. * * @private * @throws {Error} * If the type does not appear to be a valid event type. * * @param {string|Array} type * The type to test. */ var validateEventType = function validateEventType(type) { if (!isValidEventType(type)) { throw new Error('Invalid event type; must be a non-empty string or array.'); } }; /** * Validates a value to determine if it is a valid listener. Throws if not. * * @private * @throws {Error} * If the listener is not a function. * * @param {Function} listener * The listener to test. */ var validateListener = function validateListener(listener) { if (typeof listener !== 'function') { throw new Error('Invalid listener; must be a function.'); } }; /** * Takes an array of arguments given to `on()` or `one()`, validates them, and * normalizes them into an object. * * @private * @param {Object} self * The evented object on which `on()` or `one()` was called. This * object will be bound as the `this` value for the listener. * * @param {Array} args * An array of arguments passed to `on()` or `one()`. * * @return {Object} * An object containing useful values for `on()` or `one()` calls. */ var normalizeListenArgs = function normalizeListenArgs(self, args) { // If the number of arguments is less than 3, the target is always the // evented object itself. var isTargetingSelf = args.length < 3 || args[0] === self || args[0] === self.eventBusEl_; var target; var type; var listener; if (isTargetingSelf) { target = self.eventBusEl_; // Deal with cases where we got 3 arguments, but we are still listening to // the evented object itself. if (args.length >= 3) { args.shift(); } type = args[0]; listener = args[1]; } else { target = args[0]; type = args[1]; listener = args[2]; } validateTarget(target); validateEventType(type); validateListener(listener); listener = bind(self, listener); return { isTargetingSelf: isTargetingSelf, target: target, type: type, listener: listener }; }; /** * Adds the listener to the event type(s) on the target, normalizing for * the type of target. * * @private * @param {Element|Object} target * A DOM node or evented object. * * @param {string} method * The event binding method to use ("on" or "one"). * * @param {string|Array} type * One or more event type(s). * * @param {Function} listener * A listener function. */ var listen = function listen(target, method, type, listener) { validateTarget(target); if (target.nodeName) { Events[method](target, type, listener); } else { target[method](type, listener); } }; /** * Contains methods that provide event capabilities to an object which is passed * to {@link module:evented|evented}. * * @mixin EventedMixin */ var EventedMixin = { /** * Add a listener to an event (or events) on this object or another evented * object. * * @param {string|Array|Element|Object} targetOrType * If this is a string or array, it represents the event type(s) * that will trigger the listener. * * Another evented object can be passed here instead, which will * cause the listener to listen for events on _that_ object. * * In either case, the listener's `this` value will be bound to * this object. * * @param {string|Array|Function} typeOrListener * If the first argument was a string or array, this should be the * listener function. Otherwise, this is a string or array of event * type(s). * * @param {Function} [listener] * If the first argument was another evented object, this will be * the listener function. */ on: function on() { var _this = this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var _normalizeListenArgs = normalizeListenArgs(this, args), isTargetingSelf = _normalizeListenArgs.isTargetingSelf, target = _normalizeListenArgs.target, type = _normalizeListenArgs.type, listener = _normalizeListenArgs.listener; listen(target, 'on', type, listener); // If this object is listening to another evented object. if (!isTargetingSelf) { // If this object is disposed, remove the listener. var removeListenerOnDispose = function removeListenerOnDispose() { return _this.off(target, type, listener); }; // Use the same function ID as the listener so we can remove it later it // using the ID of the original listener. removeListenerOnDispose.guid = listener.guid; // Add a listener to the target's dispose event as well. This ensures // that if the target is disposed BEFORE this object, we remove the // removal listener that was just added. Otherwise, we create a memory leak. var removeRemoverOnTargetDispose = function removeRemoverOnTargetDispose() { return _this.off('dispose', removeListenerOnDispose); }; // Use the same function ID as the listener so we can remove it later // it using the ID of the original listener. removeRemoverOnTargetDispose.guid = listener.guid; listen(this, 'on', 'dispose', removeListenerOnDispose); listen(target, 'on', 'dispose', removeRemoverOnTargetDispose); } }, /** * Add a listener to an event (or events) on this object or another evented * object. The listener will be called once per event and then removed. * * @param {string|Array|Element|Object} targetOrType * If this is a string or array, it represents the event type(s) * that will trigger the listener. * * Another evented object can be passed here instead, which will * cause the listener to listen for events on _that_ object. * * In either case, the listener's `this` value will be bound to * this object. * * @param {string|Array|Function} typeOrListener * If the first argument was a string or array, this should be the * listener function. Otherwise, this is a string or array of event * type(s). * * @param {Function} [listener] * If the first argument was another evented object, this will be * the listener function. */ one: function one() { var _this2 = this; for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } var _normalizeListenArgs2 = normalizeListenArgs(this, args), isTargetingSelf = _normalizeListenArgs2.isTargetingSelf, target = _normalizeListenArgs2.target, type = _normalizeListenArgs2.type, listener = _normalizeListenArgs2.listener; // Targeting this evented object. if (isTargetingSelf) { listen(target, 'one', type, listener); // Targeting another evented object. } else { // TODO: This wrapper is incorrect! It should only // remove the wrapper for the event type that called it. // Instead all listners are removed on the first trigger! // see https://github.com/videojs/video.js/issues/5962 var wrapper = function wrapper() { _this2.off(target, type, wrapper); for (var _len3 = arguments.length, largs = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { largs[_key3] = arguments[_key3]; } listener.apply(null, largs); }; // Use the same function ID as the listener so we can remove it later // it using the ID of the original listener. wrapper.guid = listener.guid; listen(target, 'one', type, wrapper); } }, /** * Add a listener to an event (or events) on this object or another evented * object. The listener will only be called once for the first event that is triggered * then removed. * * @param {string|Array|Element|Object} targetOrType * If this is a string or array, it represents the event type(s) * that will trigger the listener. * * Another evented object can be passed here instead, which will * cause the listener to listen for events on _that_ object. * * In either case, the listener's `this` value will be bound to * this object. * * @param {string|Array|Function} typeOrListener * If the first argument was a string or array, this should be the * listener function. Otherwise, this is a string or array of event * type(s). * * @param {Function} [listener] * If the first argument was another evented object, this will be * the listener function. */ any: function any() { var _this3 = this; for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } var _normalizeListenArgs3 = normalizeListenArgs(this, args), isTargetingSelf = _normalizeListenArgs3.isTargetingSelf, target = _normalizeListenArgs3.target, type = _normalizeListenArgs3.type, listener = _normalizeListenArgs3.listener; // Targeting this evented object. if (isTargetingSelf) { listen(target, 'any', type, listener); // Targeting another evented object. } else { var wrapper = function wrapper() { _this3.off(target, type, wrapper); for (var _len5 = arguments.length, largs = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { largs[_key5] = arguments[_key5]; } listener.apply(null, largs); }; // Use the same function ID as the listener so we can remove it later // it using the ID of the original listener. wrapper.guid = listener.guid; listen(target, 'any', type, wrapper); } }, /** * Removes listener(s) from event(s) on an evented object. * * @param {string|Array|Element|Object} [targetOrType] * If this is a string or array, it represents the event type(s). * * Another evented object can be passed here instead, in which case * ALL 3 arguments are _required_. * * @param {string|Array|Function} [typeOrListener] * If the first argument was a string or array, this may be the * listener function. Otherwise, this is a string or array of event * type(s). * * @param {Function} [listener] * If the first argument was another evented object, this will be * the listener function; otherwise, _all_ listeners bound to the * event type(s) will be removed. */ off: function off$1(targetOrType, typeOrListener, listener) { // Targeting this evented object. if (!targetOrType || isValidEventType(targetOrType)) { off(this.eventBusEl_, targetOrType, typeOrListener); // Targeting another evented object. } else { var target = targetOrType; var type = typeOrListener; // Fail fast and in a meaningful way! validateTarget(target); validateEventType(type); validateListener(listener); // Ensure there's at least a guid, even if the function hasn't been used listener = bind(this, listener); // Remove the dispose listener on this evented object, which was given // the same guid as the event listener in on(). this.off('dispose', listener); if (target.nodeName) { off(target, type, listener); off(target, 'dispose', listener); } else if (isEvented(target)) { target.off(type, listener); target.off('dispose', listener); } } }, /** * Fire an event on this evented object, causing its listeners to be called. * * @param {string|Object} event * An event type or an object with a type property. * * @param {Object} [hash] * An additional object to pass along to listeners. * * @return {boolean} * Whether or not the default behavior was prevented. */ trigger: function trigger$1(event, hash) { return trigger(this.eventBusEl_, event, hash); } }; /** * Applies {@link module:evented~EventedMixin|EventedMixin} to a target object. * * @param {Object} target * The object to which to add event methods. * * @param {Object} [options={}] * Options for customizing the mixin behavior. * * @param {string} [options.eventBusKey] * By default, adds a `eventBusEl_` DOM element to the target object, * which is used as an event bus. If the target object already has a * DOM element that should be used, pass its key here. * * @return {Object} * The target object. */ function evented(target, options) { if (options === void 0) { options = {}; } var _options = options, eventBusKey = _options.eventBusKey; // Set or create the eventBusEl_. if (eventBusKey) { if (!target[eventBusKey].nodeName) { throw new Error("The eventBusKey \"" + eventBusKey + "\" does not refer to an element."); } target.eventBusEl_ = target[eventBusKey]; } else { target.eventBusEl_ = createEl('span', { className: 'vjs-event-bus' }); } assign(target, EventedMixin); if (target.eventedCallbacks) { target.eventedCallbacks.forEach(function (callback) { callback(); }); } // When any evented object is disposed, it removes all its listeners. target.on('dispose', function () { target.off(); window$1.setTimeout(function () { target.eventBusEl_ = null; }, 0); }); return target; } /** * @file mixins/stateful.js * @module stateful */ /** * Contains methods that provide statefulness to an object which is passed * to {@link module:stateful}. * * @mixin StatefulMixin */ var StatefulMixin = { /** * A hash containing arbitrary keys and values representing the state of * the object. * * @type {Object} */ state: {}, /** * Set the state of an object by mutating its * {@link module:stateful~StatefulMixin.state|state} object in place. * * @fires module:stateful~StatefulMixin#statechanged * @param {Object|Function} stateUpdates * A new set of properties to shallow-merge into the plugin state. * Can be a plain object or a function returning a plain object. * * @return {Object|undefined} * An object containing changes that occurred. If no changes * occurred, returns `undefined`. */ setState: function setState(stateUpdates) { var _this = this; // Support providing the `stateUpdates` state as a function. if (typeof stateUpdates === 'function') { stateUpdates = stateUpdates(); } var changes; each(stateUpdates, function (value, key) { // Record the change if the value is different from what's in the // current state. if (_this.state[key] !== value) { changes = changes || {}; changes[key] = { from: _this.state[key], to: value }; } _this.state[key] = value; }); // Only trigger "statechange" if there were changes AND we have a trigger // function. This allows us to not require that the target object be an // evented object. if (changes && isEvented(this)) { /** * An event triggered on an object that is both * {@link module:stateful|stateful} and {@link module:evented|evented} * indicating that its state has changed. * * @event module:stateful~StatefulMixin#statechanged * @type {Object} * @property {Object} changes * A hash containing the properties that were changed and * the values they were changed `from` and `to`. */ this.trigger({ changes: changes, type: 'statechanged' }); } return changes; } }; /** * Applies {@link module:stateful~StatefulMixin|StatefulMixin} to a target * object. * * If the target object is {@link module:evented|evented} and has a * `handleStateChanged` method, that method will be automatically bound to the * `statechanged` event on itself. * * @param {Object} target * The object to be made stateful. * * @param {Object} [defaultState] * A default set of properties to populate the newly-stateful object's * `state` property. * * @return {Object} * Returns the `target`. */ function stateful(target, defaultState) { assign(target, StatefulMixin); // This happens after the mixing-in because we need to replace the `state` // added in that step. target.state = assign({}, target.state, defaultState); // Auto-bind the `handleStateChanged` method of the target object if it exists. if (typeof target.handleStateChanged === 'function' && isEvented(target)) { target.on('statechanged', target.handleStateChanged); } return target; } /** * @file string-cases.js * @module to-lower-case */ /** * Lowercase the first letter of a string. * * @param {string} string * String to be lowercased * * @return {string} * The string with a lowercased first letter */ var toLowerCase = function toLowerCase(string) { if (typeof string !== 'string') { return string; } return string.replace(/./, function (w) { return w.toLowerCase(); }); }; /** * Uppercase the first letter of a string. * * @param {string} string * String to be uppercased * * @return {string} * The string with an uppercased first letter */ var toTitleCase = function toTitleCase(string) { if (typeof string !== 'string') { return string; } return string.replace(/./, function (w) { return w.toUpperCase(); }); }; /** * Compares the TitleCase versions of the two strings for equality. * * @param {string} str1 * The first string to compare * * @param {string} str2 * The second string to compare * * @return {boolean} * Whether the TitleCase versions of the strings are equal */ var titleCaseEquals = function titleCaseEquals(str1, str2) { return toTitleCase(str1) === toTitleCase(str2); }; /** * @file merge-options.js * @module merge-options */ /** * Merge two objects recursively. * * Performs a deep merge like * {@link https://lodash.com/docs/4.17.10#merge|lodash.merge}, but only merges * plain objects (not arrays, elements, or anything else). * * Non-plain object values will be copied directly from the right-most * argument. * * @static * @param {Object[]} sources * One or more objects to merge into a new object. * * @return {Object} * A new object that is the merged result of all sources. */ function mergeOptions() { var result = {}; for (var _len = arguments.length, sources = new Array(_len), _key = 0; _key < _len; _key++) { sources[_key] = arguments[_key]; } sources.forEach(function (source) { if (!source) { return; } each(source, function (value, key) { if (!isPlain(value)) { result[key] = value; return; } if (!isPlain(result[key])) { result[key] = {}; } result[key] = mergeOptions(result[key], value); }); }); return result; } /** * Player Component - Base class for all UI objects * * @file component.js */ /** * Base class for all UI Components. * Components are UI objects which represent both a javascript object and an element * in the DOM. They can be children of other components, and can have * children themselves. * * Components can also use methods from {@link EventTarget} */ var Component = /*#__PURE__*/ function () { /** * A callback that is called when a component is ready. Does not have any * paramters and any callback value will be ignored. * * @callback Component~ReadyCallback * @this Component */ /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. * * @param {Object[]} [options.children] * An array of children objects to intialize this component with. Children objects have * a name property that will be used if more than one component of the same type needs to be * added. * * @param {Component~ReadyCallback} [ready] * Function that gets called when the `Component` is ready. */ function Component(player, options, ready) { // The component might be the player itself and we can't pass `this` to super if (!player && this.play) { this.player_ = player = this; // eslint-disable-line } else { this.player_ = player; } // Hold the reference to the parent component via `addChild` method this.parentComponent_ = null; // Make a copy of prototype.options_ to protect against overriding defaults this.options_ = mergeOptions({}, this.options_); // Updated options with supplied options options = this.options_ = mergeOptions(this.options_, options); // Get ID from options or options element if one is supplied this.id_ = options.id || options.el && options.el.id; // If there was no ID from the options, generate one if (!this.id_) { // Don't require the player ID function in the case of mock players var id = player && player.id && player.id() || 'no_player'; this.id_ = id + "_component_" + newGUID(); } this.name_ = options.name || null; // Create element if one wasn't provided in options if (options.el) { this.el_ = options.el; } else if (options.createEl !== false) { this.el_ = this.createEl(); } // if evented is anything except false, we want to mixin in evented if (options.evented !== false) { // Make this an evented object and use `el_`, if available, as its event bus evented(this, { eventBusKey: this.el_ ? 'el_' : null }); } stateful(this, this.constructor.defaultState); this.children_ = []; this.childIndex_ = {}; this.childNameIndex_ = {}; this.setTimeoutIds_ = new Set(); this.setIntervalIds_ = new Set(); this.rafIds_ = new Set(); this.clearingTimersOnDispose_ = false; // Add any child components in options if (options.initChildren !== false) { this.initChildren(); } this.ready(ready); // Don't want to trigger ready here or it will before init is actually // finished for all children that run this constructor if (options.reportTouchActivity !== false) { this.enableTouchActivity(); } } /** * Dispose of the `Component` and all child components. * * @fires Component#dispose */ var _proto = Component.prototype; _proto.dispose = function dispose() { /** * Triggered when a `Component` is disposed. * * @event Component#dispose * @type {EventTarget~Event} * * @property {boolean} [bubbles=false] * set to false so that the close event does not * bubble up */ this.trigger({ type: 'dispose', bubbles: false }); // Dispose all children. if (this.children_) { for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i].dispose) { this.children_[i].dispose(); } } } // Delete child references this.children_ = null; this.childIndex_ = null; this.childNameIndex_ = null; this.parentComponent_ = null; if (this.el_) { // Remove element from DOM if (this.el_.parentNode) { this.el_.parentNode.removeChild(this.el_); } if (DomData.has(this.el_)) { DomData["delete"](this.el_); } this.el_ = null; } // remove reference to the player after disposing of the element this.player_ = null; } /** * Return the {@link Player} that the `Component` has attached to. * * @return {Player} * The player that this `Component` has attached to. */ ; _proto.player = function player() { return this.player_; } /** * Deep merge of options objects with new options. * > Note: When both `obj` and `options` contain properties whose values are objects. * The two properties get merged using {@link module:mergeOptions} * * @param {Object} obj * The object that contains new options. * * @return {Object} * A new object of `this.options_` and `obj` merged together. */ ; _proto.options = function options(obj) { if (!obj) { return this.options_; } this.options_ = mergeOptions(this.options_, obj); return this.options_; } /** * Get the `Component`s DOM element * * @return {Element} * The DOM element for this `Component`. */ ; _proto.el = function el() { return this.el_; } /** * Create the `Component`s DOM element. * * @param {string} [tagName] * Element's DOM node type. e.g. 'div' * * @param {Object} [properties] * An object of properties that should be set. * * @param {Object} [attributes] * An object of attributes that should be set. * * @return {Element} * The element that gets created. */ ; _proto.createEl = function createEl$1(tagName, properties, attributes) { return createEl(tagName, properties, attributes); } /** * Localize a string given the string in english. * * If tokens are provided, it'll try and run a simple token replacement on the provided string. * The tokens it looks for look like `{1}` with the index being 1-indexed into the tokens array. * * If a `defaultValue` is provided, it'll use that over `string`, * if a value isn't found in provided language files. * This is useful if you want to have a descriptive key for token replacement * but have a succinct localized string and not require `en.json` to be included. * * Currently, it is used for the progress bar timing. * ```js * { * "progress bar timing: currentTime={1} duration={2}": "{1} of {2}" * } * ``` * It is then used like so: * ```js * this.localize('progress bar timing: currentTime={1} duration{2}', * [this.player_.currentTime(), this.player_.duration()], * '{1} of {2}'); * ``` * * Which outputs something like: `01:23 of 24:56`. * * * @param {string} string * The string to localize and the key to lookup in the language files. * @param {string[]} [tokens] * If the current item has token replacements, provide the tokens here. * @param {string} [defaultValue] * Defaults to `string`. Can be a default value to use for token replacement * if the lookup key is needed to be separate. * * @return {string} * The localized string or if no localization exists the english string. */ ; _proto.localize = function localize(string, tokens, defaultValue) { if (defaultValue === void 0) { defaultValue = string; } var code = this.player_.language && this.player_.language(); var languages = this.player_.languages && this.player_.languages(); var language = languages && languages[code]; var primaryCode = code && code.split('-')[0]; var primaryLang = languages && languages[primaryCode]; var localizedString = defaultValue; if (language && language[string]) { localizedString = language[string]; } else if (primaryLang && primaryLang[string]) { localizedString = primaryLang[string]; } if (tokens) { localizedString = localizedString.replace(/\{(\d+)\}/g, function (match, index) { var value = tokens[index - 1]; var ret = value; if (typeof value === 'undefined') { ret = match; } return ret; }); } return localizedString; } /** * Return the `Component`s DOM element. This is where children get inserted. * This will usually be the the same as the element returned in {@link Component#el}. * * @return {Element} * The content element for this `Component`. */ ; _proto.contentEl = function contentEl() { return this.contentEl_ || this.el_; } /** * Get this `Component`s ID * * @return {string} * The id of this `Component` */ ; _proto.id = function id() { return this.id_; } /** * Get the `Component`s name. The name gets used to reference the `Component` * and is set during registration. * * @return {string} * The name of this `Component`. */ ; _proto.name = function name() { return this.name_; } /** * Get an array of all child components * * @return {Array} * The children */ ; _proto.children = function children() { return this.children_; } /** * Returns the child `Component` with the given `id`. * * @param {string} id * The id of the child `Component` to get. * * @return {Component|undefined} * The child `Component` with the given `id` or undefined. */ ; _proto.getChildById = function getChildById(id) { return this.childIndex_[id]; } /** * Returns the child `Component` with the given `name`. * * @param {string} name * The name of the child `Component` to get. * * @return {Component|undefined} * The child `Component` with the given `name` or undefined. */ ; _proto.getChild = function getChild(name) { if (!name) { return; } return this.childNameIndex_[name]; } /** * Add a child `Component` inside the current `Component`. * * * @param {string|Component} child * The name or instance of a child to add. * * @param {Object} [options={}] * The key/value store of options that will get passed to children of * the child. * * @param {number} [index=this.children_.length] * The index to attempt to add a child into. * * @return {Component} * The `Component` that gets added as a child. When using a string the * `Component` will get created by this process. */ ; _proto.addChild = function addChild(child, options, index) { if (options === void 0) { options = {}; } if (index === void 0) { index = this.children_.length; } var component; var componentName; // If child is a string, create component with options if (typeof child === 'string') { componentName = toTitleCase(child); var componentClassName = options.componentClass || componentName; // Set name through options options.name = componentName; // Create a new object & element for this controls set // If there's no .player_, this is a player var ComponentClass = Component.getComponent(componentClassName); if (!ComponentClass) { throw new Error("Component " + componentClassName + " does not exist"); } // data stored directly on the videojs object may be // misidentified as a component to retain // backwards-compatibility with 4.x. check to make sure the // component class can be instantiated. if (typeof ComponentClass !== 'function') { return null; } component = new ComponentClass(this.player_ || this, options); // child is a component instance } else { component = child; } if (component.parentComponent_) { component.parentComponent_.removeChild(component); } this.children_.splice(index, 0, component); component.parentComponent_ = this; if (typeof component.id === 'function') { this.childIndex_[component.id()] = component; } // If a name wasn't used to create the component, check if we can use the // name function of the component componentName = componentName || component.name && toTitleCase(component.name()); if (componentName) { this.childNameIndex_[componentName] = component; this.childNameIndex_[toLowerCase(componentName)] = component; } // Add the UI object's element to the container div (box) // Having an element is not required if (typeof component.el === 'function' && component.el()) { var childNodes = this.contentEl().children; var refNode = childNodes[index] || null; this.contentEl().insertBefore(component.el(), refNode); } // Return so it can stored on parent object if desired. return component; } /** * Remove a child `Component` from this `Component`s list of children. Also removes * the child `Component`s element from this `Component`s element. * * @param {Component} component * The child `Component` to remove. */ ; _proto.removeChild = function removeChild(component) { if (typeof component === 'string') { component = this.getChild(component); } if (!component || !this.children_) { return; } var childFound = false; for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i] === component) { childFound = true; this.children_.splice(i, 1); break; } } if (!childFound) { return; } component.parentComponent_ = null; this.childIndex_[component.id()] = null; this.childNameIndex_[toTitleCase(component.name())] = null; this.childNameIndex_[toLowerCase(component.name())] = null; var compEl = component.el(); if (compEl && compEl.parentNode === this.contentEl()) { this.contentEl().removeChild(component.el()); } } /** * Add and initialize default child `Component`s based upon options. */ ; _proto.initChildren = function initChildren() { var _this = this; var children = this.options_.children; if (children) { // `this` is `parent` var parentOptions = this.options_; var handleAdd = function handleAdd(child) { var name = child.name; var opts = child.opts; // Allow options for children to be set at the parent options // e.g. videojs(id, { controlBar: false }); // instead of videojs(id, { children: { controlBar: false }); if (parentOptions[name] !== undefined) { opts = parentOptions[name]; } // Allow for disabling default components // e.g. options['children']['posterImage'] = false if (opts === false) { return; } // Allow options to be passed as a simple boolean if no configuration // is necessary. if (opts === true) { opts = {}; } // We also want to pass the original player options // to each component as well so they don't need to // reach back into the player for options later. opts.playerOptions = _this.options_.playerOptions; // Create and add the child component. // Add a direct reference to the child by name on the parent instance. // If two of the same component are used, different names should be supplied // for each var newChild = _this.addChild(name, opts); if (newChild) { _this[name] = newChild; } }; // Allow for an array of children details to passed in the options var workingChildren; var Tech = Component.getComponent('Tech'); if (Array.isArray(children)) { workingChildren = children; } else { workingChildren = Object.keys(children); } workingChildren // children that are in this.options_ but also in workingChildren would // give us extra children we do not want. So, we want to filter them out. .concat(Object.keys(this.options_).filter(function (child) { return !workingChildren.some(function (wchild) { if (typeof wchild === 'string') { return child === wchild; } return child === wchild.name; }); })).map(function (child) { var name; var opts; if (typeof child === 'string') { name = child; opts = children[name] || _this.options_[name] || {}; } else { name = child.name; opts = child; } return { name: name, opts: opts }; }).filter(function (child) { // we have to make sure that child.name isn't in the techOrder since // techs are registerd as Components but can't aren't compatible // See https://github.com/videojs/video.js/issues/2772 var c = Component.getComponent(child.opts.componentClass || toTitleCase(child.name)); return c && !Tech.isTech(c); }).forEach(handleAdd); } } /** * Builds the default DOM class name. Should be overriden by sub-components. * * @return {string} * The DOM class name for this object. * * @abstract */ ; _proto.buildCSSClass = function buildCSSClass() { // Child classes can include a function that does: // return 'CLASS NAME' + this._super(); return ''; } /** * Bind a listener to the component's ready state. * Different from event listeners in that if the ready event has already happened * it will trigger the function immediately. * * @return {Component} * Returns itself; method can be chained. */ ; _proto.ready = function ready(fn, sync) { if (sync === void 0) { sync = false; } if (!fn) { return; } if (!this.isReady_) { this.readyQueue_ = this.readyQueue_ || []; this.readyQueue_.push(fn); return; } if (sync) { fn.call(this); } else { // Call the function asynchronously by default for consistency this.setTimeout(fn, 1); } } /** * Trigger all the ready listeners for this `Component`. * * @fires Component#ready */ ; _proto.triggerReady = function triggerReady() { this.isReady_ = true; // Ensure ready is triggered asynchronously this.setTimeout(function () { var readyQueue = this.readyQueue_; // Reset Ready Queue this.readyQueue_ = []; if (readyQueue && readyQueue.length > 0) { readyQueue.forEach(function (fn) { fn.call(this); }, this); } // Allow for using event listeners also /** * Triggered when a `Component` is ready. * * @event Component#ready * @type {EventTarget~Event} */ this.trigger('ready'); }, 1); } /** * Find a single DOM element matching a `selector`. This can be within the `Component`s * `contentEl()` or another custom context. * * @param {string} selector * A valid CSS selector, which will be passed to `querySelector`. * * @param {Element|string} [context=this.contentEl()] * A DOM element within which to query. Can also be a selector string in * which case the first matching element will get used as context. If * missing `this.contentEl()` gets used. If `this.contentEl()` returns * nothing it falls back to `document`. * * @return {Element|null} * the dom element that was found, or null * * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors) */ ; _proto.$ = function $$1(selector, context) { return $(selector, context || this.contentEl()); } /** * Finds all DOM element matching a `selector`. This can be within the `Component`s * `contentEl()` or another custom context. * * @param {string} selector * A valid CSS selector, which will be passed to `querySelectorAll`. * * @param {Element|string} [context=this.contentEl()] * A DOM element within which to query. Can also be a selector string in * which case the first matching element will get used as context. If * missing `this.contentEl()` gets used. If `this.contentEl()` returns * nothing it falls back to `document`. * * @return {NodeList} * a list of dom elements that were found * * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors) */ ; _proto.$$ = function $$$1(selector, context) { return $$(selector, context || this.contentEl()); } /** * Check if a component's element has a CSS class name. * * @param {string} classToCheck * CSS class name to check. * * @return {boolean} * - True if the `Component` has the class. * - False if the `Component` does not have the class` */ ; _proto.hasClass = function hasClass$1(classToCheck) { return hasClass(this.el_, classToCheck); } /** * Add a CSS class name to the `Component`s element. * * @param {string} classToAdd * CSS class name to add */ ; _proto.addClass = function addClass$1(classToAdd) { addClass(this.el_, classToAdd); } /** * Remove a CSS class name from the `Component`s element. * * @param {string} classToRemove * CSS class name to remove */ ; _proto.removeClass = function removeClass$1(classToRemove) { removeClass(this.el_, classToRemove); } /** * Add or remove a CSS class name from the component's element. * - `classToToggle` gets added when {@link Component#hasClass} would return false. * - `classToToggle` gets removed when {@link Component#hasClass} would return true. * * @param {string} classToToggle * The class to add or remove based on (@link Component#hasClass} * * @param {boolean|Dom~predicate} [predicate] * An {@link Dom~predicate} function or a boolean */ ; _proto.toggleClass = function toggleClass$1(classToToggle, predicate) { toggleClass(this.el_, classToToggle, predicate); } /** * Show the `Component`s element if it is hidden by removing the * 'vjs-hidden' class name from it. */ ; _proto.show = function show() { this.removeClass('vjs-hidden'); } /** * Hide the `Component`s element if it is currently showing by adding the * 'vjs-hidden` class name to it. */ ; _proto.hide = function hide() { this.addClass('vjs-hidden'); } /** * Lock a `Component`s element in its visible state by adding the 'vjs-lock-showing' * class name to it. Used during fadeIn/fadeOut. * * @private */ ; _proto.lockShowing = function lockShowing() { this.addClass('vjs-lock-showing'); } /** * Unlock a `Component`s element from its visible state by removing the 'vjs-lock-showing' * class name from it. Used during fadeIn/fadeOut. * * @private */ ; _proto.unlockShowing = function unlockShowing() { this.removeClass('vjs-lock-showing'); } /** * Get the value of an attribute on the `Component`s element. * * @param {string} attribute * Name of the attribute to get the value from. * * @return {string|null} * - The value of the attribute that was asked for. * - Can be an empty string on some browsers if the attribute does not exist * or has no value * - Most browsers will return null if the attibute does not exist or has * no value. * * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute} */ ; _proto.getAttribute = function getAttribute$1(attribute) { return getAttribute(this.el_, attribute); } /** * Set the value of an attribute on the `Component`'s element * * @param {string} attribute * Name of the attribute to set. * * @param {string} value * Value to set the attribute to. * * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute} */ ; _proto.setAttribute = function setAttribute$1(attribute, value) { setAttribute(this.el_, attribute, value); } /** * Remove an attribute from the `Component`s element. * * @param {string} attribute * Name of the attribute to remove. * * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute} */ ; _proto.removeAttribute = function removeAttribute$1(attribute) { removeAttribute(this.el_, attribute); } /** * Get or set the width of the component based upon the CSS styles. * See {@link Component#dimension} for more detailed information. * * @param {number|string} [num] * The width that you want to set postfixed with '%', 'px' or nothing. * * @param {boolean} [skipListeners] * Skip the componentresize event trigger * * @return {number|string} * The width when getting, zero if there is no width. Can be a string * postpixed with '%' or 'px'. */ ; _proto.width = function width(num, skipListeners) { return this.dimension('width', num, skipListeners); } /** * Get or set the height of the component based upon the CSS styles. * See {@link Component#dimension} for more detailed information. * * @param {number|string} [num] * The height that you want to set postfixed with '%', 'px' or nothing. * * @param {boolean} [skipListeners] * Skip the componentresize event trigger * * @return {number|string} * The width when getting, zero if there is no width. Can be a string * postpixed with '%' or 'px'. */ ; _proto.height = function height(num, skipListeners) { return this.dimension('height', num, skipListeners); } /** * Set both the width and height of the `Component` element at the same time. * * @param {number|string} width * Width to set the `Component`s element to. * * @param {number|string} height * Height to set the `Component`s element to. */ ; _proto.dimensions = function dimensions(width, height) { // Skip componentresize listeners on width for optimization this.width(width, true); this.height(height); } /** * Get or set width or height of the `Component` element. This is the shared code * for the {@link Component#width} and {@link Component#height}. * * Things to know: * - If the width or height in an number this will return the number postfixed with 'px'. * - If the width/height is a percent this will return the percent postfixed with '%' * - Hidden elements have a width of 0 with `window.getComputedStyle`. This function * defaults to the `Component`s `style.width` and falls back to `window.getComputedStyle`. * See [this]{@link http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/} * for more information * - If you want the computed style of the component, use {@link Component#currentWidth} * and {@link {Component#currentHeight} * * @fires Component#componentresize * * @param {string} widthOrHeight 8 'width' or 'height' * * @param {number|string} [num] 8 New dimension * * @param {boolean} [skipListeners] * Skip componentresize event trigger * * @return {number} * The dimension when getting or 0 if unset */ ; _proto.dimension = function dimension(widthOrHeight, num, skipListeners) { if (num !== undefined) { // Set to zero if null or literally NaN (NaN !== NaN) if (num === null || num !== num) { num = 0; } // Check if using css width/height (% or px) and adjust if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) { this.el_.style[widthOrHeight] = num; } else if (num === 'auto') { this.el_.style[widthOrHeight] = ''; } else { this.el_.style[widthOrHeight] = num + 'px'; } // skipListeners allows us to avoid triggering the resize event when setting both width and height if (!skipListeners) { /** * Triggered when a component is resized. * * @event Component#componentresize * @type {EventTarget~Event} */ this.trigger('componentresize'); } return; } // Not setting a value, so getting it // Make sure element exists if (!this.el_) { return 0; } // Get dimension value from style var val = this.el_.style[widthOrHeight]; var pxIndex = val.indexOf('px'); if (pxIndex !== -1) { // Return the pixel value with no 'px' return parseInt(val.slice(0, pxIndex), 10); } // No px so using % or no style was set, so falling back to offsetWidth/height // If component has display:none, offset will return 0 // TODO: handle display:none and no dimension style using px return parseInt(this.el_['offset' + toTitleCase(widthOrHeight)], 10); } /** * Get the computed width or the height of the component's element. * * Uses `window.getComputedStyle`. * * @param {string} widthOrHeight * A string containing 'width' or 'height'. Whichever one you want to get. * * @return {number} * The dimension that gets asked for or 0 if nothing was set * for that dimension. */ ; _proto.currentDimension = function currentDimension(widthOrHeight) { var computedWidthOrHeight = 0; if (widthOrHeight !== 'width' && widthOrHeight !== 'height') { throw new Error('currentDimension only accepts width or height value'); } computedWidthOrHeight = computedStyle(this.el_, widthOrHeight); // remove 'px' from variable and parse as integer computedWidthOrHeight = parseFloat(computedWidthOrHeight); // if the computed value is still 0, it's possible that the browser is lying // and we want to check the offset values. // This code also runs wherever getComputedStyle doesn't exist. if (computedWidthOrHeight === 0 || isNaN(computedWidthOrHeight)) { var rule = "offset" + toTitleCase(widthOrHeight); computedWidthOrHeight = this.el_[rule]; } return computedWidthOrHeight; } /** * An object that contains width and height values of the `Component`s * computed style. Uses `window.getComputedStyle`. * * @typedef {Object} Component~DimensionObject * * @property {number} width * The width of the `Component`s computed style. * * @property {number} height * The height of the `Component`s computed style. */ /** * Get an object that contains computed width and height values of the * component's element. * * Uses `window.getComputedStyle`. * * @return {Component~DimensionObject} * The computed dimensions of the component's element. */ ; _proto.currentDimensions = function currentDimensions() { return { width: this.currentDimension('width'), height: this.currentDimension('height') }; } /** * Get the computed width of the component's element. * * Uses `window.getComputedStyle`. * * @return {number} * The computed width of the component's element. */ ; _proto.currentWidth = function currentWidth() { return this.currentDimension('width'); } /** * Get the computed height of the component's element. * * Uses `window.getComputedStyle`. * * @return {number} * The computed height of the component's element. */ ; _proto.currentHeight = function currentHeight() { return this.currentDimension('height'); } /** * Set the focus to this component */ ; _proto.focus = function focus() { this.el_.focus(); } /** * Remove the focus from this component */ ; _proto.blur = function blur() { this.el_.blur(); } /** * When this Component receives a `keydown` event which it does not process, * it passes the event to the Player for handling. * * @param {EventTarget~Event} event * The `keydown` event that caused this function to be called. */ ; _proto.handleKeyDown = function handleKeyDown(event) { if (this.player_) { // We only stop propagation here because we want unhandled events to fall // back to the browser. event.stopPropagation(); this.player_.handleKeyDown(event); } } /** * Many components used to have a `handleKeyPress` method, which was poorly * named because it listened to a `keydown` event. This method name now * delegates to `handleKeyDown`. This means anyone calling `handleKeyPress` * will not see their method calls stop working. * * @param {EventTarget~Event} event * The event that caused this function to be called. */ ; _proto.handleKeyPress = function handleKeyPress(event) { this.handleKeyDown(event); } /** * Emit a 'tap' events when touch event support gets detected. This gets used to * support toggling the controls through a tap on the video. They get enabled * because every sub-component would have extra overhead otherwise. * * @private * @fires Component#tap * @listens Component#touchstart * @listens Component#touchmove * @listens Component#touchleave * @listens Component#touchcancel * @listens Component#touchend */ ; _proto.emitTapEvents = function emitTapEvents() { // Track the start time so we can determine how long the touch lasted var touchStart = 0; var firstTouch = null; // Maximum movement allowed during a touch event to still be considered a tap // Other popular libs use anywhere from 2 (hammer.js) to 15, // so 10 seems like a nice, round number. var tapMovementThreshold = 10; // The maximum length a touch can be while still being considered a tap var touchTimeThreshold = 200; var couldBeTap; this.on('touchstart', function (event) { // If more than one finger, don't consider treating this as a click if (event.touches.length === 1) { // Copy pageX/pageY from the object firstTouch = { pageX: event.touches[0].pageX, pageY: event.touches[0].pageY }; // Record start time so we can detect a tap vs. "touch and hold" touchStart = window$1.performance.now(); // Reset couldBeTap tracking couldBeTap = true; } }); this.on('touchmove', function (event) { // If more than one finger, don't consider treating this as a click if (event.touches.length > 1) { couldBeTap = false; } else if (firstTouch) { // Some devices will throw touchmoves for all but the slightest of taps. // So, if we moved only a small distance, this could still be a tap var xdiff = event.touches[0].pageX - firstTouch.pageX; var ydiff = event.touches[0].pageY - firstTouch.pageY; var touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff); if (touchDistance > tapMovementThreshold) { couldBeTap = false; } } }); var noTap = function noTap() { couldBeTap = false; }; // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s this.on('touchleave', noTap); this.on('touchcancel', noTap); // When the touch ends, measure how long it took and trigger the appropriate // event this.on('touchend', function (event) { firstTouch = null; // Proceed only if the touchmove/leave/cancel event didn't happen if (couldBeTap === true) { // Measure how long the touch lasted var touchTime = window$1.performance.now() - touchStart; // Make sure the touch was less than the threshold to be considered a tap if (touchTime < touchTimeThreshold) { // Don't let browser turn this into a click event.preventDefault(); /** * Triggered when a `Component` is tapped. * * @event Component#tap * @type {EventTarget~Event} */ this.trigger('tap'); // It may be good to copy the touchend event object and change the // type to tap, if the other event properties aren't exact after // Events.fixEvent runs (e.g. event.target) } } }); } /** * This function reports user activity whenever touch events happen. This can get * turned off by any sub-components that wants touch events to act another way. * * Report user touch activity when touch events occur. User activity gets used to * determine when controls should show/hide. It is simple when it comes to mouse * events, because any mouse event should show the controls. So we capture mouse * events that bubble up to the player and report activity when that happens. * With touch events it isn't as easy as `touchstart` and `touchend` toggle player * controls. So touch events can't help us at the player level either. * * User activity gets checked asynchronously. So what could happen is a tap event * on the video turns the controls off. Then the `touchend` event bubbles up to * the player. Which, if it reported user activity, would turn the controls right * back on. We also don't want to completely block touch events from bubbling up. * Furthermore a `touchmove` event and anything other than a tap, should not turn * controls back on. * * @listens Component#touchstart * @listens Component#touchmove * @listens Component#touchend * @listens Component#touchcancel */ ; _proto.enableTouchActivity = function enableTouchActivity() { // Don't continue if the root player doesn't support reporting user activity if (!this.player() || !this.player().reportUserActivity) { return; } // listener for reporting that the user is active var report = bind(this.player(), this.player().reportUserActivity); var touchHolding; this.on('touchstart', function () { report(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(touchHolding); // report at the same interval as activityCheck touchHolding = this.setInterval(report, 250); }); var touchEnd = function touchEnd(event) { report(); // stop the interval that maintains activity if the touch is holding this.clearInterval(touchHolding); }; this.on('touchmove', report); this.on('touchend', touchEnd); this.on('touchcancel', touchEnd); } /** * A callback that has no parameters and is bound into `Component`s context. * * @callback Component~GenericCallback * @this Component */ /** * Creates a function that runs after an `x` millisecond timeout. This function is a * wrapper around `window.setTimeout`. There are a few reasons to use this one * instead though: * 1. It gets cleared via {@link Component#clearTimeout} when * {@link Component#dispose} gets called. * 2. The function callback will gets turned into a {@link Component~GenericCallback} * * > Note: You can't use `window.clearTimeout` on the id returned by this function. This * will cause its dispose listener not to get cleaned up! Please use * {@link Component#clearTimeout} or {@link Component#dispose} instead. * * @param {Component~GenericCallback} fn * The function that will be run after `timeout`. * * @param {number} timeout * Timeout in milliseconds to delay before executing the specified function. * * @return {number} * Returns a timeout ID that gets used to identify the timeout. It can also * get used in {@link Component#clearTimeout} to clear the timeout that * was set. * * @listens Component#dispose * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout} */ ; _proto.setTimeout = function setTimeout(fn, timeout) { var _this2 = this; // declare as variables so they are properly available in timeout function // eslint-disable-next-line var timeoutId; fn = bind(this, fn); this.clearTimersOnDispose_(); timeoutId = window$1.setTimeout(function () { if (_this2.setTimeoutIds_.has(timeoutId)) { _this2.setTimeoutIds_["delete"](timeoutId); } fn(); }, timeout); this.setTimeoutIds_.add(timeoutId); return timeoutId; } /** * Clears a timeout that gets created via `window.setTimeout` or * {@link Component#setTimeout}. If you set a timeout via {@link Component#setTimeout} * use this function instead of `window.clearTimout`. If you don't your dispose * listener will not get cleaned up until {@link Component#dispose}! * * @param {number} timeoutId * The id of the timeout to clear. The return value of * {@link Component#setTimeout} or `window.setTimeout`. * * @return {number} * Returns the timeout id that was cleared. * * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearTimeout} */ ; _proto.clearTimeout = function clearTimeout(timeoutId) { if (this.setTimeoutIds_.has(timeoutId)) { this.setTimeoutIds_["delete"](timeoutId); window$1.clearTimeout(timeoutId); } return timeoutId; } /** * Creates a function that gets run every `x` milliseconds. This function is a wrapper * around `window.setInterval`. There are a few reasons to use this one instead though. * 1. It gets cleared via {@link Component#clearInterval} when * {@link Component#dispose} gets called. * 2. The function callback will be a {@link Component~GenericCallback} * * @param {Component~GenericCallback} fn * The function to run every `x` seconds. * * @param {number} interval * Execute the specified function every `x` milliseconds. * * @return {number} * Returns an id that can be used to identify the interval. It can also be be used in * {@link Component#clearInterval} to clear the interval. * * @listens Component#dispose * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval} */ ; _proto.setInterval = function setInterval(fn, interval) { fn = bind(this, fn); this.clearTimersOnDispose_(); var intervalId = window$1.setInterval(fn, interval); this.setIntervalIds_.add(intervalId); return intervalId; } /** * Clears an interval that gets created via `window.setInterval` or * {@link Component#setInterval}. If you set an inteval via {@link Component#setInterval} * use this function instead of `window.clearInterval`. If you don't your dispose * listener will not get cleaned up until {@link Component#dispose}! * * @param {number} intervalId * The id of the interval to clear. The return value of * {@link Component#setInterval} or `window.setInterval`. * * @return {number} * Returns the interval id that was cleared. * * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval} */ ; _proto.clearInterval = function clearInterval(intervalId) { if (this.setIntervalIds_.has(intervalId)) { this.setIntervalIds_["delete"](intervalId); window$1.clearInterval(intervalId); } return intervalId; } /** * Queues up a callback to be passed to requestAnimationFrame (rAF), but * with a few extra bonuses: * * - Supports browsers that do not support rAF by falling back to * {@link Component#setTimeout}. * * - The callback is turned into a {@link Component~GenericCallback} (i.e. * bound to the component). * * - Automatic cancellation of the rAF callback is handled if the component * is disposed before it is called. * * @param {Component~GenericCallback} fn * A function that will be bound to this component and executed just * before the browser's next repaint. * * @return {number} * Returns an rAF ID that gets used to identify the timeout. It can * also be used in {@link Component#cancelAnimationFrame} to cancel * the animation frame callback. * * @listens Component#dispose * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame} */ ; _proto.requestAnimationFrame = function requestAnimationFrame(fn) { var _this3 = this; // Fall back to using a timer. if (!this.supportsRaf_) { return this.setTimeout(fn, 1000 / 60); } this.clearTimersOnDispose_(); // declare as variables so they are properly available in rAF function // eslint-disable-next-line var id; fn = bind(this, fn); id = window$1.requestAnimationFrame(function () { if (_this3.rafIds_.has(id)) { _this3.rafIds_["delete"](id); } fn(); }); this.rafIds_.add(id); return id; } /** * Cancels a queued callback passed to {@link Component#requestAnimationFrame} * (rAF). * * If you queue an rAF callback via {@link Component#requestAnimationFrame}, * use this function instead of `window.cancelAnimationFrame`. If you don't, * your dispose listener will not get cleaned up until {@link Component#dispose}! * * @param {number} id * The rAF ID to clear. The return value of {@link Component#requestAnimationFrame}. * * @return {number} * Returns the rAF ID that was cleared. * * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/cancelAnimationFrame} */ ; _proto.cancelAnimationFrame = function cancelAnimationFrame(id) { // Fall back to using a timer. if (!this.supportsRaf_) { return this.clearTimeout(id); } if (this.rafIds_.has(id)) { this.rafIds_["delete"](id); window$1.cancelAnimationFrame(id); } return id; } /** * A function to setup `requestAnimationFrame`, `setTimeout`, * and `setInterval`, clearing on dispose. * * > Previously each timer added and removed dispose listeners on it's own. * For better performance it was decided to batch them all, and use `Set`s * to track outstanding timer ids. * * @private */ ; _proto.clearTimersOnDispose_ = function clearTimersOnDispose_() { var _this4 = this; if (this.clearingTimersOnDispose_) { return; } this.clearingTimersOnDispose_ = true; this.one('dispose', function () { [['rafIds_', 'cancelAnimationFrame'], ['setTimeoutIds_', 'clearTimeout'], ['setIntervalIds_', 'clearInterval']].forEach(function (_ref) { var idName = _ref[0], cancelName = _ref[1]; _this4[idName].forEach(_this4[cancelName], _this4); }); _this4.clearingTimersOnDispose_ = false; }); } /** * Register a `Component` with `videojs` given the name and the component. * * > NOTE: {@link Tech}s should not be registered as a `Component`. {@link Tech}s * should be registered using {@link Tech.registerTech} or * {@link videojs:videojs.registerTech}. * * > NOTE: This function can also be seen on videojs as * {@link videojs:videojs.registerComponent}. * * @param {string} name * The name of the `Component` to register. * * @param {Component} ComponentToRegister * The `Component` class to register. * * @return {Component} * The `Component` that was registered. */ ; Component.registerComponent = function registerComponent(name, ComponentToRegister) { if (typeof name !== 'string' || !name) { throw new Error("Illegal component name, \"" + name + "\"; must be a non-empty string."); } var Tech = Component.getComponent('Tech'); // We need to make sure this check is only done if Tech has been registered. var isTech = Tech && Tech.isTech(ComponentToRegister); var isComp = Component === ComponentToRegister || Component.prototype.isPrototypeOf(ComponentToRegister.prototype); if (isTech || !isComp) { var reason; if (isTech) { reason = 'techs must be registered using Tech.registerTech()'; } else { reason = 'must be a Component subclass'; } throw new Error("Illegal component, \"" + name + "\"; " + reason + "."); } name = toTitleCase(name); if (!Component.components_) { Component.components_ = {}; } var Player = Component.getComponent('Player'); if (name === 'Player' && Player && Player.players) { var players = Player.players; var playerNames = Object.keys(players); // If we have players that were disposed, then their name will still be // in Players.players. So, we must loop through and verify that the value // for each item is not null. This allows registration of the Player component // after all players have been disposed or before any were created. if (players && playerNames.length > 0 && playerNames.map(function (pname) { return players[pname]; }).every(Boolean)) { throw new Error('Can not register Player component after player has been created.'); } } Component.components_[name] = ComponentToRegister; Component.components_[toLowerCase(name)] = ComponentToRegister; return ComponentToRegister; } /** * Get a `Component` based on the name it was registered with. * * @param {string} name * The Name of the component to get. * * @return {Component} * The `Component` that got registered under the given name. * * @deprecated In `videojs` 6 this will not return `Component`s that were not * registered using {@link Component.registerComponent}. Currently we * check the global `videojs` object for a `Component` name and * return that if it exists. */ ; Component.getComponent = function getComponent(name) { if (!name || !Component.components_) { return; } return Component.components_[name]; }; return Component; }(); /** * Whether or not this component supports `requestAnimationFrame`. * * This is exposed primarily for testing purposes. * * @private * @type {Boolean} */ Component.prototype.supportsRaf_ = typeof window$1.requestAnimationFrame === 'function' && typeof window$1.cancelAnimationFrame === 'function'; Component.registerComponent('Component', Component); function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } /** * @file browser.js * @module browser */ var USER_AGENT = window$1.navigator && window$1.navigator.userAgent || ''; var webkitVersionMap = /AppleWebKit\/([\d.]+)/i.exec(USER_AGENT); var appleWebkitVersion = webkitVersionMap ? parseFloat(webkitVersionMap.pop()) : null; /** * Whether or not this device is an iPad. * * @static * @const * @type {Boolean} */ var IS_IPAD = /iPad/i.test(USER_AGENT); /** * Whether or not this device is an iPhone. * * @static * @const * @type {Boolean} */ // The Facebook app's UIWebView identifies as both an iPhone and iPad, so // to identify iPhones, we need to exclude iPads. // http://artsy.github.io/blog/2012/10/18/the-perils-of-ios-user-agent-sniffing/ var IS_IPHONE = /iPhone/i.test(USER_AGENT) && !IS_IPAD; /** * Whether or not this device is an iPod. * * @static * @const * @type {Boolean} */ var IS_IPOD = /iPod/i.test(USER_AGENT); /** * Whether or not this is an iOS device. * * @static * @const * @type {Boolean} */ var IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD; /** * The detected iOS version - or `null`. * * @static * @const * @type {string|null} */ var IOS_VERSION = function () { var match = USER_AGENT.match(/OS (\d+)_/i); if (match && match[1]) { return match[1]; } return null; }(); /** * Whether or not this is an Android device. * * @static * @const * @type {Boolean} */ var IS_ANDROID = /Android/i.test(USER_AGENT); /** * The detected Android version - or `null`. * * @static * @const * @type {number|string|null} */ var ANDROID_VERSION = function () { // This matches Android Major.Minor.Patch versions // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned var match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i); if (!match) { return null; } var major = match[1] && parseFloat(match[1]); var minor = match[2] && parseFloat(match[2]); if (major && minor) { return parseFloat(match[1] + '.' + match[2]); } else if (major) { return major; } return null; }(); /** * Whether or not this is a native Android browser. * * @static * @const * @type {Boolean} */ var IS_NATIVE_ANDROID = IS_ANDROID && ANDROID_VERSION < 5 && appleWebkitVersion < 537; /** * Whether or not this is Mozilla Firefox. * * @static * @const * @type {Boolean} */ var IS_FIREFOX = /Firefox/i.test(USER_AGENT); /** * Whether or not this is Microsoft Edge. * * @static * @const * @type {Boolean} */ var IS_EDGE = /Edge/i.test(USER_AGENT); /** * Whether or not this is Google Chrome. * * This will also be `true` for Chrome on iOS, which will have different support * as it is actually Safari under the hood. * * @static * @const * @type {Boolean} */ var IS_CHROME = !IS_EDGE && (/Chrome/i.test(USER_AGENT) || /CriOS/i.test(USER_AGENT)); /** * The detected Google Chrome version - or `null`. * * @static * @const * @type {number|null} */ var CHROME_VERSION = function () { var match = USER_AGENT.match(/(Chrome|CriOS)\/(\d+)/); if (match && match[2]) { return parseFloat(match[2]); } return null; }(); /** * The detected Internet Explorer version - or `null`. * * @static * @const * @type {number|null} */ var IE_VERSION = function () { var result = /MSIE\s(\d+)\.\d/.exec(USER_AGENT); var version = result && parseFloat(result[1]); if (!version && /Trident\/7.0/i.test(USER_AGENT) && /rv:11.0/.test(USER_AGENT)) { // IE 11 has a different user agent string than other IE versions version = 11.0; } return version; }(); /** * Whether or not this is desktop Safari. * * @static * @const * @type {Boolean} */ var IS_SAFARI = /Safari/i.test(USER_AGENT) && !IS_CHROME && !IS_ANDROID && !IS_EDGE; /** * Whether or not this is any flavor of Safari - including iOS. * * @static * @const * @type {Boolean} */ var IS_ANY_SAFARI = (IS_SAFARI || IS_IOS) && !IS_CHROME; /** * Whether or not this is a Windows machine. * * @static * @const * @type {Boolean} */ var IS_WINDOWS = /Windows/i.test(USER_AGENT); /** * Whether or not this device is touch-enabled. * * @static * @const * @type {Boolean} */ var TOUCH_ENABLED = isReal() && ('ontouchstart' in window$1 || window$1.navigator.maxTouchPoints || window$1.DocumentTouch && window$1.document instanceof window$1.DocumentTouch); var browser = /*#__PURE__*/Object.freeze({ IS_IPAD: IS_IPAD, IS_IPHONE: IS_IPHONE, IS_IPOD: IS_IPOD, IS_IOS: IS_IOS, IOS_VERSION: IOS_VERSION, IS_ANDROID: IS_ANDROID, ANDROID_VERSION: ANDROID_VERSION, IS_NATIVE_ANDROID: IS_NATIVE_ANDROID, IS_FIREFOX: IS_FIREFOX, IS_EDGE: IS_EDGE, IS_CHROME: IS_CHROME, CHROME_VERSION: CHROME_VERSION, IE_VERSION: IE_VERSION, IS_SAFARI: IS_SAFARI, IS_ANY_SAFARI: IS_ANY_SAFARI, IS_WINDOWS: IS_WINDOWS, TOUCH_ENABLED: TOUCH_ENABLED }); /** * @file time-ranges.js * @module time-ranges */ /** * Returns the time for the specified index at the start or end * of a TimeRange object. * * @typedef {Function} TimeRangeIndex * * @param {number} [index=0] * The range number to return the time for. * * @return {number} * The time offset at the specified index. * * @deprecated The index argument must be provided. * In the future, leaving it out will throw an error. */ /** * An object that contains ranges of time. * * @typedef {Object} TimeRange * * @property {number} length * The number of time ranges represented by this object. * * @property {module:time-ranges~TimeRangeIndex} start * Returns the time offset at which a specified time range begins. * * @property {module:time-ranges~TimeRangeIndex} end * Returns the time offset at which a specified time range ends. * * @see https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges */ /** * Check if any of the time ranges are over the maximum index. * * @private * @param {string} fnName * The function name to use for logging * * @param {number} index * The index to check * * @param {number} maxIndex * The maximum possible index * * @throws {Error} if the timeRanges provided are over the maxIndex */ function rangeCheck(fnName, index, maxIndex) { if (typeof index !== 'number' || index < 0 || index > maxIndex) { throw new Error("Failed to execute '" + fnName + "' on 'TimeRanges': The index provided (" + index + ") is non-numeric or out of bounds (0-" + maxIndex + ")."); } } /** * Get the time for the specified index at the start or end * of a TimeRange object. * * @private * @param {string} fnName * The function name to use for logging * * @param {string} valueIndex * The property that should be used to get the time. should be * 'start' or 'end' * * @param {Array} ranges * An array of time ranges * * @param {Array} [rangeIndex=0] * The index to start the search at * * @return {number} * The time that offset at the specified index. * * @deprecated rangeIndex must be set to a value, in the future this will throw an error. * @throws {Error} if rangeIndex is more than the length of ranges */ function getRange(fnName, valueIndex, ranges, rangeIndex) { rangeCheck(fnName, rangeIndex, ranges.length - 1); return ranges[rangeIndex][valueIndex]; } /** * Create a time range object given ranges of time. * * @private * @param {Array} [ranges] * An array of time ranges. */ function createTimeRangesObj(ranges) { if (ranges === undefined || ranges.length === 0) { return { length: 0, start: function start() { throw new Error('This TimeRanges object is empty'); }, end: function end() { throw new Error('This TimeRanges object is empty'); } }; } return { length: ranges.length, start: getRange.bind(null, 'start', 0, ranges), end: getRange.bind(null, 'end', 1, ranges) }; } /** * Create a `TimeRange` object which mimics an * {@link https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges|HTML5 TimeRanges instance}. * * @param {number|Array[]} start * The start of a single range (a number) or an array of ranges (an * array of arrays of two numbers each). * * @param {number} end * The end of a single range. Cannot be used with the array form of * the `start` argument. */ function createTimeRanges(start, end) { if (Array.isArray(start)) { return createTimeRangesObj(start); } else if (start === undefined || end === undefined) { return createTimeRangesObj(); } return createTimeRangesObj([[start, end]]); } /** * @file buffer.js * @module buffer */ /** * Compute the percentage of the media that has been buffered. * * @param {TimeRange} buffered * The current `TimeRange` object representing buffered time ranges * * @param {number} duration * Total duration of the media * * @return {number} * Percent buffered of the total duration in decimal form. */ function bufferedPercent(buffered, duration) { var bufferedDuration = 0; var start; var end; if (!duration) { return 0; } if (!buffered || !buffered.length) { buffered = createTimeRanges(0, 0); } for (var i = 0; i < buffered.length; i++) { start = buffered.start(i); end = buffered.end(i); // buffered end can be bigger than duration by a very small fraction if (end > duration) { end = duration; } bufferedDuration += end - start; } return bufferedDuration / duration; } /** * @file fullscreen-api.js * @module fullscreen-api * @private */ /** * Store the browser-specific methods for the fullscreen API. * * @type {Object} * @see [Specification]{@link https://fullscreen.spec.whatwg.org} * @see [Map Approach From Screenfull.js]{@link https://github.com/sindresorhus/screenfull.js} */ var FullscreenApi = { prefixed: true }; // browser API methods var apiMap = [['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror', 'fullscreen'], // WebKit ['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror', '-webkit-full-screen'], // Mozilla ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror', '-moz-full-screen'], // Microsoft ['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError', '-ms-fullscreen']]; var specApi = apiMap[0]; var browserApi; // determine the supported set of functions for (var i = 0; i < apiMap.length; i++) { // check for exitFullscreen function if (apiMap[i][1] in document) { browserApi = apiMap[i]; break; } } // map the browser API names to the spec API names if (browserApi) { for (var _i = 0; _i < browserApi.length; _i++) { FullscreenApi[specApi[_i]] = browserApi[_i]; } FullscreenApi.prefixed = browserApi[0] !== specApi[0]; } /** * @file media-error.js */ /** * A Custom `MediaError` class which mimics the standard HTML5 `MediaError` class. * * @param {number|string|Object|MediaError} value * This can be of multiple types: * - number: should be a standard error code * - string: an error message (the code will be 0) * - Object: arbitrary properties * - `MediaError` (native): used to populate a video.js `MediaError` object * - `MediaError` (video.js): will return itself if it's already a * video.js `MediaError` object. * * @see [MediaError Spec]{@link https://dev.w3.org/html5/spec-author-view/video.html#mediaerror} * @see [Encrypted MediaError Spec]{@link https://www.w3.org/TR/2013/WD-encrypted-media-20130510/#error-codes} * * @class MediaError */ function MediaError(value) { // Allow redundant calls to this constructor to avoid having `instanceof` // checks peppered around the code. if (value instanceof MediaError) { return value; } if (typeof value === 'number') { this.code = value; } else if (typeof value === 'string') { // default code is zero, so this is a custom error this.message = value; } else if (isObject(value)) { // We assign the `code` property manually because native `MediaError` objects // do not expose it as an own/enumerable property of the object. if (typeof value.code === 'number') { this.code = value.code; } assign(this, value); } if (!this.message) { this.message = MediaError.defaultMessages[this.code] || ''; } } /** * The error code that refers two one of the defined `MediaError` types * * @type {Number} */ MediaError.prototype.code = 0; /** * An optional message that to show with the error. Message is not part of the HTML5 * video spec but allows for more informative custom errors. * * @type {String} */ MediaError.prototype.message = ''; /** * An optional status code that can be set by plugins to allow even more detail about * the error. For example a plugin might provide a specific HTTP status code and an * error message for that code. Then when the plugin gets that error this class will * know how to display an error message for it. This allows a custom message to show * up on the `Player` error overlay. * * @type {Array} */ MediaError.prototype.status = null; /** * Errors indexed by the W3C standard. The order **CANNOT CHANGE**! See the * specification listed under {@link MediaError} for more information. * * @enum {array} * @readonly * @property {string} 0 - MEDIA_ERR_CUSTOM * @property {string} 1 - MEDIA_ERR_ABORTED * @property {string} 2 - MEDIA_ERR_NETWORK * @property {string} 3 - MEDIA_ERR_DECODE * @property {string} 4 - MEDIA_ERR_SRC_NOT_SUPPORTED * @property {string} 5 - MEDIA_ERR_ENCRYPTED */ MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', 'MEDIA_ERR_ABORTED', 'MEDIA_ERR_NETWORK', 'MEDIA_ERR_DECODE', 'MEDIA_ERR_SRC_NOT_SUPPORTED', 'MEDIA_ERR_ENCRYPTED']; /** * The default `MediaError` messages based on the {@link MediaError.errorTypes}. * * @type {Array} * @constant */ MediaError.defaultMessages = { 1: 'You aborted the media playback', 2: 'A network error caused the media download to fail part-way.', 3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.', 4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.', 5: 'The media is encrypted and we do not have the keys to decrypt it.' }; // Add types as properties on MediaError // e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4; for (var errNum = 0; errNum < MediaError.errorTypes.length; errNum++) { MediaError[MediaError.errorTypes[errNum]] = errNum; // values should be accessible on both the class and instance MediaError.prototype[MediaError.errorTypes[errNum]] = errNum; } // jsdocs for instance/static members added above var tuple = SafeParseTuple; function SafeParseTuple(obj, reviver) { var json; var error = null; try { json = JSON.parse(obj, reviver); } catch (err) { error = err; } return [error, json]; } /** * Returns whether an object is `Promise`-like (i.e. has a `then` method). * * @param {Object} value * An object that may or may not be `Promise`-like. * * @return {boolean} * Whether or not the object is `Promise`-like. */ function isPromise(value) { return value !== undefined && value !== null && typeof value.then === 'function'; } /** * Silence a Promise-like object. * * This is useful for avoiding non-harmful, but potentially confusing "uncaught * play promise" rejection error messages. * * @param {Object} value * An object that may or may not be `Promise`-like. */ function silencePromise(value) { if (isPromise(value)) { value.then(null, function (e) {}); } } /** * @file text-track-list-converter.js Utilities for capturing text track state and * re-creating tracks based on a capture. * * @module text-track-list-converter */ /** * Examine a single {@link TextTrack} and return a JSON-compatible javascript object that * represents the {@link TextTrack}'s state. * * @param {TextTrack} track * The text track to query. * * @return {Object} * A serializable javascript representation of the TextTrack. * @private */ var trackToJson_ = function trackToJson_(track) { var ret = ['kind', 'label', 'language', 'id', 'inBandMetadataTrackDispatchType', 'mode', 'src'].reduce(function (acc, prop, i) { if (track[prop]) { acc[prop] = track[prop]; } return acc; }, { cues: track.cues && Array.prototype.map.call(track.cues, function (cue) { return { startTime: cue.startTime, endTime: cue.endTime, text: cue.text, id: cue.id }; }) }); return ret; }; /** * Examine a {@link Tech} and return a JSON-compatible javascript array that represents the * state of all {@link TextTrack}s currently configured. The return array is compatible with * {@link text-track-list-converter:jsonToTextTracks}. * * @param {Tech} tech * The tech object to query * * @return {Array} * A serializable javascript representation of the {@link Tech}s * {@link TextTrackList}. */ var textTracksToJson = function textTracksToJson(tech) { var trackEls = tech.$$('track'); var trackObjs = Array.prototype.map.call(trackEls, function (t) { return t.track; }); var tracks = Array.prototype.map.call(trackEls, function (trackEl) { var json = trackToJson_(trackEl.track); if (trackEl.src) { json.src = trackEl.src; } return json; }); return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) { return trackObjs.indexOf(track) === -1; }).map(trackToJson_)); }; /** * Create a set of remote {@link TextTrack}s on a {@link Tech} based on an array of javascript * object {@link TextTrack} representations. * * @param {Array} json * An array of `TextTrack` representation objects, like those that would be * produced by `textTracksToJson`. * * @param {Tech} tech * The `Tech` to create the `TextTrack`s on. */ var jsonToTextTracks = function jsonToTextTracks(json, tech) { json.forEach(function (track) { var addedTrack = tech.addRemoteTextTrack(track).track; if (!track.src && track.cues) { track.cues.forEach(function (cue) { return addedTrack.addCue(cue); }); } }); return tech.textTracks(); }; var textTrackConverter = { textTracksToJson: textTracksToJson, jsonToTextTracks: jsonToTextTracks, trackToJson_: trackToJson_ }; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var keycode = createCommonjsModule(function (module, exports) { // Source: http://jsfiddle.net/vWx8V/ // http://stackoverflow.com/questions/5603195/full-list-of-javascript-keycodes /** * Conenience method returns corresponding value for given keyName or keyCode. * * @param {Mixed} keyCode {Number} or keyName {String} * @return {Mixed} * @api public */ function keyCode(searchInput) { // Keyboard Events if (searchInput && 'object' === typeof searchInput) { var hasKeyCode = searchInput.which || searchInput.keyCode || searchInput.charCode; if (hasKeyCode) searchInput = hasKeyCode; } // Numbers if ('number' === typeof searchInput) return names[searchInput]; // Everything else (cast to string) var search = String(searchInput); // check codes var foundNamedKey = codes[search.toLowerCase()]; if (foundNamedKey) return foundNamedKey; // check aliases var foundNamedKey = aliases[search.toLowerCase()]; if (foundNamedKey) return foundNamedKey; // weird character? if (search.length === 1) return search.charCodeAt(0); return undefined; } /** * Compares a keyboard event with a given keyCode or keyName. * * @param {Event} event Keyboard event that should be tested * @param {Mixed} keyCode {Number} or keyName {String} * @return {Boolean} * @api public */ keyCode.isEventKey = function isEventKey(event, nameOrCode) { if (event && 'object' === typeof event) { var keyCode = event.which || event.keyCode || event.charCode; if (keyCode === null || keyCode === undefined) { return false; } if (typeof nameOrCode === 'string') { // check codes var foundNamedKey = codes[nameOrCode.toLowerCase()]; if (foundNamedKey) { return foundNamedKey === keyCode; } // check aliases var foundNamedKey = aliases[nameOrCode.toLowerCase()]; if (foundNamedKey) { return foundNamedKey === keyCode; } } else if (typeof nameOrCode === 'number') { return nameOrCode === keyCode; } return false; } }; exports = module.exports = keyCode; /** * Get by name * * exports.code['enter'] // => 13 */ var codes = exports.code = exports.codes = { 'backspace': 8, 'tab': 9, 'enter': 13, 'shift': 16, 'ctrl': 17, 'alt': 18, 'pause/break': 19, 'caps lock': 20, 'esc': 27, 'space': 32, 'page up': 33, 'page down': 34, 'end': 35, 'home': 36, 'left': 37, 'up': 38, 'right': 39, 'down': 40, 'insert': 45, 'delete': 46, 'command': 91, 'left command': 91, 'right command': 93, 'numpad *': 106, 'numpad +': 107, 'numpad -': 109, 'numpad .': 110, 'numpad /': 111, 'num lock': 144, 'scroll lock': 145, 'my computer': 182, 'my calculator': 183, ';': 186, '=': 187, ',': 188, '-': 189, '.': 190, '/': 191, '`': 192, '[': 219, '\\': 220, ']': 221, "'": 222 // Helper aliases }; var aliases = exports.aliases = { 'windows': 91, '⇧': 16, '⌥': 18, '⌃': 17, '⌘': 91, 'ctl': 17, 'control': 17, 'option': 18, 'pause': 19, 'break': 19, 'caps': 20, 'return': 13, 'escape': 27, 'spc': 32, 'spacebar': 32, 'pgup': 33, 'pgdn': 34, 'ins': 45, 'del': 46, 'cmd': 91 /*! * Programatically add the following */ // lower case chars }; for (i = 97; i < 123; i++) { codes[String.fromCharCode(i)] = i - 32; } // numbers for (var i = 48; i < 58; i++) { codes[i - 48] = i; } // function keys for (i = 1; i < 13; i++) { codes['f' + i] = i + 111; } // numpad keys for (i = 0; i < 10; i++) { codes['numpad ' + i] = i + 96; } /** * Get by code * * exports.name[13] // => 'Enter' */ var names = exports.names = exports.title = {}; // title for backward compat // Create reverse mapping for (i in codes) { names[codes[i]] = i; } // Add aliases for (var alias in aliases) { codes[alias] = aliases[alias]; } }); var keycode_1 = keycode.code; var keycode_2 = keycode.codes; var keycode_3 = keycode.aliases; var keycode_4 = keycode.names; var keycode_5 = keycode.title; var MODAL_CLASS_NAME = 'vjs-modal-dialog'; /** * The `ModalDialog` displays over the video and its controls, which blocks * interaction with the player until it is closed. * * Modal dialogs include a "Close" button and will close when that button * is activated - or when ESC is pressed anywhere. * * @extends Component */ var ModalDialog = /*#__PURE__*/ function (_Component) { _inheritsLoose(ModalDialog, _Component); /** * Create an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. * * @param {Mixed} [options.content=undefined] * Provide customized content for this modal. * * @param {string} [options.description] * A text description for the modal, primarily for accessibility. * * @param {boolean} [options.fillAlways=false] * Normally, modals are automatically filled only the first time * they open. This tells the modal to refresh its content * every time it opens. * * @param {string} [options.label] * A text label for the modal, primarily for accessibility. * * @param {boolean} [options.pauseOnOpen=true] * If `true`, playback will will be paused if playing when * the modal opens, and resumed when it closes. * * @param {boolean} [options.temporary=true] * If `true`, the modal can only be opened once; it will be * disposed as soon as it's closed. * * @param {boolean} [options.uncloseable=false] * If `true`, the user will not be able to close the modal * through the UI in the normal ways. Programmatic closing is * still possible. */ function ModalDialog(player, options) { var _this; _this = _Component.call(this, player, options) || this; _this.opened_ = _this.hasBeenOpened_ = _this.hasBeenFilled_ = false; _this.closeable(!_this.options_.uncloseable); _this.content(_this.options_.content); // Make sure the contentEl is defined AFTER any children are initialized // because we only want the contents of the modal in the contentEl // (not the UI elements like the close button). _this.contentEl_ = createEl('div', { className: MODAL_CLASS_NAME + "-content" }, { role: 'document' }); _this.descEl_ = createEl('p', { className: MODAL_CLASS_NAME + "-description vjs-control-text", id: _this.el().getAttribute('aria-describedby') }); textContent(_this.descEl_, _this.description()); _this.el_.appendChild(_this.descEl_); _this.el_.appendChild(_this.contentEl_); return _this; } /** * Create the `ModalDialog`'s DOM element * * @return {Element} * The DOM element that gets created. */ var _proto = ModalDialog.prototype; _proto.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: this.buildCSSClass(), tabIndex: -1 }, { 'aria-describedby': this.id() + "_description", 'aria-hidden': 'true', 'aria-label': this.label(), 'role': 'dialog' }); }; _proto.dispose = function dispose() { this.contentEl_ = null; this.descEl_ = null; this.previouslyActiveEl_ = null; _Component.prototype.dispose.call(this); } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ ; _proto.buildCSSClass = function buildCSSClass() { return MODAL_CLASS_NAME + " vjs-hidden " + _Component.prototype.buildCSSClass.call(this); } /** * Returns the label string for this modal. Primarily used for accessibility. * * @return {string} * the localized or raw label of this modal. */ ; _proto.label = function label() { return this.localize(this.options_.label || 'Modal Window'); } /** * Returns the description string for this modal. Primarily used for * accessibility. * * @return {string} * The localized or raw description of this modal. */ ; _proto.description = function description() { var desc = this.options_.description || this.localize('This is a modal window.'); // Append a universal closeability message if the modal is closeable. if (this.closeable()) { desc += ' ' + this.localize('This modal can be closed by pressing the Escape key or activating the close button.'); } return desc; } /** * Opens the modal. * * @fires ModalDialog#beforemodalopen * @fires ModalDialog#modalopen */ ; _proto.open = function open() { if (!this.opened_) { var player = this.player(); /** * Fired just before a `ModalDialog` is opened. * * @event ModalDialog#beforemodalopen * @type {EventTarget~Event} */ this.trigger('beforemodalopen'); this.opened_ = true; // Fill content if the modal has never opened before and // never been filled. if (this.options_.fillAlways || !this.hasBeenOpened_ && !this.hasBeenFilled_) { this.fill(); } // If the player was playing, pause it and take note of its previously // playing state. this.wasPlaying_ = !player.paused(); if (this.options_.pauseOnOpen && this.wasPlaying_) { player.pause(); } this.on('keydown', this.handleKeyDown); // Hide controls and note if they were enabled. this.hadControls_ = player.controls(); player.controls(false); this.show(); this.conditionalFocus_(); this.el().setAttribute('aria-hidden', 'false'); /** * Fired just after a `ModalDialog` is opened. * * @event ModalDialog#modalopen * @type {EventTarget~Event} */ this.trigger('modalopen'); this.hasBeenOpened_ = true; } } /** * If the `ModalDialog` is currently open or closed. * * @param {boolean} [value] * If given, it will open (`true`) or close (`false`) the modal. * * @return {boolean} * the current open state of the modaldialog */ ; _proto.opened = function opened(value) { if (typeof value === 'boolean') { this[value ? 'open' : 'close'](); } return this.opened_; } /** * Closes the modal, does nothing if the `ModalDialog` is * not open. * * @fires ModalDialog#beforemodalclose * @fires ModalDialog#modalclose */ ; _proto.close = function close() { if (!this.opened_) { return; } var player = this.player(); /** * Fired just before a `ModalDialog` is closed. * * @event ModalDialog#beforemodalclose * @type {EventTarget~Event} */ this.trigger('beforemodalclose'); this.opened_ = false; if (this.wasPlaying_ && this.options_.pauseOnOpen) { player.play(); } this.off('keydown', this.handleKeyDown); if (this.hadControls_) { player.controls(true); } this.hide(); this.el().setAttribute('aria-hidden', 'true'); /** * Fired just after a `ModalDialog` is closed. * * @event ModalDialog#modalclose * @type {EventTarget~Event} */ this.trigger('modalclose'); this.conditionalBlur_(); if (this.options_.temporary) { this.dispose(); } } /** * Check to see if the `ModalDialog` is closeable via the UI. * * @param {boolean} [value] * If given as a boolean, it will set the `closeable` option. * * @return {boolean} * Returns the final value of the closable option. */ ; _proto.closeable = function closeable(value) { if (typeof value === 'boolean') { var closeable = this.closeable_ = !!value; var close = this.getChild('closeButton'); // If this is being made closeable and has no close button, add one. if (closeable && !close) { // The close button should be a child of the modal - not its // content element, so temporarily change the content element. var temp = this.contentEl_; this.contentEl_ = this.el_; close = this.addChild('closeButton', { controlText: 'Close Modal Dialog' }); this.contentEl_ = temp; this.on(close, 'close', this.close); } // If this is being made uncloseable and has a close button, remove it. if (!closeable && close) { this.off(close, 'close', this.close); this.removeChild(close); close.dispose(); } } return this.closeable_; } /** * Fill the modal's content element with the modal's "content" option. * The content element will be emptied before this change takes place. */ ; _proto.fill = function fill() { this.fillWith(this.content()); } /** * Fill the modal's content element with arbitrary content. * The content element will be emptied before this change takes place. * * @fires ModalDialog#beforemodalfill * @fires ModalDialog#modalfill * * @param {Mixed} [content] * The same rules apply to this as apply to the `content` option. */ ; _proto.fillWith = function fillWith(content) { var contentEl = this.contentEl(); var parentEl = contentEl.parentNode; var nextSiblingEl = contentEl.nextSibling; /** * Fired just before a `ModalDialog` is filled with content. * * @event ModalDialog#beforemodalfill * @type {EventTarget~Event} */ this.trigger('beforemodalfill'); this.hasBeenFilled_ = true; // Detach the content element from the DOM before performing // manipulation to avoid modifying the live DOM multiple times. parentEl.removeChild(contentEl); this.empty(); insertContent(contentEl, content); /** * Fired just after a `ModalDialog` is filled with content. * * @event ModalDialog#modalfill * @type {EventTarget~Event} */ this.trigger('modalfill'); // Re-inject the re-filled content element. if (nextSiblingEl) { parentEl.insertBefore(contentEl, nextSiblingEl); } else { parentEl.appendChild(contentEl); } // make sure that the close button is last in the dialog DOM var closeButton = this.getChild('closeButton'); if (closeButton) { parentEl.appendChild(closeButton.el_); } } /** * Empties the content element. This happens anytime the modal is filled. * * @fires ModalDialog#beforemodalempty * @fires ModalDialog#modalempty */ ; _proto.empty = function empty() { /** * Fired just before a `ModalDialog` is emptied. * * @event ModalDialog#beforemodalempty * @type {EventTarget~Event} */ this.trigger('beforemodalempty'); emptyEl(this.contentEl()); /** * Fired just after a `ModalDialog` is emptied. * * @event ModalDialog#modalempty * @type {EventTarget~Event} */ this.trigger('modalempty'); } /** * Gets or sets the modal content, which gets normalized before being * rendered into the DOM. * * This does not update the DOM or fill the modal, but it is called during * that process. * * @param {Mixed} [value] * If defined, sets the internal content value to be used on the * next call(s) to `fill`. This value is normalized before being * inserted. To "clear" the internal content value, pass `null`. * * @return {Mixed} * The current content of the modal dialog */ ; _proto.content = function content(value) { if (typeof value !== 'undefined') { this.content_ = value; } return this.content_; } /** * conditionally focus the modal dialog if focus was previously on the player. * * @private */ ; _proto.conditionalFocus_ = function conditionalFocus_() { var activeEl = document.activeElement; var playerEl = this.player_.el_; this.previouslyActiveEl_ = null; if (playerEl.contains(activeEl) || playerEl === activeEl) { this.previouslyActiveEl_ = activeEl; this.focus(); } } /** * conditionally blur the element and refocus the last focused element * * @private */ ; _proto.conditionalBlur_ = function conditionalBlur_() { if (this.previouslyActiveEl_) { this.previouslyActiveEl_.focus(); this.previouslyActiveEl_ = null; } } /** * Keydown handler. Attached when modal is focused. * * @listens keydown */ ; _proto.handleKeyDown = function handleKeyDown(event) { // Do not allow keydowns to reach out of the modal dialog. event.stopPropagation(); if (keycode.isEventKey(event, 'Escape') && this.closeable()) { event.preventDefault(); this.close(); return; } // exit early if it isn't a tab key if (!keycode.isEventKey(event, 'Tab')) { return; } var focusableEls = this.focusableEls_(); var activeEl = this.el_.querySelector(':focus'); var focusIndex; for (var i = 0; i < focusableEls.length; i++) { if (activeEl === focusableEls[i]) { focusIndex = i; break; } } if (document.activeElement === this.el_) { focusIndex = 0; } if (event.shiftKey && focusIndex === 0) { focusableEls[focusableEls.length - 1].focus(); event.preventDefault(); } else if (!event.shiftKey && focusIndex === focusableEls.length - 1) { focusableEls[0].focus(); event.preventDefault(); } } /** * get all focusable elements * * @private */ ; _proto.focusableEls_ = function focusableEls_() { var allChildren = this.el_.querySelectorAll('*'); return Array.prototype.filter.call(allChildren, function (child) { return (child instanceof window$1.HTMLAnchorElement || child instanceof window$1.HTMLAreaElement) && child.hasAttribute('href') || (child instanceof window$1.HTMLInputElement || child instanceof window$1.HTMLSelectElement || child instanceof window$1.HTMLTextAreaElement || child instanceof window$1.HTMLButtonElement) && !child.hasAttribute('disabled') || child instanceof window$1.HTMLIFrameElement || child instanceof window$1.HTMLObjectElement || child instanceof window$1.HTMLEmbedElement || child.hasAttribute('tabindex') && child.getAttribute('tabindex') !== -1 || child.hasAttribute('contenteditable'); }); }; return ModalDialog; }(Component); /** * Default options for `ModalDialog` default options. * * @type {Object} * @private */ ModalDialog.prototype.options_ = { pauseOnOpen: true, temporary: true }; Component.registerComponent('ModalDialog', ModalDialog); /** * Common functionaliy between {@link TextTrackList}, {@link AudioTrackList}, and * {@link VideoTrackList} * * @extends EventTarget */ var TrackList = /*#__PURE__*/ function (_EventTarget) { _inheritsLoose(TrackList, _EventTarget); /** * Create an instance of this class * * @param {Track[]} tracks * A list of tracks to initialize the list with. * * @abstract */ function TrackList(tracks) { var _this; if (tracks === void 0) { tracks = []; } _this = _EventTarget.call(this) || this; _this.tracks_ = []; /** * @memberof TrackList * @member {number} length * The current number of `Track`s in the this Trackist. * @instance */ Object.defineProperty(_assertThisInitialized(_this), 'length', { get: function get() { return this.tracks_.length; } }); for (var i = 0; i < tracks.length; i++) { _this.addTrack(tracks[i]); } return _this; } /** * Add a {@link Track} to the `TrackList` * * @param {Track} track * The audio, video, or text track to add to the list. * * @fires TrackList#addtrack */ var _proto = TrackList.prototype; _proto.addTrack = function addTrack(track) { var index = this.tracks_.length; if (!('' + index in this)) { Object.defineProperty(this, index, { get: function get() { return this.tracks_[index]; } }); } // Do not add duplicate tracks if (this.tracks_.indexOf(track) === -1) { this.tracks_.push(track); /** * Triggered when a track is added to a track list. * * @event TrackList#addtrack * @type {EventTarget~Event} * @property {Track} track * A reference to track that was added. */ this.trigger({ track: track, type: 'addtrack', target: this }); } } /** * Remove a {@link Track} from the `TrackList` * * @param {Track} rtrack * The audio, video, or text track to remove from the list. * * @fires TrackList#removetrack */ ; _proto.removeTrack = function removeTrack(rtrack) { var track; for (var i = 0, l = this.length; i < l; i++) { if (this[i] === rtrack) { track = this[i]; if (track.off) { track.off(); } this.tracks_.splice(i, 1); break; } } if (!track) { return; } /** * Triggered when a track is removed from track list. * * @event TrackList#removetrack * @type {EventTarget~Event} * @property {Track} track * A reference to track that was removed. */ this.trigger({ track: track, type: 'removetrack', target: this }); } /** * Get a Track from the TrackList by a tracks id * * @param {string} id - the id of the track to get * @method getTrackById * @return {Track} * @private */ ; _proto.getTrackById = function getTrackById(id) { var result = null; for (var i = 0, l = this.length; i < l; i++) { var track = this[i]; if (track.id === id) { result = track; break; } } return result; }; return TrackList; }(EventTarget); /** * Triggered when a different track is selected/enabled. * * @event TrackList#change * @type {EventTarget~Event} */ /** * Events that can be called with on + eventName. See {@link EventHandler}. * * @property {Object} TrackList#allowedEvents_ * @private */ TrackList.prototype.allowedEvents_ = { change: 'change', addtrack: 'addtrack', removetrack: 'removetrack' }; // emulate attribute EventHandler support to allow for feature detection for (var event in TrackList.prototype.allowedEvents_) { TrackList.prototype['on' + event] = null; } /** * Anywhere we call this function we diverge from the spec * as we only support one enabled audiotrack at a time * * @param {AudioTrackList} list * list to work on * * @param {AudioTrack} track * The track to skip * * @private */ var disableOthers = function disableOthers(list, track) { for (var i = 0; i < list.length; i++) { if (!Object.keys(list[i]).length || track.id === list[i].id) { continue; } // another audio track is enabled, disable it list[i].enabled = false; } }; /** * The current list of {@link AudioTrack} for a media file. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist} * @extends TrackList */ var AudioTrackList = /*#__PURE__*/ function (_TrackList) { _inheritsLoose(AudioTrackList, _TrackList); /** * Create an instance of this class. * * @param {AudioTrack[]} [tracks=[]] * A list of `AudioTrack` to instantiate the list with. */ function AudioTrackList(tracks) { var _this; if (tracks === void 0) { tracks = []; } // make sure only 1 track is enabled // sorted from last index to first index for (var i = tracks.length - 1; i >= 0; i--) { if (tracks[i].enabled) { disableOthers(tracks, tracks[i]); break; } } _this = _TrackList.call(this, tracks) || this; _this.changing_ = false; return _this; } /** * Add an {@link AudioTrack} to the `AudioTrackList`. * * @param {AudioTrack} track * The AudioTrack to add to the list * * @fires TrackList#addtrack */ var _proto = AudioTrackList.prototype; _proto.addTrack = function addTrack(track) { var _this2 = this; if (track.enabled) { disableOthers(this, track); } _TrackList.prototype.addTrack.call(this, track); // native tracks don't have this if (!track.addEventListener) { return; } track.enabledChange_ = function () { // when we are disabling other tracks (since we don't support // more than one track at a time) we will set changing_ // to true so that we don't trigger additional change events if (_this2.changing_) { return; } _this2.changing_ = true; disableOthers(_this2, track); _this2.changing_ = false; _this2.trigger('change'); }; /** * @listens AudioTrack#enabledchange * @fires TrackList#change */ track.addEventListener('enabledchange', track.enabledChange_); }; _proto.removeTrack = function removeTrack(rtrack) { _TrackList.prototype.removeTrack.call(this, rtrack); if (rtrack.removeEventListener && rtrack.enabledChange_) { rtrack.removeEventListener('enabledchange', rtrack.enabledChange_); rtrack.enabledChange_ = null; } }; return AudioTrackList; }(TrackList); /** * Un-select all other {@link VideoTrack}s that are selected. * * @param {VideoTrackList} list * list to work on * * @param {VideoTrack} track * The track to skip * * @private */ var disableOthers$1 = function disableOthers(list, track) { for (var i = 0; i < list.length; i++) { if (!Object.keys(list[i]).length || track.id === list[i].id) { continue; } // another video track is enabled, disable it list[i].selected = false; } }; /** * The current list of {@link VideoTrack} for a video. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist} * @extends TrackList */ var VideoTrackList = /*#__PURE__*/ function (_TrackList) { _inheritsLoose(VideoTrackList, _TrackList); /** * Create an instance of this class. * * @param {VideoTrack[]} [tracks=[]] * A list of `VideoTrack` to instantiate the list with. */ function VideoTrackList(tracks) { var _this; if (tracks === void 0) { tracks = []; } // make sure only 1 track is enabled // sorted from last index to first index for (var i = tracks.length - 1; i >= 0; i--) { if (tracks[i].selected) { disableOthers$1(tracks, tracks[i]); break; } } _this = _TrackList.call(this, tracks) || this; _this.changing_ = false; /** * @member {number} VideoTrackList#selectedIndex * The current index of the selected {@link VideoTrack`}. */ Object.defineProperty(_assertThisInitialized(_this), 'selectedIndex', { get: function get() { for (var _i = 0; _i < this.length; _i++) { if (this[_i].selected) { return _i; } } return -1; }, set: function set() {} }); return _this; } /** * Add a {@link VideoTrack} to the `VideoTrackList`. * * @param {VideoTrack} track * The VideoTrack to add to the list * * @fires TrackList#addtrack */ var _proto = VideoTrackList.prototype; _proto.addTrack = function addTrack(track) { var _this2 = this; if (track.selected) { disableOthers$1(this, track); } _TrackList.prototype.addTrack.call(this, track); // native tracks don't have this if (!track.addEventListener) { return; } track.selectedChange_ = function () { if (_this2.changing_) { return; } _this2.changing_ = true; disableOthers$1(_this2, track); _this2.changing_ = false; _this2.trigger('change'); }; /** * @listens VideoTrack#selectedchange * @fires TrackList#change */ track.addEventListener('selectedchange', track.selectedChange_); }; _proto.removeTrack = function removeTrack(rtrack) { _TrackList.prototype.removeTrack.call(this, rtrack); if (rtrack.removeEventListener && rtrack.selectedChange_) { rtrack.removeEventListener('selectedchange', rtrack.selectedChange_); rtrack.selectedChange_ = null; } }; return VideoTrackList; }(TrackList); /** * The current list of {@link TextTrack} for a media file. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist} * @extends TrackList */ var TextTrackList = /*#__PURE__*/ function (_TrackList) { _inheritsLoose(TextTrackList, _TrackList); function TextTrackList() { return _TrackList.apply(this, arguments) || this; } var _proto = TextTrackList.prototype; /** * Add a {@link TextTrack} to the `TextTrackList` * * @param {TextTrack} track * The text track to add to the list. * * @fires TrackList#addtrack */ _proto.addTrack = function addTrack(track) { var _this = this; _TrackList.prototype.addTrack.call(this, track); if (!this.queueChange_) { this.queueChange_ = function () { return _this.queueTrigger('change'); }; } if (!this.triggerSelectedlanguagechange) { this.triggerSelectedlanguagechange_ = function () { return _this.trigger('selectedlanguagechange'); }; } /** * @listens TextTrack#modechange * @fires TrackList#change */ track.addEventListener('modechange', this.queueChange_); var nonLanguageTextTrackKind = ['metadata', 'chapters']; if (nonLanguageTextTrackKind.indexOf(track.kind) === -1) { track.addEventListener('modechange', this.triggerSelectedlanguagechange_); } }; _proto.removeTrack = function removeTrack(rtrack) { _TrackList.prototype.removeTrack.call(this, rtrack); // manually remove the event handlers we added if (rtrack.removeEventListener) { if (this.queueChange_) { rtrack.removeEventListener('modechange', this.queueChange_); } if (this.selectedlanguagechange_) { rtrack.removeEventListener('modechange', this.triggerSelectedlanguagechange_); } } }; return TextTrackList; }(TrackList); /** * @file html-track-element-list.js */ /** * The current list of {@link HtmlTrackElement}s. */ var HtmlTrackElementList = /*#__PURE__*/ function () { /** * Create an instance of this class. * * @param {HtmlTrackElement[]} [tracks=[]] * A list of `HtmlTrackElement` to instantiate the list with. */ function HtmlTrackElementList(trackElements) { if (trackElements === void 0) { trackElements = []; } this.trackElements_ = []; /** * @memberof HtmlTrackElementList * @member {number} length * The current number of `Track`s in the this Trackist. * @instance */ Object.defineProperty(this, 'length', { get: function get() { return this.trackElements_.length; } }); for (var i = 0, length = trackElements.length; i < length; i++) { this.addTrackElement_(trackElements[i]); } } /** * Add an {@link HtmlTrackElement} to the `HtmlTrackElementList` * * @param {HtmlTrackElement} trackElement * The track element to add to the list. * * @private */ var _proto = HtmlTrackElementList.prototype; _proto.addTrackElement_ = function addTrackElement_(trackElement) { var index = this.trackElements_.length; if (!('' + index in this)) { Object.defineProperty(this, index, { get: function get() { return this.trackElements_[index]; } }); } // Do not add duplicate elements if (this.trackElements_.indexOf(trackElement) === -1) { this.trackElements_.push(trackElement); } } /** * Get an {@link HtmlTrackElement} from the `HtmlTrackElementList` given an * {@link TextTrack}. * * @param {TextTrack} track * The track associated with a track element. * * @return {HtmlTrackElement|undefined} * The track element that was found or undefined. * * @private */ ; _proto.getTrackElementByTrack_ = function getTrackElementByTrack_(track) { var trackElement_; for (var i = 0, length = this.trackElements_.length; i < length; i++) { if (track === this.trackElements_[i].track) { trackElement_ = this.trackElements_[i]; break; } } return trackElement_; } /** * Remove a {@link HtmlTrackElement} from the `HtmlTrackElementList` * * @param {HtmlTrackElement} trackElement * The track element to remove from the list. * * @private */ ; _proto.removeTrackElement_ = function removeTrackElement_(trackElement) { for (var i = 0, length = this.trackElements_.length; i < length; i++) { if (trackElement === this.trackElements_[i]) { if (this.trackElements_[i].track && typeof this.trackElements_[i].track.off === 'function') { this.trackElements_[i].track.off(); } if (typeof this.trackElements_[i].off === 'function') { this.trackElements_[i].off(); } this.trackElements_.splice(i, 1); break; } } }; return HtmlTrackElementList; }(); /** * @file text-track-cue-list.js */ /** * @typedef {Object} TextTrackCueList~TextTrackCue * * @property {string} id * The unique id for this text track cue * * @property {number} startTime * The start time for this text track cue * * @property {number} endTime * The end time for this text track cue * * @property {boolean} pauseOnExit * Pause when the end time is reached if true. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcue} */ /** * A List of TextTrackCues. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist} */ var TextTrackCueList = /*#__PURE__*/ function () { /** * Create an instance of this class.. * * @param {Array} cues * A list of cues to be initialized with */ function TextTrackCueList(cues) { TextTrackCueList.prototype.setCues_.call(this, cues); /** * @memberof TextTrackCueList * @member {number} length * The current number of `TextTrackCue`s in the TextTrackCueList. * @instance */ Object.defineProperty(this, 'length', { get: function get() { return this.length_; } }); } /** * A setter for cues in this list. Creates getters * an an index for the cues. * * @param {Array} cues * An array of cues to set * * @private */ var _proto = TextTrackCueList.prototype; _proto.setCues_ = function setCues_(cues) { var oldLength = this.length || 0; var i = 0; var l = cues.length; this.cues_ = cues; this.length_ = cues.length; var defineProp = function defineProp(index) { if (!('' + index in this)) { Object.defineProperty(this, '' + index, { get: function get() { return this.cues_[index]; } }); } }; if (oldLength < l) { i = oldLength; for (; i < l; i++) { defineProp.call(this, i); } } } /** * Get a `TextTrackCue` that is currently in the `TextTrackCueList` by id. * * @param {string} id * The id of the cue that should be searched for. * * @return {TextTrackCueList~TextTrackCue|null} * A single cue or null if none was found. */ ; _proto.getCueById = function getCueById(id) { var result = null; for (var i = 0, l = this.length; i < l; i++) { var cue = this[i]; if (cue.id === id) { result = cue; break; } } return result; }; return TextTrackCueList; }(); /** * @file track-kinds.js */ /** * All possible `VideoTrackKind`s * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-videotrack-kind * @typedef VideoTrack~Kind * @enum */ var VideoTrackKind = { alternative: 'alternative', captions: 'captions', main: 'main', sign: 'sign', subtitles: 'subtitles', commentary: 'commentary' }; /** * All possible `AudioTrackKind`s * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-audiotrack-kind * @typedef AudioTrack~Kind * @enum */ var AudioTrackKind = { 'alternative': 'alternative', 'descriptions': 'descriptions', 'main': 'main', 'main-desc': 'main-desc', 'translation': 'translation', 'commentary': 'commentary' }; /** * All possible `TextTrackKind`s * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-texttrack-kind * @typedef TextTrack~Kind * @enum */ var TextTrackKind = { subtitles: 'subtitles', captions: 'captions', descriptions: 'descriptions', chapters: 'chapters', metadata: 'metadata' }; /** * All possible `TextTrackMode`s * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode * @typedef TextTrack~Mode * @enum */ var TextTrackMode = { disabled: 'disabled', hidden: 'hidden', showing: 'showing' }; /** * A Track class that contains all of the common functionality for {@link AudioTrack}, * {@link VideoTrack}, and {@link TextTrack}. * * > Note: This class should not be used directly * * @see {@link https://html.spec.whatwg.org/multipage/embedded-content.html} * @extends EventTarget * @abstract */ var Track = /*#__PURE__*/ function (_EventTarget) { _inheritsLoose(Track, _EventTarget); /** * Create an instance of this class. * * @param {Object} [options={}] * Object of option names and values * * @param {string} [options.kind=''] * A valid kind for the track type you are creating. * * @param {string} [options.id='vjs_track_' + Guid.newGUID()] * A unique id for this AudioTrack. * * @param {string} [options.label=''] * The menu label for this track. * * @param {string} [options.language=''] * A valid two character language code. * * @abstract */ function Track(options) { var _this; if (options === void 0) { options = {}; } _this = _EventTarget.call(this) || this; var trackProps = { id: options.id || 'vjs_track_' + newGUID(), kind: options.kind || '', label: options.label || '', language: options.language || '' }; /** * @memberof Track * @member {string} id * The id of this track. Cannot be changed after creation. * @instance * * @readonly */ /** * @memberof Track * @member {string} kind * The kind of track that this is. Cannot be changed after creation. * @instance * * @readonly */ /** * @memberof Track * @member {string} label * The label of this track. Cannot be changed after creation. * @instance * * @readonly */ /** * @memberof Track * @member {string} language * The two letter language code for this track. Cannot be changed after * creation. * @instance * * @readonly */ var _loop = function _loop(key) { Object.defineProperty(_assertThisInitialized(_this), key, { get: function get() { return trackProps[key]; }, set: function set() {} }); }; for (var key in trackProps) { _loop(key); } return _this; } return Track; }(EventTarget); /** * @file url.js * @module url */ /** * @typedef {Object} url:URLObject * * @property {string} protocol * The protocol of the url that was parsed. * * @property {string} hostname * The hostname of the url that was parsed. * * @property {string} port * The port of the url that was parsed. * * @property {string} pathname * The pathname of the url that was parsed. * * @property {string} search * The search query of the url that was parsed. * * @property {string} hash * The hash of the url that was parsed. * * @property {string} host * The host of the url that was parsed. */ /** * Resolve and parse the elements of a URL. * * @function * @param {String} url * The url to parse * * @return {url:URLObject} * An object of url details */ var parseUrl = function parseUrl(url) { var props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host']; // add the url to an anchor and let the browser parse the URL var a = document.createElement('a'); a.href = url; // IE8 (and 9?) Fix // ie8 doesn't parse the URL correctly until the anchor is actually // added to the body, and an innerHTML is needed to trigger the parsing var addToBody = a.host === '' && a.protocol !== 'file:'; var div; if (addToBody) { div = document.createElement('div'); div.innerHTML = "<a href=\"" + url + "\"></a>"; a = div.firstChild; // prevent the div from affecting layout div.setAttribute('style', 'display:none; position:absolute;'); document.body.appendChild(div); } // Copy the specific URL properties to a new object // This is also needed for IE8 because the anchor loses its // properties when it's removed from the dom var details = {}; for (var i = 0; i < props.length; i++) { details[props[i]] = a[props[i]]; } // IE9 adds the port to the host property unlike everyone else. If // a port identifier is added for standard ports, strip it. if (details.protocol === 'http:') { details.host = details.host.replace(/:80$/, ''); } if (details.protocol === 'https:') { details.host = details.host.replace(/:443$/, ''); } if (!details.protocol) { details.protocol = window$1.location.protocol; } if (addToBody) { document.body.removeChild(div); } return details; }; /** * Get absolute version of relative URL. Used to tell Flash the correct URL. * * @function * @param {string} url * URL to make absolute * * @return {string} * Absolute URL * * @see http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue */ var getAbsoluteURL = function getAbsoluteURL(url) { // Check if absolute URL if (!url.match(/^https?:\/\//)) { // Convert to absolute URL. Flash hosted off-site needs an absolute URL. var div = document.createElement('div'); div.innerHTML = "<a href=\"" + url + "\">x</a>"; url = div.firstChild.href; } return url; }; /** * Returns the extension of the passed file name. It will return an empty string * if passed an invalid path. * * @function * @param {string} path * The fileName path like '/path/to/file.mp4' * * @return {string} * The extension in lower case or an empty string if no * extension could be found. */ var getFileExtension = function getFileExtension(path) { if (typeof path === 'string') { var splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/; var pathParts = splitPathRe.exec(path); if (pathParts) { return pathParts.pop().toLowerCase(); } } return ''; }; /** * Returns whether the url passed is a cross domain request or not. * * @function * @param {string} url * The url to check. * * @return {boolean} * Whether it is a cross domain request or not. */ var isCrossOrigin = function isCrossOrigin(url) { var winLoc = window$1.location; var urlInfo = parseUrl(url); // IE8 protocol relative urls will return ':' for protocol var srcProtocol = urlInfo.protocol === ':' ? winLoc.protocol : urlInfo.protocol; // Check if url is for another domain/origin // IE8 doesn't know location.origin, so we won't rely on it here var crossOrigin = srcProtocol + urlInfo.host !== winLoc.protocol + winLoc.host; return crossOrigin; }; var Url = /*#__PURE__*/Object.freeze({ parseUrl: parseUrl, getAbsoluteURL: getAbsoluteURL, getFileExtension: getFileExtension, isCrossOrigin: isCrossOrigin }); var isFunction_1 = isFunction; var toString$1 = Object.prototype.toString; function isFunction(fn) { var string = toString$1.call(fn); return string === '[object Function]' || typeof fn === 'function' && string !== '[object RegExp]' || typeof window !== 'undefined' && ( // IE8 and below fn === window.setTimeout || fn === window.alert || fn === window.confirm || fn === window.prompt); } /* eslint no-invalid-this: 1 */ var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; var slice = Array.prototype.slice; var toStr = Object.prototype.toString; var funcType = '[object Function]'; var implementation = function bind(that) { var target = this; if (typeof target !== 'function' || toStr.call(target) !== funcType) { throw new TypeError(ERROR_MESSAGE + target); } var args = slice.call(arguments, 1); var bound; var binder = function binder() { if (this instanceof bound) { var result = target.apply(this, args.concat(slice.call(arguments))); if (Object(result) === result) { return result; } return this; } else { return target.apply(that, args.concat(slice.call(arguments))); } }; var boundLength = Math.max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs.push('$' + i); } bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); if (target.prototype) { var Empty = function Empty() {}; Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; var functionBind = Function.prototype.bind || implementation; var toStr$1 = Object.prototype.toString; var isArguments = function isArguments(value) { var str = toStr$1.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr$1.call(value.callee) === '[object Function]'; } return isArgs; }; var keysShim; if (!Object.keys) { // modified from https://github.com/es-shims/es5-shim var has = Object.prototype.hasOwnProperty; var toStr$2 = Object.prototype.toString; var isArgs = isArguments; // eslint-disable-line global-require var isEnumerable = Object.prototype.propertyIsEnumerable; var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); var dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor']; var equalsConstructorPrototype = function equalsConstructorPrototype(o) { var ctor = o.constructor; return ctor && ctor.prototype === o; }; var excludedKeys = { $applicationCache: true, $console: true, $external: true, $frame: true, $frameElement: true, $frames: true, $innerHeight: true, $innerWidth: true, $onmozfullscreenchange: true, $onmozfullscreenerror: true, $outerHeight: true, $outerWidth: true, $pageXOffset: true, $pageYOffset: true, $parent: true, $scrollLeft: true, $scrollTop: true, $scrollX: true, $scrollY: true, $self: true, $webkitIndexedDB: true, $webkitStorageInfo: true, $window: true }; var hasAutomationEqualityBug = function () { /* global window */ if (typeof window === 'undefined') { return false; } for (var k in window) { try { if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { try { equalsConstructorPrototype(window[k]); } catch (e) { return true; } } } catch (e) { return true; } } return false; }(); var equalsConstructorPrototypeIfNotBuggy = function equalsConstructorPrototypeIfNotBuggy(o) { /* global window */ if (typeof window === 'undefined' || !hasAutomationEqualityBug) { return equalsConstructorPrototype(o); } try { return equalsConstructorPrototype(o); } catch (e) { return false; } }; keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr$2.call(object) === '[object Function]'; var isArguments = isArgs(object); var isString = isObject && toStr$2.call(object) === '[object String]'; var theKeys = []; if (!isObject && !isFunction && !isArguments) { throw new TypeError('Object.keys called on a non-object'); } var skipProto = hasProtoEnumBug && isFunction; if (isString && object.length > 0 && !has.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && has.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; } var implementation$1 = keysShim; var slice$1 = Array.prototype.slice; var origKeys = Object.keys; var keysShim$1 = origKeys ? function keys(o) { return origKeys(o); } : implementation$1; var originalKeys = Object.keys; keysShim$1.shim = function shimObjectKeys() { if (Object.keys) { var keysWorksWithArguments = function () { // Safari 5.0 bug var args = Object.keys(arguments); return args && args.length === arguments.length; }(1, 2); if (!keysWorksWithArguments) { Object.keys = function keys(object) { // eslint-disable-line func-name-matching if (isArguments(object)) { return originalKeys(slice$1.call(object)); } return originalKeys(object); }; } } else { Object.keys = keysShim$1; } return Object.keys || keysShim$1; }; var objectKeys = keysShim$1; var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; var toStr$3 = Object.prototype.toString; var concat = Array.prototype.concat; var origDefineProperty = Object.defineProperty; var isFunction$1 = function isFunction(fn) { return typeof fn === 'function' && toStr$3.call(fn) === '[object Function]'; }; var arePropertyDescriptorsSupported = function arePropertyDescriptorsSupported() { var obj = {}; try { origDefineProperty(obj, 'x', { enumerable: false, value: obj }); // eslint-disable-next-line no-unused-vars, no-restricted-syntax for (var _ in obj) { // jscs:ignore disallowUnusedVariables return false; } return obj.x === obj; } catch (e) { /* this is IE 8. */ return false; } }; var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported(); var defineProperty = function defineProperty(object, name, value, predicate) { if (name in object && (!isFunction$1(predicate) || !predicate())) { return; } if (supportsDescriptors) { origDefineProperty(object, name, { configurable: true, enumerable: false, value: value, writable: true }); } else { object[name] = value; } }; var defineProperties = function defineProperties(object, map) { var predicates = arguments.length > 2 ? arguments[2] : {}; var props = objectKeys(map); if (hasSymbols) { props = concat.call(props, Object.getOwnPropertySymbols(map)); } for (var i = 0; i < props.length; i += 1) { defineProperty(object, props[i], map[props[i]], predicates[props[i]]); } }; defineProperties.supportsDescriptors = !!supportsDescriptors; var defineProperties_1 = defineProperties; /* globals Set, Map, WeakSet, WeakMap, Promise, Symbol, Proxy, Atomics, SharedArrayBuffer, ArrayBuffer, DataView, Uint8Array, Float32Array, Float64Array, Int8Array, Int16Array, Int32Array, Uint8ClampedArray, Uint16Array, Uint32Array, */ var undefined$1; // eslint-disable-line no-shadow-restricted-names var ThrowTypeError = Object.getOwnPropertyDescriptor ? function () { return Object.getOwnPropertyDescriptor(arguments, 'callee').get; }() : function () { throw new TypeError(); }; var hasSymbols$1 = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol'; var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto var generatorFunction = undefined$1; var asyncFunction = undefined$1; var asyncGenFunction = undefined$1; var TypedArray = typeof Uint8Array === 'undefined' ? undefined$1 : getProto(Uint8Array); var INTRINSICS = { '$ %Array%': Array, '$ %ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined$1 : ArrayBuffer, '$ %ArrayBufferPrototype%': typeof ArrayBuffer === 'undefined' ? undefined$1 : ArrayBuffer.prototype, '$ %ArrayIteratorPrototype%': hasSymbols$1 ? getProto([][Symbol.iterator]()) : undefined$1, '$ %ArrayPrototype%': Array.prototype, '$ %ArrayProto_entries%': Array.prototype.entries, '$ %ArrayProto_forEach%': Array.prototype.forEach, '$ %ArrayProto_keys%': Array.prototype.keys, '$ %ArrayProto_values%': Array.prototype.values, '$ %AsyncFromSyncIteratorPrototype%': undefined$1, '$ %AsyncFunction%': asyncFunction, '$ %AsyncFunctionPrototype%': undefined$1, '$ %AsyncGenerator%': undefined$1, '$ %AsyncGeneratorFunction%': asyncGenFunction, '$ %AsyncGeneratorPrototype%': undefined$1, '$ %AsyncIteratorPrototype%': undefined$1, '$ %Atomics%': typeof Atomics === 'undefined' ? undefined$1 : Atomics, '$ %Boolean%': Boolean, '$ %BooleanPrototype%': Boolean.prototype, '$ %DataView%': typeof DataView === 'undefined' ? undefined$1 : DataView, '$ %DataViewPrototype%': typeof DataView === 'undefined' ? undefined$1 : DataView.prototype, '$ %Date%': Date, '$ %DatePrototype%': Date.prototype, '$ %decodeURI%': decodeURI, '$ %decodeURIComponent%': decodeURIComponent, '$ %encodeURI%': encodeURI, '$ %encodeURIComponent%': encodeURIComponent, '$ %Error%': Error, '$ %ErrorPrototype%': Error.prototype, '$ %eval%': eval, // eslint-disable-line no-eval '$ %EvalError%': EvalError, '$ %EvalErrorPrototype%': EvalError.prototype, '$ %Float32Array%': typeof Float32Array === 'undefined' ? undefined$1 : Float32Array, '$ %Float32ArrayPrototype%': typeof Float32Array === 'undefined' ? undefined$1 : Float32Array.prototype, '$ %Float64Array%': typeof Float64Array === 'undefined' ? undefined$1 : Float64Array, '$ %Float64ArrayPrototype%': typeof Float64Array === 'undefined' ? undefined$1 : Float64Array.prototype, '$ %Function%': Function, '$ %FunctionPrototype%': Function.prototype, '$ %Generator%': undefined$1, '$ %GeneratorFunction%': generatorFunction, '$ %GeneratorPrototype%': undefined$1, '$ %Int8Array%': typeof Int8Array === 'undefined' ? undefined$1 : Int8Array, '$ %Int8ArrayPrototype%': typeof Int8Array === 'undefined' ? undefined$1 : Int8Array.prototype, '$ %Int16Array%': typeof Int16Array === 'undefined' ? undefined$1 : Int16Array, '$ %Int16ArrayPrototype%': typeof Int16Array === 'undefined' ? undefined$1 : Int8Array.prototype, '$ %Int32Array%': typeof Int32Array === 'undefined' ? undefined$1 : Int32Array, '$ %Int32ArrayPrototype%': typeof Int32Array === 'undefined' ? undefined$1 : Int32Array.prototype, '$ %isFinite%': isFinite, '$ %isNaN%': isNaN, '$ %IteratorPrototype%': hasSymbols$1 ? getProto(getProto([][Symbol.iterator]())) : undefined$1, '$ %JSON%': JSON, '$ %JSONParse%': JSON.parse, '$ %Map%': typeof Map === 'undefined' ? undefined$1 : Map, '$ %MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols$1 ? undefined$1 : getProto(new Map()[Symbol.iterator]()), '$ %MapPrototype%': typeof Map === 'undefined' ? undefined$1 : Map.prototype, '$ %Math%': Math, '$ %Number%': Number, '$ %NumberPrototype%': Number.prototype, '$ %Object%': Object, '$ %ObjectPrototype%': Object.prototype, '$ %ObjProto_toString%': Object.prototype.toString, '$ %ObjProto_valueOf%': Object.prototype.valueOf, '$ %parseFloat%': parseFloat, '$ %parseInt%': parseInt, '$ %Promise%': typeof Promise === 'undefined' ? undefined$1 : Promise, '$ %PromisePrototype%': typeof Promise === 'undefined' ? undefined$1 : Promise.prototype, '$ %PromiseProto_then%': typeof Promise === 'undefined' ? undefined$1 : Promise.prototype.then, '$ %Promise_all%': typeof Promise === 'undefined' ? undefined$1 : Promise.all, '$ %Promise_reject%': typeof Promise === 'undefined' ? undefined$1 : Promise.reject, '$ %Promise_resolve%': typeof Promise === 'undefined' ? undefined$1 : Promise.resolve, '$ %Proxy%': typeof Proxy === 'undefined' ? undefined$1 : Proxy, '$ %RangeError%': RangeError, '$ %RangeErrorPrototype%': RangeError.prototype, '$ %ReferenceError%': ReferenceError, '$ %ReferenceErrorPrototype%': ReferenceError.prototype, '$ %Reflect%': typeof Reflect === 'undefined' ? undefined$1 : Reflect, '$ %RegExp%': RegExp, '$ %RegExpPrototype%': RegExp.prototype, '$ %Set%': typeof Set === 'undefined' ? undefined$1 : Set, '$ %SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols$1 ? undefined$1 : getProto(new Set()[Symbol.iterator]()), '$ %SetPrototype%': typeof Set === 'undefined' ? undefined$1 : Set.prototype, '$ %SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined$1 : SharedArrayBuffer, '$ %SharedArrayBufferPrototype%': typeof SharedArrayBuffer === 'undefined' ? undefined$1 : SharedArrayBuffer.prototype, '$ %String%': String, '$ %StringIteratorPrototype%': hasSymbols$1 ? getProto(''[Symbol.iterator]()) : undefined$1, '$ %StringPrototype%': String.prototype, '$ %Symbol%': hasSymbols$1 ? Symbol : undefined$1, '$ %SymbolPrototype%': hasSymbols$1 ? Symbol.prototype : undefined$1, '$ %SyntaxError%': SyntaxError, '$ %SyntaxErrorPrototype%': SyntaxError.prototype, '$ %ThrowTypeError%': ThrowTypeError, '$ %TypedArray%': TypedArray, '$ %TypedArrayPrototype%': TypedArray ? TypedArray.prototype : undefined$1, '$ %TypeError%': TypeError, '$ %TypeErrorPrototype%': TypeError.prototype, '$ %Uint8Array%': typeof Uint8Array === 'undefined' ? undefined$1 : Uint8Array, '$ %Uint8ArrayPrototype%': typeof Uint8Array === 'undefined' ? undefined$1 : Uint8Array.prototype, '$ %Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined$1 : Uint8ClampedArray, '$ %Uint8ClampedArrayPrototype%': typeof Uint8ClampedArray === 'undefined' ? undefined$1 : Uint8ClampedArray.prototype, '$ %Uint16Array%': typeof Uint16Array === 'undefined' ? undefined$1 : Uint16Array, '$ %Uint16ArrayPrototype%': typeof Uint16Array === 'undefined' ? undefined$1 : Uint16Array.prototype, '$ %Uint32Array%': typeof Uint32Array === 'undefined' ? undefined$1 : Uint32Array, '$ %Uint32ArrayPrototype%': typeof Uint32Array === 'undefined' ? undefined$1 : Uint32Array.prototype, '$ %URIError%': URIError, '$ %URIErrorPrototype%': URIError.prototype, '$ %WeakMap%': typeof WeakMap === 'undefined' ? undefined$1 : WeakMap, '$ %WeakMapPrototype%': typeof WeakMap === 'undefined' ? undefined$1 : WeakMap.prototype, '$ %WeakSet%': typeof WeakSet === 'undefined' ? undefined$1 : WeakSet, '$ %WeakSetPrototype%': typeof WeakSet === 'undefined' ? undefined$1 : WeakSet.prototype }; var GetIntrinsic = function GetIntrinsic(name, allowMissing) { if (arguments.length > 1 && typeof allowMissing !== 'boolean') { throw new TypeError('"allowMissing" argument must be a boolean'); } var key = '$ ' + name; if (!(key in INTRINSICS)) { throw new SyntaxError('intrinsic ' + name + ' does not exist!'); } // istanbul ignore if // hopefully this is impossible to test :-) if (typeof INTRINSICS[key] === 'undefined' && !allowMissing) { throw new TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); } return INTRINSICS[key]; }; var src = functionBind.call(Function.call, Object.prototype.hasOwnProperty); var $TypeError = GetIntrinsic('%TypeError%'); var $SyntaxError = GetIntrinsic('%SyntaxError%'); var predicates = { // https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type 'Property Descriptor': function isPropertyDescriptor(ES, Desc) { if (ES.Type(Desc) !== 'Object') { return false; } var allowed = { '[[Configurable]]': true, '[[Enumerable]]': true, '[[Get]]': true, '[[Set]]': true, '[[Value]]': true, '[[Writable]]': true }; for (var key in Desc) { // eslint-disable-line if (src(Desc, key) && !allowed[key]) { return false; } } var isData = src(Desc, '[[Value]]'); var IsAccessor = src(Desc, '[[Get]]') || src(Desc, '[[Set]]'); if (isData && IsAccessor) { throw new $TypeError('Property Descriptors may not be both accessor and data descriptors'); } return true; } }; var assertRecord = function assertRecord(ES, recordType, argumentName, value) { var predicate = predicates[recordType]; if (typeof predicate !== 'function') { throw new $SyntaxError('unknown record type: ' + recordType); } if (!predicate(ES, value)) { throw new $TypeError(argumentName + ' must be a ' + recordType); } console.log(predicate(ES, value), value); }; var _isNaN = Number.isNaN || function isNaN(a) { return a !== a; }; var $isNaN = Number.isNaN || function (a) { return a !== a; }; var _isFinite = Number.isFinite || function (x) { return typeof x === 'number' && !$isNaN(x) && x !== Infinity && x !== -Infinity; }; var sign = function sign(number) { return number >= 0 ? 1 : -1; }; var mod = function mod(number, modulo) { var remain = number % modulo; return Math.floor(remain >= 0 ? remain : remain + modulo); }; var fnToStr = Function.prototype.toString; var constructorRegex = /^\s*class\b/; var isES6ClassFn = function isES6ClassFunction(value) { try { var fnStr = fnToStr.call(value); return constructorRegex.test(fnStr); } catch (e) { return false; // not a function } }; var tryFunctionObject = function tryFunctionToStr(value) { try { if (isES6ClassFn(value)) { return false; } fnToStr.call(value); return true; } catch (e) { return false; } }; var toStr$4 = Object.prototype.toString; var fnClass = '[object Function]'; var genClass = '[object GeneratorFunction]'; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; var isCallable = function isCallable(value) { if (!value) { return false; } if (typeof value !== 'function' && typeof value !== 'object') { return false; } if (typeof value === 'function' && !value.prototype) { return true; } if (hasToStringTag) { return tryFunctionObject(value); } if (isES6ClassFn(value)) { return false; } var strClass = toStr$4.call(value); return strClass === fnClass || strClass === genClass; }; var isPrimitive = function isPrimitive(value) { return value === null || typeof value !== 'function' && typeof value !== 'object'; }; var toStr$5 = Object.prototype.toString; // http://ecma-international.org/ecma-262/5.1/#sec-8.12.8 var ES5internalSlots = { '[[DefaultValue]]': function DefaultValue(O) { var actualHint; if (arguments.length > 1) { actualHint = arguments[1]; } else { actualHint = toStr$5.call(O) === '[object Date]' ? String : Number; } if (actualHint === String || actualHint === Number) { var methods = actualHint === String ? ['toString', 'valueOf'] : ['valueOf', 'toString']; var value, i; for (i = 0; i < methods.length; ++i) { if (isCallable(O[methods[i]])) { value = O[methods[i]](); if (isPrimitive(value)) { return value; } } } throw new TypeError('No default value'); } throw new TypeError('invalid [[DefaultValue]] hint supplied'); } }; // http://ecma-international.org/ecma-262/5.1/#sec-9.1 var es5 = function ToPrimitive(input) { if (isPrimitive(input)) { return input; } if (arguments.length > 1) { return ES5internalSlots['[[DefaultValue]]'](input, arguments[1]); } return ES5internalSlots['[[DefaultValue]]'](input); }; var $Object = GetIntrinsic('%Object%'); var $TypeError$1 = GetIntrinsic('%TypeError%'); var $String = GetIntrinsic('%String%'); // https://es5.github.io/#x9 var ES5 = { ToPrimitive: es5, ToBoolean: function ToBoolean(value) { return !!value; }, ToNumber: function ToNumber(value) { return +value; // eslint-disable-line no-implicit-coercion }, ToInteger: function ToInteger(value) { var number = this.ToNumber(value); if (_isNaN(number)) { return 0; } if (number === 0 || !_isFinite(number)) { return number; } return sign(number) * Math.floor(Math.abs(number)); }, ToInt32: function ToInt32(x) { return this.ToNumber(x) >> 0; }, ToUint32: function ToUint32(x) { return this.ToNumber(x) >>> 0; }, ToUint16: function ToUint16(value) { var number = this.ToNumber(value); if (_isNaN(number) || number === 0 || !_isFinite(number)) { return 0; } var posInt = sign(number) * Math.floor(Math.abs(number)); return mod(posInt, 0x10000); }, ToString: function ToString(value) { return $String(value); }, ToObject: function ToObject(value) { this.CheckObjectCoercible(value); return $Object(value); }, CheckObjectCoercible: function CheckObjectCoercible(value, optMessage) { /* jshint eqnull:true */ if (value == null) { throw new $TypeError$1(optMessage || 'Cannot call method on ' + value); } return value; }, IsCallable: isCallable, SameValue: function SameValue(x, y) { if (x === y) { // 0 === -0, but they are not identical. if (x === 0) { return 1 / x === 1 / y; } return true; } return _isNaN(x) && _isNaN(y); }, // https://www.ecma-international.org/ecma-262/5.1/#sec-8 Type: function Type(x) { if (x === null) { return 'Null'; } if (typeof x === 'undefined') { return 'Undefined'; } if (typeof x === 'function' || typeof x === 'object') { return 'Object'; } if (typeof x === 'number') { return 'Number'; } if (typeof x === 'boolean') { return 'Boolean'; } if (typeof x === 'string') { return 'String'; } }, // https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type IsPropertyDescriptor: function IsPropertyDescriptor(Desc) { if (this.Type(Desc) !== 'Object') { return false; } var allowed = { '[[Configurable]]': true, '[[Enumerable]]': true, '[[Get]]': true, '[[Set]]': true, '[[Value]]': true, '[[Writable]]': true }; for (var key in Desc) { // eslint-disable-line if (src(Desc, key) && !allowed[key]) { return false; } } var isData = src(Desc, '[[Value]]'); var IsAccessor = src(Desc, '[[Get]]') || src(Desc, '[[Set]]'); if (isData && IsAccessor) { throw new $TypeError$1('Property Descriptors may not be both accessor and data descriptors'); } return true; }, // https://ecma-international.org/ecma-262/5.1/#sec-8.10.1 IsAccessorDescriptor: function IsAccessorDescriptor(Desc) { if (typeof Desc === 'undefined') { return false; } assertRecord(this, 'Property Descriptor', 'Desc', Desc); if (!src(Desc, '[[Get]]') && !src(Desc, '[[Set]]')) { return false; } return true; }, // https://ecma-international.org/ecma-262/5.1/#sec-8.10.2 IsDataDescriptor: function IsDataDescriptor(Desc) { if (typeof Desc === 'undefined') { return false; } assertRecord(this, 'Property Descriptor', 'Desc', Desc); if (!src(Desc, '[[Value]]') && !src(Desc, '[[Writable]]')) { return false; } return true; }, // https://ecma-international.org/ecma-262/5.1/#sec-8.10.3 IsGenericDescriptor: function IsGenericDescriptor(Desc) { if (typeof Desc === 'undefined') { return false; } assertRecord(this, 'Property Descriptor', 'Desc', Desc); if (!this.IsAccessorDescriptor(Desc) && !this.IsDataDescriptor(Desc)) { return true; } return false; }, // https://ecma-international.org/ecma-262/5.1/#sec-8.10.4 FromPropertyDescriptor: function FromPropertyDescriptor(Desc) { if (typeof Desc === 'undefined') { return Desc; } assertRecord(this, 'Property Descriptor', 'Desc', Desc); if (this.IsDataDescriptor(Desc)) { return { value: Desc['[[Value]]'], writable: !!Desc['[[Writable]]'], enumerable: !!Desc['[[Enumerable]]'], configurable: !!Desc['[[Configurable]]'] }; } else if (this.IsAccessorDescriptor(Desc)) { return { get: Desc['[[Get]]'], set: Desc['[[Set]]'], enumerable: !!Desc['[[Enumerable]]'], configurable: !!Desc['[[Configurable]]'] }; } else { throw new $TypeError$1('FromPropertyDescriptor must be called with a fully populated Property Descriptor'); } }, // https://ecma-international.org/ecma-262/5.1/#sec-8.10.5 ToPropertyDescriptor: function ToPropertyDescriptor(Obj) { if (this.Type(Obj) !== 'Object') { throw new $TypeError$1('ToPropertyDescriptor requires an object'); } var desc = {}; if (src(Obj, 'enumerable')) { desc['[[Enumerable]]'] = this.ToBoolean(Obj.enumerable); } if (src(Obj, 'configurable')) { desc['[[Configurable]]'] = this.ToBoolean(Obj.configurable); } if (src(Obj, 'value')) { desc['[[Value]]'] = Obj.value; } if (src(Obj, 'writable')) { desc['[[Writable]]'] = this.ToBoolean(Obj.writable); } if (src(Obj, 'get')) { var getter = Obj.get; if (typeof getter !== 'undefined' && !this.IsCallable(getter)) { throw new TypeError('getter must be a function'); } desc['[[Get]]'] = getter; } if (src(Obj, 'set')) { var setter = Obj.set; if (typeof setter !== 'undefined' && !this.IsCallable(setter)) { throw new $TypeError$1('setter must be a function'); } desc['[[Set]]'] = setter; } if ((src(desc, '[[Get]]') || src(desc, '[[Set]]')) && (src(desc, '[[Value]]') || src(desc, '[[Writable]]'))) { throw new $TypeError$1('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute'); } return desc; } }; var es5$1 = ES5; var replace = functionBind.call(Function.call, String.prototype.replace); /* eslint-disable no-control-regex */ var leftWhitespace = /^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+/; var rightWhitespace = /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+$/; /* eslint-enable no-control-regex */ var implementation$2 = function trim() { var S = es5$1.ToString(es5$1.CheckObjectCoercible(this)); return replace(replace(S, leftWhitespace, ''), rightWhitespace, ''); }; var zeroWidthSpace = "\u200B"; var polyfill = function getPolyfill() { if (String.prototype.trim && zeroWidthSpace.trim() === zeroWidthSpace) { return String.prototype.trim; } return implementation$2; }; var shim = function shimStringTrim() { var polyfill$1 = polyfill(); defineProperties_1(String.prototype, { trim: polyfill$1 }, { trim: function testTrim() { return String.prototype.trim !== polyfill$1; } }); return polyfill$1; }; var boundTrim = functionBind.call(Function.call, polyfill()); defineProperties_1(boundTrim, { getPolyfill: polyfill, implementation: implementation$2, shim: shim }); var string_prototype_trim = boundTrim; var toStr$6 = Object.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; var forEachArray = function forEachArray(array, iterator, receiver) { for (var i = 0, len = array.length; i < len; i++) { if (hasOwnProperty.call(array, i)) { if (receiver == null) { iterator(array[i], i, array); } else { iterator.call(receiver, array[i], i, array); } } } }; var forEachString = function forEachString(string, iterator, receiver) { for (var i = 0, len = string.length; i < len; i++) { // no such thing as a sparse string. if (receiver == null) { iterator(string.charAt(i), i, string); } else { iterator.call(receiver, string.charAt(i), i, string); } } }; var forEachObject = function forEachObject(object, iterator, receiver) { for (var k in object) { if (hasOwnProperty.call(object, k)) { if (receiver == null) { iterator(object[k], k, object); } else { iterator.call(receiver, object[k], k, object); } } } }; var forEach = function forEach(list, iterator, thisArg) { if (!isCallable(iterator)) { throw new TypeError('iterator must be a function'); } var receiver; if (arguments.length >= 3) { receiver = thisArg; } if (toStr$6.call(list) === '[object Array]') { forEachArray(list, iterator, receiver); } else if (typeof list === 'string') { forEachString(list, iterator, receiver); } else { forEachObject(list, iterator, receiver); } }; var forEach_1 = forEach; var isArray = function isArray(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; var parseHeaders = function parseHeaders(headers) { if (!headers) return {}; var result = {}; forEach_1(string_prototype_trim(headers).split('\n'), function (row) { var index = row.indexOf(':'), key = string_prototype_trim(row.slice(0, index)).toLowerCase(), value = string_prototype_trim(row.slice(index + 1)); if (typeof result[key] === 'undefined') { result[key] = value; } else if (isArray(result[key])) { result[key].push(value); } else { result[key] = [result[key], value]; } }); return result; }; var immutable = extend; var hasOwnProperty$1 = Object.prototype.hasOwnProperty; function extend() { var target = {}; for (var i = 0; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (hasOwnProperty$1.call(source, key)) { target[key] = source[key]; } } } return target; } var xhr = createXHR; createXHR.XMLHttpRequest = window$1.XMLHttpRequest || noop; createXHR.XDomainRequest = "withCredentials" in new createXHR.XMLHttpRequest() ? createXHR.XMLHttpRequest : window$1.XDomainRequest; forEachArray$1(["get", "put", "post", "patch", "head", "delete"], function (method) { createXHR[method === "delete" ? "del" : method] = function (uri, options, callback) { options = initParams(uri, options, callback); options.method = method.toUpperCase(); return _createXHR(options); }; }); function forEachArray$1(array, iterator) { for (var i = 0; i < array.length; i++) { iterator(array[i]); } } function isEmpty(obj) { for (var i in obj) { if (obj.hasOwnProperty(i)) return false; } return true; } function initParams(uri, options, callback) { var params = uri; if (isFunction_1(options)) { callback = options; if (typeof uri === "string") { params = { uri: uri }; } } else { params = immutable(options, { uri: uri }); } params.callback = callback; return params; } function createXHR(uri, options, callback) { options = initParams(uri, options, callback); return _createXHR(options); } function _createXHR(options) { if (typeof options.callback === "undefined") { throw new Error("callback argument missing"); } var called = false; var callback = function cbOnce(err, response, body) { if (!called) { called = true; options.callback(err, response, body); } }; function readystatechange() { if (xhr.readyState === 4) { setTimeout(loadFunc, 0); } } function getBody() { // Chrome with requestType=blob throws errors arround when even testing access to responseText var body = undefined; if (xhr.response) { body = xhr.response; } else { body = xhr.responseText || getXml(xhr); } if (isJson) { try { body = JSON.parse(body); } catch (e) {} } return body; } function errorFunc(evt) { clearTimeout(timeoutTimer); if (!(evt instanceof Error)) { evt = new Error("" + (evt || "Unknown XMLHttpRequest Error")); } evt.statusCode = 0; return callback(evt, failureResponse); } // will load the data & process the response in a special response object function loadFunc() { if (aborted) return; var status; clearTimeout(timeoutTimer); if (options.useXDR && xhr.status === undefined) { //IE8 CORS GET successful response doesn't have a status field, but body is fine status = 200; } else { status = xhr.status === 1223 ? 204 : xhr.status; } var response = failureResponse; var err = null; if (status !== 0) { response = { body: getBody(), statusCode: status, method: method, headers: {}, url: uri, rawRequest: xhr }; if (xhr.getAllResponseHeaders) { //remember xhr can in fact be XDR for CORS in IE response.headers = parseHeaders(xhr.getAllResponseHeaders()); } } else { err = new Error("Internal XMLHttpRequest Error"); } return callback(err, response, response.body); } var xhr = options.xhr || null; if (!xhr) { if (options.cors || options.useXDR) { xhr = new createXHR.XDomainRequest(); } else { xhr = new createXHR.XMLHttpRequest(); } } var key; var aborted; var uri = xhr.url = options.uri || options.url; var method = xhr.method = options.method || "GET"; var body = options.body || options.data; var headers = xhr.headers = options.headers || {}; var sync = !!options.sync; var isJson = false; var timeoutTimer; var failureResponse = { body: undefined, headers: {}, statusCode: 0, method: method, url: uri, rawRequest: xhr }; if ("json" in options && options.json !== false) { isJson = true; headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json"); //Don't override existing accept header declared by user if (method !== "GET" && method !== "HEAD") { headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json"); //Don't override existing accept header declared by user body = JSON.stringify(options.json === true ? body : options.json); } } xhr.onreadystatechange = readystatechange; xhr.onload = loadFunc; xhr.onerror = errorFunc; // IE9 must have onprogress be set to a unique function. xhr.onprogress = function () {// IE must die }; xhr.onabort = function () { aborted = true; }; xhr.ontimeout = errorFunc; xhr.open(method, uri, !sync, options.username, options.password); //has to be after open if (!sync) { xhr.withCredentials = !!options.withCredentials; } // Cannot set timeout with sync request // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent if (!sync && options.timeout > 0) { timeoutTimer = setTimeout(function () { if (aborted) return; aborted = true; //IE9 may still call readystatechange xhr.abort("timeout"); var e = new Error("XMLHttpRequest timeout"); e.code = "ETIMEDOUT"; errorFunc(e); }, options.timeout); } if (xhr.setRequestHeader) { for (key in headers) { if (headers.hasOwnProperty(key)) { xhr.setRequestHeader(key, headers[key]); } } } else if (options.headers && !isEmpty(options.headers)) { throw new Error("Headers cannot be set on an XDomainRequest object"); } if ("responseType" in options) { xhr.responseType = options.responseType; } if ("beforeSend" in options && typeof options.beforeSend === "function") { options.beforeSend(xhr); } // Microsoft Edge browser sends "undefined" when send is called with undefined value. // XMLHttpRequest spec says to pass null as body to indicate no body // See https://github.com/naugtur/xhr/issues/100. xhr.send(body || null); return xhr; } function getXml(xhr) { if (xhr.responseType === "document") { return xhr.responseXML; } var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"; if (xhr.responseType === "" && !firefoxBugTakenEffect) { return xhr.responseXML; } return null; } function noop() {} /** * Takes a webvtt file contents and parses it into cues * * @param {string} srcContent * webVTT file contents * * @param {TextTrack} track * TextTrack to add cues to. Cues come from the srcContent. * * @private */ var parseCues = function parseCues(srcContent, track) { var parser = new window$1.WebVTT.Parser(window$1, window$1.vttjs, window$1.WebVTT.StringDecoder()); var errors = []; parser.oncue = function (cue) { track.addCue(cue); }; parser.onparsingerror = function (error) { errors.push(error); }; parser.onflush = function () { track.trigger({ type: 'loadeddata', target: track }); }; parser.parse(srcContent); if (errors.length > 0) { if (window$1.console && window$1.console.groupCollapsed) { window$1.console.groupCollapsed("Text Track parsing errors for " + track.src); } errors.forEach(function (error) { return log.error(error); }); if (window$1.console && window$1.console.groupEnd) { window$1.console.groupEnd(); } } parser.flush(); }; /** * Load a `TextTrack` from a specified url. * * @param {string} src * Url to load track from. * * @param {TextTrack} track * Track to add cues to. Comes from the content at the end of `url`. * * @private */ var loadTrack = function loadTrack(src, track) { var opts = { uri: src }; var crossOrigin = isCrossOrigin(src); if (crossOrigin) { opts.cors = crossOrigin; } xhr(opts, bind(this, function (err, response, responseBody) { if (err) { return log.error(err, response); } track.loaded_ = true; // Make sure that vttjs has loaded, otherwise, wait till it finished loading // NOTE: this is only used for the alt/video.novtt.js build if (typeof window$1.WebVTT !== 'function') { if (track.tech_) { // to prevent use before define eslint error, we define loadHandler // as a let here track.tech_.any(['vttjsloaded', 'vttjserror'], function (event) { if (event.type === 'vttjserror') { log.error("vttjs failed to load, stopping trying to process " + track.src); return; } return parseCues(responseBody, track); }); } } else { parseCues(responseBody, track); } })); }; /** * A representation of a single `TextTrack`. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack} * @extends Track */ var TextTrack = /*#__PURE__*/ function (_Track) { _inheritsLoose(TextTrack, _Track); /** * Create an instance of this class. * * @param {Object} options={} * Object of option names and values * * @param {Tech} options.tech * A reference to the tech that owns this TextTrack. * * @param {TextTrack~Kind} [options.kind='subtitles'] * A valid text track kind. * * @param {TextTrack~Mode} [options.mode='disabled'] * A valid text track mode. * * @param {string} [options.id='vjs_track_' + Guid.newGUID()] * A unique id for this TextTrack. * * @param {string} [options.label=''] * The menu label for this track. * * @param {string} [options.language=''] * A valid two character language code. * * @param {string} [options.srclang=''] * A valid two character language code. An alternative, but deprioritized * version of `options.language` * * @param {string} [options.src] * A url to TextTrack cues. * * @param {boolean} [options.default] * If this track should default to on or off. */ function TextTrack(options) { var _this; if (options === void 0) { options = {}; } if (!options.tech) { throw new Error('A tech was not provided.'); } var settings = mergeOptions(options, { kind: TextTrackKind[options.kind] || 'subtitles', language: options.language || options.srclang || '' }); var mode = TextTrackMode[settings.mode] || 'disabled'; var default_ = settings["default"]; if (settings.kind === 'metadata' || settings.kind === 'chapters') { mode = 'hidden'; } _this = _Track.call(this, settings) || this; _this.tech_ = settings.tech; _this.cues_ = []; _this.activeCues_ = []; var cues = new TextTrackCueList(_this.cues_); var activeCues = new TextTrackCueList(_this.activeCues_); var changed = false; var timeupdateHandler = bind(_assertThisInitialized(_this), function () { // Accessing this.activeCues for the side-effects of updating itself // due to its nature as a getter function. Do not remove or cues will // stop updating! // Use the setter to prevent deletion from uglify (pure_getters rule) this.activeCues = this.activeCues; if (changed) { this.trigger('cuechange'); changed = false; } }); if (mode !== 'disabled') { _this.tech_.ready(function () { _this.tech_.on('timeupdate', timeupdateHandler); }, true); } Object.defineProperties(_assertThisInitialized(_this), { /** * @memberof TextTrack * @member {boolean} default * If this track was set to be on or off by default. Cannot be changed after * creation. * @instance * * @readonly */ "default": { get: function get() { return default_; }, set: function set() {} }, /** * @memberof TextTrack * @member {string} mode * Set the mode of this TextTrack to a valid {@link TextTrack~Mode}. Will * not be set if setting to an invalid mode. * @instance * * @fires TextTrack#modechange */ mode: { get: function get() { return mode; }, set: function set(newMode) { var _this2 = this; if (!TextTrackMode[newMode]) { return; } mode = newMode; if (mode !== 'disabled') { this.tech_.ready(function () { _this2.tech_.on('timeupdate', timeupdateHandler); }, true); } else { this.tech_.off('timeupdate', timeupdateHandler); } /** * An event that fires when mode changes on this track. This allows * the TextTrackList that holds this track to act accordingly. * * > Note: This is not part of the spec! * * @event TextTrack#modechange * @type {EventTarget~Event} */ this.trigger('modechange'); } }, /** * @memberof TextTrack * @member {TextTrackCueList} cues * The text track cue list for this TextTrack. * @instance */ cues: { get: function get() { if (!this.loaded_) { return null; } return cues; }, set: function set() {} }, /** * @memberof TextTrack * @member {TextTrackCueList} activeCues * The list text track cues that are currently active for this TextTrack. * @instance */ activeCues: { get: function get() { if (!this.loaded_) { return null; } // nothing to do if (this.cues.length === 0) { return activeCues; } var ct = this.tech_.currentTime(); var active = []; for (var i = 0, l = this.cues.length; i < l; i++) { var cue = this.cues[i]; if (cue.startTime <= ct && cue.endTime >= ct) { active.push(cue); } else if (cue.startTime === cue.endTime && cue.startTime <= ct && cue.startTime + 0.5 >= ct) { active.push(cue); } } changed = false; if (active.length !== this.activeCues_.length) { changed = true; } else { for (var _i = 0; _i < active.length; _i++) { if (this.activeCues_.indexOf(active[_i]) === -1) { changed = true; } } } this.activeCues_ = active; activeCues.setCues_(this.activeCues_); return activeCues; }, // /!\ Keep this setter empty (see the timeupdate handler above) set: function set() {} } }); if (settings.src) { _this.src = settings.src; loadTrack(settings.src, _assertThisInitialized(_this)); } else { _this.loaded_ = true; } return _this; } /** * Add a cue to the internal list of cues. * * @param {TextTrack~Cue} cue * The cue to add to our internal list */ var _proto = TextTrack.prototype; _proto.addCue = function addCue(originalCue) { var cue = originalCue; if (window$1.vttjs && !(originalCue instanceof window$1.vttjs.VTTCue)) { cue = new window$1.vttjs.VTTCue(originalCue.startTime, originalCue.endTime, originalCue.text); for (var prop in originalCue) { if (!(prop in cue)) { cue[prop] = originalCue[prop]; } } // make sure that `id` is copied over cue.id = originalCue.id; cue.originalCue_ = originalCue; } var tracks = this.tech_.textTracks(); for (var i = 0; i < tracks.length; i++) { if (tracks[i] !== this) { tracks[i].removeCue(cue); } } this.cues_.push(cue); this.cues.setCues_(this.cues_); } /** * Remove a cue from our internal list * * @param {TextTrack~Cue} removeCue * The cue to remove from our internal list */ ; _proto.removeCue = function removeCue(_removeCue) { var i = this.cues_.length; while (i--) { var cue = this.cues_[i]; if (cue === _removeCue || cue.originalCue_ && cue.originalCue_ === _removeCue) { this.cues_.splice(i, 1); this.cues.setCues_(this.cues_); break; } } }; return TextTrack; }(Track); /** * cuechange - One or more cues in the track have become active or stopped being active. */ TextTrack.prototype.allowedEvents_ = { cuechange: 'cuechange' }; /** * A representation of a single `AudioTrack`. If it is part of an {@link AudioTrackList} * only one `AudioTrack` in the list will be enabled at a time. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotrack} * @extends Track */ var AudioTrack = /*#__PURE__*/ function (_Track) { _inheritsLoose(AudioTrack, _Track); /** * Create an instance of this class. * * @param {Object} [options={}] * Object of option names and values * * @param {AudioTrack~Kind} [options.kind=''] * A valid audio track kind * * @param {string} [options.id='vjs_track_' + Guid.newGUID()] * A unique id for this AudioTrack. * * @param {string} [options.label=''] * The menu label for this track. * * @param {string} [options.language=''] * A valid two character language code. * * @param {boolean} [options.enabled] * If this track is the one that is currently playing. If this track is part of * an {@link AudioTrackList}, only one {@link AudioTrack} will be enabled. */ function AudioTrack(options) { var _this; if (options === void 0) { options = {}; } var settings = mergeOptions(options, { kind: AudioTrackKind[options.kind] || '' }); _this = _Track.call(this, settings) || this; var enabled = false; /** * @memberof AudioTrack * @member {boolean} enabled * If this `AudioTrack` is enabled or not. When setting this will * fire {@link AudioTrack#enabledchange} if the state of enabled is changed. * @instance * * @fires VideoTrack#selectedchange */ Object.defineProperty(_assertThisInitialized(_this), 'enabled', { get: function get() { return enabled; }, set: function set(newEnabled) { // an invalid or unchanged value if (typeof newEnabled !== 'boolean' || newEnabled === enabled) { return; } enabled = newEnabled; /** * An event that fires when enabled changes on this track. This allows * the AudioTrackList that holds this track to act accordingly. * * > Note: This is not part of the spec! Native tracks will do * this internally without an event. * * @event AudioTrack#enabledchange * @type {EventTarget~Event} */ this.trigger('enabledchange'); } }); // if the user sets this track to selected then // set selected to that true value otherwise // we keep it false if (settings.enabled) { _this.enabled = settings.enabled; } _this.loaded_ = true; return _this; } return AudioTrack; }(Track); /** * A representation of a single `VideoTrack`. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotrack} * @extends Track */ var VideoTrack = /*#__PURE__*/ function (_Track) { _inheritsLoose(VideoTrack, _Track); /** * Create an instance of this class. * * @param {Object} [options={}] * Object of option names and values * * @param {string} [options.kind=''] * A valid {@link VideoTrack~Kind} * * @param {string} [options.id='vjs_track_' + Guid.newGUID()] * A unique id for this AudioTrack. * * @param {string} [options.label=''] * The menu label for this track. * * @param {string} [options.language=''] * A valid two character language code. * * @param {boolean} [options.selected] * If this track is the one that is currently playing. */ function VideoTrack(options) { var _this; if (options === void 0) { options = {}; } var settings = mergeOptions(options, { kind: VideoTrackKind[options.kind] || '' }); _this = _Track.call(this, settings) || this; var selected = false; /** * @memberof VideoTrack * @member {boolean} selected * If this `VideoTrack` is selected or not. When setting this will * fire {@link VideoTrack#selectedchange} if the state of selected changed. * @instance * * @fires VideoTrack#selectedchange */ Object.defineProperty(_assertThisInitialized(_this), 'selected', { get: function get() { return selected; }, set: function set(newSelected) { // an invalid or unchanged value if (typeof newSelected !== 'boolean' || newSelected === selected) { return; } selected = newSelected; /** * An event that fires when selected changes on this track. This allows * the VideoTrackList that holds this track to act accordingly. * * > Note: This is not part of the spec! Native tracks will do * this internally without an event. * * @event VideoTrack#selectedchange * @type {EventTarget~Event} */ this.trigger('selectedchange'); } }); // if the user sets this track to selected then // set selected to that true value otherwise // we keep it false if (settings.selected) { _this.selected = settings.selected; } return _this; } return VideoTrack; }(Track); /** * @memberof HTMLTrackElement * @typedef {HTMLTrackElement~ReadyState} * @enum {number} */ var NONE = 0; var LOADING = 1; var LOADED = 2; var ERROR = 3; /** * A single track represented in the DOM. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#htmltrackelement} * @extends EventTarget */ var HTMLTrackElement = /*#__PURE__*/ function (_EventTarget) { _inheritsLoose(HTMLTrackElement, _EventTarget); /** * Create an instance of this class. * * @param {Object} options={} * Object of option names and values * * @param {Tech} options.tech * A reference to the tech that owns this HTMLTrackElement. * * @param {TextTrack~Kind} [options.kind='subtitles'] * A valid text track kind. * * @param {TextTrack~Mode} [options.mode='disabled'] * A valid text track mode. * * @param {string} [options.id='vjs_track_' + Guid.newGUID()] * A unique id for this TextTrack. * * @param {string} [options.label=''] * The menu label for this track. * * @param {string} [options.language=''] * A valid two character language code. * * @param {string} [options.srclang=''] * A valid two character language code. An alternative, but deprioritized * vesion of `options.language` * * @param {string} [options.src] * A url to TextTrack cues. * * @param {boolean} [options.default] * If this track should default to on or off. */ function HTMLTrackElement(options) { var _this; if (options === void 0) { options = {}; } _this = _EventTarget.call(this) || this; var readyState; var track = new TextTrack(options); _this.kind = track.kind; _this.src = track.src; _this.srclang = track.language; _this.label = track.label; _this["default"] = track["default"]; Object.defineProperties(_assertThisInitialized(_this), { /** * @memberof HTMLTrackElement * @member {HTMLTrackElement~ReadyState} readyState * The current ready state of the track element. * @instance */ readyState: { get: function get() { return readyState; } }, /** * @memberof HTMLTrackElement * @member {TextTrack} track * The underlying TextTrack object. * @instance * */ track: { get: function get() { return track; } } }); readyState = NONE; /** * @listens TextTrack#loadeddata * @fires HTMLTrackElement#load */ track.addEventListener('loadeddata', function () { readyState = LOADED; _this.trigger({ type: 'load', target: _assertThisInitialized(_this) }); }); return _this; } return HTMLTrackElement; }(EventTarget); HTMLTrackElement.prototype.allowedEvents_ = { load: 'load' }; HTMLTrackElement.NONE = NONE; HTMLTrackElement.LOADING = LOADING; HTMLTrackElement.LOADED = LOADED; HTMLTrackElement.ERROR = ERROR; /* * This file contains all track properties that are used in * player.js, tech.js, html5.js and possibly other techs in the future. */ var NORMAL = { audio: { ListClass: AudioTrackList, TrackClass: AudioTrack, capitalName: 'Audio' }, video: { ListClass: VideoTrackList, TrackClass: VideoTrack, capitalName: 'Video' }, text: { ListClass: TextTrackList, TrackClass: TextTrack, capitalName: 'Text' } }; Object.keys(NORMAL).forEach(function (type) { NORMAL[type].getterName = type + "Tracks"; NORMAL[type].privateName = type + "Tracks_"; }); var REMOTE = { remoteText: { ListClass: TextTrackList, TrackClass: TextTrack, capitalName: 'RemoteText', getterName: 'remoteTextTracks', privateName: 'remoteTextTracks_' }, remoteTextEl: { ListClass: HtmlTrackElementList, TrackClass: HTMLTrackElement, capitalName: 'RemoteTextTrackEls', getterName: 'remoteTextTrackEls', privateName: 'remoteTextTrackEls_' } }; var ALL = mergeOptions(NORMAL, REMOTE); REMOTE.names = Object.keys(REMOTE); NORMAL.names = Object.keys(NORMAL); ALL.names = [].concat(REMOTE.names).concat(NORMAL.names); var vtt = {}; /** * An Object containing a structure like: `{src: 'url', type: 'mimetype'}` or string * that just contains the src url alone. * * `var SourceObject = {src: 'http://ex.com/video.mp4', type: 'video/mp4'};` * `var SourceString = 'http://example.com/some-video.mp4';` * * @typedef {Object|string} Tech~SourceObject * * @property {string} src * The url to the source * * @property {string} type * The mime type of the source */ /** * A function used by {@link Tech} to create a new {@link TextTrack}. * * @private * * @param {Tech} self * An instance of the Tech class. * * @param {string} kind * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata) * * @param {string} [label] * Label to identify the text track * * @param {string} [language] * Two letter language abbreviation * * @param {Object} [options={}] * An object with additional text track options * * @return {TextTrack} * The text track that was created. */ function createTrackHelper(self, kind, label, language, options) { if (options === void 0) { options = {}; } var tracks = self.textTracks(); options.kind = kind; if (label) { options.label = label; } if (language) { options.language = language; } options.tech = self; var track = new ALL.text.TrackClass(options); tracks.addTrack(track); return track; } /** * This is the base class for media playback technology controllers, such as * {@link Flash} and {@link HTML5} * * @extends Component */ var Tech = /*#__PURE__*/ function (_Component) { _inheritsLoose(Tech, _Component); /** * Create an instance of this Tech. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} ready * Callback function to call when the `HTML5` Tech is ready. */ function Tech(options, ready) { var _this; if (options === void 0) { options = {}; } if (ready === void 0) { ready = function ready() {}; } // we don't want the tech to report user activity automatically. // This is done manually in addControlsListeners options.reportTouchActivity = false; _this = _Component.call(this, null, options, ready) || this; // keep track of whether the current source has played at all to // implement a very limited played() _this.hasStarted_ = false; _this.on('playing', function () { this.hasStarted_ = true; }); _this.on('loadstart', function () { this.hasStarted_ = false; }); ALL.names.forEach(function (name) { var props = ALL[name]; if (options && options[props.getterName]) { _this[props.privateName] = options[props.getterName]; } }); // Manually track progress in cases where the browser/flash player doesn't report it. if (!_this.featuresProgressEvents) { _this.manualProgressOn(); } // Manually track timeupdates in cases where the browser/flash player doesn't report it. if (!_this.featuresTimeupdateEvents) { _this.manualTimeUpdatesOn(); } ['Text', 'Audio', 'Video'].forEach(function (track) { if (options["native" + track + "Tracks"] === false) { _this["featuresNative" + track + "Tracks"] = false; } }); if (options.nativeCaptions === false || options.nativeTextTracks === false) { _this.featuresNativeTextTracks = false; } else if (options.nativeCaptions === true || options.nativeTextTracks === true) { _this.featuresNativeTextTracks = true; } if (!_this.featuresNativeTextTracks) { _this.emulateTextTracks(); } _this.autoRemoteTextTracks_ = new ALL.text.ListClass(); _this.initTrackListeners(); // Turn on component tap events only if not using native controls if (!options.nativeControlsForTouch) { _this.emitTapEvents(); } if (_this.constructor) { _this.name_ = _this.constructor.name || 'Unknown Tech'; } return _this; } /** * A special function to trigger source set in a way that will allow player * to re-trigger if the player or tech are not ready yet. * * @fires Tech#sourceset * @param {string} src The source string at the time of the source changing. */ var _proto = Tech.prototype; _proto.triggerSourceset = function triggerSourceset(src) { var _this2 = this; if (!this.isReady_) { // on initial ready we have to trigger source set // 1ms after ready so that player can watch for it. this.one('ready', function () { return _this2.setTimeout(function () { return _this2.triggerSourceset(src); }, 1); }); } /** * Fired when the source is set on the tech causing the media element * to reload. * * @see {@link Player#event:sourceset} * @event Tech#sourceset * @type {EventTarget~Event} */ this.trigger({ src: src, type: 'sourceset' }); } /* Fallbacks for unsupported event types ================================================================================ */ /** * Polyfill the `progress` event for browsers that don't support it natively. * * @see {@link Tech#trackProgress} */ ; _proto.manualProgressOn = function manualProgressOn() { this.on('durationchange', this.onDurationChange); this.manualProgress = true; // Trigger progress watching when a source begins loading this.one('ready', this.trackProgress); } /** * Turn off the polyfill for `progress` events that was created in * {@link Tech#manualProgressOn} */ ; _proto.manualProgressOff = function manualProgressOff() { this.manualProgress = false; this.stopTrackingProgress(); this.off('durationchange', this.onDurationChange); } /** * This is used to trigger a `progress` event when the buffered percent changes. It * sets an interval function that will be called every 500 milliseconds to check if the * buffer end percent has changed. * * > This function is called by {@link Tech#manualProgressOn} * * @param {EventTarget~Event} event * The `ready` event that caused this to run. * * @listens Tech#ready * @fires Tech#progress */ ; _proto.trackProgress = function trackProgress(event) { this.stopTrackingProgress(); this.progressInterval = this.setInterval(bind(this, function () { // Don't trigger unless buffered amount is greater than last time var numBufferedPercent = this.bufferedPercent(); if (this.bufferedPercent_ !== numBufferedPercent) { /** * See {@link Player#progress} * * @event Tech#progress * @type {EventTarget~Event} */ this.trigger('progress'); } this.bufferedPercent_ = numBufferedPercent; if (numBufferedPercent === 1) { this.stopTrackingProgress(); } }), 500); } /** * Update our internal duration on a `durationchange` event by calling * {@link Tech#duration}. * * @param {EventTarget~Event} event * The `durationchange` event that caused this to run. * * @listens Tech#durationchange */ ; _proto.onDurationChange = function onDurationChange(event) { this.duration_ = this.duration(); } /** * Get and create a `TimeRange` object for buffering. * * @return {TimeRange} * The time range object that was created. */ ; _proto.buffered = function buffered() { return createTimeRanges(0, 0); } /** * Get the percentage of the current video that is currently buffered. * * @return {number} * A number from 0 to 1 that represents the decimal percentage of the * video that is buffered. * */ ; _proto.bufferedPercent = function bufferedPercent$1() { return bufferedPercent(this.buffered(), this.duration_); } /** * Turn off the polyfill for `progress` events that was created in * {@link Tech#manualProgressOn} * Stop manually tracking progress events by clearing the interval that was set in * {@link Tech#trackProgress}. */ ; _proto.stopTrackingProgress = function stopTrackingProgress() { this.clearInterval(this.progressInterval); } /** * Polyfill the `timeupdate` event for browsers that don't support it. * * @see {@link Tech#trackCurrentTime} */ ; _proto.manualTimeUpdatesOn = function manualTimeUpdatesOn() { this.manualTimeUpdates = true; this.on('play', this.trackCurrentTime); this.on('pause', this.stopTrackingCurrentTime); } /** * Turn off the polyfill for `timeupdate` events that was created in * {@link Tech#manualTimeUpdatesOn} */ ; _proto.manualTimeUpdatesOff = function manualTimeUpdatesOff() { this.manualTimeUpdates = false; this.stopTrackingCurrentTime(); this.off('play', this.trackCurrentTime); this.off('pause', this.stopTrackingCurrentTime); } /** * Sets up an interval function to track current time and trigger `timeupdate` every * 250 milliseconds. * * @listens Tech#play * @triggers Tech#timeupdate */ ; _proto.trackCurrentTime = function trackCurrentTime() { if (this.currentTimeInterval) { this.stopTrackingCurrentTime(); } this.currentTimeInterval = this.setInterval(function () { /** * Triggered at an interval of 250ms to indicated that time is passing in the video. * * @event Tech#timeupdate * @type {EventTarget~Event} */ this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15 }, 250); } /** * Stop the interval function created in {@link Tech#trackCurrentTime} so that the * `timeupdate` event is no longer triggered. * * @listens {Tech#pause} */ ; _proto.stopTrackingCurrentTime = function stopTrackingCurrentTime() { this.clearInterval(this.currentTimeInterval); // #1002 - if the video ends right before the next timeupdate would happen, // the progress bar won't make it all the way to the end this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); } /** * Turn off all event polyfills, clear the `Tech`s {@link AudioTrackList}, * {@link VideoTrackList}, and {@link TextTrackList}, and dispose of this Tech. * * @fires Component#dispose */ ; _proto.dispose = function dispose() { // clear out all tracks because we can't reuse them between techs this.clearTracks(NORMAL.names); // Turn off any manual progress or timeupdate tracking if (this.manualProgress) { this.manualProgressOff(); } if (this.manualTimeUpdates) { this.manualTimeUpdatesOff(); } _Component.prototype.dispose.call(this); } /** * Clear out a single `TrackList` or an array of `TrackLists` given their names. * * > Note: Techs without source handlers should call this between sources for `video` * & `audio` tracks. You don't want to use them between tracks! * * @param {string[]|string} types * TrackList names to clear, valid names are `video`, `audio`, and * `text`. */ ; _proto.clearTracks = function clearTracks(types) { var _this3 = this; types = [].concat(types); // clear out all tracks because we can't reuse them between techs types.forEach(function (type) { var list = _this3[type + "Tracks"]() || []; var i = list.length; while (i--) { var track = list[i]; if (type === 'text') { _this3.removeRemoteTextTrack(track); } list.removeTrack(track); } }); } /** * Remove any TextTracks added via addRemoteTextTrack that are * flagged for automatic garbage collection */ ; _proto.cleanupAutoTextTracks = function cleanupAutoTextTracks() { var list = this.autoRemoteTextTracks_ || []; var i = list.length; while (i--) { var track = list[i]; this.removeRemoteTextTrack(track); } } /** * Reset the tech, which will removes all sources and reset the internal readyState. * * @abstract */ ; _proto.reset = function reset() {} /** * Get or set an error on the Tech. * * @param {MediaError} [err] * Error to set on the Tech * * @return {MediaError|null} * The current error object on the tech, or null if there isn't one. */ ; _proto.error = function error(err) { if (err !== undefined) { this.error_ = new MediaError(err); this.trigger('error'); } return this.error_; } /** * Returns the `TimeRange`s that have been played through for the current source. * * > NOTE: This implementation is incomplete. It does not track the played `TimeRange`. * It only checks whether the source has played at all or not. * * @return {TimeRange} * - A single time range if this video has played * - An empty set of ranges if not. */ ; _proto.played = function played() { if (this.hasStarted_) { return createTimeRanges(0, 0); } return createTimeRanges(); } /** * Causes a manual time update to occur if {@link Tech#manualTimeUpdatesOn} was * previously called. * * @fires Tech#timeupdate */ ; _proto.setCurrentTime = function setCurrentTime() { // improve the accuracy of manual timeupdates if (this.manualTimeUpdates) { /** * A manual `timeupdate` event. * * @event Tech#timeupdate * @type {EventTarget~Event} */ this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); } } /** * Turn on listeners for {@link VideoTrackList}, {@link {AudioTrackList}, and * {@link TextTrackList} events. * * This adds {@link EventTarget~EventListeners} for `addtrack`, and `removetrack`. * * @fires Tech#audiotrackchange * @fires Tech#videotrackchange * @fires Tech#texttrackchange */ ; _proto.initTrackListeners = function initTrackListeners() { var _this4 = this; /** * Triggered when tracks are added or removed on the Tech {@link AudioTrackList} * * @event Tech#audiotrackchange * @type {EventTarget~Event} */ /** * Triggered when tracks are added or removed on the Tech {@link VideoTrackList} * * @event Tech#videotrackchange * @type {EventTarget~Event} */ /** * Triggered when tracks are added or removed on the Tech {@link TextTrackList} * * @event Tech#texttrackchange * @type {EventTarget~Event} */ NORMAL.names.forEach(function (name) { var props = NORMAL[name]; var trackListChanges = function trackListChanges() { _this4.trigger(name + "trackchange"); }; var tracks = _this4[props.getterName](); tracks.addEventListener('removetrack', trackListChanges); tracks.addEventListener('addtrack', trackListChanges); _this4.on('dispose', function () { tracks.removeEventListener('removetrack', trackListChanges); tracks.removeEventListener('addtrack', trackListChanges); }); }); } /** * Emulate TextTracks using vtt.js if necessary * * @fires Tech#vttjsloaded * @fires Tech#vttjserror */ ; _proto.addWebVttScript_ = function addWebVttScript_() { var _this5 = this; if (window$1.WebVTT) { return; } // Initially, Tech.el_ is a child of a dummy-div wait until the Component system // signals that the Tech is ready at which point Tech.el_ is part of the DOM // before inserting the WebVTT script if (document.body.contains(this.el())) { // load via require if available and vtt.js script location was not passed in // as an option. novtt builds will turn the above require call into an empty object // which will cause this if check to always fail. if (!this.options_['vtt.js'] && isPlain(vtt) && Object.keys(vtt).length > 0) { this.trigger('vttjsloaded'); return; } // load vtt.js via the script location option or the cdn of no location was // passed in var script = document.createElement('script'); script.src = this.options_['vtt.js'] || 'https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js'; script.onload = function () { /** * Fired when vtt.js is loaded. * * @event Tech#vttjsloaded * @type {EventTarget~Event} */ _this5.trigger('vttjsloaded'); }; script.onerror = function () { /** * Fired when vtt.js was not loaded due to an error * * @event Tech#vttjsloaded * @type {EventTarget~Event} */ _this5.trigger('vttjserror'); }; this.on('dispose', function () { script.onload = null; script.onerror = null; }); // but have not loaded yet and we set it to true before the inject so that // we don't overwrite the injected window.WebVTT if it loads right away window$1.WebVTT = true; this.el().parentNode.appendChild(script); } else { this.ready(this.addWebVttScript_); } } /** * Emulate texttracks * */ ; _proto.emulateTextTracks = function emulateTextTracks() { var _this6 = this; var tracks = this.textTracks(); var remoteTracks = this.remoteTextTracks(); var handleAddTrack = function handleAddTrack(e) { return tracks.addTrack(e.track); }; var handleRemoveTrack = function handleRemoveTrack(e) { return tracks.removeTrack(e.track); }; remoteTracks.on('addtrack', handleAddTrack); remoteTracks.on('removetrack', handleRemoveTrack); this.addWebVttScript_(); var updateDisplay = function updateDisplay() { return _this6.trigger('texttrackchange'); }; var textTracksChanges = function textTracksChanges() { updateDisplay(); for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; track.removeEventListener('cuechange', updateDisplay); if (track.mode === 'showing') { track.addEventListener('cuechange', updateDisplay); } } }; textTracksChanges(); tracks.addEventListener('change', textTracksChanges); tracks.addEventListener('addtrack', textTracksChanges); tracks.addEventListener('removetrack', textTracksChanges); this.on('dispose', function () { remoteTracks.off('addtrack', handleAddTrack); remoteTracks.off('removetrack', handleRemoveTrack); tracks.removeEventListener('change', textTracksChanges); tracks.removeEventListener('addtrack', textTracksChanges); tracks.removeEventListener('removetrack', textTracksChanges); for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; track.removeEventListener('cuechange', updateDisplay); } }); } /** * Create and returns a remote {@link TextTrack} object. * * @param {string} kind * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata) * * @param {string} [label] * Label to identify the text track * * @param {string} [language] * Two letter language abbreviation * * @return {TextTrack} * The TextTrack that gets created. */ ; _proto.addTextTrack = function addTextTrack(kind, label, language) { if (!kind) { throw new Error('TextTrack kind is required but was not provided'); } return createTrackHelper(this, kind, label, language); } /** * Create an emulated TextTrack for use by addRemoteTextTrack * * This is intended to be overridden by classes that inherit from * Tech in order to create native or custom TextTracks. * * @param {Object} options * The object should contain the options to initialize the TextTrack with. * * @param {string} [options.kind] * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata). * * @param {string} [options.label]. * Label to identify the text track * * @param {string} [options.language] * Two letter language abbreviation. * * @return {HTMLTrackElement} * The track element that gets created. */ ; _proto.createRemoteTextTrack = function createRemoteTextTrack(options) { var track = mergeOptions(options, { tech: this }); return new REMOTE.remoteTextEl.TrackClass(track); } /** * Creates a remote text track object and returns an html track element. * * > Note: This can be an emulated {@link HTMLTrackElement} or a native one. * * @param {Object} options * See {@link Tech#createRemoteTextTrack} for more detailed properties. * * @param {boolean} [manualCleanup=true] * - When false: the TextTrack will be automatically removed from the video * element whenever the source changes * - When True: The TextTrack will have to be cleaned up manually * * @return {HTMLTrackElement} * An Html Track Element. * * @deprecated The default functionality for this function will be equivalent * to "manualCleanup=false" in the future. The manualCleanup parameter will * also be removed. */ ; _proto.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) { var _this7 = this; if (options === void 0) { options = {}; } var htmlTrackElement = this.createRemoteTextTrack(options); if (manualCleanup !== true && manualCleanup !== false) { // deprecation warning log.warn('Calling addRemoteTextTrack without explicitly setting the "manualCleanup" parameter to `true` is deprecated and default to `false` in future version of video.js'); manualCleanup = true; } // store HTMLTrackElement and TextTrack to remote list this.remoteTextTrackEls().addTrackElement_(htmlTrackElement); this.remoteTextTracks().addTrack(htmlTrackElement.track); if (manualCleanup !== true) { // create the TextTrackList if it doesn't exist this.ready(function () { return _this7.autoRemoteTextTracks_.addTrack(htmlTrackElement.track); }); } return htmlTrackElement; } /** * Remove a remote text track from the remote `TextTrackList`. * * @param {TextTrack} track * `TextTrack` to remove from the `TextTrackList` */ ; _proto.removeRemoteTextTrack = function removeRemoteTextTrack(track) { var trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track); // remove HTMLTrackElement and TextTrack from remote list this.remoteTextTrackEls().removeTrackElement_(trackElement); this.remoteTextTracks().removeTrack(track); this.autoRemoteTextTracks_.removeTrack(track); } /** * Gets available media playback quality metrics as specified by the W3C's Media * Playback Quality API. * * @see [Spec]{@link https://wicg.github.io/media-playback-quality} * * @return {Object} * An object with supported media playback quality metrics * * @abstract */ ; _proto.getVideoPlaybackQuality = function getVideoPlaybackQuality() { return {}; } /** * Attempt to create a floating video window always on top of other windows * so that users may continue consuming media while they interact with other * content sites, or applications on their device. * * @see [Spec]{@link https://wicg.github.io/picture-in-picture} * * @return {Promise|undefined} * A promise with a Picture-in-Picture window if the browser supports * Promises (or one was passed in as an option). It returns undefined * otherwise. * * @abstract */ ; _proto.requestPictureInPicture = function requestPictureInPicture() { var PromiseClass = this.options_.Promise || window$1.Promise; if (PromiseClass) { return PromiseClass.reject(); } } /** * A method to set a poster from a `Tech`. * * @abstract */ ; _proto.setPoster = function setPoster() {} /** * A method to check for the presence of the 'playsinline' <video> attribute. * * @abstract */ ; _proto.playsinline = function playsinline() {} /** * A method to set or unset the 'playsinline' <video> attribute. * * @abstract */ ; _proto.setPlaysinline = function setPlaysinline() {} /** * Attempt to force override of native audio tracks. * * @param {boolean} override - If set to true native audio will be overridden, * otherwise native audio will potentially be used. * * @abstract */ ; _proto.overrideNativeAudioTracks = function overrideNativeAudioTracks() {} /** * Attempt to force override of native video tracks. * * @param {boolean} override - If set to true native video will be overridden, * otherwise native video will potentially be used. * * @abstract */ ; _proto.overrideNativeVideoTracks = function overrideNativeVideoTracks() {} /* * Check if the tech can support the given mime-type. * * The base tech does not support any type, but source handlers might * overwrite this. * * @param {string} type * The mimetype to check for support * * @return {string} * 'probably', 'maybe', or empty string * * @see [Spec]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType} * * @abstract */ ; _proto.canPlayType = function canPlayType() { return ''; } /** * Check if the type is supported by this tech. * * The base tech does not support any type, but source handlers might * overwrite this. * * @param {string} type * The media type to check * @return {string} Returns the native video element's response */ ; Tech.canPlayType = function canPlayType() { return ''; } /** * Check if the tech can support the given source * * @param {Object} srcObj * The source object * @param {Object} options * The options passed to the tech * @return {string} 'probably', 'maybe', or '' (empty string) */ ; Tech.canPlaySource = function canPlaySource(srcObj, options) { return Tech.canPlayType(srcObj.type); } /* * Return whether the argument is a Tech or not. * Can be passed either a Class like `Html5` or a instance like `player.tech_` * * @param {Object} component * The item to check * * @return {boolean} * Whether it is a tech or not * - True if it is a tech * - False if it is not */ ; Tech.isTech = function isTech(component) { return component.prototype instanceof Tech || component instanceof Tech || component === Tech; } /** * Registers a `Tech` into a shared list for videojs. * * @param {string} name * Name of the `Tech` to register. * * @param {Object} tech * The `Tech` class to register. */ ; Tech.registerTech = function registerTech(name, tech) { if (!Tech.techs_) { Tech.techs_ = {}; } if (!Tech.isTech(tech)) { throw new Error("Tech " + name + " must be a Tech"); } if (!Tech.canPlayType) { throw new Error('Techs must have a static canPlayType method on them'); } if (!Tech.canPlaySource) { throw new Error('Techs must have a static canPlaySource method on them'); } name = toTitleCase(name); Tech.techs_[name] = tech; Tech.techs_[toLowerCase(name)] = tech; if (name !== 'Tech') { // camel case the techName for use in techOrder Tech.defaultTechOrder_.push(name); } return tech; } /** * Get a `Tech` from the shared list by name. * * @param {string} name * `camelCase` or `TitleCase` name of the Tech to get * * @return {Tech|undefined} * The `Tech` or undefined if there was no tech with the name requested. */ ; Tech.getTech = function getTech(name) { if (!name) { return; } if (Tech.techs_ && Tech.techs_[name]) { return Tech.techs_[name]; } name = toTitleCase(name); if (window$1 && window$1.videojs && window$1.videojs[name]) { log.warn("The " + name + " tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)"); return window$1.videojs[name]; } }; return Tech; }(Component); /** * Get the {@link VideoTrackList} * * @returns {VideoTrackList} * @method Tech.prototype.videoTracks */ /** * Get the {@link AudioTrackList} * * @returns {AudioTrackList} * @method Tech.prototype.audioTracks */ /** * Get the {@link TextTrackList} * * @returns {TextTrackList} * @method Tech.prototype.textTracks */ /** * Get the remote element {@link TextTrackList} * * @returns {TextTrackList} * @method Tech.prototype.remoteTextTracks */ /** * Get the remote element {@link HtmlTrackElementList} * * @returns {HtmlTrackElementList} * @method Tech.prototype.remoteTextTrackEls */ ALL.names.forEach(function (name) { var props = ALL[name]; Tech.prototype[props.getterName] = function () { this[props.privateName] = this[props.privateName] || new props.ListClass(); return this[props.privateName]; }; }); /** * List of associated text tracks * * @type {TextTrackList} * @private * @property Tech#textTracks_ */ /** * List of associated audio tracks. * * @type {AudioTrackList} * @private * @property Tech#audioTracks_ */ /** * List of associated video tracks. * * @type {VideoTrackList} * @private * @property Tech#videoTracks_ */ /** * Boolean indicating whether the `Tech` supports volume control. * * @type {boolean} * @default */ Tech.prototype.featuresVolumeControl = true; /** * Boolean indicating whether the `Tech` supports muting volume. * * @type {bolean} * @default */ Tech.prototype.featuresMuteControl = true; /** * Boolean indicating whether the `Tech` supports fullscreen resize control. * Resizing plugins using request fullscreen reloads the plugin * * @type {boolean} * @default */ Tech.prototype.featuresFullscreenResize = false; /** * Boolean indicating whether the `Tech` supports changing the speed at which the video * plays. Examples: * - Set player to play 2x (twice) as fast * - Set player to play 0.5x (half) as fast * * @type {boolean} * @default */ Tech.prototype.featuresPlaybackRate = false; /** * Boolean indicating whether the `Tech` supports the `progress` event. This is currently * not triggered by video-js-swf. This will be used to determine if * {@link Tech#manualProgressOn} should be called. * * @type {boolean} * @default */ Tech.prototype.featuresProgressEvents = false; /** * Boolean indicating whether the `Tech` supports the `sourceset` event. * * A tech should set this to `true` and then use {@link Tech#triggerSourceset} * to trigger a {@link Tech#event:sourceset} at the earliest time after getting * a new source. * * @type {boolean} * @default */ Tech.prototype.featuresSourceset = false; /** * Boolean indicating whether the `Tech` supports the `timeupdate` event. This is currently * not triggered by video-js-swf. This will be used to determine if * {@link Tech#manualTimeUpdates} should be called. * * @type {boolean} * @default */ Tech.prototype.featuresTimeupdateEvents = false; /** * Boolean indicating whether the `Tech` supports the native `TextTrack`s. * This will help us integrate with native `TextTrack`s if the browser supports them. * * @type {boolean} * @default */ Tech.prototype.featuresNativeTextTracks = false; /** * A functional mixin for techs that want to use the Source Handler pattern. * Source handlers are scripts for handling specific formats. * The source handler pattern is used for adaptive formats (HLS, DASH) that * manually load video data and feed it into a Source Buffer (Media Source Extensions) * Example: `Tech.withSourceHandlers.call(MyTech);` * * @param {Tech} _Tech * The tech to add source handler functions to. * * @mixes Tech~SourceHandlerAdditions */ Tech.withSourceHandlers = function (_Tech) { /** * Register a source handler * * @param {Function} handler * The source handler class * * @param {number} [index] * Register it at the following index */ _Tech.registerSourceHandler = function (handler, index) { var handlers = _Tech.sourceHandlers; if (!handlers) { handlers = _Tech.sourceHandlers = []; } if (index === undefined) { // add to the end of the list index = handlers.length; } handlers.splice(index, 0, handler); }; /** * Check if the tech can support the given type. Also checks the * Techs sourceHandlers. * * @param {string} type * The mimetype to check. * * @return {string} * 'probably', 'maybe', or '' (empty string) */ _Tech.canPlayType = function (type) { var handlers = _Tech.sourceHandlers || []; var can; for (var i = 0; i < handlers.length; i++) { can = handlers[i].canPlayType(type); if (can) { return can; } } return ''; }; /** * Returns the first source handler that supports the source. * * TODO: Answer question: should 'probably' be prioritized over 'maybe' * * @param {Tech~SourceObject} source * The source object * * @param {Object} options * The options passed to the tech * * @return {SourceHandler|null} * The first source handler that supports the source or null if * no SourceHandler supports the source */ _Tech.selectSourceHandler = function (source, options) { var handlers = _Tech.sourceHandlers || []; var can; for (var i = 0; i < handlers.length; i++) { can = handlers[i].canHandleSource(source, options); if (can) { return handlers[i]; } } return null; }; /** * Check if the tech can support the given source. * * @param {Tech~SourceObject} srcObj * The source object * * @param {Object} options * The options passed to the tech * * @return {string} * 'probably', 'maybe', or '' (empty string) */ _Tech.canPlaySource = function (srcObj, options) { var sh = _Tech.selectSourceHandler(srcObj, options); if (sh) { return sh.canHandleSource(srcObj, options); } return ''; }; /** * When using a source handler, prefer its implementation of * any function normally provided by the tech. */ var deferrable = ['seekable', 'seeking', 'duration']; /** * A wrapper around {@link Tech#seekable} that will call a `SourceHandler`s seekable * function if it exists, with a fallback to the Techs seekable function. * * @method _Tech.seekable */ /** * A wrapper around {@link Tech#duration} that will call a `SourceHandler`s duration * function if it exists, otherwise it will fallback to the techs duration function. * * @method _Tech.duration */ deferrable.forEach(function (fnName) { var originalFn = this[fnName]; if (typeof originalFn !== 'function') { return; } this[fnName] = function () { if (this.sourceHandler_ && this.sourceHandler_[fnName]) { return this.sourceHandler_[fnName].apply(this.sourceHandler_, arguments); } return originalFn.apply(this, arguments); }; }, _Tech.prototype); /** * Create a function for setting the source using a source object * and source handlers. * Should never be called unless a source handler was found. * * @param {Tech~SourceObject} source * A source object with src and type keys */ _Tech.prototype.setSource = function (source) { var sh = _Tech.selectSourceHandler(source, this.options_); if (!sh) { // Fall back to a native source hander when unsupported sources are // deliberately set if (_Tech.nativeSourceHandler) { sh = _Tech.nativeSourceHandler; } else { log.error('No source handler found for the current source.'); } } // Dispose any existing source handler this.disposeSourceHandler(); this.off('dispose', this.disposeSourceHandler); if (sh !== _Tech.nativeSourceHandler) { this.currentSource_ = source; } this.sourceHandler_ = sh.handleSource(source, this, this.options_); this.one('dispose', this.disposeSourceHandler); }; /** * Clean up any existing SourceHandlers and listeners when the Tech is disposed. * * @listens Tech#dispose */ _Tech.prototype.disposeSourceHandler = function () { // if we have a source and get another one // then we are loading something new // than clear all of our current tracks if (this.currentSource_) { this.clearTracks(['audio', 'video']); this.currentSource_ = null; } // always clean up auto-text tracks this.cleanupAutoTextTracks(); if (this.sourceHandler_) { if (this.sourceHandler_.dispose) { this.sourceHandler_.dispose(); } this.sourceHandler_ = null; } }; }; // The base Tech class needs to be registered as a Component. It is the only // Tech that can be registered as a Component. Component.registerComponent('Tech', Tech); Tech.registerTech('Tech', Tech); /** * A list of techs that should be added to techOrder on Players * * @private */ Tech.defaultTechOrder_ = []; /** * @file middleware.js * @module middleware */ var middlewares = {}; var middlewareInstances = {}; var TERMINATOR = {}; /** * A middleware object is a plain JavaScript object that has methods that * match the {@link Tech} methods found in the lists of allowed * {@link module:middleware.allowedGetters|getters}, * {@link module:middleware.allowedSetters|setters}, and * {@link module:middleware.allowedMediators|mediators}. * * @typedef {Object} MiddlewareObject */ /** * A middleware factory function that should return a * {@link module:middleware~MiddlewareObject|MiddlewareObject}. * * This factory will be called for each player when needed, with the player * passed in as an argument. * * @callback MiddlewareFactory * @param {Player} player * A Video.js player. */ /** * Define a middleware that the player should use by way of a factory function * that returns a middleware object. * * @param {string} type * The MIME type to match or `"*"` for all MIME types. * * @param {MiddlewareFactory} middleware * A middleware factory function that will be executed for * matching types. */ function use(type, middleware) { middlewares[type] = middlewares[type] || []; middlewares[type].push(middleware); } /** * Asynchronously sets a source using middleware by recursing through any * matching middlewares and calling `setSource` on each, passing along the * previous returned value each time. * * @param {Player} player * A {@link Player} instance. * * @param {Tech~SourceObject} src * A source object. * * @param {Function} * The next middleware to run. */ function setSource(player, src, next) { player.setTimeout(function () { return setSourceHelper(src, middlewares[src.type], next, player); }, 1); } /** * When the tech is set, passes the tech to each middleware's `setTech` method. * * @param {Object[]} middleware * An array of middleware instances. * * @param {Tech} tech * A Video.js tech. */ function setTech(middleware, tech) { middleware.forEach(function (mw) { return mw.setTech && mw.setTech(tech); }); } /** * Calls a getter on the tech first, through each middleware * from right to left to the player. * * @param {Object[]} middleware * An array of middleware instances. * * @param {Tech} tech * The current tech. * * @param {string} method * A method name. * * @return {Mixed} * The final value from the tech after middleware has intercepted it. */ function get(middleware, tech, method) { return middleware.reduceRight(middlewareIterator(method), tech[method]()); } /** * Takes the argument given to the player and calls the setter method on each * middleware from left to right to the tech. * * @param {Object[]} middleware * An array of middleware instances. * * @param {Tech} tech * The current tech. * * @param {string} method * A method name. * * @param {Mixed} arg * The value to set on the tech. * * @return {Mixed} * The return value of the `method` of the `tech`. */ function set(middleware, tech, method, arg) { return tech[method](middleware.reduce(middlewareIterator(method), arg)); } /** * Takes the argument given to the player and calls the `call` version of the * method on each middleware from left to right. * * Then, call the passed in method on the tech and return the result unchanged * back to the player, through middleware, this time from right to left. * * @param {Object[]} middleware * An array of middleware instances. * * @param {Tech} tech * The current tech. * * @param {string} method * A method name. * * @param {Mixed} arg * The value to set on the tech. * * @return {Mixed} * The return value of the `method` of the `tech`, regardless of the * return values of middlewares. */ function mediate(middleware, tech, method, arg) { if (arg === void 0) { arg = null; } var callMethod = 'call' + toTitleCase(method); var middlewareValue = middleware.reduce(middlewareIterator(callMethod), arg); var terminated = middlewareValue === TERMINATOR; // deprecated. The `null` return value should instead return TERMINATOR to // prevent confusion if a techs method actually returns null. var returnValue = terminated ? null : tech[method](middlewareValue); executeRight(middleware, method, returnValue, terminated); return returnValue; } /** * Enumeration of allowed getters where the keys are method names. * * @type {Object} */ var allowedGetters = { buffered: 1, currentTime: 1, duration: 1, seekable: 1, played: 1, paused: 1, volume: 1 }; /** * Enumeration of allowed setters where the keys are method names. * * @type {Object} */ var allowedSetters = { setCurrentTime: 1, setVolume: 1 }; /** * Enumeration of allowed mediators where the keys are method names. * * @type {Object} */ var allowedMediators = { play: 1, pause: 1 }; function middlewareIterator(method) { return function (value, mw) { // if the previous middleware terminated, pass along the termination if (value === TERMINATOR) { return TERMINATOR; } if (mw[method]) { return mw[method](value); } return value; }; } function executeRight(mws, method, value, terminated) { for (var i = mws.length - 1; i >= 0; i--) { var mw = mws[i]; if (mw[method]) { mw[method](terminated, value); } } } /** * Clear the middleware cache for a player. * * @param {Player} player * A {@link Player} instance. */ function clearCacheForPlayer(player) { middlewareInstances[player.id()] = null; } /** * { * [playerId]: [[mwFactory, mwInstance], ...] * } * * @private */ function getOrCreateFactory(player, mwFactory) { var mws = middlewareInstances[player.id()]; var mw = null; if (mws === undefined || mws === null) { mw = mwFactory(player); middlewareInstances[player.id()] = [[mwFactory, mw]]; return mw; } for (var i = 0; i < mws.length; i++) { var _mws$i = mws[i], mwf = _mws$i[0], mwi = _mws$i[1]; if (mwf !== mwFactory) { continue; } mw = mwi; } if (mw === null) { mw = mwFactory(player); mws.push([mwFactory, mw]); } return mw; } function setSourceHelper(src, middleware, next, player, acc, lastRun) { if (src === void 0) { src = {}; } if (middleware === void 0) { middleware = []; } if (acc === void 0) { acc = []; } if (lastRun === void 0) { lastRun = false; } var _middleware = middleware, mwFactory = _middleware[0], mwrest = _middleware.slice(1); // if mwFactory is a string, then we're at a fork in the road if (typeof mwFactory === 'string') { setSourceHelper(src, middlewares[mwFactory], next, player, acc, lastRun); // if we have an mwFactory, call it with the player to get the mw, // then call the mw's setSource method } else if (mwFactory) { var mw = getOrCreateFactory(player, mwFactory); // if setSource isn't present, implicitly select this middleware if (!mw.setSource) { acc.push(mw); return setSourceHelper(src, mwrest, next, player, acc, lastRun); } mw.setSource(assign({}, src), function (err, _src) { // something happened, try the next middleware on the current level // make sure to use the old src if (err) { return setSourceHelper(src, mwrest, next, player, acc, lastRun); } // we've succeeded, now we need to go deeper acc.push(mw); // if it's the same type, continue down the current chain // otherwise, we want to go down the new chain setSourceHelper(_src, src.type === _src.type ? mwrest : middlewares[_src.type], next, player, acc, lastRun); }); } else if (mwrest.length) { setSourceHelper(src, mwrest, next, player, acc, lastRun); } else if (lastRun) { next(src, acc); } else { setSourceHelper(src, middlewares['*'], next, player, acc, true); } } /** * Mimetypes * * @see http://hul.harvard.edu/ois/////systems/wax/wax-public-help/mimetypes.htm * @typedef Mimetypes~Kind * @enum */ var MimetypesKind = { opus: 'video/ogg', ogv: 'video/ogg', mp4: 'video/mp4', mov: 'video/mp4', m4v: 'video/mp4', mkv: 'video/x-matroska', m4a: 'audio/mp4', mp3: 'audio/mpeg', aac: 'audio/aac', oga: 'audio/ogg', m3u8: 'application/x-mpegURL', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', png: 'image/png', svg: 'image/svg+xml', webp: 'image/webp' }; /** * Get the mimetype of a given src url if possible * * @param {string} src * The url to the src * * @return {string} * return the mimetype if it was known or empty string otherwise */ var getMimetype = function getMimetype(src) { if (src === void 0) { src = ''; } var ext = getFileExtension(src); var mimetype = MimetypesKind[ext.toLowerCase()]; return mimetype || ''; }; /** * Find the mime type of a given source string if possible. Uses the player * source cache. * * @param {Player} player * The player object * * @param {string} src * The source string * * @return {string} * The type that was found */ var findMimetype = function findMimetype(player, src) { if (!src) { return ''; } // 1. check for the type in the `source` cache if (player.cache_.source.src === src && player.cache_.source.type) { return player.cache_.source.type; } // 2. see if we have this source in our `currentSources` cache var matchingSources = player.cache_.sources.filter(function (s) { return s.src === src; }); if (matchingSources.length) { return matchingSources[0].type; } // 3. look for the src url in source elements and use the type there var sources = player.$$('source'); for (var i = 0; i < sources.length; i++) { var s = sources[i]; if (s.type && s.src && s.src === src) { return s.type; } } // 4. finally fallback to our list of mime types based on src url extension return getMimetype(src); }; /** * @module filter-source */ /** * Filter out single bad source objects or multiple source objects in an * array. Also flattens nested source object arrays into a 1 dimensional * array of source objects. * * @param {Tech~SourceObject|Tech~SourceObject[]} src * The src object to filter * * @return {Tech~SourceObject[]} * An array of sourceobjects containing only valid sources * * @private */ var filterSource = function filterSource(src) { // traverse array if (Array.isArray(src)) { var newsrc = []; src.forEach(function (srcobj) { srcobj = filterSource(srcobj); if (Array.isArray(srcobj)) { newsrc = newsrc.concat(srcobj); } else if (isObject(srcobj)) { newsrc.push(srcobj); } }); src = newsrc; } else if (typeof src === 'string' && src.trim()) { // convert string into object src = [fixSource({ src: src })]; } else if (isObject(src) && typeof src.src === 'string' && src.src && src.src.trim()) { // src is already valid src = [fixSource(src)]; } else { // invalid source, turn it into an empty array src = []; } return src; }; /** * Checks src mimetype, adding it when possible * * @param {Tech~SourceObject} src * The src object to check * @return {Tech~SourceObject} * src Object with known type */ function fixSource(src) { if (!src.type) { var mimetype = getMimetype(src.src); if (mimetype) { src.type = mimetype; } } return src; } /** * The `MediaLoader` is the `Component` that decides which playback technology to load * when a player is initialized. * * @extends Component */ var MediaLoader = /*#__PURE__*/ function (_Component) { _inheritsLoose(MediaLoader, _Component); /** * Create an instance of this class. * * @param {Player} player * The `Player` that this class should attach to. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} [ready] * The function that is run when this component is ready. */ function MediaLoader(player, options, ready) { var _this; // MediaLoader has no element var options_ = mergeOptions({ createEl: false }, options); _this = _Component.call(this, player, options_, ready) || this; // If there are no sources when the player is initialized, // load the first supported playback technology. if (!options.playerOptions.sources || options.playerOptions.sources.length === 0) { for (var i = 0, j = options.playerOptions.techOrder; i < j.length; i++) { var techName = toTitleCase(j[i]); var tech = Tech.getTech(techName); // Support old behavior of techs being registered as components. // Remove once that deprecated behavior is removed. if (!techName) { tech = Component.getComponent(techName); } // Check if the browser supports this technology if (tech && tech.isSupported()) { player.loadTech_(techName); break; } } } else { // Loop through playback technologies (HTML5, Flash) and check for support. // Then load the best source. // A few assumptions here: // All playback technologies respect preload false. player.src(options.playerOptions.sources); } return _this; } return MediaLoader; }(Component); Component.registerComponent('MediaLoader', MediaLoader); /** * Component which is clickable or keyboard actionable, but is not a * native HTML button. * * @extends Component */ var ClickableComponent = /*#__PURE__*/ function (_Component) { _inheritsLoose(ClickableComponent, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function ClickableComponent(player, options) { var _this; _this = _Component.call(this, player, options) || this; _this.emitTapEvents(); _this.enable(); return _this; } /** * Create the `ClickableComponent`s DOM element. * * @param {string} [tag=div] * The element's node type. * * @param {Object} [props={}] * An object of properties that should be set on the element. * * @param {Object} [attributes={}] * An object of attributes that should be set on the element. * * @return {Element} * The element that gets created. */ var _proto = ClickableComponent.prototype; _proto.createEl = function createEl(tag, props, attributes) { if (tag === void 0) { tag = 'div'; } if (props === void 0) { props = {}; } if (attributes === void 0) { attributes = {}; } props = assign({ innerHTML: '<span aria-hidden="true" class="vjs-icon-placeholder"></span>', className: this.buildCSSClass(), tabIndex: 0 }, props); if (tag === 'button') { log.error("Creating a ClickableComponent with an HTML element of " + tag + " is not supported; use a Button instead."); } // Add ARIA attributes for clickable element which is not a native HTML button attributes = assign({ role: 'button' }, attributes); this.tabIndex_ = props.tabIndex; var el = _Component.prototype.createEl.call(this, tag, props, attributes); this.createControlTextEl(el); return el; }; _proto.dispose = function dispose() { // remove controlTextEl_ on dispose this.controlTextEl_ = null; _Component.prototype.dispose.call(this); } /** * Create a control text element on this `ClickableComponent` * * @param {Element} [el] * Parent element for the control text. * * @return {Element} * The control text element that gets created. */ ; _proto.createControlTextEl = function createControlTextEl(el) { this.controlTextEl_ = createEl('span', { className: 'vjs-control-text' }, { // let the screen reader user know that the text of the element may change 'aria-live': 'polite' }); if (el) { el.appendChild(this.controlTextEl_); } this.controlText(this.controlText_, el); return this.controlTextEl_; } /** * Get or set the localize text to use for the controls on the `ClickableComponent`. * * @param {string} [text] * Control text for element. * * @param {Element} [el=this.el()] * Element to set the title on. * * @return {string} * - The control text when getting */ ; _proto.controlText = function controlText(text, el) { if (el === void 0) { el = this.el(); } if (text === undefined) { return this.controlText_ || 'Need Text'; } var localizedText = this.localize(text); this.controlText_ = text; textContent(this.controlTextEl_, localizedText); if (!this.nonIconControl) { // Set title attribute if only an icon is shown el.setAttribute('title', localizedText); } } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ ; _proto.buildCSSClass = function buildCSSClass() { return "vjs-control vjs-button " + _Component.prototype.buildCSSClass.call(this); } /** * Enable this `ClickableComponent` */ ; _proto.enable = function enable() { if (!this.enabled_) { this.enabled_ = true; this.removeClass('vjs-disabled'); this.el_.setAttribute('aria-disabled', 'false'); if (typeof this.tabIndex_ !== 'undefined') { this.el_.setAttribute('tabIndex', this.tabIndex_); } this.on(['tap', 'click'], this.handleClick); this.on('keydown', this.handleKeyDown); } } /** * Disable this `ClickableComponent` */ ; _proto.disable = function disable() { this.enabled_ = false; this.addClass('vjs-disabled'); this.el_.setAttribute('aria-disabled', 'true'); if (typeof this.tabIndex_ !== 'undefined') { this.el_.removeAttribute('tabIndex'); } this.off('mouseover', this.handleMouseOver); this.off('mouseout', this.handleMouseOut); this.off(['tap', 'click'], this.handleClick); this.off('keydown', this.handleKeyDown); } /** * Event handler that is called when a `ClickableComponent` receives a * `click` or `tap` event. * * @param {EventTarget~Event} event * The `tap` or `click` event that caused this function to be called. * * @listens tap * @listens click * @abstract */ ; _proto.handleClick = function handleClick(event) {} /** * Event handler that is called when a `ClickableComponent` receives a * `keydown` event. * * By default, if the key is Space or Enter, it will trigger a `click` event. * * @param {EventTarget~Event} event * The `keydown` event that caused this function to be called. * * @listens keydown */ ; _proto.handleKeyDown = function handleKeyDown(event) { // Support Space or Enter key operation to fire a click event. Also, // prevent the event from propagating through the DOM and triggering // Player hotkeys. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) { event.preventDefault(); event.stopPropagation(); this.trigger('click'); } else { // Pass keypress handling up for unsupported keys _Component.prototype.handleKeyDown.call(this, event); } }; return ClickableComponent; }(Component); Component.registerComponent('ClickableComponent', ClickableComponent); /** * A `ClickableComponent` that handles showing the poster image for the player. * * @extends ClickableComponent */ var PosterImage = /*#__PURE__*/ function (_ClickableComponent) { _inheritsLoose(PosterImage, _ClickableComponent); /** * Create an instance of this class. * * @param {Player} player * The `Player` that this class should attach to. * * @param {Object} [options] * The key/value store of player options. */ function PosterImage(player, options) { var _this; _this = _ClickableComponent.call(this, player, options) || this; _this.update(); player.on('posterchange', bind(_assertThisInitialized(_this), _this.update)); return _this; } /** * Clean up and dispose of the `PosterImage`. */ var _proto = PosterImage.prototype; _proto.dispose = function dispose() { this.player().off('posterchange', this.update); _ClickableComponent.prototype.dispose.call(this); } /** * Create the `PosterImage`s DOM element. * * @return {Element} * The element that gets created. */ ; _proto.createEl = function createEl$1() { var el = createEl('div', { className: 'vjs-poster', // Don't want poster to be tabbable. tabIndex: -1 }); return el; } /** * An {@link EventTarget~EventListener} for {@link Player#posterchange} events. * * @listens Player#posterchange * * @param {EventTarget~Event} [event] * The `Player#posterchange` event that triggered this function. */ ; _proto.update = function update(event) { var url = this.player().poster(); this.setSrc(url); // If there's no poster source we should display:none on this component // so it's not still clickable or right-clickable if (url) { this.show(); } else { this.hide(); } } /** * Set the source of the `PosterImage` depending on the display method. * * @param {string} url * The URL to the source for the `PosterImage`. */ ; _proto.setSrc = function setSrc(url) { var backgroundImage = ''; // Any falsy value should stay as an empty string, otherwise // this will throw an extra error if (url) { backgroundImage = "url(\"" + url + "\")"; } this.el_.style.backgroundImage = backgroundImage; } /** * An {@link EventTarget~EventListener} for clicks on the `PosterImage`. See * {@link ClickableComponent#handleClick} for instances where this will be triggered. * * @listens tap * @listens click * @listens keydown * * @param {EventTarget~Event} event + The `click`, `tap` or `keydown` event that caused this function to be called. */ ; _proto.handleClick = function handleClick(event) { // We don't want a click to trigger playback when controls are disabled if (!this.player_.controls()) { return; } if (this.player_.tech(true)) { this.player_.tech(true).focus(); } if (this.player_.paused()) { silencePromise(this.player_.play()); } else { this.player_.pause(); } }; return PosterImage; }(ClickableComponent); Component.registerComponent('PosterImage', PosterImage); var darkGray = '#222'; var lightGray = '#ccc'; var fontMap = { monospace: 'monospace', sansSerif: 'sans-serif', serif: 'serif', monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace', monospaceSerif: '"Courier New", monospace', proportionalSansSerif: 'sans-serif', proportionalSerif: 'serif', casual: '"Comic Sans MS", Impact, fantasy', script: '"Monotype Corsiva", cursive', smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif' }; /** * Construct an rgba color from a given hex color code. * * @param {number} color * Hex number for color, like #f0e or #f604e2. * * @param {number} opacity * Value for opacity, 0.0 - 1.0. * * @return {string} * The rgba color that was created, like 'rgba(255, 0, 0, 0.3)'. */ function constructColor(color, opacity) { var hex; if (color.length === 4) { // color looks like "#f0e" hex = color[1] + color[1] + color[2] + color[2] + color[3] + color[3]; } else if (color.length === 7) { // color looks like "#f604e2" hex = color.slice(1); } else { throw new Error('Invalid color code provided, ' + color + '; must be formatted as e.g. #f0e or #f604e2.'); } return 'rgba(' + parseInt(hex.slice(0, 2), 16) + ',' + parseInt(hex.slice(2, 4), 16) + ',' + parseInt(hex.slice(4, 6), 16) + ',' + opacity + ')'; } /** * Try to update the style of a DOM element. Some style changes will throw an error, * particularly in IE8. Those should be noops. * * @param {Element} el * The DOM element to be styled. * * @param {string} style * The CSS property on the element that should be styled. * * @param {string} rule * The style rule that should be applied to the property. * * @private */ function tryUpdateStyle(el, style, rule) { try { el.style[style] = rule; } catch (e) { // Satisfies linter. return; } } /** * The component for displaying text track cues. * * @extends Component */ var TextTrackDisplay = /*#__PURE__*/ function (_Component) { _inheritsLoose(TextTrackDisplay, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} [ready] * The function to call when `TextTrackDisplay` is ready. */ function TextTrackDisplay(player, options, ready) { var _this; _this = _Component.call(this, player, options, ready) || this; var updateDisplayHandler = bind(_assertThisInitialized(_this), _this.updateDisplay); player.on('loadstart', bind(_assertThisInitialized(_this), _this.toggleDisplay)); player.on('texttrackchange', updateDisplayHandler); player.on('loadedmetadata', bind(_assertThisInitialized(_this), _this.preselectTrack)); // This used to be called during player init, but was causing an error // if a track should show by default and the display hadn't loaded yet. // Should probably be moved to an external track loader when we support // tracks that don't need a display. player.ready(bind(_assertThisInitialized(_this), function () { if (player.tech_ && player.tech_.featuresNativeTextTracks) { this.hide(); return; } player.on('fullscreenchange', updateDisplayHandler); player.on('playerresize', updateDisplayHandler); window$1.addEventListener('orientationchange', updateDisplayHandler); player.on('dispose', function () { return window$1.removeEventListener('orientationchange', updateDisplayHandler); }); var tracks = this.options_.playerOptions.tracks || []; for (var i = 0; i < tracks.length; i++) { this.player_.addRemoteTextTrack(tracks[i], true); } this.preselectTrack(); })); return _this; } /** * Preselect a track following this precedence: * - matches the previously selected {@link TextTrack}'s language and kind * - matches the previously selected {@link TextTrack}'s language only * - is the first default captions track * - is the first default descriptions track * * @listens Player#loadstart */ var _proto = TextTrackDisplay.prototype; _proto.preselectTrack = function preselectTrack() { var modes = { captions: 1, subtitles: 1 }; var trackList = this.player_.textTracks(); var userPref = this.player_.cache_.selectedLanguage; var firstDesc; var firstCaptions; var preferredTrack; for (var i = 0; i < trackList.length; i++) { var track = trackList[i]; if (userPref && userPref.enabled && userPref.language && userPref.language === track.language && track.kind in modes) { // Always choose the track that matches both language and kind if (track.kind === userPref.kind) { preferredTrack = track; // or choose the first track that matches language } else if (!preferredTrack) { preferredTrack = track; } // clear everything if offTextTrackMenuItem was clicked } else if (userPref && !userPref.enabled) { preferredTrack = null; firstDesc = null; firstCaptions = null; } else if (track["default"]) { if (track.kind === 'descriptions' && !firstDesc) { firstDesc = track; } else if (track.kind in modes && !firstCaptions) { firstCaptions = track; } } } // The preferredTrack matches the user preference and takes // precedence over all the other tracks. // So, display the preferredTrack before the first default track // and the subtitles/captions track before the descriptions track if (preferredTrack) { preferredTrack.mode = 'showing'; } else if (firstCaptions) { firstCaptions.mode = 'showing'; } else if (firstDesc) { firstDesc.mode = 'showing'; } } /** * Turn display of {@link TextTrack}'s from the current state into the other state. * There are only two states: * - 'shown' * - 'hidden' * * @listens Player#loadstart */ ; _proto.toggleDisplay = function toggleDisplay() { if (this.player_.tech_ && this.player_.tech_.featuresNativeTextTracks) { this.hide(); } else { this.show(); } } /** * Create the {@link Component}'s DOM element. * * @return {Element} * The element that was created. */ ; _proto.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-text-track-display' }, { 'aria-live': 'off', 'aria-atomic': 'true' }); } /** * Clear all displayed {@link TextTrack}s. */ ; _proto.clearDisplay = function clearDisplay() { if (typeof window$1.WebVTT === 'function') { window$1.WebVTT.processCues(window$1, [], this.el_); } } /** * Update the displayed TextTrack when a either a {@link Player#texttrackchange} or * a {@link Player#fullscreenchange} is fired. * * @listens Player#texttrackchange * @listens Player#fullscreenchange */ ; _proto.updateDisplay = function updateDisplay() { var tracks = this.player_.textTracks(); var allowMultipleShowingTracks = this.options_.allowMultipleShowingTracks; this.clearDisplay(); if (allowMultipleShowingTracks) { var showingTracks = []; for (var _i = 0; _i < tracks.length; ++_i) { var track = tracks[_i]; if (track.mode !== 'showing') { continue; } showingTracks.push(track); } this.updateForTrack(showingTracks); return; } // Track display prioritization model: if multiple tracks are 'showing', // display the first 'subtitles' or 'captions' track which is 'showing', // otherwise display the first 'descriptions' track which is 'showing' var descriptionsTrack = null; var captionsSubtitlesTrack = null; var i = tracks.length; while (i--) { var _track = tracks[i]; if (_track.mode === 'showing') { if (_track.kind === 'descriptions') { descriptionsTrack = _track; } else { captionsSubtitlesTrack = _track; } } } if (captionsSubtitlesTrack) { if (this.getAttribute('aria-live') !== 'off') { this.setAttribute('aria-live', 'off'); } this.updateForTrack(captionsSubtitlesTrack); } else if (descriptionsTrack) { if (this.getAttribute('aria-live') !== 'assertive') { this.setAttribute('aria-live', 'assertive'); } this.updateForTrack(descriptionsTrack); } } /** * Style {@Link TextTrack} activeCues according to {@Link TextTrackSettings}. * * @param {TextTrack} track * Text track object containing active cues to style. */ ; _proto.updateDisplayState = function updateDisplayState(track) { var overrides = this.player_.textTrackSettings.getValues(); var cues = track.activeCues; var i = cues.length; while (i--) { var cue = cues[i]; if (!cue) { continue; } var cueDiv = cue.displayState; if (overrides.color) { cueDiv.firstChild.style.color = overrides.color; } if (overrides.textOpacity) { tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity)); } if (overrides.backgroundColor) { cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor; } if (overrides.backgroundOpacity) { tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity)); } if (overrides.windowColor) { if (overrides.windowOpacity) { tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity)); } else { cueDiv.style.backgroundColor = overrides.windowColor; } } if (overrides.edgeStyle) { if (overrides.edgeStyle === 'dropshadow') { cueDiv.firstChild.style.textShadow = "2px 2px 3px " + darkGray + ", 2px 2px 4px " + darkGray + ", 2px 2px 5px " + darkGray; } else if (overrides.edgeStyle === 'raised') { cueDiv.firstChild.style.textShadow = "1px 1px " + darkGray + ", 2px 2px " + darkGray + ", 3px 3px " + darkGray; } else if (overrides.edgeStyle === 'depressed') { cueDiv.firstChild.style.textShadow = "1px 1px " + lightGray + ", 0 1px " + lightGray + ", -1px -1px " + darkGray + ", 0 -1px " + darkGray; } else if (overrides.edgeStyle === 'uniform') { cueDiv.firstChild.style.textShadow = "0 0 4px " + darkGray + ", 0 0 4px " + darkGray + ", 0 0 4px " + darkGray + ", 0 0 4px " + darkGray; } } if (overrides.fontPercent && overrides.fontPercent !== 1) { var fontSize = window$1.parseFloat(cueDiv.style.fontSize); cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px'; cueDiv.style.height = 'auto'; cueDiv.style.top = 'auto'; cueDiv.style.bottom = '2px'; } if (overrides.fontFamily && overrides.fontFamily !== 'default') { if (overrides.fontFamily === 'small-caps') { cueDiv.firstChild.style.fontVariant = 'small-caps'; } else { cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily]; } } } } /** * Add an {@link TextTrack} to to the {@link Tech}s {@link TextTrackList}. * * @param {TextTrack|TextTrack[]} tracks * Text track object or text track array to be added to the list. */ ; _proto.updateForTrack = function updateForTrack(tracks) { if (!Array.isArray(tracks)) { tracks = [tracks]; } if (typeof window$1.WebVTT !== 'function' || tracks.every(function (track) { return !track.activeCues; })) { return; } var cues = []; // push all active track cues for (var i = 0; i < tracks.length; ++i) { var track = tracks[i]; for (var j = 0; j < track.activeCues.length; ++j) { cues.push(track.activeCues[j]); } } // removes all cues before it processes new ones window$1.WebVTT.processCues(window$1, cues, this.el_); // add unique class to each language text track & add settings styling if necessary for (var _i2 = 0; _i2 < tracks.length; ++_i2) { var _track2 = tracks[_i2]; for (var _j = 0; _j < _track2.activeCues.length; ++_j) { var cueEl = _track2.activeCues[_j].displayState; addClass(cueEl, 'vjs-text-track-cue'); addClass(cueEl, 'vjs-text-track-cue-' + (_track2.language ? _track2.language : _i2)); } if (this.player_.textTrackSettings) { this.updateDisplayState(_track2); } } }; return TextTrackDisplay; }(Component); Component.registerComponent('TextTrackDisplay', TextTrackDisplay); /** * A loading spinner for use during waiting/loading events. * * @extends Component */ var LoadingSpinner = /*#__PURE__*/ function (_Component) { _inheritsLoose(LoadingSpinner, _Component); function LoadingSpinner() { return _Component.apply(this, arguments) || this; } var _proto = LoadingSpinner.prototype; /** * Create the `LoadingSpinner`s DOM element. * * @return {Element} * The dom element that gets created. */ _proto.createEl = function createEl$1() { var isAudio = this.player_.isAudio(); var playerType = this.localize(isAudio ? 'Audio Player' : 'Video Player'); var controlText = createEl('span', { className: 'vjs-control-text', innerHTML: this.localize('{1} is loading.', [playerType]) }); var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-loading-spinner', dir: 'ltr' }); el.appendChild(controlText); return el; }; return LoadingSpinner; }(Component); Component.registerComponent('LoadingSpinner', LoadingSpinner); /** * Base class for all buttons. * * @extends ClickableComponent */ var Button = /*#__PURE__*/ function (_ClickableComponent) { _inheritsLoose(Button, _ClickableComponent); function Button() { return _ClickableComponent.apply(this, arguments) || this; } var _proto = Button.prototype; /** * Create the `Button`s DOM element. * * @param {string} [tag="button"] * The element's node type. This argument is IGNORED: no matter what * is passed, it will always create a `button` element. * * @param {Object} [props={}] * An object of properties that should be set on the element. * * @param {Object} [attributes={}] * An object of attributes that should be set on the element. * * @return {Element} * The element that gets created. */ _proto.createEl = function createEl(tag, props, attributes) { if (props === void 0) { props = {}; } if (attributes === void 0) { attributes = {}; } tag = 'button'; props = assign({ innerHTML: '<span aria-hidden="true" class="vjs-icon-placeholder"></span>', className: this.buildCSSClass() }, props); // Add attributes for button element attributes = assign({ // Necessary since the default button type is "submit" type: 'button' }, attributes); var el = Component.prototype.createEl.call(this, tag, props, attributes); this.createControlTextEl(el); return el; } /** * Add a child `Component` inside of this `Button`. * * @param {string|Component} child * The name or instance of a child to add. * * @param {Object} [options={}] * The key/value store of options that will get passed to children of * the child. * * @return {Component} * The `Component` that gets added as a child. When using a string the * `Component` will get created by this process. * * @deprecated since version 5 */ ; _proto.addChild = function addChild(child, options) { if (options === void 0) { options = {}; } var className = this.constructor.name; log.warn("Adding an actionable (user controllable) child to a Button (" + className + ") is not supported; use a ClickableComponent instead."); // Avoid the error message generated by ClickableComponent's addChild method return Component.prototype.addChild.call(this, child, options); } /** * Enable the `Button` element so that it can be activated or clicked. Use this with * {@link Button#disable}. */ ; _proto.enable = function enable() { _ClickableComponent.prototype.enable.call(this); this.el_.removeAttribute('disabled'); } /** * Disable the `Button` element so that it cannot be activated or clicked. Use this with * {@link Button#enable}. */ ; _proto.disable = function disable() { _ClickableComponent.prototype.disable.call(this); this.el_.setAttribute('disabled', 'disabled'); } /** * This gets called when a `Button` has focus and `keydown` is triggered via a key * press. * * @param {EventTarget~Event} event * The event that caused this function to get called. * * @listens keydown */ ; _proto.handleKeyDown = function handleKeyDown(event) { // Ignore Space or Enter key operation, which is handled by the browser for // a button - though not for its super class, ClickableComponent. Also, // prevent the event from propagating through the DOM and triggering Player // hotkeys. We do not preventDefault here because we _want_ the browser to // handle it. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) { event.stopPropagation(); return; } // Pass keypress handling up for unsupported keys _ClickableComponent.prototype.handleKeyDown.call(this, event); }; return Button; }(ClickableComponent); Component.registerComponent('Button', Button); /** * The initial play button that shows before the video has played. The hiding of the * `BigPlayButton` get done via CSS and `Player` states. * * @extends Button */ var BigPlayButton = /*#__PURE__*/ function (_Button) { _inheritsLoose(BigPlayButton, _Button); function BigPlayButton(player, options) { var _this; _this = _Button.call(this, player, options) || this; _this.mouseused_ = false; _this.on('mousedown', _this.handleMouseDown); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. Always returns 'vjs-big-play-button'. */ var _proto = BigPlayButton.prototype; _proto.buildCSSClass = function buildCSSClass() { return 'vjs-big-play-button'; } /** * This gets called when a `BigPlayButton` "clicked". See {@link ClickableComponent} * for more detailed information on what a click can be. * * @param {EventTarget~Event} event * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ ; _proto.handleClick = function handleClick(event) { var playPromise = this.player_.play(); // exit early if clicked via the mouse if (this.mouseused_ && event.clientX && event.clientY) { silencePromise(playPromise); if (this.player_.tech(true)) { this.player_.tech(true).focus(); } return; } var cb = this.player_.getChild('controlBar'); var playToggle = cb && cb.getChild('playToggle'); if (!playToggle) { this.player_.tech(true).focus(); return; } var playFocus = function playFocus() { return playToggle.focus(); }; if (isPromise(playPromise)) { playPromise.then(playFocus, function () {}); } else { this.setTimeout(playFocus, 1); } }; _proto.handleKeyDown = function handleKeyDown(event) { this.mouseused_ = false; _Button.prototype.handleKeyDown.call(this, event); }; _proto.handleMouseDown = function handleMouseDown(event) { this.mouseused_ = true; }; return BigPlayButton; }(Button); /** * The text that should display over the `BigPlayButton`s controls. Added to for localization. * * @type {string} * @private */ BigPlayButton.prototype.controlText_ = 'Play Video'; Component.registerComponent('BigPlayButton', BigPlayButton); /** * The `CloseButton` is a `{@link Button}` that fires a `close` event when * it gets clicked. * * @extends Button */ var CloseButton = /*#__PURE__*/ function (_Button) { _inheritsLoose(CloseButton, _Button); /** * Creates an instance of the this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function CloseButton(player, options) { var _this; _this = _Button.call(this, player, options) || this; _this.controlText(options && options.controlText || _this.localize('Close')); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ var _proto = CloseButton.prototype; _proto.buildCSSClass = function buildCSSClass() { return "vjs-close-button " + _Button.prototype.buildCSSClass.call(this); } /** * This gets called when a `CloseButton` gets clicked. See * {@link ClickableComponent#handleClick} for more information on when * this will be triggered * * @param {EventTarget~Event} event * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click * @fires CloseButton#close */ ; _proto.handleClick = function handleClick(event) { /** * Triggered when the a `CloseButton` is clicked. * * @event CloseButton#close * @type {EventTarget~Event} * * @property {boolean} [bubbles=false] * set to false so that the close event does not * bubble up to parents if there is no listener */ this.trigger({ type: 'close', bubbles: false }); } /** * Event handler that is called when a `CloseButton` receives a * `keydown` event. * * By default, if the key is Esc, it will trigger a `click` event. * * @param {EventTarget~Event} event * The `keydown` event that caused this function to be called. * * @listens keydown */ ; _proto.handleKeyDown = function handleKeyDown(event) { // Esc button will trigger `click` event if (keycode.isEventKey(event, 'Esc')) { event.preventDefault(); event.stopPropagation(); this.trigger('click'); } else { // Pass keypress handling up for unsupported keys _Button.prototype.handleKeyDown.call(this, event); } }; return CloseButton; }(Button); Component.registerComponent('CloseButton', CloseButton); /** * Button to toggle between play and pause. * * @extends Button */ var PlayToggle = /*#__PURE__*/ function (_Button) { _inheritsLoose(PlayToggle, _Button); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options={}] * The key/value store of player options. */ function PlayToggle(player, options) { var _this; if (options === void 0) { options = {}; } _this = _Button.call(this, player, options) || this; // show or hide replay icon options.replay = options.replay === undefined || options.replay; _this.on(player, 'play', _this.handlePlay); _this.on(player, 'pause', _this.handlePause); if (options.replay) { _this.on(player, 'ended', _this.handleEnded); } return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ var _proto = PlayToggle.prototype; _proto.buildCSSClass = function buildCSSClass() { return "vjs-play-control " + _Button.prototype.buildCSSClass.call(this); } /** * This gets called when an `PlayToggle` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ ; _proto.handleClick = function handleClick(event) { if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } } /** * This gets called once after the video has ended and the user seeks so that * we can change the replay button back to a play button. * * @param {EventTarget~Event} [event] * The event that caused this function to run. * * @listens Player#seeked */ ; _proto.handleSeeked = function handleSeeked(event) { this.removeClass('vjs-ended'); if (this.player_.paused()) { this.handlePause(event); } else { this.handlePlay(event); } } /** * Add the vjs-playing class to the element so it can change appearance. * * @param {EventTarget~Event} [event] * The event that caused this function to run. * * @listens Player#play */ ; _proto.handlePlay = function handlePlay(event) { this.removeClass('vjs-ended'); this.removeClass('vjs-paused'); this.addClass('vjs-playing'); // change the button text to "Pause" this.controlText('Pause'); } /** * Add the vjs-paused class to the element so it can change appearance. * * @param {EventTarget~Event} [event] * The event that caused this function to run. * * @listens Player#pause */ ; _proto.handlePause = function handlePause(event) { this.removeClass('vjs-playing'); this.addClass('vjs-paused'); // change the button text to "Play" this.controlText('Play'); } /** * Add the vjs-ended class to the element so it can change appearance * * @param {EventTarget~Event} [event] * The event that caused this function to run. * * @listens Player#ended */ ; _proto.handleEnded = function handleEnded(event) { this.removeClass('vjs-playing'); this.addClass('vjs-ended'); // change the button text to "Replay" this.controlText('Replay'); // on the next seek remove the replay button this.one(this.player_, 'seeked', this.handleSeeked); }; return PlayToggle; }(Button); /** * The text that should display over the `PlayToggle`s controls. Added for localization. * * @type {string} * @private */ PlayToggle.prototype.controlText_ = 'Play'; Component.registerComponent('PlayToggle', PlayToggle); /** * @file format-time.js * @module format-time */ /** * Format seconds as a time string, H:MM:SS or M:SS. Supplying a guide (in * seconds) will force a number of leading zeros to cover the length of the * guide. * * @private * @param {number} seconds * Number of seconds to be turned into a string * * @param {number} guide * Number (in seconds) to model the string after * * @return {string} * Time formatted as H:MM:SS or M:SS */ var defaultImplementation = function defaultImplementation(seconds, guide) { seconds = seconds < 0 ? 0 : seconds; var s = Math.floor(seconds % 60); var m = Math.floor(seconds / 60 % 60); var h = Math.floor(seconds / 3600); var gm = Math.floor(guide / 60 % 60); var gh = Math.floor(guide / 3600); // handle invalid times if (isNaN(seconds) || seconds === Infinity) { // '-' is false for all relational operators (e.g. <, >=) so this setting // will add the minimum number of fields specified by the guide h = m = s = '-'; } // Check if we need to show hours h = h > 0 || gh > 0 ? h + ':' : ''; // If hours are showing, we may need to add a leading zero. // Always show at least one digit of minutes. m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':'; // Check if leading zero is need for seconds s = s < 10 ? '0' + s : s; return h + m + s; }; // Internal pointer to the current implementation. var implementation$3 = defaultImplementation; /** * Replaces the default formatTime implementation with a custom implementation. * * @param {Function} customImplementation * A function which will be used in place of the default formatTime * implementation. Will receive the current time in seconds and the * guide (in seconds) as arguments. */ function setFormatTime(customImplementation) { implementation$3 = customImplementation; } /** * Resets formatTime to the default implementation. */ function resetFormatTime() { implementation$3 = defaultImplementation; } /** * Delegates to either the default time formatting function or a custom * function supplied via `setFormatTime`. * * Formats seconds as a time string (H:MM:SS or M:SS). Supplying a * guide (in seconds) will force a number of leading zeros to cover the * length of the guide. * * @static * @example formatTime(125, 600) === "02:05" * @param {number} seconds * Number of seconds to be turned into a string * * @param {number} guide * Number (in seconds) to model the string after * * @return {string} * Time formatted as H:MM:SS or M:SS */ function formatTime(seconds, guide) { if (guide === void 0) { guide = seconds; } return implementation$3(seconds, guide); } /** * Displays time information about the video * * @extends Component */ var TimeDisplay = /*#__PURE__*/ function (_Component) { _inheritsLoose(TimeDisplay, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function TimeDisplay(player, options) { var _this; _this = _Component.call(this, player, options) || this; _this.throttledUpdateContent = throttle(bind(_assertThisInitialized(_this), _this.updateContent), UPDATE_REFRESH_INTERVAL); _this.on(player, 'timeupdate', _this.throttledUpdateContent); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ var _proto = TimeDisplay.prototype; _proto.createEl = function createEl$1() { var className = this.buildCSSClass(); var el = _Component.prototype.createEl.call(this, 'div', { className: className + " vjs-time-control vjs-control", innerHTML: "<span class=\"vjs-control-text\" role=\"presentation\">" + this.localize(this.labelText_) + "\xA0</span>" }); this.contentEl_ = createEl('span', { className: className + "-display" }, { // tell screen readers not to automatically read the time as it changes 'aria-live': 'off', // span elements have no implicit role, but some screen readers (notably VoiceOver) // treat them as a break between items in the DOM when using arrow keys // (or left-to-right swipes on iOS) to read contents of a page. Using // role='presentation' causes VoiceOver to NOT treat this span as a break. 'role': 'presentation' }); this.updateTextNode_(); el.appendChild(this.contentEl_); return el; }; _proto.dispose = function dispose() { this.contentEl_ = null; this.textNode_ = null; _Component.prototype.dispose.call(this); } /** * Updates the "remaining time" text node with new content using the * contents of the `formattedTime_` property. * * @private */ ; _proto.updateTextNode_ = function updateTextNode_() { if (!this.contentEl_) { return; } while (this.contentEl_.firstChild) { this.contentEl_.removeChild(this.contentEl_.firstChild); } this.textNode_ = document.createTextNode(this.formattedTime_ || this.formatTime_(0)); this.contentEl_.appendChild(this.textNode_); } /** * Generates a formatted time for this component to use in display. * * @param {number} time * A numeric time, in seconds. * * @return {string} * A formatted time * * @private */ ; _proto.formatTime_ = function formatTime_(time) { return formatTime(time); } /** * Updates the time display text node if it has what was passed in changed * the formatted time. * * @param {number} time * The time to update to * * @private */ ; _proto.updateFormattedTime_ = function updateFormattedTime_(time) { var formattedTime = this.formatTime_(time); if (formattedTime === this.formattedTime_) { return; } this.formattedTime_ = formattedTime; this.requestAnimationFrame(this.updateTextNode_); } /** * To be filled out in the child class, should update the displayed time * in accordance with the fact that the current time has changed. * * @param {EventTarget~Event} [event] * The `timeupdate` event that caused this to run. * * @listens Player#timeupdate */ ; _proto.updateContent = function updateContent(event) {}; return TimeDisplay; }(Component); /** * The text that is added to the `TimeDisplay` for screen reader users. * * @type {string} * @private */ TimeDisplay.prototype.labelText_ = 'Time'; /** * The text that should display over the `TimeDisplay`s controls. Added to for localization. * * @type {string} * @private * * @deprecated in v7; controlText_ is not used in non-active display Components */ TimeDisplay.prototype.controlText_ = 'Time'; Component.registerComponent('TimeDisplay', TimeDisplay); /** * Displays the current time * * @extends Component */ var CurrentTimeDisplay = /*#__PURE__*/ function (_TimeDisplay) { _inheritsLoose(CurrentTimeDisplay, _TimeDisplay); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function CurrentTimeDisplay(player, options) { var _this; _this = _TimeDisplay.call(this, player, options) || this; _this.on(player, 'ended', _this.handleEnded); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ var _proto = CurrentTimeDisplay.prototype; _proto.buildCSSClass = function buildCSSClass() { return 'vjs-current-time'; } /** * Update current time display * * @param {EventTarget~Event} [event] * The `timeupdate` event that caused this function to run. * * @listens Player#timeupdate */ ; _proto.updateContent = function updateContent(event) { // Allows for smooth scrubbing, when player can't keep up. var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); this.updateFormattedTime_(time); } /** * When the player fires ended there should be no time left. Sadly * this is not always the case, lets make it seem like that is the case * for users. * * @param {EventTarget~Event} [event] * The `ended` event that caused this to run. * * @listens Player#ended */ ; _proto.handleEnded = function handleEnded(event) { if (!this.player_.duration()) { return; } this.updateFormattedTime_(this.player_.duration()); }; return CurrentTimeDisplay; }(TimeDisplay); /** * The text that is added to the `CurrentTimeDisplay` for screen reader users. * * @type {string} * @private */ CurrentTimeDisplay.prototype.labelText_ = 'Current Time'; /** * The text that should display over the `CurrentTimeDisplay`s controls. Added to for localization. * * @type {string} * @private * * @deprecated in v7; controlText_ is not used in non-active display Components */ CurrentTimeDisplay.prototype.controlText_ = 'Current Time'; Component.registerComponent('CurrentTimeDisplay', CurrentTimeDisplay); /** * Displays the duration * * @extends Component */ var DurationDisplay = /*#__PURE__*/ function (_TimeDisplay) { _inheritsLoose(DurationDisplay, _TimeDisplay); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function DurationDisplay(player, options) { var _this; _this = _TimeDisplay.call(this, player, options) || this; // we do not want to/need to throttle duration changes, // as they should always display the changed duration as // it has changed _this.on(player, 'durationchange', _this.updateContent); // Listen to loadstart because the player duration is reset when a new media element is loaded, // but the durationchange on the user agent will not fire. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm} _this.on(player, 'loadstart', _this.updateContent); // Also listen for timeupdate (in the parent) and loadedmetadata because removing those // listeners could have broken dependent applications/libraries. These // can likely be removed for 7.0. _this.on(player, 'loadedmetadata', _this.throttledUpdateContent); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ var _proto = DurationDisplay.prototype; _proto.buildCSSClass = function buildCSSClass() { return 'vjs-duration'; } /** * Update duration time display. * * @param {EventTarget~Event} [event] * The `durationchange`, `timeupdate`, or `loadedmetadata` event that caused * this function to be called. * * @listens Player#durationchange * @listens Player#timeupdate * @listens Player#loadedmetadata */ ; _proto.updateContent = function updateContent(event) { var duration = this.player_.duration(); if (this.duration_ !== duration) { this.duration_ = duration; this.updateFormattedTime_(duration); } }; return DurationDisplay; }(TimeDisplay); /** * The text that is added to the `DurationDisplay` for screen reader users. * * @type {string} * @private */ DurationDisplay.prototype.labelText_ = 'Duration'; /** * The text that should display over the `DurationDisplay`s controls. Added to for localization. * * @type {string} * @private * * @deprecated in v7; controlText_ is not used in non-active display Components */ DurationDisplay.prototype.controlText_ = 'Duration'; Component.registerComponent('DurationDisplay', DurationDisplay); /** * The separator between the current time and duration. * Can be hidden if it's not needed in the design. * * @extends Component */ var TimeDivider = /*#__PURE__*/ function (_Component) { _inheritsLoose(TimeDivider, _Component); function TimeDivider() { return _Component.apply(this, arguments) || this; } var _proto = TimeDivider.prototype; /** * Create the component's DOM element * * @return {Element} * The element that was created. */ _proto.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-time-control vjs-time-divider', innerHTML: '<div><span>/</span></div>' }, { // this element and its contents can be hidden from assistive techs since // it is made extraneous by the announcement of the control text // for the current time and duration displays 'aria-hidden': true }); }; return TimeDivider; }(Component); Component.registerComponent('TimeDivider', TimeDivider); /** * Displays the time left in the video * * @extends Component */ var RemainingTimeDisplay = /*#__PURE__*/ function (_TimeDisplay) { _inheritsLoose(RemainingTimeDisplay, _TimeDisplay); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function RemainingTimeDisplay(player, options) { var _this; _this = _TimeDisplay.call(this, player, options) || this; _this.on(player, 'durationchange', _this.throttledUpdateContent); _this.on(player, 'ended', _this.handleEnded); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ var _proto = RemainingTimeDisplay.prototype; _proto.buildCSSClass = function buildCSSClass() { return 'vjs-remaining-time'; } /** * Create the `Component`'s DOM element with the "minus" characted prepend to the time * * @return {Element} * The element that was created. */ ; _proto.createEl = function createEl$1() { var el = _TimeDisplay.prototype.createEl.call(this); el.insertBefore(createEl('span', {}, { 'aria-hidden': true }, '-'), this.contentEl_); return el; } /** * Update remaining time display. * * @param {EventTarget~Event} [event] * The `timeupdate` or `durationchange` event that caused this to run. * * @listens Player#timeupdate * @listens Player#durationchange */ ; _proto.updateContent = function updateContent(event) { if (typeof this.player_.duration() !== 'number') { return; } // @deprecated We should only use remainingTimeDisplay // as of video.js 7 if (this.player_.remainingTimeDisplay) { this.updateFormattedTime_(this.player_.remainingTimeDisplay()); } else { this.updateFormattedTime_(this.player_.remainingTime()); } } /** * When the player fires ended there should be no time left. Sadly * this is not always the case, lets make it seem like that is the case * for users. * * @param {EventTarget~Event} [event] * The `ended` event that caused this to run. * * @listens Player#ended */ ; _proto.handleEnded = function handleEnded(event) { if (!this.player_.duration()) { return; } this.updateFormattedTime_(0); }; return RemainingTimeDisplay; }(TimeDisplay); /** * The text that is added to the `RemainingTimeDisplay` for screen reader users. * * @type {string} * @private */ RemainingTimeDisplay.prototype.labelText_ = 'Remaining Time'; /** * The text that should display over the `RemainingTimeDisplay`s controls. Added to for localization. * * @type {string} * @private * * @deprecated in v7; controlText_ is not used in non-active display Components */ RemainingTimeDisplay.prototype.controlText_ = 'Remaining Time'; Component.registerComponent('RemainingTimeDisplay', RemainingTimeDisplay); /** * Displays the live indicator when duration is Infinity. * * @extends Component */ var LiveDisplay = /*#__PURE__*/ function (_Component) { _inheritsLoose(LiveDisplay, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function LiveDisplay(player, options) { var _this; _this = _Component.call(this, player, options) || this; _this.updateShowing(); _this.on(_this.player(), 'durationchange', _this.updateShowing); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ var _proto = LiveDisplay.prototype; _proto.createEl = function createEl$1() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-live-control vjs-control' }); this.contentEl_ = createEl('div', { className: 'vjs-live-display', innerHTML: "<span class=\"vjs-control-text\">" + this.localize('Stream Type') + "\xA0</span>" + this.localize('LIVE') }, { 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; _proto.dispose = function dispose() { this.contentEl_ = null; _Component.prototype.dispose.call(this); } /** * Check the duration to see if the LiveDisplay should be showing or not. Then show/hide * it accordingly * * @param {EventTarget~Event} [event] * The {@link Player#durationchange} event that caused this function to run. * * @listens Player#durationchange */ ; _proto.updateShowing = function updateShowing(event) { if (this.player().duration() === Infinity) { this.show(); } else { this.hide(); } }; return LiveDisplay; }(Component); Component.registerComponent('LiveDisplay', LiveDisplay); /** * Displays the live indicator when duration is Infinity. * * @extends Component */ var SeekToLive = /*#__PURE__*/ function (_Button) { _inheritsLoose(SeekToLive, _Button); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function SeekToLive(player, options) { var _this; _this = _Button.call(this, player, options) || this; _this.updateLiveEdgeStatus(); if (_this.player_.liveTracker) { _this.on(_this.player_.liveTracker, 'liveedgechange', _this.updateLiveEdgeStatus); } return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ var _proto = SeekToLive.prototype; _proto.createEl = function createEl$1() { var el = _Button.prototype.createEl.call(this, 'button', { className: 'vjs-seek-to-live-control vjs-control' }); this.textEl_ = createEl('span', { className: 'vjs-seek-to-live-text', innerHTML: this.localize('LIVE') }, { 'aria-hidden': 'true' }); el.appendChild(this.textEl_); return el; } /** * Update the state of this button if we are at the live edge * or not */ ; _proto.updateLiveEdgeStatus = function updateLiveEdgeStatus(e) { // default to live edge if (!this.player_.liveTracker || this.player_.liveTracker.atLiveEdge()) { this.setAttribute('aria-disabled', true); this.addClass('vjs-at-live-edge'); this.controlText('Seek to live, currently playing live'); } else { this.setAttribute('aria-disabled', false); this.removeClass('vjs-at-live-edge'); this.controlText('Seek to live, currently behind live'); } } /** * On click bring us as near to the live point as possible. * This requires that we wait for the next `live-seekable-change` * event which will happen every segment length seconds. */ ; _proto.handleClick = function handleClick() { this.player_.liveTracker.seekToLiveEdge(); } /** * Dispose of the element and stop tracking */ ; _proto.dispose = function dispose() { if (this.player_.liveTracker) { this.off(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatus); } this.textEl_ = null; _Button.prototype.dispose.call(this); }; return SeekToLive; }(Button); SeekToLive.prototype.controlText_ = 'Seek to live, currently playing live'; Component.registerComponent('SeekToLive', SeekToLive); /** * The base functionality for a slider. Can be vertical or horizontal. * For instance the volume bar or the seek bar on a video is a slider. * * @extends Component */ var Slider = /*#__PURE__*/ function (_Component) { _inheritsLoose(Slider, _Component); /** * Create an instance of this class * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function Slider(player, options) { var _this; _this = _Component.call(this, player, options) || this; // Set property names to bar to match with the child Slider class is looking for _this.bar = _this.getChild(_this.options_.barName); // Set a horizontal or vertical class on the slider depending on the slider type _this.vertical(!!_this.options_.vertical); _this.enable(); return _this; } /** * Are controls are currently enabled for this slider or not. * * @return {boolean} * true if controls are enabled, false otherwise */ var _proto = Slider.prototype; _proto.enabled = function enabled() { return this.enabled_; } /** * Enable controls for this slider if they are disabled */ ; _proto.enable = function enable() { if (this.enabled()) { return; } this.on('mousedown', this.handleMouseDown); this.on('touchstart', this.handleMouseDown); this.on('keydown', this.handleKeyDown); this.on('click', this.handleClick); // TODO: deprecated, controlsvisible does not seem to be fired this.on(this.player_, 'controlsvisible', this.update); if (this.playerEvent) { this.on(this.player_, this.playerEvent, this.update); } this.removeClass('disabled'); this.setAttribute('tabindex', 0); this.enabled_ = true; } /** * Disable controls for this slider if they are enabled */ ; _proto.disable = function disable() { if (!this.enabled()) { return; } var doc = this.bar.el_.ownerDocument; this.off('mousedown', this.handleMouseDown); this.off('touchstart', this.handleMouseDown); this.off('keydown', this.handleKeyDown); this.off('click', this.handleClick); this.off(this.player_, 'controlsvisible', this.update); this.off(doc, 'mousemove', this.handleMouseMove); this.off(doc, 'mouseup', this.handleMouseUp); this.off(doc, 'touchmove', this.handleMouseMove); this.off(doc, 'touchend', this.handleMouseUp); this.removeAttribute('tabindex'); this.addClass('disabled'); if (this.playerEvent) { this.off(this.player_, this.playerEvent, this.update); } this.enabled_ = false; } /** * Create the `Slider`s DOM element. * * @param {string} type * Type of element to create. * * @param {Object} [props={}] * List of properties in Object form. * * @param {Object} [attributes={}] * list of attributes in Object form. * * @return {Element} * The element that gets created. */ ; _proto.createEl = function createEl(type, props, attributes) { if (props === void 0) { props = {}; } if (attributes === void 0) { attributes = {}; } // Add the slider element class to all sub classes props.className = props.className + ' vjs-slider'; props = assign({ tabIndex: 0 }, props); attributes = assign({ 'role': 'slider', 'aria-valuenow': 0, 'aria-valuemin': 0, 'aria-valuemax': 100, 'tabIndex': 0 }, attributes); return _Component.prototype.createEl.call(this, type, props, attributes); } /** * Handle `mousedown` or `touchstart` events on the `Slider`. * * @param {EventTarget~Event} event * `mousedown` or `touchstart` event that triggered this function * * @listens mousedown * @listens touchstart * @fires Slider#slideractive */ ; _proto.handleMouseDown = function handleMouseDown(event) { var doc = this.bar.el_.ownerDocument; if (event.type === 'mousedown') { event.preventDefault(); } // Do not call preventDefault() on touchstart in Chrome // to avoid console warnings. Use a 'touch-action: none' style // instead to prevent unintented scrolling. // https://developers.google.com/web/updates/2017/01/scrolling-intervention if (event.type === 'touchstart' && !IS_CHROME) { event.preventDefault(); } blockTextSelection(); this.addClass('vjs-sliding'); /** * Triggered when the slider is in an active state * * @event Slider#slideractive * @type {EventTarget~Event} */ this.trigger('slideractive'); this.on(doc, 'mousemove', this.handleMouseMove); this.on(doc, 'mouseup', this.handleMouseUp); this.on(doc, 'touchmove', this.handleMouseMove); this.on(doc, 'touchend', this.handleMouseUp); this.handleMouseMove(event); } /** * Handle the `mousemove`, `touchmove`, and `mousedown` events on this `Slider`. * The `mousemove` and `touchmove` events will only only trigger this function during * `mousedown` and `touchstart`. This is due to {@link Slider#handleMouseDown} and * {@link Slider#handleMouseUp}. * * @param {EventTarget~Event} event * `mousedown`, `mousemove`, `touchstart`, or `touchmove` event that triggered * this function * * @listens mousemove * @listens touchmove */ ; _proto.handleMouseMove = function handleMouseMove(event) {} /** * Handle `mouseup` or `touchend` events on the `Slider`. * * @param {EventTarget~Event} event * `mouseup` or `touchend` event that triggered this function. * * @listens touchend * @listens mouseup * @fires Slider#sliderinactive */ ; _proto.handleMouseUp = function handleMouseUp() { var doc = this.bar.el_.ownerDocument; unblockTextSelection(); this.removeClass('vjs-sliding'); /** * Triggered when the slider is no longer in an active state. * * @event Slider#sliderinactive * @type {EventTarget~Event} */ this.trigger('sliderinactive'); this.off(doc, 'mousemove', this.handleMouseMove); this.off(doc, 'mouseup', this.handleMouseUp); this.off(doc, 'touchmove', this.handleMouseMove); this.off(doc, 'touchend', this.handleMouseUp); this.update(); } /** * Update the progress bar of the `Slider`. * * @return {number} * The percentage of progress the progress bar represents as a * number from 0 to 1. */ ; _proto.update = function update() { // In VolumeBar init we have a setTimeout for update that pops and update // to the end of the execution stack. The player is destroyed before then // update will cause an error if (!this.el_) { return; } // If scrubbing, we could use a cached value to make the handle keep up // with the user's mouse. On HTML5 browsers scrubbing is really smooth, but // some flash players are slow, so we might want to utilize this later. // var progress = (this.player_.scrubbing()) ? this.player_.getCache().currentTime / this.player_.duration() : this.player_.currentTime() / this.player_.duration(); var progress = this.getPercent(); var bar = this.bar; // If there's no bar... if (!bar) { return; } // Protect against no duration and other division issues if (typeof progress !== 'number' || progress !== progress || progress < 0 || progress === Infinity) { progress = 0; } // Convert to a percentage for setting var percentage = (progress * 100).toFixed(2) + '%'; var style = bar.el().style; // Set the new bar width or height var sizeKey = this.vertical() ? 'height' : 'width'; if (style[sizeKey] !== percentage) { style[sizeKey] = percentage; } return progress; } /** * Calculate distance for slider * * @param {EventTarget~Event} event * The event that caused this function to run. * * @return {number} * The current position of the Slider. * - position.x for vertical `Slider`s * - position.y for horizontal `Slider`s */ ; _proto.calculateDistance = function calculateDistance(event) { var position = getPointerPosition(this.el_, event); if (this.vertical()) { return position.y; } return position.x; } /** * Handle a `keydown` event on the `Slider`. Watches for left, rigth, up, and down * arrow keys. This function will only be called when the slider has focus. See * {@link Slider#handleFocus} and {@link Slider#handleBlur}. * * @param {EventTarget~Event} event * the `keydown` event that caused this function to run. * * @listens keydown */ ; _proto.handleKeyDown = function handleKeyDown(event) { // Left and Down Arrows if (keycode.isEventKey(event, 'Left') || keycode.isEventKey(event, 'Down')) { event.preventDefault(); event.stopPropagation(); this.stepBack(); // Up and Right Arrows } else if (keycode.isEventKey(event, 'Right') || keycode.isEventKey(event, 'Up')) { event.preventDefault(); event.stopPropagation(); this.stepForward(); } else { // Pass keydown handling up for unsupported keys _Component.prototype.handleKeyDown.call(this, event); } } /** * Listener for click events on slider, used to prevent clicks * from bubbling up to parent elements like button menus. * * @param {Object} event * Event that caused this object to run */ ; _proto.handleClick = function handleClick(event) { event.stopPropagation(); event.preventDefault(); } /** * Get/set if slider is horizontal for vertical * * @param {boolean} [bool] * - true if slider is vertical, * - false is horizontal * * @return {boolean} * - true if slider is vertical, and getting * - false if the slider is horizontal, and getting */ ; _proto.vertical = function vertical(bool) { if (bool === undefined) { return this.vertical_ || false; } this.vertical_ = !!bool; if (this.vertical_) { this.addClass('vjs-slider-vertical'); } else { this.addClass('vjs-slider-horizontal'); } }; return Slider; }(Component); Component.registerComponent('Slider', Slider); /** * Shows loading progress * * @extends Component */ var LoadProgressBar = /*#__PURE__*/ function (_Component) { _inheritsLoose(LoadProgressBar, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function LoadProgressBar(player, options) { var _this; _this = _Component.call(this, player, options) || this; _this.partEls_ = []; _this.on(player, 'progress', _this.update); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ var _proto = LoadProgressBar.prototype; _proto.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-load-progress', innerHTML: "<span class=\"vjs-control-text\"><span>" + this.localize('Loaded') + "</span>: <span class=\"vjs-control-text-loaded-percentage\">0%</span></span>" }); }; _proto.dispose = function dispose() { this.partEls_ = null; _Component.prototype.dispose.call(this); } /** * Update progress bar * * @param {EventTarget~Event} [event] * The `progress` event that caused this function to run. * * @listens Player#progress */ ; _proto.update = function update(event) { var liveTracker = this.player_.liveTracker; var buffered = this.player_.buffered(); var duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : this.player_.duration(); var bufferedEnd = this.player_.bufferedEnd(); var children = this.partEls_; var controlTextPercentage = this.$('.vjs-control-text-loaded-percentage'); // get the percent width of a time compared to the total end var percentify = function percentify(time, end, rounded) { // no NaN var percent = time / end || 0; percent = (percent >= 1 ? 1 : percent) * 100; if (rounded) { percent = percent.toFixed(2); } return percent + '%'; }; // update the width of the progress bar this.el_.style.width = percentify(bufferedEnd, duration); // update the control-text textContent(controlTextPercentage, percentify(bufferedEnd, duration, true)); // add child elements to represent the individual buffered time ranges for (var i = 0; i < buffered.length; i++) { var start = buffered.start(i); var end = buffered.end(i); var part = children[i]; if (!part) { part = this.el_.appendChild(createEl()); children[i] = part; } // set the percent based on the width of the progress bar (bufferedEnd) part.style.left = percentify(start, bufferedEnd); part.style.width = percentify(end - start, bufferedEnd); } // remove unused buffered range elements for (var _i = children.length; _i > buffered.length; _i--) { this.el_.removeChild(children[_i - 1]); } children.length = buffered.length; }; return LoadProgressBar; }(Component); Component.registerComponent('LoadProgressBar', LoadProgressBar); /** * Time tooltips display a time above the progress bar. * * @extends Component */ var TimeTooltip = /*#__PURE__*/ function (_Component) { _inheritsLoose(TimeTooltip, _Component); /** * Creates an instance of this class. * * @param {Player} player * The {@link Player} that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function TimeTooltip(player, options) { var _this; _this = _Component.call(this, player, options) || this; _this.update = throttle(bind(_assertThisInitialized(_this), _this.update), UPDATE_REFRESH_INTERVAL); return _this; } /** * Create the time tooltip DOM element * * @return {Element} * The element that was created. */ var _proto = TimeTooltip.prototype; _proto.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-time-tooltip' }, { 'aria-hidden': 'true' }); } /** * Updates the position of the time tooltip relative to the `SeekBar`. * * @param {Object} seekBarRect * The `ClientRect` for the {@link SeekBar} element. * * @param {number} seekBarPoint * A number from 0 to 1, representing a horizontal reference point * from the left edge of the {@link SeekBar} */ ; _proto.update = function update(seekBarRect, seekBarPoint, content) { var tooltipRect = getBoundingClientRect(this.el_); var playerRect = getBoundingClientRect(this.player_.el()); var seekBarPointPx = seekBarRect.width * seekBarPoint; // do nothing if either rect isn't available // for example, if the player isn't in the DOM for testing if (!playerRect || !tooltipRect) { return; } // This is the space left of the `seekBarPoint` available within the bounds // of the player. We calculate any gap between the left edge of the player // and the left edge of the `SeekBar` and add the number of pixels in the // `SeekBar` before hitting the `seekBarPoint` var spaceLeftOfPoint = seekBarRect.left - playerRect.left + seekBarPointPx; // This is the space right of the `seekBarPoint` available within the bounds // of the player. We calculate the number of pixels from the `seekBarPoint` // to the right edge of the `SeekBar` and add to that any gap between the // right edge of the `SeekBar` and the player. var spaceRightOfPoint = seekBarRect.width - seekBarPointPx + (playerRect.right - seekBarRect.right); // This is the number of pixels by which the tooltip will need to be pulled // further to the right to center it over the `seekBarPoint`. var pullTooltipBy = tooltipRect.width / 2; // Adjust the `pullTooltipBy` distance to the left or right depending on // the results of the space calculations above. if (spaceLeftOfPoint < pullTooltipBy) { pullTooltipBy += pullTooltipBy - spaceLeftOfPoint; } else if (spaceRightOfPoint < pullTooltipBy) { pullTooltipBy = spaceRightOfPoint; } // Due to the imprecision of decimal/ratio based calculations and varying // rounding behaviors, there are cases where the spacing adjustment is off // by a pixel or two. This adds insurance to these calculations. if (pullTooltipBy < 0) { pullTooltipBy = 0; } else if (pullTooltipBy > tooltipRect.width) { pullTooltipBy = tooltipRect.width; } this.el_.style.right = "-" + pullTooltipBy + "px"; this.write(content); } /** * Write the time to the tooltip DOM element. * * @param {string} content * The formatted time for the tooltip. */ ; _proto.write = function write(content) { textContent(this.el_, content); } /** * Updates the position of the time tooltip relative to the `SeekBar`. * * @param {Object} seekBarRect * The `ClientRect` for the {@link SeekBar} element. * * @param {number} seekBarPoint * A number from 0 to 1, representing a horizontal reference point * from the left edge of the {@link SeekBar} * * @param {number} time * The time to update the tooltip to, not used during live playback * * @param {Function} cb * A function that will be called during the request animation frame * for tooltips that need to do additional animations from the default */ ; _proto.updateTime = function updateTime(seekBarRect, seekBarPoint, time, cb) { var _this2 = this; // If there is an existing rAF ID, cancel it so we don't over-queue. if (this.rafId_) { this.cancelAnimationFrame(this.rafId_); } this.rafId_ = this.requestAnimationFrame(function () { var content; var duration = _this2.player_.duration(); if (_this2.player_.liveTracker && _this2.player_.liveTracker.isLive()) { var liveWindow = _this2.player_.liveTracker.liveWindow(); var secondsBehind = liveWindow - seekBarPoint * liveWindow; content = (secondsBehind < 1 ? '' : '-') + formatTime(secondsBehind, liveWindow); } else { content = formatTime(time, duration); } _this2.update(seekBarRect, seekBarPoint, content); if (cb) { cb(); } }); }; return TimeTooltip; }(Component); Component.registerComponent('TimeTooltip', TimeTooltip); /** * Used by {@link SeekBar} to display media playback progress as part of the * {@link ProgressControl}. * * @extends Component */ var PlayProgressBar = /*#__PURE__*/ function (_Component) { _inheritsLoose(PlayProgressBar, _Component); /** * Creates an instance of this class. * * @param {Player} player * The {@link Player} that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function PlayProgressBar(player, options) { var _this; _this = _Component.call(this, player, options) || this; _this.update = throttle(bind(_assertThisInitialized(_this), _this.update), UPDATE_REFRESH_INTERVAL); return _this; } /** * Create the the DOM element for this class. * * @return {Element} * The element that was created. */ var _proto = PlayProgressBar.prototype; _proto.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-play-progress vjs-slider-bar' }, { 'aria-hidden': 'true' }); } /** * Enqueues updates to its own DOM as well as the DOM of its * {@link TimeTooltip} child. * * @param {Object} seekBarRect * The `ClientRect` for the {@link SeekBar} element. * * @param {number} seekBarPoint * A number from 0 to 1, representing a horizontal reference point * from the left edge of the {@link SeekBar} */ ; _proto.update = function update(seekBarRect, seekBarPoint) { var timeTooltip = this.getChild('timeTooltip'); if (!timeTooltip) { return; } var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); timeTooltip.updateTime(seekBarRect, seekBarPoint, time); }; return PlayProgressBar; }(Component); /** * Default options for {@link PlayProgressBar}. * * @type {Object} * @private */ PlayProgressBar.prototype.options_ = { children: [] }; // Time tooltips should not be added to a player on mobile devices if (!IS_IOS && !IS_ANDROID) { PlayProgressBar.prototype.options_.children.push('timeTooltip'); } Component.registerComponent('PlayProgressBar', PlayProgressBar); /** * The {@link MouseTimeDisplay} component tracks mouse movement over the * {@link ProgressControl}. It displays an indicator and a {@link TimeTooltip} * indicating the time which is represented by a given point in the * {@link ProgressControl}. * * @extends Component */ var MouseTimeDisplay = /*#__PURE__*/ function (_Component) { _inheritsLoose(MouseTimeDisplay, _Component); /** * Creates an instance of this class. * * @param {Player} player * The {@link Player} that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function MouseTimeDisplay(player, options) { var _this; _this = _Component.call(this, player, options) || this; _this.update = throttle(bind(_assertThisInitialized(_this), _this.update), UPDATE_REFRESH_INTERVAL); return _this; } /** * Create the DOM element for this class. * * @return {Element} * The element that was created. */ var _proto = MouseTimeDisplay.prototype; _proto.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-mouse-display' }); } /** * Enqueues updates to its own DOM as well as the DOM of its * {@link TimeTooltip} child. * * @param {Object} seekBarRect * The `ClientRect` for the {@link SeekBar} element. * * @param {number} seekBarPoint * A number from 0 to 1, representing a horizontal reference point * from the left edge of the {@link SeekBar} */ ; _proto.update = function update(seekBarRect, seekBarPoint) { var _this2 = this; var time = seekBarPoint * this.player_.duration(); this.getChild('timeTooltip').updateTime(seekBarRect, seekBarPoint, time, function () { _this2.el_.style.left = seekBarRect.width * seekBarPoint + "px"; }); }; return MouseTimeDisplay; }(Component); /** * Default options for `MouseTimeDisplay` * * @type {Object} * @private */ MouseTimeDisplay.prototype.options_ = { children: ['timeTooltip'] }; Component.registerComponent('MouseTimeDisplay', MouseTimeDisplay); var STEP_SECONDS = 5; // The multiplier of STEP_SECONDS that PgUp/PgDown move the timeline. var PAGE_KEY_MULTIPLIER = 12; // The interval at which the bar should update as it progresses. var UPDATE_REFRESH_INTERVAL$1 = 30; /** * Seek bar and container for the progress bars. Uses {@link PlayProgressBar} * as its `bar`. * * @extends Slider */ var SeekBar = /*#__PURE__*/ function (_Slider) { _inheritsLoose(SeekBar, _Slider); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function SeekBar(player, options) { var _this; _this = _Slider.call(this, player, options) || this; _this.setEventHandlers_(); return _this; } /** * Sets the event handlers * * @private */ var _proto = SeekBar.prototype; _proto.setEventHandlers_ = function setEventHandlers_() { this.update = throttle(bind(this, this.update), UPDATE_REFRESH_INTERVAL$1); this.on(this.player_, 'timeupdate', this.update); this.on(this.player_, 'ended', this.handleEnded); this.on(this.player_, 'durationchange', this.update); if (this.player_.liveTracker) { this.on(this.player_.liveTracker, 'liveedgechange', this.update); } // when playing, let's ensure we smoothly update the play progress bar // via an interval this.updateInterval = null; this.on(this.player_, ['playing'], this.enableInterval_); this.on(this.player_, ['ended', 'pause', 'waiting'], this.disableInterval_); // we don't need to update the play progress if the document is hidden, // also, this causes the CPU to spike and eventually crash the page on IE11. if ('hidden' in document && 'visibilityState' in document) { this.on(document, 'visibilitychange', this.toggleVisibility_); } }; _proto.toggleVisibility_ = function toggleVisibility_(e) { if (document.hidden) { this.disableInterval_(e); } else { this.enableInterval_(); // we just switched back to the page and someone may be looking, so, update ASAP this.requestAnimationFrame(this.update); } }; _proto.enableInterval_ = function enableInterval_() { var _this2 = this; this.clearInterval(this.updateInterval); this.updateInterval = this.setInterval(function () { _this2.requestAnimationFrame(_this2.update); }, UPDATE_REFRESH_INTERVAL$1); }; _proto.disableInterval_ = function disableInterval_(e) { if (this.player_.liveTracker && this.player_.liveTracker.isLive() && e.type !== 'ended') { return; } this.clearInterval(this.updateInterval); } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ ; _proto.createEl = function createEl() { return _Slider.prototype.createEl.call(this, 'div', { className: 'vjs-progress-holder' }, { 'aria-label': this.localize('Progress Bar') }); } /** * This function updates the play progress bar and accessibility * attributes to whatever is passed in. * * @param {number} currentTime * The currentTime value that should be used for accessibility * * @param {number} percent * The percentage as a decimal that the bar should be filled from 0-1. * * @private */ ; _proto.update_ = function update_(currentTime, percent) { var liveTracker = this.player_.liveTracker; var duration = this.player_.duration(); if (liveTracker && liveTracker.isLive()) { duration = this.player_.liveTracker.liveCurrentTime(); } // machine readable value of progress bar (percentage complete) this.el_.setAttribute('aria-valuenow', (percent * 100).toFixed(2)); // human readable value of progress bar (time complete) this.el_.setAttribute('aria-valuetext', this.localize('progress bar timing: currentTime={1} duration={2}', [formatTime(currentTime, duration), formatTime(duration, duration)], '{1} of {2}')); // Update the `PlayProgressBar`. if (this.bar) { this.bar.update(getBoundingClientRect(this.el_), percent); } } /** * Update the seek bar's UI. * * @param {EventTarget~Event} [event] * The `timeupdate` or `ended` event that caused this to run. * * @listens Player#timeupdate * * @return {number} * The current percent at a number from 0-1 */ ; _proto.update = function update(event) { // if the offsetParent is null, then this element is hidden, in which case // we don't need to update it. if (this.el().offsetParent === null) { return; } var percent = _Slider.prototype.update.call(this); this.update_(this.getCurrentTime_(), percent); return percent; } /** * Get the value of current time but allows for smooth scrubbing, * when player can't keep up. * * @return {number} * The current time value to display * * @private */ ; _proto.getCurrentTime_ = function getCurrentTime_() { return this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); } /** * We want the seek bar to be full on ended * no matter what the actual internal values are. so we force it. * * @param {EventTarget~Event} [event] * The `timeupdate` or `ended` event that caused this to run. * * @listens Player#ended */ ; _proto.handleEnded = function handleEnded(event) { this.update_(this.player_.duration(), 1); } /** * Get the percentage of media played so far. * * @return {number} * The percentage of media played so far (0 to 1). */ ; _proto.getPercent = function getPercent() { var currentTime = this.getCurrentTime_(); var percent; var liveTracker = this.player_.liveTracker; if (liveTracker && liveTracker.isLive()) { percent = (currentTime - liveTracker.seekableStart()) / liveTracker.liveWindow(); // prevent the percent from changing at the live edge if (liveTracker.atLiveEdge()) { percent = 1; } } else { percent = currentTime / this.player_.duration(); } return percent >= 1 ? 1 : percent || 0; } /** * Handle mouse down on seek bar * * @param {EventTarget~Event} event * The `mousedown` event that caused this to run. * * @listens mousedown */ ; _proto.handleMouseDown = function handleMouseDown(event) { if (!isSingleLeftClick(event)) { return; } // Stop event propagation to prevent double fire in progress-control.js event.stopPropagation(); this.player_.scrubbing(true); this.videoWasPlaying = !this.player_.paused(); this.player_.pause(); _Slider.prototype.handleMouseDown.call(this, event); } /** * Handle mouse move on seek bar * * @param {EventTarget~Event} event * The `mousemove` event that caused this to run. * * @listens mousemove */ ; _proto.handleMouseMove = function handleMouseMove(event) { if (!isSingleLeftClick(event)) { return; } var newTime; var distance = this.calculateDistance(event); var liveTracker = this.player_.liveTracker; if (!liveTracker || !liveTracker.isLive()) { newTime = distance * this.player_.duration(); // Don't let video end while scrubbing. if (newTime === this.player_.duration()) { newTime = newTime - 0.1; } } else { var seekableStart = liveTracker.seekableStart(); var seekableEnd = liveTracker.liveCurrentTime(); newTime = seekableStart + distance * liveTracker.liveWindow(); // Don't let video end while scrubbing. if (newTime >= seekableEnd) { newTime = seekableEnd; } // Compensate for precision differences so that currentTime is not less // than seekable start if (newTime <= seekableStart) { newTime = seekableStart + 0.1; } // On android seekableEnd can be Infinity sometimes, // this will cause newTime to be Infinity, which is // not a valid currentTime. if (newTime === Infinity) { return; } } // Set new time (tell player to seek to new time) this.player_.currentTime(newTime); }; _proto.enable = function enable() { _Slider.prototype.enable.call(this); var mouseTimeDisplay = this.getChild('mouseTimeDisplay'); if (!mouseTimeDisplay) { return; } mouseTimeDisplay.show(); }; _proto.disable = function disable() { _Slider.prototype.disable.call(this); var mouseTimeDisplay = this.getChild('mouseTimeDisplay'); if (!mouseTimeDisplay) { return; } mouseTimeDisplay.hide(); } /** * Handle mouse up on seek bar * * @param {EventTarget~Event} event * The `mouseup` event that caused this to run. * * @listens mouseup */ ; _proto.handleMouseUp = function handleMouseUp(event) { _Slider.prototype.handleMouseUp.call(this, event); // Stop event propagation to prevent double fire in progress-control.js if (event) { event.stopPropagation(); } this.player_.scrubbing(false); /** * Trigger timeupdate because we're done seeking and the time has changed. * This is particularly useful for if the player is paused to time the time displays. * * @event Tech#timeupdate * @type {EventTarget~Event} */ this.player_.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); if (this.videoWasPlaying) { silencePromise(this.player_.play()); } } /** * Move more quickly fast forward for keyboard-only users */ ; _proto.stepForward = function stepForward() { this.player_.currentTime(this.player_.currentTime() + STEP_SECONDS); } /** * Move more quickly rewind for keyboard-only users */ ; _proto.stepBack = function stepBack() { this.player_.currentTime(this.player_.currentTime() - STEP_SECONDS); } /** * Toggles the playback state of the player * This gets called when enter or space is used on the seekbar * * @param {EventTarget~Event} event * The `keydown` event that caused this function to be called * */ ; _proto.handleAction = function handleAction(event) { if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } } /** * Called when this SeekBar has focus and a key gets pressed down. * Supports the following keys: * * Space or Enter key fire a click event * Home key moves to start of the timeline * End key moves to end of the timeline * Digit "0" through "9" keys move to 0%, 10% ... 80%, 90% of the timeline * PageDown key moves back a larger step than ArrowDown * PageUp key moves forward a large step * * @param {EventTarget~Event} event * The `keydown` event that caused this function to be called. * * @listens keydown */ ; _proto.handleKeyDown = function handleKeyDown(event) { if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) { event.preventDefault(); event.stopPropagation(); this.handleAction(event); } else if (keycode.isEventKey(event, 'Home')) { event.preventDefault(); event.stopPropagation(); this.player_.currentTime(0); } else if (keycode.isEventKey(event, 'End')) { event.preventDefault(); event.stopPropagation(); this.player_.currentTime(this.player_.duration()); } else if (/^[0-9]$/.test(keycode(event))) { event.preventDefault(); event.stopPropagation(); var gotoFraction = (keycode.codes[keycode(event)] - keycode.codes['0']) * 10.0 / 100.0; this.player_.currentTime(this.player_.duration() * gotoFraction); } else if (keycode.isEventKey(event, 'PgDn')) { event.preventDefault(); event.stopPropagation(); this.player_.currentTime(this.player_.currentTime() - STEP_SECONDS * PAGE_KEY_MULTIPLIER); } else if (keycode.isEventKey(event, 'PgUp')) { event.preventDefault(); event.stopPropagation(); this.player_.currentTime(this.player_.currentTime() + STEP_SECONDS * PAGE_KEY_MULTIPLIER); } else { // Pass keydown handling up for unsupported keys _Slider.prototype.handleKeyDown.call(this, event); } }; return SeekBar; }(Slider); /** * Default options for the `SeekBar` * * @type {Object} * @private */ SeekBar.prototype.options_ = { children: ['loadProgressBar', 'playProgressBar'], barName: 'playProgressBar' }; // MouseTimeDisplay tooltips should not be added to a player on mobile devices if (!IS_IOS && !IS_ANDROID) { SeekBar.prototype.options_.children.splice(1, 0, 'mouseTimeDisplay'); } Component.registerComponent('SeekBar', SeekBar); /** * The Progress Control component contains the seek bar, load progress, * and play progress. * * @extends Component */ var ProgressControl = /*#__PURE__*/ function (_Component) { _inheritsLoose(ProgressControl, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function ProgressControl(player, options) { var _this; _this = _Component.call(this, player, options) || this; _this.handleMouseMove = throttle(bind(_assertThisInitialized(_this), _this.handleMouseMove), UPDATE_REFRESH_INTERVAL); _this.throttledHandleMouseSeek = throttle(bind(_assertThisInitialized(_this), _this.handleMouseSeek), UPDATE_REFRESH_INTERVAL); _this.enable(); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ var _proto = ProgressControl.prototype; _proto.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-progress-control vjs-control' }); } /** * When the mouse moves over the `ProgressControl`, the pointer position * gets passed down to the `MouseTimeDisplay` component. * * @param {EventTarget~Event} event * The `mousemove` event that caused this function to run. * * @listen mousemove */ ; _proto.handleMouseMove = function handleMouseMove(event) { var seekBar = this.getChild('seekBar'); if (seekBar) { var mouseTimeDisplay = seekBar.getChild('mouseTimeDisplay'); var seekBarEl = seekBar.el(); var seekBarRect = getBoundingClientRect(seekBarEl); var seekBarPoint = getPointerPosition(seekBarEl, event).x; // The default skin has a gap on either side of the `SeekBar`. This means // that it's possible to trigger this behavior outside the boundaries of // the `SeekBar`. This ensures we stay within it at all times. if (seekBarPoint > 1) { seekBarPoint = 1; } else if (seekBarPoint < 0) { seekBarPoint = 0; } if (mouseTimeDisplay) { mouseTimeDisplay.update(seekBarRect, seekBarPoint); } } } /** * A throttled version of the {@link ProgressControl#handleMouseSeek} listener. * * @method ProgressControl#throttledHandleMouseSeek * @param {EventTarget~Event} event * The `mousemove` event that caused this function to run. * * @listen mousemove * @listen touchmove */ /** * Handle `mousemove` or `touchmove` events on the `ProgressControl`. * * @param {EventTarget~Event} event * `mousedown` or `touchstart` event that triggered this function * * @listens mousemove * @listens touchmove */ ; _proto.handleMouseSeek = function handleMouseSeek(event) { var seekBar = this.getChild('seekBar'); if (seekBar) { seekBar.handleMouseMove(event); } } /** * Are controls are currently enabled for this progress control. * * @return {boolean} * true if controls are enabled, false otherwise */ ; _proto.enabled = function enabled() { return this.enabled_; } /** * Disable all controls on the progress control and its children */ ; _proto.disable = function disable() { this.children().forEach(function (child) { return child.disable && child.disable(); }); if (!this.enabled()) { return; } this.off(['mousedown', 'touchstart'], this.handleMouseDown); this.off(this.el_, 'mousemove', this.handleMouseMove); this.handleMouseUp(); this.addClass('disabled'); this.enabled_ = false; } /** * Enable all controls on the progress control and its children */ ; _proto.enable = function enable() { this.children().forEach(function (child) { return child.enable && child.enable(); }); if (this.enabled()) { return; } this.on(['mousedown', 'touchstart'], this.handleMouseDown); this.on(this.el_, 'mousemove', this.handleMouseMove); this.removeClass('disabled'); this.enabled_ = true; } /** * Handle `mousedown` or `touchstart` events on the `ProgressControl`. * * @param {EventTarget~Event} event * `mousedown` or `touchstart` event that triggered this function * * @listens mousedown * @listens touchstart */ ; _proto.handleMouseDown = function handleMouseDown(event) { var doc = this.el_.ownerDocument; var seekBar = this.getChild('seekBar'); if (seekBar) { seekBar.handleMouseDown(event); } this.on(doc, 'mousemove', this.throttledHandleMouseSeek); this.on(doc, 'touchmove', this.throttledHandleMouseSeek); this.on(doc, 'mouseup', this.handleMouseUp); this.on(doc, 'touchend', this.handleMouseUp); } /** * Handle `mouseup` or `touchend` events on the `ProgressControl`. * * @param {EventTarget~Event} event * `mouseup` or `touchend` event that triggered this function. * * @listens touchend * @listens mouseup */ ; _proto.handleMouseUp = function handleMouseUp(event) { var doc = this.el_.ownerDocument; var seekBar = this.getChild('seekBar'); if (seekBar) { seekBar.handleMouseUp(event); } this.off(doc, 'mousemove', this.throttledHandleMouseSeek); this.off(doc, 'touchmove', this.throttledHandleMouseSeek); this.off(doc, 'mouseup', this.handleMouseUp); this.off(doc, 'touchend', this.handleMouseUp); }; return ProgressControl; }(Component); /** * Default options for `ProgressControl` * * @type {Object} * @private */ ProgressControl.prototype.options_ = { children: ['seekBar'] }; Component.registerComponent('ProgressControl', ProgressControl); /** * Toggle Picture-in-Picture mode * * @extends Button */ var PictureInPictureToggle = /*#__PURE__*/ function (_Button) { _inheritsLoose(PictureInPictureToggle, _Button); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. * * @listens Player#enterpictureinpicture * @listens Player#leavepictureinpicture */ function PictureInPictureToggle(player, options) { var _this; _this = _Button.call(this, player, options) || this; _this.on(player, ['enterpictureinpicture', 'leavepictureinpicture'], _this.handlePictureInPictureChange); // TODO: Activate button on player loadedmetadata event. // TODO: Deactivate button on player emptied event. // TODO: Deactivate button if disablepictureinpicture attribute is present. if (!document.pictureInPictureEnabled) { _this.disable(); } return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ var _proto = PictureInPictureToggle.prototype; _proto.buildCSSClass = function buildCSSClass() { return "vjs-picture-in-picture-control " + _Button.prototype.buildCSSClass.call(this); } /** * Handles enterpictureinpicture and leavepictureinpicture on the player and change control text accordingly. * * @param {EventTarget~Event} [event] * The {@link Player#enterpictureinpicture} or {@link Player#leavepictureinpicture} event that caused this function to be * called. * * @listens Player#enterpictureinpicture * @listens Player#leavepictureinpicture */ ; _proto.handlePictureInPictureChange = function handlePictureInPictureChange(event) { if (this.player_.isInPictureInPicture()) { this.controlText('Exit Picture-in-Picture'); } else { this.controlText('Picture-in-Picture'); } } /** * This gets called when an `PictureInPictureToggle` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ ; _proto.handleClick = function handleClick(event) { if (!this.player_.isInPictureInPicture()) { this.player_.requestPictureInPicture(); } else { this.player_.exitPictureInPicture(); } }; return PictureInPictureToggle; }(Button); /** * The text that should display over the `PictureInPictureToggle`s controls. Added for localization. * * @type {string} * @private */ PictureInPictureToggle.prototype.controlText_ = 'Picture-in-Picture'; Component.registerComponent('PictureInPictureToggle', PictureInPictureToggle); /** * Toggle fullscreen video * * @extends Button */ var FullscreenToggle = /*#__PURE__*/ function (_Button) { _inheritsLoose(FullscreenToggle, _Button); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function FullscreenToggle(player, options) { var _this; _this = _Button.call(this, player, options) || this; _this.on(player, 'fullscreenchange', _this.handleFullscreenChange); if (document[player.fsApi_.fullscreenEnabled] === false) { _this.disable(); } return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ var _proto = FullscreenToggle.prototype; _proto.buildCSSClass = function buildCSSClass() { return "vjs-fullscreen-control " + _Button.prototype.buildCSSClass.call(this); } /** * Handles fullscreenchange on the player and change control text accordingly. * * @param {EventTarget~Event} [event] * The {@link Player#fullscreenchange} event that caused this function to be * called. * * @listens Player#fullscreenchange */ ; _proto.handleFullscreenChange = function handleFullscreenChange(event) { if (this.player_.isFullscreen()) { this.controlText('Non-Fullscreen'); } else { this.controlText('Fullscreen'); } } /** * This gets called when an `FullscreenToggle` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ ; _proto.handleClick = function handleClick(event) { if (!this.player_.isFullscreen()) { this.player_.requestFullscreen(); } else { this.player_.exitFullscreen(); } }; return FullscreenToggle; }(Button); /** * The text that should display over the `FullscreenToggle`s controls. Added for localization. * * @type {string} * @private */ FullscreenToggle.prototype.controlText_ = 'Fullscreen'; Component.registerComponent('FullscreenToggle', FullscreenToggle); /** * Check if volume control is supported and if it isn't hide the * `Component` that was passed using the `vjs-hidden` class. * * @param {Component} self * The component that should be hidden if volume is unsupported * * @param {Player} player * A reference to the player * * @private */ var checkVolumeSupport = function checkVolumeSupport(self, player) { // hide volume controls when they're not supported by the current tech if (player.tech_ && !player.tech_.featuresVolumeControl) { self.addClass('vjs-hidden'); } self.on(player, 'loadstart', function () { if (!player.tech_.featuresVolumeControl) { self.addClass('vjs-hidden'); } else { self.removeClass('vjs-hidden'); } }); }; /** * Shows volume level * * @extends Component */ var VolumeLevel = /*#__PURE__*/ function (_Component) { _inheritsLoose(VolumeLevel, _Component); function VolumeLevel() { return _Component.apply(this, arguments) || this; } var _proto = VolumeLevel.prototype; /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ _proto.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-level', innerHTML: '<span class="vjs-control-text"></span>' }); }; return VolumeLevel; }(Component); Component.registerComponent('VolumeLevel', VolumeLevel); /** * The bar that contains the volume level and can be clicked on to adjust the level * * @extends Slider */ var VolumeBar = /*#__PURE__*/ function (_Slider) { _inheritsLoose(VolumeBar, _Slider); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function VolumeBar(player, options) { var _this; _this = _Slider.call(this, player, options) || this; _this.on('slideractive', _this.updateLastVolume_); _this.on(player, 'volumechange', _this.updateARIAAttributes); player.ready(function () { return _this.updateARIAAttributes(); }); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ var _proto = VolumeBar.prototype; _proto.createEl = function createEl() { return _Slider.prototype.createEl.call(this, 'div', { className: 'vjs-volume-bar vjs-slider-bar' }, { 'aria-label': this.localize('Volume Level'), 'aria-live': 'polite' }); } /** * Handle mouse down on volume bar * * @param {EventTarget~Event} event * The `mousedown` event that caused this to run. * * @listens mousedown */ ; _proto.handleMouseDown = function handleMouseDown(event) { if (!isSingleLeftClick(event)) { return; } _Slider.prototype.handleMouseDown.call(this, event); } /** * Handle movement events on the {@link VolumeMenuButton}. * * @param {EventTarget~Event} event * The event that caused this function to run. * * @listens mousemove */ ; _proto.handleMouseMove = function handleMouseMove(event) { if (!isSingleLeftClick(event)) { return; } this.checkMuted(); this.player_.volume(this.calculateDistance(event)); } /** * If the player is muted unmute it. */ ; _proto.checkMuted = function checkMuted() { if (this.player_.muted()) { this.player_.muted(false); } } /** * Get percent of volume level * * @return {number} * Volume level percent as a decimal number. */ ; _proto.getPercent = function getPercent() { if (this.player_.muted()) { return 0; } return this.player_.volume(); } /** * Increase volume level for keyboard users */ ; _proto.stepForward = function stepForward() { this.checkMuted(); this.player_.volume(this.player_.volume() + 0.1); } /** * Decrease volume level for keyboard users */ ; _proto.stepBack = function stepBack() { this.checkMuted(); this.player_.volume(this.player_.volume() - 0.1); } /** * Update ARIA accessibility attributes * * @param {EventTarget~Event} [event] * The `volumechange` event that caused this function to run. * * @listens Player#volumechange */ ; _proto.updateARIAAttributes = function updateARIAAttributes(event) { var ariaValue = this.player_.muted() ? 0 : this.volumeAsPercentage_(); this.el_.setAttribute('aria-valuenow', ariaValue); this.el_.setAttribute('aria-valuetext', ariaValue + '%'); } /** * Returns the current value of the player volume as a percentage * * @private */ ; _proto.volumeAsPercentage_ = function volumeAsPercentage_() { return Math.round(this.player_.volume() * 100); } /** * When user starts dragging the VolumeBar, store the volume and listen for * the end of the drag. When the drag ends, if the volume was set to zero, * set lastVolume to the stored volume. * * @listens slideractive * @private */ ; _proto.updateLastVolume_ = function updateLastVolume_() { var _this2 = this; var volumeBeforeDrag = this.player_.volume(); this.one('sliderinactive', function () { if (_this2.player_.volume() === 0) { _this2.player_.lastVolume_(volumeBeforeDrag); } }); }; return VolumeBar; }(Slider); /** * Default options for the `VolumeBar` * * @type {Object} * @private */ VolumeBar.prototype.options_ = { children: ['volumeLevel'], barName: 'volumeLevel' }; /** * Call the update event for this Slider when this event happens on the player. * * @type {string} */ VolumeBar.prototype.playerEvent = 'volumechange'; Component.registerComponent('VolumeBar', VolumeBar); /** * The component for controlling the volume level * * @extends Component */ var VolumeControl = /*#__PURE__*/ function (_Component) { _inheritsLoose(VolumeControl, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options={}] * The key/value store of player options. */ function VolumeControl(player, options) { var _this; if (options === void 0) { options = {}; } options.vertical = options.vertical || false; // Pass the vertical option down to the VolumeBar if // the VolumeBar is turned on. if (typeof options.volumeBar === 'undefined' || isPlain(options.volumeBar)) { options.volumeBar = options.volumeBar || {}; options.volumeBar.vertical = options.vertical; } _this = _Component.call(this, player, options) || this; // hide this control if volume support is missing checkVolumeSupport(_assertThisInitialized(_this), player); _this.throttledHandleMouseMove = throttle(bind(_assertThisInitialized(_this), _this.handleMouseMove), UPDATE_REFRESH_INTERVAL); _this.on('mousedown', _this.handleMouseDown); _this.on('touchstart', _this.handleMouseDown); // while the slider is active (the mouse has been pressed down and // is dragging) or in focus we do not want to hide the VolumeBar _this.on(_this.volumeBar, ['focus', 'slideractive'], function () { _this.volumeBar.addClass('vjs-slider-active'); _this.addClass('vjs-slider-active'); _this.trigger('slideractive'); }); _this.on(_this.volumeBar, ['blur', 'sliderinactive'], function () { _this.volumeBar.removeClass('vjs-slider-active'); _this.removeClass('vjs-slider-active'); _this.trigger('sliderinactive'); }); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ var _proto = VolumeControl.prototype; _proto.createEl = function createEl() { var orientationClass = 'vjs-volume-horizontal'; if (this.options_.vertical) { orientationClass = 'vjs-volume-vertical'; } return _Component.prototype.createEl.call(this, 'div', { className: "vjs-volume-control vjs-control " + orientationClass }); } /** * Handle `mousedown` or `touchstart` events on the `VolumeControl`. * * @param {EventTarget~Event} event * `mousedown` or `touchstart` event that triggered this function * * @listens mousedown * @listens touchstart */ ; _proto.handleMouseDown = function handleMouseDown(event) { var doc = this.el_.ownerDocument; this.on(doc, 'mousemove', this.throttledHandleMouseMove); this.on(doc, 'touchmove', this.throttledHandleMouseMove); this.on(doc, 'mouseup', this.handleMouseUp); this.on(doc, 'touchend', this.handleMouseUp); } /** * Handle `mouseup` or `touchend` events on the `VolumeControl`. * * @param {EventTarget~Event} event * `mouseup` or `touchend` event that triggered this function. * * @listens touchend * @listens mouseup */ ; _proto.handleMouseUp = function handleMouseUp(event) { var doc = this.el_.ownerDocument; this.off(doc, 'mousemove', this.throttledHandleMouseMove); this.off(doc, 'touchmove', this.throttledHandleMouseMove); this.off(doc, 'mouseup', this.handleMouseUp); this.off(doc, 'touchend', this.handleMouseUp); } /** * Handle `mousedown` or `touchstart` events on the `VolumeControl`. * * @param {EventTarget~Event} event * `mousedown` or `touchstart` event that triggered this function * * @listens mousedown * @listens touchstart */ ; _proto.handleMouseMove = function handleMouseMove(event) { this.volumeBar.handleMouseMove(event); }; return VolumeControl; }(Component); /** * Default options for the `VolumeControl` * * @type {Object} * @private */ VolumeControl.prototype.options_ = { children: ['volumeBar'] }; Component.registerComponent('VolumeControl', VolumeControl); /** * Check if muting volume is supported and if it isn't hide the mute toggle * button. * * @param {Component} self * A reference to the mute toggle button * * @param {Player} player * A reference to the player * * @private */ var checkMuteSupport = function checkMuteSupport(self, player) { // hide mute toggle button if it's not supported by the current tech if (player.tech_ && !player.tech_.featuresMuteControl) { self.addClass('vjs-hidden'); } self.on(player, 'loadstart', function () { if (!player.tech_.featuresMuteControl) { self.addClass('vjs-hidden'); } else { self.removeClass('vjs-hidden'); } }); }; /** * A button component for muting the audio. * * @extends Button */ var MuteToggle = /*#__PURE__*/ function (_Button) { _inheritsLoose(MuteToggle, _Button); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function MuteToggle(player, options) { var _this; _this = _Button.call(this, player, options) || this; // hide this control if volume support is missing checkMuteSupport(_assertThisInitialized(_this), player); _this.on(player, ['loadstart', 'volumechange'], _this.update); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ var _proto = MuteToggle.prototype; _proto.buildCSSClass = function buildCSSClass() { return "vjs-mute-control " + _Button.prototype.buildCSSClass.call(this); } /** * This gets called when an `MuteToggle` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ ; _proto.handleClick = function handleClick(event) { var vol = this.player_.volume(); var lastVolume = this.player_.lastVolume_(); if (vol === 0) { var volumeToSet = lastVolume < 0.1 ? 0.1 : lastVolume; this.player_.volume(volumeToSet); this.player_.muted(false); } else { this.player_.muted(this.player_.muted() ? false : true); } } /** * Update the `MuteToggle` button based on the state of `volume` and `muted` * on the player. * * @param {EventTarget~Event} [event] * The {@link Player#loadstart} event if this function was called * through an event. * * @listens Player#loadstart * @listens Player#volumechange */ ; _proto.update = function update(event) { this.updateIcon_(); this.updateControlText_(); } /** * Update the appearance of the `MuteToggle` icon. * * Possible states (given `level` variable below): * - 0: crossed out * - 1: zero bars of volume * - 2: one bar of volume * - 3: two bars of volume * * @private */ ; _proto.updateIcon_ = function updateIcon_() { var vol = this.player_.volume(); var level = 3; // in iOS when a player is loaded with muted attribute // and volume is changed with a native mute button // we want to make sure muted state is updated if (IS_IOS && this.player_.tech_ && this.player_.tech_.el_) { this.player_.muted(this.player_.tech_.el_.muted); } if (vol === 0 || this.player_.muted()) { level = 0; } else if (vol < 0.33) { level = 1; } else if (vol < 0.67) { level = 2; } // TODO improve muted icon classes for (var i = 0; i < 4; i++) { removeClass(this.el_, "vjs-vol-" + i); } addClass(this.el_, "vjs-vol-" + level); } /** * If `muted` has changed on the player, update the control text * (`title` attribute on `vjs-mute-control` element and content of * `vjs-control-text` element). * * @private */ ; _proto.updateControlText_ = function updateControlText_() { var soundOff = this.player_.muted() || this.player_.volume() === 0; var text = soundOff ? 'Unmute' : 'Mute'; if (this.controlText() !== text) { this.controlText(text); } }; return MuteToggle; }(Button); /** * The text that should display over the `MuteToggle`s controls. Added for localization. * * @type {string} * @private */ MuteToggle.prototype.controlText_ = 'Mute'; Component.registerComponent('MuteToggle', MuteToggle); /** * A Component to contain the MuteToggle and VolumeControl so that * they can work together. * * @extends Component */ var VolumePanel = /*#__PURE__*/ function (_Component) { _inheritsLoose(VolumePanel, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options={}] * The key/value store of player options. */ function VolumePanel(player, options) { var _this; if (options === void 0) { options = {}; } if (typeof options.inline !== 'undefined') { options.inline = options.inline; } else { options.inline = true; } // pass the inline option down to the VolumeControl as vertical if // the VolumeControl is on. if (typeof options.volumeControl === 'undefined' || isPlain(options.volumeControl)) { options.volumeControl = options.volumeControl || {}; options.volumeControl.vertical = !options.inline; } _this = _Component.call(this, player, options) || this; _this.on(player, ['loadstart'], _this.volumePanelState_); _this.on(_this.muteToggle, 'keyup', _this.handleKeyPress); _this.on(_this.volumeControl, 'keyup', _this.handleVolumeControlKeyUp); _this.on('keydown', _this.handleKeyPress); _this.on('mouseover', _this.handleMouseOver); _this.on('mouseout', _this.handleMouseOut); // while the slider is active (the mouse has been pressed down and // is dragging) we do not want to hide the VolumeBar _this.on(_this.volumeControl, ['slideractive'], _this.sliderActive_); _this.on(_this.volumeControl, ['sliderinactive'], _this.sliderInactive_); return _this; } /** * Add vjs-slider-active class to the VolumePanel * * @listens VolumeControl#slideractive * @private */ var _proto = VolumePanel.prototype; _proto.sliderActive_ = function sliderActive_() { this.addClass('vjs-slider-active'); } /** * Removes vjs-slider-active class to the VolumePanel * * @listens VolumeControl#sliderinactive * @private */ ; _proto.sliderInactive_ = function sliderInactive_() { this.removeClass('vjs-slider-active'); } /** * Adds vjs-hidden or vjs-mute-toggle-only to the VolumePanel * depending on MuteToggle and VolumeControl state * * @listens Player#loadstart * @private */ ; _proto.volumePanelState_ = function volumePanelState_() { // hide volume panel if neither volume control or mute toggle // are displayed if (this.volumeControl.hasClass('vjs-hidden') && this.muteToggle.hasClass('vjs-hidden')) { this.addClass('vjs-hidden'); } // if only mute toggle is visible we don't want // volume panel expanding when hovered or active if (this.volumeControl.hasClass('vjs-hidden') && !this.muteToggle.hasClass('vjs-hidden')) { this.addClass('vjs-mute-toggle-only'); } } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ ; _proto.createEl = function createEl() { var orientationClass = 'vjs-volume-panel-horizontal'; if (!this.options_.inline) { orientationClass = 'vjs-volume-panel-vertical'; } return _Component.prototype.createEl.call(this, 'div', { className: "vjs-volume-panel vjs-control " + orientationClass }); } /** * Dispose of the `volume-panel` and all child components. */ ; _proto.dispose = function dispose() { this.handleMouseOut(); _Component.prototype.dispose.call(this); } /** * Handles `keyup` events on the `VolumeControl`, looking for ESC, which closes * the volume panel and sets focus on `MuteToggle`. * * @param {EventTarget~Event} event * The `keyup` event that caused this function to be called. * * @listens keyup */ ; _proto.handleVolumeControlKeyUp = function handleVolumeControlKeyUp(event) { if (keycode.isEventKey(event, 'Esc')) { this.muteToggle.focus(); } } /** * This gets called when a `VolumePanel` gains hover via a `mouseover` event. * Turns on listening for `mouseover` event. When they happen it * calls `this.handleMouseOver`. * * @param {EventTarget~Event} event * The `mouseover` event that caused this function to be called. * * @listens mouseover */ ; _proto.handleMouseOver = function handleMouseOver(event) { this.addClass('vjs-hover'); on(document, 'keyup', bind(this, this.handleKeyPress)); } /** * This gets called when a `VolumePanel` gains hover via a `mouseout` event. * Turns on listening for `mouseout` event. When they happen it * calls `this.handleMouseOut`. * * @param {EventTarget~Event} event * The `mouseout` event that caused this function to be called. * * @listens mouseout */ ; _proto.handleMouseOut = function handleMouseOut(event) { this.removeClass('vjs-hover'); off(document, 'keyup', bind(this, this.handleKeyPress)); } /** * Handles `keyup` event on the document or `keydown` event on the `VolumePanel`, * looking for ESC, which hides the `VolumeControl`. * * @param {EventTarget~Event} event * The keypress that triggered this event. * * @listens keydown | keyup */ ; _proto.handleKeyPress = function handleKeyPress(event) { if (keycode.isEventKey(event, 'Esc')) { this.handleMouseOut(); } }; return VolumePanel; }(Component); /** * Default options for the `VolumeControl` * * @type {Object} * @private */ VolumePanel.prototype.options_ = { children: ['muteToggle', 'volumeControl'] }; Component.registerComponent('VolumePanel', VolumePanel); /** * The Menu component is used to build popup menus, including subtitle and * captions selection menus. * * @extends Component */ var Menu = /*#__PURE__*/ function (_Component) { _inheritsLoose(Menu, _Component); /** * Create an instance of this class. * * @param {Player} player * the player that this component should attach to * * @param {Object} [options] * Object of option names and values * */ function Menu(player, options) { var _this; _this = _Component.call(this, player, options) || this; if (options) { _this.menuButton_ = options.menuButton; } _this.focusedChild_ = -1; _this.on('keydown', _this.handleKeyDown); // All the menu item instances share the same blur handler provided by the menu container. _this.boundHandleBlur_ = bind(_assertThisInitialized(_this), _this.handleBlur); _this.boundHandleTapClick_ = bind(_assertThisInitialized(_this), _this.handleTapClick); return _this; } /** * Add event listeners to the {@link MenuItem}. * * @param {Object} component * The instance of the `MenuItem` to add listeners to. * */ var _proto = Menu.prototype; _proto.addEventListenerForItem = function addEventListenerForItem(component) { if (!(component instanceof Component)) { return; } this.on(component, 'blur', this.boundHandleBlur_); this.on(component, ['tap', 'click'], this.boundHandleTapClick_); } /** * Remove event listeners from the {@link MenuItem}. * * @param {Object} component * The instance of the `MenuItem` to remove listeners. * */ ; _proto.removeEventListenerForItem = function removeEventListenerForItem(component) { if (!(component instanceof Component)) { return; } this.off(component, 'blur', this.boundHandleBlur_); this.off(component, ['tap', 'click'], this.boundHandleTapClick_); } /** * This method will be called indirectly when the component has been added * before the component adds to the new menu instance by `addItem`. * In this case, the original menu instance will remove the component * by calling `removeChild`. * * @param {Object} component * The instance of the `MenuItem` */ ; _proto.removeChild = function removeChild(component) { if (typeof component === 'string') { component = this.getChild(component); } this.removeEventListenerForItem(component); _Component.prototype.removeChild.call(this, component); } /** * Add a {@link MenuItem} to the menu. * * @param {Object|string} component * The name or instance of the `MenuItem` to add. * */ ; _proto.addItem = function addItem(component) { var childComponent = this.addChild(component); if (childComponent) { this.addEventListenerForItem(childComponent); } } /** * Create the `Menu`s DOM element. * * @return {Element} * the element that was created */ ; _proto.createEl = function createEl$1() { var contentElType = this.options_.contentElType || 'ul'; this.contentEl_ = createEl(contentElType, { className: 'vjs-menu-content' }); this.contentEl_.setAttribute('role', 'menu'); var el = _Component.prototype.createEl.call(this, 'div', { append: this.contentEl_, className: 'vjs-menu' }); el.appendChild(this.contentEl_); // Prevent clicks from bubbling up. Needed for Menu Buttons, // where a click on the parent is significant on(el, 'click', function (event) { event.preventDefault(); event.stopImmediatePropagation(); }); return el; }; _proto.dispose = function dispose() { this.contentEl_ = null; this.boundHandleBlur_ = null; this.boundHandleTapClick_ = null; _Component.prototype.dispose.call(this); } /** * Called when a `MenuItem` loses focus. * * @param {EventTarget~Event} event * The `blur` event that caused this function to be called. * * @listens blur */ ; _proto.handleBlur = function handleBlur(event) { var relatedTarget = event.relatedTarget || document.activeElement; // Close menu popup when a user clicks outside the menu if (!this.children().some(function (element) { return element.el() === relatedTarget; })) { var btn = this.menuButton_; if (btn && btn.buttonPressed_ && relatedTarget !== btn.el().firstChild) { btn.unpressButton(); } } } /** * Called when a `MenuItem` gets clicked or tapped. * * @param {EventTarget~Event} event * The `click` or `tap` event that caused this function to be called. * * @listens click,tap */ ; _proto.handleTapClick = function handleTapClick(event) { // Unpress the associated MenuButton, and move focus back to it if (this.menuButton_) { this.menuButton_.unpressButton(); var childComponents = this.children(); if (!Array.isArray(childComponents)) { return; } var foundComponent = childComponents.filter(function (component) { return component.el() === event.target; })[0]; if (!foundComponent) { return; } // don't focus menu button if item is a caption settings item // because focus will move elsewhere if (foundComponent.name() !== 'CaptionSettingsMenuItem') { this.menuButton_.focus(); } } } /** * Handle a `keydown` event on this menu. This listener is added in the constructor. * * @param {EventTarget~Event} event * A `keydown` event that happened on the menu. * * @listens keydown */ ; _proto.handleKeyDown = function handleKeyDown(event) { // Left and Down Arrows if (keycode.isEventKey(event, 'Left') || keycode.isEventKey(event, 'Down')) { event.preventDefault(); event.stopPropagation(); this.stepForward(); // Up and Right Arrows } else if (keycode.isEventKey(event, 'Right') || keycode.isEventKey(event, 'Up')) { event.preventDefault(); event.stopPropagation(); this.stepBack(); } } /** * Move to next (lower) menu item for keyboard users. */ ; _proto.stepForward = function stepForward() { var stepChild = 0; if (this.focusedChild_ !== undefined) { stepChild = this.focusedChild_ + 1; } this.focus(stepChild); } /** * Move to previous (higher) menu item for keyboard users. */ ; _proto.stepBack = function stepBack() { var stepChild = 0; if (this.focusedChild_ !== undefined) { stepChild = this.focusedChild_ - 1; } this.focus(stepChild); } /** * Set focus on a {@link MenuItem} in the `Menu`. * * @param {Object|string} [item=0] * Index of child item set focus on. */ ; _proto.focus = function focus(item) { if (item === void 0) { item = 0; } var children = this.children().slice(); var haveTitle = children.length && children[0].className && /vjs-menu-title/.test(children[0].className); if (haveTitle) { children.shift(); } if (children.length > 0) { if (item < 0) { item = 0; } else if (item >= children.length) { item = children.length - 1; } this.focusedChild_ = item; children[item].el_.focus(); } }; return Menu; }(Component); Component.registerComponent('Menu', Menu); /** * A `MenuButton` class for any popup {@link Menu}. * * @extends Component */ var MenuButton = /*#__PURE__*/ function (_Component) { _inheritsLoose(MenuButton, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options={}] * The key/value store of player options. */ function MenuButton(player, options) { var _this; if (options === void 0) { options = {}; } _this = _Component.call(this, player, options) || this; _this.menuButton_ = new Button(player, options); _this.menuButton_.controlText(_this.controlText_); _this.menuButton_.el_.setAttribute('aria-haspopup', 'true'); // Add buildCSSClass values to the button, not the wrapper var buttonClass = Button.prototype.buildCSSClass(); _this.menuButton_.el_.className = _this.buildCSSClass() + ' ' + buttonClass; _this.menuButton_.removeClass('vjs-control'); _this.addChild(_this.menuButton_); _this.update(); _this.enabled_ = true; _this.on(_this.menuButton_, 'tap', _this.handleClick); _this.on(_this.menuButton_, 'click', _this.handleClick); _this.on(_this.menuButton_, 'keydown', _this.handleKeyDown); _this.on(_this.menuButton_, 'mouseenter', function () { _this.addClass('vjs-hover'); _this.menu.show(); on(document, 'keyup', bind(_assertThisInitialized(_this), _this.handleMenuKeyUp)); }); _this.on('mouseleave', _this.handleMouseLeave); _this.on('keydown', _this.handleSubmenuKeyDown); return _this; } /** * Update the menu based on the current state of its items. */ var _proto = MenuButton.prototype; _proto.update = function update() { var menu = this.createMenu(); if (this.menu) { this.menu.dispose(); this.removeChild(this.menu); } this.menu = menu; this.addChild(menu); /** * Track the state of the menu button * * @type {Boolean} * @private */ this.buttonPressed_ = false; this.menuButton_.el_.setAttribute('aria-expanded', 'false'); if (this.items && this.items.length <= this.hideThreshold_) { this.hide(); } else { this.show(); } } /** * Create the menu and add all items to it. * * @return {Menu} * The constructed menu */ ; _proto.createMenu = function createMenu() { var menu = new Menu(this.player_, { menuButton: this }); /** * Hide the menu if the number of items is less than or equal to this threshold. This defaults * to 0 and whenever we add items which can be hidden to the menu we'll increment it. We list * it here because every time we run `createMenu` we need to reset the value. * * @protected * @type {Number} */ this.hideThreshold_ = 0; // Add a title list item to the top if (this.options_.title) { var titleEl = createEl('li', { className: 'vjs-menu-title', innerHTML: toTitleCase(this.options_.title), tabIndex: -1 }); this.hideThreshold_ += 1; var titleComponent = new Component(this.player_, { el: titleEl }); menu.addItem(titleComponent); } this.items = this.createItems(); if (this.items) { // Add menu items to the menu for (var i = 0; i < this.items.length; i++) { menu.addItem(this.items[i]); } } return menu; } /** * Create the list of menu items. Specific to each subclass. * * @abstract */ ; _proto.createItems = function createItems() {} /** * Create the `MenuButtons`s DOM element. * * @return {Element} * The element that gets created. */ ; _proto.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: this.buildWrapperCSSClass() }, {}); } /** * Allow sub components to stack CSS class names for the wrapper element * * @return {string} * The constructed wrapper DOM `className` */ ; _proto.buildWrapperCSSClass = function buildWrapperCSSClass() { var menuButtonClass = 'vjs-menu-button'; // If the inline option is passed, we want to use different styles altogether. if (this.options_.inline === true) { menuButtonClass += '-inline'; } else { menuButtonClass += '-popup'; } // TODO: Fix the CSS so that this isn't necessary var buttonClass = Button.prototype.buildCSSClass(); return "vjs-menu-button " + menuButtonClass + " " + buttonClass + " " + _Component.prototype.buildCSSClass.call(this); } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ ; _proto.buildCSSClass = function buildCSSClass() { var menuButtonClass = 'vjs-menu-button'; // If the inline option is passed, we want to use different styles altogether. if (this.options_.inline === true) { menuButtonClass += '-inline'; } else { menuButtonClass += '-popup'; } return "vjs-menu-button " + menuButtonClass + " " + _Component.prototype.buildCSSClass.call(this); } /** * Get or set the localized control text that will be used for accessibility. * * > NOTE: This will come from the internal `menuButton_` element. * * @param {string} [text] * Control text for element. * * @param {Element} [el=this.menuButton_.el()] * Element to set the title on. * * @return {string} * - The control text when getting */ ; _proto.controlText = function controlText(text, el) { if (el === void 0) { el = this.menuButton_.el(); } return this.menuButton_.controlText(text, el); } /** * Dispose of the `menu-button` and all child components. */ ; _proto.dispose = function dispose() { this.handleMouseLeave(); _Component.prototype.dispose.call(this); } /** * Handle a click on a `MenuButton`. * See {@link ClickableComponent#handleClick} for instances where this is called. * * @param {EventTarget~Event} event * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ ; _proto.handleClick = function handleClick(event) { if (this.buttonPressed_) { this.unpressButton(); } else { this.pressButton(); } } /** * Handle `mouseleave` for `MenuButton`. * * @param {EventTarget~Event} event * The `mouseleave` event that caused this function to be called. * * @listens mouseleave */ ; _proto.handleMouseLeave = function handleMouseLeave(event) { this.removeClass('vjs-hover'); off(document, 'keyup', bind(this, this.handleMenuKeyUp)); } /** * Set the focus to the actual button, not to this element */ ; _proto.focus = function focus() { this.menuButton_.focus(); } /** * Remove the focus from the actual button, not this element */ ; _proto.blur = function blur() { this.menuButton_.blur(); } /** * Handle tab, escape, down arrow, and up arrow keys for `MenuButton`. See * {@link ClickableComponent#handleKeyDown} for instances where this is called. * * @param {EventTarget~Event} event * The `keydown` event that caused this function to be called. * * @listens keydown */ ; _proto.handleKeyDown = function handleKeyDown(event) { // Escape or Tab unpress the 'button' if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) { if (this.buttonPressed_) { this.unpressButton(); } // Don't preventDefault for Tab key - we still want to lose focus if (!keycode.isEventKey(event, 'Tab')) { event.preventDefault(); // Set focus back to the menu button's button this.menuButton_.focus(); } // Up Arrow or Down Arrow also 'press' the button to open the menu } else if (keycode.isEventKey(event, 'Up') || keycode.isEventKey(event, 'Down')) { if (!this.buttonPressed_) { event.preventDefault(); this.pressButton(); } } } /** * Handle a `keyup` event on a `MenuButton`. The listener for this is added in * the constructor. * * @param {EventTarget~Event} event * Key press event * * @listens keyup */ ; _proto.handleMenuKeyUp = function handleMenuKeyUp(event) { // Escape hides popup menu if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) { this.removeClass('vjs-hover'); } } /** * This method name now delegates to `handleSubmenuKeyDown`. This means * anyone calling `handleSubmenuKeyPress` will not see their method calls * stop working. * * @param {EventTarget~Event} event * The event that caused this function to be called. */ ; _proto.handleSubmenuKeyPress = function handleSubmenuKeyPress(event) { this.handleSubmenuKeyDown(event); } /** * Handle a `keydown` event on a sub-menu. The listener for this is added in * the constructor. * * @param {EventTarget~Event} event * Key press event * * @listens keydown */ ; _proto.handleSubmenuKeyDown = function handleSubmenuKeyDown(event) { // Escape or Tab unpress the 'button' if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) { if (this.buttonPressed_) { this.unpressButton(); } // Don't preventDefault for Tab key - we still want to lose focus if (!keycode.isEventKey(event, 'Tab')) { event.preventDefault(); // Set focus back to the menu button's button this.menuButton_.focus(); } } } /** * Put the current `MenuButton` into a pressed state. */ ; _proto.pressButton = function pressButton() { if (this.enabled_) { this.buttonPressed_ = true; this.menu.show(); this.menu.lockShowing(); this.menuButton_.el_.setAttribute('aria-expanded', 'true'); // set the focus into the submenu, except on iOS where it is resulting in // undesired scrolling behavior when the player is in an iframe if (IS_IOS && isInFrame()) { // Return early so that the menu isn't focused return; } this.menu.focus(); } } /** * Take the current `MenuButton` out of a pressed state. */ ; _proto.unpressButton = function unpressButton() { if (this.enabled_) { this.buttonPressed_ = false; this.menu.unlockShowing(); this.menu.hide(); this.menuButton_.el_.setAttribute('aria-expanded', 'false'); } } /** * Disable the `MenuButton`. Don't allow it to be clicked. */ ; _proto.disable = function disable() { this.unpressButton(); this.enabled_ = false; this.addClass('vjs-disabled'); this.menuButton_.disable(); } /** * Enable the `MenuButton`. Allow it to be clicked. */ ; _proto.enable = function enable() { this.enabled_ = true; this.removeClass('vjs-disabled'); this.menuButton_.enable(); }; return MenuButton; }(Component); Component.registerComponent('MenuButton', MenuButton); /** * The base class for buttons that toggle specific track types (e.g. subtitles). * * @extends MenuButton */ var TrackButton = /*#__PURE__*/ function (_MenuButton) { _inheritsLoose(TrackButton, _MenuButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function TrackButton(player, options) { var _this; var tracks = options.tracks; _this = _MenuButton.call(this, player, options) || this; if (_this.items.length <= 1) { _this.hide(); } if (!tracks) { return _assertThisInitialized(_this); } var updateHandler = bind(_assertThisInitialized(_this), _this.update); tracks.addEventListener('removetrack', updateHandler); tracks.addEventListener('addtrack', updateHandler); _this.player_.on('ready', updateHandler); _this.player_.on('dispose', function () { tracks.removeEventListener('removetrack', updateHandler); tracks.removeEventListener('addtrack', updateHandler); }); return _this; } return TrackButton; }(MenuButton); Component.registerComponent('TrackButton', TrackButton); /** * @file menu-keys.js */ /** * All keys used for operation of a menu (`MenuButton`, `Menu`, and `MenuItem`) * Note that 'Enter' and 'Space' are not included here (otherwise they would * prevent the `MenuButton` and `MenuItem` from being keyboard-clickable) * @typedef MenuKeys * @array */ var MenuKeys = ['Tab', 'Esc', 'Up', 'Down', 'Right', 'Left']; /** * The component for a menu item. `<li>` * * @extends ClickableComponent */ var MenuItem = /*#__PURE__*/ function (_ClickableComponent) { _inheritsLoose(MenuItem, _ClickableComponent); /** * Creates an instance of the this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options={}] * The key/value store of player options. * */ function MenuItem(player, options) { var _this; _this = _ClickableComponent.call(this, player, options) || this; _this.selectable = options.selectable; _this.isSelected_ = options.selected || false; _this.multiSelectable = options.multiSelectable; _this.selected(_this.isSelected_); if (_this.selectable) { if (_this.multiSelectable) { _this.el_.setAttribute('role', 'menuitemcheckbox'); } else { _this.el_.setAttribute('role', 'menuitemradio'); } } else { _this.el_.setAttribute('role', 'menuitem'); } return _this; } /** * Create the `MenuItem's DOM element * * @param {string} [type=li] * Element's node type, not actually used, always set to `li`. * * @param {Object} [props={}] * An object of properties that should be set on the element * * @param {Object} [attrs={}] * An object of attributes that should be set on the element * * @return {Element} * The element that gets created. */ var _proto = MenuItem.prototype; _proto.createEl = function createEl(type, props, attrs) { // The control is textual, not just an icon this.nonIconControl = true; return _ClickableComponent.prototype.createEl.call(this, 'li', assign({ className: 'vjs-menu-item', innerHTML: "<span class=\"vjs-menu-item-text\">" + this.localize(this.options_.label) + "</span>", tabIndex: -1 }, props), attrs); } /** * Ignore keys which are used by the menu, but pass any other ones up. See * {@link ClickableComponent#handleKeyDown} for instances where this is called. * * @param {EventTarget~Event} event * The `keydown` event that caused this function to be called. * * @listens keydown */ ; _proto.handleKeyDown = function handleKeyDown(event) { if (!MenuKeys.some(function (key) { return keycode.isEventKey(event, key); })) { // Pass keydown handling up for unused keys _ClickableComponent.prototype.handleKeyDown.call(this, event); } } /** * Any click on a `MenuItem` puts it into the selected state. * See {@link ClickableComponent#handleClick} for instances where this is called. * * @param {EventTarget~Event} event * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ ; _proto.handleClick = function handleClick(event) { this.selected(true); } /** * Set the state for this menu item as selected or not. * * @param {boolean} selected * if the menu item is selected or not */ ; _proto.selected = function selected(_selected) { if (this.selectable) { if (_selected) { this.addClass('vjs-selected'); this.el_.setAttribute('aria-checked', 'true'); // aria-checked isn't fully supported by browsers/screen readers, // so indicate selected state to screen reader in the control text. this.controlText(', selected'); this.isSelected_ = true; } else { this.removeClass('vjs-selected'); this.el_.setAttribute('aria-checked', 'false'); // Indicate un-selected state to screen reader this.controlText(''); this.isSelected_ = false; } } }; return MenuItem; }(ClickableComponent); Component.registerComponent('MenuItem', MenuItem); /** * The specific menu item type for selecting a language within a text track kind * * @extends MenuItem */ var TextTrackMenuItem = /*#__PURE__*/ function (_MenuItem) { _inheritsLoose(TextTrackMenuItem, _MenuItem); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function TextTrackMenuItem(player, options) { var _this; var track = options.track; var tracks = player.textTracks(); // Modify options for parent MenuItem class's init. options.label = track.label || track.language || 'Unknown'; options.selected = track.mode === 'showing'; _this = _MenuItem.call(this, player, options) || this; _this.track = track; // Determine the relevant kind(s) of tracks for this component and filter // out empty kinds. _this.kinds = (options.kinds || [options.kind || _this.track.kind]).filter(Boolean); var changeHandler = function changeHandler() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this.handleTracksChange.apply(_assertThisInitialized(_this), args); }; var selectedLanguageChangeHandler = function selectedLanguageChangeHandler() { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } _this.handleSelectedLanguageChange.apply(_assertThisInitialized(_this), args); }; player.on(['loadstart', 'texttrackchange'], changeHandler); tracks.addEventListener('change', changeHandler); tracks.addEventListener('selectedlanguagechange', selectedLanguageChangeHandler); _this.on('dispose', function () { player.off(['loadstart', 'texttrackchange'], changeHandler); tracks.removeEventListener('change', changeHandler); tracks.removeEventListener('selectedlanguagechange', selectedLanguageChangeHandler); }); // iOS7 doesn't dispatch change events to TextTrackLists when an // associated track's mode changes. Without something like // Object.observe() (also not present on iOS7), it's not // possible to detect changes to the mode attribute and polyfill // the change event. As a poor substitute, we manually dispatch // change events whenever the controls modify the mode. if (tracks.onchange === undefined) { var event; _this.on(['tap', 'click'], function () { if (typeof window$1.Event !== 'object') { // Android 2.3 throws an Illegal Constructor error for window.Event try { event = new window$1.Event('change'); } catch (err) {// continue regardless of error } } if (!event) { event = document.createEvent('Event'); event.initEvent('change', true, true); } tracks.dispatchEvent(event); }); } // set the default state based on current tracks _this.handleTracksChange(); return _this; } /** * This gets called when an `TextTrackMenuItem` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} event * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ var _proto = TextTrackMenuItem.prototype; _proto.handleClick = function handleClick(event) { var referenceTrack = this.track; var tracks = this.player_.textTracks(); _MenuItem.prototype.handleClick.call(this, event); if (!tracks) { return; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; // If the track from the text tracks list is not of the right kind, // skip it. We do not want to affect tracks of incompatible kind(s). if (this.kinds.indexOf(track.kind) === -1) { continue; } // If this text track is the component's track and it is not showing, // set it to showing. if (track === referenceTrack) { if (track.mode !== 'showing') { track.mode = 'showing'; } // If this text track is not the component's track and it is not // disabled, set it to disabled. } else if (track.mode !== 'disabled') { track.mode = 'disabled'; } } } /** * Handle text track list change * * @param {EventTarget~Event} event * The `change` event that caused this function to be called. * * @listens TextTrackList#change */ ; _proto.handleTracksChange = function handleTracksChange(event) { var shouldBeSelected = this.track.mode === 'showing'; // Prevent redundant selected() calls because they may cause // screen readers to read the appended control text unnecessarily if (shouldBeSelected !== this.isSelected_) { this.selected(shouldBeSelected); } }; _proto.handleSelectedLanguageChange = function handleSelectedLanguageChange(event) { if (this.track.mode === 'showing') { var selectedLanguage = this.player_.cache_.selectedLanguage; // Don't replace the kind of track across the same language if (selectedLanguage && selectedLanguage.enabled && selectedLanguage.language === this.track.language && selectedLanguage.kind !== this.track.kind) { return; } this.player_.cache_.selectedLanguage = { enabled: true, language: this.track.language, kind: this.track.kind }; } }; _proto.dispose = function dispose() { // remove reference to track object on dispose this.track = null; _MenuItem.prototype.dispose.call(this); }; return TextTrackMenuItem; }(MenuItem); Component.registerComponent('TextTrackMenuItem', TextTrackMenuItem); /** * A special menu item for turning of a specific type of text track * * @extends TextTrackMenuItem */ var OffTextTrackMenuItem = /*#__PURE__*/ function (_TextTrackMenuItem) { _inheritsLoose(OffTextTrackMenuItem, _TextTrackMenuItem); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function OffTextTrackMenuItem(player, options) { // Create pseudo track info // Requires options['kind'] options.track = { player: player, // it is no longer necessary to store `kind` or `kinds` on the track itself // since they are now stored in the `kinds` property of all instances of // TextTrackMenuItem, but this will remain for backwards compatibility kind: options.kind, kinds: options.kinds, "default": false, mode: 'disabled' }; if (!options.kinds) { options.kinds = [options.kind]; } if (options.label) { options.track.label = options.label; } else { options.track.label = options.kinds.join(' and ') + ' off'; } // MenuItem is selectable options.selectable = true; // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time) options.multiSelectable = false; return _TextTrackMenuItem.call(this, player, options) || this; } /** * Handle text track change * * @param {EventTarget~Event} event * The event that caused this function to run */ var _proto = OffTextTrackMenuItem.prototype; _proto.handleTracksChange = function handleTracksChange(event) { var tracks = this.player().textTracks(); var shouldBeSelected = true; for (var i = 0, l = tracks.length; i < l; i++) { var track = tracks[i]; if (this.options_.kinds.indexOf(track.kind) > -1 && track.mode === 'showing') { shouldBeSelected = false; break; } } // Prevent redundant selected() calls because they may cause // screen readers to read the appended control text unnecessarily if (shouldBeSelected !== this.isSelected_) { this.selected(shouldBeSelected); } }; _proto.handleSelectedLanguageChange = function handleSelectedLanguageChange(event) { var tracks = this.player().textTracks(); var allHidden = true; for (var i = 0, l = tracks.length; i < l; i++) { var track = tracks[i]; if (['captions', 'descriptions', 'subtitles'].indexOf(track.kind) > -1 && track.mode === 'showing') { allHidden = false; break; } } if (allHidden) { this.player_.cache_.selectedLanguage = { enabled: false }; } }; return OffTextTrackMenuItem; }(TextTrackMenuItem); Component.registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem); /** * The base class for buttons that toggle specific text track types (e.g. subtitles) * * @extends MenuButton */ var TextTrackButton = /*#__PURE__*/ function (_TrackButton) { _inheritsLoose(TextTrackButton, _TrackButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options={}] * The key/value store of player options. */ function TextTrackButton(player, options) { if (options === void 0) { options = {}; } options.tracks = player.textTracks(); return _TrackButton.call(this, player, options) || this; } /** * Create a menu item for each text track * * @param {TextTrackMenuItem[]} [items=[]] * Existing array of items to use during creation * * @return {TextTrackMenuItem[]} * Array of menu items that were created */ var _proto = TextTrackButton.prototype; _proto.createItems = function createItems(items, TrackMenuItem) { if (items === void 0) { items = []; } if (TrackMenuItem === void 0) { TrackMenuItem = TextTrackMenuItem; } // Label is an override for the [track] off label // USed to localise captions/subtitles var label; if (this.label_) { label = this.label_ + " off"; } // Add an OFF menu item to turn all tracks off items.push(new OffTextTrackMenuItem(this.player_, { kinds: this.kinds_, kind: this.kind_, label: label })); this.hideThreshold_ += 1; var tracks = this.player_.textTracks(); if (!Array.isArray(this.kinds_)) { this.kinds_ = [this.kind_]; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; // only add tracks that are of an appropriate kind and have a label if (this.kinds_.indexOf(track.kind) > -1) { var item = new TrackMenuItem(this.player_, { track: track, kinds: this.kinds_, kind: this.kind_, // MenuItem is selectable selectable: true, // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time) multiSelectable: false }); item.addClass("vjs-" + track.kind + "-menu-item"); items.push(item); } } return items; }; return TextTrackButton; }(TrackButton); Component.registerComponent('TextTrackButton', TextTrackButton); /** * The chapter track menu item * * @extends MenuItem */ var ChaptersTrackMenuItem = /*#__PURE__*/ function (_MenuItem) { _inheritsLoose(ChaptersTrackMenuItem, _MenuItem); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function ChaptersTrackMenuItem(player, options) { var _this; var track = options.track; var cue = options.cue; var currentTime = player.currentTime(); // Modify options for parent MenuItem class's init. options.selectable = true; options.multiSelectable = false; options.label = cue.text; options.selected = cue.startTime <= currentTime && currentTime < cue.endTime; _this = _MenuItem.call(this, player, options) || this; _this.track = track; _this.cue = cue; track.addEventListener('cuechange', bind(_assertThisInitialized(_this), _this.update)); return _this; } /** * This gets called when an `ChaptersTrackMenuItem` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ var _proto = ChaptersTrackMenuItem.prototype; _proto.handleClick = function handleClick(event) { _MenuItem.prototype.handleClick.call(this); this.player_.currentTime(this.cue.startTime); this.update(this.cue.startTime); } /** * Update chapter menu item * * @param {EventTarget~Event} [event] * The `cuechange` event that caused this function to run. * * @listens TextTrack#cuechange */ ; _proto.update = function update(event) { var cue = this.cue; var currentTime = this.player_.currentTime(); // vjs.log(currentTime, cue.startTime); this.selected(cue.startTime <= currentTime && currentTime < cue.endTime); }; return ChaptersTrackMenuItem; }(MenuItem); Component.registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem); /** * The button component for toggling and selecting chapters * Chapters act much differently than other text tracks * Cues are navigation vs. other tracks of alternative languages * * @extends TextTrackButton */ var ChaptersButton = /*#__PURE__*/ function (_TextTrackButton) { _inheritsLoose(ChaptersButton, _TextTrackButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} [ready] * The function to call when this function is ready. */ function ChaptersButton(player, options, ready) { return _TextTrackButton.call(this, player, options, ready) || this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ var _proto = ChaptersButton.prototype; _proto.buildCSSClass = function buildCSSClass() { return "vjs-chapters-button " + _TextTrackButton.prototype.buildCSSClass.call(this); }; _proto.buildWrapperCSSClass = function buildWrapperCSSClass() { return "vjs-chapters-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this); } /** * Update the menu based on the current state of its items. * * @param {EventTarget~Event} [event] * An event that triggered this function to run. * * @listens TextTrackList#addtrack * @listens TextTrackList#removetrack * @listens TextTrackList#change */ ; _proto.update = function update(event) { if (!this.track_ || event && (event.type === 'addtrack' || event.type === 'removetrack')) { this.setTrack(this.findChaptersTrack()); } _TextTrackButton.prototype.update.call(this); } /** * Set the currently selected track for the chapters button. * * @param {TextTrack} track * The new track to select. Nothing will change if this is the currently selected * track. */ ; _proto.setTrack = function setTrack(track) { if (this.track_ === track) { return; } if (!this.updateHandler_) { this.updateHandler_ = this.update.bind(this); } // here this.track_ refers to the old track instance if (this.track_) { var remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_); if (remoteTextTrackEl) { remoteTextTrackEl.removeEventListener('load', this.updateHandler_); } this.track_ = null; } this.track_ = track; // here this.track_ refers to the new track instance if (this.track_) { this.track_.mode = 'hidden'; var _remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_); if (_remoteTextTrackEl) { _remoteTextTrackEl.addEventListener('load', this.updateHandler_); } } } /** * Find the track object that is currently in use by this ChaptersButton * * @return {TextTrack|undefined} * The current track or undefined if none was found. */ ; _proto.findChaptersTrack = function findChaptersTrack() { var tracks = this.player_.textTracks() || []; for (var i = tracks.length - 1; i >= 0; i--) { // We will always choose the last track as our chaptersTrack var track = tracks[i]; if (track.kind === this.kind_) { return track; } } } /** * Get the caption for the ChaptersButton based on the track label. This will also * use the current tracks localized kind as a fallback if a label does not exist. * * @return {string} * The tracks current label or the localized track kind. */ ; _proto.getMenuCaption = function getMenuCaption() { if (this.track_ && this.track_.label) { return this.track_.label; } return this.localize(toTitleCase(this.kind_)); } /** * Create menu from chapter track * * @return {Menu} * New menu for the chapter buttons */ ; _proto.createMenu = function createMenu() { this.options_.title = this.getMenuCaption(); return _TextTrackButton.prototype.createMenu.call(this); } /** * Create a menu item for each text track * * @return {TextTrackMenuItem[]} * Array of menu items */ ; _proto.createItems = function createItems() { var items = []; if (!this.track_) { return items; } var cues = this.track_.cues; if (!cues) { return items; } for (var i = 0, l = cues.length; i < l; i++) { var cue = cues[i]; var mi = new ChaptersTrackMenuItem(this.player_, { track: this.track_, cue: cue }); items.push(mi); } return items; }; return ChaptersButton; }(TextTrackButton); /** * `kind` of TextTrack to look for to associate it with this menu. * * @type {string} * @private */ ChaptersButton.prototype.kind_ = 'chapters'; /** * The text that should display over the `ChaptersButton`s controls. Added for localization. * * @type {string} * @private */ ChaptersButton.prototype.controlText_ = 'Chapters'; Component.registerComponent('ChaptersButton', ChaptersButton); /** * The button component for toggling and selecting descriptions * * @extends TextTrackButton */ var DescriptionsButton = /*#__PURE__*/ function (_TextTrackButton) { _inheritsLoose(DescriptionsButton, _TextTrackButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} [ready] * The function to call when this component is ready. */ function DescriptionsButton(player, options, ready) { var _this; _this = _TextTrackButton.call(this, player, options, ready) || this; var tracks = player.textTracks(); var changeHandler = bind(_assertThisInitialized(_this), _this.handleTracksChange); tracks.addEventListener('change', changeHandler); _this.on('dispose', function () { tracks.removeEventListener('change', changeHandler); }); return _this; } /** * Handle text track change * * @param {EventTarget~Event} event * The event that caused this function to run * * @listens TextTrackList#change */ var _proto = DescriptionsButton.prototype; _proto.handleTracksChange = function handleTracksChange(event) { var tracks = this.player().textTracks(); var disabled = false; // Check whether a track of a different kind is showing for (var i = 0, l = tracks.length; i < l; i++) { var track = tracks[i]; if (track.kind !== this.kind_ && track.mode === 'showing') { disabled = true; break; } } // If another track is showing, disable this menu button if (disabled) { this.disable(); } else { this.enable(); } } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ ; _proto.buildCSSClass = function buildCSSClass() { return "vjs-descriptions-button " + _TextTrackButton.prototype.buildCSSClass.call(this); }; _proto.buildWrapperCSSClass = function buildWrapperCSSClass() { return "vjs-descriptions-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this); }; return DescriptionsButton; }(TextTrackButton); /** * `kind` of TextTrack to look for to associate it with this menu. * * @type {string} * @private */ DescriptionsButton.prototype.kind_ = 'descriptions'; /** * The text that should display over the `DescriptionsButton`s controls. Added for localization. * * @type {string} * @private */ DescriptionsButton.prototype.controlText_ = 'Descriptions'; Component.registerComponent('DescriptionsButton', DescriptionsButton); /** * The button component for toggling and selecting subtitles * * @extends TextTrackButton */ var SubtitlesButton = /*#__PURE__*/ function (_TextTrackButton) { _inheritsLoose(SubtitlesButton, _TextTrackButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} [ready] * The function to call when this component is ready. */ function SubtitlesButton(player, options, ready) { return _TextTrackButton.call(this, player, options, ready) || this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ var _proto = SubtitlesButton.prototype; _proto.buildCSSClass = function buildCSSClass() { return "vjs-subtitles-button " + _TextTrackButton.prototype.buildCSSClass.call(this); }; _proto.buildWrapperCSSClass = function buildWrapperCSSClass() { return "vjs-subtitles-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this); }; return SubtitlesButton; }(TextTrackButton); /** * `kind` of TextTrack to look for to associate it with this menu. * * @type {string} * @private */ SubtitlesButton.prototype.kind_ = 'subtitles'; /** * The text that should display over the `SubtitlesButton`s controls. Added for localization. * * @type {string} * @private */ SubtitlesButton.prototype.controlText_ = 'Subtitles'; Component.registerComponent('SubtitlesButton', SubtitlesButton); /** * The menu item for caption track settings menu * * @extends TextTrackMenuItem */ var CaptionSettingsMenuItem = /*#__PURE__*/ function (_TextTrackMenuItem) { _inheritsLoose(CaptionSettingsMenuItem, _TextTrackMenuItem); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function CaptionSettingsMenuItem(player, options) { var _this; options.track = { player: player, kind: options.kind, label: options.kind + ' settings', selectable: false, "default": false, mode: 'disabled' }; // CaptionSettingsMenuItem has no concept of 'selected' options.selectable = false; options.name = 'CaptionSettingsMenuItem'; _this = _TextTrackMenuItem.call(this, player, options) || this; _this.addClass('vjs-texttrack-settings'); _this.controlText(', opens ' + options.kind + ' settings dialog'); return _this; } /** * This gets called when an `CaptionSettingsMenuItem` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ var _proto = CaptionSettingsMenuItem.prototype; _proto.handleClick = function handleClick(event) { this.player().getChild('textTrackSettings').open(); }; return CaptionSettingsMenuItem; }(TextTrackMenuItem); Component.registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem); /** * The button component for toggling and selecting captions * * @extends TextTrackButton */ var CaptionsButton = /*#__PURE__*/ function (_TextTrackButton) { _inheritsLoose(CaptionsButton, _TextTrackButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} [ready] * The function to call when this component is ready. */ function CaptionsButton(player, options, ready) { return _TextTrackButton.call(this, player, options, ready) || this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ var _proto = CaptionsButton.prototype; _proto.buildCSSClass = function buildCSSClass() { return "vjs-captions-button " + _TextTrackButton.prototype.buildCSSClass.call(this); }; _proto.buildWrapperCSSClass = function buildWrapperCSSClass() { return "vjs-captions-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this); } /** * Create caption menu items * * @return {CaptionSettingsMenuItem[]} * The array of current menu items. */ ; _proto.createItems = function createItems() { var items = []; if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) { items.push(new CaptionSettingsMenuItem(this.player_, { kind: this.kind_ })); this.hideThreshold_ += 1; } return _TextTrackButton.prototype.createItems.call(this, items); }; return CaptionsButton; }(TextTrackButton); /** * `kind` of TextTrack to look for to associate it with this menu. * * @type {string} * @private */ CaptionsButton.prototype.kind_ = 'captions'; /** * The text that should display over the `CaptionsButton`s controls. Added for localization. * * @type {string} * @private */ CaptionsButton.prototype.controlText_ = 'Captions'; Component.registerComponent('CaptionsButton', CaptionsButton); /** * SubsCapsMenuItem has an [cc] icon to distinguish captions from subtitles * in the SubsCapsMenu. * * @extends TextTrackMenuItem */ var SubsCapsMenuItem = /*#__PURE__*/ function (_TextTrackMenuItem) { _inheritsLoose(SubsCapsMenuItem, _TextTrackMenuItem); function SubsCapsMenuItem() { return _TextTrackMenuItem.apply(this, arguments) || this; } var _proto = SubsCapsMenuItem.prototype; _proto.createEl = function createEl(type, props, attrs) { var innerHTML = "<span class=\"vjs-menu-item-text\">" + this.localize(this.options_.label); if (this.options_.track.kind === 'captions') { innerHTML += "\n <span aria-hidden=\"true\" class=\"vjs-icon-placeholder\"></span>\n <span class=\"vjs-control-text\"> " + this.localize('Captions') + "</span>\n "; } innerHTML += '</span>'; var el = _TextTrackMenuItem.prototype.createEl.call(this, type, assign({ innerHTML: innerHTML }, props), attrs); return el; }; return SubsCapsMenuItem; }(TextTrackMenuItem); Component.registerComponent('SubsCapsMenuItem', SubsCapsMenuItem); /** * The button component for toggling and selecting captions and/or subtitles * * @extends TextTrackButton */ var SubsCapsButton = /*#__PURE__*/ function (_TextTrackButton) { _inheritsLoose(SubsCapsButton, _TextTrackButton); function SubsCapsButton(player, options) { var _this; if (options === void 0) { options = {}; } _this = _TextTrackButton.call(this, player, options) || this; // Although North America uses "captions" in most cases for // "captions and subtitles" other locales use "subtitles" _this.label_ = 'subtitles'; if (['en', 'en-us', 'en-ca', 'fr-ca'].indexOf(_this.player_.language_) > -1) { _this.label_ = 'captions'; } _this.menuButton_.controlText(toTitleCase(_this.label_)); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ var _proto = SubsCapsButton.prototype; _proto.buildCSSClass = function buildCSSClass() { return "vjs-subs-caps-button " + _TextTrackButton.prototype.buildCSSClass.call(this); }; _proto.buildWrapperCSSClass = function buildWrapperCSSClass() { return "vjs-subs-caps-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this); } /** * Create caption/subtitles menu items * * @return {CaptionSettingsMenuItem[]} * The array of current menu items. */ ; _proto.createItems = function createItems() { var items = []; if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) { items.push(new CaptionSettingsMenuItem(this.player_, { kind: this.label_ })); this.hideThreshold_ += 1; } items = _TextTrackButton.prototype.createItems.call(this, items, SubsCapsMenuItem); return items; }; return SubsCapsButton; }(TextTrackButton); /** * `kind`s of TextTrack to look for to associate it with this menu. * * @type {array} * @private */ SubsCapsButton.prototype.kinds_ = ['captions', 'subtitles']; /** * The text that should display over the `SubsCapsButton`s controls. * * * @type {string} * @private */ SubsCapsButton.prototype.controlText_ = 'Subtitles'; Component.registerComponent('SubsCapsButton', SubsCapsButton); /** * An {@link AudioTrack} {@link MenuItem} * * @extends MenuItem */ var AudioTrackMenuItem = /*#__PURE__*/ function (_MenuItem) { _inheritsLoose(AudioTrackMenuItem, _MenuItem); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function AudioTrackMenuItem(player, options) { var _this; var track = options.track; var tracks = player.audioTracks(); // Modify options for parent MenuItem class's init. options.label = track.label || track.language || 'Unknown'; options.selected = track.enabled; _this = _MenuItem.call(this, player, options) || this; _this.track = track; _this.addClass("vjs-" + track.kind + "-menu-item"); var changeHandler = function changeHandler() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this.handleTracksChange.apply(_assertThisInitialized(_this), args); }; tracks.addEventListener('change', changeHandler); _this.on('dispose', function () { tracks.removeEventListener('change', changeHandler); }); return _this; } var _proto = AudioTrackMenuItem.prototype; _proto.createEl = function createEl(type, props, attrs) { var innerHTML = "<span class=\"vjs-menu-item-text\">" + this.localize(this.options_.label); if (this.options_.track.kind === 'main-desc') { innerHTML += "\n <span aria-hidden=\"true\" class=\"vjs-icon-placeholder\"></span>\n <span class=\"vjs-control-text\"> " + this.localize('Descriptions') + "</span>\n "; } innerHTML += '</span>'; var el = _MenuItem.prototype.createEl.call(this, type, assign({ innerHTML: innerHTML }, props), attrs); return el; } /** * This gets called when an `AudioTrackMenuItem is "clicked". See {@link ClickableComponent} * for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ ; _proto.handleClick = function handleClick(event) { var tracks = this.player_.audioTracks(); _MenuItem.prototype.handleClick.call(this, event); for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; track.enabled = track === this.track; } } /** * Handle any {@link AudioTrack} change. * * @param {EventTarget~Event} [event] * The {@link AudioTrackList#change} event that caused this to run. * * @listens AudioTrackList#change */ ; _proto.handleTracksChange = function handleTracksChange(event) { this.selected(this.track.enabled); }; return AudioTrackMenuItem; }(MenuItem); Component.registerComponent('AudioTrackMenuItem', AudioTrackMenuItem); /** * The base class for buttons that toggle specific {@link AudioTrack} types. * * @extends TrackButton */ var AudioTrackButton = /*#__PURE__*/ function (_TrackButton) { _inheritsLoose(AudioTrackButton, _TrackButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options={}] * The key/value store of player options. */ function AudioTrackButton(player, options) { if (options === void 0) { options = {}; } options.tracks = player.audioTracks(); return _TrackButton.call(this, player, options) || this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ var _proto = AudioTrackButton.prototype; _proto.buildCSSClass = function buildCSSClass() { return "vjs-audio-button " + _TrackButton.prototype.buildCSSClass.call(this); }; _proto.buildWrapperCSSClass = function buildWrapperCSSClass() { return "vjs-audio-button " + _TrackButton.prototype.buildWrapperCSSClass.call(this); } /** * Create a menu item for each audio track * * @param {AudioTrackMenuItem[]} [items=[]] * An array of existing menu items to use. * * @return {AudioTrackMenuItem[]} * An array of menu items */ ; _proto.createItems = function createItems(items) { if (items === void 0) { items = []; } // if there's only one audio track, there no point in showing it this.hideThreshold_ = 1; var tracks = this.player_.audioTracks(); for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; items.push(new AudioTrackMenuItem(this.player_, { track: track, // MenuItem is selectable selectable: true, // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time) multiSelectable: false })); } return items; }; return AudioTrackButton; }(TrackButton); /** * The text that should display over the `AudioTrackButton`s controls. Added for localization. * * @type {string} * @private */ AudioTrackButton.prototype.controlText_ = 'Audio Track'; Component.registerComponent('AudioTrackButton', AudioTrackButton); /** * The specific menu item type for selecting a playback rate. * * @extends MenuItem */ var PlaybackRateMenuItem = /*#__PURE__*/ function (_MenuItem) { _inheritsLoose(PlaybackRateMenuItem, _MenuItem); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function PlaybackRateMenuItem(player, options) { var _this; var label = options.rate; var rate = parseFloat(label, 10); // Modify options for parent MenuItem class's init. options.label = label; options.selected = rate === 1; options.selectable = true; options.multiSelectable = false; _this = _MenuItem.call(this, player, options) || this; _this.label = label; _this.rate = rate; _this.on(player, 'ratechange', _this.update); return _this; } /** * This gets called when an `PlaybackRateMenuItem` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ var _proto = PlaybackRateMenuItem.prototype; _proto.handleClick = function handleClick(event) { _MenuItem.prototype.handleClick.call(this); this.player().playbackRate(this.rate); } /** * Update the PlaybackRateMenuItem when the playbackrate changes. * * @param {EventTarget~Event} [event] * The `ratechange` event that caused this function to run. * * @listens Player#ratechange */ ; _proto.update = function update(event) { this.selected(this.player().playbackRate() === this.rate); }; return PlaybackRateMenuItem; }(MenuItem); /** * The text that should display over the `PlaybackRateMenuItem`s controls. Added for localization. * * @type {string} * @private */ PlaybackRateMenuItem.prototype.contentElType = 'button'; Component.registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem); /** * The component for controlling the playback rate. * * @extends MenuButton */ var PlaybackRateMenuButton = /*#__PURE__*/ function (_MenuButton) { _inheritsLoose(PlaybackRateMenuButton, _MenuButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function PlaybackRateMenuButton(player, options) { var _this; _this = _MenuButton.call(this, player, options) || this; _this.updateVisibility(); _this.updateLabel(); _this.on(player, 'loadstart', _this.updateVisibility); _this.on(player, 'ratechange', _this.updateLabel); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ var _proto = PlaybackRateMenuButton.prototype; _proto.createEl = function createEl$1() { var el = _MenuButton.prototype.createEl.call(this); this.labelEl_ = createEl('div', { className: 'vjs-playback-rate-value', innerHTML: '1x' }); el.appendChild(this.labelEl_); return el; }; _proto.dispose = function dispose() { this.labelEl_ = null; _MenuButton.prototype.dispose.call(this); } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ ; _proto.buildCSSClass = function buildCSSClass() { return "vjs-playback-rate " + _MenuButton.prototype.buildCSSClass.call(this); }; _proto.buildWrapperCSSClass = function buildWrapperCSSClass() { return "vjs-playback-rate " + _MenuButton.prototype.buildWrapperCSSClass.call(this); } /** * Create the playback rate menu * * @return {Menu} * Menu object populated with {@link PlaybackRateMenuItem}s */ ; _proto.createMenu = function createMenu() { var menu = new Menu(this.player()); var rates = this.playbackRates(); if (rates) { for (var i = rates.length - 1; i >= 0; i--) { menu.addChild(new PlaybackRateMenuItem(this.player(), { rate: rates[i] + 'x' })); } } return menu; } /** * Updates ARIA accessibility attributes */ ; _proto.updateARIAAttributes = function updateARIAAttributes() { // Current playback rate this.el().setAttribute('aria-valuenow', this.player().playbackRate()); } /** * This gets called when an `PlaybackRateMenuButton` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ ; _proto.handleClick = function handleClick(event) { // select next rate option var currentRate = this.player().playbackRate(); var rates = this.playbackRates(); // this will select first one if the last one currently selected var newRate = rates[0]; for (var i = 0; i < rates.length; i++) { if (rates[i] > currentRate) { newRate = rates[i]; break; } } this.player().playbackRate(newRate); } /** * Get possible playback rates * * @return {Array} * All possible playback rates */ ; _proto.playbackRates = function playbackRates() { return this.options_.playbackRates || this.options_.playerOptions && this.options_.playerOptions.playbackRates; } /** * Get whether playback rates is supported by the tech * and an array of playback rates exists * * @return {boolean} * Whether changing playback rate is supported */ ; _proto.playbackRateSupported = function playbackRateSupported() { return this.player().tech_ && this.player().tech_.featuresPlaybackRate && this.playbackRates() && this.playbackRates().length > 0; } /** * Hide playback rate controls when they're no playback rate options to select * * @param {EventTarget~Event} [event] * The event that caused this function to run. * * @listens Player#loadstart */ ; _proto.updateVisibility = function updateVisibility(event) { if (this.playbackRateSupported()) { this.removeClass('vjs-hidden'); } else { this.addClass('vjs-hidden'); } } /** * Update button label when rate changed * * @param {EventTarget~Event} [event] * The event that caused this function to run. * * @listens Player#ratechange */ ; _proto.updateLabel = function updateLabel(event) { if (this.playbackRateSupported()) { this.labelEl_.innerHTML = this.player().playbackRate() + 'x'; } }; return PlaybackRateMenuButton; }(MenuButton); /** * The text that should display over the `FullscreenToggle`s controls. Added for localization. * * @type {string} * @private */ PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate'; Component.registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton); /** * Just an empty spacer element that can be used as an append point for plugins, etc. * Also can be used to create space between elements when necessary. * * @extends Component */ var Spacer = /*#__PURE__*/ function (_Component) { _inheritsLoose(Spacer, _Component); function Spacer() { return _Component.apply(this, arguments) || this; } var _proto = Spacer.prototype; /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ _proto.buildCSSClass = function buildCSSClass() { return "vjs-spacer " + _Component.prototype.buildCSSClass.call(this); } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ ; _proto.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: this.buildCSSClass() }); }; return Spacer; }(Component); Component.registerComponent('Spacer', Spacer); /** * Spacer specifically meant to be used as an insertion point for new plugins, etc. * * @extends Spacer */ var CustomControlSpacer = /*#__PURE__*/ function (_Spacer) { _inheritsLoose(CustomControlSpacer, _Spacer); function CustomControlSpacer() { return _Spacer.apply(this, arguments) || this; } var _proto = CustomControlSpacer.prototype; /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ _proto.buildCSSClass = function buildCSSClass() { return "vjs-custom-control-spacer " + _Spacer.prototype.buildCSSClass.call(this); } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ ; _proto.createEl = function createEl() { var el = _Spacer.prototype.createEl.call(this, { className: this.buildCSSClass() }); // No-flex/table-cell mode requires there be some content // in the cell to fill the remaining space of the table. el.innerHTML = "\xA0"; return el; }; return CustomControlSpacer; }(Spacer); Component.registerComponent('CustomControlSpacer', CustomControlSpacer); /** * Container of main controls. * * @extends Component */ var ControlBar = /*#__PURE__*/ function (_Component) { _inheritsLoose(ControlBar, _Component); function ControlBar() { return _Component.apply(this, arguments) || this; } var _proto = ControlBar.prototype; /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ _proto.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-control-bar', dir: 'ltr' }); }; return ControlBar; }(Component); /** * Default options for `ControlBar` * * @type {Object} * @private */ ControlBar.prototype.options_ = { children: ['playToggle', 'volumePanel', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'seekToLive', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'descriptionsButton', 'subsCapsButton', 'audioTrackButton', 'fullscreenToggle'] }; if ('exitPictureInPicture' in document) { ControlBar.prototype.options_.children.splice(ControlBar.prototype.options_.children.length - 1, 0, 'pictureInPictureToggle'); } Component.registerComponent('ControlBar', ControlBar); /** * A display that indicates an error has occurred. This means that the video * is unplayable. * * @extends ModalDialog */ var ErrorDisplay = /*#__PURE__*/ function (_ModalDialog) { _inheritsLoose(ErrorDisplay, _ModalDialog); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function ErrorDisplay(player, options) { var _this; _this = _ModalDialog.call(this, player, options) || this; _this.on(player, 'error', _this.open); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. * * @deprecated Since version 5. */ var _proto = ErrorDisplay.prototype; _proto.buildCSSClass = function buildCSSClass() { return "vjs-error-display " + _ModalDialog.prototype.buildCSSClass.call(this); } /** * Gets the localized error message based on the `Player`s error. * * @return {string} * The `Player`s error message localized or an empty string. */ ; _proto.content = function content() { var error = this.player().error(); return error ? this.localize(error.message) : ''; }; return ErrorDisplay; }(ModalDialog); /** * The default options for an `ErrorDisplay`. * * @private */ ErrorDisplay.prototype.options_ = mergeOptions(ModalDialog.prototype.options_, { pauseOnOpen: false, fillAlways: true, temporary: false, uncloseable: true }); Component.registerComponent('ErrorDisplay', ErrorDisplay); var LOCAL_STORAGE_KEY = 'vjs-text-track-settings'; var COLOR_BLACK = ['#000', 'Black']; var COLOR_BLUE = ['#00F', 'Blue']; var COLOR_CYAN = ['#0FF', 'Cyan']; var COLOR_GREEN = ['#0F0', 'Green']; var COLOR_MAGENTA = ['#F0F', 'Magenta']; var COLOR_RED = ['#F00', 'Red']; var COLOR_WHITE = ['#FFF', 'White']; var COLOR_YELLOW = ['#FF0', 'Yellow']; var OPACITY_OPAQUE = ['1', 'Opaque']; var OPACITY_SEMI = ['0.5', 'Semi-Transparent']; var OPACITY_TRANS = ['0', 'Transparent']; // Configuration for the various <select> elements in the DOM of this component. // // Possible keys include: // // `default`: // The default option index. Only needs to be provided if not zero. // `parser`: // A function which is used to parse the value from the selected option in // a customized way. // `selector`: // The selector used to find the associated <select> element. var selectConfigs = { backgroundColor: { selector: '.vjs-bg-color > select', id: 'captions-background-color-%s', label: 'Color', options: [COLOR_BLACK, COLOR_WHITE, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN] }, backgroundOpacity: { selector: '.vjs-bg-opacity > select', id: 'captions-background-opacity-%s', label: 'Transparency', options: [OPACITY_OPAQUE, OPACITY_SEMI, OPACITY_TRANS] }, color: { selector: '.vjs-fg-color > select', id: 'captions-foreground-color-%s', label: 'Color', options: [COLOR_WHITE, COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN] }, edgeStyle: { selector: '.vjs-edge-style > select', id: '%s', label: 'Text Edge Style', options: [['none', 'None'], ['raised', 'Raised'], ['depressed', 'Depressed'], ['uniform', 'Uniform'], ['dropshadow', 'Dropshadow']] }, fontFamily: { selector: '.vjs-font-family > select', id: 'captions-font-family-%s', label: 'Font Family', options: [['proportionalSansSerif', 'Proportional Sans-Serif'], ['monospaceSansSerif', 'Monospace Sans-Serif'], ['proportionalSerif', 'Proportional Serif'], ['monospaceSerif', 'Monospace Serif'], ['casual', 'Casual'], ['script', 'Script'], ['small-caps', 'Small Caps']] }, fontPercent: { selector: '.vjs-font-percent > select', id: 'captions-font-size-%s', label: 'Font Size', options: [['0.50', '50%'], ['0.75', '75%'], ['1.00', '100%'], ['1.25', '125%'], ['1.50', '150%'], ['1.75', '175%'], ['2.00', '200%'], ['3.00', '300%'], ['4.00', '400%']], "default": 2, parser: function parser(v) { return v === '1.00' ? null : Number(v); } }, textOpacity: { selector: '.vjs-text-opacity > select', id: 'captions-foreground-opacity-%s', label: 'Transparency', options: [OPACITY_OPAQUE, OPACITY_SEMI] }, // Options for this object are defined below. windowColor: { selector: '.vjs-window-color > select', id: 'captions-window-color-%s', label: 'Color' }, // Options for this object are defined below. windowOpacity: { selector: '.vjs-window-opacity > select', id: 'captions-window-opacity-%s', label: 'Transparency', options: [OPACITY_TRANS, OPACITY_SEMI, OPACITY_OPAQUE] } }; selectConfigs.windowColor.options = selectConfigs.backgroundColor.options; /** * Get the actual value of an option. * * @param {string} value * The value to get * * @param {Function} [parser] * Optional function to adjust the value. * * @return {Mixed} * - Will be `undefined` if no value exists * - Will be `undefined` if the given value is "none". * - Will be the actual value otherwise. * * @private */ function parseOptionValue(value, parser) { if (parser) { value = parser(value); } if (value && value !== 'none') { return value; } } /** * Gets the value of the selected <option> element within a <select> element. * * @param {Element} el * the element to look in * * @param {Function} [parser] * Optional function to adjust the value. * * @return {Mixed} * - Will be `undefined` if no value exists * - Will be `undefined` if the given value is "none". * - Will be the actual value otherwise. * * @private */ function getSelectedOptionValue(el, parser) { var value = el.options[el.options.selectedIndex].value; return parseOptionValue(value, parser); } /** * Sets the selected <option> element within a <select> element based on a * given value. * * @param {Element} el * The element to look in. * * @param {string} value * the property to look on. * * @param {Function} [parser] * Optional function to adjust the value before comparing. * * @private */ function setSelectedOption(el, value, parser) { if (!value) { return; } for (var i = 0; i < el.options.length; i++) { if (parseOptionValue(el.options[i].value, parser) === value) { el.selectedIndex = i; break; } } } /** * Manipulate Text Tracks settings. * * @extends ModalDialog */ var TextTrackSettings = /*#__PURE__*/ function (_ModalDialog) { _inheritsLoose(TextTrackSettings, _ModalDialog); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function TextTrackSettings(player, options) { var _this; options.temporary = false; _this = _ModalDialog.call(this, player, options) || this; _this.updateDisplay = bind(_assertThisInitialized(_this), _this.updateDisplay); // fill the modal and pretend we have opened it _this.fill(); _this.hasBeenOpened_ = _this.hasBeenFilled_ = true; _this.endDialog = createEl('p', { className: 'vjs-control-text', textContent: _this.localize('End of dialog window.') }); _this.el().appendChild(_this.endDialog); _this.setDefaults(); // Grab `persistTextTrackSettings` from the player options if not passed in child options if (options.persistTextTrackSettings === undefined) { _this.options_.persistTextTrackSettings = _this.options_.playerOptions.persistTextTrackSettings; } _this.on(_this.$('.vjs-done-button'), 'click', function () { _this.saveSettings(); _this.close(); }); _this.on(_this.$('.vjs-default-button'), 'click', function () { _this.setDefaults(); _this.updateDisplay(); }); each(selectConfigs, function (config) { _this.on(_this.$(config.selector), 'change', _this.updateDisplay); }); if (_this.options_.persistTextTrackSettings) { _this.restoreSettings(); } return _this; } var _proto = TextTrackSettings.prototype; _proto.dispose = function dispose() { this.endDialog = null; _ModalDialog.prototype.dispose.call(this); } /** * Create a <select> element with configured options. * * @param {string} key * Configuration key to use during creation. * * @return {string} * An HTML string. * * @private */ ; _proto.createElSelect_ = function createElSelect_(key, legendId, type) { var _this2 = this; if (legendId === void 0) { legendId = ''; } if (type === void 0) { type = 'label'; } var config = selectConfigs[key]; var id = config.id.replace('%s', this.id_); var selectLabelledbyIds = [legendId, id].join(' ').trim(); return ["<" + type + " id=\"" + id + "\" class=\"" + (type === 'label' ? 'vjs-label' : '') + "\">", this.localize(config.label), "</" + type + ">", "<select aria-labelledby=\"" + selectLabelledbyIds + "\">"].concat(config.options.map(function (o) { var optionId = id + '-' + o[1].replace(/\W+/g, ''); return ["<option id=\"" + optionId + "\" value=\"" + o[0] + "\" ", "aria-labelledby=\"" + selectLabelledbyIds + " " + optionId + "\">", _this2.localize(o[1]), '</option>'].join(''); })).concat('</select>').join(''); } /** * Create foreground color element for the component * * @return {string} * An HTML string. * * @private */ ; _proto.createElFgColor_ = function createElFgColor_() { var legendId = "captions-text-legend-" + this.id_; return ['<fieldset class="vjs-fg-color vjs-track-setting">', "<legend id=\"" + legendId + "\">", this.localize('Text'), '</legend>', this.createElSelect_('color', legendId), '<span class="vjs-text-opacity vjs-opacity">', this.createElSelect_('textOpacity', legendId), '</span>', '</fieldset>'].join(''); } /** * Create background color element for the component * * @return {string} * An HTML string. * * @private */ ; _proto.createElBgColor_ = function createElBgColor_() { var legendId = "captions-background-" + this.id_; return ['<fieldset class="vjs-bg-color vjs-track-setting">', "<legend id=\"" + legendId + "\">", this.localize('Background'), '</legend>', this.createElSelect_('backgroundColor', legendId), '<span class="vjs-bg-opacity vjs-opacity">', this.createElSelect_('backgroundOpacity', legendId), '</span>', '</fieldset>'].join(''); } /** * Create window color element for the component * * @return {string} * An HTML string. * * @private */ ; _proto.createElWinColor_ = function createElWinColor_() { var legendId = "captions-window-" + this.id_; return ['<fieldset class="vjs-window-color vjs-track-setting">', "<legend id=\"" + legendId + "\">", this.localize('Window'), '</legend>', this.createElSelect_('windowColor', legendId), '<span class="vjs-window-opacity vjs-opacity">', this.createElSelect_('windowOpacity', legendId), '</span>', '</fieldset>'].join(''); } /** * Create color elements for the component * * @return {Element} * The element that was created * * @private */ ; _proto.createElColors_ = function createElColors_() { return createEl('div', { className: 'vjs-track-settings-colors', innerHTML: [this.createElFgColor_(), this.createElBgColor_(), this.createElWinColor_()].join('') }); } /** * Create font elements for the component * * @return {Element} * The element that was created. * * @private */ ; _proto.createElFont_ = function createElFont_() { return createEl('div', { className: 'vjs-track-settings-font', innerHTML: ['<fieldset class="vjs-font-percent vjs-track-setting">', this.createElSelect_('fontPercent', '', 'legend'), '</fieldset>', '<fieldset class="vjs-edge-style vjs-track-setting">', this.createElSelect_('edgeStyle', '', 'legend'), '</fieldset>', '<fieldset class="vjs-font-family vjs-track-setting">', this.createElSelect_('fontFamily', '', 'legend'), '</fieldset>'].join('') }); } /** * Create controls for the component * * @return {Element} * The element that was created. * * @private */ ; _proto.createElControls_ = function createElControls_() { var defaultsDescription = this.localize('restore all settings to the default values'); return createEl('div', { className: 'vjs-track-settings-controls', innerHTML: ["<button type=\"button\" class=\"vjs-default-button\" title=\"" + defaultsDescription + "\">", this.localize('Reset'), "<span class=\"vjs-control-text\"> " + defaultsDescription + "</span>", '</button>', "<button type=\"button\" class=\"vjs-done-button\">" + this.localize('Done') + "</button>"].join('') }); }; _proto.content = function content() { return [this.createElColors_(), this.createElFont_(), this.createElControls_()]; }; _proto.label = function label() { return this.localize('Caption Settings Dialog'); }; _proto.description = function description() { return this.localize('Beginning of dialog window. Escape will cancel and close the window.'); }; _proto.buildCSSClass = function buildCSSClass() { return _ModalDialog.prototype.buildCSSClass.call(this) + ' vjs-text-track-settings'; } /** * Gets an object of text track settings (or null). * * @return {Object} * An object with config values parsed from the DOM or localStorage. */ ; _proto.getValues = function getValues() { var _this3 = this; return reduce(selectConfigs, function (accum, config, key) { var value = getSelectedOptionValue(_this3.$(config.selector), config.parser); if (value !== undefined) { accum[key] = value; } return accum; }, {}); } /** * Sets text track settings from an object of values. * * @param {Object} values * An object with config values parsed from the DOM or localStorage. */ ; _proto.setValues = function setValues(values) { var _this4 = this; each(selectConfigs, function (config, key) { setSelectedOption(_this4.$(config.selector), values[key], config.parser); }); } /** * Sets all `<select>` elements to their default values. */ ; _proto.setDefaults = function setDefaults() { var _this5 = this; each(selectConfigs, function (config) { var index = config.hasOwnProperty('default') ? config["default"] : 0; _this5.$(config.selector).selectedIndex = index; }); } /** * Restore texttrack settings from localStorage */ ; _proto.restoreSettings = function restoreSettings() { var values; try { values = JSON.parse(window$1.localStorage.getItem(LOCAL_STORAGE_KEY)); } catch (err) { log.warn(err); } if (values) { this.setValues(values); } } /** * Save text track settings to localStorage */ ; _proto.saveSettings = function saveSettings() { if (!this.options_.persistTextTrackSettings) { return; } var values = this.getValues(); try { if (Object.keys(values).length) { window$1.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(values)); } else { window$1.localStorage.removeItem(LOCAL_STORAGE_KEY); } } catch (err) { log.warn(err); } } /** * Update display of text track settings */ ; _proto.updateDisplay = function updateDisplay() { var ttDisplay = this.player_.getChild('textTrackDisplay'); if (ttDisplay) { ttDisplay.updateDisplay(); } } /** * conditionally blur the element and refocus the captions button * * @private */ ; _proto.conditionalBlur_ = function conditionalBlur_() { this.previouslyActiveEl_ = null; var cb = this.player_.controlBar; var subsCapsBtn = cb && cb.subsCapsButton; var ccBtn = cb && cb.captionsButton; if (subsCapsBtn) { subsCapsBtn.focus(); } else if (ccBtn) { ccBtn.focus(); } }; return TextTrackSettings; }(ModalDialog); Component.registerComponent('TextTrackSettings', TextTrackSettings); /** * A Resize Manager. It is in charge of triggering `playerresize` on the player in the right conditions. * * It'll either create an iframe and use a debounced resize handler on it or use the new {@link https://wicg.github.io/ResizeObserver/|ResizeObserver}. * * If the ResizeObserver is available natively, it will be used. A polyfill can be passed in as an option. * If a `playerresize` event is not needed, the ResizeManager component can be removed from the player, see the example below. * @example <caption>How to disable the resize manager</caption> * const player = videojs('#vid', { * resizeManager: false * }); * * @see {@link https://wicg.github.io/ResizeObserver/|ResizeObserver specification} * * @extends Component */ var ResizeManager = /*#__PURE__*/ function (_Component) { _inheritsLoose(ResizeManager, _Component); /** * Create the ResizeManager. * * @param {Object} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of ResizeManager options. * * @param {Object} [options.ResizeObserver] * A polyfill for ResizeObserver can be passed in here. * If this is set to null it will ignore the native ResizeObserver and fall back to the iframe fallback. */ function ResizeManager(player, options) { var _this; var RESIZE_OBSERVER_AVAILABLE = options.ResizeObserver || window$1.ResizeObserver; // if `null` was passed, we want to disable the ResizeObserver if (options.ResizeObserver === null) { RESIZE_OBSERVER_AVAILABLE = false; } // Only create an element when ResizeObserver isn't available var options_ = mergeOptions({ createEl: !RESIZE_OBSERVER_AVAILABLE, reportTouchActivity: false }, options); _this = _Component.call(this, player, options_) || this; _this.ResizeObserver = options.ResizeObserver || window$1.ResizeObserver; _this.loadListener_ = null; _this.resizeObserver_ = null; _this.debouncedHandler_ = debounce(function () { _this.resizeHandler(); }, 100, false, _assertThisInitialized(_this)); if (RESIZE_OBSERVER_AVAILABLE) { _this.resizeObserver_ = new _this.ResizeObserver(_this.debouncedHandler_); _this.resizeObserver_.observe(player.el()); } else { _this.loadListener_ = function () { if (!_this.el_ || !_this.el_.contentWindow) { return; } var debouncedHandler_ = _this.debouncedHandler_; var unloadListener_ = _this.unloadListener_ = function () { off(this, 'resize', debouncedHandler_); off(this, 'unload', unloadListener_); unloadListener_ = null; }; // safari and edge can unload the iframe before resizemanager dispose // we have to dispose of event handlers correctly before that happens on(_this.el_.contentWindow, 'unload', unloadListener_); on(_this.el_.contentWindow, 'resize', debouncedHandler_); }; _this.one('load', _this.loadListener_); } return _this; } var _proto = ResizeManager.prototype; _proto.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'iframe', { className: 'vjs-resize-manager', tabIndex: -1 }, { 'aria-hidden': 'true' }); } /** * Called when a resize is triggered on the iframe or a resize is observed via the ResizeObserver * * @fires Player#playerresize */ ; _proto.resizeHandler = function resizeHandler() { /** * Called when the player size has changed * * @event Player#playerresize * @type {EventTarget~Event} */ // make sure player is still around to trigger // prevents this from causing an error after dispose if (!this.player_ || !this.player_.trigger) { return; } this.player_.trigger('playerresize'); }; _proto.dispose = function dispose() { if (this.debouncedHandler_) { this.debouncedHandler_.cancel(); } if (this.resizeObserver_) { if (this.player_.el()) { this.resizeObserver_.unobserve(this.player_.el()); } this.resizeObserver_.disconnect(); } if (this.loadListener_) { this.off('load', this.loadListener_); } if (this.el_ && this.el_.contentWindow && this.unloadListener_) { this.unloadListener_.call(this.el_.contentWindow); } this.ResizeObserver = null; this.resizeObserver = null; this.debouncedHandler_ = null; this.loadListener_ = null; _Component.prototype.dispose.call(this); }; return ResizeManager; }(Component); Component.registerComponent('ResizeManager', ResizeManager); /** * Computes the median of an array. * * @param {number[]} arr * Input array of numbers. * * @return {number} * Median value. */ var median = function median(arr) { var mid = Math.floor(arr.length / 2); var sortedList = [].concat(arr).sort(function (a, b) { return a - b; }); return arr.length % 2 !== 0 ? sortedList[mid] : (sortedList[mid - 1] + sortedList[mid]) / 2; }; /* track when we are at the live edge, and other helpers for live playback */ var LiveTracker = /*#__PURE__*/ function (_Component) { _inheritsLoose(LiveTracker, _Component); function LiveTracker(player, options) { var _this; // LiveTracker does not need an element var options_ = mergeOptions({ createEl: false }, options); _this = _Component.call(this, player, options_) || this; _this.reset_(); _this.on(_this.player_, 'durationchange', _this.handleDurationchange); // we don't need to track live playback if the document is hidden, // also, tracking when the document is hidden can // cause the CPU to spike and eventually crash the page on IE11. if (IE_VERSION && 'hidden' in document && 'visibilityState' in document) { _this.on(document, 'visibilitychange', _this.handleVisibilityChange); } return _this; } var _proto = LiveTracker.prototype; _proto.handleVisibilityChange = function handleVisibilityChange() { if (this.player_.duration() !== Infinity) { return; } if (document.hidden) { this.stopTracking(); } else { this.startTracking(); } }; _proto.isBehind_ = function isBehind_() { // don't report that we are behind until a timeupdate has been seen if (!this.timeupdateSeen_) { return false; } var liveCurrentTime = this.liveCurrentTime(); var currentTime = this.player_.currentTime(); // the live edge window is the amount of seconds away from live // that a player can be, but still be considered live. // we add 0.07 because the live tracking happens every 30ms // and we want some wiggle room for short segment live playback var liveEdgeWindow = this.seekableIncrement_ * 2 + 0.07; // on Android liveCurrentTime can bee Infinity, because seekableEnd // can be Infinity, so we handle that case. return liveCurrentTime !== Infinity && liveCurrentTime - liveEdgeWindow >= currentTime; } // all the functionality for tracking when seek end changes // and for tracking how far past seek end we should be ; _proto.trackLive_ = function trackLive_() { this.pastSeekEnd_ = this.pastSeekEnd_; var seekable = this.player_.seekable(); // skip undefined seekable if (!seekable || !seekable.length) { return; } var newSeekEnd = this.seekableEnd(); // we can only tell if we are behind live, when seekable changes // once we detect that seekable has changed we check the new seek // end against current time, with a fudge value of half a second. if (newSeekEnd !== this.lastSeekEnd_) { if (this.lastSeekEnd_) { // we try to get the best fit value for the seeking increment // variable from the last 12 values. this.seekableIncrementList_ = this.seekableIncrementList_.slice(-11); this.seekableIncrementList_.push(Math.abs(newSeekEnd - this.lastSeekEnd_)); if (this.seekableIncrementList_.length > 3) { this.seekableIncrement_ = median(this.seekableIncrementList_); } } this.pastSeekEnd_ = 0; this.lastSeekEnd_ = newSeekEnd; this.trigger('seekableendchange'); } this.pastSeekEnd_ = this.pastSeekEnd() + 0.03; if (this.isBehind_() !== this.behindLiveEdge()) { this.behindLiveEdge_ = this.isBehind_(); this.trigger('liveedgechange'); } } /** * handle a durationchange event on the player * and start/stop tracking accordingly. */ ; _proto.handleDurationchange = function handleDurationchange() { if (this.player_.duration() === Infinity) { this.startTracking(); } else { this.stopTracking(); } } /** * start tracking live playback */ ; _proto.startTracking = function startTracking() { var _this2 = this; if (this.isTracking()) { return; } // If we haven't seen a timeupdate, we need to check whether playback // began before this component started tracking. This can happen commonly // when using autoplay. if (!this.timeupdateSeen_) { this.timeupdateSeen_ = this.player_.hasStarted(); } this.trackingInterval_ = this.setInterval(this.trackLive_, 30); this.trackLive_(); this.on(this.player_, 'play', this.trackLive_); this.on(this.player_, 'pause', this.trackLive_); // this is to prevent showing that we are not live // before a video starts to play if (!this.timeupdateSeen_) { this.one(this.player_, 'play', this.handlePlay); this.handleTimeupdate = function () { _this2.timeupdateSeen_ = true; _this2.handleTimeupdate = null; }; this.one(this.player_, 'timeupdate', this.handleTimeupdate); } }; _proto.handlePlay = function handlePlay() { this.one(this.player_, 'timeupdate', this.seekToLiveEdge); } /** * Stop tracking, and set all internal variables to * their initial value. */ ; _proto.reset_ = function reset_() { this.pastSeekEnd_ = 0; this.lastSeekEnd_ = null; this.behindLiveEdge_ = null; this.timeupdateSeen_ = false; this.clearInterval(this.trackingInterval_); this.trackingInterval_ = null; this.seekableIncrement_ = 12; this.seekableIncrementList_ = []; this.off(this.player_, 'play', this.trackLive_); this.off(this.player_, 'pause', this.trackLive_); this.off(this.player_, 'play', this.handlePlay); this.off(this.player_, 'timeupdate', this.seekToLiveEdge); if (this.handleTimeupdate) { this.off(this.player_, 'timeupdate', this.handleTimeupdate); this.handleTimeupdate = null; } } /** * stop tracking live playback */ ; _proto.stopTracking = function stopTracking() { if (!this.isTracking()) { return; } this.reset_(); } /** * A helper to get the player seekable end * so that we don't have to null check everywhere */ ; _proto.seekableEnd = function seekableEnd() { var seekable = this.player_.seekable(); var seekableEnds = []; var i = seekable ? seekable.length : 0; while (i--) { seekableEnds.push(seekable.end(i)); } // grab the furthest seekable end after sorting, or if there are none // default to Infinity return seekableEnds.length ? seekableEnds.sort()[seekableEnds.length - 1] : Infinity; } /** * A helper to get the player seekable start * so that we don't have to null check everywhere */ ; _proto.seekableStart = function seekableStart() { var seekable = this.player_.seekable(); var seekableStarts = []; var i = seekable ? seekable.length : 0; while (i--) { seekableStarts.push(seekable.start(i)); } // grab the first seekable start after sorting, or if there are none // default to 0 return seekableStarts.length ? seekableStarts.sort()[0] : 0; } /** * Get the live time window */ ; _proto.liveWindow = function liveWindow() { var liveCurrentTime = this.liveCurrentTime(); if (liveCurrentTime === Infinity) { return Infinity; } return liveCurrentTime - this.seekableStart(); } /** * Determines if the player is live, only checks if this component * is tracking live playback or not */ ; _proto.isLive = function isLive() { return this.isTracking(); } /** * Determines if currentTime is at the live edge and won't fall behind * on each seekableendchange */ ; _proto.atLiveEdge = function atLiveEdge() { return !this.behindLiveEdge(); } /** * get what we expect the live current time to be */ ; _proto.liveCurrentTime = function liveCurrentTime() { return this.pastSeekEnd() + this.seekableEnd(); } /** * Returns how far past seek end we expect current time to be */ ; _proto.pastSeekEnd = function pastSeekEnd() { return this.pastSeekEnd_; } /** * If we are currently behind the live edge, aka currentTime will be * behind on a seekableendchange */ ; _proto.behindLiveEdge = function behindLiveEdge() { return this.behindLiveEdge_; }; _proto.isTracking = function isTracking() { return typeof this.trackingInterval_ === 'number'; } /** * Seek to the live edge if we are behind the live edge */ ; _proto.seekToLiveEdge = function seekToLiveEdge() { if (this.atLiveEdge()) { return; } this.player_.currentTime(this.liveCurrentTime()); if (this.player_.paused()) { this.player_.play(); } }; _proto.dispose = function dispose() { this.stopTracking(); _Component.prototype.dispose.call(this); }; return LiveTracker; }(Component); Component.registerComponent('LiveTracker', LiveTracker); /** * This function is used to fire a sourceset when there is something * similar to `mediaEl.load()` being called. It will try to find the source via * the `src` attribute and then the `<source>` elements. It will then fire `sourceset` * with the source that was found or empty string if we cannot know. If it cannot * find a source then `sourceset` will not be fired. * * @param {Html5} tech * The tech object that sourceset was setup on * * @return {boolean} * returns false if the sourceset was not fired and true otherwise. */ var sourcesetLoad = function sourcesetLoad(tech) { var el = tech.el(); // if `el.src` is set, that source will be loaded. if (el.hasAttribute('src')) { tech.triggerSourceset(el.src); return true; } /** * Since there isn't a src property on the media element, source elements will be used for * implementing the source selection algorithm. This happens asynchronously and * for most cases were there is more than one source we cannot tell what source will * be loaded, without re-implementing the source selection algorithm. At this time we are not * going to do that. There are three special cases that we do handle here though: * * 1. If there are no sources, do not fire `sourceset`. * 2. If there is only one `<source>` with a `src` property/attribute that is our `src` * 3. If there is more than one `<source>` but all of them have the same `src` url. * That will be our src. */ var sources = tech.$$('source'); var srcUrls = []; var src = ''; // if there are no sources, do not fire sourceset if (!sources.length) { return false; } // only count valid/non-duplicate source elements for (var i = 0; i < sources.length; i++) { var url = sources[i].src; if (url && srcUrls.indexOf(url) === -1) { srcUrls.push(url); } } // there were no valid sources if (!srcUrls.length) { return false; } // there is only one valid source element url // use that if (srcUrls.length === 1) { src = srcUrls[0]; } tech.triggerSourceset(src); return true; }; /** * our implementation of an `innerHTML` descriptor for browsers * that do not have one. */ var innerHTMLDescriptorPolyfill = Object.defineProperty({}, 'innerHTML', { get: function get() { return this.cloneNode(true).innerHTML; }, set: function set(v) { // make a dummy node to use innerHTML on var dummy = document.createElement(this.nodeName.toLowerCase()); // set innerHTML to the value provided dummy.innerHTML = v; // make a document fragment to hold the nodes from dummy var docFrag = document.createDocumentFragment(); // copy all of the nodes created by the innerHTML on dummy // to the document fragment while (dummy.childNodes.length) { docFrag.appendChild(dummy.childNodes[0]); } // remove content this.innerText = ''; // now we add all of that html in one by appending the // document fragment. This is how innerHTML does it. window$1.Element.prototype.appendChild.call(this, docFrag); // then return the result that innerHTML's setter would return this.innerHTML; } }); /** * Get a property descriptor given a list of priorities and the * property to get. */ var getDescriptor = function getDescriptor(priority, prop) { var descriptor = {}; for (var i = 0; i < priority.length; i++) { descriptor = Object.getOwnPropertyDescriptor(priority[i], prop); if (descriptor && descriptor.set && descriptor.get) { break; } } descriptor.enumerable = true; descriptor.configurable = true; return descriptor; }; var getInnerHTMLDescriptor = function getInnerHTMLDescriptor(tech) { return getDescriptor([tech.el(), window$1.HTMLMediaElement.prototype, window$1.Element.prototype, innerHTMLDescriptorPolyfill], 'innerHTML'); }; /** * Patches browser internal functions so that we can tell synchronously * if a `<source>` was appended to the media element. For some reason this * causes a `sourceset` if the the media element is ready and has no source. * This happens when: * - The page has just loaded and the media element does not have a source. * - The media element was emptied of all sources, then `load()` was called. * * It does this by patching the following functions/properties when they are supported: * * - `append()` - can be used to add a `<source>` element to the media element * - `appendChild()` - can be used to add a `<source>` element to the media element * - `insertAdjacentHTML()` - can be used to add a `<source>` element to the media element * - `innerHTML` - can be used to add a `<source>` element to the media element * * @param {Html5} tech * The tech object that sourceset is being setup on. */ var firstSourceWatch = function firstSourceWatch(tech) { var el = tech.el(); // make sure firstSourceWatch isn't setup twice. if (el.resetSourceWatch_) { return; } var old = {}; var innerDescriptor = getInnerHTMLDescriptor(tech); var appendWrapper = function appendWrapper(appendFn) { return function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var retval = appendFn.apply(el, args); sourcesetLoad(tech); return retval; }; }; ['append', 'appendChild', 'insertAdjacentHTML'].forEach(function (k) { if (!el[k]) { return; } // store the old function old[k] = el[k]; // call the old function with a sourceset if a source // was loaded el[k] = appendWrapper(old[k]); }); Object.defineProperty(el, 'innerHTML', mergeOptions(innerDescriptor, { set: appendWrapper(innerDescriptor.set) })); el.resetSourceWatch_ = function () { el.resetSourceWatch_ = null; Object.keys(old).forEach(function (k) { el[k] = old[k]; }); Object.defineProperty(el, 'innerHTML', innerDescriptor); }; // on the first sourceset, we need to revert our changes tech.one('sourceset', el.resetSourceWatch_); }; /** * our implementation of a `src` descriptor for browsers * that do not have one. */ var srcDescriptorPolyfill = Object.defineProperty({}, 'src', { get: function get() { if (this.hasAttribute('src')) { return getAbsoluteURL(window$1.Element.prototype.getAttribute.call(this, 'src')); } return ''; }, set: function set(v) { window$1.Element.prototype.setAttribute.call(this, 'src', v); return v; } }); var getSrcDescriptor = function getSrcDescriptor(tech) { return getDescriptor([tech.el(), window$1.HTMLMediaElement.prototype, srcDescriptorPolyfill], 'src'); }; /** * setup `sourceset` handling on the `Html5` tech. This function * patches the following element properties/functions: * * - `src` - to determine when `src` is set * - `setAttribute()` - to determine when `src` is set * - `load()` - this re-triggers the source selection algorithm, and can * cause a sourceset. * * If there is no source when we are adding `sourceset` support or during a `load()` * we also patch the functions listed in `firstSourceWatch`. * * @param {Html5} tech * The tech to patch */ var setupSourceset = function setupSourceset(tech) { if (!tech.featuresSourceset) { return; } var el = tech.el(); // make sure sourceset isn't setup twice. if (el.resetSourceset_) { return; } var srcDescriptor = getSrcDescriptor(tech); var oldSetAttribute = el.setAttribute; var oldLoad = el.load; Object.defineProperty(el, 'src', mergeOptions(srcDescriptor, { set: function set(v) { var retval = srcDescriptor.set.call(el, v); // we use the getter here to get the actual value set on src tech.triggerSourceset(el.src); return retval; } })); el.setAttribute = function (n, v) { var retval = oldSetAttribute.call(el, n, v); if (/src/i.test(n)) { tech.triggerSourceset(el.src); } return retval; }; el.load = function () { var retval = oldLoad.call(el); // if load was called, but there was no source to fire // sourceset on. We have to watch for a source append // as that can trigger a `sourceset` when the media element // has no source if (!sourcesetLoad(tech)) { tech.triggerSourceset(''); firstSourceWatch(tech); } return retval; }; if (el.currentSrc) { tech.triggerSourceset(el.currentSrc); } else if (!sourcesetLoad(tech)) { firstSourceWatch(tech); } el.resetSourceset_ = function () { el.resetSourceset_ = null; el.load = oldLoad; el.setAttribute = oldSetAttribute; Object.defineProperty(el, 'src', srcDescriptor); if (el.resetSourceWatch_) { el.resetSourceWatch_(); } }; }; /** * HTML5 Media Controller - Wrapper for HTML5 Media API * * @mixes Tech~SourceHandlerAdditions * @extends Tech */ var Html5 = /*#__PURE__*/ function (_Tech) { _inheritsLoose(Html5, _Tech); /** * Create an instance of this Tech. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} ready * Callback function to call when the `HTML5` Tech is ready. */ function Html5(options, ready) { var _this; _this = _Tech.call(this, options, ready) || this; var source = options.source; var crossoriginTracks = false; // Set the source if one is provided // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted) // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source // anyway so the error gets fired. if (source && (_this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) { _this.setSource(source); } else { _this.handleLateInit_(_this.el_); } // setup sourceset after late sourceset/init if (options.enableSourceset) { _this.setupSourcesetHandling_(); } if (_this.el_.hasChildNodes()) { var nodes = _this.el_.childNodes; var nodesLength = nodes.length; var removeNodes = []; while (nodesLength--) { var node = nodes[nodesLength]; var nodeName = node.nodeName.toLowerCase(); if (nodeName === 'track') { if (!_this.featuresNativeTextTracks) { // Empty video tag tracks so the built-in player doesn't use them also. // This may not be fast enough to stop HTML5 browsers from reading the tags // so we'll need to turn off any default tracks if we're manually doing // captions and subtitles. videoElement.textTracks removeNodes.push(node); } else { // store HTMLTrackElement and TextTrack to remote list _this.remoteTextTrackEls().addTrackElement_(node); _this.remoteTextTracks().addTrack(node.track); _this.textTracks().addTrack(node.track); if (!crossoriginTracks && !_this.el_.hasAttribute('crossorigin') && isCrossOrigin(node.src)) { crossoriginTracks = true; } } } } for (var i = 0; i < removeNodes.length; i++) { _this.el_.removeChild(removeNodes[i]); } } _this.proxyNativeTracks_(); if (_this.featuresNativeTextTracks && crossoriginTracks) { log.warn('Text Tracks are being loaded from another origin but the crossorigin attribute isn\'t used.\n' + 'This may prevent text tracks from loading.'); } // prevent iOS Safari from disabling metadata text tracks during native playback _this.restoreMetadataTracksInIOSNativePlayer_(); // Determine if native controls should be used // Our goal should be to get the custom controls on mobile solid everywhere // so we can remove this all together. Right now this will block custom // controls on touch enabled laptops like the Chrome Pixel if ((TOUCH_ENABLED || IS_IPHONE || IS_NATIVE_ANDROID) && options.nativeControlsForTouch === true) { _this.setControls(true); } // on iOS, we want to proxy `webkitbeginfullscreen` and `webkitendfullscreen` // into a `fullscreenchange` event _this.proxyWebkitFullscreen_(); _this.triggerReady(); return _this; } /** * Dispose of `HTML5` media element and remove all tracks. */ var _proto = Html5.prototype; _proto.dispose = function dispose() { if (this.el_ && this.el_.resetSourceset_) { this.el_.resetSourceset_(); } Html5.disposeMediaElement(this.el_); this.options_ = null; // tech will handle clearing of the emulated track list _Tech.prototype.dispose.call(this); } /** * Modify the media element so that we can detect when * the source is changed. Fires `sourceset` just after the source has changed */ ; _proto.setupSourcesetHandling_ = function setupSourcesetHandling_() { setupSourceset(this); } /** * When a captions track is enabled in the iOS Safari native player, all other * tracks are disabled (including metadata tracks), which nulls all of their * associated cue points. This will restore metadata tracks to their pre-fullscreen * state in those cases so that cue points are not needlessly lost. * * @private */ ; _proto.restoreMetadataTracksInIOSNativePlayer_ = function restoreMetadataTracksInIOSNativePlayer_() { var textTracks = this.textTracks(); var metadataTracksPreFullscreenState; // captures a snapshot of every metadata track's current state var takeMetadataTrackSnapshot = function takeMetadataTrackSnapshot() { metadataTracksPreFullscreenState = []; for (var i = 0; i < textTracks.length; i++) { var track = textTracks[i]; if (track.kind === 'metadata') { metadataTracksPreFullscreenState.push({ track: track, storedMode: track.mode }); } } }; // snapshot each metadata track's initial state, and update the snapshot // each time there is a track 'change' event takeMetadataTrackSnapshot(); textTracks.addEventListener('change', takeMetadataTrackSnapshot); this.on('dispose', function () { return textTracks.removeEventListener('change', takeMetadataTrackSnapshot); }); var restoreTrackMode = function restoreTrackMode() { for (var i = 0; i < metadataTracksPreFullscreenState.length; i++) { var storedTrack = metadataTracksPreFullscreenState[i]; if (storedTrack.track.mode === 'disabled' && storedTrack.track.mode !== storedTrack.storedMode) { storedTrack.track.mode = storedTrack.storedMode; } } // we only want this handler to be executed on the first 'change' event textTracks.removeEventListener('change', restoreTrackMode); }; // when we enter fullscreen playback, stop updating the snapshot and // restore all track modes to their pre-fullscreen state this.on('webkitbeginfullscreen', function () { textTracks.removeEventListener('change', takeMetadataTrackSnapshot); // remove the listener before adding it just in case it wasn't previously removed textTracks.removeEventListener('change', restoreTrackMode); textTracks.addEventListener('change', restoreTrackMode); }); // start updating the snapshot again after leaving fullscreen this.on('webkitendfullscreen', function () { // remove the listener before adding it just in case it wasn't previously removed textTracks.removeEventListener('change', takeMetadataTrackSnapshot); textTracks.addEventListener('change', takeMetadataTrackSnapshot); // remove the restoreTrackMode handler in case it wasn't triggered during fullscreen playback textTracks.removeEventListener('change', restoreTrackMode); }); } /** * Attempt to force override of tracks for the given type * * @param {string} type - Track type to override, possible values include 'Audio', * 'Video', and 'Text'. * @param {boolean} override - If set to true native audio/video will be overridden, * otherwise native audio/video will potentially be used. * @private */ ; _proto.overrideNative_ = function overrideNative_(type, override) { var _this2 = this; // If there is no behavioral change don't add/remove listeners if (override !== this["featuresNative" + type + "Tracks"]) { return; } var lowerCaseType = type.toLowerCase(); if (this[lowerCaseType + "TracksListeners_"]) { Object.keys(this[lowerCaseType + "TracksListeners_"]).forEach(function (eventName) { var elTracks = _this2.el()[lowerCaseType + "Tracks"]; elTracks.removeEventListener(eventName, _this2[lowerCaseType + "TracksListeners_"][eventName]); }); } this["featuresNative" + type + "Tracks"] = !override; this[lowerCaseType + "TracksListeners_"] = null; this.proxyNativeTracksForType_(lowerCaseType); } /** * Attempt to force override of native audio tracks. * * @param {boolean} override - If set to true native audio will be overridden, * otherwise native audio will potentially be used. */ ; _proto.overrideNativeAudioTracks = function overrideNativeAudioTracks(override) { this.overrideNative_('Audio', override); } /** * Attempt to force override of native video tracks. * * @param {boolean} override - If set to true native video will be overridden, * otherwise native video will potentially be used. */ ; _proto.overrideNativeVideoTracks = function overrideNativeVideoTracks(override) { this.overrideNative_('Video', override); } /** * Proxy native track list events for the given type to our track * lists if the browser we are playing in supports that type of track list. * * @param {string} name - Track type; values include 'audio', 'video', and 'text' * @private */ ; _proto.proxyNativeTracksForType_ = function proxyNativeTracksForType_(name) { var _this3 = this; var props = NORMAL[name]; var elTracks = this.el()[props.getterName]; var techTracks = this[props.getterName](); if (!this["featuresNative" + props.capitalName + "Tracks"] || !elTracks || !elTracks.addEventListener) { return; } var listeners = { change: function change(e) { techTracks.trigger({ type: 'change', target: techTracks, currentTarget: techTracks, srcElement: techTracks }); }, addtrack: function addtrack(e) { techTracks.addTrack(e.track); }, removetrack: function removetrack(e) { techTracks.removeTrack(e.track); } }; var removeOldTracks = function removeOldTracks() { var removeTracks = []; for (var i = 0; i < techTracks.length; i++) { var found = false; for (var j = 0; j < elTracks.length; j++) { if (elTracks[j] === techTracks[i]) { found = true; break; } } if (!found) { removeTracks.push(techTracks[i]); } } while (removeTracks.length) { techTracks.removeTrack(removeTracks.shift()); } }; this[props.getterName + 'Listeners_'] = listeners; Object.keys(listeners).forEach(function (eventName) { var listener = listeners[eventName]; elTracks.addEventListener(eventName, listener); _this3.on('dispose', function (e) { return elTracks.removeEventListener(eventName, listener); }); }); // Remove (native) tracks that are not used anymore this.on('loadstart', removeOldTracks); this.on('dispose', function (e) { return _this3.off('loadstart', removeOldTracks); }); } /** * Proxy all native track list events to our track lists if the browser we are playing * in supports that type of track list. * * @private */ ; _proto.proxyNativeTracks_ = function proxyNativeTracks_() { var _this4 = this; NORMAL.names.forEach(function (name) { _this4.proxyNativeTracksForType_(name); }); } /** * Create the `Html5` Tech's DOM element. * * @return {Element} * The element that gets created. */ ; _proto.createEl = function createEl() { var el = this.options_.tag; // Check if this browser supports moving the element into the box. // On the iPhone video will break if you move the element, // So we have to create a brand new element. // If we ingested the player div, we do not need to move the media element. if (!el || !(this.options_.playerElIngest || this.movingMediaElementInDOM)) { // If the original tag is still there, clone and remove it. if (el) { var clone = el.cloneNode(true); if (el.parentNode) { el.parentNode.insertBefore(clone, el); } Html5.disposeMediaElement(el); el = clone; } else { el = document.createElement('video'); // determine if native controls should be used var tagAttributes = this.options_.tag && getAttributes(this.options_.tag); var attributes = mergeOptions({}, tagAttributes); if (!TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) { delete attributes.controls; } setAttributes(el, assign(attributes, { id: this.options_.techId, "class": 'vjs-tech' })); } el.playerId = this.options_.playerId; } if (typeof this.options_.preload !== 'undefined') { setAttribute(el, 'preload', this.options_.preload); } // Update specific tag settings, in case they were overridden // `autoplay` has to be *last* so that `muted` and `playsinline` are present // when iOS/Safari or other browsers attempt to autoplay. var settingsAttrs = ['loop', 'muted', 'playsinline', 'autoplay']; for (var i = 0; i < settingsAttrs.length; i++) { var attr = settingsAttrs[i]; var value = this.options_[attr]; if (typeof value !== 'undefined') { if (value) { setAttribute(el, attr, attr); } else { removeAttribute(el, attr); } el[attr] = value; } } return el; } /** * This will be triggered if the loadstart event has already fired, before videojs was * ready. Two known examples of when this can happen are: * 1. If we're loading the playback object after it has started loading * 2. The media is already playing the (often with autoplay on) then * * This function will fire another loadstart so that videojs can catchup. * * @fires Tech#loadstart * * @return {undefined} * returns nothing. */ ; _proto.handleLateInit_ = function handleLateInit_(el) { if (el.networkState === 0 || el.networkState === 3) { // The video element hasn't started loading the source yet // or didn't find a source return; } if (el.readyState === 0) { // NetworkState is set synchronously BUT loadstart is fired at the // end of the current stack, usually before setInterval(fn, 0). // So at this point we know loadstart may have already fired or is // about to fire, and either way the player hasn't seen it yet. // We don't want to fire loadstart prematurely here and cause a // double loadstart so we'll wait and see if it happens between now // and the next loop, and fire it if not. // HOWEVER, we also want to make sure it fires before loadedmetadata // which could also happen between now and the next loop, so we'll // watch for that also. var loadstartFired = false; var setLoadstartFired = function setLoadstartFired() { loadstartFired = true; }; this.on('loadstart', setLoadstartFired); var triggerLoadstart = function triggerLoadstart() { // We did miss the original loadstart. Make sure the player // sees loadstart before loadedmetadata if (!loadstartFired) { this.trigger('loadstart'); } }; this.on('loadedmetadata', triggerLoadstart); this.ready(function () { this.off('loadstart', setLoadstartFired); this.off('loadedmetadata', triggerLoadstart); if (!loadstartFired) { // We did miss the original native loadstart. Fire it now. this.trigger('loadstart'); } }); return; } // From here on we know that loadstart already fired and we missed it. // The other readyState events aren't as much of a problem if we double // them, so not going to go to as much trouble as loadstart to prevent // that unless we find reason to. var eventsToTrigger = ['loadstart']; // loadedmetadata: newly equal to HAVE_METADATA (1) or greater eventsToTrigger.push('loadedmetadata'); // loadeddata: newly increased to HAVE_CURRENT_DATA (2) or greater if (el.readyState >= 2) { eventsToTrigger.push('loadeddata'); } // canplay: newly increased to HAVE_FUTURE_DATA (3) or greater if (el.readyState >= 3) { eventsToTrigger.push('canplay'); } // canplaythrough: newly equal to HAVE_ENOUGH_DATA (4) if (el.readyState >= 4) { eventsToTrigger.push('canplaythrough'); } // We still need to give the player time to add event listeners this.ready(function () { eventsToTrigger.forEach(function (type) { this.trigger(type); }, this); }); } /** * Set current time for the `HTML5` tech. * * @param {number} seconds * Set the current time of the media to this. */ ; _proto.setCurrentTime = function setCurrentTime(seconds) { try { this.el_.currentTime = seconds; } catch (e) { log(e, 'Video is not ready. (Video.js)'); // this.warning(VideoJS.warnings.videoNotReady); } } /** * Get the current duration of the HTML5 media element. * * @return {number} * The duration of the media or 0 if there is no duration. */ ; _proto.duration = function duration() { var _this5 = this; // Android Chrome will report duration as Infinity for VOD HLS until after // playback has started, which triggers the live display erroneously. // Return NaN if playback has not started and trigger a durationupdate once // the duration can be reliably known. if (this.el_.duration === Infinity && IS_ANDROID && IS_CHROME && this.el_.currentTime === 0) { // Wait for the first `timeupdate` with currentTime > 0 - there may be // several with 0 var checkProgress = function checkProgress() { if (_this5.el_.currentTime > 0) { // Trigger durationchange for genuinely live video if (_this5.el_.duration === Infinity) { _this5.trigger('durationchange'); } _this5.off('timeupdate', checkProgress); } }; this.on('timeupdate', checkProgress); return NaN; } return this.el_.duration || NaN; } /** * Get the current width of the HTML5 media element. * * @return {number} * The width of the HTML5 media element. */ ; _proto.width = function width() { return this.el_.offsetWidth; } /** * Get the current height of the HTML5 media element. * * @return {number} * The height of the HTML5 media element. */ ; _proto.height = function height() { return this.el_.offsetHeight; } /** * Proxy iOS `webkitbeginfullscreen` and `webkitendfullscreen` into * `fullscreenchange` event. * * @private * @fires fullscreenchange * @listens webkitendfullscreen * @listens webkitbeginfullscreen * @listens webkitbeginfullscreen */ ; _proto.proxyWebkitFullscreen_ = function proxyWebkitFullscreen_() { var _this6 = this; if (!('webkitDisplayingFullscreen' in this.el_)) { return; } var endFn = function endFn() { this.trigger('fullscreenchange', { isFullscreen: false }); }; var beginFn = function beginFn() { if ('webkitPresentationMode' in this.el_ && this.el_.webkitPresentationMode !== 'picture-in-picture') { this.one('webkitendfullscreen', endFn); this.trigger('fullscreenchange', { isFullscreen: true }); } }; this.on('webkitbeginfullscreen', beginFn); this.on('dispose', function () { _this6.off('webkitbeginfullscreen', beginFn); _this6.off('webkitendfullscreen', endFn); }); } /** * Check if fullscreen is supported on the current playback device. * * @return {boolean} * - True if fullscreen is supported. * - False if fullscreen is not supported. */ ; _proto.supportsFullScreen = function supportsFullScreen() { if (typeof this.el_.webkitEnterFullScreen === 'function') { var userAgent = window$1.navigator && window$1.navigator.userAgent || ''; // Seems to be broken in Chromium/Chrome && Safari in Leopard if (/Android/.test(userAgent) || !/Chrome|Mac OS X 10.5/.test(userAgent)) { return true; } } return false; } /** * Request that the `HTML5` Tech enter fullscreen. */ ; _proto.enterFullScreen = function enterFullScreen() { var video = this.el_; if (video.paused && video.networkState <= video.HAVE_METADATA) { // attempt to prime the video element for programmatic access // this isn't necessary on the desktop but shouldn't hurt this.el_.play(); // playing and pausing synchronously during the transition to fullscreen // can get iOS ~6.1 devices into a play/pause loop this.setTimeout(function () { video.pause(); video.webkitEnterFullScreen(); }, 0); } else { video.webkitEnterFullScreen(); } } /** * Request that the `HTML5` Tech exit fullscreen. */ ; _proto.exitFullScreen = function exitFullScreen() { this.el_.webkitExitFullScreen(); } /** * Create a floating video window always on top of other windows so that users may * continue consuming media while they interact with other content sites, or * applications on their device. * * @see [Spec]{@link https://wicg.github.io/picture-in-picture} * * @return {Promise} * A promise with a Picture-in-Picture window. */ ; _proto.requestPictureInPicture = function requestPictureInPicture() { return this.el_.requestPictureInPicture(); } /** * A getter/setter for the `Html5` Tech's source object. * > Note: Please use {@link Html5#setSource} * * @param {Tech~SourceObject} [src] * The source object you want to set on the `HTML5` techs element. * * @return {Tech~SourceObject|undefined} * - The current source object when a source is not passed in. * - undefined when setting * * @deprecated Since version 5. */ ; _proto.src = function src(_src) { if (_src === undefined) { return this.el_.src; } // Setting src through `src` instead of `setSrc` will be deprecated this.setSrc(_src); } /** * Reset the tech by removing all sources and then calling * {@link Html5.resetMediaElement}. */ ; _proto.reset = function reset() { Html5.resetMediaElement(this.el_); } /** * Get the current source on the `HTML5` Tech. Falls back to returning the source from * the HTML5 media element. * * @return {Tech~SourceObject} * The current source object from the HTML5 tech. With a fallback to the * elements source. */ ; _proto.currentSrc = function currentSrc() { if (this.currentSource_) { return this.currentSource_.src; } return this.el_.currentSrc; } /** * Set controls attribute for the HTML5 media Element. * * @param {string} val * Value to set the controls attribute to */ ; _proto.setControls = function setControls(val) { this.el_.controls = !!val; } /** * Create and returns a remote {@link TextTrack} object. * * @param {string} kind * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata) * * @param {string} [label] * Label to identify the text track * * @param {string} [language] * Two letter language abbreviation * * @return {TextTrack} * The TextTrack that gets created. */ ; _proto.addTextTrack = function addTextTrack(kind, label, language) { if (!this.featuresNativeTextTracks) { return _Tech.prototype.addTextTrack.call(this, kind, label, language); } return this.el_.addTextTrack(kind, label, language); } /** * Creates either native TextTrack or an emulated TextTrack depending * on the value of `featuresNativeTextTracks` * * @param {Object} options * The object should contain the options to initialize the TextTrack with. * * @param {string} [options.kind] * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata). * * @param {string} [options.label] * Label to identify the text track * * @param {string} [options.language] * Two letter language abbreviation. * * @param {boolean} [options.default] * Default this track to on. * * @param {string} [options.id] * The internal id to assign this track. * * @param {string} [options.src] * A source url for the track. * * @return {HTMLTrackElement} * The track element that gets created. */ ; _proto.createRemoteTextTrack = function createRemoteTextTrack(options) { if (!this.featuresNativeTextTracks) { return _Tech.prototype.createRemoteTextTrack.call(this, options); } var htmlTrackElement = document.createElement('track'); if (options.kind) { htmlTrackElement.kind = options.kind; } if (options.label) { htmlTrackElement.label = options.label; } if (options.language || options.srclang) { htmlTrackElement.srclang = options.language || options.srclang; } if (options["default"]) { htmlTrackElement["default"] = options["default"]; } if (options.id) { htmlTrackElement.id = options.id; } if (options.src) { htmlTrackElement.src = options.src; } return htmlTrackElement; } /** * Creates a remote text track object and returns an html track element. * * @param {Object} options The object should contain values for * kind, language, label, and src (location of the WebVTT file) * @param {boolean} [manualCleanup=true] if set to false, the TextTrack will be * automatically removed from the video element whenever the source changes * @return {HTMLTrackElement} An Html Track Element. * This can be an emulated {@link HTMLTrackElement} or a native one. * @deprecated The default value of the "manualCleanup" parameter will default * to "false" in upcoming versions of Video.js */ ; _proto.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) { var htmlTrackElement = _Tech.prototype.addRemoteTextTrack.call(this, options, manualCleanup); if (this.featuresNativeTextTracks) { this.el().appendChild(htmlTrackElement); } return htmlTrackElement; } /** * Remove remote `TextTrack` from `TextTrackList` object * * @param {TextTrack} track * `TextTrack` object to remove */ ; _proto.removeRemoteTextTrack = function removeRemoteTextTrack(track) { _Tech.prototype.removeRemoteTextTrack.call(this, track); if (this.featuresNativeTextTracks) { var tracks = this.$$('track'); var i = tracks.length; while (i--) { if (track === tracks[i] || track === tracks[i].track) { this.el().removeChild(tracks[i]); } } } } /** * Gets available media playback quality metrics as specified by the W3C's Media * Playback Quality API. * * @see [Spec]{@link https://wicg.github.io/media-playback-quality} * * @return {Object} * An object with supported media playback quality metrics */ ; _proto.getVideoPlaybackQuality = function getVideoPlaybackQuality() { if (typeof this.el().getVideoPlaybackQuality === 'function') { return this.el().getVideoPlaybackQuality(); } var videoPlaybackQuality = {}; if (typeof this.el().webkitDroppedFrameCount !== 'undefined' && typeof this.el().webkitDecodedFrameCount !== 'undefined') { videoPlaybackQuality.droppedVideoFrames = this.el().webkitDroppedFrameCount; videoPlaybackQuality.totalVideoFrames = this.el().webkitDecodedFrameCount; } if (window$1.performance && typeof window$1.performance.now === 'function') { videoPlaybackQuality.creationTime = window$1.performance.now(); } else if (window$1.performance && window$1.performance.timing && typeof window$1.performance.timing.navigationStart === 'number') { videoPlaybackQuality.creationTime = window$1.Date.now() - window$1.performance.timing.navigationStart; } return videoPlaybackQuality; }; return Html5; }(Tech); /* HTML5 Support Testing ---------------------------------------------------- */ if (isReal()) { /** * Element for testing browser HTML5 media capabilities * * @type {Element} * @constant * @private */ Html5.TEST_VID = document.createElement('video'); var track = document.createElement('track'); track.kind = 'captions'; track.srclang = 'en'; track.label = 'English'; Html5.TEST_VID.appendChild(track); } /** * Check if HTML5 media is supported by this browser/device. * * @return {boolean} * - True if HTML5 media is supported. * - False if HTML5 media is not supported. */ Html5.isSupported = function () { // IE with no Media Player is a LIAR! (#984) try { Html5.TEST_VID.volume = 0.5; } catch (e) { return false; } return !!(Html5.TEST_VID && Html5.TEST_VID.canPlayType); }; /** * Check if the tech can support the given type * * @param {string} type * The mimetype to check * @return {string} 'probably', 'maybe', or '' (empty string) */ Html5.canPlayType = function (type) { return Html5.TEST_VID.canPlayType(type); }; /** * Check if the tech can support the given source * * @param {Object} srcObj * The source object * @param {Object} options * The options passed to the tech * @return {string} 'probably', 'maybe', or '' (empty string) */ Html5.canPlaySource = function (srcObj, options) { return Html5.canPlayType(srcObj.type); }; /** * Check if the volume can be changed in this browser/device. * Volume cannot be changed in a lot of mobile devices. * Specifically, it can't be changed from 1 on iOS. * * @return {boolean} * - True if volume can be controlled * - False otherwise */ Html5.canControlVolume = function () { // IE will error if Windows Media Player not installed #3315 try { var volume = Html5.TEST_VID.volume; Html5.TEST_VID.volume = volume / 2 + 0.1; return volume !== Html5.TEST_VID.volume; } catch (e) { return false; } }; /** * Check if the volume can be muted in this browser/device. * Some devices, e.g. iOS, don't allow changing volume * but permits muting/unmuting. * * @return {bolean} * - True if volume can be muted * - False otherwise */ Html5.canMuteVolume = function () { try { var muted = Html5.TEST_VID.muted; // in some versions of iOS muted property doesn't always // work, so we want to set both property and attribute Html5.TEST_VID.muted = !muted; if (Html5.TEST_VID.muted) { setAttribute(Html5.TEST_VID, 'muted', 'muted'); } else { removeAttribute(Html5.TEST_VID, 'muted', 'muted'); } return muted !== Html5.TEST_VID.muted; } catch (e) { return false; } }; /** * Check if the playback rate can be changed in this browser/device. * * @return {boolean} * - True if playback rate can be controlled * - False otherwise */ Html5.canControlPlaybackRate = function () { // Playback rate API is implemented in Android Chrome, but doesn't do anything // https://github.com/videojs/video.js/issues/3180 if (IS_ANDROID && IS_CHROME && CHROME_VERSION < 58) { return false; } // IE will error if Windows Media Player not installed #3315 try { var playbackRate = Html5.TEST_VID.playbackRate; Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1; return playbackRate !== Html5.TEST_VID.playbackRate; } catch (e) { return false; } }; /** * Check if we can override a video/audio elements attributes, with * Object.defineProperty. * * @return {boolean} * - True if builtin attributes can be overridden * - False otherwise */ Html5.canOverrideAttributes = function () { // if we cannot overwrite the src/innerHTML property, there is no support // iOS 7 safari for instance cannot do this. try { var noop = function noop() {}; Object.defineProperty(document.createElement('video'), 'src', { get: noop, set: noop }); Object.defineProperty(document.createElement('audio'), 'src', { get: noop, set: noop }); Object.defineProperty(document.createElement('video'), 'innerHTML', { get: noop, set: noop }); Object.defineProperty(document.createElement('audio'), 'innerHTML', { get: noop, set: noop }); } catch (e) { return false; } return true; }; /** * Check to see if native `TextTrack`s are supported by this browser/device. * * @return {boolean} * - True if native `TextTrack`s are supported. * - False otherwise */ Html5.supportsNativeTextTracks = function () { return IS_ANY_SAFARI || IS_IOS && IS_CHROME; }; /** * Check to see if native `VideoTrack`s are supported by this browser/device * * @return {boolean} * - True if native `VideoTrack`s are supported. * - False otherwise */ Html5.supportsNativeVideoTracks = function () { return !!(Html5.TEST_VID && Html5.TEST_VID.videoTracks); }; /** * Check to see if native `AudioTrack`s are supported by this browser/device * * @return {boolean} * - True if native `AudioTrack`s are supported. * - False otherwise */ Html5.supportsNativeAudioTracks = function () { return !!(Html5.TEST_VID && Html5.TEST_VID.audioTracks); }; /** * An array of events available on the Html5 tech. * * @private * @type {Array} */ Html5.Events = ['loadstart', 'suspend', 'abort', 'error', 'emptied', 'stalled', 'loadedmetadata', 'loadeddata', 'canplay', 'canplaythrough', 'playing', 'waiting', 'seeking', 'seeked', 'ended', 'durationchange', 'timeupdate', 'progress', 'play', 'pause', 'ratechange', 'resize', 'volumechange']; /** * Boolean indicating whether the `Tech` supports volume control. * * @type {boolean} * @default {@link Html5.canControlVolume} */ Html5.prototype.featuresVolumeControl = Html5.canControlVolume(); /** * Boolean indicating whether the `Tech` supports muting volume. * * @type {bolean} * @default {@link Html5.canMuteVolume} */ Html5.prototype.featuresMuteControl = Html5.canMuteVolume(); /** * Boolean indicating whether the `Tech` supports changing the speed at which the media * plays. Examples: * - Set player to play 2x (twice) as fast * - Set player to play 0.5x (half) as fast * * @type {boolean} * @default {@link Html5.canControlPlaybackRate} */ Html5.prototype.featuresPlaybackRate = Html5.canControlPlaybackRate(); /** * Boolean indicating whether the `Tech` supports the `sourceset` event. * * @type {boolean} * @default */ Html5.prototype.featuresSourceset = Html5.canOverrideAttributes(); /** * Boolean indicating whether the `HTML5` tech currently supports the media element * moving in the DOM. iOS breaks if you move the media element, so this is set this to * false there. Everywhere else this should be true. * * @type {boolean} * @default */ Html5.prototype.movingMediaElementInDOM = !IS_IOS; // TODO: Previous comment: No longer appears to be used. Can probably be removed. // Is this true? /** * Boolean indicating whether the `HTML5` tech currently supports automatic media resize * when going into fullscreen. * * @type {boolean} * @default */ Html5.prototype.featuresFullscreenResize = true; /** * Boolean indicating whether the `HTML5` tech currently supports the progress event. * If this is false, manual `progress` events will be triggered instead. * * @type {boolean} * @default */ Html5.prototype.featuresProgressEvents = true; /** * Boolean indicating whether the `HTML5` tech currently supports the timeupdate event. * If this is false, manual `timeupdate` events will be triggered instead. * * @default */ Html5.prototype.featuresTimeupdateEvents = true; /** * Boolean indicating whether the `HTML5` tech currently supports native `TextTrack`s. * * @type {boolean} * @default {@link Html5.supportsNativeTextTracks} */ Html5.prototype.featuresNativeTextTracks = Html5.supportsNativeTextTracks(); /** * Boolean indicating whether the `HTML5` tech currently supports native `VideoTrack`s. * * @type {boolean} * @default {@link Html5.supportsNativeVideoTracks} */ Html5.prototype.featuresNativeVideoTracks = Html5.supportsNativeVideoTracks(); /** * Boolean indicating whether the `HTML5` tech currently supports native `AudioTrack`s. * * @type {boolean} * @default {@link Html5.supportsNativeAudioTracks} */ Html5.prototype.featuresNativeAudioTracks = Html5.supportsNativeAudioTracks(); // HTML5 Feature detection and Device Fixes --------------------------------- // var canPlayType = Html5.TEST_VID && Html5.TEST_VID.constructor.prototype.canPlayType; var mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i; Html5.patchCanPlayType = function () { // Android 4.0 and above can play HLS to some extent but it reports being unable to do so // Firefox and Chrome report correctly if (ANDROID_VERSION >= 4.0 && !IS_FIREFOX && !IS_CHROME) { Html5.TEST_VID.constructor.prototype.canPlayType = function (type) { if (type && mpegurlRE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } }; Html5.unpatchCanPlayType = function () { var r = Html5.TEST_VID.constructor.prototype.canPlayType; Html5.TEST_VID.constructor.prototype.canPlayType = canPlayType; return r; }; // by default, patch the media element Html5.patchCanPlayType(); Html5.disposeMediaElement = function (el) { if (!el) { return; } if (el.parentNode) { el.parentNode.removeChild(el); } // remove any child track or source nodes to prevent their loading while (el.hasChildNodes()) { el.removeChild(el.firstChild); } // remove any src reference. not setting `src=''` because that causes a warning // in firefox el.removeAttribute('src'); // force the media element to update its loading state by calling load() // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793) if (typeof el.load === 'function') { // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473) (function () { try { el.load(); } catch (e) {// not supported } })(); } }; Html5.resetMediaElement = function (el) { if (!el) { return; } var sources = el.querySelectorAll('source'); var i = sources.length; while (i--) { el.removeChild(sources[i]); } // remove any src reference. // not setting `src=''` because that throws an error el.removeAttribute('src'); if (typeof el.load === 'function') { // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473) (function () { try { el.load(); } catch (e) {// satisfy linter } })(); } }; /* Native HTML5 element property wrapping ----------------------------------- */ // Wrap native boolean attributes with getters that check both property and attribute // The list is as followed: // muted, defaultMuted, autoplay, controls, loop, playsinline [ /** * Get the value of `muted` from the media element. `muted` indicates * that the volume for the media should be set to silent. This does not actually change * the `volume` attribute. * * @method Html5#muted * @return {boolean} * - True if the value of `volume` should be ignored and the audio set to silent. * - False if the value of `volume` should be used. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted} */ 'muted', /** * Get the value of `defaultMuted` from the media element. `defaultMuted` indicates * whether the media should start muted or not. Only changes the default state of the * media. `muted` and `defaultMuted` can have different values. {@link Html5#muted} indicates the * current state. * * @method Html5#defaultMuted * @return {boolean} * - The value of `defaultMuted` from the media element. * - True indicates that the media should start muted. * - False indicates that the media should not start muted * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted} */ 'defaultMuted', /** * Get the value of `autoplay` from the media element. `autoplay` indicates * that the media should start to play as soon as the page is ready. * * @method Html5#autoplay * @return {boolean} * - The value of `autoplay` from the media element. * - True indicates that the media should start as soon as the page loads. * - False indicates that the media should not start as soon as the page loads. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay} */ 'autoplay', /** * Get the value of `controls` from the media element. `controls` indicates * whether the native media controls should be shown or hidden. * * @method Html5#controls * @return {boolean} * - The value of `controls` from the media element. * - True indicates that native controls should be showing. * - False indicates that native controls should be hidden. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-controls} */ 'controls', /** * Get the value of `loop` from the media element. `loop` indicates * that the media should return to the start of the media and continue playing once * it reaches the end. * * @method Html5#loop * @return {boolean} * - The value of `loop` from the media element. * - True indicates that playback should seek back to start once * the end of a media is reached. * - False indicates that playback should not loop back to the start when the * end of the media is reached. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop} */ 'loop', /** * Get the value of `playsinline` from the media element. `playsinline` indicates * to the browser that non-fullscreen playback is preferred when fullscreen * playback is the native default, such as in iOS Safari. * * @method Html5#playsinline * @return {boolean} * - The value of `playsinline` from the media element. * - True indicates that the media should play inline. * - False indicates that the media should not play inline. * * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline} */ 'playsinline'].forEach(function (prop) { Html5.prototype[prop] = function () { return this.el_[prop] || this.el_.hasAttribute(prop); }; }); // Wrap native boolean attributes with setters that set both property and attribute // The list is as followed: // setMuted, setDefaultMuted, setAutoplay, setLoop, setPlaysinline // setControls is special-cased above [ /** * Set the value of `muted` on the media element. `muted` indicates that the current * audio level should be silent. * * @method Html5#setMuted * @param {boolean} muted * - True if the audio should be set to silent * - False otherwise * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted} */ 'muted', /** * Set the value of `defaultMuted` on the media element. `defaultMuted` indicates that the current * audio level should be silent, but will only effect the muted level on intial playback.. * * @method Html5.prototype.setDefaultMuted * @param {boolean} defaultMuted * - True if the audio should be set to silent * - False otherwise * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted} */ 'defaultMuted', /** * Set the value of `autoplay` on the media element. `autoplay` indicates * that the media should start to play as soon as the page is ready. * * @method Html5#setAutoplay * @param {boolean} autoplay * - True indicates that the media should start as soon as the page loads. * - False indicates that the media should not start as soon as the page loads. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay} */ 'autoplay', /** * Set the value of `loop` on the media element. `loop` indicates * that the media should return to the start of the media and continue playing once * it reaches the end. * * @method Html5#setLoop * @param {boolean} loop * - True indicates that playback should seek back to start once * the end of a media is reached. * - False indicates that playback should not loop back to the start when the * end of the media is reached. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop} */ 'loop', /** * Set the value of `playsinline` from the media element. `playsinline` indicates * to the browser that non-fullscreen playback is preferred when fullscreen * playback is the native default, such as in iOS Safari. * * @method Html5#setPlaysinline * @param {boolean} playsinline * - True indicates that the media should play inline. * - False indicates that the media should not play inline. * * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline} */ 'playsinline'].forEach(function (prop) { Html5.prototype['set' + toTitleCase(prop)] = function (v) { this.el_[prop] = v; if (v) { this.el_.setAttribute(prop, prop); } else { this.el_.removeAttribute(prop); } }; }); // Wrap native properties with a getter // The list is as followed // paused, currentTime, buffered, volume, poster, preload, error, seeking // seekable, ended, playbackRate, defaultPlaybackRate, played, networkState // readyState, videoWidth, videoHeight [ /** * Get the value of `paused` from the media element. `paused` indicates whether the media element * is currently paused or not. * * @method Html5#paused * @return {boolean} * The value of `paused` from the media element. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-paused} */ 'paused', /** * Get the value of `currentTime` from the media element. `currentTime` indicates * the current second that the media is at in playback. * * @method Html5#currentTime * @return {number} * The value of `currentTime` from the media element. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-currenttime} */ 'currentTime', /** * Get the value of `buffered` from the media element. `buffered` is a `TimeRange` * object that represents the parts of the media that are already downloaded and * available for playback. * * @method Html5#buffered * @return {TimeRange} * The value of `buffered` from the media element. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-buffered} */ 'buffered', /** * Get the value of `volume` from the media element. `volume` indicates * the current playback volume of audio for a media. `volume` will be a value from 0 * (silent) to 1 (loudest and default). * * @method Html5#volume * @return {number} * The value of `volume` from the media element. Value will be between 0-1. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume} */ 'volume', /** * Get the value of `poster` from the media element. `poster` indicates * that the url of an image file that can/will be shown when no media data is available. * * @method Html5#poster * @return {string} * The value of `poster` from the media element. Value will be a url to an * image. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-video-poster} */ 'poster', /** * Get the value of `preload` from the media element. `preload` indicates * what should download before the media is interacted with. It can have the following * values: * - none: nothing should be downloaded * - metadata: poster and the first few frames of the media may be downloaded to get * media dimensions and other metadata * - auto: allow the media and metadata for the media to be downloaded before * interaction * * @method Html5#preload * @return {string} * The value of `preload` from the media element. Will be 'none', 'metadata', * or 'auto'. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload} */ 'preload', /** * Get the value of the `error` from the media element. `error` indicates any * MediaError that may have occurred during playback. If error returns null there is no * current error. * * @method Html5#error * @return {MediaError|null} * The value of `error` from the media element. Will be `MediaError` if there * is a current error and null otherwise. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-error} */ 'error', /** * Get the value of `seeking` from the media element. `seeking` indicates whether the * media is currently seeking to a new position or not. * * @method Html5#seeking * @return {boolean} * - The value of `seeking` from the media element. * - True indicates that the media is currently seeking to a new position. * - False indicates that the media is not seeking to a new position at this time. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seeking} */ 'seeking', /** * Get the value of `seekable` from the media element. `seekable` returns a * `TimeRange` object indicating ranges of time that can currently be `seeked` to. * * @method Html5#seekable * @return {TimeRange} * The value of `seekable` from the media element. A `TimeRange` object * indicating the current ranges of time that can be seeked to. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seekable} */ 'seekable', /** * Get the value of `ended` from the media element. `ended` indicates whether * the media has reached the end or not. * * @method Html5#ended * @return {boolean} * - The value of `ended` from the media element. * - True indicates that the media has ended. * - False indicates that the media has not ended. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-ended} */ 'ended', /** * Get the value of `playbackRate` from the media element. `playbackRate` indicates * the rate at which the media is currently playing back. Examples: * - if playbackRate is set to 2, media will play twice as fast. * - if playbackRate is set to 0.5, media will play half as fast. * * @method Html5#playbackRate * @return {number} * The value of `playbackRate` from the media element. A number indicating * the current playback speed of the media, where 1 is normal speed. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate} */ 'playbackRate', /** * Get the value of `defaultPlaybackRate` from the media element. `defaultPlaybackRate` indicates * the rate at which the media is currently playing back. This value will not indicate the current * `playbackRate` after playback has started, use {@link Html5#playbackRate} for that. * * Examples: * - if defaultPlaybackRate is set to 2, media will play twice as fast. * - if defaultPlaybackRate is set to 0.5, media will play half as fast. * * @method Html5.prototype.defaultPlaybackRate * @return {number} * The value of `defaultPlaybackRate` from the media element. A number indicating * the current playback speed of the media, where 1 is normal speed. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate} */ 'defaultPlaybackRate', /** * Get the value of `played` from the media element. `played` returns a `TimeRange` * object representing points in the media timeline that have been played. * * @method Html5#played * @return {TimeRange} * The value of `played` from the media element. A `TimeRange` object indicating * the ranges of time that have been played. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-played} */ 'played', /** * Get the value of `networkState` from the media element. `networkState` indicates * the current network state. It returns an enumeration from the following list: * - 0: NETWORK_EMPTY * - 1: NETWORK_IDLE * - 2: NETWORK_LOADING * - 3: NETWORK_NO_SOURCE * * @method Html5#networkState * @return {number} * The value of `networkState` from the media element. This will be a number * from the list in the description. * * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-networkstate} */ 'networkState', /** * Get the value of `readyState` from the media element. `readyState` indicates * the current state of the media element. It returns an enumeration from the * following list: * - 0: HAVE_NOTHING * - 1: HAVE_METADATA * - 2: HAVE_CURRENT_DATA * - 3: HAVE_FUTURE_DATA * - 4: HAVE_ENOUGH_DATA * * @method Html5#readyState * @return {number} * The value of `readyState` from the media element. This will be a number * from the list in the description. * * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#ready-states} */ 'readyState', /** * Get the value of `videoWidth` from the video element. `videoWidth` indicates * the current width of the video in css pixels. * * @method Html5#videoWidth * @return {number} * The value of `videoWidth` from the video element. This will be a number * in css pixels. * * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth} */ 'videoWidth', /** * Get the value of `videoHeight` from the video element. `videoHeight` indicates * the current height of the video in css pixels. * * @method Html5#videoHeight * @return {number} * The value of `videoHeight` from the video element. This will be a number * in css pixels. * * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth} */ 'videoHeight'].forEach(function (prop) { Html5.prototype[prop] = function () { return this.el_[prop]; }; }); // Wrap native properties with a setter in this format: // set + toTitleCase(name) // The list is as follows: // setVolume, setSrc, setPoster, setPreload, setPlaybackRate, setDefaultPlaybackRate [ /** * Set the value of `volume` on the media element. `volume` indicates the current * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and * so on. * * @method Html5#setVolume * @param {number} percentAsDecimal * The volume percent as a decimal. Valid range is from 0-1. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume} */ 'volume', /** * Set the value of `src` on the media element. `src` indicates the current * {@link Tech~SourceObject} for the media. * * @method Html5#setSrc * @param {Tech~SourceObject} src * The source object to set as the current source. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-src} */ 'src', /** * Set the value of `poster` on the media element. `poster` is the url to * an image file that can/will be shown when no media data is available. * * @method Html5#setPoster * @param {string} poster * The url to an image that should be used as the `poster` for the media * element. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-poster} */ 'poster', /** * Set the value of `preload` on the media element. `preload` indicates * what should download before the media is interacted with. It can have the following * values: * - none: nothing should be downloaded * - metadata: poster and the first few frames of the media may be downloaded to get * media dimensions and other metadata * - auto: allow the media and metadata for the media to be downloaded before * interaction * * @method Html5#setPreload * @param {string} preload * The value of `preload` to set on the media element. Must be 'none', 'metadata', * or 'auto'. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload} */ 'preload', /** * Set the value of `playbackRate` on the media element. `playbackRate` indicates * the rate at which the media should play back. Examples: * - if playbackRate is set to 2, media will play twice as fast. * - if playbackRate is set to 0.5, media will play half as fast. * * @method Html5#setPlaybackRate * @return {number} * The value of `playbackRate` from the media element. A number indicating * the current playback speed of the media, where 1 is normal speed. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate} */ 'playbackRate', /** * Set the value of `defaultPlaybackRate` on the media element. `defaultPlaybackRate` indicates * the rate at which the media should play back upon initial startup. Changing this value * after a video has started will do nothing. Instead you should used {@link Html5#setPlaybackRate}. * * Example Values: * - if playbackRate is set to 2, media will play twice as fast. * - if playbackRate is set to 0.5, media will play half as fast. * * @method Html5.prototype.setDefaultPlaybackRate * @return {number} * The value of `defaultPlaybackRate` from the media element. A number indicating * the current playback speed of the media, where 1 is normal speed. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultplaybackrate} */ 'defaultPlaybackRate'].forEach(function (prop) { Html5.prototype['set' + toTitleCase(prop)] = function (v) { this.el_[prop] = v; }; }); // wrap native functions with a function // The list is as follows: // pause, load, play [ /** * A wrapper around the media elements `pause` function. This will call the `HTML5` * media elements `pause` function. * * @method Html5#pause * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-pause} */ 'pause', /** * A wrapper around the media elements `load` function. This will call the `HTML5`s * media element `load` function. * * @method Html5#load * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-load} */ 'load', /** * A wrapper around the media elements `play` function. This will call the `HTML5`s * media element `play` function. * * @method Html5#play * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-play} */ 'play'].forEach(function (prop) { Html5.prototype[prop] = function () { return this.el_[prop](); }; }); Tech.withSourceHandlers(Html5); /** * Native source handler for Html5, simply passes the source to the media element. * * @property {Tech~SourceObject} source * The source object * * @property {Html5} tech * The instance of the HTML5 tech. */ Html5.nativeSourceHandler = {}; /** * Check if the media element can play the given mime type. * * @param {string} type * The mimetype to check * * @return {string} * 'probably', 'maybe', or '' (empty string) */ Html5.nativeSourceHandler.canPlayType = function (type) { // IE without MediaPlayer throws an error (#519) try { return Html5.TEST_VID.canPlayType(type); } catch (e) { return ''; } }; /** * Check if the media element can handle a source natively. * * @param {Tech~SourceObject} source * The source object * * @param {Object} [options] * Options to be passed to the tech. * * @return {string} * 'probably', 'maybe', or '' (empty string). */ Html5.nativeSourceHandler.canHandleSource = function (source, options) { // If a type was provided we should rely on that if (source.type) { return Html5.nativeSourceHandler.canPlayType(source.type); // If no type, fall back to checking 'video/[EXTENSION]' } else if (source.src) { var ext = getFileExtension(source.src); return Html5.nativeSourceHandler.canPlayType("video/" + ext); } return ''; }; /** * Pass the source to the native media element. * * @param {Tech~SourceObject} source * The source object * * @param {Html5} tech * The instance of the Html5 tech * * @param {Object} [options] * The options to pass to the source */ Html5.nativeSourceHandler.handleSource = function (source, tech, options) { tech.setSrc(source.src); }; /** * A noop for the native dispose function, as cleanup is not needed. */ Html5.nativeSourceHandler.dispose = function () {}; // Register the native source handler Html5.registerSourceHandler(Html5.nativeSourceHandler); Tech.registerTech('Html5', Html5); // on the player when they happen var TECH_EVENTS_RETRIGGER = [ /** * Fired while the user agent is downloading media data. * * @event Player#progress * @type {EventTarget~Event} */ /** * Retrigger the `progress` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechProgress_ * @fires Player#progress * @listens Tech#progress */ 'progress', /** * Fires when the loading of an audio/video is aborted. * * @event Player#abort * @type {EventTarget~Event} */ /** * Retrigger the `abort` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechAbort_ * @fires Player#abort * @listens Tech#abort */ 'abort', /** * Fires when the browser is intentionally not getting media data. * * @event Player#suspend * @type {EventTarget~Event} */ /** * Retrigger the `suspend` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechSuspend_ * @fires Player#suspend * @listens Tech#suspend */ 'suspend', /** * Fires when the current playlist is empty. * * @event Player#emptied * @type {EventTarget~Event} */ /** * Retrigger the `emptied` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechEmptied_ * @fires Player#emptied * @listens Tech#emptied */ 'emptied', /** * Fires when the browser is trying to get media data, but data is not available. * * @event Player#stalled * @type {EventTarget~Event} */ /** * Retrigger the `stalled` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechStalled_ * @fires Player#stalled * @listens Tech#stalled */ 'stalled', /** * Fires when the browser has loaded meta data for the audio/video. * * @event Player#loadedmetadata * @type {EventTarget~Event} */ /** * Retrigger the `stalled` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechLoadedmetadata_ * @fires Player#loadedmetadata * @listens Tech#loadedmetadata */ 'loadedmetadata', /** * Fires when the browser has loaded the current frame of the audio/video. * * @event Player#loadeddata * @type {event} */ /** * Retrigger the `loadeddata` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechLoaddeddata_ * @fires Player#loadeddata * @listens Tech#loadeddata */ 'loadeddata', /** * Fires when the current playback position has changed. * * @event Player#timeupdate * @type {event} */ /** * Retrigger the `timeupdate` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechTimeUpdate_ * @fires Player#timeupdate * @listens Tech#timeupdate */ 'timeupdate', /** * Fires when the video's intrinsic dimensions change * * @event Player#resize * @type {event} */ /** * Retrigger the `resize` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechResize_ * @fires Player#resize * @listens Tech#resize */ 'resize', /** * Fires when the volume has been changed * * @event Player#volumechange * @type {event} */ /** * Retrigger the `volumechange` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechVolumechange_ * @fires Player#volumechange * @listens Tech#volumechange */ 'volumechange', /** * Fires when the text track has been changed * * @event Player#texttrackchange * @type {event} */ /** * Retrigger the `texttrackchange` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechTexttrackchange_ * @fires Player#texttrackchange * @listens Tech#texttrackchange */ 'texttrackchange']; // events to queue when playback rate is zero // this is a hash for the sole purpose of mapping non-camel-cased event names // to camel-cased function names var TECH_EVENTS_QUEUE = { canplay: 'CanPlay', canplaythrough: 'CanPlayThrough', playing: 'Playing', seeked: 'Seeked' }; var BREAKPOINT_ORDER = ['tiny', 'xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']; var BREAKPOINT_CLASSES = {}; // grep: vjs-layout-tiny // grep: vjs-layout-x-small // grep: vjs-layout-small // grep: vjs-layout-medium // grep: vjs-layout-large // grep: vjs-layout-x-large // grep: vjs-layout-huge BREAKPOINT_ORDER.forEach(function (k) { var v = k.charAt(0) === 'x' ? "x-" + k.substring(1) : k; BREAKPOINT_CLASSES[k] = "vjs-layout-" + v; }); var DEFAULT_BREAKPOINTS = { tiny: 210, xsmall: 320, small: 425, medium: 768, large: 1440, xlarge: 2560, huge: Infinity }; /** * An instance of the `Player` class is created when any of the Video.js setup methods * are used to initialize a video. * * After an instance has been created it can be accessed globally in two ways: * 1. By calling `videojs('example_video_1');` * 2. By using it directly via `videojs.players.example_video_1;` * * @extends Component */ var Player = /*#__PURE__*/ function (_Component) { _inheritsLoose(Player, _Component); /** * Create an instance of this class. * * @param {Element} tag * The original video DOM element used for configuring options. * * @param {Object} [options] * Object of option names and values. * * @param {Component~ReadyCallback} [ready] * Ready callback function. */ function Player(tag, options, ready) { var _this; // Make sure tag ID exists tag.id = tag.id || options.id || "vjs_video_" + newGUID(); // Set Options // The options argument overrides options set in the video tag // which overrides globally set options. // This latter part coincides with the load order // (tag must exist before Player) options = assign(Player.getTagSettings(tag), options); // Delay the initialization of children because we need to set up // player properties first, and can't use `this` before `super()` options.initChildren = false; // Same with creating the element options.createEl = false; // don't auto mixin the evented mixin options.evented = false; // we don't want the player to report touch activity on itself // see enableTouchActivity in Component options.reportTouchActivity = false; // If language is not set, get the closest lang attribute if (!options.language) { if (typeof tag.closest === 'function') { var closest = tag.closest('[lang]'); if (closest && closest.getAttribute) { options.language = closest.getAttribute('lang'); } } else { var element = tag; while (element && element.nodeType === 1) { if (getAttributes(element).hasOwnProperty('lang')) { options.language = element.getAttribute('lang'); break; } element = element.parentNode; } } } // Run base component initializing with new options _this = _Component.call(this, null, options, ready) || this; // Create bound methods for document listeners. _this.boundDocumentFullscreenChange_ = bind(_assertThisInitialized(_this), _this.documentFullscreenChange_); _this.boundFullWindowOnEscKey_ = bind(_assertThisInitialized(_this), _this.fullWindowOnEscKey); // create logger _this.log = createLogger$1(_this.id_); // Hold our own reference to fullscreen api so it can be mocked in tests _this.fsApi_ = FullscreenApi; // Tracks when a tech changes the poster _this.isPosterFromTech_ = false; // Holds callback info that gets queued when playback rate is zero // and a seek is happening _this.queuedCallbacks_ = []; // Turn off API access because we're loading a new tech that might load asynchronously _this.isReady_ = false; // Init state hasStarted_ _this.hasStarted_ = false; // Init state userActive_ _this.userActive_ = false; // if the global option object was accidentally blown away by // someone, bail early with an informative error if (!_this.options_ || !_this.options_.techOrder || !_this.options_.techOrder.length) { throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?'); } // Store the original tag used to set options _this.tag = tag; // Store the tag attributes used to restore html5 element _this.tagAttributes = tag && getAttributes(tag); // Update current language _this.language(_this.options_.language); // Update Supported Languages if (options.languages) { // Normalise player option languages to lowercase var languagesToLower = {}; Object.getOwnPropertyNames(options.languages).forEach(function (name) { languagesToLower[name.toLowerCase()] = options.languages[name]; }); _this.languages_ = languagesToLower; } else { _this.languages_ = Player.prototype.options_.languages; } _this.resetCache_(); // Set poster _this.poster_ = options.poster || ''; // Set controls _this.controls_ = !!options.controls; // Original tag settings stored in options // now remove immediately so native controls don't flash. // May be turned back on by HTML5 tech if nativeControlsForTouch is true tag.controls = false; tag.removeAttribute('controls'); _this.changingSrc_ = false; _this.playCallbacks_ = []; _this.playTerminatedQueue_ = []; // the attribute overrides the option if (tag.hasAttribute('autoplay')) { _this.autoplay(true); } else { // otherwise use the setter to validate and // set the correct value. _this.autoplay(_this.options_.autoplay); } // check plugins if (options.plugins) { Object.keys(options.plugins).forEach(function (name) { if (typeof _this[name] !== 'function') { throw new Error("plugin \"" + name + "\" does not exist"); } }); } /* * Store the internal state of scrubbing * * @private * @return {Boolean} True if the user is scrubbing */ _this.scrubbing_ = false; _this.el_ = _this.createEl(); // Make this an evented object and use `el_` as its event bus. evented(_assertThisInitialized(_this), { eventBusKey: 'el_' }); if (_this.fluid_) { _this.on('playerreset', _this.updateStyleEl_); } // We also want to pass the original player options to each component and plugin // as well so they don't need to reach back into the player for options later. // We also need to do another copy of this.options_ so we don't end up with // an infinite loop. var playerOptionsCopy = mergeOptions(_this.options_); // Load plugins if (options.plugins) { Object.keys(options.plugins).forEach(function (name) { _this[name](options.plugins[name]); }); } _this.options_.playerOptions = playerOptionsCopy; _this.middleware_ = []; _this.initChildren(); // Set isAudio based on whether or not an audio tag was used _this.isAudio(tag.nodeName.toLowerCase() === 'audio'); // Update controls className. Can't do this when the controls are initially // set because the element doesn't exist yet. if (_this.controls()) { _this.addClass('vjs-controls-enabled'); } else { _this.addClass('vjs-controls-disabled'); } // Set ARIA label and region role depending on player type _this.el_.setAttribute('role', 'region'); if (_this.isAudio()) { _this.el_.setAttribute('aria-label', _this.localize('Audio Player')); } else { _this.el_.setAttribute('aria-label', _this.localize('Video Player')); } if (_this.isAudio()) { _this.addClass('vjs-audio'); } if (_this.flexNotSupported_()) { _this.addClass('vjs-no-flex'); } // TODO: Make this smarter. Toggle user state between touching/mousing // using events, since devices can have both touch and mouse events. // TODO: Make this check be performed again when the window switches between monitors // (See https://github.com/videojs/video.js/issues/5683) if (TOUCH_ENABLED) { _this.addClass('vjs-touch-enabled'); } // iOS Safari has broken hover handling if (!IS_IOS) { _this.addClass('vjs-workinghover'); } // Make player easily findable by ID Player.players[_this.id_] = _assertThisInitialized(_this); // Add a major version class to aid css in plugins var majorVersion = version.split('.')[0]; _this.addClass("vjs-v" + majorVersion); // When the player is first initialized, trigger activity so components // like the control bar show themselves if needed _this.userActive(true); _this.reportUserActivity(); _this.one('play', _this.listenForUserActivity_); _this.on('stageclick', _this.handleStageClick_); _this.on('keydown', _this.handleKeyDown); _this.breakpoints(_this.options_.breakpoints); _this.responsive(_this.options_.responsive); return _this; } /** * Destroys the video player and does any necessary cleanup. * * This is especially helpful if you are dynamically adding and removing videos * to/from the DOM. * * @fires Player#dispose */ var _proto = Player.prototype; _proto.dispose = function dispose() { var _this2 = this; /** * Called when the player is being disposed of. * * @event Player#dispose * @type {EventTarget~Event} */ this.trigger('dispose'); // prevent dispose from being called twice this.off('dispose'); // Make sure all player-specific document listeners are unbound. This is off(document, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_); off(document, 'keydown', this.boundFullWindowOnEscKey_); if (this.styleEl_ && this.styleEl_.parentNode) { this.styleEl_.parentNode.removeChild(this.styleEl_); this.styleEl_ = null; } // Kill reference to this player Player.players[this.id_] = null; if (this.tag && this.tag.player) { this.tag.player = null; } if (this.el_ && this.el_.player) { this.el_.player = null; } if (this.tech_) { this.tech_.dispose(); this.isPosterFromTech_ = false; this.poster_ = ''; } if (this.playerElIngest_) { this.playerElIngest_ = null; } if (this.tag) { this.tag = null; } clearCacheForPlayer(this); // remove all event handlers for track lists // all tracks and track listeners are removed on // tech dispose ALL.names.forEach(function (name) { var props = ALL[name]; var list = _this2[props.getterName](); // if it is not a native list // we have to manually remove event listeners if (list && list.off) { list.off(); } }); // the actual .el_ is removed here _Component.prototype.dispose.call(this); } /** * Create the `Player`'s DOM element. * * @return {Element} * The DOM element that gets created. */ ; _proto.createEl = function createEl() { var tag = this.tag; var el; var playerElIngest = this.playerElIngest_ = tag.parentNode && tag.parentNode.hasAttribute && tag.parentNode.hasAttribute('data-vjs-player'); var divEmbed = this.tag.tagName.toLowerCase() === 'video-js'; if (playerElIngest) { el = this.el_ = tag.parentNode; } else if (!divEmbed) { el = this.el_ = _Component.prototype.createEl.call(this, 'div'); } // Copy over all the attributes from the tag, including ID and class // ID will now reference player box, not the video tag var attrs = getAttributes(tag); if (divEmbed) { el = this.el_ = tag; tag = this.tag = document.createElement('video'); while (el.children.length) { tag.appendChild(el.firstChild); } if (!hasClass(el, 'video-js')) { addClass(el, 'video-js'); } el.appendChild(tag); playerElIngest = this.playerElIngest_ = el; // move properties over from our custom `video-js` element // to our new `video` element. This will move things like // `src` or `controls` that were set via js before the player // was initialized. Object.keys(el).forEach(function (k) { tag[k] = el[k]; }); } // set tabindex to -1 to remove the video element from the focus order tag.setAttribute('tabindex', '-1'); attrs.tabindex = '-1'; // Workaround for #4583 (JAWS+IE doesn't announce BPB or play button), and // for the same issue with Chrome (on Windows) with JAWS. // See https://github.com/FreedomScientific/VFO-standards-support/issues/78 // Note that we can't detect if JAWS is being used, but this ARIA attribute // doesn't change behavior of IE11 or Chrome if JAWS is not being used if (IE_VERSION || IS_CHROME && IS_WINDOWS) { tag.setAttribute('role', 'application'); attrs.role = 'application'; } // Remove width/height attrs from tag so CSS can make it 100% width/height tag.removeAttribute('width'); tag.removeAttribute('height'); if ('width' in attrs) { delete attrs.width; } if ('height' in attrs) { delete attrs.height; } Object.getOwnPropertyNames(attrs).forEach(function (attr) { // don't copy over the class attribute to the player element when we're in a div embed // the class is already set up properly in the divEmbed case // and we want to make sure that the `video-js` class doesn't get lost if (!(divEmbed && attr === 'class')) { el.setAttribute(attr, attrs[attr]); } if (divEmbed) { tag.setAttribute(attr, attrs[attr]); } }); // Update tag id/class for use as HTML5 playback tech // Might think we should do this after embedding in container so .vjs-tech class // doesn't flash 100% width/height, but class only applies with .video-js parent tag.playerId = tag.id; tag.id += '_html5_api'; tag.className = 'vjs-tech'; // Make player findable on elements tag.player = el.player = this; // Default state of video is paused this.addClass('vjs-paused'); // Add a style element in the player that we'll use to set the width/height // of the player in a way that's still overrideable by CSS, just like the // video element if (window$1.VIDEOJS_NO_DYNAMIC_STYLE !== true) { this.styleEl_ = createStyleElement('vjs-styles-dimensions'); var defaultsStyleEl = $('.vjs-styles-defaults'); var head = $('head'); head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild); } this.fill_ = false; this.fluid_ = false; // Pass in the width/height/aspectRatio options which will update the style el this.width(this.options_.width); this.height(this.options_.height); this.fill(this.options_.fill); this.fluid(this.options_.fluid); this.aspectRatio(this.options_.aspectRatio); // Hide any links within the video/audio tag, // because IE doesn't hide them completely from screen readers. var links = tag.getElementsByTagName('a'); for (var i = 0; i < links.length; i++) { var linkEl = links.item(i); addClass(linkEl, 'vjs-hidden'); linkEl.setAttribute('hidden', 'hidden'); } // insertElFirst seems to cause the networkState to flicker from 3 to 2, so // keep track of the original for later so we can know if the source originally failed tag.initNetworkState_ = tag.networkState; // Wrap video tag in div (el/box) container if (tag.parentNode && !playerElIngest) { tag.parentNode.insertBefore(el, tag); } // insert the tag as the first child of the player element // then manually add it to the children array so that this.addChild // will work properly for other components // // Breaks iPhone, fixed in HTML5 setup. prependTo(tag, el); this.children_.unshift(tag); // Set lang attr on player to ensure CSS :lang() in consistent with player // if it's been set to something different to the doc this.el_.setAttribute('lang', this.language_); this.el_ = el; return el; } /** * A getter/setter for the `Player`'s width. Returns the player's configured value. * To get the current width use `currentWidth()`. * * @param {number} [value] * The value to set the `Player`'s width to. * * @return {number} * The current width of the `Player` when getting. */ ; _proto.width = function width(value) { return this.dimension('width', value); } /** * A getter/setter for the `Player`'s height. Returns the player's configured value. * To get the current height use `currentheight()`. * * @param {number} [value] * The value to set the `Player`'s heigth to. * * @return {number} * The current height of the `Player` when getting. */ ; _proto.height = function height(value) { return this.dimension('height', value); } /** * A getter/setter for the `Player`'s width & height. * * @param {string} dimension * This string can be: * - 'width' * - 'height' * * @param {number} [value] * Value for dimension specified in the first argument. * * @return {number} * The dimension arguments value when getting (width/height). */ ; _proto.dimension = function dimension(_dimension, value) { var privDimension = _dimension + '_'; if (value === undefined) { return this[privDimension] || 0; } if (value === '') { // If an empty string is given, reset the dimension to be automatic this[privDimension] = undefined; this.updateStyleEl_(); return; } var parsedVal = parseFloat(value); if (isNaN(parsedVal)) { log.error("Improper value \"" + value + "\" supplied for for " + _dimension); return; } this[privDimension] = parsedVal; this.updateStyleEl_(); } /** * A getter/setter/toggler for the vjs-fluid `className` on the `Player`. * * Turning this on will turn off fill mode. * * @param {boolean} [bool] * - A value of true adds the class. * - A value of false removes the class. * - No value will be a getter. * * @return {boolean|undefined} * - The value of fluid when getting. * - `undefined` when setting. */ ; _proto.fluid = function fluid(bool) { if (bool === undefined) { return !!this.fluid_; } this.fluid_ = !!bool; if (isEvented(this)) { this.off('playerreset', this.updateStyleEl_); } if (bool) { this.addClass('vjs-fluid'); this.fill(false); addEventedCallback(function () { this.on('playerreset', this.updateStyleEl_); }); } else { this.removeClass('vjs-fluid'); } this.updateStyleEl_(); } /** * A getter/setter/toggler for the vjs-fill `className` on the `Player`. * * Turning this on will turn off fluid mode. * * @param {boolean} [bool] * - A value of true adds the class. * - A value of false removes the class. * - No value will be a getter. * * @return {boolean|undefined} * - The value of fluid when getting. * - `undefined` when setting. */ ; _proto.fill = function fill(bool) { if (bool === undefined) { return !!this.fill_; } this.fill_ = !!bool; if (bool) { this.addClass('vjs-fill'); this.fluid(false); } else { this.removeClass('vjs-fill'); } } /** * Get/Set the aspect ratio * * @param {string} [ratio] * Aspect ratio for player * * @return {string|undefined} * returns the current aspect ratio when getting */ /** * A getter/setter for the `Player`'s aspect ratio. * * @param {string} [ratio] * The value to set the `Player's aspect ratio to. * * @return {string|undefined} * - The current aspect ratio of the `Player` when getting. * - undefined when setting */ ; _proto.aspectRatio = function aspectRatio(ratio) { if (ratio === undefined) { return this.aspectRatio_; } // Check for width:height format if (!/^\d+\:\d+$/.test(ratio)) { throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.'); } this.aspectRatio_ = ratio; // We're assuming if you set an aspect ratio you want fluid mode, // because in fixed mode you could calculate width and height yourself. this.fluid(true); this.updateStyleEl_(); } /** * Update styles of the `Player` element (height, width and aspect ratio). * * @private * @listens Tech#loadedmetadata */ ; _proto.updateStyleEl_ = function updateStyleEl_() { if (window$1.VIDEOJS_NO_DYNAMIC_STYLE === true) { var _width = typeof this.width_ === 'number' ? this.width_ : this.options_.width; var _height = typeof this.height_ === 'number' ? this.height_ : this.options_.height; var techEl = this.tech_ && this.tech_.el(); if (techEl) { if (_width >= 0) { techEl.width = _width; } if (_height >= 0) { techEl.height = _height; } } return; } var width; var height; var aspectRatio; var idClass; // The aspect ratio is either used directly or to calculate width and height. if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') { // Use any aspectRatio that's been specifically set aspectRatio = this.aspectRatio_; } else if (this.videoWidth() > 0) { // Otherwise try to get the aspect ratio from the video metadata aspectRatio = this.videoWidth() + ':' + this.videoHeight(); } else { // Or use a default. The video element's is 2:1, but 16:9 is more common. aspectRatio = '16:9'; } // Get the ratio as a decimal we can use to calculate dimensions var ratioParts = aspectRatio.split(':'); var ratioMultiplier = ratioParts[1] / ratioParts[0]; if (this.width_ !== undefined) { // Use any width that's been specifically set width = this.width_; } else if (this.height_ !== undefined) { // Or calulate the width from the aspect ratio if a height has been set width = this.height_ / ratioMultiplier; } else { // Or use the video's metadata, or use the video el's default of 300 width = this.videoWidth() || 300; } if (this.height_ !== undefined) { // Use any height that's been specifically set height = this.height_; } else { // Otherwise calculate the height from the ratio and the width height = width * ratioMultiplier; } // Ensure the CSS class is valid by starting with an alpha character if (/^[^a-zA-Z]/.test(this.id())) { idClass = 'dimensions-' + this.id(); } else { idClass = this.id() + '-dimensions'; } // Ensure the right class is still on the player for the style element this.addClass(idClass); setTextContent(this.styleEl_, "\n ." + idClass + " {\n width: " + width + "px;\n height: " + height + "px;\n }\n\n ." + idClass + ".vjs-fluid {\n padding-top: " + ratioMultiplier * 100 + "%;\n }\n "); } /** * Load/Create an instance of playback {@link Tech} including element * and API methods. Then append the `Tech` element in `Player` as a child. * * @param {string} techName * name of the playback technology * * @param {string} source * video source * * @private */ ; _proto.loadTech_ = function loadTech_(techName, source) { var _this3 = this; // Pause and remove current playback technology if (this.tech_) { this.unloadTech_(); } var titleTechName = toTitleCase(techName); var camelTechName = techName.charAt(0).toLowerCase() + techName.slice(1); // get rid of the HTML5 video tag as soon as we are using another tech if (titleTechName !== 'Html5' && this.tag) { Tech.getTech('Html5').disposeMediaElement(this.tag); this.tag.player = null; this.tag = null; } this.techName_ = titleTechName; // Turn off API access because we're loading a new tech that might load asynchronously this.isReady_ = false; // if autoplay is a string we pass false to the tech // because the player is going to handle autoplay on `loadstart` var autoplay = typeof this.autoplay() === 'string' ? false : this.autoplay(); // Grab tech-specific options from player options and add source and parent element to use. var techOptions = { source: source, autoplay: autoplay, 'nativeControlsForTouch': this.options_.nativeControlsForTouch, 'playerId': this.id(), 'techId': this.id() + "_" + camelTechName + "_api", 'playsinline': this.options_.playsinline, 'preload': this.options_.preload, 'loop': this.options_.loop, 'muted': this.options_.muted, 'poster': this.poster(), 'language': this.language(), 'playerElIngest': this.playerElIngest_ || false, 'vtt.js': this.options_['vtt.js'], 'canOverridePoster': !!this.options_.techCanOverridePoster, 'enableSourceset': this.options_.enableSourceset, 'Promise': this.options_.Promise }; ALL.names.forEach(function (name) { var props = ALL[name]; techOptions[props.getterName] = _this3[props.privateName]; }); assign(techOptions, this.options_[titleTechName]); assign(techOptions, this.options_[camelTechName]); assign(techOptions, this.options_[techName.toLowerCase()]); if (this.tag) { techOptions.tag = this.tag; } if (source && source.src === this.cache_.src && this.cache_.currentTime > 0) { techOptions.startTime = this.cache_.currentTime; } // Initialize tech instance var TechClass = Tech.getTech(techName); if (!TechClass) { throw new Error("No Tech named '" + titleTechName + "' exists! '" + titleTechName + "' should be registered using videojs.registerTech()'"); } this.tech_ = new TechClass(techOptions); // player.triggerReady is always async, so don't need this to be async this.tech_.ready(bind(this, this.handleTechReady_), true); textTrackConverter.jsonToTextTracks(this.textTracksJson_ || [], this.tech_); // Listen to all HTML5-defined events and trigger them on the player TECH_EVENTS_RETRIGGER.forEach(function (event) { _this3.on(_this3.tech_, event, _this3["handleTech" + toTitleCase(event) + "_"]); }); Object.keys(TECH_EVENTS_QUEUE).forEach(function (event) { _this3.on(_this3.tech_, event, function (eventObj) { if (_this3.tech_.playbackRate() === 0 && _this3.tech_.seeking()) { _this3.queuedCallbacks_.push({ callback: _this3["handleTech" + TECH_EVENTS_QUEUE[event] + "_"].bind(_this3), event: eventObj }); return; } _this3["handleTech" + TECH_EVENTS_QUEUE[event] + "_"](eventObj); }); }); this.on(this.tech_, 'loadstart', this.handleTechLoadStart_); this.on(this.tech_, 'sourceset', this.handleTechSourceset_); this.on(this.tech_, 'waiting', this.handleTechWaiting_); this.on(this.tech_, 'ended', this.handleTechEnded_); this.on(this.tech_, 'seeking', this.handleTechSeeking_); this.on(this.tech_, 'play', this.handleTechPlay_); this.on(this.tech_, 'firstplay', this.handleTechFirstPlay_); this.on(this.tech_, 'pause', this.handleTechPause_); this.on(this.tech_, 'durationchange', this.handleTechDurationChange_); this.on(this.tech_, 'fullscreenchange', this.handleTechFullscreenChange_); this.on(this.tech_, 'enterpictureinpicture', this.handleTechEnterPictureInPicture_); this.on(this.tech_, 'leavepictureinpicture', this.handleTechLeavePictureInPicture_); this.on(this.tech_, 'error', this.handleTechError_); this.on(this.tech_, 'loadedmetadata', this.updateStyleEl_); this.on(this.tech_, 'posterchange', this.handleTechPosterChange_); this.on(this.tech_, 'textdata', this.handleTechTextData_); this.on(this.tech_, 'ratechange', this.handleTechRateChange_); this.usingNativeControls(this.techGet_('controls')); if (this.controls() && !this.usingNativeControls()) { this.addTechControlsListeners_(); } // Add the tech element in the DOM if it was not already there // Make sure to not insert the original video element if using Html5 if (this.tech_.el().parentNode !== this.el() && (titleTechName !== 'Html5' || !this.tag)) { prependTo(this.tech_.el(), this.el()); } // Get rid of the original video tag reference after the first tech is loaded if (this.tag) { this.tag.player = null; this.tag = null; } } /** * Unload and dispose of the current playback {@link Tech}. * * @private */ ; _proto.unloadTech_ = function unloadTech_() { var _this4 = this; // Save the current text tracks so that we can reuse the same text tracks with the next tech ALL.names.forEach(function (name) { var props = ALL[name]; _this4[props.privateName] = _this4[props.getterName](); }); this.textTracksJson_ = textTrackConverter.textTracksToJson(this.tech_); this.isReady_ = false; this.tech_.dispose(); this.tech_ = false; if (this.isPosterFromTech_) { this.poster_ = ''; this.trigger('posterchange'); } this.isPosterFromTech_ = false; } /** * Return a reference to the current {@link Tech}. * It will print a warning by default about the danger of using the tech directly * but any argument that is passed in will silence the warning. * * @param {*} [safety] * Anything passed in to silence the warning * * @return {Tech} * The Tech */ ; _proto.tech = function tech(safety) { if (safety === undefined) { log.warn('Using the tech directly can be dangerous. I hope you know what you\'re doing.\n' + 'See https://github.com/videojs/video.js/issues/2617 for more info.\n'); } return this.tech_; } /** * Set up click and touch listeners for the playback element * * - On desktops: a click on the video itself will toggle playback * - On mobile devices: a click on the video toggles controls * which is done by toggling the user state between active and * inactive * - A tap can signal that a user has become active or has become inactive * e.g. a quick tap on an iPhone movie should reveal the controls. Another * quick tap should hide them again (signaling the user is in an inactive * viewing state) * - In addition to this, we still want the user to be considered inactive after * a few seconds of inactivity. * * > Note: the only part of iOS interaction we can't mimic with this setup * is a touch and hold on the video element counting as activity in order to * keep the controls showing, but that shouldn't be an issue. A touch and hold * on any controls will still keep the user active * * @private */ ; _proto.addTechControlsListeners_ = function addTechControlsListeners_() { // Make sure to remove all the previous listeners in case we are called multiple times. this.removeTechControlsListeners_(); // Some browsers (Chrome & IE) don't trigger a click on a flash swf, but do // trigger mousedown/up. // http://stackoverflow.com/questions/1444562/javascript-onclick-event-over-flash-object // Any touch events are set to block the mousedown event from happening this.on(this.tech_, 'mouseup', this.handleTechClick_); this.on(this.tech_, 'dblclick', this.handleTechDoubleClick_); // If the controls were hidden we don't want that to change without a tap event // so we'll check if the controls were already showing before reporting user // activity this.on(this.tech_, 'touchstart', this.handleTechTouchStart_); this.on(this.tech_, 'touchmove', this.handleTechTouchMove_); this.on(this.tech_, 'touchend', this.handleTechTouchEnd_); // The tap listener needs to come after the touchend listener because the tap // listener cancels out any reportedUserActivity when setting userActive(false) this.on(this.tech_, 'tap', this.handleTechTap_); } /** * Remove the listeners used for click and tap controls. This is needed for * toggling to controls disabled, where a tap/touch should do nothing. * * @private */ ; _proto.removeTechControlsListeners_ = function removeTechControlsListeners_() { // We don't want to just use `this.off()` because there might be other needed // listeners added by techs that extend this. this.off(this.tech_, 'tap', this.handleTechTap_); this.off(this.tech_, 'touchstart', this.handleTechTouchStart_); this.off(this.tech_, 'touchmove', this.handleTechTouchMove_); this.off(this.tech_, 'touchend', this.handleTechTouchEnd_); this.off(this.tech_, 'mouseup', this.handleTechClick_); this.off(this.tech_, 'dblclick', this.handleTechDoubleClick_); } /** * Player waits for the tech to be ready * * @private */ ; _proto.handleTechReady_ = function handleTechReady_() { this.triggerReady(); // Keep the same volume as before if (this.cache_.volume) { this.techCall_('setVolume', this.cache_.volume); } // Look if the tech found a higher resolution poster while loading this.handleTechPosterChange_(); // Update the duration if available this.handleTechDurationChange_(); } /** * Retrigger the `loadstart` event that was triggered by the {@link Tech}. This * function will also trigger {@link Player#firstplay} if it is the first loadstart * for a video. * * @fires Player#loadstart * @fires Player#firstplay * @listens Tech#loadstart * @private */ ; _proto.handleTechLoadStart_ = function handleTechLoadStart_() { // TODO: Update to use `emptied` event instead. See #1277. this.removeClass('vjs-ended'); this.removeClass('vjs-seeking'); // reset the error state this.error(null); // Update the duration this.handleTechDurationChange_(); // If it's already playing we want to trigger a firstplay event now. // The firstplay event relies on both the play and loadstart events // which can happen in any order for a new source if (!this.paused()) { /** * Fired when the user agent begins looking for media data * * @event Player#loadstart * @type {EventTarget~Event} */ this.trigger('loadstart'); this.trigger('firstplay'); } else { // reset the hasStarted state this.hasStarted(false); this.trigger('loadstart'); } // autoplay happens after loadstart for the browser, // so we mimic that behavior this.manualAutoplay_(this.autoplay()); } /** * Handle autoplay string values, rather than the typical boolean * values that should be handled by the tech. Note that this is not * part of any specification. Valid values and what they do can be * found on the autoplay getter at Player#autoplay() */ ; _proto.manualAutoplay_ = function manualAutoplay_(type) { var _this5 = this; if (!this.tech_ || typeof type !== 'string') { return; } var muted = function muted() { var previouslyMuted = _this5.muted(); _this5.muted(true); var restoreMuted = function restoreMuted() { _this5.muted(previouslyMuted); }; // restore muted on play terminatation _this5.playTerminatedQueue_.push(restoreMuted); var mutedPromise = _this5.play(); if (!isPromise(mutedPromise)) { return; } return mutedPromise["catch"](restoreMuted); }; var promise; // if muted defaults to true // the only thing we can do is call play if (type === 'any' && this.muted() !== true) { promise = this.play(); if (isPromise(promise)) { promise = promise["catch"](muted); } } else if (type === 'muted' && this.muted() !== true) { promise = muted(); } else { promise = this.play(); } if (!isPromise(promise)) { return; } return promise.then(function () { _this5.trigger({ type: 'autoplay-success', autoplay: type }); })["catch"](function (e) { _this5.trigger({ type: 'autoplay-failure', autoplay: type }); }); } /** * Update the internal source caches so that we return the correct source from * `src()`, `currentSource()`, and `currentSources()`. * * > Note: `currentSources` will not be updated if the source that is passed in exists * in the current `currentSources` cache. * * * @param {Tech~SourceObject} srcObj * A string or object source to update our caches to. */ ; _proto.updateSourceCaches_ = function updateSourceCaches_(srcObj) { if (srcObj === void 0) { srcObj = ''; } var src = srcObj; var type = ''; if (typeof src !== 'string') { src = srcObj.src; type = srcObj.type; } // make sure all the caches are set to default values // to prevent null checking this.cache_.source = this.cache_.source || {}; this.cache_.sources = this.cache_.sources || []; // try to get the type of the src that was passed in if (src && !type) { type = findMimetype(this, src); } // update `currentSource` cache always this.cache_.source = mergeOptions({}, srcObj, { src: src, type: type }); var matchingSources = this.cache_.sources.filter(function (s) { return s.src && s.src === src; }); var sourceElSources = []; var sourceEls = this.$$('source'); var matchingSourceEls = []; for (var i = 0; i < sourceEls.length; i++) { var sourceObj = getAttributes(sourceEls[i]); sourceElSources.push(sourceObj); if (sourceObj.src && sourceObj.src === src) { matchingSourceEls.push(sourceObj.src); } } // if we have matching source els but not matching sources // the current source cache is not up to date if (matchingSourceEls.length && !matchingSources.length) { this.cache_.sources = sourceElSources; // if we don't have matching source or source els set the // sources cache to the `currentSource` cache } else if (!matchingSources.length) { this.cache_.sources = [this.cache_.source]; } // update the tech `src` cache this.cache_.src = src; } /** * *EXPERIMENTAL* Fired when the source is set or changed on the {@link Tech} * causing the media element to reload. * * It will fire for the initial source and each subsequent source. * This event is a custom event from Video.js and is triggered by the {@link Tech}. * * The event object for this event contains a `src` property that will contain the source * that was available when the event was triggered. This is generally only necessary if Video.js * is switching techs while the source was being changed. * * It is also fired when `load` is called on the player (or media element) * because the {@link https://html.spec.whatwg.org/multipage/media.html#dom-media-load|specification for `load`} * says that the resource selection algorithm needs to be aborted and restarted. * In this case, it is very likely that the `src` property will be set to the * empty string `""` to indicate we do not know what the source will be but * that it is changing. * * *This event is currently still experimental and may change in minor releases.* * __To use this, pass `enableSourceset` option to the player.__ * * @event Player#sourceset * @type {EventTarget~Event} * @prop {string} src * The source url available when the `sourceset` was triggered. * It will be an empty string if we cannot know what the source is * but know that the source will change. */ /** * Retrigger the `sourceset` event that was triggered by the {@link Tech}. * * @fires Player#sourceset * @listens Tech#sourceset * @private */ ; _proto.handleTechSourceset_ = function handleTechSourceset_(event) { var _this6 = this; // only update the source cache when the source // was not updated using the player api if (!this.changingSrc_) { var updateSourceCaches = function updateSourceCaches(src) { return _this6.updateSourceCaches_(src); }; var playerSrc = this.currentSource().src; var eventSrc = event.src; // if we have a playerSrc that is not a blob, and a tech src that is a blob if (playerSrc && !/^blob:/.test(playerSrc) && /^blob:/.test(eventSrc)) { // if both the tech source and the player source were updated we assume // something like @videojs/http-streaming did the sourceset and skip updating the source cache. if (!this.lastSource_ || this.lastSource_.tech !== eventSrc && this.lastSource_.player !== playerSrc) { updateSourceCaches = function updateSourceCaches() {}; } } // update the source to the intial source right away // in some cases this will be empty string updateSourceCaches(eventSrc); // if the `sourceset` `src` was an empty string // wait for a `loadstart` to update the cache to `currentSrc`. // If a sourceset happens before a `loadstart`, we reset the state if (!event.src) { this.tech_.any(['sourceset', 'loadstart'], function (e) { // if a sourceset happens before a `loadstart` there // is nothing to do as this `handleTechSourceset_` // will be called again and this will be handled there. if (e.type === 'sourceset') { return; } var techSrc = _this6.techGet('currentSrc'); _this6.lastSource_.tech = techSrc; _this6.updateSourceCaches_(techSrc); }); } } this.lastSource_ = { player: this.currentSource().src, tech: event.src }; this.trigger({ src: event.src, type: 'sourceset' }); } /** * Add/remove the vjs-has-started class * * @fires Player#firstplay * * @param {boolean} request * - true: adds the class * - false: remove the class * * @return {boolean} * the boolean value of hasStarted_ */ ; _proto.hasStarted = function hasStarted(request) { if (request === undefined) { // act as getter, if we have no request to change return this.hasStarted_; } if (request === this.hasStarted_) { return; } this.hasStarted_ = request; if (this.hasStarted_) { this.addClass('vjs-has-started'); this.trigger('firstplay'); } else { this.removeClass('vjs-has-started'); } } /** * Fired whenever the media begins or resumes playback * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play} * @fires Player#play * @listens Tech#play * @private */ ; _proto.handleTechPlay_ = function handleTechPlay_() { this.removeClass('vjs-ended'); this.removeClass('vjs-paused'); this.addClass('vjs-playing'); // hide the poster when the user hits play this.hasStarted(true); /** * Triggered whenever an {@link Tech#play} event happens. Indicates that * playback has started or resumed. * * @event Player#play * @type {EventTarget~Event} */ this.trigger('play'); } /** * Retrigger the `ratechange` event that was triggered by the {@link Tech}. * * If there were any events queued while the playback rate was zero, fire * those events now. * * @private * @method Player#handleTechRateChange_ * @fires Player#ratechange * @listens Tech#ratechange */ ; _proto.handleTechRateChange_ = function handleTechRateChange_() { if (this.tech_.playbackRate() > 0 && this.cache_.lastPlaybackRate === 0) { this.queuedCallbacks_.forEach(function (queued) { return queued.callback(queued.event); }); this.queuedCallbacks_ = []; } this.cache_.lastPlaybackRate = this.tech_.playbackRate(); /** * Fires when the playing speed of the audio/video is changed * * @event Player#ratechange * @type {event} */ this.trigger('ratechange'); } /** * Retrigger the `waiting` event that was triggered by the {@link Tech}. * * @fires Player#waiting * @listens Tech#waiting * @private */ ; _proto.handleTechWaiting_ = function handleTechWaiting_() { var _this7 = this; this.addClass('vjs-waiting'); /** * A readyState change on the DOM element has caused playback to stop. * * @event Player#waiting * @type {EventTarget~Event} */ this.trigger('waiting'); // Browsers may emit a timeupdate event after a waiting event. In order to prevent // premature removal of the waiting class, wait for the time to change. var timeWhenWaiting = this.currentTime(); var timeUpdateListener = function timeUpdateListener() { if (timeWhenWaiting !== _this7.currentTime()) { _this7.removeClass('vjs-waiting'); _this7.off('timeupdate', timeUpdateListener); } }; this.on('timeupdate', timeUpdateListener); } /** * Retrigger the `canplay` event that was triggered by the {@link Tech}. * > Note: This is not consistent between browsers. See #1351 * * @fires Player#canplay * @listens Tech#canplay * @private */ ; _proto.handleTechCanPlay_ = function handleTechCanPlay_() { this.removeClass('vjs-waiting'); /** * The media has a readyState of HAVE_FUTURE_DATA or greater. * * @event Player#canplay * @type {EventTarget~Event} */ this.trigger('canplay'); } /** * Retrigger the `canplaythrough` event that was triggered by the {@link Tech}. * * @fires Player#canplaythrough * @listens Tech#canplaythrough * @private */ ; _proto.handleTechCanPlayThrough_ = function handleTechCanPlayThrough_() { this.removeClass('vjs-waiting'); /** * The media has a readyState of HAVE_ENOUGH_DATA or greater. This means that the * entire media file can be played without buffering. * * @event Player#canplaythrough * @type {EventTarget~Event} */ this.trigger('canplaythrough'); } /** * Retrigger the `playing` event that was triggered by the {@link Tech}. * * @fires Player#playing * @listens Tech#playing * @private */ ; _proto.handleTechPlaying_ = function handleTechPlaying_() { this.removeClass('vjs-waiting'); /** * The media is no longer blocked from playback, and has started playing. * * @event Player#playing * @type {EventTarget~Event} */ this.trigger('playing'); } /** * Retrigger the `seeking` event that was triggered by the {@link Tech}. * * @fires Player#seeking * @listens Tech#seeking * @private */ ; _proto.handleTechSeeking_ = function handleTechSeeking_() { this.addClass('vjs-seeking'); /** * Fired whenever the player is jumping to a new time * * @event Player#seeking * @type {EventTarget~Event} */ this.trigger('seeking'); } /** * Retrigger the `seeked` event that was triggered by the {@link Tech}. * * @fires Player#seeked * @listens Tech#seeked * @private */ ; _proto.handleTechSeeked_ = function handleTechSeeked_() { this.removeClass('vjs-seeking'); this.removeClass('vjs-ended'); /** * Fired when the player has finished jumping to a new time * * @event Player#seeked * @type {EventTarget~Event} */ this.trigger('seeked'); } /** * Retrigger the `firstplay` event that was triggered by the {@link Tech}. * * @fires Player#firstplay * @listens Tech#firstplay * @deprecated As of 6.0 firstplay event is deprecated. * As of 6.0 passing the `starttime` option to the player and the firstplay event are deprecated. * @private */ ; _proto.handleTechFirstPlay_ = function handleTechFirstPlay_() { // If the first starttime attribute is specified // then we will start at the given offset in seconds if (this.options_.starttime) { log.warn('Passing the `starttime` option to the player will be deprecated in 6.0'); this.currentTime(this.options_.starttime); } this.addClass('vjs-has-started'); /** * Fired the first time a video is played. Not part of the HLS spec, and this is * probably not the best implementation yet, so use sparingly. If you don't have a * reason to prevent playback, use `myPlayer.one('play');` instead. * * @event Player#firstplay * @deprecated As of 6.0 firstplay event is deprecated. * @type {EventTarget~Event} */ this.trigger('firstplay'); } /** * Retrigger the `pause` event that was triggered by the {@link Tech}. * * @fires Player#pause * @listens Tech#pause * @private */ ; _proto.handleTechPause_ = function handleTechPause_() { this.removeClass('vjs-playing'); this.addClass('vjs-paused'); /** * Fired whenever the media has been paused * * @event Player#pause * @type {EventTarget~Event} */ this.trigger('pause'); } /** * Retrigger the `ended` event that was triggered by the {@link Tech}. * * @fires Player#ended * @listens Tech#ended * @private */ ; _proto.handleTechEnded_ = function handleTechEnded_() { this.addClass('vjs-ended'); if (this.options_.loop) { this.currentTime(0); this.play(); } else if (!this.paused()) { this.pause(); } /** * Fired when the end of the media resource is reached (currentTime == duration) * * @event Player#ended * @type {EventTarget~Event} */ this.trigger('ended'); } /** * Fired when the duration of the media resource is first known or changed * * @listens Tech#durationchange * @private */ ; _proto.handleTechDurationChange_ = function handleTechDurationChange_() { this.duration(this.techGet_('duration')); } /** * Handle a click on the media element to play/pause * * @param {EventTarget~Event} event * the event that caused this function to trigger * * @listens Tech#mouseup * @private */ ; _proto.handleTechClick_ = function handleTechClick_(event) { if (!isSingleLeftClick(event)) { return; } // When controls are disabled a click should not toggle playback because // the click is considered a control if (!this.controls_) { return; } if (this.paused()) { silencePromise(this.play()); } else { this.pause(); } } /** * Handle a double-click on the media element to enter/exit fullscreen * * @param {EventTarget~Event} event * the event that caused this function to trigger * * @listens Tech#dblclick * @private */ ; _proto.handleTechDoubleClick_ = function handleTechDoubleClick_(event) { if (!this.controls_) { return; } // we do not want to toggle fullscreen state // when double-clicking inside a control bar or a modal var inAllowedEls = Array.prototype.some.call(this.$$('.vjs-control-bar, .vjs-modal-dialog'), function (el) { return el.contains(event.target); }); if (!inAllowedEls) { /* * options.userActions.doubleClick * * If `undefined` or `true`, double-click toggles fullscreen if controls are present * Set to `false` to disable double-click handling * Set to a function to substitute an external double-click handler */ if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.doubleClick === undefined || this.options_.userActions.doubleClick !== false) { if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.doubleClick === 'function') { this.options_.userActions.doubleClick.call(this, event); } else if (this.isFullscreen()) { this.exitFullscreen(); } else { this.requestFullscreen(); } } } } /** * Handle a tap on the media element. It will toggle the user * activity state, which hides and shows the controls. * * @listens Tech#tap * @private */ ; _proto.handleTechTap_ = function handleTechTap_() { this.userActive(!this.userActive()); } /** * Handle touch to start * * @listens Tech#touchstart * @private */ ; _proto.handleTechTouchStart_ = function handleTechTouchStart_() { this.userWasActive = this.userActive(); } /** * Handle touch to move * * @listens Tech#touchmove * @private */ ; _proto.handleTechTouchMove_ = function handleTechTouchMove_() { if (this.userWasActive) { this.reportUserActivity(); } } /** * Handle touch to end * * @param {EventTarget~Event} event * the touchend event that triggered * this function * * @listens Tech#touchend * @private */ ; _proto.handleTechTouchEnd_ = function handleTechTouchEnd_(event) { // Stop the mouse events from also happening event.preventDefault(); } /** * native click events on the SWF aren't triggered on IE11, Win8.1RT * use stageclick events triggered from inside the SWF instead * * @private * @listens stageclick */ ; _proto.handleStageClick_ = function handleStageClick_() { this.reportUserActivity(); } /** * @private */ ; _proto.toggleFullscreenClass_ = function toggleFullscreenClass_() { if (this.isFullscreen()) { this.addClass('vjs-fullscreen'); } else { this.removeClass('vjs-fullscreen'); } } /** * when the document fschange event triggers it calls this */ ; _proto.documentFullscreenChange_ = function documentFullscreenChange_(e) { var el = this.el(); var isFs = document[this.fsApi_.fullscreenElement] === el; if (!isFs && el.matches) { isFs = el.matches(':' + this.fsApi_.fullscreen); } else if (!isFs && el.msMatchesSelector) { isFs = el.msMatchesSelector(':' + this.fsApi_.fullscreen); } this.isFullscreen(isFs); // If cancelling fullscreen, remove event listener. if (this.isFullscreen() === false) { off(document, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_); } if (this.fsApi_.prefixed) { /** * @event Player#fullscreenchange * @type {EventTarget~Event} */ this.trigger('fullscreenchange'); } } /** * Handle Tech Fullscreen Change * * @param {EventTarget~Event} event * the fullscreenchange event that triggered this function * * @param {Object} data * the data that was sent with the event * * @private * @listens Tech#fullscreenchange * @fires Player#fullscreenchange */ ; _proto.handleTechFullscreenChange_ = function handleTechFullscreenChange_(event, data) { if (data) { this.isFullscreen(data.isFullscreen); } /** * Fired when going in and out of fullscreen. * * @event Player#fullscreenchange * @type {EventTarget~Event} */ this.trigger('fullscreenchange'); } /** * @private */ ; _proto.togglePictureInPictureClass_ = function togglePictureInPictureClass_() { if (this.isInPictureInPicture()) { this.addClass('vjs-picture-in-picture'); } else { this.removeClass('vjs-picture-in-picture'); } } /** * Handle Tech Enter Picture-in-Picture. * * @param {EventTarget~Event} event * the enterpictureinpicture event that triggered this function * * @private * @listens Tech#enterpictureinpicture */ ; _proto.handleTechEnterPictureInPicture_ = function handleTechEnterPictureInPicture_(event) { this.isInPictureInPicture(true); } /** * Handle Tech Leave Picture-in-Picture. * * @param {EventTarget~Event} event * the leavepictureinpicture event that triggered this function * * @private * @listens Tech#leavepictureinpicture */ ; _proto.handleTechLeavePictureInPicture_ = function handleTechLeavePictureInPicture_(event) { this.isInPictureInPicture(false); } /** * Fires when an error occurred during the loading of an audio/video. * * @private * @listens Tech#error */ ; _proto.handleTechError_ = function handleTechError_() { var error = this.tech_.error(); this.error(error); } /** * Retrigger the `textdata` event that was triggered by the {@link Tech}. * * @fires Player#textdata * @listens Tech#textdata * @private */ ; _proto.handleTechTextData_ = function handleTechTextData_() { var data = null; if (arguments.length > 1) { data = arguments[1]; } /** * Fires when we get a textdata event from tech * * @event Player#textdata * @type {EventTarget~Event} */ this.trigger('textdata', data); } /** * Get object for cached values. * * @return {Object} * get the current object cache */ ; _proto.getCache = function getCache() { return this.cache_; } /** * Resets the internal cache object. * * Using this function outside the player constructor or reset method may * have unintended side-effects. * * @private */ ; _proto.resetCache_ = function resetCache_() { this.cache_ = { // Right now, the currentTime is not _really_ cached because it is always // retrieved from the tech (see: currentTime). However, for completeness, // we set it to zero here to ensure that if we do start actually caching // it, we reset it along with everything else. currentTime: 0, inactivityTimeout: this.options_.inactivityTimeout, duration: NaN, lastVolume: 1, lastPlaybackRate: this.defaultPlaybackRate(), media: null, src: '', source: {}, sources: [], volume: 1 }; } /** * Pass values to the playback tech * * @param {string} [method] * the method to call * * @param {Object} arg * the argument to pass * * @private */ ; _proto.techCall_ = function techCall_(method, arg) { // If it's not ready yet, call method when it is this.ready(function () { if (method in allowedSetters) { return set(this.middleware_, this.tech_, method, arg); } else if (method in allowedMediators) { return mediate(this.middleware_, this.tech_, method, arg); } try { if (this.tech_) { this.tech_[method](arg); } } catch (e) { log(e); throw e; } }, true); } /** * Get calls can't wait for the tech, and sometimes don't need to. * * @param {string} method * Tech method * * @return {Function|undefined} * the method or undefined * * @private */ ; _proto.techGet_ = function techGet_(method) { if (!this.tech_ || !this.tech_.isReady_) { return; } if (method in allowedGetters) { return get(this.middleware_, this.tech_, method); } else if (method in allowedMediators) { return mediate(this.middleware_, this.tech_, method); } // Flash likes to die and reload when you hide or reposition it. // In these cases the object methods go away and we get errors. // When that happens we'll catch the errors and inform tech that it's not ready any more. try { return this.tech_[method](); } catch (e) { // When building additional tech libs, an expected method may not be defined yet if (this.tech_[method] === undefined) { log("Video.js: " + method + " method not defined for " + this.techName_ + " playback technology.", e); throw e; } // When a method isn't available on the object it throws a TypeError if (e.name === 'TypeError') { log("Video.js: " + method + " unavailable on " + this.techName_ + " playback technology element.", e); this.tech_.isReady_ = false; throw e; } // If error unknown, just log and throw log(e); throw e; } } /** * Attempt to begin playback at the first opportunity. * * @return {Promise|undefined} * Returns a promise if the browser supports Promises (or one * was passed in as an option). This promise will be resolved on * the return value of play. If this is undefined it will fulfill the * promise chain otherwise the promise chain will be fulfilled when * the promise from play is fulfilled. */ ; _proto.play = function play() { var _this8 = this; var PromiseClass = this.options_.Promise || window$1.Promise; if (PromiseClass) { return new PromiseClass(function (resolve) { _this8.play_(resolve); }); } return this.play_(); } /** * The actual logic for play, takes a callback that will be resolved on the * return value of play. This allows us to resolve to the play promise if there * is one on modern browsers. * * @private * @param {Function} [callback] * The callback that should be called when the techs play is actually called */ ; _proto.play_ = function play_(callback) { var _this9 = this; if (callback === void 0) { callback = silencePromise; } this.playCallbacks_.push(callback); var isSrcReady = Boolean(!this.changingSrc_ && (this.src() || this.currentSrc())); // treat calls to play_ somewhat like the `one` event function if (this.waitToPlay_) { this.off(['ready', 'loadstart'], this.waitToPlay_); this.waitToPlay_ = null; } // if the player/tech is not ready or the src itself is not ready // queue up a call to play on `ready` or `loadstart` if (!this.isReady_ || !isSrcReady) { this.waitToPlay_ = function (e) { _this9.play_(); }; this.one(['ready', 'loadstart'], this.waitToPlay_); // if we are in Safari, there is a high chance that loadstart will trigger after the gesture timeperiod // in that case, we need to prime the video element by calling load so it'll be ready in time if (!isSrcReady && (IS_ANY_SAFARI || IS_IOS)) { this.load(); } return; } // If the player/tech is ready and we have a source, we can attempt playback. var val = this.techGet_('play'); // play was terminated if the returned value is null if (val === null) { this.runPlayTerminatedQueue_(); } else { this.runPlayCallbacks_(val); } } /** * These functions will be run when if play is terminated. If play * runPlayCallbacks_ is run these function will not be run. This allows us * to differenciate between a terminated play and an actual call to play. */ ; _proto.runPlayTerminatedQueue_ = function runPlayTerminatedQueue_() { var queue = this.playTerminatedQueue_.slice(0); this.playTerminatedQueue_ = []; queue.forEach(function (q) { q(); }); } /** * When a callback to play is delayed we have to run these * callbacks when play is actually called on the tech. This function * runs the callbacks that were delayed and accepts the return value * from the tech. * * @param {undefined|Promise} val * The return value from the tech. */ ; _proto.runPlayCallbacks_ = function runPlayCallbacks_(val) { var callbacks = this.playCallbacks_.slice(0); this.playCallbacks_ = []; // clear play terminatedQueue since we finished a real play this.playTerminatedQueue_ = []; callbacks.forEach(function (cb) { cb(val); }); } /** * Pause the video playback * * @return {Player} * A reference to the player object this function was called on */ ; _proto.pause = function pause() { this.techCall_('pause'); } /** * Check if the player is paused or has yet to play * * @return {boolean} * - false: if the media is currently playing * - true: if media is not currently playing */ ; _proto.paused = function paused() { // The initial state of paused should be true (in Safari it's actually false) return this.techGet_('paused') === false ? false : true; } /** * Get a TimeRange object representing the current ranges of time that the user * has played. * * @return {TimeRange} * A time range object that represents all the increments of time that have * been played. */ ; _proto.played = function played() { return this.techGet_('played') || createTimeRanges(0, 0); } /** * Returns whether or not the user is "scrubbing". Scrubbing is * when the user has clicked the progress bar handle and is * dragging it along the progress bar. * * @param {boolean} [isScrubbing] * whether the user is or is not scrubbing * * @return {boolean} * The value of scrubbing when getting */ ; _proto.scrubbing = function scrubbing(isScrubbing) { if (typeof isScrubbing === 'undefined') { return this.scrubbing_; } this.scrubbing_ = !!isScrubbing; if (isScrubbing) { this.addClass('vjs-scrubbing'); } else { this.removeClass('vjs-scrubbing'); } } /** * Get or set the current time (in seconds) * * @param {number|string} [seconds] * The time to seek to in seconds * * @return {number} * - the current time in seconds when getting */ ; _proto.currentTime = function currentTime(seconds) { if (typeof seconds !== 'undefined') { if (seconds < 0) { seconds = 0; } this.techCall_('setCurrentTime', seconds); return; } // cache last currentTime and return. default to 0 seconds // // Caching the currentTime is meant to prevent a massive amount of reads on the tech's // currentTime when scrubbing, but may not provide much performance benefit afterall. // Should be tested. Also something has to read the actual current time or the cache will // never get updated. this.cache_.currentTime = this.techGet_('currentTime') || 0; return this.cache_.currentTime; } /** * Normally gets the length in time of the video in seconds; * in all but the rarest use cases an argument will NOT be passed to the method * * > **NOTE**: The video must have started loading before the duration can be * known, and in the case of Flash, may not be known until the video starts * playing. * * @fires Player#durationchange * * @param {number} [seconds] * The duration of the video to set in seconds * * @return {number} * - The duration of the video in seconds when getting */ ; _proto.duration = function duration(seconds) { if (seconds === undefined) { // return NaN if the duration is not known return this.cache_.duration !== undefined ? this.cache_.duration : NaN; } seconds = parseFloat(seconds); // Standardize on Infinity for signaling video is live if (seconds < 0) { seconds = Infinity; } if (seconds !== this.cache_.duration) { // Cache the last set value for optimized scrubbing (esp. Flash) this.cache_.duration = seconds; if (seconds === Infinity) { this.addClass('vjs-live'); if (this.options_.liveui && this.player_.liveTracker) { this.addClass('vjs-liveui'); } } else { this.removeClass('vjs-live'); this.removeClass('vjs-liveui'); } if (!isNaN(seconds)) { // Do not fire durationchange unless the duration value is known. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm} /** * @event Player#durationchange * @type {EventTarget~Event} */ this.trigger('durationchange'); } } } /** * Calculates how much time is left in the video. Not part * of the native video API. * * @return {number} * The time remaining in seconds */ ; _proto.remainingTime = function remainingTime() { return this.duration() - this.currentTime(); } /** * A remaining time function that is intented to be used when * the time is to be displayed directly to the user. * * @return {number} * The rounded time remaining in seconds */ ; _proto.remainingTimeDisplay = function remainingTimeDisplay() { return Math.floor(this.duration()) - Math.floor(this.currentTime()); } // // Kind of like an array of portions of the video that have been downloaded. /** * Get a TimeRange object with an array of the times of the video * that have been downloaded. If you just want the percent of the * video that's been downloaded, use bufferedPercent. * * @see [Buffered Spec]{@link http://dev.w3.org/html5/spec/video.html#dom-media-buffered} * * @return {TimeRange} * A mock TimeRange object (following HTML spec) */ ; _proto.buffered = function buffered() { var buffered = this.techGet_('buffered'); if (!buffered || !buffered.length) { buffered = createTimeRanges(0, 0); } return buffered; } /** * Get the percent (as a decimal) of the video that's been downloaded. * This method is not a part of the native HTML video API. * * @return {number} * A decimal between 0 and 1 representing the percent * that is buffered 0 being 0% and 1 being 100% */ ; _proto.bufferedPercent = function bufferedPercent$1() { return bufferedPercent(this.buffered(), this.duration()); } /** * Get the ending time of the last buffered time range * This is used in the progress bar to encapsulate all time ranges. * * @return {number} * The end of the last buffered time range */ ; _proto.bufferedEnd = function bufferedEnd() { var buffered = this.buffered(); var duration = this.duration(); var end = buffered.end(buffered.length - 1); if (end > duration) { end = duration; } return end; } /** * Get or set the current volume of the media * * @param {number} [percentAsDecimal] * The new volume as a decimal percent: * - 0 is muted/0%/off * - 1.0 is 100%/full * - 0.5 is half volume or 50% * * @return {number} * The current volume as a percent when getting */ ; _proto.volume = function volume(percentAsDecimal) { var vol; if (percentAsDecimal !== undefined) { // Force value to between 0 and 1 vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal))); this.cache_.volume = vol; this.techCall_('setVolume', vol); if (vol > 0) { this.lastVolume_(vol); } return; } // Default to 1 when returning current volume. vol = parseFloat(this.techGet_('volume')); return isNaN(vol) ? 1 : vol; } /** * Get the current muted state, or turn mute on or off * * @param {boolean} [muted] * - true to mute * - false to unmute * * @return {boolean} * - true if mute is on and getting * - false if mute is off and getting */ ; _proto.muted = function muted(_muted) { if (_muted !== undefined) { this.techCall_('setMuted', _muted); return; } return this.techGet_('muted') || false; } /** * Get the current defaultMuted state, or turn defaultMuted on or off. defaultMuted * indicates the state of muted on initial playback. * * ```js * var myPlayer = videojs('some-player-id'); * * myPlayer.src("http://www.example.com/path/to/video.mp4"); * * // get, should be false * console.log(myPlayer.defaultMuted()); * // set to true * myPlayer.defaultMuted(true); * // get should be true * console.log(myPlayer.defaultMuted()); * ``` * * @param {boolean} [defaultMuted] * - true to mute * - false to unmute * * @return {boolean|Player} * - true if defaultMuted is on and getting * - false if defaultMuted is off and getting * - A reference to the current player when setting */ ; _proto.defaultMuted = function defaultMuted(_defaultMuted) { if (_defaultMuted !== undefined) { return this.techCall_('setDefaultMuted', _defaultMuted); } return this.techGet_('defaultMuted') || false; } /** * Get the last volume, or set it * * @param {number} [percentAsDecimal] * The new last volume as a decimal percent: * - 0 is muted/0%/off * - 1.0 is 100%/full * - 0.5 is half volume or 50% * * @return {number} * the current value of lastVolume as a percent when getting * * @private */ ; _proto.lastVolume_ = function lastVolume_(percentAsDecimal) { if (percentAsDecimal !== undefined && percentAsDecimal !== 0) { this.cache_.lastVolume = percentAsDecimal; return; } return this.cache_.lastVolume; } /** * Check if current tech can support native fullscreen * (e.g. with built in controls like iOS, so not our flash swf) * * @return {boolean} * if native fullscreen is supported */ ; _proto.supportsFullScreen = function supportsFullScreen() { return this.techGet_('supportsFullScreen') || false; } /** * Check if the player is in fullscreen mode or tell the player that it * is or is not in fullscreen mode. * * > NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official * property and instead document.fullscreenElement is used. But isFullscreen is * still a valuable property for internal player workings. * * @param {boolean} [isFS] * Set the players current fullscreen state * * @return {boolean} * - true if fullscreen is on and getting * - false if fullscreen is off and getting */ ; _proto.isFullscreen = function isFullscreen(isFS) { if (isFS !== undefined) { this.isFullscreen_ = !!isFS; this.toggleFullscreenClass_(); return; } return !!this.isFullscreen_; } /** * Increase the size of the video to full screen * In some browsers, full screen is not supported natively, so it enters * "full window mode", where the video fills the browser window. * In browsers and devices that support native full screen, sometimes the * browser's default controls will be shown, and not the Video.js custom skin. * This includes most mobile devices (iOS, Android) and older versions of * Safari. * * @param {Object} [fullscreenOptions] * Override the player fullscreen options * * @fires Player#fullscreenchange */ ; _proto.requestFullscreen = function requestFullscreen(fullscreenOptions) { var fsOptions; this.isFullscreen(true); if (this.fsApi_.requestFullscreen) { // the browser supports going fullscreen at the element level so we can // take the controls fullscreen as well as the video // Trigger fullscreenchange event after change // We have to specifically add this each time, and remove // when canceling fullscreen. Otherwise if there's multiple // players on a page, they would all be reacting to the same fullscreen // events on(document, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_); // only pass FullscreenOptions to requestFullscreen if it isn't prefixed if (!this.fsApi_.prefixed) { fsOptions = this.options_.fullscreen && this.options_.fullscreen.options || {}; if (fullscreenOptions !== undefined) { fsOptions = fullscreenOptions; } } silencePromise(this.el_[this.fsApi_.requestFullscreen](fsOptions)); } else if (this.tech_.supportsFullScreen()) { // we can't take the video.js controls fullscreen but we can go fullscreen // with native controls this.techCall_('enterFullScreen'); } else { // fullscreen isn't supported so we'll just stretch the video element to // fill the viewport this.enterFullWindow(); /** * @event Player#fullscreenchange * @type {EventTarget~Event} */ this.trigger('fullscreenchange'); } } /** * Return the video to its normal size after having been in full screen mode * * @fires Player#fullscreenchange */ ; _proto.exitFullscreen = function exitFullscreen() { this.isFullscreen(false); // Check for browser element fullscreen support if (this.fsApi_.requestFullscreen) { silencePromise(document[this.fsApi_.exitFullscreen]()); } else if (this.tech_.supportsFullScreen()) { this.techCall_('exitFullScreen'); } else { this.exitFullWindow(); /** * @event Player#fullscreenchange * @type {EventTarget~Event} */ this.trigger('fullscreenchange'); } } /** * When fullscreen isn't supported we can stretch the * video container to as wide as the browser will let us. * * @fires Player#enterFullWindow */ ; _proto.enterFullWindow = function enterFullWindow() { this.isFullWindow = true; // Storing original doc overflow value to return to when fullscreen is off this.docOrigOverflow = document.documentElement.style.overflow; // Add listener for esc key to exit fullscreen on(document, 'keydown', this.boundFullWindowOnEscKey_); // Hide any scroll bars document.documentElement.style.overflow = 'hidden'; // Apply fullscreen styles addClass(document.body, 'vjs-full-window'); /** * @event Player#enterFullWindow * @type {EventTarget~Event} */ this.trigger('enterFullWindow'); } /** * Check for call to either exit full window or * full screen on ESC key * * @param {string} event * Event to check for key press */ ; _proto.fullWindowOnEscKey = function fullWindowOnEscKey(event) { if (keycode.isEventKey(event, 'Esc')) { if (this.isFullscreen() === true) { this.exitFullscreen(); } else { this.exitFullWindow(); } } } /** * Exit full window * * @fires Player#exitFullWindow */ ; _proto.exitFullWindow = function exitFullWindow() { this.isFullWindow = false; off(document, 'keydown', this.boundFullWindowOnEscKey_); // Unhide scroll bars. document.documentElement.style.overflow = this.docOrigOverflow; // Remove fullscreen styles removeClass(document.body, 'vjs-full-window'); // Resize the box, controller, and poster to original sizes // this.positionAll(); /** * @event Player#exitFullWindow * @type {EventTarget~Event} */ this.trigger('exitFullWindow'); } /** * Check if the player is in Picture-in-Picture mode or tell the player that it * is or is not in Picture-in-Picture mode. * * @param {boolean} [isPiP] * Set the players current Picture-in-Picture state * * @return {boolean} * - true if Picture-in-Picture is on and getting * - false if Picture-in-Picture is off and getting */ ; _proto.isInPictureInPicture = function isInPictureInPicture(isPiP) { if (isPiP !== undefined) { this.isInPictureInPicture_ = !!isPiP; this.togglePictureInPictureClass_(); return; } return !!this.isInPictureInPicture_; } /** * Create a floating video window always on top of other windows so that users may * continue consuming media while they interact with other content sites, or * applications on their device. * * @see [Spec]{@link https://wicg.github.io/picture-in-picture} * * @fires Player#enterpictureinpicture * * @return {Promise} * A promise with a Picture-in-Picture window. */ ; _proto.requestPictureInPicture = function requestPictureInPicture() { if ('pictureInPictureEnabled' in document) { /** * This event fires when the player enters picture in picture mode * * @event Player#enterpictureinpicture * @type {EventTarget~Event} */ return this.techGet_('requestPictureInPicture'); } } /** * Exit Picture-in-Picture mode. * * @see [Spec]{@link https://wicg.github.io/picture-in-picture} * * @fires Player#leavepictureinpicture * * @return {Promise} * A promise. */ ; _proto.exitPictureInPicture = function exitPictureInPicture() { if ('pictureInPictureEnabled' in document) { /** * This event fires when the player leaves picture in picture mode * * @event Player#leavepictureinpicture * @type {EventTarget~Event} */ return document.exitPictureInPicture(); } } /** * Called when this Player has focus and a key gets pressed down, or when * any Component of this player receives a key press that it doesn't handle. * This allows player-wide hotkeys (either as defined below, or optionally * by an external function). * * @param {EventTarget~Event} event * The `keydown` event that caused this function to be called. * * @listens keydown */ ; _proto.handleKeyDown = function handleKeyDown(event) { var userActions = this.options_.userActions; // Bail out if hotkeys are not configured. if (!userActions || !userActions.hotkeys) { return; } // Function that determines whether or not to exclude an element from // hotkeys handling. var excludeElement = function excludeElement(el) { var tagName = el.tagName.toLowerCase(); // The first and easiest test is for `contenteditable` elements. if (el.isContentEditable) { return true; } // Inputs matching these types will still trigger hotkey handling as // they are not text inputs. var allowedInputTypes = ['button', 'checkbox', 'hidden', 'radio', 'reset', 'submit']; if (tagName === 'input') { return allowedInputTypes.indexOf(el.type) === -1; } // The final test is by tag name. These tags will be excluded entirely. var excludedTags = ['textarea']; return excludedTags.indexOf(tagName) !== -1; }; // Bail out if the user is focused on an interactive form element. if (excludeElement(this.el_.ownerDocument.activeElement)) { return; } if (typeof userActions.hotkeys === 'function') { userActions.hotkeys.call(this, event); } else { this.handleHotkeys(event); } } /** * Called when this Player receives a hotkey keydown event. * Supported player-wide hotkeys are: * * f - toggle fullscreen * m - toggle mute * k or Space - toggle play/pause * * @param {EventTarget~Event} event * The `keydown` event that caused this function to be called. */ ; _proto.handleHotkeys = function handleHotkeys(event) { var hotkeys = this.options_.userActions ? this.options_.userActions.hotkeys : {}; // set fullscreenKey, muteKey, playPauseKey from `hotkeys`, use defaults if not set var _hotkeys$fullscreenKe = hotkeys.fullscreenKey, fullscreenKey = _hotkeys$fullscreenKe === void 0 ? function (keydownEvent) { return keycode.isEventKey(keydownEvent, 'f'); } : _hotkeys$fullscreenKe, _hotkeys$muteKey = hotkeys.muteKey, muteKey = _hotkeys$muteKey === void 0 ? function (keydownEvent) { return keycode.isEventKey(keydownEvent, 'm'); } : _hotkeys$muteKey, _hotkeys$playPauseKey = hotkeys.playPauseKey, playPauseKey = _hotkeys$playPauseKey === void 0 ? function (keydownEvent) { return keycode.isEventKey(keydownEvent, 'k') || keycode.isEventKey(keydownEvent, 'Space'); } : _hotkeys$playPauseKey; if (fullscreenKey.call(this, event)) { event.preventDefault(); event.stopPropagation(); var FSToggle = Component.getComponent('FullscreenToggle'); if (document[this.fsApi_.fullscreenEnabled] !== false) { FSToggle.prototype.handleClick.call(this, event); } } else if (muteKey.call(this, event)) { event.preventDefault(); event.stopPropagation(); var MuteToggle = Component.getComponent('MuteToggle'); MuteToggle.prototype.handleClick.call(this, event); } else if (playPauseKey.call(this, event)) { event.preventDefault(); event.stopPropagation(); var PlayToggle = Component.getComponent('PlayToggle'); PlayToggle.prototype.handleClick.call(this, event); } } /** * Check whether the player can play a given mimetype * * @see https://www.w3.org/TR/2011/WD-html5-20110113/video.html#dom-navigator-canplaytype * * @param {string} type * The mimetype to check * * @return {string} * 'probably', 'maybe', or '' (empty string) */ ; _proto.canPlayType = function canPlayType(type) { var can; // Loop through each playback technology in the options order for (var i = 0, j = this.options_.techOrder; i < j.length; i++) { var techName = j[i]; var tech = Tech.getTech(techName); // Support old behavior of techs being registered as components. // Remove once that deprecated behavior is removed. if (!tech) { tech = Component.getComponent(techName); } // Check if the current tech is defined before continuing if (!tech) { log.error("The \"" + techName + "\" tech is undefined. Skipped browser support check for that tech."); continue; } // Check if the browser supports this technology if (tech.isSupported()) { can = tech.canPlayType(type); if (can) { return can; } } } return ''; } /** * Select source based on tech-order or source-order * Uses source-order selection if `options.sourceOrder` is truthy. Otherwise, * defaults to tech-order selection * * @param {Array} sources * The sources for a media asset * * @return {Object|boolean} * Object of source and tech order or false */ ; _proto.selectSource = function selectSource(sources) { var _this10 = this; // Get only the techs specified in `techOrder` that exist and are supported by the // current platform var techs = this.options_.techOrder.map(function (techName) { return [techName, Tech.getTech(techName)]; }).filter(function (_ref) { var techName = _ref[0], tech = _ref[1]; // Check if the current tech is defined before continuing if (tech) { // Check if the browser supports this technology return tech.isSupported(); } log.error("The \"" + techName + "\" tech is undefined. Skipped browser support check for that tech."); return false; }); // Iterate over each `innerArray` element once per `outerArray` element and execute // `tester` with both. If `tester` returns a non-falsy value, exit early and return // that value. var findFirstPassingTechSourcePair = function findFirstPassingTechSourcePair(outerArray, innerArray, tester) { var found; outerArray.some(function (outerChoice) { return innerArray.some(function (innerChoice) { found = tester(outerChoice, innerChoice); if (found) { return true; } }); }); return found; }; var foundSourceAndTech; var flip = function flip(fn) { return function (a, b) { return fn(b, a); }; }; var finder = function finder(_ref2, source) { var techName = _ref2[0], tech = _ref2[1]; if (tech.canPlaySource(source, _this10.options_[techName.toLowerCase()])) { return { source: source, tech: techName }; } }; // Depending on the truthiness of `options.sourceOrder`, we swap the order of techs and sources // to select from them based on their priority. if (this.options_.sourceOrder) { // Source-first ordering foundSourceAndTech = findFirstPassingTechSourcePair(sources, techs, flip(finder)); } else { // Tech-first ordering foundSourceAndTech = findFirstPassingTechSourcePair(techs, sources, finder); } return foundSourceAndTech || false; } /** * Get or set the video source. * * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source] * A SourceObject, an array of SourceObjects, or a string referencing * a URL to a media source. It is _highly recommended_ that an object * or array of objects is used here, so that source selection * algorithms can take the `type` into account. * * If not provided, this method acts as a getter. * * @return {string|undefined} * If the `source` argument is missing, returns the current source * URL. Otherwise, returns nothing/undefined. */ ; _proto.src = function src(source) { var _this11 = this; // getter usage if (typeof source === 'undefined') { return this.cache_.src || ''; } // filter out invalid sources and turn our source into // an array of source objects var sources = filterSource(source); // if a source was passed in then it is invalid because // it was filtered to a zero length Array. So we have to // show an error if (!sources.length) { this.setTimeout(function () { this.error({ code: 4, message: this.localize(this.options_.notSupportedMessage) }); }, 0); return; } // intial sources this.changingSrc_ = true; this.cache_.sources = sources; this.updateSourceCaches_(sources[0]); // middlewareSource is the source after it has been changed by middleware setSource(this, sources[0], function (middlewareSource, mws) { _this11.middleware_ = mws; // since sourceSet is async we have to update the cache again after we select a source since // the source that is selected could be out of order from the cache update above this callback. _this11.cache_.sources = sources; _this11.updateSourceCaches_(middlewareSource); var err = _this11.src_(middlewareSource); if (err) { if (sources.length > 1) { return _this11.src(sources.slice(1)); } _this11.changingSrc_ = false; // We need to wrap this in a timeout to give folks a chance to add error event handlers _this11.setTimeout(function () { this.error({ code: 4, message: this.localize(this.options_.notSupportedMessage) }); }, 0); // we could not find an appropriate tech, but let's still notify the delegate that this is it // this needs a better comment about why this is needed _this11.triggerReady(); return; } setTech(mws, _this11.tech_); }); } /** * Set the source object on the tech, returns a boolean that indicates whether * there is a tech that can play the source or not * * @param {Tech~SourceObject} source * The source object to set on the Tech * * @return {boolean} * - True if there is no Tech to playback this source * - False otherwise * * @private */ ; _proto.src_ = function src_(source) { var _this12 = this; var sourceTech = this.selectSource([source]); if (!sourceTech) { return true; } if (!titleCaseEquals(sourceTech.tech, this.techName_)) { this.changingSrc_ = true; // load this technology with the chosen source this.loadTech_(sourceTech.tech, sourceTech.source); this.tech_.ready(function () { _this12.changingSrc_ = false; }); return false; } // wait until the tech is ready to set the source // and set it synchronously if possible (#2326) this.ready(function () { // The setSource tech method was added with source handlers // so older techs won't support it // We need to check the direct prototype for the case where subclasses // of the tech do not support source handlers if (this.tech_.constructor.prototype.hasOwnProperty('setSource')) { this.techCall_('setSource', source); } else { this.techCall_('src', source.src); } this.changingSrc_ = false; }, true); return false; } /** * Begin loading the src data. */ ; _proto.load = function load() { this.techCall_('load'); } /** * Reset the player. Loads the first tech in the techOrder, * removes all the text tracks in the existing `tech`, * and calls `reset` on the `tech`. */ ; _proto.reset = function reset() { var _this13 = this; var PromiseClass = this.options_.Promise || window$1.Promise; if (this.paused() || !PromiseClass) { this.doReset_(); } else { var playPromise = this.play(); silencePromise(playPromise.then(function () { return _this13.doReset_(); })); } }; _proto.doReset_ = function doReset_() { if (this.tech_) { this.tech_.clearTracks('text'); } this.resetCache_(); this.poster(''); this.loadTech_(this.options_.techOrder[0], null); this.techCall_('reset'); this.resetControlBarUI_(); if (isEvented(this)) { this.trigger('playerreset'); } } /** * Reset Control Bar's UI by calling sub-methods that reset * all of Control Bar's components */ ; _proto.resetControlBarUI_ = function resetControlBarUI_() { this.resetProgressBar_(); this.resetPlaybackRate_(); this.resetVolumeBar_(); } /** * Reset tech's progress so progress bar is reset in the UI */ ; _proto.resetProgressBar_ = function resetProgressBar_() { this.currentTime(0); var _this$controlBar = this.controlBar, durationDisplay = _this$controlBar.durationDisplay, remainingTimeDisplay = _this$controlBar.remainingTimeDisplay; if (durationDisplay) { durationDisplay.updateContent(); } if (remainingTimeDisplay) { remainingTimeDisplay.updateContent(); } } /** * Reset Playback ratio */ ; _proto.resetPlaybackRate_ = function resetPlaybackRate_() { this.playbackRate(this.defaultPlaybackRate()); this.handleTechRateChange_(); } /** * Reset Volume bar */ ; _proto.resetVolumeBar_ = function resetVolumeBar_() { this.volume(1.0); this.trigger('volumechange'); } /** * Returns all of the current source objects. * * @return {Tech~SourceObject[]} * The current source objects */ ; _proto.currentSources = function currentSources() { var source = this.currentSource(); var sources = []; // assume `{}` or `{ src }` if (Object.keys(source).length !== 0) { sources.push(source); } return this.cache_.sources || sources; } /** * Returns the current source object. * * @return {Tech~SourceObject} * The current source object */ ; _proto.currentSource = function currentSource() { return this.cache_.source || {}; } /** * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4 * Can be used in conjunction with `currentType` to assist in rebuilding the current source object. * * @return {string} * The current source */ ; _proto.currentSrc = function currentSrc() { return this.currentSource() && this.currentSource().src || ''; } /** * Get the current source type e.g. video/mp4 * This can allow you rebuild the current source object so that you could load the same * source and tech later * * @return {string} * The source MIME type */ ; _proto.currentType = function currentType() { return this.currentSource() && this.currentSource().type || ''; } /** * Get or set the preload attribute * * @param {boolean} [value] * - true means that we should preload * - false means that we should not preload * * @return {string} * The preload attribute value when getting */ ; _proto.preload = function preload(value) { if (value !== undefined) { this.techCall_('setPreload', value); this.options_.preload = value; return; } return this.techGet_('preload'); } /** * Get or set the autoplay option. When this is a boolean it will * modify the attribute on the tech. When this is a string the attribute on * the tech will be removed and `Player` will handle autoplay on loadstarts. * * @param {boolean|string} [value] * - true: autoplay using the browser behavior * - false: do not autoplay * - 'play': call play() on every loadstart * - 'muted': call muted() then play() on every loadstart * - 'any': call play() on every loadstart. if that fails call muted() then play(). * - *: values other than those listed here will be set `autoplay` to true * * @return {boolean|string} * The current value of autoplay when getting */ ; _proto.autoplay = function autoplay(value) { // getter usage if (value === undefined) { return this.options_.autoplay || false; } var techAutoplay; // if the value is a valid string set it to that if (typeof value === 'string' && /(any|play|muted)/.test(value)) { this.options_.autoplay = value; this.manualAutoplay_(value); techAutoplay = false; // any falsy value sets autoplay to false in the browser, // lets do the same } else if (!value) { this.options_.autoplay = false; // any other value (ie truthy) sets autoplay to true } else { this.options_.autoplay = true; } techAutoplay = typeof techAutoplay === 'undefined' ? this.options_.autoplay : techAutoplay; // if we don't have a tech then we do not queue up // a setAutoplay call on tech ready. We do this because the // autoplay option will be passed in the constructor and we // do not need to set it twice if (this.tech_) { this.techCall_('setAutoplay', techAutoplay); } } /** * Set or unset the playsinline attribute. * Playsinline tells the browser that non-fullscreen playback is preferred. * * @param {boolean} [value] * - true means that we should try to play inline by default * - false means that we should use the browser's default playback mode, * which in most cases is inline. iOS Safari is a notable exception * and plays fullscreen by default. * * @return {string|Player} * - the current value of playsinline * - the player when setting * * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline} */ ; _proto.playsinline = function playsinline(value) { if (value !== undefined) { this.techCall_('setPlaysinline', value); this.options_.playsinline = value; return this; } return this.techGet_('playsinline'); } /** * Get or set the loop attribute on the video element. * * @param {boolean} [value] * - true means that we should loop the video * - false means that we should not loop the video * * @return {boolean} * The current value of loop when getting */ ; _proto.loop = function loop(value) { if (value !== undefined) { this.techCall_('setLoop', value); this.options_.loop = value; return; } return this.techGet_('loop'); } /** * Get or set the poster image source url * * @fires Player#posterchange * * @param {string} [src] * Poster image source URL * * @return {string} * The current value of poster when getting */ ; _proto.poster = function poster(src) { if (src === undefined) { return this.poster_; } // The correct way to remove a poster is to set as an empty string // other falsey values will throw errors if (!src) { src = ''; } if (src === this.poster_) { return; } // update the internal poster variable this.poster_ = src; // update the tech's poster this.techCall_('setPoster', src); this.isPosterFromTech_ = false; // alert components that the poster has been set /** * This event fires when the poster image is changed on the player. * * @event Player#posterchange * @type {EventTarget~Event} */ this.trigger('posterchange'); } /** * Some techs (e.g. YouTube) can provide a poster source in an * asynchronous way. We want the poster component to use this * poster source so that it covers up the tech's controls. * (YouTube's play button). However we only want to use this * source if the player user hasn't set a poster through * the normal APIs. * * @fires Player#posterchange * @listens Tech#posterchange * @private */ ; _proto.handleTechPosterChange_ = function handleTechPosterChange_() { if ((!this.poster_ || this.options_.techCanOverridePoster) && this.tech_ && this.tech_.poster) { var newPoster = this.tech_.poster() || ''; if (newPoster !== this.poster_) { this.poster_ = newPoster; this.isPosterFromTech_ = true; // Let components know the poster has changed this.trigger('posterchange'); } } } /** * Get or set whether or not the controls are showing. * * @fires Player#controlsenabled * * @param {boolean} [bool] * - true to turn controls on * - false to turn controls off * * @return {boolean} * The current value of controls when getting */ ; _proto.controls = function controls(bool) { if (bool === undefined) { return !!this.controls_; } bool = !!bool; // Don't trigger a change event unless it actually changed if (this.controls_ === bool) { return; } this.controls_ = bool; if (this.usingNativeControls()) { this.techCall_('setControls', bool); } if (this.controls_) { this.removeClass('vjs-controls-disabled'); this.addClass('vjs-controls-enabled'); /** * @event Player#controlsenabled * @type {EventTarget~Event} */ this.trigger('controlsenabled'); if (!this.usingNativeControls()) { this.addTechControlsListeners_(); } } else { this.removeClass('vjs-controls-enabled'); this.addClass('vjs-controls-disabled'); /** * @event Player#controlsdisabled * @type {EventTarget~Event} */ this.trigger('controlsdisabled'); if (!this.usingNativeControls()) { this.removeTechControlsListeners_(); } } } /** * Toggle native controls on/off. Native controls are the controls built into * devices (e.g. default iPhone controls), Flash, or other techs * (e.g. Vimeo Controls) * **This should only be set by the current tech, because only the tech knows * if it can support native controls** * * @fires Player#usingnativecontrols * @fires Player#usingcustomcontrols * * @param {boolean} [bool] * - true to turn native controls on * - false to turn native controls off * * @return {boolean} * The current value of native controls when getting */ ; _proto.usingNativeControls = function usingNativeControls(bool) { if (bool === undefined) { return !!this.usingNativeControls_; } bool = !!bool; // Don't trigger a change event unless it actually changed if (this.usingNativeControls_ === bool) { return; } this.usingNativeControls_ = bool; if (this.usingNativeControls_) { this.addClass('vjs-using-native-controls'); /** * player is using the native device controls * * @event Player#usingnativecontrols * @type {EventTarget~Event} */ this.trigger('usingnativecontrols'); } else { this.removeClass('vjs-using-native-controls'); /** * player is using the custom HTML controls * * @event Player#usingcustomcontrols * @type {EventTarget~Event} */ this.trigger('usingcustomcontrols'); } } /** * Set or get the current MediaError * * @fires Player#error * * @param {MediaError|string|number} [err] * A MediaError or a string/number to be turned * into a MediaError * * @return {MediaError|null} * The current MediaError when getting (or null) */ ; _proto.error = function error(err) { if (err === undefined) { return this.error_ || null; } // Suppress the first error message for no compatible source until // user interaction if (this.options_.suppressNotSupportedError && err && err.message && err.message === this.localize(this.options_.notSupportedMessage)) { var triggerSuppressedError = function triggerSuppressedError() { this.error(err); }; this.options_.suppressNotSupportedError = false; this.any(['click', 'touchstart'], triggerSuppressedError); this.one('loadstart', function () { this.off(['click', 'touchstart'], triggerSuppressedError); }); return; } // restoring to default if (err === null) { this.error_ = err; this.removeClass('vjs-error'); if (this.errorDisplay) { this.errorDisplay.close(); } return; } this.error_ = new MediaError(err); // add the vjs-error classname to the player this.addClass('vjs-error'); // log the name of the error type and any message // IE11 logs "[object object]" and required you to expand message to see error object log.error("(CODE:" + this.error_.code + " " + MediaError.errorTypes[this.error_.code] + ")", this.error_.message, this.error_); /** * @event Player#error * @type {EventTarget~Event} */ this.trigger('error'); return; } /** * Report user activity * * @param {Object} event * Event object */ ; _proto.reportUserActivity = function reportUserActivity(event) { this.userActivity_ = true; } /** * Get/set if user is active * * @fires Player#useractive * @fires Player#userinactive * * @param {boolean} [bool] * - true if the user is active * - false if the user is inactive * * @return {boolean} * The current value of userActive when getting */ ; _proto.userActive = function userActive(bool) { if (bool === undefined) { return this.userActive_; } bool = !!bool; if (bool === this.userActive_) { return; } this.userActive_ = bool; if (this.userActive_) { this.userActivity_ = true; this.removeClass('vjs-user-inactive'); this.addClass('vjs-user-active'); /** * @event Player#useractive * @type {EventTarget~Event} */ this.trigger('useractive'); return; } // Chrome/Safari/IE have bugs where when you change the cursor it can // trigger a mousemove event. This causes an issue when you're hiding // the cursor when the user is inactive, and a mousemove signals user // activity. Making it impossible to go into inactive mode. Specifically // this happens in fullscreen when we really need to hide the cursor. // // When this gets resolved in ALL browsers it can be removed // https://code.google.com/p/chromium/issues/detail?id=103041 if (this.tech_) { this.tech_.one('mousemove', function (e) { e.stopPropagation(); e.preventDefault(); }); } this.userActivity_ = false; this.removeClass('vjs-user-active'); this.addClass('vjs-user-inactive'); /** * @event Player#userinactive * @type {EventTarget~Event} */ this.trigger('userinactive'); } /** * Listen for user activity based on timeout value * * @private */ ; _proto.listenForUserActivity_ = function listenForUserActivity_() { var mouseInProgress; var lastMoveX; var lastMoveY; var handleActivity = bind(this, this.reportUserActivity); var handleMouseMove = function handleMouseMove(e) { // #1068 - Prevent mousemove spamming // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970 if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) { lastMoveX = e.screenX; lastMoveY = e.screenY; handleActivity(); } }; var handleMouseDown = function handleMouseDown() { handleActivity(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(mouseInProgress); // Setting userActivity=true now and setting the interval to the same time // as the activityCheck interval (250) should ensure we never miss the // next activityCheck mouseInProgress = this.setInterval(handleActivity, 250); }; var handleMouseUp = function handleMouseUp(event) { handleActivity(); // Stop the interval that maintains activity if the mouse/touch is down this.clearInterval(mouseInProgress); }; // Any mouse movement will be considered user activity this.on('mousedown', handleMouseDown); this.on('mousemove', handleMouseMove); this.on('mouseup', handleMouseUp); var controlBar = this.getChild('controlBar'); // Fixes bug on Android & iOS where when tapping progressBar (when control bar is displayed) // controlBar would no longer be hidden by default timeout. if (controlBar && !IS_IOS && !IS_ANDROID) { controlBar.on('mouseenter', function (event) { this.player().cache_.inactivityTimeout = this.player().options_.inactivityTimeout; this.player().options_.inactivityTimeout = 0; }); controlBar.on('mouseleave', function (event) { this.player().options_.inactivityTimeout = this.player().cache_.inactivityTimeout; }); } // Listen for keyboard navigation // Shouldn't need to use inProgress interval because of key repeat this.on('keydown', handleActivity); this.on('keyup', handleActivity); // Run an interval every 250 milliseconds instead of stuffing everything into // the mousemove/touchmove function itself, to prevent performance degradation. // `this.reportUserActivity` simply sets this.userActivity_ to true, which // then gets picked up by this loop // http://ejohn.org/blog/learning-from-twitter/ var inactivityTimeout; this.setInterval(function () { // Check to see if mouse/touch activity has happened if (!this.userActivity_) { return; } // Reset the activity tracker this.userActivity_ = false; // If the user state was inactive, set the state to active this.userActive(true); // Clear any existing inactivity timeout to start the timer over this.clearTimeout(inactivityTimeout); var timeout = this.options_.inactivityTimeout; if (timeout <= 0) { return; } // In <timeout> milliseconds, if no more activity has occurred the // user will be considered inactive inactivityTimeout = this.setTimeout(function () { // Protect against the case where the inactivityTimeout can trigger just // before the next user activity is picked up by the activity check loop // causing a flicker if (!this.userActivity_) { this.userActive(false); } }, timeout); }, 250); } /** * Gets or sets the current playback rate. A playback rate of * 1.0 represents normal speed and 0.5 would indicate half-speed * playback, for instance. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate * * @param {number} [rate] * New playback rate to set. * * @return {number} * The current playback rate when getting or 1.0 */ ; _proto.playbackRate = function playbackRate(rate) { if (rate !== undefined) { // NOTE: this.cache_.lastPlaybackRate is set from the tech handler // that is registered above this.techCall_('setPlaybackRate', rate); return; } if (this.tech_ && this.tech_.featuresPlaybackRate) { return this.cache_.lastPlaybackRate || this.techGet_('playbackRate'); } return 1.0; } /** * Gets or sets the current default playback rate. A default playback rate of * 1.0 represents normal speed and 0.5 would indicate half-speed playback, for instance. * defaultPlaybackRate will only represent what the initial playbackRate of a video was, not * not the current playbackRate. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-defaultplaybackrate * * @param {number} [rate] * New default playback rate to set. * * @return {number|Player} * - The default playback rate when getting or 1.0 * - the player when setting */ ; _proto.defaultPlaybackRate = function defaultPlaybackRate(rate) { if (rate !== undefined) { return this.techCall_('setDefaultPlaybackRate', rate); } if (this.tech_ && this.tech_.featuresPlaybackRate) { return this.techGet_('defaultPlaybackRate'); } return 1.0; } /** * Gets or sets the audio flag * * @param {boolean} bool * - true signals that this is an audio player * - false signals that this is not an audio player * * @return {boolean} * The current value of isAudio when getting */ ; _proto.isAudio = function isAudio(bool) { if (bool !== undefined) { this.isAudio_ = !!bool; return; } return !!this.isAudio_; } /** * A helper method for adding a {@link TextTrack} to our * {@link TextTrackList}. * * In addition to the W3C settings we allow adding additional info through options. * * @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack * * @param {string} [kind] * the kind of TextTrack you are adding * * @param {string} [label] * the label to give the TextTrack label * * @param {string} [language] * the language to set on the TextTrack * * @return {TextTrack|undefined} * the TextTrack that was added or undefined * if there is no tech */ ; _proto.addTextTrack = function addTextTrack(kind, label, language) { if (this.tech_) { return this.tech_.addTextTrack(kind, label, language); } } /** * Create a remote {@link TextTrack} and an {@link HTMLTrackElement}. It will * automatically removed from the video element whenever the source changes, unless * manualCleanup is set to false. * * @param {Object} options * Options to pass to {@link HTMLTrackElement} during creation. See * {@link HTMLTrackElement} for object properties that you should use. * * @param {boolean} [manualCleanup=true] if set to false, the TextTrack will be * * @return {HtmlTrackElement} * the HTMLTrackElement that was created and added * to the HtmlTrackElementList and the remote * TextTrackList * * @deprecated The default value of the "manualCleanup" parameter will default * to "false" in upcoming versions of Video.js */ ; _proto.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) { if (this.tech_) { return this.tech_.addRemoteTextTrack(options, manualCleanup); } } /** * Remove a remote {@link TextTrack} from the respective * {@link TextTrackList} and {@link HtmlTrackElementList}. * * @param {Object} track * Remote {@link TextTrack} to remove * * @return {undefined} * does not return anything */ ; _proto.removeRemoteTextTrack = function removeRemoteTextTrack(obj) { if (obj === void 0) { obj = {}; } var _obj = obj, track = _obj.track; if (!track) { track = obj; } // destructure the input into an object with a track argument, defaulting to arguments[0] // default the whole argument to an empty object if nothing was passed in if (this.tech_) { return this.tech_.removeRemoteTextTrack(track); } } /** * Gets available media playback quality metrics as specified by the W3C's Media * Playback Quality API. * * @see [Spec]{@link https://wicg.github.io/media-playback-quality} * * @return {Object|undefined} * An object with supported media playback quality metrics or undefined if there * is no tech or the tech does not support it. */ ; _proto.getVideoPlaybackQuality = function getVideoPlaybackQuality() { return this.techGet_('getVideoPlaybackQuality'); } /** * Get video width * * @return {number} * current video width */ ; _proto.videoWidth = function videoWidth() { return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0; } /** * Get video height * * @return {number} * current video height */ ; _proto.videoHeight = function videoHeight() { return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0; } /** * The player's language code * NOTE: The language should be set in the player options if you want the * the controls to be built with a specific language. Changing the language * later will not update controls text. * * @param {string} [code] * the language code to set the player to * * @return {string} * The current language code when getting */ ; _proto.language = function language(code) { if (code === undefined) { return this.language_; } this.language_ = String(code).toLowerCase(); } /** * Get the player's language dictionary * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time * Languages specified directly in the player options have precedence * * @return {Array} * An array of of supported languages */ ; _proto.languages = function languages() { return mergeOptions(Player.prototype.options_.languages, this.languages_); } /** * returns a JavaScript object reperesenting the current track * information. **DOES not return it as JSON** * * @return {Object} * Object representing the current of track info */ ; _proto.toJSON = function toJSON() { var options = mergeOptions(this.options_); var tracks = options.tracks; options.tracks = []; for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; // deep merge tracks and null out player so no circular references track = mergeOptions(track); track.player = undefined; options.tracks[i] = track; } return options; } /** * Creates a simple modal dialog (an instance of the {@link ModalDialog} * component) that immediately overlays the player with arbitrary * content and removes itself when closed. * * @param {string|Function|Element|Array|null} content * Same as {@link ModalDialog#content}'s param of the same name. * The most straight-forward usage is to provide a string or DOM * element. * * @param {Object} [options] * Extra options which will be passed on to the {@link ModalDialog}. * * @return {ModalDialog} * the {@link ModalDialog} that was created */ ; _proto.createModal = function createModal(content, options) { var _this14 = this; options = options || {}; options.content = content || ''; var modal = new ModalDialog(this, options); this.addChild(modal); modal.on('dispose', function () { _this14.removeChild(modal); }); modal.open(); return modal; } /** * Change breakpoint classes when the player resizes. * * @private */ ; _proto.updateCurrentBreakpoint_ = function updateCurrentBreakpoint_() { if (!this.responsive()) { return; } var currentBreakpoint = this.currentBreakpoint(); var currentWidth = this.currentWidth(); for (var i = 0; i < BREAKPOINT_ORDER.length; i++) { var candidateBreakpoint = BREAKPOINT_ORDER[i]; var maxWidth = this.breakpoints_[candidateBreakpoint]; if (currentWidth <= maxWidth) { // The current breakpoint did not change, nothing to do. if (currentBreakpoint === candidateBreakpoint) { return; } // Only remove a class if there is a current breakpoint. if (currentBreakpoint) { this.removeClass(BREAKPOINT_CLASSES[currentBreakpoint]); } this.addClass(BREAKPOINT_CLASSES[candidateBreakpoint]); this.breakpoint_ = candidateBreakpoint; break; } } } /** * Removes the current breakpoint. * * @private */ ; _proto.removeCurrentBreakpoint_ = function removeCurrentBreakpoint_() { var className = this.currentBreakpointClass(); this.breakpoint_ = ''; if (className) { this.removeClass(className); } } /** * Get or set breakpoints on the player. * * Calling this method with an object or `true` will remove any previous * custom breakpoints and start from the defaults again. * * @param {Object|boolean} [breakpoints] * If an object is given, it can be used to provide custom * breakpoints. If `true` is given, will set default breakpoints. * If this argument is not given, will simply return the current * breakpoints. * * @param {number} [breakpoints.tiny] * The maximum width for the "vjs-layout-tiny" class. * * @param {number} [breakpoints.xsmall] * The maximum width for the "vjs-layout-x-small" class. * * @param {number} [breakpoints.small] * The maximum width for the "vjs-layout-small" class. * * @param {number} [breakpoints.medium] * The maximum width for the "vjs-layout-medium" class. * * @param {number} [breakpoints.large] * The maximum width for the "vjs-layout-large" class. * * @param {number} [breakpoints.xlarge] * The maximum width for the "vjs-layout-x-large" class. * * @param {number} [breakpoints.huge] * The maximum width for the "vjs-layout-huge" class. * * @return {Object} * An object mapping breakpoint names to maximum width values. */ ; _proto.breakpoints = function breakpoints(_breakpoints) { // Used as a getter. if (_breakpoints === undefined) { return assign(this.breakpoints_); } this.breakpoint_ = ''; this.breakpoints_ = assign({}, DEFAULT_BREAKPOINTS, _breakpoints); // When breakpoint definitions change, we need to update the currently // selected breakpoint. this.updateCurrentBreakpoint_(); // Clone the breakpoints before returning. return assign(this.breakpoints_); } /** * Get or set a flag indicating whether or not this player should adjust * its UI based on its dimensions. * * @param {boolean} value * Should be `true` if the player should adjust its UI based on its * dimensions; otherwise, should be `false`. * * @return {boolean} * Will be `true` if this player should adjust its UI based on its * dimensions; otherwise, will be `false`. */ ; _proto.responsive = function responsive(value) { // Used as a getter. if (value === undefined) { return this.responsive_; } value = Boolean(value); var current = this.responsive_; // Nothing changed. if (value === current) { return; } // The value actually changed, set it. this.responsive_ = value; // Start listening for breakpoints and set the initial breakpoint if the // player is now responsive. if (value) { this.on('playerresize', this.updateCurrentBreakpoint_); this.updateCurrentBreakpoint_(); // Stop listening for breakpoints if the player is no longer responsive. } else { this.off('playerresize', this.updateCurrentBreakpoint_); this.removeCurrentBreakpoint_(); } return value; } /** * Get current breakpoint name, if any. * * @return {string} * If there is currently a breakpoint set, returns a the key from the * breakpoints object matching it. Otherwise, returns an empty string. */ ; _proto.currentBreakpoint = function currentBreakpoint() { return this.breakpoint_; } /** * Get the current breakpoint class name. * * @return {string} * The matching class name (e.g. `"vjs-layout-tiny"` or * `"vjs-layout-large"`) for the current breakpoint. Empty string if * there is no current breakpoint. */ ; _proto.currentBreakpointClass = function currentBreakpointClass() { return BREAKPOINT_CLASSES[this.breakpoint_] || ''; } /** * An object that describes a single piece of media. * * Properties that are not part of this type description will be retained; so, * this can be viewed as a generic metadata storage mechanism as well. * * @see {@link https://wicg.github.io/mediasession/#the-mediametadata-interface} * @typedef {Object} Player~MediaObject * * @property {string} [album] * Unused, except if this object is passed to the `MediaSession` * API. * * @property {string} [artist] * Unused, except if this object is passed to the `MediaSession` * API. * * @property {Object[]} [artwork] * Unused, except if this object is passed to the `MediaSession` * API. If not specified, will be populated via the `poster`, if * available. * * @property {string} [poster] * URL to an image that will display before playback. * * @property {Tech~SourceObject|Tech~SourceObject[]|string} [src] * A single source object, an array of source objects, or a string * referencing a URL to a media source. It is _highly recommended_ * that an object or array of objects is used here, so that source * selection algorithms can take the `type` into account. * * @property {string} [title] * Unused, except if this object is passed to the `MediaSession` * API. * * @property {Object[]} [textTracks] * An array of objects to be used to create text tracks, following * the {@link https://www.w3.org/TR/html50/embedded-content-0.html#the-track-element|native track element format}. * For ease of removal, these will be created as "remote" text * tracks and set to automatically clean up on source changes. * * These objects may have properties like `src`, `kind`, `label`, * and `language`, see {@link Tech#createRemoteTextTrack}. */ /** * Populate the player using a {@link Player~MediaObject|MediaObject}. * * @param {Player~MediaObject} media * A media object. * * @param {Function} ready * A callback to be called when the player is ready. */ ; _proto.loadMedia = function loadMedia(media, ready) { var _this15 = this; if (!media || typeof media !== 'object') { return; } this.reset(); // Clone the media object so it cannot be mutated from outside. this.cache_.media = mergeOptions(media); var _this$cache_$media = this.cache_.media, artwork = _this$cache_$media.artwork, poster = _this$cache_$media.poster, src = _this$cache_$media.src, textTracks = _this$cache_$media.textTracks; // If `artwork` is not given, create it using `poster`. if (!artwork && poster) { this.cache_.media.artwork = [{ src: poster, type: getMimetype(poster) }]; } if (src) { this.src(src); } if (poster) { this.poster(poster); } if (Array.isArray(textTracks)) { textTracks.forEach(function (tt) { return _this15.addRemoteTextTrack(tt, false); }); } this.ready(ready); } /** * Get a clone of the current {@link Player~MediaObject} for this player. * * If the `loadMedia` method has not been used, will attempt to return a * {@link Player~MediaObject} based on the current state of the player. * * @return {Player~MediaObject} */ ; _proto.getMedia = function getMedia() { if (!this.cache_.media) { var poster = this.poster(); var src = this.currentSources(); var textTracks = Array.prototype.map.call(this.remoteTextTracks(), function (tt) { return { kind: tt.kind, label: tt.label, language: tt.language, src: tt.src }; }); var media = { src: src, textTracks: textTracks }; if (poster) { media.poster = poster; media.artwork = [{ src: media.poster, type: getMimetype(media.poster) }]; } return media; } return mergeOptions(this.cache_.media); } /** * Gets tag settings * * @param {Element} tag * The player tag * * @return {Object} * An object containing all of the settings * for a player tag */ ; Player.getTagSettings = function getTagSettings(tag) { var baseOptions = { sources: [], tracks: [] }; var tagOptions = getAttributes(tag); var dataSetup = tagOptions['data-setup']; if (hasClass(tag, 'vjs-fill')) { tagOptions.fill = true; } if (hasClass(tag, 'vjs-fluid')) { tagOptions.fluid = true; } // Check if data-setup attr exists. if (dataSetup !== null) { // Parse options JSON // If empty string, make it a parsable json object. var _safeParseTuple = tuple(dataSetup || '{}'), err = _safeParseTuple[0], data = _safeParseTuple[1]; if (err) { log.error(err); } assign(tagOptions, data); } assign(baseOptions, tagOptions); // Get tag children settings if (tag.hasChildNodes()) { var children = tag.childNodes; for (var i = 0, j = children.length; i < j; i++) { var child = children[i]; // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/ var childName = child.nodeName.toLowerCase(); if (childName === 'source') { baseOptions.sources.push(getAttributes(child)); } else if (childName === 'track') { baseOptions.tracks.push(getAttributes(child)); } } } return baseOptions; } /** * Determine whether or not flexbox is supported * * @return {boolean} * - true if flexbox is supported * - false if flexbox is not supported */ ; _proto.flexNotSupported_ = function flexNotSupported_() { var elem = document.createElement('i'); // Note: We don't actually use flexBasis (or flexOrder), but it's one of the more // common flex features that we can rely on when checking for flex support. return !('flexBasis' in elem.style || 'webkitFlexBasis' in elem.style || 'mozFlexBasis' in elem.style || 'msFlexBasis' in elem.style || // IE10-specific (2012 flex spec), available for completeness 'msFlexOrder' in elem.style); }; return Player; }(Component); /** * Get the {@link VideoTrackList} * @link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist * * @return {VideoTrackList} * the current video track list * * @method Player.prototype.videoTracks */ /** * Get the {@link AudioTrackList} * @link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist * * @return {AudioTrackList} * the current audio track list * * @method Player.prototype.audioTracks */ /** * Get the {@link TextTrackList} * * @link http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks * * @return {TextTrackList} * the current text track list * * @method Player.prototype.textTracks */ /** * Get the remote {@link TextTrackList} * * @return {TextTrackList} * The current remote text track list * * @method Player.prototype.remoteTextTracks */ /** * Get the remote {@link HtmlTrackElementList} tracks. * * @return {HtmlTrackElementList} * The current remote text track element list * * @method Player.prototype.remoteTextTrackEls */ ALL.names.forEach(function (name) { var props = ALL[name]; Player.prototype[props.getterName] = function () { if (this.tech_) { return this.tech_[props.getterName](); } // if we have not yet loadTech_, we create {video,audio,text}Tracks_ // these will be passed to the tech during loading this[props.privateName] = this[props.privateName] || new props.ListClass(); return this[props.privateName]; }; }); /** * Global enumeration of players. * * The keys are the player IDs and the values are either the {@link Player} * instance or `null` for disposed players. * * @type {Object} */ Player.players = {}; var navigator = window$1.navigator; /* * Player instance options, surfaced using options * options = Player.prototype.options_ * Make changes in options, not here. * * @type {Object} * @private */ Player.prototype.options_ = { // Default order of fallback technology techOrder: Tech.defaultTechOrder_, html5: {}, flash: {}, // default inactivity timeout inactivityTimeout: 2000, // default playback rates playbackRates: [], // Add playback rate selection by adding rates // 'playbackRates': [0.5, 1, 1.5, 2], liveui: false, // Included control sets children: ['mediaLoader', 'posterImage', 'textTrackDisplay', 'loadingSpinner', 'bigPlayButton', 'liveTracker', 'controlBar', 'errorDisplay', 'textTrackSettings', 'resizeManager'], language: navigator && (navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language) || 'en', // locales and their language translations languages: {}, // Default message to show when a video cannot be played. notSupportedMessage: 'No compatible source was found for this media.', fullscreen: { options: { navigationUI: 'hide' } }, breakpoints: {}, responsive: false }; [ /** * Returns whether or not the player is in the "ended" state. * * @return {Boolean} True if the player is in the ended state, false if not. * @method Player#ended */ 'ended', /** * Returns whether or not the player is in the "seeking" state. * * @return {Boolean} True if the player is in the seeking state, false if not. * @method Player#seeking */ 'seeking', /** * Returns the TimeRanges of the media that are currently available * for seeking to. * * @return {TimeRanges} the seekable intervals of the media timeline * @method Player#seekable */ 'seekable', /** * Returns the current state of network activity for the element, from * the codes in the list below. * - NETWORK_EMPTY (numeric value 0) * The element has not yet been initialised. All attributes are in * their initial states. * - NETWORK_IDLE (numeric value 1) * The element's resource selection algorithm is active and has * selected a resource, but it is not actually using the network at * this time. * - NETWORK_LOADING (numeric value 2) * The user agent is actively trying to download data. * - NETWORK_NO_SOURCE (numeric value 3) * The element's resource selection algorithm is active, but it has * not yet found a resource to use. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states * @return {number} the current network activity state * @method Player#networkState */ 'networkState', /** * Returns a value that expresses the current state of the element * with respect to rendering the current playback position, from the * codes in the list below. * - HAVE_NOTHING (numeric value 0) * No information regarding the media resource is available. * - HAVE_METADATA (numeric value 1) * Enough of the resource has been obtained that the duration of the * resource is available. * - HAVE_CURRENT_DATA (numeric value 2) * Data for the immediate current playback position is available. * - HAVE_FUTURE_DATA (numeric value 3) * Data for the immediate current playback position is available, as * well as enough data for the user agent to advance the current * playback position in the direction of playback. * - HAVE_ENOUGH_DATA (numeric value 4) * The user agent estimates that enough data is available for * playback to proceed uninterrupted. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate * @return {number} the current playback rendering state * @method Player#readyState */ 'readyState'].forEach(function (fn) { Player.prototype[fn] = function () { return this.techGet_(fn); }; }); TECH_EVENTS_RETRIGGER.forEach(function (event) { Player.prototype["handleTech" + toTitleCase(event) + "_"] = function () { return this.trigger(event); }; }); /** * Fired when the player has initial duration and dimension information * * @event Player#loadedmetadata * @type {EventTarget~Event} */ /** * Fired when the player has downloaded data at the current playback position * * @event Player#loadeddata * @type {EventTarget~Event} */ /** * Fired when the current playback position has changed * * During playback this is fired every 15-250 milliseconds, depending on the * playback technology in use. * * @event Player#timeupdate * @type {EventTarget~Event} */ /** * Fired when the volume changes * * @event Player#volumechange * @type {EventTarget~Event} */ /** * Reports whether or not a player has a plugin available. * * This does not report whether or not the plugin has ever been initialized * on this player. For that, [usingPlugin]{@link Player#usingPlugin}. * * @method Player#hasPlugin * @param {string} name * The name of a plugin. * * @return {boolean} * Whether or not this player has the requested plugin available. */ /** * Reports whether or not a player is using a plugin by name. * * For basic plugins, this only reports whether the plugin has _ever_ been * initialized on this player. * * @method Player#usingPlugin * @param {string} name * The name of a plugin. * * @return {boolean} * Whether or not this player is using the requested plugin. */ Component.registerComponent('Player', Player); /** * The base plugin name. * * @private * @constant * @type {string} */ var BASE_PLUGIN_NAME = 'plugin'; /** * The key on which a player's active plugins cache is stored. * * @private * @constant * @type {string} */ var PLUGIN_CACHE_KEY = 'activePlugins_'; /** * Stores registered plugins in a private space. * * @private * @type {Object} */ var pluginStorage = {}; /** * Reports whether or not a plugin has been registered. * * @private * @param {string} name * The name of a plugin. * * @return {boolean} * Whether or not the plugin has been registered. */ var pluginExists = function pluginExists(name) { return pluginStorage.hasOwnProperty(name); }; /** * Get a single registered plugin by name. * * @private * @param {string} name * The name of a plugin. * * @return {Function|undefined} * The plugin (or undefined). */ var getPlugin = function getPlugin(name) { return pluginExists(name) ? pluginStorage[name] : undefined; }; /** * Marks a plugin as "active" on a player. * * Also, ensures that the player has an object for tracking active plugins. * * @private * @param {Player} player * A Video.js player instance. * * @param {string} name * The name of a plugin. */ var markPluginAsActive = function markPluginAsActive(player, name) { player[PLUGIN_CACHE_KEY] = player[PLUGIN_CACHE_KEY] || {}; player[PLUGIN_CACHE_KEY][name] = true; }; /** * Triggers a pair of plugin setup events. * * @private * @param {Player} player * A Video.js player instance. * * @param {Plugin~PluginEventHash} hash * A plugin event hash. * * @param {boolean} [before] * If true, prefixes the event name with "before". In other words, * use this to trigger "beforepluginsetup" instead of "pluginsetup". */ var triggerSetupEvent = function triggerSetupEvent(player, hash, before) { var eventName = (before ? 'before' : '') + 'pluginsetup'; player.trigger(eventName, hash); player.trigger(eventName + ':' + hash.name, hash); }; /** * Takes a basic plugin function and returns a wrapper function which marks * on the player that the plugin has been activated. * * @private * @param {string} name * The name of the plugin. * * @param {Function} plugin * The basic plugin. * * @return {Function} * A wrapper function for the given plugin. */ var createBasicPlugin = function createBasicPlugin(name, plugin) { var basicPluginWrapper = function basicPluginWrapper() { // We trigger the "beforepluginsetup" and "pluginsetup" events on the player // regardless, but we want the hash to be consistent with the hash provided // for advanced plugins. // // The only potentially counter-intuitive thing here is the `instance` in // the "pluginsetup" event is the value returned by the `plugin` function. triggerSetupEvent(this, { name: name, plugin: plugin, instance: null }, true); var instance = plugin.apply(this, arguments); markPluginAsActive(this, name); triggerSetupEvent(this, { name: name, plugin: plugin, instance: instance }); return instance; }; Object.keys(plugin).forEach(function (prop) { basicPluginWrapper[prop] = plugin[prop]; }); return basicPluginWrapper; }; /** * Takes a plugin sub-class and returns a factory function for generating * instances of it. * * This factory function will replace itself with an instance of the requested * sub-class of Plugin. * * @private * @param {string} name * The name of the plugin. * * @param {Plugin} PluginSubClass * The advanced plugin. * * @return {Function} */ var createPluginFactory = function createPluginFactory(name, PluginSubClass) { // Add a `name` property to the plugin prototype so that each plugin can // refer to itself by name. PluginSubClass.prototype.name = name; return function () { triggerSetupEvent(this, { name: name, plugin: PluginSubClass, instance: null }, true); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var instance = _construct(PluginSubClass, [this].concat(args)); // The plugin is replaced by a function that returns the current instance. this[name] = function () { return instance; }; triggerSetupEvent(this, instance.getEventHash()); return instance; }; }; /** * Parent class for all advanced plugins. * * @mixes module:evented~EventedMixin * @mixes module:stateful~StatefulMixin * @fires Player#beforepluginsetup * @fires Player#beforepluginsetup:$name * @fires Player#pluginsetup * @fires Player#pluginsetup:$name * @listens Player#dispose * @throws {Error} * If attempting to instantiate the base {@link Plugin} class * directly instead of via a sub-class. */ var Plugin = /*#__PURE__*/ function () { /** * Creates an instance of this class. * * Sub-classes should call `super` to ensure plugins are properly initialized. * * @param {Player} player * A Video.js player instance. */ function Plugin(player) { if (this.constructor === Plugin) { throw new Error('Plugin must be sub-classed; not directly instantiated.'); } this.player = player; // Make this object evented, but remove the added `trigger` method so we // use the prototype version instead. evented(this); delete this.trigger; stateful(this, this.constructor.defaultState); markPluginAsActive(player, this.name); // Auto-bind the dispose method so we can use it as a listener and unbind // it later easily. this.dispose = bind(this, this.dispose); // If the player is disposed, dispose the plugin. player.on('dispose', this.dispose); } /** * Get the version of the plugin that was set on <pluginName>.VERSION */ var _proto = Plugin.prototype; _proto.version = function version() { return this.constructor.VERSION; } /** * Each event triggered by plugins includes a hash of additional data with * conventional properties. * * This returns that object or mutates an existing hash. * * @param {Object} [hash={}] * An object to be used as event an event hash. * * @return {Plugin~PluginEventHash} * An event hash object with provided properties mixed-in. */ ; _proto.getEventHash = function getEventHash(hash) { if (hash === void 0) { hash = {}; } hash.name = this.name; hash.plugin = this.constructor; hash.instance = this; return hash; } /** * Triggers an event on the plugin object and overrides * {@link module:evented~EventedMixin.trigger|EventedMixin.trigger}. * * @param {string|Object} event * An event type or an object with a type property. * * @param {Object} [hash={}] * Additional data hash to merge with a * {@link Plugin~PluginEventHash|PluginEventHash}. * * @return {boolean} * Whether or not default was prevented. */ ; _proto.trigger = function trigger$1(event, hash) { if (hash === void 0) { hash = {}; } return trigger(this.eventBusEl_, event, this.getEventHash(hash)); } /** * Handles "statechanged" events on the plugin. No-op by default, override by * subclassing. * * @abstract * @param {Event} e * An event object provided by a "statechanged" event. * * @param {Object} e.changes * An object describing changes that occurred with the "statechanged" * event. */ ; _proto.handleStateChanged = function handleStateChanged(e) {} /** * Disposes a plugin. * * Subclasses can override this if they want, but for the sake of safety, * it's probably best to subscribe the "dispose" event. * * @fires Plugin#dispose */ ; _proto.dispose = function dispose() { var name = this.name, player = this.player; /** * Signals that a advanced plugin is about to be disposed. * * @event Plugin#dispose * @type {EventTarget~Event} */ this.trigger('dispose'); this.off(); player.off('dispose', this.dispose); // Eliminate any possible sources of leaking memory by clearing up // references between the player and the plugin instance and nulling out // the plugin's state and replacing methods with a function that throws. player[PLUGIN_CACHE_KEY][name] = false; this.player = this.state = null; // Finally, replace the plugin name on the player with a new factory // function, so that the plugin is ready to be set up again. player[name] = createPluginFactory(name, pluginStorage[name]); } /** * Determines if a plugin is a basic plugin (i.e. not a sub-class of `Plugin`). * * @param {string|Function} plugin * If a string, matches the name of a plugin. If a function, will be * tested directly. * * @return {boolean} * Whether or not a plugin is a basic plugin. */ ; Plugin.isBasic = function isBasic(plugin) { var p = typeof plugin === 'string' ? getPlugin(plugin) : plugin; return typeof p === 'function' && !Plugin.prototype.isPrototypeOf(p.prototype); } /** * Register a Video.js plugin. * * @param {string} name * The name of the plugin to be registered. Must be a string and * must not match an existing plugin or a method on the `Player` * prototype. * * @param {Function} plugin * A sub-class of `Plugin` or a function for basic plugins. * * @return {Function} * For advanced plugins, a factory function for that plugin. For * basic plugins, a wrapper function that initializes the plugin. */ ; Plugin.registerPlugin = function registerPlugin(name, plugin) { if (typeof name !== 'string') { throw new Error("Illegal plugin name, \"" + name + "\", must be a string, was " + typeof name + "."); } if (pluginExists(name)) { log.warn("A plugin named \"" + name + "\" already exists. You may want to avoid re-registering plugins!"); } else if (Player.prototype.hasOwnProperty(name)) { throw new Error("Illegal plugin name, \"" + name + "\", cannot share a name with an existing player method!"); } if (typeof plugin !== 'function') { throw new Error("Illegal plugin for \"" + name + "\", must be a function, was " + typeof plugin + "."); } pluginStorage[name] = plugin; // Add a player prototype method for all sub-classed plugins (but not for // the base Plugin class). if (name !== BASE_PLUGIN_NAME) { if (Plugin.isBasic(plugin)) { Player.prototype[name] = createBasicPlugin(name, plugin); } else { Player.prototype[name] = createPluginFactory(name, plugin); } } return plugin; } /** * De-register a Video.js plugin. * * @param {string} name * The name of the plugin to be de-registered. Must be a string that * matches an existing plugin. * * @throws {Error} * If an attempt is made to de-register the base plugin. */ ; Plugin.deregisterPlugin = function deregisterPlugin(name) { if (name === BASE_PLUGIN_NAME) { throw new Error('Cannot de-register base plugin.'); } if (pluginExists(name)) { delete pluginStorage[name]; delete Player.prototype[name]; } } /** * Gets an object containing multiple Video.js plugins. * * @param {Array} [names] * If provided, should be an array of plugin names. Defaults to _all_ * plugin names. * * @return {Object|undefined} * An object containing plugin(s) associated with their name(s) or * `undefined` if no matching plugins exist). */ ; Plugin.getPlugins = function getPlugins(names) { if (names === void 0) { names = Object.keys(pluginStorage); } var result; names.forEach(function (name) { var plugin = getPlugin(name); if (plugin) { result = result || {}; result[name] = plugin; } }); return result; } /** * Gets a plugin's version, if available * * @param {string} name * The name of a plugin. * * @return {string} * The plugin's version or an empty string. */ ; Plugin.getPluginVersion = function getPluginVersion(name) { var plugin = getPlugin(name); return plugin && plugin.VERSION || ''; }; return Plugin; }(); /** * Gets a plugin by name if it exists. * * @static * @method getPlugin * @memberOf Plugin * @param {string} name * The name of a plugin. * * @returns {Function|undefined} * The plugin (or `undefined`). */ Plugin.getPlugin = getPlugin; /** * The name of the base plugin class as it is registered. * * @type {string} */ Plugin.BASE_PLUGIN_NAME = BASE_PLUGIN_NAME; Plugin.registerPlugin(BASE_PLUGIN_NAME, Plugin); /** * Documented in player.js * * @ignore */ Player.prototype.usingPlugin = function (name) { return !!this[PLUGIN_CACHE_KEY] && this[PLUGIN_CACHE_KEY][name] === true; }; /** * Documented in player.js * * @ignore */ Player.prototype.hasPlugin = function (name) { return !!pluginExists(name); }; /** * Signals that a plugin is about to be set up on a player. * * @event Player#beforepluginsetup * @type {Plugin~PluginEventHash} */ /** * Signals that a plugin is about to be set up on a player - by name. The name * is the name of the plugin. * * @event Player#beforepluginsetup:$name * @type {Plugin~PluginEventHash} */ /** * Signals that a plugin has just been set up on a player. * * @event Player#pluginsetup * @type {Plugin~PluginEventHash} */ /** * Signals that a plugin has just been set up on a player - by name. The name * is the name of the plugin. * * @event Player#pluginsetup:$name * @type {Plugin~PluginEventHash} */ /** * @typedef {Object} Plugin~PluginEventHash * * @property {string} instance * For basic plugins, the return value of the plugin function. For * advanced plugins, the plugin instance on which the event is fired. * * @property {string} name * The name of the plugin. * * @property {string} plugin * For basic plugins, the plugin function. For advanced plugins, the * plugin class/constructor. */ /** * @file extend.js * @module extend */ /** * A combination of node inherits and babel's inherits (after transpile). * Both work the same but node adds `super_` to the subClass * and Bable adds the superClass as __proto__. Both seem useful. * * @param {Object} subClass * The class to inherit to * * @param {Object} superClass * The class to inherit from * * @private */ var _inherits = 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) { // node subClass.super_ = superClass; } }; /** * Used to subclass an existing class by emulating ES subclassing using the * `extends` keyword. * * @function * @example * var MyComponent = videojs.extend(videojs.getComponent('Component'), { * myCustomMethod: function() { * // Do things in my method. * } * }); * * @param {Function} superClass * The class to inherit from * * @param {Object} [subClassMethods={}] * Methods of the new class * * @return {Function} * The new class with subClassMethods that inherited superClass. */ var extend$1 = function extend(superClass, subClassMethods) { if (subClassMethods === void 0) { subClassMethods = {}; } var subClass = function subClass() { superClass.apply(this, arguments); }; var methods = {}; if (typeof subClassMethods === 'object') { if (subClassMethods.constructor !== Object.prototype.constructor) { subClass = subClassMethods.constructor; } methods = subClassMethods; } else if (typeof subClassMethods === 'function') { subClass = subClassMethods; } _inherits(subClass, superClass); // Extend subObj's prototype with functions and other properties from props for (var name in methods) { if (methods.hasOwnProperty(name)) { subClass.prototype[name] = methods[name]; } } return subClass; }; /** * @file video.js * @module videojs */ /** * Normalize an `id` value by trimming off a leading `#` * * @private * @param {string} id * A string, maybe with a leading `#`. * * @return {string} * The string, without any leading `#`. */ var normalizeId = function normalizeId(id) { return id.indexOf('#') === 0 ? id.slice(1) : id; }; /** * The `videojs()` function doubles as the main function for users to create a * {@link Player} instance as well as the main library namespace. * * It can also be used as a getter for a pre-existing {@link Player} instance. * However, we _strongly_ recommend using `videojs.getPlayer()` for this * purpose because it avoids any potential for unintended initialization. * * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149) * of our JSDoc template, we cannot properly document this as both a function * and a namespace, so its function signature is documented here. * * #### Arguments * ##### id * string|Element, **required** * * Video element or video element ID. * * ##### options * Object, optional * * Options object for providing settings. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html). * * ##### ready * {@link Component~ReadyCallback}, optional * * A function to be called when the {@link Player} and {@link Tech} are ready. * * #### Return Value * * The `videojs()` function returns a {@link Player} instance. * * @namespace * * @borrows AudioTrack as AudioTrack * @borrows Component.getComponent as getComponent * @borrows module:computed-style~computedStyle as computedStyle * @borrows module:events.on as on * @borrows module:events.one as one * @borrows module:events.off as off * @borrows module:events.trigger as trigger * @borrows EventTarget as EventTarget * @borrows module:extend~extend as extend * @borrows module:fn.bind as bind * @borrows module:format-time.formatTime as formatTime * @borrows module:format-time.resetFormatTime as resetFormatTime * @borrows module:format-time.setFormatTime as setFormatTime * @borrows module:merge-options.mergeOptions as mergeOptions * @borrows module:middleware.use as use * @borrows Player.players as players * @borrows Plugin.registerPlugin as registerPlugin * @borrows Plugin.deregisterPlugin as deregisterPlugin * @borrows Plugin.getPlugins as getPlugins * @borrows Plugin.getPlugin as getPlugin * @borrows Plugin.getPluginVersion as getPluginVersion * @borrows Tech.getTech as getTech * @borrows Tech.registerTech as registerTech * @borrows TextTrack as TextTrack * @borrows module:time-ranges.createTimeRanges as createTimeRange * @borrows module:time-ranges.createTimeRanges as createTimeRanges * @borrows module:url.isCrossOrigin as isCrossOrigin * @borrows module:url.parseUrl as parseUrl * @borrows VideoTrack as VideoTrack * * @param {string|Element} id * Video element or video element ID. * * @param {Object} [options] * Options object for providing settings. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html). * * @param {Component~ReadyCallback} [ready] * A function to be called when the {@link Player} and {@link Tech} are * ready. * * @return {Player} * The `videojs()` function returns a {@link Player|Player} instance. */ function videojs$1(id, options, ready) { var player = videojs$1.getPlayer(id); if (player) { if (options) { log.warn("Player \"" + id + "\" is already initialised. Options will not be applied."); } if (ready) { player.ready(ready); } return player; } var el = typeof id === 'string' ? $('#' + normalizeId(id)) : id; if (!isEl(el)) { throw new TypeError('The element or ID supplied is not valid. (videojs)'); } // document.body.contains(el) will only check if el is contained within that one document. // This causes problems for elements in iframes. // Instead, use the element's ownerDocument instead of the global document. // This will make sure that the element is indeed in the dom of that document. // Additionally, check that the document in question has a default view. // If the document is no longer attached to the dom, the defaultView of the document will be null. if (!el.ownerDocument.defaultView || !el.ownerDocument.body.contains(el)) { log.warn('The element supplied is not included in the DOM'); } options = options || {}; videojs$1.hooks('beforesetup').forEach(function (hookFunction) { var opts = hookFunction(el, mergeOptions(options)); if (!isObject(opts) || Array.isArray(opts)) { log.error('please return an object in beforesetup hooks'); return; } options = mergeOptions(options, opts); }); // We get the current "Player" component here in case an integration has // replaced it with a custom player. var PlayerComponent = Component.getComponent('Player'); player = new PlayerComponent(el, options, ready); videojs$1.hooks('setup').forEach(function (hookFunction) { return hookFunction(player); }); return player; } /** * An Object that contains lifecycle hooks as keys which point to an array * of functions that are run when a lifecycle is triggered * * @private */ videojs$1.hooks_ = {}; /** * Get a list of hooks for a specific lifecycle * * @param {string} type * the lifecyle to get hooks from * * @param {Function|Function[]} [fn] * Optionally add a hook (or hooks) to the lifecycle that your are getting. * * @return {Array} * an array of hooks, or an empty array if there are none. */ videojs$1.hooks = function (type, fn) { videojs$1.hooks_[type] = videojs$1.hooks_[type] || []; if (fn) { videojs$1.hooks_[type] = videojs$1.hooks_[type].concat(fn); } return videojs$1.hooks_[type]; }; /** * Add a function hook to a specific videojs lifecycle. * * @param {string} type * the lifecycle to hook the function to. * * @param {Function|Function[]} * The function or array of functions to attach. */ videojs$1.hook = function (type, fn) { videojs$1.hooks(type, fn); }; /** * Add a function hook that will only run once to a specific videojs lifecycle. * * @param {string} type * the lifecycle to hook the function to. * * @param {Function|Function[]} * The function or array of functions to attach. */ videojs$1.hookOnce = function (type, fn) { videojs$1.hooks(type, [].concat(fn).map(function (original) { var wrapper = function wrapper() { videojs$1.removeHook(type, wrapper); return original.apply(void 0, arguments); }; return wrapper; })); }; /** * Remove a hook from a specific videojs lifecycle. * * @param {string} type * the lifecycle that the function hooked to * * @param {Function} fn * The hooked function to remove * * @return {boolean} * The function that was removed or undef */ videojs$1.removeHook = function (type, fn) { var index = videojs$1.hooks(type).indexOf(fn); if (index <= -1) { return false; } videojs$1.hooks_[type] = videojs$1.hooks_[type].slice(); videojs$1.hooks_[type].splice(index, 1); return true; }; // Add default styles if (window$1.VIDEOJS_NO_DYNAMIC_STYLE !== true && isReal()) { var style = $('.vjs-styles-defaults'); if (!style) { style = createStyleElement('vjs-styles-defaults'); var head = $('head'); if (head) { head.insertBefore(style, head.firstChild); } setTextContent(style, "\n .video-js {\n width: 300px;\n height: 150px;\n }\n\n .vjs-fluid {\n padding-top: 56.25%\n }\n "); } } // Run Auto-load players // You have to wait at least once in case this script is loaded after your // video in the DOM (weird behavior only with minified version) autoSetupTimeout(1, videojs$1); /** * Current Video.js version. Follows [semantic versioning](https://semver.org/). * * @type {string} */ videojs$1.VERSION = version; /** * The global options object. These are the settings that take effect * if no overrides are specified when the player is created. * * @type {Object} */ videojs$1.options = Player.prototype.options_; /** * Get an object with the currently created players, keyed by player ID * * @return {Object} * The created players */ videojs$1.getPlayers = function () { return Player.players; }; /** * Get a single player based on an ID or DOM element. * * This is useful if you want to check if an element or ID has an associated * Video.js player, but not create one if it doesn't. * * @param {string|Element} id * An HTML element - `<video>`, `<audio>`, or `<video-js>` - * or a string matching the `id` of such an element. * * @return {Player|undefined} * A player instance or `undefined` if there is no player instance * matching the argument. */ videojs$1.getPlayer = function (id) { var players = Player.players; var tag; if (typeof id === 'string') { var nId = normalizeId(id); var player = players[nId]; if (player) { return player; } tag = $('#' + nId); } else { tag = id; } if (isEl(tag)) { var _tag = tag, _player = _tag.player, playerId = _tag.playerId; // Element may have a `player` property referring to an already created // player instance. If so, return that. if (_player || players[playerId]) { return _player || players[playerId]; } } }; /** * Returns an array of all current players. * * @return {Array} * An array of all players. The array will be in the order that * `Object.keys` provides, which could potentially vary between * JavaScript engines. * */ videojs$1.getAllPlayers = function () { return (// Disposed players leave a key with a `null` value, so we need to make sure // we filter those out. Object.keys(Player.players).map(function (k) { return Player.players[k]; }).filter(Boolean) ); }; videojs$1.players = Player.players; videojs$1.getComponent = Component.getComponent; /** * Register a component so it can referred to by name. Used when adding to other * components, either through addChild `component.addChild('myComponent')` or through * default children options `{ children: ['myComponent'] }`. * * > NOTE: You could also just initialize the component before adding. * `component.addChild(new MyComponent());` * * @param {string} name * The class name of the component * * @param {Component} comp * The component class * * @return {Component} * The newly registered component */ videojs$1.registerComponent = function (name, comp) { if (Tech.isTech(comp)) { log.warn("The " + name + " tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)"); } Component.registerComponent.call(Component, name, comp); }; videojs$1.getTech = Tech.getTech; videojs$1.registerTech = Tech.registerTech; videojs$1.use = use; /** * An object that can be returned by a middleware to signify * that the middleware is being terminated. * * @type {object} * @property {object} middleware.TERMINATOR */ Object.defineProperty(videojs$1, 'middleware', { value: {}, writeable: false, enumerable: true }); Object.defineProperty(videojs$1.middleware, 'TERMINATOR', { value: TERMINATOR, writeable: false, enumerable: true }); /** * A reference to the {@link module:browser|browser utility module} as an object. * * @type {Object} * @see {@link module:browser|browser} */ videojs$1.browser = browser; /** * Use {@link module:browser.TOUCH_ENABLED|browser.TOUCH_ENABLED} instead; only * included for backward-compatibility with 4.x. * * @deprecated Since version 5.0, use {@link module:browser.TOUCH_ENABLED|browser.TOUCH_ENABLED instead. * @type {boolean} */ videojs$1.TOUCH_ENABLED = TOUCH_ENABLED; videojs$1.extend = extend$1; videojs$1.mergeOptions = mergeOptions; videojs$1.bind = bind; videojs$1.registerPlugin = Plugin.registerPlugin; videojs$1.deregisterPlugin = Plugin.deregisterPlugin; /** * Deprecated method to register a plugin with Video.js * * @deprecated videojs.plugin() is deprecated; use videojs.registerPlugin() instead * * @param {string} name * The plugin name * * @param {Plugin|Function} plugin * The plugin sub-class or function */ videojs$1.plugin = function (name, plugin) { log.warn('videojs.plugin() is deprecated; use videojs.registerPlugin() instead'); return Plugin.registerPlugin(name, plugin); }; videojs$1.getPlugins = Plugin.getPlugins; videojs$1.getPlugin = Plugin.getPlugin; videojs$1.getPluginVersion = Plugin.getPluginVersion; /** * Adding languages so that they're available to all players. * Example: `videojs.addLanguage('es', { 'Hello': 'Hola' });` * * @param {string} code * The language code or dictionary property * * @param {Object} data * The data values to be translated * * @return {Object} * The resulting language dictionary object */ videojs$1.addLanguage = function (code, data) { var _mergeOptions; code = ('' + code).toLowerCase(); videojs$1.options.languages = mergeOptions(videojs$1.options.languages, (_mergeOptions = {}, _mergeOptions[code] = data, _mergeOptions)); return videojs$1.options.languages[code]; }; /** * A reference to the {@link module:log|log utility module} as an object. * * @type {Function} * @see {@link module:log|log} */ videojs$1.log = log; videojs$1.createLogger = createLogger$1; videojs$1.createTimeRange = videojs$1.createTimeRanges = createTimeRanges; videojs$1.formatTime = formatTime; videojs$1.setFormatTime = setFormatTime; videojs$1.resetFormatTime = resetFormatTime; videojs$1.parseUrl = parseUrl; videojs$1.isCrossOrigin = isCrossOrigin; videojs$1.EventTarget = EventTarget; videojs$1.on = on; videojs$1.one = one; videojs$1.off = off; videojs$1.trigger = trigger; /** * A cross-browser XMLHttpRequest wrapper. * * @function * @param {Object} options * Settings for the request. * * @return {XMLHttpRequest|XDomainRequest} * The request object. * * @see https://github.com/Raynos/xhr */ videojs$1.xhr = xhr; videojs$1.TextTrack = TextTrack; videojs$1.AudioTrack = AudioTrack; videojs$1.VideoTrack = VideoTrack; ['isEl', 'isTextNode', 'createEl', 'hasClass', 'addClass', 'removeClass', 'toggleClass', 'setAttributes', 'getAttributes', 'emptyEl', 'appendContent', 'insertContent'].forEach(function (k) { videojs$1[k] = function () { log.warn("videojs." + k + "() is deprecated; use videojs.dom." + k + "() instead"); return Dom[k].apply(null, arguments); }; }); videojs$1.computedStyle = computedStyle; /** * A reference to the {@link module:dom|DOM utility module} as an object. * * @type {Object} * @see {@link module:dom|dom} */ videojs$1.dom = Dom; /** * A reference to the {@link module:url|URL utility module} as an object. * * @type {Object} * @see {@link module:url|url} */ videojs$1.url = Url; return videojs$1; }));
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ 'use strict'; module.exports = require('./src/ReactTestRenderer');
/** * Expose `parse`. */ module.exports = parse; /** * Wrap map from jquery. */ var map = { legend: [1, '<fieldset>', '</fieldset>'], tr: [2, '<table><tbody>', '</tbody></table>'], col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], _default: [0, '', ''] }; map.td = map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>']; map.option = map.optgroup = [1, '<select multiple="multiple">', '</select>']; map.thead = map.tbody = map.colgroup = map.caption = map.tfoot = [1, '<table>', '</table>']; map.text = map.circle = map.ellipse = map.line = map.path = map.polygon = map.polyline = map.rect = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>']; /** * Parse `html` and return the children. * * @param {String} html * @return {Array} * @api private */ function parse(html) { if ('string' != typeof html) throw new TypeError('String expected'); // tag name var m = /<([\w:]+)/.exec(html); if (!m) return document.createTextNode(html); html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace var tag = m[1]; // body support if (tag == 'body') { var el = document.createElement('html'); el.innerHTML = html; return el.removeChild(el.lastChild); } // wrap map var wrap = map[tag] || map._default; var depth = wrap[0]; var prefix = wrap[1]; var suffix = wrap[2]; var el = document.createElement('div'); el.innerHTML = prefix + html + suffix; while (depth--) el = el.lastChild; // one element if (el.firstChild == el.lastChild) { return el.removeChild(el.firstChild); } // several elements var fragment = document.createDocumentFragment(); while (el.firstChild) { fragment.appendChild(el.removeChild(el.firstChild)); } return fragment; }
var cartApp = angular.module('cartApp', []); cartApp.controller('cartCtrl', function($scope, $http) { $scope.refreshCart = function(cartId) { $http.get('/webstore/rest/cart/' + $scope.cartId) .success(function(data) { $scope.cart = data; }); }; $scope.clearCart = function() { $http.delete('/webstore/rest/cart/' + $scope.cartId) .success(function(data) { $scope.refreshCart($scope.cartId); }); }; $scope.initCartId = function(cartId) { $scope.cartId = cartId; $scope.refreshCart($scope.cartId); }; $scope.addToCart = function(productId) { $http.put('/webstore/rest/cart/add/' + productId) .success(function(data) { alert("Product Successfully added to the Cart!"); }); }; $scope.removeFromCart = function(productId) { $http.put('/webstore/rest/cart/remove/' + productId) .success(function(data) { $scope.refreshCart($scope.cartId); }); }; });
YUI.add('inputex-dateselectmonth', function (Y, NAME) { /** * @module inputex-dateselectmonth */ var lang = Y.Lang, inputEx = Y.inputEx; /** * A field to enter a date with 2 strings and a select * @class inputEx.DateSelectMonthField * @extends inputEx.CombineField */ inputEx.DateSelectMonthField = function (options) { var formatSplit, selectOptions, i, j, monthsNb; // The ressource bundle is loaded here because // DateSelectMonthField needs them to construct his fields // this.messages will be overridden by the constructor of Field and re-loaded and mix in setOptions this.messages = Y.Intl.get("inputex-dateselectmonth"); if (!options.dateFormat) { options.dateFormat = this.messages.defaultDateFormat; } formatSplit = options.dateFormat.split("/"); this.yearIndex = inputEx.indexOf('Y', formatSplit); this.monthIndex = inputEx.indexOf('m', formatSplit); this.dayIndex = inputEx.indexOf('d', formatSplit); options.fields = []; for (i = 0 ; i < 3 ; i += 1) { if (i === this.dayIndex) { options.fields.push({ type: 'string', placeholder: this.messages.dayPlaceholder, size: 2 }); } else if (i === this.yearIndex) { options.fields.push({ type: 'string', placeholder: this.messages.yearPlaceholder, size: 4 }); } else { selectOptions = [{ value: '', label: this.messages.selectMonth }]; for (j = 0, monthsNb = this.messages.months.length; j < monthsNb; j += 1) { selectOptions.push({ value: j, label: this.messages.months[j] }); } options.fields.push({ type: 'select', choices: selectOptions, value: '' }); } } options.separators = options.separators || [false, "&nbsp;", "&nbsp;", false]; inputEx.DateSelectMonthField.superclass.constructor.call(this, options); }; Y.extend(inputEx.DateSelectMonthField, inputEx.CombineField, { /** * @method setOptions */ setOptions: function(options) { inputEx.DateSelectMonthField.superclass.setOptions.call(this, options); //I18N this.messages = Y.mix(this.messages, Y.Intl.get("inputex-dateselectmonth")); }, /** * @method setValue */ setValue: function (value, sendUpdatedEvt) { var values, i; values = []; // !value catches "" (empty field), other tests invalid dates (Invalid Date, or NaN) if (!value || !(value instanceof Date) || !lang.isNumber(value.getTime())) { values[this.monthIndex] = ""; values[this.yearIndex] = ""; values[this.dayIndex] = ""; } else { for (i = 0 ; i < 3 ; i += 1) { values.push(i === this.dayIndex ? value.getDate() : (i === this.yearIndex ? value.getFullYear() : value.getMonth())); } } inputEx.DateSelectMonthField.superclass.setValue.call(this, values, sendUpdatedEvt); }, /** * @method getValue */ getValue: function () { // if all sub-fields are empty (isEmpty method is inherited from inputEx.Group) if (this.isEmpty()) { return ""; } var values = inputEx.DateSelectMonthField.superclass.getValue.call(this); // if selected month index is '', new Date(..) would create a valid date with month == January !!!) if (values[this.monthIndex] === '') { return new Date(NaN, NaN, NaN); // -> Invalid Date (Firefox) or NaN (IE) (both instanceof Date ...) } return new Date(parseInt(values[this.yearIndex], 10), values[this.monthIndex], parseInt(values[this.dayIndex], 10)); }, /** * @method validate */ validate: function () { var val = this.getValue(); // empty field if (val === '') { // validate only if not required return !this.options.required; } // val is : // -> a Date, when valid // -> an Invalid Date (== "Invalid Date"), when invalid on FF // -> NaN, when invalid on IE // // These 3 cases would pass the "val instanceof Date" test, // but last 2 cases return NaN on val.getDate(), so "isFinite" test fails. return (val instanceof Date && lang.isNumber(val.getTime())); } }); // Register this class as "dateselectmonth" type inputEx.registerType("dateselectmonth", inputEx.DateSelectMonthField); }, '@VERSION@', { "requires": [ "inputex-combine", "inputex-string", "inputex-select" ], "ix_provides": "dateselectmonth", "lang": [ "en", "fr", "de", "ca", "es", "fr", "it", "nl", "pl", "pt-BR" ] });
"use strict"; module.exports = function parseOptional() { return { $runBefore: ['rendering-docs'], $process: docs => { docs.forEach(doc => { if (doc.members && doc.members.length) { for (let i in doc.members) { if (doc.members[i].params && doc.members[i].params.length) { for (let ii in doc.members[i].params) { if (doc.members[i].params[ii].optional) { doc.members[i].params[ii].description += '<strong class="tag">Optional</strong>'; } } } } } }); return docs; } } };
/*! * jQuery JavaScript Library v2.0.1 -ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-effects,-dimensions,-deprecated * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-05-27T00:57Z */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Support: IE9 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "2.0.1 -ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-effects,-dimensions,-deprecated", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler and self cleanup method completed = function() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } // Support: Safari <= 5.1 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Support: Firefox <20 // The try/catch suppresses exceptions thrown when attempting to access // the "constructor" property of certain host objects, ie. |window.location| // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 try { if ( obj.constructor && !core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } } catch ( e ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: JSON.parse, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, trim: function( text ) { return text == null ? "" : core_trim.call( text ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : core_indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: Date.now, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.9.4-pre * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-05-15 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), hasDuplicate = false, sortOrder = function() { return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rsibling = new RegExp( whitespace + "*[+~]" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * For feature detection * @param {Function} fn The function to test for native support */ function isNative( fn ) { return rnative.test( fn + "" ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied if the test fails * @param {Boolean} test The result of a test. If true, null will be set as the handler in leiu of the specified handler */ function addHandle( attrs, handler, test ) { attrs = attrs.split("|"); var current, i = attrs.length, setHandle = test ? null : handler; while ( i-- ) { // Don't override a user's handler if ( !(current = Expr.attrHandle[ attrs[i] ]) || current === handler ) { Expr.attrHandle[ attrs[i] ] = setHandle; } } } /** * Fetches boolean attributes by node * @param {Element} elem * @param {String} name */ function boolHandler( elem, name ) { // XML does not need to be checked as this will not be assigned for XML documents var val = elem.getAttributeNode( name ); return val && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } /** * Fetches attributes without interpolation * http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx * @param {Element} elem * @param {String} name */ function interpolationHandler( elem, name ) { // XML does not need to be checked as this will not be assigned for XML documents return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } /** * Uses defaultValue to retrieve value in IE6/7 * @param {Element} elem * @param {String} name */ function valueHandler( elem ) { // Ignore the value *property* on inputs by using defaultValue // Fallback to Sizzle.attr by returning undefined where appropriate // XML does not need to be checked as this will not be assigned for XML documents if ( elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns Returns -1 if a precedes b, 1 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { // Support: IE<8 // Prevent attribute/property "interpolation" div.innerHTML = "<a href='#'></a>"; addHandle( "type|href|height|width", interpolationHandler, div.firstChild.getAttribute("href") === "#" ); // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies addHandle( booleans, boolHandler, div.getAttribute("disabled") == null ); div.className = "i"; return !div.getAttribute("className"); }); // Support: IE<9 // Retrieving value should defer to defaultValue support.input = assert(function( div ) { div.innerHTML = "<input>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }); // IE6/7 still return empty string for value, // but are actually retrieving the property addHandle( "value", valueHandler, support.attributes && support.input ); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = isNative(doc.querySelectorAll)) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = isNative( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( doc.createElement("div") ) & 1; }); // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = ( fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined ); return val === undefined ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) ); return results; } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Initialize against the default document setDocument(); // Support: Chrome<<14 // Always assume duplicates if they aren't passed to the comparison function [0, 0].sort( sortOrder ); support.detectDuplicates = hasDuplicate; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function( support ) { var input = document.createElement("input"), fragment = document.createDocumentFragment(), div = document.createElement("div"), select = document.createElement("select"), opt = select.appendChild( document.createElement("option") ); // Finish early in limited environments if ( !input.type ) { return support; } input.type = "checkbox"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) support.checkOn = input.value !== ""; // Must access the parent to make an option select properly // Support: IE9, IE10 support.optSelected = opt.selected; // Will be defined later support.reliableMarginRight = true; support.boxSizingReliable = true; support.pixelPosition = false; // Make sure checked status is properly cloned // Support: IE9, IE10 input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Check if an input maintains its value after becoming a radio // Support: IE9, IE10 input = document.createElement("input"); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment.appendChild( input ); // Support: Safari 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: Firefox, Chrome, Safari // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) support.focusinBubbles = "onfocusin" in window; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box", body = document.getElementsByTagName("body")[ 0 ]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; // Check box-sizing and margin behavior. body.appendChild( container ).appendChild( div ); div.innerHTML = ""; // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } body.removeChild( container ); }); return support; })( {} ); /* Implementation Summary 1. Enforce API surface and semantic compatibility with 1.9.x branch 2. Improve the module's maintainability by reducing the storage paths to a single mechanism. 3. Use the same single mechanism to support "private" and "user" data. 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) 5. Avoid exposing implementation details on user objects (eg. expando properties) 6. Provide a clear path for implementation upgrade to WeakMap in 2014 */ var data_user, data_priv, rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function Data() { // Support: Android < 4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Math.random(); } Data.uid = 1; Data.accepts = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any return owner.nodeType ? owner.nodeType === 1 || owner.nodeType === 9 : true; }; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android < 4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { return this.get( owner, key ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( core_rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; // These may be used throughout the jQuery core codebase data_user = new Data(); data_priv = new Data(); jQuery.extend({ acceptData: Data.accepts, hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, elem = this[ 0 ], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return jQuery.access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? JSON.parse( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } hooks.cur = fn; if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", key ] ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button)$/i; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set data_priv.set( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // IE6-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ // Temporarily disable this handler to check existence (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; // Restore handler jQuery.expr.attrHandle[ name ] = fn; return ret; }; }); // Support: IE9+ // Selectedness for an option in an optgroup can be inaccurate if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !jQuery.support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome < 28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // Support: Chrome 15+ jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // Create "bubbling" focus and blur events // Support: Firefox, Chrome, Safari if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = ( rneedsContext.test( selectors ) || typeof selectors !== "string" ) ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { cur = matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return core_indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return core_indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }, dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( isSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE 9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE 9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because core_push.apply(_, arraylike) throws core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Support: IE >= 9 // Fix Cloning issues if ( !jQuery.support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, i = 0, l = elems.length, fragment = context.createDocumentFragment(), nodes = []; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.firstChild; } // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Fixes #12346 // Support: Webkit, IE tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, events, type, key, j, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( Data.accepts( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { events = Object.keys( data.events || {} ); if ( events.length ) { for ( j = 0; (type = events[j]) !== undefined; j++ ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var l = elems.length, i = 0; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Support: IE >= 9 function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.fn.extend({ wrapAll: function( html ) { var wrap; if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapAll( html.call(this, i) ); }); } if ( this[ 0 ] ) { // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map(function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function( i ) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); var curCSS, iframe, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. function getStyles( elem ) { return window.getComputedStyle( elem, null ); } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = data_priv.get( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = data_priv.access( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css(elem, "display") ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { var bool = typeof state === "boolean"; return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifying setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { style[ name ] = value; } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // Support: IE9 // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // Support: Safari 5.1 // A tribute to the "awesome hack by Dean Edwards" // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { // Support: Android 2.3 if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // Support: Android 2.3 // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0; }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, elem = this[ 0 ], box = { top: 0, left: 0 }, doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf("auto") > -1; // Need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // We assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : window.pageXOffset, top ? val : window.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; } if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } // If there is a window object, that at least has a document property, // define jQuery and $ identifiers if ( typeof window === "object" && typeof window.document === "object" ) { window.jQuery = window.$ = jQuery; } })( window );
import minifyCSSString from '../minifyCSSString' describe('Minifying CSS strings', () => { it('should return a minified CSS string', () => { expect(minifyCSSString('.foo{color:bar}')).toEqual('.foo{color:bar}') expect( minifyCSSString( ` .foo { color: bar } .baz { font-size: 12px } ` ) ).toEqual('.foo {color: bar}.baz {font-size: 12px}') }) })
/** * BC Math Library for Javascript * Ported from the PHP5 bcmath extension source code, * which uses the libbcmath package... * Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc. * Copyright (C) 2000 Philip A. Nelson * The Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA. * e-mail: philnelson@acm.org * us-mail: Philip A. Nelson * Computer Science Department, 9062 * Western Washington University * Bellingham, WA 98226-9062 * * bcmath-js homepage: * * This code is covered under the LGPL licence, and can be used however you want :) * Be kind and share any decent code changes. */ var libbcmath = { PLUS: '+', MINUS: '-', BASE: 10, // must be 10 (for now) scale: 0, // default scale /** * Basic number structure */ bc_num: function() { this.n_sign = null; // sign this.n_len = null; /* (int) The number of digits before the decimal point. */ this.n_scale = null; /* (int) The number of digits after the decimal point. */ //this.n_refs = null; /* (int) The number of pointers to this number. */ //this.n_text = null; /* ?? Linked list for available list. */ this.n_value = null; /* array as value, where 1.23 = [1,2,3] */ this.toString = function() { var r, tmp; tmp=this.n_value.join(''); // add minus sign (if applicable) then add the integer part r = ((this.n_sign == libbcmath.PLUS) ? '' : this.n_sign) + tmp.substr(0, this.n_len); // if decimal places, add a . and the decimal part if (this.n_scale > 0) { r += '.' + tmp.substr(this.n_len, this.n_scale); } return r; }; }, /** * @param int length * @param int scale * @return bc_num */ bc_new_num: function(length, scale) { var temp; // bc_num temp = new libbcmath.bc_num(); temp.n_sign = libbcmath.PLUS; temp.n_len = length; temp.n_scale = scale; temp.n_value = libbcmath.safe_emalloc(1, length+scale, 0); libbcmath.memset(temp.n_value, 0, 0, length+scale); return temp; }, safe_emalloc: function(size, len, extra) { return Array((size * len) + extra); }, /** * Create a new number */ bc_init_num: function() { return new libbcmath.bc_new_num(1,0); }, _bc_rm_leading_zeros: function (num) { /* We can move n_value to point to the first non zero digit! */ while ((num.n_value[0] === 0) && (num.n_len > 1)) { num.n_value.shift(); num.n_len--; } }, /** * Convert to bc_num detecting scale */ php_str2num: function(str) { var p; p = str.indexOf('.'); if (p==-1) { return libbcmath.bc_str2num(str, 0); } else { return libbcmath.bc_str2num(str, (str.length-p)); } }, CH_VAL: function(c) { return c - '0'; //?? }, BCD_CHAR: function(d) { return d + '0'; // ?? }, isdigit: function(c) { return (isNaN(parseInt(c,10)) ? false : true); }, bc_str2num: function(str_in, scale) { var str,num, ptr, digits, strscale, zero_int, nptr; // remove any non-expected characters /* Check for valid number and count digits. */ str=str_in.split(''); // convert to array ptr = 0; // str digits = 0; strscale = 0; zero_int = false; if ( (str[ptr] === '+') || (str[ptr] === '-')) { ptr++; /* Sign */ } while (str[ptr] === '0') { ptr++; /* Skip leading zeros. */ } //while (libbcmath.isdigit(str[ptr])) { while ((str[ptr]) % 1 === 0) { //libbcmath.isdigit(str[ptr])) { ptr++; digits++; /* digits */ } if (str[ptr] === '.') { ptr++; /* decimal point */ } //while (libbcmath.isdigit(str[ptr])) { while ((str[ptr]) % 1 === 0) { //libbcmath.isdigit(str[ptr])) { ptr++; strscale++; /* digits */ } if ((str[ptr]) || (digits+strscale === 0)) { // invalid number, return 0 return libbcmath.bc_init_num(); //*num = bc_copy_num (BCG(_zero_)); } /* Adjust numbers and allocate storage and initialize fields. */ strscale = libbcmath.MIN(strscale, scale); if (digits === 0) { zero_int = true; digits = 1; } num = libbcmath.bc_new_num(digits, strscale); /* Build the whole number. */ ptr = 0; // str if (str[ptr] === '-') { num.n_sign = libbcmath.MINUS; //(*num)->n_sign = MINUS; ptr++; } else { num.n_sign = libbcmath.PLUS; //(*num)->n_sign = PLUS; if (str[ptr] === '+') { ptr++; } } while (str[ptr] === '0') { ptr++; /* Skip leading zeros. */ } nptr = 0; //(*num)->n_value; if (zero_int) { num.n_value[nptr++] = 0; digits = 0; } for (;digits > 0; digits--) { num.n_value[nptr++] = libbcmath.CH_VAL(str[ptr++]); //*nptr++ = CH_VAL(*ptr++); } /* Build the fractional part. */ if (strscale > 0) { ptr++; /* skip the decimal point! */ for (;strscale > 0; strscale--) { num.n_value[nptr++] = libbcmath.CH_VAL(str[ptr++]); } } return num; }, cint: function(v) { if (typeof(v) == 'undefined') { v = 0; } var x=parseInt(v,10); if (isNaN(x)) { x = 0; } return x; }, /** * Basic min function * @param int * @param int */ MIN: function(a, b) { return ((a > b) ? b : a); }, /** * Basic max function * @param int * @param int */ MAX: function(a, b) { return ((a > b) ? a : b); }, /** * Basic odd function * @param int * @param int */ ODD: function(a) { return (a & 1); }, /** * replicate c function * @param array return (by reference) * @param string char to fill * @param int length to fill */ memset: function(r, ptr, chr, len) { var i; for (i=0;i<len;i++) { r[ptr+i] = chr; } }, /** * Replacement c function * Obviously can't work like c does, so we've added an "offset" param so you could do memcpy(dest+1, src, len) as memcpy(dest, 1, src, len) * Also only works on arrays */ memcpy: function(dest, ptr, src, srcptr, len) { var i; for (i=0;i<len;i++) { dest[ptr+i]=src[srcptr+i]; } return true; }, /** * Determine if the number specified is zero or not * @param bc_num num number to check * @return boolean true when zero, false when not zero. */ bc_is_zero: function(num) { var count; // int var nptr; // int /* Quick check. */ //if (num == BCG(_zero_)) return TRUE; /* Initialize */ count = num.n_len + num.n_scale; nptr = 0; //num->n_value; /* The check */ while ((count > 0) && (num.n_value[nptr++] === 0)) { count--; } if (count !== 0) { return false; } else { return true; } }, bc_out_of_memory: function() { throw new Error("(BC) Out of memory"); } };
import _curry3 from './internal/_curry3.js'; /** * The `mapAccumRight` function behaves like a combination of map and reduce; it * applies a function to each element of a list, passing an accumulating * parameter from right to left, and returning a final value of this * accumulator together with the new list. * * Similar to [`mapAccum`](#mapAccum), except moves through the input list from * the right to the left. * * The iterator function receives two arguments, *acc* and *value*, and should * return a tuple *[acc, value]*. * * @func * @memberOf R * @since v0.10.0 * @category List * @sig ((acc, x) -> (acc, y)) -> acc -> [x] -> (acc, [y]) * @param {Function} fn The function to be called on every element of the input `list`. * @param {*} acc The accumulator value. * @param {Array} list The list to iterate over. * @return {*} The final, accumulated value. * @see R.addIndex, R.mapAccum * @example * * const digits = ['1', '2', '3', '4']; * const appender = (a, b) => [b + a, b + a]; * * R.mapAccumRight(appender, 5, digits); //=> ['12345', ['12345', '2345', '345', '45']] * @symb R.mapAccumRight(f, a, [b, c, d]) = [ * f(f(f(a, d)[0], c)[0], b)[0], * [ * f(a, d)[1], * f(f(a, d)[0], c)[1], * f(f(f(a, d)[0], c)[0], b)[1] * ] * ] */ var mapAccumRight = _curry3(function mapAccumRight(fn, acc, list) { var idx = list.length - 1; var result = []; var tuple = [acc]; while (idx >= 0) { tuple = fn(tuple[0], list[idx]); result[idx] = tuple[1]; idx -= 1; } return [tuple[0], result]; }); export default mapAccumRight;
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.styles = void 0; var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties")); var React = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _clsx = _interopRequireDefault(require("clsx")); var _withStyles = _interopRequireDefault(require("../styles/withStyles")); var _Tablelvl2Context = _interopRequireDefault(require("../Table/Tablelvl2Context")); var styles = { /* Styles applied to the root element. */ root: { display: 'table-header-group' } }; exports.styles = styles; var tablelvl2 = { variant: 'head' }; var defaultComponent = 'thead'; var TableHead = /*#__PURE__*/React.forwardRef(function TableHead(props, ref) { var classes = props.classes, className = props.className, _props$component = props.component, Component = _props$component === void 0 ? defaultComponent : _props$component, other = (0, _objectWithoutProperties2.default)(props, ["classes", "className", "component"]); return /*#__PURE__*/React.createElement(_Tablelvl2Context.default.Provider, { value: tablelvl2 }, /*#__PURE__*/React.createElement(Component, (0, _extends2.default)({ className: (0, _clsx.default)(classes.root, className), ref: ref, role: Component === defaultComponent ? null : 'rowgroup' }, other))); }); process.env.NODE_ENV !== "production" ? TableHead.propTypes = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * The content of the component, normally `TableRow`. */ children: _propTypes.default.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: _propTypes.default.object, /** * @ignore */ className: _propTypes.default.string, /** * The component used for the root node. * Either a string to use a HTML element or a component. */ component: _propTypes.default /* @typescript-to-proptypes-ignore */ .elementType } : void 0; var _default = (0, _withStyles.default)(styles, { name: 'MuiTableHead' })(TableHead); exports.default = _default;
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Defines errors to be thrown by the storage. * */ goog.provide('goog.storage.ErrorCode'); /** * Errors thrown by the storage. * @enum {string} */ goog.storage.ErrorCode = { INVALID_VALUE: 'Storage: Invalid value was encountered', DECRYPTION_ERROR: 'Storage: The value could not be decrypted' };
version https://git-lfs.github.com/spec/v1 oid sha256:54e1c65a298299c2148ff644dec8c8551e0d0e792a4e862efa232476f6cf7bee size 15280
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'elementspath', 'en-gb', { eleLabel: 'Elements path', eleTitle: '%1 element' });
/** * Copyright (c) 2015-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 ScrollView * @flow */ 'use strict'; const Animated = require('Animated'); const ColorPropType = require('ColorPropType'); const EdgeInsetsPropType = require('EdgeInsetsPropType'); const Platform = require('Platform'); const PointPropType = require('PointPropType'); const PropTypes = require('prop-types'); const React = require('React'); const ReactNative = require('ReactNative'); const ScrollResponder = require('ScrollResponder'); const ScrollViewStickyHeader = require('ScrollViewStickyHeader'); const StyleSheet = require('StyleSheet'); const StyleSheetPropType = require('StyleSheetPropType'); const View = require('View'); const ViewPropTypes = require('ViewPropTypes'); const ViewStylePropTypes = require('ViewStylePropTypes'); const createReactClass = require('create-react-class'); const dismissKeyboard = require('dismissKeyboard'); const flattenStyle = require('flattenStyle'); const invariant = require('fbjs/lib/invariant'); const processDecelerationRate = require('processDecelerationRate'); const requireNativeComponent = require('requireNativeComponent'); const warning = require('fbjs/lib/warning'); import type {NativeMethodsMixinType} from 'ReactNativeTypes'; /** * Component that wraps platform ScrollView while providing * integration with touch locking "responder" system. * * Keep in mind that ScrollViews must have a bounded height in order to work, * since they contain unbounded-height children into a bounded container (via * a scroll interaction). In order to bound the height of a ScrollView, either * set the height of the view directly (discouraged) or make sure all parent * views have bounded height. Forgetting to transfer `{flex: 1}` down the * view stack can lead to errors here, which the element inspector makes * easy to debug. * * Doesn't yet support other contained responders from blocking this scroll * view from becoming the responder. * * * `<ScrollView>` vs [`<FlatList>`](/react-native/docs/flatlist.html) - which one to use? * * `ScrollView` simply renders all its react child components at once. That * makes it very easy to understand and use. * * On the other hand, this has a performance downside. Imagine you have a very * long list of items you want to display, maybe several screens worth of * content. Creating JS components and native views for everything all at once, * much of which may not even be shown, will contribute to slow rendering and * increased memory usage. * * This is where `FlatList` comes into play. `FlatList` renders items lazily, * just when they are about to appear, and removes items that scroll way off * screen to save memory and processing time. * * `FlatList` is also handy if you want to render separators between your items, * multiple columns, infinite scroll loading, or any number of other features it * supports out of the box. */ // $FlowFixMe(>=0.41.0) const ScrollView = createReactClass({ displayName: 'ScrollView', propTypes: { ...ViewPropTypes, /** * Controls whether iOS should automatically adjust the content inset * for scroll views that are placed behind a navigation bar or * tab bar/ toolbar. The default value is true. * @platform ios */ automaticallyAdjustContentInsets: PropTypes.bool, /** * The amount by which the scroll view content is inset from the edges * of the scroll view. Defaults to `{top: 0, left: 0, bottom: 0, right: 0}`. * @platform ios */ contentInset: EdgeInsetsPropType, /** * Used to manually set the starting scroll offset. * The default value is `{x: 0, y: 0}`. * @platform ios */ contentOffset: PointPropType, /** * When true, the scroll view bounces when it reaches the end of the * content if the content is larger then the scroll view along the axis of * the scroll direction. When false, it disables all bouncing even if * the `alwaysBounce*` props are true. The default value is true. * @platform ios */ bounces: PropTypes.bool, /** * When true, gestures can drive zoom past min/max and the zoom will animate * to the min/max value at gesture end, otherwise the zoom will not exceed * the limits. * @platform ios */ bouncesZoom: PropTypes.bool, /** * When true, the scroll view bounces horizontally when it reaches the end * even if the content is smaller than the scroll view itself. The default * value is true when `horizontal={true}` and false otherwise. * @platform ios */ alwaysBounceHorizontal: PropTypes.bool, /** * When true, the scroll view bounces vertically when it reaches the end * even if the content is smaller than the scroll view itself. The default * value is false when `horizontal={true}` and true otherwise. * @platform ios */ alwaysBounceVertical: PropTypes.bool, /** * When true, the scroll view automatically centers the content when the * content is smaller than the scroll view bounds; when the content is * larger than the scroll view, this property has no effect. The default * value is false. * @platform ios */ centerContent: PropTypes.bool, /** * These styles will be applied to the scroll view content container which * wraps all of the child views. Example: * * ``` * return ( * <ScrollView contentContainerStyle={styles.contentContainer}> * </ScrollView> * ); * ... * const styles = StyleSheet.create({ * contentContainer: { * paddingVertical: 20 * } * }); * ``` */ contentContainerStyle: StyleSheetPropType(ViewStylePropTypes), /** * A floating-point number that determines how quickly the scroll view * decelerates after the user lifts their finger. You may also use string * shortcuts `"normal"` and `"fast"` which match the underlying iOS settings * for `UIScrollViewDecelerationRateNormal` and * `UIScrollViewDecelerationRateFast` respectively. * * - `'normal'`: 0.998 (the default) * - `'fast'`: 0.99 * * @platform ios */ decelerationRate: PropTypes.oneOfType([ PropTypes.oneOf(['fast', 'normal']), PropTypes.number, ]), /** * When true, the scroll view's children are arranged horizontally in a row * instead of vertically in a column. The default value is false. */ horizontal: PropTypes.bool, /** * The style of the scroll indicators. * * - `'default'` (the default), same as `black`. * - `'black'`, scroll indicator is black. This style is good against a light background. * - `'white'`, scroll indicator is white. This style is good against a dark background. * * @platform ios */ indicatorStyle: PropTypes.oneOf([ 'default', // default 'black', 'white', ]), /** * When true, the ScrollView will try to lock to only vertical or horizontal * scrolling while dragging. The default value is false. * @platform ios */ directionalLockEnabled: PropTypes.bool, /** * When false, once tracking starts, won't try to drag if the touch moves. * The default value is true. * @platform ios */ canCancelContentTouches: PropTypes.bool, /** * Determines whether the keyboard gets dismissed in response to a drag. * * - `'none'` (the default), drags do not dismiss the keyboard. * - `'on-drag'`, the keyboard is dismissed when a drag begins. * - `'interactive'`, the keyboard is dismissed interactively with the drag and moves in * synchrony with the touch; dragging upwards cancels the dismissal. * On android this is not supported and it will have the same behavior as 'none'. */ keyboardDismissMode: PropTypes.oneOf([ 'none', // default 'interactive', 'on-drag', ]), /** * Determines when the keyboard should stay visible after a tap. * * - `'never'` (the default), tapping outside of the focused text input when the keyboard * is up dismisses the keyboard. When this happens, children won't receive the tap. * - `'always'`, the keyboard will not dismiss automatically, and the scroll view will not * catch taps, but children of the scroll view can catch taps. * - `'handled'`, the keyboard will not dismiss automatically when the tap was handled by * a children, (or captured by an ancestor). * - `false`, deprecated, use 'never' instead * - `true`, deprecated, use 'always' instead */ keyboardShouldPersistTaps: PropTypes.oneOf(['always', 'never', 'handled', false, true]), /** * The maximum allowed zoom scale. The default value is 1.0. * @platform ios */ maximumZoomScale: PropTypes.number, /** * The minimum allowed zoom scale. The default value is 1.0. * @platform ios */ minimumZoomScale: PropTypes.number, /** * Fires at most once per frame during scrolling. The frequency of the * events can be controlled using the `scrollEventThrottle` prop. */ onScroll: PropTypes.func, /** * Called when a scrolling animation ends. * @platform ios */ onScrollAnimationEnd: PropTypes.func, /** * Called when scrollable content view of the ScrollView changes. * * Handler function is passed the content width and content height as parameters: * `(contentWidth, contentHeight)` * * It's implemented using onLayout handler attached to the content container * which this ScrollView renders. */ onContentSizeChange: PropTypes.func, /** * When true, the scroll view stops on multiples of the scroll view's size * when scrolling. This can be used for horizontal pagination. The default * value is false. */ pagingEnabled: PropTypes.bool, /** * When false, the view cannot be scrolled via touch interaction. * The default value is true. * * Note that the view can be always be scrolled by calling `scrollTo`. */ scrollEnabled: PropTypes.bool, /** * This controls how often the scroll event will be fired while scrolling * (as a time interval in ms). A lower number yields better accuracy for code * that is tracking the scroll position, but can lead to scroll performance * problems due to the volume of information being send over the bridge. * You will not notice a difference between values set between 1-16 as the * JS run loop is synced to the screen refresh rate. If you do not need precise * scroll position tracking, set this value higher to limit the information * being sent across the bridge. The default value is zero, which results in * the scroll event being sent only once each time the view is scrolled. * @platform ios */ scrollEventThrottle: PropTypes.number, /** * The amount by which the scroll view indicators are inset from the edges * of the scroll view. This should normally be set to the same value as * the `contentInset`. Defaults to `{0, 0, 0, 0}`. * @platform ios */ scrollIndicatorInsets: EdgeInsetsPropType, /** * When true, the scroll view scrolls to top when the status bar is tapped. * The default value is true. * @platform ios */ scrollsToTop: PropTypes.bool, /** * When true, shows a horizontal scroll indicator. * The default value is true. */ showsHorizontalScrollIndicator: PropTypes.bool, /** * When true, shows a vertical scroll indicator. * The default value is true. */ showsVerticalScrollIndicator: PropTypes.bool, /** * An array of child indices determining which children get docked to the * top of the screen when scrolling. For example, passing * `stickyHeaderIndices={[0]}` will cause the first child to be fixed to the * top of the scroll view. This property is not supported in conjunction * with `horizontal={true}`. */ stickyHeaderIndices: PropTypes.arrayOf(PropTypes.number), style: StyleSheetPropType(ViewStylePropTypes), /** * When set, causes the scroll view to stop at multiples of the value of * `snapToInterval`. This can be used for paginating through children * that have lengths smaller than the scroll view. Typically used in * combination with `snapToAlignment` and `decelerationRate="fast"`. * Overrides less configurable `pagingEnabled` prop. * * @platform ios */ snapToInterval: PropTypes.number, /** * When `snapToInterval` is set, `snapToAlignment` will define the relationship * of the snapping to the scroll view. * * - `'start'` (the default) will align the snap at the left (horizontal) or top (vertical) * - `'center'` will align the snap in the center * - `'end'` will align the snap at the right (horizontal) or bottom (vertical) * * @platform ios */ snapToAlignment: PropTypes.oneOf([ 'start', // default 'center', 'end', ]), /** * Experimental: When true, offscreen child views (whose `overflow` value is * `hidden`) are removed from their native backing superview when offscreen. * This can improve scrolling performance on long lists. The default value is * true. */ removeClippedSubviews: PropTypes.bool, /** * The current scale of the scroll view content. The default value is 1.0. * @platform ios */ zoomScale: PropTypes.number, /** * A RefreshControl component, used to provide pull-to-refresh * functionality for the ScrollView. Only works for vertical ScrollViews * (`horizontal` prop must be `false`). * * See [RefreshControl](docs/refreshcontrol.html). */ refreshControl: PropTypes.element, /** * Sometimes a scrollview takes up more space than its content fills. When this is * the case, this prop will fill the rest of the scrollview with a color to avoid setting * a background and creating unnecessary overdraw. This is an advanced optimization * that is not needed in the general case. * @platform android */ endFillColor: ColorPropType, /** * Tag used to log scroll performance on this scroll view. Will force * momentum events to be turned on (see sendMomentumEvents). This doesn't do * anything out of the box and you need to implement a custom native * FpsListener for it to be useful. * @platform android */ scrollPerfTag: PropTypes.string, /** * Used to override default value of overScroll mode. * * Possible values: * * - `'auto'` - Default value, allow a user to over-scroll * this view only if the content is large enough to meaningfully scroll. * - `'always'` - Always allow a user to over-scroll this view. * - `'never'` - Never allow a user to over-scroll this view. * * @platform android */ overScrollMode: PropTypes.oneOf([ 'auto', 'always', 'never', ]), /** * When true, ScrollView will emit updateChildFrames data in scroll events, * otherwise will not compute or emit child frame data. This only exists * to support legacy issues, `onLayout` should be used instead to retrieve * frame data. * The default value is false. * @platform ios */ DEPRECATED_sendUpdatedChildFrames: PropTypes.bool, }, mixins: [ScrollResponder.Mixin], _scrollAnimatedValue: (new Animated.Value(0): Animated.Value), _scrollAnimatedValueAttachment: (null: ?{detach: () => void}), _stickyHeaderRefs: (new Map(): Map<number, ScrollViewStickyHeader>), _headerLayoutYs: (new Map(): Map<string, number>), getInitialState: function() { return this.scrollResponderMixinGetInitialState(); }, componentWillMount: function() { this._scrollAnimatedValue = new Animated.Value(0); this._stickyHeaderRefs = new Map(); this._headerLayoutYs = new Map(); }, componentDidMount: function() { this._updateAnimatedNodeAttachment(); }, componentDidUpdate: function() { this._updateAnimatedNodeAttachment(); }, componentWillUnmount: function() { if (this._scrollAnimatedValueAttachment) { this._scrollAnimatedValueAttachment.detach(); } }, setNativeProps: function(props: Object) { this._scrollViewRef && this._scrollViewRef.setNativeProps(props); }, /** * Returns a reference to the underlying scroll responder, which supports * operations like `scrollTo`. All ScrollView-like components should * implement this method so that they can be composed while providing access * to the underlying scroll responder's methods. */ getScrollResponder: function(): ScrollView { return this; }, getScrollableNode: function(): any { return ReactNative.findNodeHandle(this._scrollViewRef); }, getInnerViewNode: function(): any { return ReactNative.findNodeHandle(this._innerViewRef); }, /** * Scrolls to a given x, y offset, either immediately or with a smooth animation. * * Example: * * `scrollTo({x: 0, y: 0, animated: true})` * * Note: The weird function signature is due to the fact that, for historical reasons, * the function also accepts separate arguments as an alternative to the options object. * This is deprecated due to ambiguity (y before x), and SHOULD NOT BE USED. */ scrollTo: function( y?: number | { x?: number, y?: number, animated?: boolean }, x?: number, animated?: boolean ) { if (typeof y === 'number') { console.warn('`scrollTo(y, x, animated)` is deprecated. Use `scrollTo({x: 5, y: 5, ' + 'animated: true})` instead.'); } else { ({x, y, animated} = y || {}); } this.getScrollResponder().scrollResponderScrollTo( {x: x || 0, y: y || 0, animated: animated !== false} ); }, /** * If this is a vertical ScrollView scrolls to the bottom. * If this is a horizontal ScrollView scrolls to the right. * * Use `scrollToEnd({animated: true})` for smooth animated scrolling, * `scrollToEnd({animated: false})` for immediate scrolling. * If no options are passed, `animated` defaults to true. */ scrollToEnd: function( options?: { animated?: boolean }, ) { // Default to true const animated = (options && options.animated) !== false; this.getScrollResponder().scrollResponderScrollToEnd({ animated: animated, }); }, /** * Deprecated, use `scrollTo` instead. */ scrollWithoutAnimationTo: function(y: number = 0, x: number = 0) { console.warn('`scrollWithoutAnimationTo` is deprecated. Use `scrollTo` instead'); this.scrollTo({x, y, animated: false}); }, /** * Displays the scroll indicators momentarily. * * @platform ios */ flashScrollIndicators: function() { this.getScrollResponder().scrollResponderFlashScrollIndicators(); }, _getKeyForIndex: function(index, childArray) { const child = childArray[index]; return child && child.key; }, _updateAnimatedNodeAttachment: function() { if (this._scrollAnimatedValueAttachment) { this._scrollAnimatedValueAttachment.detach(); } if (this.props.stickyHeaderIndices && this.props.stickyHeaderIndices.length > 0) { this._scrollAnimatedValueAttachment = Animated.attachNativeEvent( this._scrollViewRef, 'onScroll', [{nativeEvent: {contentOffset: {y: this._scrollAnimatedValue}}}] ); } }, _setStickyHeaderRef: function(key, ref) { if (ref) { this._stickyHeaderRefs.set(key, ref); } else { this._stickyHeaderRefs.delete(key); } }, _onStickyHeaderLayout: function(index, event, key) { if (!this.props.stickyHeaderIndices) { return; } const childArray = React.Children.toArray(this.props.children); if (key !== this._getKeyForIndex(index, childArray)) { // ignore stale layout update return; } const layoutY = event.nativeEvent.layout.y; this._headerLayoutYs.set(key, layoutY); const indexOfIndex = this.props.stickyHeaderIndices.indexOf(index); const previousHeaderIndex = this.props.stickyHeaderIndices[indexOfIndex - 1]; if (previousHeaderIndex != null) { const previousHeader = this._stickyHeaderRefs.get( this._getKeyForIndex(previousHeaderIndex, childArray) ); previousHeader && previousHeader.setNextHeaderY(layoutY); } }, _handleScroll: function(e: Object) { if (__DEV__) { if (this.props.onScroll && this.props.scrollEventThrottle == null && Platform.OS === 'ios') { console.log( // eslint-disable-line no-console-disallow 'You specified `onScroll` on a <ScrollView> but not ' + '`scrollEventThrottle`. You will only receive one event. ' + 'Using `16` you get all the events but be aware that it may ' + 'cause frame drops, use a bigger number if you don\'t need as ' + 'much precision.' ); } } if (Platform.OS === 'android') { if (this.props.keyboardDismissMode === 'on-drag') { dismissKeyboard(); } } this.scrollResponderHandleScroll(e); }, _handleContentOnLayout: function(e: Object) { const {width, height} = e.nativeEvent.layout; this.props.onContentSizeChange && this.props.onContentSizeChange(width, height); }, _scrollViewRef: (null: ?ScrollView), _setScrollViewRef: function(ref: ?ScrollView) { this._scrollViewRef = ref; }, _innerViewRef: (null: ?NativeMethodsMixinType), _setInnerViewRef: function(ref: ?NativeMethodsMixinType) { this._innerViewRef = ref; }, render: function() { let ScrollViewClass; let ScrollContentContainerViewClass; if (Platform.OS === 'ios') { ScrollViewClass = RCTScrollView; ScrollContentContainerViewClass = RCTScrollContentView; warning( !this.props.snapToInterval || !this.props.pagingEnabled, 'snapToInterval is currently ignored when pagingEnabled is true.' ); } else if (Platform.OS === 'android') { if (this.props.horizontal) { ScrollViewClass = AndroidHorizontalScrollView; } else { ScrollViewClass = AndroidScrollView; } ScrollContentContainerViewClass = View; } invariant( ScrollViewClass !== undefined, 'ScrollViewClass must not be undefined' ); invariant( ScrollContentContainerViewClass !== undefined, 'ScrollContentContainerViewClass must not be undefined' ); const contentContainerStyle = [ this.props.horizontal && styles.contentContainerHorizontal, this.props.contentContainerStyle, ]; let style, childLayoutProps; if (__DEV__ && this.props.style) { style = flattenStyle(this.props.style); childLayoutProps = ['alignItems', 'justifyContent'] .filter((prop) => style && style[prop] !== undefined); invariant( childLayoutProps.length === 0, 'ScrollView child layout (' + JSON.stringify(childLayoutProps) + ') must be applied through the contentContainerStyle prop.' ); } let contentSizeChangeProps = {}; if (this.props.onContentSizeChange) { contentSizeChangeProps = { onLayout: this._handleContentOnLayout, }; } const {stickyHeaderIndices} = this.props; const hasStickyHeaders = stickyHeaderIndices && stickyHeaderIndices.length > 0; const childArray = hasStickyHeaders && React.Children.toArray(this.props.children); const children = hasStickyHeaders ? childArray.map((child, index) => { const indexOfIndex = child ? stickyHeaderIndices.indexOf(index) : -1; if (indexOfIndex > -1) { const key = child.key; const nextIndex = stickyHeaderIndices[indexOfIndex + 1]; return ( <ScrollViewStickyHeader key={key} ref={(ref) => this._setStickyHeaderRef(key, ref)} nextHeaderLayoutY={ this._headerLayoutYs.get(this._getKeyForIndex(nextIndex, childArray)) } onLayout={(event) => this._onStickyHeaderLayout(index, event, key)} scrollAnimatedValue={this._scrollAnimatedValue}> {child} </ScrollViewStickyHeader> ); } else { return child; } }) : this.props.children; const contentContainer = <ScrollContentContainerViewClass {...contentSizeChangeProps} ref={this._setInnerViewRef} style={contentContainerStyle} removeClippedSubviews={ // Subview clipping causes issues with sticky headers on Android and // would be hard to fix properly in a performant way. Platform.OS === 'android' && hasStickyHeaders ? false : this.props.removeClippedSubviews } collapsable={false}> {children} </ScrollContentContainerViewClass>; const alwaysBounceHorizontal = this.props.alwaysBounceHorizontal !== undefined ? this.props.alwaysBounceHorizontal : this.props.horizontal; const alwaysBounceVertical = this.props.alwaysBounceVertical !== undefined ? this.props.alwaysBounceVertical : !this.props.horizontal; const DEPRECATED_sendUpdatedChildFrames = !!this.props.DEPRECATED_sendUpdatedChildFrames; const baseStyle = this.props.horizontal ? styles.baseHorizontal : styles.baseVertical; const props = { ...this.props, alwaysBounceHorizontal, alwaysBounceVertical, style: ([baseStyle, this.props.style]: ?Array<any>), // Override the onContentSizeChange from props, since this event can // bubble up from TextInputs onContentSizeChange: null, onMomentumScrollBegin: this.scrollResponderHandleMomentumScrollBegin, onMomentumScrollEnd: this.scrollResponderHandleMomentumScrollEnd, onResponderGrant: this.scrollResponderHandleResponderGrant, onResponderReject: this.scrollResponderHandleResponderReject, onResponderRelease: this.scrollResponderHandleResponderRelease, onResponderTerminate: this.scrollResponderHandleTerminate, onResponderTerminationRequest: this.scrollResponderHandleTerminationRequest, onScroll: this._handleScroll, onScrollBeginDrag: this.scrollResponderHandleScrollBeginDrag, onScrollEndDrag: this.scrollResponderHandleScrollEndDrag, onScrollShouldSetResponder: this.scrollResponderHandleScrollShouldSetResponder, onStartShouldSetResponder: this.scrollResponderHandleStartShouldSetResponder, onStartShouldSetResponderCapture: this.scrollResponderHandleStartShouldSetResponderCapture, onTouchEnd: this.scrollResponderHandleTouchEnd, onTouchMove: this.scrollResponderHandleTouchMove, onTouchStart: this.scrollResponderHandleTouchStart, scrollEventThrottle: hasStickyHeaders ? 1 : this.props.scrollEventThrottle, sendMomentumEvents: (this.props.onMomentumScrollBegin || this.props.onMomentumScrollEnd) ? true : false, DEPRECATED_sendUpdatedChildFrames, }; const { decelerationRate } = this.props; if (decelerationRate) { props.decelerationRate = processDecelerationRate(decelerationRate); } const refreshControl = this.props.refreshControl; if (refreshControl) { if (Platform.OS === 'ios') { // On iOS the RefreshControl is a child of the ScrollView. // tvOS lacks native support for RefreshControl, so don't include it in that case return ( <ScrollViewClass {...props} ref={this._setScrollViewRef}> {Platform.isTVOS ? null : refreshControl} {contentContainer} </ScrollViewClass> ); } else if (Platform.OS === 'android') { // On Android wrap the ScrollView with a AndroidSwipeRefreshLayout. // Since the ScrollView is wrapped add the style props to the // AndroidSwipeRefreshLayout and use flex: 1 for the ScrollView. // Note: we should only apply props.style on the wrapper // however, the ScrollView still needs the baseStyle to be scrollable return React.cloneElement( refreshControl, {style: props.style}, <ScrollViewClass {...props} style={baseStyle} ref={this._setScrollViewRef}> {contentContainer} </ScrollViewClass> ); } } return ( <ScrollViewClass {...props} ref={this._setScrollViewRef}> {contentContainer} </ScrollViewClass> ); } }); const styles = StyleSheet.create({ baseVertical: { flexGrow: 1, flexShrink: 1, flexDirection: 'column', overflow: 'scroll', }, baseHorizontal: { flexGrow: 1, flexShrink: 1, flexDirection: 'row', overflow: 'scroll', }, contentContainerHorizontal: { flexDirection: 'row', }, }); let nativeOnlyProps, AndroidScrollView, AndroidHorizontalScrollView, RCTScrollView, RCTScrollContentView; if (Platform.OS === 'android') { nativeOnlyProps = { nativeOnly: { sendMomentumEvents: true, } }; AndroidScrollView = requireNativeComponent( 'RCTScrollView', (ScrollView: ReactClass<any>), nativeOnlyProps ); AndroidHorizontalScrollView = requireNativeComponent( 'AndroidHorizontalScrollView', (ScrollView: ReactClass<any>), nativeOnlyProps ); } else if (Platform.OS === 'ios') { nativeOnlyProps = { nativeOnly: { onMomentumScrollBegin: true, onMomentumScrollEnd : true, onScrollBeginDrag: true, onScrollEndDrag: true, } }; RCTScrollView = requireNativeComponent( 'RCTScrollView', (ScrollView: ReactClass<any>), nativeOnlyProps, ); // $FlowFixMe (bvaughn) Update ComponentInterface in ViewPropTypes to include a string type (for Fiber host components) in a follow-up. RCTScrollContentView = requireNativeComponent('RCTScrollContentView', View); } module.exports = ScrollView;
var name = "Fine Friend"; var collection_type = 0; var is_secret = 0; var desc = "Made 7 friends"; var status_text = "You're getting pretty popular! You've earned a Fine Friend badge."; var last_published = 1316379385; var is_shareworthy = 0; var url = "fine-friend"; var category = "social"; var url_swf = "\/c2.glitch.bz\/achievements\/2011-09-14\/fine_friend_1316061689.swf"; var url_img_180 = "\/c2.glitch.bz\/achievements\/2011-09-14\/fine_friend_1316061689_180.png"; var url_img_60 = "\/c2.glitch.bz\/achievements\/2011-09-14\/fine_friend_1316061689_60.png"; var url_img_40 = "\/c2.glitch.bz\/achievements\/2011-09-14\/fine_friend_1316061689_40.png"; function on_apply(pc){ } var conditions = { 211 : { type : "counter", group : "player", label : "buddies_count", value : "7" }, }; function onComplete(pc){ // generated from rewards var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0; multiplier += pc.imagination_get_achievement_modifier(); if (/completist/i.exec(this.name)) { var level = pc.stats_get_level(); if (level > 4) { multiplier *= (pc.stats_get_level()/4); } } pc.stats_add_favor_points("friendly", round_to_5(10 * multiplier)); if(pc.buffs_has('gift_of_gab')) { pc.buffs_remove('gift_of_gab'); } else if(pc.buffs_has('silvertongue')) { pc.buffs_remove('silvertongue'); } } var rewards = { "favor" : { "giant" : "friendly", "points" : 10 } }; // generated ok (NO DATE)
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; const models = require('./index'); /** * The inputs for the Azure Machine Learning web service endpoint. * */ class AzureMachineLearningWebServiceInputs { /** * Create a AzureMachineLearningWebServiceInputs. * @member {string} [name] The name of the input. This is the name provided * while authoring the endpoint. * @member {array} [columnNames] A list of input columns for the Azure * Machine Learning web service endpoint. */ constructor() { } /** * Defines the metadata of AzureMachineLearningWebServiceInputs * * @returns {object} metadata of AzureMachineLearningWebServiceInputs * */ mapper() { return { required: false, serializedName: 'AzureMachineLearningWebServiceInputs', type: { name: 'Composite', className: 'AzureMachineLearningWebServiceInputs', modelProperties: { name: { required: false, serializedName: 'name', type: { name: 'String' } }, columnNames: { required: false, serializedName: 'columnNames', type: { name: 'Sequence', element: { required: false, serializedName: 'AzureMachineLearningWebServiceInputColumnElementType', type: { name: 'Composite', className: 'AzureMachineLearningWebServiceInputColumn' } } } } } } }; } } module.exports = AzureMachineLearningWebServiceInputs;
'use strict'; /* jshint -W030 */ /* jshint -W110 */ var chai = require('chai') , expect = chai.expect , Sequelize = require('../../index') , Support = require(__dirname + '/support') , DataTypes = require(__dirname + '/../../lib/data-types') , dialect = Support.getTestDialect() , config = require(__dirname + '/../config/config') , sinon = require('sinon') , uuid = require('node-uuid') , current = Support.sequelize; describe(Support.getTestDialectTeaser('Instance'), function() { before(function () { this.clock = sinon.useFakeTimers(); }); after(function () { this.clock.restore(); }); beforeEach(function() { this.User = this.sequelize.define('User', { username: { type: DataTypes.STRING }, uuidv1: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV1 }, uuidv4: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4 }, touchedAt: { type: DataTypes.DATE, defaultValue: DataTypes.NOW }, aNumber: { type: DataTypes.INTEGER }, bNumber: { type: DataTypes.INTEGER }, aDate: { type: DataTypes.DATE }, validateTest: { type: DataTypes.INTEGER, allowNull: true, validate: {isInt: true} }, validateCustom: { type: DataTypes.STRING, allowNull: true, validate: {len: {msg: 'Length failed.', args: [1, 20]}} }, dateAllowNullTrue: { type: DataTypes.DATE, allowNull: true }, isSuperUser: { type: DataTypes.BOOLEAN, defaultValue: false } }); return this.User.sync({ force: true }); }); describe('Escaping', function() { it('is done properly for special characters', function() { // Ideally we should test more: "\0\n\r\b\t\\\'\"\x1a" // But this causes sqlite to fail and exits the entire test suite immediately var bio = dialect + "'\"\n" // Need to add the dialect here so in case of failure I know what DB it failed for , self = this; return this.User.create({ username: bio }).then(function(u1) { return self.User.findById(u1.id).then(function(u2) { expect(u2.username).to.equal(bio); }); }); }); }); describe('isNewRecord', function() { it('returns true for non-saved objects', function() { var user = this.User.build({ username: 'user' }); expect(user.id).to.be.null; expect(user.isNewRecord).to.be.ok; }); it('returns false for saved objects', function() { return this.User.build({ username: 'user' }).save().then(function(user) { expect(user.isNewRecord).to.not.be.ok; }); }); it('returns false for created objects', function() { return this.User.create({ username: 'user' }).then(function(user) { expect(user.isNewRecord).to.not.be.ok; }); }); it('returns false for objects found by find method', function() { var self = this; return this.User.create({ username: 'user' }).then(function() { return self.User.create({ username: 'user' }).then(function(user) { return self.User.findById(user.id).then(function(user) { expect(user.isNewRecord).to.not.be.ok; }); }); }); }); it('returns false for objects found by findAll method', function() { var self = this , users = []; for (var i = 0; i < 10; i++) { users[users.length] = {username: 'user'}; } return this.User.bulkCreate(users).then(function() { return self.User.findAll().then(function(users) { users.forEach(function(u) { expect(u.isNewRecord).to.not.be.ok; }); }); }); }); }); describe('increment', function() { beforeEach(function() { return this.User.create({ id: 1, aNumber: 0, bNumber: 0 }); }); if (current.dialect.supports.transactions) { it('supports transactions', function() { return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) { var User = sequelize.define('User', { number: Support.Sequelize.INTEGER }); return User.sync({ force: true }).then(function() { return User.create({ number: 1 }).then(function(user) { return sequelize.transaction().then(function(t) { return user.increment('number', { by: 2, transaction: t }).then(function() { return User.findAll().then(function(users1) { return User.findAll({ transaction: t }).then(function(users2) { expect(users1[0].number).to.equal(1); expect(users2[0].number).to.equal(3); return t.rollback(); }); }); }); }); }); }); }); }); } if (current.dialect.supports.returnValues.returning) { it('supports returning', function() { return this.User.findById(1).then(function(user1) { return user1.increment('aNumber', { by: 2 }).then(function() { expect(user1.aNumber).to.be.equal(2); }); }); }); } it('supports where conditions', function() { var self = this; return this.User.findById(1).then(function(user1) { return user1.increment(['aNumber'], { by: 2, where: { bNumber: 1 } }).then(function() { return self.User.findById(1).then(function(user3) { expect(user3.aNumber).to.be.equal(0); }); }); }); }); it('with array', function() { var self = this; return this.User.findById(1).then(function(user1) { return user1.increment(['aNumber'], { by: 2 }).then(function() { return self.User.findById(1).then(function(user3) { expect(user3.aNumber).to.be.equal(2); }); }); }); }); it('with single field', function() { var self = this; return this.User.findById(1).then(function(user1) { return user1.increment('aNumber', { by: 2 }).then(function() { return self.User.findById(1).then(function(user3) { expect(user3.aNumber).to.be.equal(2); }); }); }); }); it('with single field and no value', function() { var self = this; return this.User.findById(1).then(function(user1) { return user1.increment('aNumber').then(function() { return self.User.findById(1).then(function(user2) { expect(user2.aNumber).to.be.equal(1); }); }); }); }); it('should still work right with other concurrent updates', function() { var self = this; return this.User.findById(1).then(function(user1) { // Select the user again (simulating a concurrent query) return self.User.findById(1).then(function(user2) { return user2.updateAttributes({ aNumber: user2.aNumber + 1 }).then(function() { return user1.increment(['aNumber'], { by: 2 }).then(function() { return self.User.findById(1).then(function(user5) { expect(user5.aNumber).to.be.equal(3); }); }); }); }); }); }); it('should still work right with other concurrent increments', function() { var self = this; return this.User.findById(1).then(function(user1) { return this.sequelize.Promise.all([ user1.increment(['aNumber'], { by: 2 }), user1.increment(['aNumber'], { by: 2 }), user1.increment(['aNumber'], { by: 2 }) ]).then(function() { return self.User.findById(1).then(function(user2) { expect(user2.aNumber).to.equal(6); }); }); }); }); it('with key value pair', function() { var self = this; return this.User.findById(1).then(function(user1) { return user1.increment({ 'aNumber': 1, 'bNumber': 2 }).then(function() { return self.User.findById(1).then(function(user3) { expect(user3.aNumber).to.be.equal(1); expect(user3.bNumber).to.be.equal(2); }); }); }); }); it('with timestamps set to true', function() { var User = this.sequelize.define('IncrementUser', { aNumber: DataTypes.INTEGER }, { timestamps: true }) , oldDate; return User.sync({ force: true }).bind(this).then(function() { return User.create({aNumber: 1}); }).then(function(user) { oldDate = user.updatedAt; this.clock.tick(1000); return user.increment('aNumber', {by: 1}); }).then(function() { return expect(User.findById(1)).to.eventually.have.property('updatedAt').afterTime(oldDate); }); }); }); describe('decrement', function() { beforeEach(function() { return this.User.create({ id: 1, aNumber: 0, bNumber: 0 }); }); if (current.dialect.supports.transactions) { it('supports transactions', function() { return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) { var User = sequelize.define('User', { number: Support.Sequelize.INTEGER }); return User.sync({ force: true }).then(function() { return User.create({ number: 3 }).then(function(user) { return sequelize.transaction().then(function(t) { return user.decrement('number', { by: 2, transaction: t }).then(function() { return User.findAll().then(function(users1) { return User.findAll({ transaction: t }).then(function(users2) { expect(users1[0].number).to.equal(3); expect(users2[0].number).to.equal(1); return t.rollback(); }); }); }); }); }); }); }); }); } it('with array', function() { var self = this; return this.User.findById(1).then(function(user1) { return user1.decrement(['aNumber'], { by: 2 }).then(function() { return self.User.findById(1).then(function(user3) { expect(user3.aNumber).to.be.equal(-2); }); }); }); }); it('with single field', function() { var self = this; return this.User.findById(1).then(function(user1) { return user1.decrement('aNumber', { by: 2 }).then(function() { return self.User.findById(1).then(function(user3) { expect(user3.aNumber).to.be.equal(-2); }); }); }); }); it('with single field and no value', function() { var self = this; return this.User.findById(1).then(function(user1) { return user1.decrement('aNumber').then(function() { return self.User.findById(1).then(function(user2) { expect(user2.aNumber).to.be.equal(-1); }); }); }); }); it('should still work right with other concurrent updates', function() { var self = this; return this.User.findById(1).then(function(user1) { // Select the user again (simulating a concurrent query) return self.User.findById(1).then(function(user2) { return user2.updateAttributes({ aNumber: user2.aNumber + 1 }).then(function() { return user1.decrement(['aNumber'], { by: 2 }).then(function() { return self.User.findById(1).then(function(user5) { expect(user5.aNumber).to.be.equal(-1); }); }); }); }); }); }); it('should still work right with other concurrent increments', function() { var self = this; return this.User.findById(1).then(function(user1) { return this.sequelize.Promise.all([ user1.decrement(['aNumber'], { by: 2 }), user1.decrement(['aNumber'], { by: 2 }), user1.decrement(['aNumber'], { by: 2 }) ]).then(function() { return self.User.findById(1).then(function(user2) { expect(user2.aNumber).to.equal(-6); }); }); }); }); it('with key value pair', function() { var self = this; return this.User.findById(1).then(function(user1) { return user1.decrement({ 'aNumber': 1, 'bNumber': 2}).then(function() { return self.User.findById(1).then(function(user3) { expect(user3.aNumber).to.be.equal(-1); expect(user3.bNumber).to.be.equal(-2); }); }); }); }); it('with timestamps set to true', function() { var User = this.sequelize.define('IncrementUser', { aNumber: DataTypes.INTEGER }, { timestamps: true }) , oldDate; return User.sync({ force: true }).bind(this).then(function() { return User.create({aNumber: 1}); }).then(function(user) { oldDate = user.updatedAt; this.clock.tick(1000); return user.decrement('aNumber', {by: 1}); }).then(function() { return expect(User.findById(1)).to.eventually.have.property('updatedAt').afterTime(oldDate); }); }); }); describe('reload', function() { if (current.dialect.supports.transactions) { it('supports transactions', function() { return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) { var User = sequelize.define('User', { username: Support.Sequelize.STRING }); return User.sync({ force: true }).then(function() { return User.create({ username: 'foo' }).then(function(user) { return sequelize.transaction().then(function(t) { return User.update({ username: 'bar' }, {where: {username: 'foo'}, transaction: t }).then(function() { return user.reload().then(function(user) { expect(user.username).to.equal('foo'); return user.reload({ transaction: t }).then(function(user) { expect(user.username).to.equal('bar'); return t.rollback(); }); }); }); }); }); }); }); }); } it('should return a reference to the same DAO instead of creating a new one', function() { return this.User.create({ username: 'John Doe' }).then(function(originalUser) { return originalUser.updateAttributes({ username: 'Doe John' }).then(function() { return originalUser.reload().then(function(updatedUser) { expect(originalUser === updatedUser).to.be.true; }); }); }); }); it('should update the values on all references to the DAO', function() { var self = this; return this.User.create({ username: 'John Doe' }).then(function(originalUser) { return self.User.findById(originalUser.id).then(function(updater) { return updater.updateAttributes({ username: 'Doe John' }).then(function() { // We used a different reference when calling updateAttributes, so originalUser is now out of sync expect(originalUser.username).to.equal('John Doe'); return originalUser.reload().then(function(updatedUser) { expect(originalUser.username).to.equal('Doe John'); expect(updatedUser.username).to.equal('Doe John'); }); }); }); }); }); it('should support updating a subset of attributes', function () { return this.User.create({ aNumber: 1, bNumber: 1, }).bind(this).tap(function (user) { return this.User.update({ bNumber: 2 }, { where: { id: user.get('id') } }); }).then(function (user) { return user.reload({ attributes: ['bNumber'] }); }).then(function (user) { expect(user.get('aNumber')).to.equal(1); expect(user.get('bNumber')).to.equal(2); }); }); it('should update read only attributes as well (updatedAt)', function() { return this.User.create({ username: 'John Doe' }).bind(this).then(function(originalUser) { this.originallyUpdatedAt = originalUser.updatedAt; this.originalUser = originalUser; // Wait for a second, so updatedAt will actually be different this.clock.tick(1000); return this.User.findById(originalUser.id); }).then(function(updater) { return updater.updateAttributes({username: 'Doe John'}); }).then(function(updatedUser) { this.updatedUser = updatedUser; return this.originalUser.reload(); }).then(function() { expect(this.originalUser.updatedAt).to.be.above(this.originallyUpdatedAt); expect(this.updatedUser.updatedAt).to.be.above(this.originallyUpdatedAt); }); }); it('should update the associations as well', function() { var Book = this.sequelize.define('Book', { title: DataTypes.STRING }) , Page = this.sequelize.define('Page', { content: DataTypes.TEXT }); Book.hasMany(Page); Page.belongsTo(Book); return Book.sync({force: true}).then(function() { return Page.sync({force: true}).then(function() { return Book.create({ title: 'A very old book' }).then(function(book) { return Page.create({ content: 'om nom nom' }).then(function(page) { return book.setPages([page]).then(function() { return Book.findOne({ where: { id: book.id }, include: [Page] }).then(function(leBook) { return page.updateAttributes({ content: 'something totally different' }).then(function(page) { expect(leBook.Pages.length).to.equal(1); expect(leBook.Pages[0].content).to.equal('om nom nom'); expect(page.content).to.equal('something totally different'); return leBook.reload().then(function(leBook) { expect(leBook.Pages.length).to.equal(1); expect(leBook.Pages[0].content).to.equal('something totally different'); expect(page.content).to.equal('something totally different'); }); }); }); }); }); }); }); }); }); it('should update internal options of the instance', function() { var Book = this.sequelize.define('Book', { title: DataTypes.STRING }) , Page = this.sequelize.define('Page', { content: DataTypes.TEXT }); Book.hasMany(Page); Page.belongsTo(Book); return Book.sync({force: true}).then(function() { return Page.sync({force: true}).then(function() { return Book.create({ title: 'A very old book' }).then(function(book) { return Page.create().then(function(page) { return book.setPages([page]).then(function() { return Book.findOne({ where: { id: book.id } }).then(function(leBook) { var oldOptions = leBook.$options; return leBook.reload({ include: [Page] }).then(function(leBook) { expect(oldOptions).not.to.equal(leBook.$options); expect(leBook.$options.include.length).to.equal(1); expect(leBook.Pages.length).to.equal(1); expect(leBook.get({plain: true}).Pages.length).to.equal(1); }); }); }); }); }); }); }); }); it('should return an error when reload fails', function() { return this.User.create({ username: 'John Doe' }).then(function(user) { return user.destroy().then(function () { return expect(user.reload()).to.be.rejectedWith( Sequelize.InstanceError, 'Instance could not be reloaded because it does not exist anymore (find call returned null)' ); }); }); }); it('should set an association to null after deletion, 1-1', function() { var Shoe = this.sequelize.define('Shoe', { brand: DataTypes.STRING }) , Player = this.sequelize.define('Player', { name: DataTypes.STRING }); Player.hasOne(Shoe); Shoe.belongsTo(Player); return this.sequelize.sync({force: true}).then(function() { return Shoe.create({ brand: 'the brand', Player: { name: 'the player' } }, {include: [Player]}); }).then(function(shoe) { return Player.findOne({ where: { id: shoe.Player.id }, include: [Shoe] }).then(function(lePlayer) { expect(lePlayer.Shoe).not.to.be.null; return lePlayer.Shoe.destroy().return(lePlayer); }).then(function(lePlayer) { return lePlayer.reload(); }).then(function(lePlayer) { expect(lePlayer.Shoe).to.be.null; }); }); }); it('should set an association to empty after all deletion, 1-N', function() { var Team = this.sequelize.define('Team', { name: DataTypes.STRING }) , Player = this.sequelize.define('Player', { name: DataTypes.STRING }); Team.hasMany(Player); Player.belongsTo(Team); return this.sequelize.sync({force: true}).then(function() { return Team.create({ name: 'the team', Players: [{ name: 'the player1' }, { name: 'the player2' }] }, {include: [Player]}); }).then(function(team) { return Team.findOne({ where: { id: team.id }, include: [Player] }).then(function(leTeam) { expect(leTeam.Players).not.to.be.empty; return leTeam.Players[1].destroy().then(function() { return leTeam.Players[0].destroy(); }).return(leTeam); }).then(function(leTeam) { return leTeam.reload(); }).then(function(leTeam) { expect(leTeam.Players).to.be.empty; }); }); }); it('should update the associations after one element deleted', function() { var Team = this.sequelize.define('Team', { name: DataTypes.STRING }) , Player = this.sequelize.define('Player', { name: DataTypes.STRING }); Team.hasMany(Player); Player.belongsTo(Team); return this.sequelize.sync({force: true}).then(function() { return Team.create({ name: 'the team', Players: [{ name: 'the player1' }, { name: 'the player2' }] }, {include: [Player]}); }).then(function(team) { return Team.findOne({ where: { id: team.id }, include: [Player] }).then(function(leTeam) { expect(leTeam.Players).to.have.length(2); return leTeam.Players[0].destroy().return(leTeam); }).then(function(leTeam) { return leTeam.reload(); }).then(function(leTeam) { expect(leTeam.Players).to.have.length(1); }); }); }); }); describe('default values', function() { describe('uuid', function() { it('should store a string in uuidv1 and uuidv4', function() { var user = this.User.build({ username: 'a user'}); expect(user.uuidv1).to.be.a('string'); expect(user.uuidv4).to.be.a('string'); }); it('should store a string of length 36 in uuidv1 and uuidv4', function() { var user = this.User.build({ username: 'a user'}); expect(user.uuidv1).to.have.length(36); expect(user.uuidv4).to.have.length(36); }); it('should store a valid uuid in uuidv1 and uuidv4 that can be parsed to something of length 16', function() { var user = this.User.build({ username: 'a user'}); expect(uuid.parse(user.uuidv1)).to.have.length(16); expect(uuid.parse(user.uuidv4)).to.have.length(16); }); it('should store a valid uuid if the field is a primary key named id', function() { var Person = this.sequelize.define('Person', { id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV1, primaryKey: true } }); var person = Person.build({}); expect(person.id).to.be.ok; expect(person.id).to.have.length(36); }); }); describe('current date', function() { it('should store a date in touchedAt', function() { var user = this.User.build({ username: 'a user'}); expect(user.touchedAt).to.be.instanceof(Date); }); it('should store the current date in touchedAt', function() { var clock = sinon.useFakeTimers(); clock.tick(5000); var user = this.User.build({ username: 'a user'}); clock.restore(); expect(+user.touchedAt).to.be.equal(5000); }); }); describe('allowNull date', function() { it('should be just "null" and not Date with Invalid Date', function() { var self = this; return this.User.build({ username: 'a user'}).save().then(function() { return self.User.findOne({where: {username: 'a user'}}).then(function(user) { expect(user.dateAllowNullTrue).to.be.null; }); }); }); it('should be the same valid date when saving the date', function() { var self = this; var date = new Date(); return this.User.build({ username: 'a user', dateAllowNullTrue: date}).save().then(function() { return self.User.findOne({where: {username: 'a user'}}).then(function(user) { expect(user.dateAllowNullTrue.toString()).to.equal(date.toString()); }); }); }); }); describe('super user boolean', function() { it('should default to false', function() { return this.User.build({ username: 'a user' }) .save() .bind(this) .then(function() { return this.User.findOne({ where: { username: 'a user' } }) .then(function(user) { expect(user.isSuperUser).to.be.false; }); }); }); it('should override default when given truthy boolean', function() { return this.User.build({ username: 'a user', isSuperUser: true }) .save() .bind(this) .then(function() { return this.User.findOne({ where: { username: 'a user' } }) .then(function(user) { expect(user.isSuperUser).to.be.true; }); }); }); it('should override default when given truthy boolean-string ("true")', function() { return this.User.build({ username: 'a user', isSuperUser: "true" }) .save() .bind(this) .then(function() { return this.User.findOne({ where: { username: 'a user' } }) .then(function(user) { expect(user.isSuperUser).to.be.true; }); }); }); it('should override default when given truthy boolean-int (1)', function() { return this.User.build({ username: 'a user', isSuperUser: 1 }) .save() .bind(this) .then(function() { return this.User.findOne({ where: { username: 'a user' } }) .then(function(user) { expect(user.isSuperUser).to.be.true; }); }); }); it('should throw error when given value of incorrect type', function() { var callCount = 0; return this.User.build({ username: 'a user', isSuperUser: "INCORRECT_VALUE_TYPE" }) .save() .then(function () { callCount += 1; }) .catch(function(err) { expect(callCount).to.equal(0); expect(err).to.exist; expect(err.message).to.exist; }); }); }); }); describe('complete', function() { it('gets triggered if an error occurs', function() { return this.User.findOne({ where: ['asdasdasd'] }).catch(function(err) { expect(err).to.exist; expect(err.message).to.exist; }); }); it('gets triggered if everything was ok', function() { return this.User.count().then(function(result) { expect(result).to.exist; }); }); }); describe('save', function() { if (current.dialect.supports.transactions) { it('supports transactions', function() { return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) { var User = sequelize.define('User', { username: Support.Sequelize.STRING }); return User.sync({ force: true }).then(function() { return sequelize.transaction().then(function(t) { return User.build({ username: 'foo' }).save({ transaction: t }).then(function() { return User.count().then(function(count1) { return User.count({ transaction: t }).then(function(count2) { expect(count1).to.equal(0); expect(count2).to.equal(1); return t.rollback(); }); }); }); }); }); }); }); } it('only updates fields in passed array', function() { var self = this , date = new Date(1990, 1, 1); return this.User.create({ username: 'foo', touchedAt: new Date() }).then(function(user) { user.username = 'fizz'; user.touchedAt = date; return user.save({fields: ['username']}).then(function() { // re-select user return self.User.findById(user.id).then(function(user2) { // name should have changed expect(user2.username).to.equal('fizz'); // bio should be unchanged expect(user2.birthDate).not.to.equal(date); }); }); }); }); it('should work on a model with an attribute named length', function () { var Box = this.sequelize.define('box', { length : DataTypes.INTEGER, width : DataTypes.INTEGER, height : DataTypes.INTEGER }); return Box.sync({force: true}).then(function () { return Box.create({ length: 1, width: 2, height: 3 }).then(function (box) { return box.update({ length: 4, width: 5, height: 6 }); }).then(function () { return Box.findOne({}).then(function (box) { expect(box.get('length')).to.equal(4); expect(box.get('width')).to.equal(5); expect(box.get('height')).to.equal(6); }); }); }); }); it('only validates fields in passed array', function() { return this.User.build({ validateTest: 'cake', // invalid, but not saved validateCustom: '1' }).save({ fields: ['validateCustom'] }); }); describe('hooks', function () { it('should update attributes added in hooks when default fields are used', function () { var User = this.sequelize.define('User' + config.rand(), { name: DataTypes.STRING, bio: DataTypes.TEXT, email: DataTypes.STRING }); User.beforeUpdate(function(instance) { instance.set('email', 'B'); }); return User.sync({force: true}).then(function() { return User.create({ name: 'A', bio: 'A', email: 'A' }).then(function (user) { return user.set({ name: 'B', bio: 'B' }).save(); }).then(function () { return User.findOne({}); }).then(function (user) { expect(user.get('name')).to.equal('B'); expect(user.get('bio')).to.equal('B'); expect(user.get('email')).to.equal('B'); }); }); }); it('should update attributes changed in hooks when default fields are used', function () { var User = this.sequelize.define('User' + config.rand(), { name: DataTypes.STRING, bio: DataTypes.TEXT, email: DataTypes.STRING }); User.beforeUpdate(function(instance) { instance.set('email', 'C'); }); return User.sync({force: true}).then(function() { return User.create({ name: 'A', bio: 'A', email: 'A' }).then(function (user) { return user.set({ name: 'B', bio: 'B', email: 'B' }).save(); }).then(function () { return User.findOne({}); }).then(function (user) { expect(user.get('name')).to.equal('B'); expect(user.get('bio')).to.equal('B'); expect(user.get('email')).to.equal('C'); }); }); }); it('should validate attributes added in hooks when default fields are used', function () { var User = this.sequelize.define('User' + config.rand(), { name: DataTypes.STRING, bio: DataTypes.TEXT, email: { type: DataTypes.STRING, validate: { isEmail: true } } }); User.beforeUpdate(function(instance) { instance.set('email', 'B'); }); return User.sync({force: true}).then(function () { return User.create({ name: 'A', bio: 'A', email: 'valid.email@gmail.com' }).then(function (user) { return expect(user.set({ name: 'B' }).save()).to.be.rejectedWith(Sequelize.ValidationError); }).then(function () { return User.findOne({}).then(function (user) { expect(user.get('email')).to.equal('valid.email@gmail.com'); }); }); }); }); it('should validate attributes changed in hooks when default fields are used', function () { var User = this.sequelize.define('User' + config.rand(), { name: DataTypes.STRING, bio: DataTypes.TEXT, email: { type: DataTypes.STRING, validate: { isEmail: true } } }); User.beforeUpdate(function(instance) { instance.set('email', 'B'); }); return User.sync({force: true}).then(function () { return User.create({ name: 'A', bio: 'A', email: 'valid.email@gmail.com' }).then(function (user) { return expect(user.set({ name: 'B', email: 'still.valid.email@gmail.com' }).save()).to.be.rejectedWith(Sequelize.ValidationError); }).then(function () { return User.findOne({}).then(function (user) { expect(user.get('email')).to.equal('valid.email@gmail.com'); }); }); }); }); }); it('stores an entry in the database', function() { var username = 'user' , User = this.User , user = this.User.build({ username: username, touchedAt: new Date(1984, 8, 23) }); return User.findAll().then(function(users) { expect(users).to.have.length(0); return user.save().then(function() { return User.findAll().then(function(users) { expect(users).to.have.length(1); expect(users[0].username).to.equal(username); expect(users[0].touchedAt).to.be.instanceof(Date); expect(users[0].touchedAt).to.equalDate(new Date(1984, 8, 23)); }); }); }); }); it('handles an entry with primaryKey of zero', function() { var username = 'user' , newUsername = 'newUser' , User2 = this.sequelize.define('User2', { id: { type: DataTypes.INTEGER.UNSIGNED, autoIncrement: false, primaryKey: true }, username: { type: DataTypes.STRING } }); return User2.sync().then(function () { return User2.create({id: 0, username: username}).then(function (user){ expect(user).to.be.ok; expect(user.id).to.equal(0); expect(user.username).to.equal(username); return User2.findById(0).then(function (user) { expect(user).to.be.ok; expect(user.id).to.equal(0); expect(user.username).to.equal(username); return user.updateAttributes({username: newUsername}).then(function (user) { expect(user).to.be.ok; expect(user.id).to.equal(0); expect(user.username).to.equal(newUsername); }); }); }); }); }); it('updates the timestamps', function() { var now = new Date() , user = null; user = this.User.build({ username: 'user' }); this.clock.tick(1000); return expect(user.save()).to.eventually.have.property('updatedAt').afterTime(now); }); it('does not update timestamps when passing silent=true', function() { return this.User.create({ username: 'user' }).bind(this).then(function(user) { var updatedAt = user.updatedAt; this.clock.tick(1000); return expect(user.update({ username: 'userman' }, { silent: true })).to.eventually.have.property('updatedAt').equalTime(updatedAt); }); }); it('does not update timestamps when passing silent=true in a bulk update', function() { var self = this , updatedAtPeter , updatedAtPaul , data = [ { username: 'Paul' }, { username: 'Peter' } ]; return this.User.bulkCreate(data).bind(this).then(function() { return this.User.findAll(); }).then(function(users) { updatedAtPaul = users[0].updatedAt; updatedAtPeter = users[1].updatedAt; }) .then(function() { this.clock.tick(150); return this.User.update( { aNumber: 1 }, { where: {}, silent: true } ); }).then(function() { return self.User.findAll(); }).then(function(users) { expect(users[0].updatedAt).to.equalTime(updatedAtPeter); expect(users[1].updatedAt).to.equalTime(updatedAtPaul); }); }); describe('when nothing changed', function() { beforeEach(function () { this.clock = sinon.useFakeTimers(); }); afterEach(function () { this.clock.restore(); }); it('does not update timestamps', function() { var self = this; return self.User.create({ username: 'John' }).then(function() { return self.User.findOne({ username: 'John' }).then(function(user) { var updatedAt = user.updatedAt; self.clock.tick(2000); return user.save().then(function(newlySavedUser) { expect(newlySavedUser.updatedAt).to.equalTime(updatedAt); return self.User.findOne({ username: 'John' }).then(function(newlySavedUser) { expect(newlySavedUser.updatedAt).to.equalTime(updatedAt); }); }); }); }); }); }); it('updates with function and column value', function() { var self = this; return this.User.create({ aNumber: 42 }).then(function(user) { user.bNumber = self.sequelize.col('aNumber'); user.username = self.sequelize.fn('upper', 'sequelize'); return user.save().then(function() { return self.User.findById(user.id).then(function(user2) { expect(user2.username).to.equal('SEQUELIZE'); expect(user2.bNumber).to.equal(42); }); }); }); }); describe('without timestamps option', function() { it("doesn't update the updatedAt column", function() { var User2 = this.sequelize.define('User2', { username: DataTypes.STRING, updatedAt: DataTypes.DATE }, { timestamps: false }); return User2.sync().then(function() { return User2.create({ username: 'john doe' }).then(function(johnDoe) { // sqlite and mysql return undefined, whereas postgres returns null expect([undefined, null].indexOf(johnDoe.updatedAt)).not.to.be.equal(-1); }); }); }); }); describe('with custom timestamp options', function() { it('updates the createdAt column if updatedAt is disabled', function() { var now = new Date(); this.clock.tick(1000); var User2 = this.sequelize.define('User2', { username: DataTypes.STRING }, { updatedAt: false }); return User2.sync().then(function() { return User2.create({ username: 'john doe' }).then(function(johnDoe) { expect(johnDoe.updatedAt).to.be.undefined; expect(now).to.be.beforeTime(johnDoe.createdAt); }); }); }); it('updates the updatedAt column if createdAt is disabled', function() { var now = new Date(); this.clock.tick(1000); var User2 = this.sequelize.define('User2', { username: DataTypes.STRING }, { createdAt: false }); return User2.sync().then(function() { return User2.create({ username: 'john doe' }).then(function(johnDoe) { expect(johnDoe.createdAt).to.be.undefined; expect(now).to.be.beforeTime(johnDoe.updatedAt); }); }); }); it('works with `allowNull: false` on createdAt and updatedAt columns', function() { var User2 = this.sequelize.define('User2', { username: DataTypes.STRING, createdAt: { type: DataTypes.DATE, allowNull: false }, updatedAt: { type: DataTypes.DATE, allowNull: false } }, { timestamps: true }); return User2.sync().then(function() { return User2.create({ username: 'john doe' }).then(function(johnDoe) { expect(johnDoe.createdAt).to.be.an.instanceof(Date); expect( ! isNaN(johnDoe.createdAt.valueOf()) ).to.be.ok; expect(johnDoe.createdAt).to.equalTime(johnDoe.updatedAt); }); }); }); }); it('should fail a validation upon creating', function() { return this.User.create({aNumber: 0, validateTest: 'hello'}).catch(function(err) { expect(err).to.exist; expect(err).to.be.instanceof(Object); expect(err.get('validateTest')).to.be.instanceof(Array); expect(err.get('validateTest')[0]).to.exist; expect(err.get('validateTest')[0].message).to.equal('Validation isInt failed'); }); }); it('should fail a validation upon creating with hooks false', function() { return this.User.create({aNumber: 0, validateTest: 'hello'}, {hooks: false}).catch(function(err) { expect(err).to.exist; expect(err).to.be.instanceof(Object); expect(err.get('validateTest')).to.be.instanceof(Array); expect(err.get('validateTest')[0]).to.exist; expect(err.get('validateTest')[0].message).to.equal('Validation isInt failed'); }); }); it('should fail a validation upon building', function() { return this.User.build({aNumber: 0, validateCustom: 'aaaaaaaaaaaaaaaaaaaaaaaaaa'}).save() .catch(function(err) { expect(err).to.exist; expect(err).to.be.instanceof(Object); expect(err.get('validateCustom')).to.exist; expect(err.get('validateCustom')).to.be.instanceof(Array); expect(err.get('validateCustom')[0]).to.exist; expect(err.get('validateCustom')[0].message).to.equal('Length failed.'); }); }); it('should fail a validation when updating', function() { return this.User.create({aNumber: 0}).then(function(user) { return user.updateAttributes({validateTest: 'hello'}).catch(function(err) { expect(err).to.exist; expect(err).to.be.instanceof(Object); expect(err.get('validateTest')).to.exist; expect(err.get('validateTest')).to.be.instanceof(Array); expect(err.get('validateTest')[0]).to.exist; expect(err.get('validateTest')[0].message).to.equal('Validation isInt failed'); }); }); }); it('takes zero into account', function() { return this.User.build({ aNumber: 0 }).save({ fields: ['aNumber'] }).then(function(user) { expect(user.aNumber).to.equal(0); }); }); it('saves a record with no primary key', function() { var HistoryLog = this.sequelize.define('HistoryLog', { someText: { type: DataTypes.STRING }, aNumber: { type: DataTypes.INTEGER }, aRandomId: { type: DataTypes.INTEGER } }); return HistoryLog.sync().then(function() { return HistoryLog.create({ someText: 'Some random text', aNumber: 3, aRandomId: 5 }).then(function(log) { return log.updateAttributes({ aNumber: 5 }).then(function(newLog) { expect(newLog.aNumber).to.equal(5); }); }); }); }); describe('eagerly loaded objects', function() { beforeEach(function() { var self = this; this.UserEager = this.sequelize.define('UserEagerLoadingSaves', { username: DataTypes.STRING, age: DataTypes.INTEGER }, { timestamps: false }); this.ProjectEager = this.sequelize.define('ProjectEagerLoadingSaves', { title: DataTypes.STRING, overdue_days: DataTypes.INTEGER }, { timestamps: false }); this.UserEager.hasMany(this.ProjectEager, { as: 'Projects', foreignKey: 'PoobahId' }); this.ProjectEager.belongsTo(this.UserEager, { as: 'Poobah', foreignKey: 'PoobahId' }); return self.UserEager.sync({force: true}).then(function() { return self.ProjectEager.sync({force: true}); }); }); it('saves one object that has a collection of eagerly loaded objects', function() { var self = this; return this.UserEager.create({ username: 'joe', age: 1 }).then(function(user) { return self.ProjectEager.create({ title: 'project-joe1', overdue_days: 0 }).then(function(project1) { return self.ProjectEager.create({ title: 'project-joe2', overdue_days: 0 }).then(function(project2) { return user.setProjects([project1, project2]).then(function() { return self.UserEager.findOne({where: {age: 1}, include: [{model: self.ProjectEager, as: 'Projects'}]}).then(function(user) { expect(user.username).to.equal('joe'); expect(user.age).to.equal(1); expect(user.Projects).to.exist; expect(user.Projects.length).to.equal(2); user.age = user.age + 1; // happy birthday joe return user.save().then(function(user) { expect(user.username).to.equal('joe'); expect(user.age).to.equal(2); expect(user.Projects).to.exist; expect(user.Projects.length).to.equal(2); }); }); }); }); }); }); }); it('saves many objects that each a have collection of eagerly loaded objects', function() { var self = this; return this.UserEager.create({ username: 'bart', age: 20 }).then(function(bart) { return self.UserEager.create({ username: 'lisa', age: 20 }).then(function(lisa) { return self.ProjectEager.create({ title: 'detention1', overdue_days: 0 }).then(function(detention1) { return self.ProjectEager.create({ title: 'detention2', overdue_days: 0 }).then(function(detention2) { return self.ProjectEager.create({ title: 'exam1', overdue_days: 0 }).then(function(exam1) { return self.ProjectEager.create({ title: 'exam2', overdue_days: 0 }).then(function(exam2) { return bart.setProjects([detention1, detention2]).then(function() { return lisa.setProjects([exam1, exam2]).then(function() { return self.UserEager.findAll({where: {age: 20}, order: 'username ASC', include: [{model: self.ProjectEager, as: 'Projects'}]}).then(function(simpsons) { var _bart, _lisa; expect(simpsons.length).to.equal(2); _bart = simpsons[0]; _lisa = simpsons[1]; expect(_bart.Projects).to.exist; expect(_lisa.Projects).to.exist; expect(_bart.Projects.length).to.equal(2); expect(_lisa.Projects.length).to.equal(2); _bart.age = _bart.age + 1; // happy birthday bart - off to Moe's return _bart.save().then(function(savedbart) { expect(savedbart.username).to.equal('bart'); expect(savedbart.age).to.equal(21); _lisa.username = 'lsimpson'; return _lisa.save().then(function(savedlisa) { expect(savedlisa.username).to.equal('lsimpson'); expect(savedlisa.age).to.equal(20); }); }); }); }); }); }); }); }); }); }); }); }); it('saves many objects that each has one eagerly loaded object (to which they belong)', function() { var self = this; return this.UserEager.create({ username: 'poobah', age: 18 }).then(function(user) { return self.ProjectEager.create({ title: 'homework', overdue_days: 10 }).then(function(homework) { return self.ProjectEager.create({ title: 'party', overdue_days: 2 }).then(function(party) { return user.setProjects([homework, party]).then(function() { return self.ProjectEager.findAll({include: [{model: self.UserEager, as: 'Poobah'}]}).then(function(projects) { expect(projects.length).to.equal(2); expect(projects[0].Poobah).to.exist; expect(projects[1].Poobah).to.exist; expect(projects[0].Poobah.username).to.equal('poobah'); expect(projects[1].Poobah.username).to.equal('poobah'); projects[0].title = 'partymore'; projects[1].title = 'partymore'; projects[0].overdue_days = 0; projects[1].overdue_days = 0; return projects[0].save().then(function() { return projects[1].save().then(function() { return self.ProjectEager.findAll({where: {title: 'partymore', overdue_days: 0}, include: [{model: self.UserEager, as: 'Poobah'}]}).then(function(savedprojects) { expect(savedprojects.length).to.equal(2); expect(savedprojects[0].Poobah).to.exist; expect(savedprojects[1].Poobah).to.exist; expect(savedprojects[0].Poobah.username).to.equal('poobah'); expect(savedprojects[1].Poobah.username).to.equal('poobah'); }); }); }); }); }); }); }); }); }); }); }); describe('many to many relations', function() { var udo; beforeEach(function() { var self = this; this.User = this.sequelize.define('UserWithUsernameAndAgeAndIsAdmin', { username: DataTypes.STRING, age: DataTypes.INTEGER, isAdmin: DataTypes.BOOLEAN }, {timestamps: false}); this.Project = this.sequelize.define('NiceProject', { title: DataTypes.STRING }, {timestamps: false}); this.Project.hasMany(this.User); this.User.hasMany(this.Project); return this.User.sync({ force: true }).then(function() { return self.Project.sync({ force: true }).then(function() { return self.User.create({ username: 'fnord', age: 1, isAdmin: true }) .then(function(user) { udo = user; }); }); }); }); it.skip('Should assign a property to the instance', function() { // @thanpolas rethink this test, it doesn't make sense, a relation has // to be created first in the beforeEach(). return this.User.findOne({id: udo.id}) .then(function(user) { user.NiceProjectId = 1; expect(user.NiceProjectId).to.equal(1); }); }); }); describe('toJSON', function() { beforeEach(function() { var self = this; this.User = this.sequelize.define('UserWithUsernameAndAgeAndIsAdmin', { username: DataTypes.STRING, age: DataTypes.INTEGER, isAdmin: DataTypes.BOOLEAN }, { timestamps: false }); this.Project = this.sequelize.define('NiceProject', { title: DataTypes.STRING }, { timestamps: false }); this.User.hasMany(this.Project, { as: 'Projects', foreignKey: 'lovelyUserId' }); this.Project.belongsTo(this.User, { as: 'LovelyUser', foreignKey: 'lovelyUserId' }); return this.User.sync({ force: true }).then(function() { return self.Project.sync({ force: true }); }); }); it("dont return instance that isn't defined", function() { var self = this; return self.Project.create({ lovelyUserId: null }) .then(function(project) { return self.Project.findOne({ where: { id: project.id }, include: [ { model: self.User, as: 'LovelyUser' } ] }); }) .then(function(project) { var json = project.toJSON(); expect(json.LovelyUser).to.be.equal(null); }); }); it("dont return instances that aren't defined", function() { var self = this; return self.User.create({ username: 'cuss' }) .then(function(user) { return self.User.findOne({ where: { id: user.id }, include: [ { model: self.Project, as: 'Projects' } ] }); }) .then(function(user) { expect(user.Projects).to.be.instanceof(Array); expect(user.Projects).to.be.length(0); }); }); it('returns an object containing all values', function() { var user = this.User.build({ username: 'test.user', age: 99, isAdmin: true }); expect(user.toJSON()).to.deep.equal({ username: 'test.user', age: 99, isAdmin: true, id: null }); }); it('returns a response that can be stringified', function() { var user = this.User.build({ username: 'test.user', age: 99, isAdmin: true }); expect(JSON.stringify(user)).to.deep.equal('{"id":null,"username":"test.user","age":99,"isAdmin":true}'); }); it('returns a response that can be stringified and then parsed', function() { var user = this.User.build({ username: 'test.user', age: 99, isAdmin: true }); expect(JSON.parse(JSON.stringify(user))).to.deep.equal({ username: 'test.user', age: 99, isAdmin: true, id: null }); }); it('includes the eagerly loaded associations', function() { var self = this; return this.User.create({ username: 'fnord', age: 1, isAdmin: true }).then(function(user) { return self.Project.create({ title: 'fnord' }).then(function(project) { return user.setProjects([project]).then(function() { return self.User.findAll({include: [{ model: self.Project, as: 'Projects' }]}).then(function(users) { var _user = users[0]; expect(_user.Projects).to.exist; expect(JSON.parse(JSON.stringify(_user)).Projects).to.exist; return self.Project.findAll({include: [{ model: self.User, as: 'LovelyUser' }]}).then(function(projects) { var _project = projects[0]; expect(_project.LovelyUser).to.exist; expect(JSON.parse(JSON.stringify(_project)).LovelyUser).to.exist; }); }); }); }); }); }); }); describe('findAll', function() { beforeEach(function() { this.ParanoidUser = this.sequelize.define('ParanoidUser', { username: { type: DataTypes.STRING } }, { paranoid: true }); this.ParanoidUser.hasOne(this.ParanoidUser); return this.ParanoidUser.sync({ force: true }); }); it('sql should have paranoid condition', function() { var self = this; return self.ParanoidUser.create({ username: 'cuss' }) .then(function() { return self.ParanoidUser.findAll(); }) .then(function(users) { expect(users).to.have.length(1); return users[0].destroy(); }) .then(function() { return self.ParanoidUser.findAll(); }) .then(function(users) { expect(users).to.have.length(0); }); }); it('sequelize.and as where should include paranoid condition', function() { var self = this; return self.ParanoidUser.create({ username: 'cuss' }) .then(function() { return self.ParanoidUser.findAll({ where: self.sequelize.and({ username: 'cuss' }) }); }) .then(function(users) { expect(users).to.have.length(1); return users[0].destroy(); }) .then(function() { return self.ParanoidUser.findAll({ where: self.sequelize.and({ username: 'cuss' }) }); }) .then(function(users) { expect(users).to.have.length(0); }); }); it('sequelize.or as where should include paranoid condition', function() { var self = this; return self.ParanoidUser.create({ username: 'cuss' }) .then(function() { return self.ParanoidUser.findAll({ where: self.sequelize.or({ username: 'cuss' }) }); }) .then(function(users) { expect(users).to.have.length(1); return users[0].destroy(); }) .then(function() { return self.ParanoidUser.findAll({ where: self.sequelize.or({ username: 'cuss' }) }); }) .then(function(users) { expect(users).to.have.length(0); }); }); it('escapes a single single quotes properly in where clauses', function() { var self = this; return this.User .create({ username: "user'name" }) .then(function() { return self.User.findAll({ where: { username: "user'name" } }).then(function(users) { expect(users.length).to.equal(1); expect(users[0].username).to.equal("user'name"); }); }); }); it('escapes two single quotes properly in where clauses', function() { var self = this; return this.User .create({ username: "user''name" }) .then(function() { return self.User.findAll({ where: { username: "user''name" } }).then(function(users) { expect(users.length).to.equal(1); expect(users[0].username).to.equal("user''name"); }); }); }); it('returns the timestamps if no attributes have been specified', function() { var self = this; return this.User.create({ username: 'fnord' }).then(function() { return self.User.findAll().then(function(users) { expect(users[0].createdAt).to.exist; }); }); }); it('does not return the timestamps if the username attribute has been specified', function() { var self = this; return this.User.create({ username: 'fnord' }).then(function() { return self.User.findAll({ attributes: ['username'] }).then(function(users) { expect(users[0].createdAt).not.to.exist; expect(users[0].username).to.exist; }); }); }); it('creates the deletedAt property, when defining paranoid as true', function() { var self = this; return this.ParanoidUser.create({ username: 'fnord' }).then(function() { return self.ParanoidUser.findAll().then(function(users) { expect(users[0].deletedAt).to.be.null; }); }); }); it('destroys a record with a primary key of something other than id', function() { var UserDestroy = this.sequelize.define('UserDestroy', { newId: { type: DataTypes.STRING, primaryKey: true }, email: DataTypes.STRING }); return UserDestroy.sync().then(function() { return UserDestroy.create({newId: '123ABC', email: 'hello'}).then(function() { return UserDestroy.findOne({where: {email: 'hello'}}).then(function(user) { return user.destroy(); }); }); }); }); it('sets deletedAt property to a specific date when deleting an instance', function() { var self = this; return this.ParanoidUser.create({ username: 'fnord' }).then(function() { return self.ParanoidUser.findAll().then(function(users) { return users[0].destroy().then(function() { expect(users[0].deletedAt.getMonth).to.exist; return users[0].reload({ paranoid: false }).then(function(user) { expect(user.deletedAt.getMonth).to.exist; }); }); }); }); }); it('keeps the deletedAt-attribute with value null, when running updateAttributes', function() { var self = this; return this.ParanoidUser.create({ username: 'fnord' }).then(function() { return self.ParanoidUser.findAll().then(function(users) { return users[0].updateAttributes({username: 'newFnord'}).then(function(user) { expect(user.deletedAt).not.to.exist; }); }); }); }); it('keeps the deletedAt-attribute with value null, when updating associations', function() { var self = this; return this.ParanoidUser.create({ username: 'fnord' }).then(function() { return self.ParanoidUser.findAll().then(function(users) { return self.ParanoidUser.create({ username: 'linkedFnord' }).then(function(linkedUser) { return users[0].setParanoidUser(linkedUser).then(function(user) { expect(user.deletedAt).not.to.exist; }); }); }); }); }); it('can reuse query option objects', function() { var self = this; return this.User.create({ username: 'fnord' }).then(function() { var query = { where: { username: 'fnord' }}; return self.User.findAll(query).then(function(users) { expect(users[0].username).to.equal('fnord'); return self.User.findAll(query).then(function(users) { expect(users[0].username).to.equal('fnord'); }); }); }); }); }); describe('find', function() { it('can reuse query option objects', function() { var self = this; return this.User.create({ username: 'fnord' }).then(function() { var query = { where: { username: 'fnord' }}; return self.User.findOne(query).then(function(user) { expect(user.username).to.equal('fnord'); return self.User.findOne(query).then(function(user) { expect(user.username).to.equal('fnord'); }); }); }); }); it('returns null for null, undefined, and unset boolean values', function() { var Setting = this.sequelize.define('SettingHelper', { setting_key: DataTypes.STRING, bool_value: { type: DataTypes.BOOLEAN, allowNull: true }, bool_value2: { type: DataTypes.BOOLEAN, allowNull: true }, bool_value3: { type: DataTypes.BOOLEAN, allowNull: true } }, { timestamps: false, logging: false }); return Setting.sync({ force: true }).then(function() { return Setting.create({ setting_key: 'test', bool_value: null, bool_value2: undefined }).then(function() { return Setting.findOne({ where: { setting_key: 'test' } }).then(function(setting) { expect(setting.bool_value).to.equal(null); expect(setting.bool_value2).to.equal(null); expect(setting.bool_value3).to.equal(null); }); }); }); }); }); describe('equals', function() { it('can compare records with Date field', function() { var self = this; return this.User.create({ username: 'fnord' }).then(function(user1) { return self.User.findOne({ where: { username: 'fnord' }}).then(function(user2) { expect(user1.equals(user2)).to.be.true; }); }); }); it('does not compare the existence of associations', function () { var self = this; this.UserAssociationEqual = this.sequelize.define('UserAssociationEquals', { username: DataTypes.STRING, age: DataTypes.INTEGER }, { timestamps: false }); this.ProjectAssociationEqual = this.sequelize.define('ProjectAssocationEquals', { title: DataTypes.STRING, overdue_days: DataTypes.INTEGER }, { timestamps: false }); this.UserAssociationEqual.hasMany(this.ProjectAssociationEqual, { as: 'Projects', foreignKey: 'userId' }); this.ProjectAssociationEqual.belongsTo(this.UserAssociationEqual, { as: 'Users', foreignKey: 'userId' }); return this.UserAssociationEqual.sync({force: true}).then(function() { return self.ProjectAssociationEqual.sync({force: true}).then(function () { return self.UserAssociationEqual.create({ username: 'jimhalpert' }).then(function (user1) { return self.ProjectAssociationEqual.create({ title: 'A Cool Project'}).then(function (project1) { return user1.setProjects([project1]).then(function () { return self.UserAssociationEqual.findOne({ where: { username: 'jimhalpert' }, include: [{model: self.ProjectAssociationEqual, as: 'Projects'}] }).then(function (user2) { return self.UserAssociationEqual.create({ username: 'pambeesly' }).then(function (user3) { expect(user1.get('Projects')).to.not.exist; expect(user2.get('Projects')).to.exist; expect(user1.equals(user2)).to.be.true; expect(user1.equals(user3)).to.not.be.true; }); }); }); }); }); }); }); }); }); describe('values', function() { it('returns all values', function() { var User = this.sequelize.define('UserHelper', { username: DataTypes.STRING }, { timestamps: false, logging: false }); return User.sync().then(function() { var user = User.build({ username: 'foo' }); expect(user.get({ plain: true })).to.deep.equal({ username: 'foo', id: null }); }); }); }); describe('destroy', function() { if (current.dialect.supports.transactions) { it('supports transactions', function() { return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) { var User = sequelize.define('User', { username: Support.Sequelize.STRING }); return User.sync({ force: true }).then(function() { return User.create({ username: 'foo' }).then(function(user) { return sequelize.transaction().then(function(t) { return user.destroy({ transaction: t }).then(function() { return User.count().then(function(count1) { return User.count({ transaction: t }).then(function(count2) { expect(count1).to.equal(1); expect(count2).to.equal(0); return t.rollback(); }); }); }); }); }); }); }); }); } it('does not set the deletedAt date in subsequent destroys if dao is paranoid', function() { var UserDestroy = this.sequelize.define('UserDestroy', { name: Support.Sequelize.STRING, bio: Support.Sequelize.TEXT }, { paranoid: true }); return UserDestroy.sync({ force: true }).then(function() { return UserDestroy.create({name: 'hallo', bio: 'welt'}).then(function(user) { return user.destroy().then(function() { return user.reload({ paranoid: false }).then(function() { var deletedAt = user.deletedAt; return user.destroy().then(function() { return user.reload({ paranoid: false }).then(function() { expect(user.deletedAt).to.eql(deletedAt); }); }); }); }); }); }); }); it('deletes a record from the database if dao is not paranoid', function() { var UserDestroy = this.sequelize.define('UserDestroy', { name: Support.Sequelize.STRING, bio: Support.Sequelize.TEXT }); return UserDestroy.sync({ force: true }).then(function() { return UserDestroy.create({name: 'hallo', bio: 'welt'}).then(function(u) { return UserDestroy.findAll().then(function(users) { expect(users.length).to.equal(1); return u.destroy().then(function() { return UserDestroy.findAll().then(function(users) { expect(users.length).to.equal(0); }); }); }); }); }); }); it('allows sql logging of delete statements', function() { var UserDelete = this.sequelize.define('UserDelete', { name: Support.Sequelize.STRING, bio: Support.Sequelize.TEXT }); return UserDelete.sync({ force: true }).then(function() { return UserDelete.create({name: 'hallo', bio: 'welt'}).then(function(u) { return UserDelete.findAll().then(function(users) { expect(users.length).to.equal(1); return u.destroy({ logging: function (sql) { expect(sql).to.exist; expect(sql.toUpperCase().indexOf('DELETE')).to.be.above(-1); } }); }); }); }); }); it('delete a record of multiple primary keys table', function() { var MultiPrimary = this.sequelize.define('MultiPrimary', { bilibili: { type: Support.Sequelize.CHAR(2), primaryKey: true }, guruguru: { type: Support.Sequelize.CHAR(2), primaryKey: true } }); return MultiPrimary.sync({ force: true }).then(function() { return MultiPrimary.create({ bilibili: 'bl', guruguru: 'gu' }).then(function() { return MultiPrimary.create({ bilibili: 'bl', guruguru: 'ru' }).then(function(m2) { return MultiPrimary.findAll().then(function(ms) { expect(ms.length).to.equal(2); return m2.destroy({ logging: function(sql) { expect(sql).to.exist; expect(sql.toUpperCase().indexOf('DELETE')).to.be.above(-1); expect(sql.indexOf('ru')).to.be.above(-1); expect(sql.indexOf('bl')).to.be.above(-1); } }).then(function() { return MultiPrimary.findAll().then(function(ms) { expect(ms.length).to.equal(1); expect(ms[0].bilibili).to.equal('bl'); expect(ms[0].guruguru).to.equal('gu'); }); }); }); }); }); }); }); }); describe('restore', function() { it('returns an error if the model is not paranoid', function() { return this.User.create({username: 'Peter', secretValue: '42'}).then(function(user) { expect(function() {user.restore();}).to.throw(Error, 'Model is not paranoid'); }); }); it('restores a previously deleted model', function() { var self = this , ParanoidUser = self.sequelize.define('ParanoidUser', { username: DataTypes.STRING, secretValue: DataTypes.STRING, data: DataTypes.STRING, intVal: { type: DataTypes.INTEGER, defaultValue: 1} }, { paranoid: true }) , data = [{ username: 'Peter', secretValue: '42' }, { username: 'Paul', secretValue: '43' }, { username: 'Bob', secretValue: '44' }]; return ParanoidUser.sync({ force: true }).then(function() { return ParanoidUser.bulkCreate(data); }).then(function() { return ParanoidUser.findOne({where: {secretValue: '42'}}); }).then(function(user) { return user.destroy().then(function() { return user.restore(); }); }).then(function() { return ParanoidUser.findOne({where: {secretValue: '42'}}); }).then(function(user) { expect(user).to.be.ok; expect(user.username).to.equal('Peter'); }); }); }); });
'use strict'; angular.module('arethusa.core').directive('sidepanelFolder', [ 'sidepanel', '$window', 'translator', function(sidepanel, $window, translator) { return { scope: {}, link: function (scope, element, attrs) { var win = angular.element($window); scope.translations = translator({ 'sidepanel.show': 'show', 'sidepanel.fold': 'fold' }); scope.$watch('translations', function(newVal, oldVal) { if (newVal !== oldVal) { setIconClassAndTitle(); } }, true); function setIconClassAndTitle() { var icon = sidepanel.folded ? 'expand' : 'compress'; var text = sidepanel.folded ? 'show' : 'fold'; var key = arethusaUtil.formatKeyHint(sidepanel.activeKeys.toggle); scope.iconClass = 'fi-arrows-' + icon; element.attr('title', scope.translations[text]() + " " + key); } element.on('click', function () { sidepanel.toggle(); scope.$apply(setIconClassAndTitle()); }); scope.sp = sidepanel; var foldWatch = function() {}; scope.$watch('sp.active', function(newVal) { if (newVal) { element.show(); foldWatch = scope.$watch('sp.folded', function(newVal, oldVal) { setIconClassAndTitle(); win.trigger('resize'); }); } else { element.hide(); foldWatch(); } }); }, template: '<i ng-class="iconClass"/>' }; } ]);
var test = require('tape'); var bitIterator = require('../lib/bit_iterator'); test('should return the correct bit pattern across byte boundaries', function(t) { t.plan(5); var bi = bitIterator(function() { return new Buffer([0x0f,0x10,0x01,0x80]); }); t.equal(bi(16), 0x0f10); t.equal(bi(7), 0x0); t.equal(bi(2), 0x03); t.equal(bi(7), 0x0); t.equal(bi.bytesRead, 5); }); test('should correctly switch from one buffer to the next', function(t) { t.plan(4); var i = 0; var buffs = [[0x01],[0x80]]; var bi = bitIterator(function() { return buffs[i++]; }); t.equal(bi(7), 0x0); t.equal(bi(2), 0x03); t.equal(bi(7), 0x0); t.equal(bi.bytesRead, 3); }); test('each iterator has an independent bytesRead property', function(t) { t.plan(6); var i = 0, ii = 0; var buffs = [[0x01],[0x80]]; var bi1 = bitIterator(function() { return buffs[i++]; }); var bi2 = bitIterator(function() { return buffs[ii++]; }); t.equal(bi1.bytesRead, 1); t.equal(bi2.bytesRead, 1); bi1(9); t.equal(bi1.bytesRead, 2); t.equal(bi2.bytesRead, 1); bi2(7); t.equal(bi1.bytesRead, 2); t.equal(bi2.bytesRead, 1); });
'use strict'; var path = require('path') , chai = require('chai') , should = chai.should() , expect = chai.expect , fs = require('fs') , Config = require(path.join(__dirname, '..', 'lib', 'config')) ; function idempotentEnv(name, value, callback) { var is, saved; // process.env is not a normal object if (Object.hasOwnProperty.call(process.env, name)) { is = true; saved = process.env[name]; } process.env[name] = value; try { var tc = Config.initialize({}); callback(tc); } finally { if (is) { process.env[name] = saved; } else { delete process.env[name]; } } } describe("the agent configuration", function () { it("should handle a directly passed minimal configuration", function () { var c; expect(function testInitialize() { c = Config.initialize({}); }).not.throws(); expect(c.agent_enabled).equal(true); }); describe("when overriding configuration values via environment variables", function () { it("should pick up the application name", function () { idempotentEnv('NEW_RELIC_APP_NAME', 'feeling testy,and schizophrenic', function (tc) { should.exist(tc.app_name); expect(tc.app_name).eql(['feeling testy', 'and schizophrenic']); }); }); it("should trim spaces from multiple application names ", function () { idempotentEnv('NEW_RELIC_APP_NAME', 'zero,one, two, three, four', function (tc) { should.exist(tc.app_name); expect(tc.app_name).eql(['zero', 'one', 'two', 'three', 'four']); }); }); it("should pick up the license key", function () { idempotentEnv('NEW_RELIC_LICENSE_KEY', 'hambulance', function (tc) { should.exist(tc.license_key); expect(tc.license_key).equal('hambulance'); }); }); it("should pick up the collector host", function () { idempotentEnv('NEW_RELIC_HOST', 'localhost', function (tc) { should.exist(tc.host); expect(tc.host).equal('localhost'); }); }); it("should pick up the collector port", function () { idempotentEnv('NEW_RELIC_PORT', 7777, function (tc) { should.exist(tc.port); expect(tc.port).equal('7777'); }); }); it("should pick up the proxy host", function () { idempotentEnv('NEW_RELIC_PROXY_HOST', 'proxyhost', function (tc) { should.exist(tc.proxy_host); expect(tc.proxy_host).equal('proxyhost'); }); }); it("should pick up the proxy port", function () { idempotentEnv('NEW_RELIC_PROXY_PORT', 7777, function (tc) { should.exist(tc.proxy_port); expect(tc.proxy_port).equal('7777'); }); }); it("should pick up the log level", function () { idempotentEnv('NEW_RELIC_LOG_LEVEL', 'XXNOEXIST', function (tc) { should.exist(tc.logging.level); expect(tc.logging.level).equal('XXNOEXIST'); }); }); it("should pick up the log filepath", function () { idempotentEnv('NEW_RELIC_LOG', '/highway/to/the/danger/zone', function (tc) { should.exist(tc.logging.filepath); expect(tc.logging.filepath).equal('/highway/to/the/danger/zone'); }); }); it("should pick up whether server-side config is enabled", function () { idempotentEnv('NEW_RELIC_IGNORE_SERVER_CONFIGURATION', 'yeah', function (tc) { should.exist(tc.ignore_server_configuration); expect(tc.ignore_server_configuration).equal(true); }); }); it("should pick up whether the agent is enabled", function () { idempotentEnv('NEW_RELIC_ENABLED', 0, function (tc) { should.exist(tc.agent_enabled); expect(tc.agent_enabled).equal(false); }); }); it("should pick up whether the apdexT is set", function () { idempotentEnv('NEW_RELIC_APDEX', 0.666, function (tc) { should.exist(tc.apdex_t); expect(tc.apdex_t).equal('0.666'); }); }); it("should pick up whether to capture request parameters", function () { idempotentEnv('NEW_RELIC_CAPTURE_PARAMS', 'yes', function (tc) { should.exist(tc.capture_params); expect(tc.capture_params).equal(true); }); }); it("should pick up ignored request parameters", function () { idempotentEnv('NEW_RELIC_IGNORED_PARAMS', 'one,two,three', function (tc) { should.exist(tc.ignored_params); expect(tc.ignored_params).eql(['one', 'two', 'three']); }); }); it("should pick up whether the error collector is enabled", function () { idempotentEnv('NEW_RELIC_ERROR_COLLECTOR_ENABLED', 'NO', function (tc) { should.exist(tc.error_collector.enabled); expect(tc.error_collector.enabled).equal(false); }); }); it("should pick up which status codes are ignored", function () { idempotentEnv('NEW_RELIC_ERROR_COLLECTOR_IGNORE_ERROR_CODES', '401,404,502', function (tc) { should.exist(tc.error_collector.ignore_status_codes); expect(tc.error_collector.ignore_status_codes).eql([401, 404, 502]); }); }); it("should pick up whether the transaction tracer is enabled", function () { idempotentEnv('NEW_RELIC_TRACER_ENABLED', false, function (tc) { should.exist(tc.transaction_tracer.enabled); expect(tc.transaction_tracer.enabled).equal(false); }); }); it("should pick up the transaction trace threshold", function () { idempotentEnv('NEW_RELIC_TRACER_THRESHOLD', 0.02, function (tc) { should.exist(tc.transaction_tracer.transaction_threshold); expect(tc.transaction_tracer.transaction_threshold).equal('0.02'); }); }); it("should pick up the transaction trace Top N scale", function () { idempotentEnv('NEW_RELIC_TRACER_TOP_N', 5, function (tc) { should.exist(tc.transaction_tracer.top_n); expect(tc.transaction_tracer.top_n).equal('5'); }); }); it("should pick up whether internal metrics are enabled", function () { idempotentEnv('NEW_RELIC_DEBUG_METRICS', true, function (tc) { should.exist(tc.debug.internal_metrics); expect(tc.debug.internal_metrics).equal(true); }); }); it("should pick up whether tracing of the transaction tracer is enabled", function () { idempotentEnv('NEW_RELIC_DEBUG_TRACER', 'yup', function (tc) { should.exist(tc.debug.tracer_tracing); expect(tc.debug.tracer_tracing).equal(true); }); }); it("should pick up renaming rules", function () { idempotentEnv( 'NEW_RELIC_NAMING_RULES', '{"name":"u","pattern":"^t"},{"name":"t","pattern":"^u"}', function (tc) { should.exist(tc.rules.name); expect(tc.rules.name).eql([ {name : 'u', pattern : '^t'}, {name : 't', pattern : '^u'}, ]); } ); }); it("should pick up ignoring rules", function () { idempotentEnv( 'NEW_RELIC_IGNORING_RULES', '^/test,^/no_match,^/socket\\.io/,^/api/.*/index$', function (tc) { should.exist(tc.rules.ignore); expect(tc.rules.ignore).eql([ '^/test', '^/no_match', '^/socket\\.io/', '^/api/.*/index$' ]); } ); }); it("should pick up whether URL backstop has been turned off", function () { idempotentEnv('NEW_RELIC_ENFORCE_BACKSTOP', 'f', function (tc) { should.exist(tc.enforce_backstop); expect(tc.enforce_backstop).equal(false); }); }); it("should pick app name from APP_POOL_ID", function () { idempotentEnv('APP_POOL_ID', 'Simple Azure app', function (tc) { should.exist(tc.app_name); expect(tc.applications()).eql(['Simple Azure app']); }); }); }); describe("with default properties", function () { var configuration; before(function () { configuration = Config.initialize({}); // ensure environment is clean delete configuration.newrelic_home; }); it("should have no application name", function () { expect(configuration.app_name).eql([]); }); it("should return no application name", function () { expect(configuration.applications()).eql([]); }); it("should have no application ID", function () { expect(configuration.application_id).eql(null); }); it("should have no license key", function () { expect(configuration.license_key).equal(''); }); it("should connect to the collector at collector.newrelic.com", function () { expect(configuration.host).equal('collector.newrelic.com'); }); it("should connect to the collector on port 443", function () { expect(configuration.port).equal(443); }); it("should have SSL enabled", function () { expect(configuration.ssl).equal(true); }); it("should have no proxy host", function () { expect(configuration.proxy_host).equal(''); }); it("should have no proxy port", function () { expect(configuration.proxy_port).equal(''); }); it("should not ignore server-side configuration", function () { expect(configuration.ignore_server_configuration).equal(false); }); it("should enable the agent", function () { expect(configuration.agent_enabled).equal(true); }); it("should have an apdexT of 0.1", function () { expect(configuration.apdex_t).equal(0.1); }); it("should not capture request parameters", function () { expect(configuration.capture_params).equal(false); }); it("should have no ignored request parameters", function () { expect(configuration.ignored_params).eql([]); }); it("should log at the info level", function () { expect(configuration.logging.level).equal('info'); }); it("should have a log filepath of process.cwd + newrelic_agent.log", function () { var logPath = path.join(process.cwd(), 'newrelic_agent.log'); expect(configuration.logging.filepath).equal(logPath); }); it("should enable the error collector", function () { expect(configuration.error_collector.enabled).equal(true); }); it("should ignore status code 404", function () { expect(configuration.error_collector.ignore_status_codes).eql([404]); }); it("should enable the transaction tracer", function () { expect(configuration.transaction_tracer.enabled).equal(true); }); it("should set the transaction tracer threshold to 'apdex_f'", function () { expect(configuration.transaction_tracer.transaction_threshold).equal('apdex_f'); }); it("should collect one slow transaction trace per harvest cycle", function () { expect(configuration.transaction_tracer.top_n).equal(20); }); it("should not debug internal metrics", function () { expect(configuration.debug.internal_metrics).equal(false); }); it("REALLY should not trace the transaction tracer", function () { expect(configuration.debug.tracer_tracing).equal(false); }); it("should have no naming rules", function () { expect(configuration.rules.name.length).equal(0); }); it("should have no ignoring rules", function () { expect(configuration.rules.ignore.length).equal(0); }); it("should enforce URL backstop", function () { expect(configuration.enforce_backstop).equal(true); }); it("should allow passed-in config to override errors ignored", function () { configuration = Config.initialize({ error_collector : { ignore_status_codes : [] } }); expect(configuration.error_collector.ignore_status_codes).eql([]); }); }); describe("when overriding the config file location via NR_HOME", function () { var origHome , startDir , DESTDIR = path.join(__dirname, 'xXxNRHOMETESTxXx') , NOPLACEDIR = path.join(__dirname, 'NOHEREHERECHAMP') , CONFIGPATH = path.join(DESTDIR, 'newrelic.js') ; beforeEach(function (done) { if (process.env.NEW_RELIC_HOME) { origHome = process.env.NEW_RELIC_HOME; } startDir = process.cwd(); fs.mkdir(DESTDIR, function (error) { if (error) return done(error); fs.mkdir(NOPLACEDIR, function (error) { if (error) return done(error); process.chdir(NOPLACEDIR); process.env.NEW_RELIC_HOME = DESTDIR; var sampleConfig = fs.createReadStream(path.join(__dirname, '..', 'lib', 'config.default.js')); var sandboxedConfig = fs.createWriteStream(CONFIGPATH); sampleConfig.pipe(sandboxedConfig); sandboxedConfig.on('close', function () { return done(); }); }); }); }); afterEach(function (done) { if (origHome) { process.env.NEW_RELIC_HOME = origHome; } else { delete process.env.NEW_RELIC_HOME; } origHome = null; fs.unlink(CONFIGPATH, function (error) { if (error) return done(error); fs.rmdir(DESTDIR, function (error) { if (error) return done(error); process.chdir(startDir); fs.rmdir(NOPLACEDIR, done); }); }); }); it("should load the configuration", function () { expect(function () { Config.initialize(); }).not.throws(); }); it("should export the home directory on the resulting object", function () { var configuration = Config.initialize(); expect(configuration.newrelic_home).equal(DESTDIR); }); it("should ignore the configuration file completely when so directed", function () { process.env.NEW_RELIC_NO_CONFIG_FILE = 'true'; process.env.NEW_RELIC_HOME = '/xxxnoexist/nofile'; var configuration; expect(function envTest() { configuration = Config.initialize(); }).not.throws(); should.not.exist(configuration.newrelic_home); expect(configuration.error_collector && configuration.error_collector.enabled).equal(true); delete process.env.NEW_RELIC_NO_CONFIG_FILE; delete process.env.NEW_RELIC_HOME; }); }); describe("when receiving server-side configuration", function () { var config; beforeEach(function () { config = new Config(); }); it("should set the agent run ID", function () { config.onConnect({'agent_run_id' : 1234}); expect(config.run_id).equal(1234); }); it("should set the application ID", function () { config.onConnect({'application_id' : 76543}); expect(config.application_id).equal(76543); }); it("should always respect collect_traces", function () { expect(config.collect_traces).equal(true); config.onConnect({'collect_traces' : false}); expect(config.collect_traces).equal(false); }); it("should disable the transaction tracer when told to", function () { expect(config.transaction_tracer.enabled).equal(true); config.onConnect({'transaction_tracer.enabled' : false}); expect(config.transaction_tracer.enabled).equal(false); }); it("should always respect collect_errors", function () { expect(config.collect_errors).equal(true); config.onConnect({'collect_errors' : false}); expect(config.collect_errors).equal(false); }); it("should disable the error tracer when told to", function () { expect(config.error_collector.enabled).equal(true); config.onConnect({'error_collector.enabled' : false}); expect(config.error_collector.enabled).equal(false); }); it("should set apdex_t", function () { expect(config.apdex_t).equal(0.1); config.on('apdex_t', function (value) { expect(value).equal(0.05); }); config.onConnect({'apdex_t' : 0.05}); expect(config.apdex_t).equal(0.05); }); it("should map transaction_tracer.transaction_threshold", function () { expect(config.transaction_tracer.transaction_threshold).equal('apdex_f'); config.onConnect({'transaction_tracer.transaction_threshold' : 0.75}); expect(config.transaction_tracer.transaction_threshold).equal(0.75); }); it("should map URL rules to the URL normalizer", function (done) { config.on('url_rules', function (rules) { expect(rules).eql([{name : 'sample_rule'}]); done(); }); config.onConnect({'url_rules' : [{name : 'sample_rule'}]}); }); it("should map metric naming rules to the metric name normalizer", function (done) { config.on('metric_name_rules', function (rules) { expect(rules).eql([{name : 'sample_rule'}]); done(); }); config.onConnect({'metric_name_rules' : [{name : 'sample_rule'}]}); }); it("should map transaction naming rules to the transaction name normalizer", function (done) { config.on('transaction_name_rules', function (rules) { expect(rules).eql([{name : 'sample_rule'}]); done(); }); config.onConnect({'transaction_name_rules' : [{name : 'sample_rule'}]}); }); it("should log the product level", function () { expect(config.product_level).equal(0); config.onConnect({'product_level' : 30}); expect(config.product_level).equal(30); }); it("should reject high_security", function () { config.onConnect({'high_security' : true}); expect(config.high_security).equal(false); }); it("should configure param capture", function () { expect(config.capture_params).equal(false); config.onConnect({'capture_params' : true}); expect(config.capture_params).equal(true); }); it("should configure ignored params", function () { expect(config.ignored_params).eql([]); config.onConnect({'ignored_params' : ['a', 'b']}); expect(config.ignored_params).eql(['a', 'b']); }); it("should configure ignored params without stomping local config", function () { config.ignored_params = ['b', 'c']; config.onConnect({'ignored_params' : ['a', 'b']}); expect(config.ignored_params).eql(['b', 'c', 'a']); }); describe("when handling embedded agent_config", function () { it("shouldn't blow up when agent_config is passed in", function () { expect(function () { config.onConnect({'agent_config' : {}}); }).not.throws(); }); it("should ignore status codes set on the server", function () { config.onConnect({'agent_config' : { 'error_collector.ignore_status_codes' : [401, 409, 415] }}); expect(config.error_collector.ignore_status_codes).eql([404, 401, 409, 415]); }); it("should ignore status codes set on the server as strings", function () { config.onConnect({'agent_config' : { 'error_collector.ignore_status_codes' : ['401', '409', '415'] }}); expect(config.error_collector.ignore_status_codes).eql([404, 401, 409, 415]); }); }); it("should load named transaction apdexes", function () { var apdexes = {"WebTransaction/Custom/UrlGenerator/en/betting/Football" : 7.0}; expect(config.web_transactions_apdex).eql({}); config.onConnect({'web_transactions_apdex' : apdexes}); expect(config.web_transactions_apdex).eql(apdexes); }); it("shouldn't blow up when sampling_rate is received", function () { expect(function () { config.onConnect({'sampling_rate' : 0}); }).not.throws(); }); it("shouldn't blow up when cross_process_id is received", function () { expect(function () { config.onConnect({'cross_process_id' : 'junk'}); }).not.throws(); }); it("shouldn't blow up when cross_application_tracing is received", function () { expect(function () { config.onConnect({'cross_application_tracing' : true}); }).not.throws(); }); it("shouldn't blow up when encoding_key is received", function () { expect(function () { config.onConnect({'encoding_key' : 'hamsnadwich'}); }).not.throws(); }); it("shouldn't blow up when trusted_account_ids is received", function () { expect(function () { config.onConnect({'trusted_account_ids' : [1, 2, 3]}); }).not.throws(); }); it("shouldn't blow up when high_security is received", function () { expect(function () { config.onConnect({'high_security' : true}); }).not.throws(); }); it("shouldn't blow up when ssl is received", function () { expect(function () { config.onConnect({'ssl' : true}); }).not.throws(); }); it("shouldn't blow up when transaction_tracer.record_sql is received", function () { expect(function () { config.onConnect({'transaction_tracer.record_sql' : true}); }).not.throws(); }); it("shouldn't blow up when slow_sql.enabled is received", function () { expect(function () { config.onConnect({'slow_sql.enabled' : true}); }).not.throws(); }); it("shouldn't blow up when rum.load_episodes_file is received", function () { expect(function () { config.onConnect({'rum.load_episodes_file' : true}); }).not.throws(); }); it("shouldn't blow up when beacon is received", function () { expect(function () { config.onConnect({'beacon' : 'beacon-0.newrelic.com'}); }).not.throws(); }); it("shouldn't blow up when beacon is received", function () { expect(function () { config.onConnect({'error_beacon' : null}); }).not.throws(); }); it("shouldn't blow up when js_agent_file is received", function () { expect(function () { config.onConnect({'js_agent_file' : 'jxc4afffef.js'}); }).not.throws(); }); it("shouldn't blow up when js_agent_loader_file is received", function () { expect(function () { config.onConnect({'js_agent_loader_file' : 'nr-js-bootstrap.js'}); }).not.throws(); }); it("shouldn't blow up when episodes_file is received", function () { expect(function () { config.onConnect({'episodes_file' : 'js-agent.newrelic.com/nr-100.js'}); }).not.throws(); }); it("shouldn't blow up when episodes_url is received", function () { expect(function () { config.onConnect({'episodes_url' : 'https://js-agent.newrelic.com/nr-100.js'}); }).not.throws(); }); it("shouldn't blow up when browser_key is received", function () { expect(function () { config.onConnect({'browser_key' : 'beefchunx'}); }).not.throws(); }); it("shouldn't blow up when collect_analytics_events is received", function () { config.transaction_events.enabled = true; expect(function () { config.onConnect({'collect_analytics_events' : false}); }).not.throws(); expect(config.transaction_events.enabled).equals(false); }); it("shouldn't blow up when transaction_events.max_samples_stored is received", function () { expect(function () { config.onConnect({'transaction_events.max_samples_stored' : 10}); }).not.throws(); expect(config.transaction_events.max_samples_stored).equals(10); }); it("shouldn't blow up when transaction_events.max_samples_per_minute is received", function () { expect(function () { config.onConnect({'transaction_events.max_samples_per_minute' : 1}); }).not.throws(); expect(config.transaction_events.max_samples_per_minute).equals(1); }); it("shouldn't blow up when transaction_events.enabled is received", function () { expect(function () { config.onConnect({'transaction_events.enabled' : false}); }).not.throws(); expect(config.transaction_events.enabled).equals(false); }); describe("when data_report_period is set", function () { it("should emit 'data_report_period' when harvest interval is changed", function (done) { config.once('data_report_period', function (harvestInterval) { expect(harvestInterval).equal(45); done(); }); config.onConnect({'data_report_period' : 45}); }); it("should update data_report_period only when it is changed", function () { expect(config.data_report_period).equal(60); config.once('data_report_period', function () { throw new Error('should never get here'); }); config.onConnect({'data_report_period' : 60}); }); }); describe("when apdex_t is set", function () { it("should emit 'apdex_t' when apdex_t changes", function (done) { config.once('apdex_t', function (apdexT) { expect(apdexT).equal(0.75); done(); }); config.onConnect({'apdex_t' : 0.75}); }); it("should update its apdex_t only when it has changed", function () { expect(config.apdex_t).equal(0.1); config.once('apdex_t', function () { throw new Error('should never get here'); }); config.onConnect({'apdex_t' : 0.1}); }); }); }); describe("when receiving server-side configuration while it's disabled", function () { var config; beforeEach(function () { config = new Config(); config.ignore_server_configuration = true; }); it("should still set rum properties", function () { config.onConnect({ js_agent_loader : "LOADER", js_agent_file : "FILE", js_agent_loader_file : "LOADER_FILE", beacon : "BEACON", error_beacon : "ERR_BEACON", browser_key : "KEY" }); var bm = config.browser_monitoring; expect(bm.js_agent_loader) .equal ("LOADER"); expect(bm.js_agent_file) .equal ("FILE"); expect(bm.js_agent_loader_file) .equal ("LOADER_FILE"); expect(bm.beacon) .equal ("BEACON"); expect(bm.error_beacon) .equal ("ERR_BEACON"); expect(bm.browser_key) .equal ("KEY"); }); it("should still set agent_run_id", function () { config.onConnect({'agent_run_id' : 1234}); expect(config.run_id).equal(1234); }); it("should always respect collect_traces", function () { expect(config.collect_traces).equal(true); config.onConnect({'collect_traces' : false}); expect(config.collect_traces).equal(false); }); it("should always respect collect_errors", function () { expect(config.collect_errors).equal(true); config.onConnect({'collect_errors' : false}); expect(config.collect_errors).equal(false); }); it("should still log product_level", function () { expect(config.product_level).equal(0); config.onConnect({'product_level' : 30}); expect(config.product_level).equal(30); }); it("should still pass url_rules to the URL normalizer", function (done) { config.on('url_rules', function (rules) { expect(rules).eql([{name : 'sample_rule'}]); done(); }); config.onConnect({'url_rules' : [{name : 'sample_rule'}]}); }); it("should still pass metric_name_rules to the metric name normalizer", function (done) { config.on('metric_name_rules', function (rules) { expect(rules).eql([{name : 'sample_rule'}]); done(); }); config.onConnect({'metric_name_rules' : [{name : 'sample_rule'}]}); }); it("should still pass transaction_name_rules to the transaction name normalizer", function (done) { config.on('transaction_name_rules', function (rules) { expect(rules).eql([{name : 'sample_rule'}]); done(); }); config.onConnect({'transaction_name_rules' : [{name : 'sample_rule'}]}); }); it("shouldn't configure apdex_t", function () { expect(config.apdex_t).equal(0.1); config.on('apdex_t', function () { throw new Error("shouldn't happen"); }); config.onConnect({'apdex_t' : 0.05}); expect(config.apdex_t).equal(0.1); }); it("shouldn't configure named transaction apdexes", function () { var apdexes = {"WebTransaction/Custom/UrlGenerator/en/betting/Football" : 7.0}; expect(config.web_transactions_apdex).eql({}); config.onConnect({'web_transactions_apdex' : apdexes}); expect(config.web_transactions_apdex).eql({}); }); it("shouldn't configure data_report_period", function () { expect(config.data_report_period).equal(60); config.onConnect({'data_report_period' : 45}); expect(config.data_report_period).equal(60); }); it("shouldn't configure transaction_tracer.enabled", function () { expect(config.transaction_tracer.enabled).equal(true); config.onConnect({'transaction_tracer.enabled' : false}); expect(config.transaction_tracer.enabled).equal(true); }); it("shouldn't configure error_tracer.enabled", function () { expect(config.error_collector.enabled).equal(true); config.onConnect({'error_collector.enabled' : false}); expect(config.error_collector.enabled).equal(true); }); it("shouldn't configure transaction_tracer.transaction_threshold", function () { expect(config.transaction_tracer.transaction_threshold).equal('apdex_f'); config.onConnect({'transaction_tracer.transaction_threshold' : 0.75}); expect(config.transaction_tracer.transaction_threshold).equal('apdex_f'); }); it("shouldn't configure capture_params", function () { expect(config.capture_params).equal(false); config.onConnect({'capture_params' : true}); expect(config.capture_params).equal(false); }); it("shouldn't configure ignored_params", function () { expect(config.ignored_params).eql([]); config.onConnect({'ignored_params' : ['a', 'b']}); expect(config.ignored_params).eql([]); }); it("should ignore sampling_rate", function () { expect(function () { config.onConnect({'sampling_rate' : 0}); }).not.throws(); }); it("should ignore ssl", function () { expect(config.ssl).eql(true); expect(function () { config.onConnect({'ssl' : false}); }).not.throws(); expect(config.ssl).eql(true); }); it("should ignore cross_process_id", function () { expect(function () { config.onConnect({'cross_process_id' : 'junk'}); }).not.throws(); }); it("should ignore cross_application_tracing", function () { expect(function () { config.onConnect({'cross_application_tracing' : true}); }).not.throws(); }); it("should ignore encoding_key", function () { expect(function () { config.onConnect({'encoding_key' : true}); }).not.throws(); }); it("should ignore trusted_account_ids", function () { expect(function () { config.onConnect({'trusted_account_ids' : [1, 2, 3]}); }).not.throws(); }); it("should ignore transaction_tracer.record_sql", function () { expect(function () { config.onConnect({'transaction_tracer.record_sql' : true}); }).not.throws(); }); it("should ignore slow_sql.enabled", function () { expect(function () { config.onConnect({'slow_sql.enabled' : true}); }).not.throws(); }); it("should ignore rum.load_episodes_file", function () { expect(function () { config.onConnect({'rum.load_episodes_file' : true}); }).not.throws(); }); }); });
(function() { CodeMirror.extendMode("css", { commentStart: "/*", commentEnd: "*/", newlineAfterToken: function(type, content) { return /^[;{}]$/.test(content); } }); CodeMirror.extendMode("javascript", { commentStart: "/*", commentEnd: "*/", // FIXME semicolons inside of for newlineAfterToken: function(type, content, textAfter, state) { if (this.jsonMode) { return /^[\[,{]$/.test(content) || /^}/.test(textAfter); } else { if (content == ";" && state.lexical && state.lexical.type == ")") return false; return /^[;{}]$/.test(content) && !/^;/.test(textAfter); } } }); CodeMirror.extendMode("xml", { commentStart: "<!--", commentEnd: "-->", newlineAfterToken: function(type, content, textAfter) { return type == "tag" && />$/.test(content) || /^</.test(textAfter); } }); // Comment/uncomment the specified range CodeMirror.defineExtension("commentRange", function (isComment, from, to) { var cm = this, curMode = CodeMirror.innerMode(cm.getMode(), cm.getTokenAt(from).state).mode; cm.operation(function() { if (isComment) { // Comment range cm.replaceRange(curMode.commentEnd, to); cm.replaceRange(curMode.commentStart, from); if (from.line == to.line && from.ch == to.ch) // An empty comment inserted - put cursor inside cm.setCursor(from.line, from.ch + curMode.commentStart.length); } else { // Uncomment range var selText = cm.getRange(from, to); var startIndex = selText.indexOf(curMode.commentStart); var endIndex = selText.lastIndexOf(curMode.commentEnd); if (startIndex > -1 && endIndex > -1 && endIndex > startIndex) { // Take string till comment start selText = selText.substr(0, startIndex) // From comment start till comment end + selText.substring(startIndex + curMode.commentStart.length, endIndex) // From comment end till string end + selText.substr(endIndex + curMode.commentEnd.length); } cm.replaceRange(selText, from, to); } }); }); // Applies automatic mode-aware indentation to the specified range CodeMirror.defineExtension("autoIndentRange", function (from, to) { var cmInstance = this; this.operation(function () { for (var i = from.line; i <= to.line; i++) { cmInstance.indentLine(i, "smart"); } }); }); // Applies automatic formatting to the specified range CodeMirror.defineExtension("autoFormatRange", function (from, to) { var cm = this; var outer = cm.getMode(), text = cm.getRange(from, to).split("\n"); var state = CodeMirror.copyState(outer, cm.getTokenAt(from).state); var tabSize = cm.getOption("tabSize"); var out = "", lines = 0, atSol = from.ch == 0; function newline() { out += "\n"; atSol = true; ++lines; } for (var i = 0; i < text.length; ++i) { var stream = new CodeMirror.StringStream(text[i], tabSize); while (!stream.eol()) { var inner = CodeMirror.innerMode(outer, state); var style = outer.token(stream, state), cur = stream.current(); stream.start = stream.pos; if (!atSol || /\S/.test(cur)) { out += cur; atSol = false; } if (!atSol && inner.mode.newlineAfterToken && inner.mode.newlineAfterToken(style, cur, stream.string.slice(stream.pos) || text[i+1] || "", inner.state)) newline(); } if (!stream.pos && outer.blankLine) outer.blankLine(state); if (!atSol) newline(); } cm.operation(function () { cm.replaceRange(out, from, to); for (var cur = from.line + 1, end = from.line + lines; cur <= end; ++cur) cm.indentLine(cur, "smart"); cm.setSelection(from, cm.getCursor(false)); }); }); })();
'use strict'; const common = require('../common'); const fixtures = require('../common/fixtures'); // Adding a CA certificate to contextWithCert should not also add it to // contextWithoutCert. This is tested by trying to connect to a server that // depends on that CA using contextWithoutCert. const { assert, connect, keys, tls } = require(fixtures.path('tls-connect')); const contextWithoutCert = tls.createSecureContext({}); const contextWithCert = tls.createSecureContext({}); contextWithCert.context.addCACert(keys.agent1.ca); const serverOptions = { key: keys.agent1.key, cert: keys.agent1.cert, }; const clientOptions = { ca: [keys.agent1.ca], servername: 'agent1', rejectUnauthorized: true, }; // This client should fail to connect because it doesn't trust the CA // certificate. clientOptions.secureContext = contextWithoutCert; connect({ client: clientOptions, server: serverOptions, }, common.mustCall((err, pair, cleanup) => { assert(err); assert.strictEqual(err.message, 'unable to verify the first certificate'); cleanup(); // This time it should connect because contextWithCert includes the needed CA // certificate. clientOptions.secureContext = contextWithCert; connect({ client: clientOptions, server: serverOptions, }, common.mustCall((err, pair, cleanup) => { assert.ifError(err); cleanup(); })); }));
"use strict"; var Message_1 = require("../Message"); var ReceiptCard = (function () { function ReceiptCard(session) { this.session = session; this.data = { contentType: 'application/vnd.microsoft.card.receipt', content: {} }; } ReceiptCard.prototype.title = function (text) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } if (text) { this.data.content.title = Message_1.fmtText(this.session, text, args); } return this; }; ReceiptCard.prototype.items = function (list) { this.data.content.items = []; if (list) { for (var i = 0; i < list.length; i++) { var item = list[i]; this.data.content.items.push(item.toItem ? item.toItem() : item); } } return this; }; ReceiptCard.prototype.facts = function (list) { this.data.content.facts = []; if (list) { for (var i = 0; i < list.length; i++) { var fact = list[i]; this.data.content.facts.push(fact.toFact ? fact.toFact() : fact); } } return this; }; ReceiptCard.prototype.tap = function (action) { if (action) { this.data.content.tap = action.toAction ? action.toAction() : action; } return this; }; ReceiptCard.prototype.total = function (v) { this.data.content.total = v || ''; return this; }; ReceiptCard.prototype.tax = function (v) { this.data.content.tax = v || ''; return this; }; ReceiptCard.prototype.vat = function (v) { this.data.content.vat = v || ''; return this; }; ReceiptCard.prototype.buttons = function (list) { this.data.content.buttons = []; if (list) { for (var i = 0; i < list.length; i++) { var action = list[i]; this.data.content.buttons.push(action.toAction ? action.toAction() : action); } } return this; }; ReceiptCard.prototype.toAttachment = function () { return this.data; }; return ReceiptCard; }()); exports.ReceiptCard = ReceiptCard; var ReceiptItem = (function () { function ReceiptItem(session) { this.session = session; this.data = {}; } ReceiptItem.prototype.title = function (text) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } if (text) { this.data.title = Message_1.fmtText(this.session, text, args); } return this; }; ReceiptItem.prototype.subtitle = function (text) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } if (text) { this.data.subtitle = Message_1.fmtText(this.session, text, args); } return this; }; ReceiptItem.prototype.text = function (text) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } if (text) { this.data.text = Message_1.fmtText(this.session, text, args); } return this; }; ReceiptItem.prototype.image = function (img) { if (img) { this.data.image = img.toImage ? img.toImage() : img; } return this; }; ReceiptItem.prototype.price = function (v) { this.data.price = v || ''; return this; }; ReceiptItem.prototype.quantity = function (v) { this.data.quantity = v || ''; return this; }; ReceiptItem.prototype.tap = function (action) { if (action) { this.data.tap = action.toAction ? action.toAction() : action; } return this; }; ReceiptItem.prototype.toItem = function () { return this.data; }; ReceiptItem.create = function (session, price, title) { return new ReceiptItem(session).price(price).title(title); }; return ReceiptItem; }()); exports.ReceiptItem = ReceiptItem; var Fact = (function () { function Fact(session) { this.session = session; this.data = { value: '' }; } Fact.prototype.key = function (text) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } if (text) { this.data.key = Message_1.fmtText(this.session, text, args); } return this; }; Fact.prototype.value = function (v) { this.data.value = v || ''; return this; }; Fact.prototype.toFact = function () { return this.data; }; Fact.create = function (session, value, key) { return new Fact(session).value(value).key(key); }; return Fact; }()); exports.Fact = Fact;
module.exports = { preCommit : [ ], postCommit : [ '(git pull --rebase origin master && git push origin master) || (echo "Ok fine, I\'ll stash" >&2 && git stash -u -q && git push origin master && git stash pop -q)', 'npm publish .', "ssh root@dibsy 'updateDibsy'" ] };
$(function() { /* Uploadify */ var uploaded_attachments = $('#uploaded-attachments'); var upload_token = $('input[name=token]').val(); var session = $('input[name=session]').val(); var project = $('input[name=project_id]').val(); $('#upload').uploadify({ 'uploader' : baseurl + '/app/assets/js/uploadify/uploadify.swf', 'script' : siteurl + 'ajax/project/issue_upload_attachment', 'scriptData' : { session : session, project_id : project, upload_token : upload_token }, 'cancelImg' : baseurl + '/app/assets/images/layout/icon-delete.png', 'auto' : true, 'multi' : true, 'queSizeLimit' : 10, 'onComplete' : function(event, id, file){ var body = '<li id="' + id + '">' + '<a href="javascript:void(0);" class="delete" rel="' + id + '">Remove</a><span>' + file.name + '</span></li>'; uploaded_attachments.append(body); } }); uploaded_attachments.find('.delete').live('click', function(){ var attachment = $(this); var id = attachment.attr('rel'); var filename = $('#' + id).find('span').html(); $.post(siteurl + 'ajax/project/issue_remove_attachment', { filename : filename, upload_token : upload_token, project_id : project }, function(){ $('#' + id).fadeOut(); }) }); /* Comment Actions */ var discussion = $('.issue-discussion'); discussion.find('li .edit').live('click', function(){ var id = $(this).closest('.comment').attr('id'); $('#' + id + ' .issue').hide(); $('#' + id + ' .comment-edit').show(); return false; }); discussion.find('li .delete').live('click', function(e){ e.preventDefault(); if(confirm('Are sure you want to delete this comment?')){ var saving = $('.global-saving span').html(); $('.global-saving span').html('Deleting'); $('.global-saving').show(); var id = $(this).closest('.comment').attr('id'); $.get('?delete=' + id, function(){ $('#' + id).fadeOut(); $('.global-saving').hide(); $('.global-saving span').html(saving); }); } return false; }); discussion.find('li .save').live('click', function(){ var id = $(this).closest('.comment').attr('id'); $('#' + id + ' textarea').attr('disabled', 'disabled'); saving_toggle(); $.post(current_url + '/edit_comment', { body: discussion.find('#' + id + ' textarea').val(), id: id, csrf_token: $('input[name=csrf_token]').val() }, function(data){ $('#' + id + ' textarea').removeAttr('disabled'); $('#' + id + ' .comment-edit').hide(); $('#' + id + ' .issue').html(data).show(); saving_toggle(); }); }); discussion.find('li .cancel').live('click', function(){ var id = $(this).closest('.comment').attr('id'); $('#' + id + ' .comment-edit').hide(); $('#' + id + ' .issue').show(); }); }); /* Autocomplete for sidebar adding user */ var autocomplete_sidebar_init = false; function init_sidebar_autocomplete(project){ if(!autocomplete_sidebar_init){ var users = $('.sidebar-users'); $.getJSON(siteurl + 'ajax/project/inactive_users?project_id=' + project, function(data){ var suggestions = []; $.each(data, function(key, value){ suggestions.push(value); }); var input = $('#add-user-project'); $(input).autocomplete({ source: suggestions, select: function (event, ui){ saving_toggle(); $.post(siteurl + 'ajax/project/add_user', { user_id : ui.item.id, project_id : project }, function(data){ saving_toggle(); var append = '<li id="project-user' + ui.item.id + '">' + '<a href="javascript:void(0);" onclick="remove_project_user(' + ui.item.id + ', ' + project + ');" class="delete">Remove</a>' + '' + ui.item.label + '' + '</li>'; users.append(append); }); }, close: function(event, ui){ $('#add-user-project').val(''); } }); }); autocomplete_sidebar_init = true; } } function remove_project_user(user_id, project_id){ if(!confirm('Are you sure you want to remove this user from the project?')){ return false; } saving_toggle(); $.post(siteurl + 'ajax/project/remove_user', { user_id : user_id, project_id : project_id }, function(data){ $('#project-user' + user_id).fadeOut(); saving_toggle(); }); return true; } function issue_assign_change(user_id, issue_id){ saving_toggle(); assign_issue_to_user(user_id, issue_id, function(){ var assigned_to = $('.assigned-to'); var assign_to = assigned_to.find('.user' + user_id); assigned_to.find('.assigned').removeClass('assigned'); assign_to.addClass('assigned'); assigned_to.find('.currently_assigned').html(assign_to.html()); saving_toggle(); }); } function assign_issue_to_user(user_id, issue_id, callback){ $.post(siteurl + 'ajax/project/issue_assign', { user_id : user_id, issue_id : issue_id }, function(){ callback(); }); }
exports.foo = 'bar'
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _oneLineCommaListsOr = require('./oneLineCommaListsOr'); var _oneLineCommaListsOr2 = _interopRequireDefault(_oneLineCommaListsOr); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _oneLineCommaListsOr2.default; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9vbmVMaW5lQ29tbWFMaXN0c09yL2luZGV4LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7QUFFQSIsImZpbGUiOiJpbmRleC5qcyIsInNvdXJjZXNDb250ZW50IjpbIid1c2Ugc3RyaWN0J1xuXG5pbXBvcnQgb25lTGluZUNvbW1hTGlzdHNPciBmcm9tICcuL29uZUxpbmVDb21tYUxpc3RzT3InXG5cbmV4cG9ydCBkZWZhdWx0IG9uZUxpbmVDb21tYUxpc3RzT3JcbiJdfQ==
'use strict'; var minilog = require('minilog') , log = minilog('traverson'); /* * This transform is meant to be run at the very end of a getResource call. It * just extracts the last doc from the step and calls t.callback with it. */ module.exports = function extractDoc(t) { log.debug('walker.walk has finished'); /* TODO Breaks a lot of tests although it seems to make perfect sense?!? if (!t.doc) { t.callback(createError('No document available', errors.InvalidStateError)); return false; } */ t.callback(null, t.step.doc); // This is a so called final transform that is only applied at the very end // and it always calls t.callback - in contrast to other transforms it does // not call t.callback in the error case, but as a success. // We return false to make sure processing ends here. return false; };
var NobleDevice = require('noble-device'); var Common = require('./common'); var ACCELEROMETER_UUID = 'f000aa1004514000b000000000000000'; var MAGNETOMETER_UUID = 'f000aa3004514000b000000000000000'; var GYROSCOPE_UUID = 'f000aa5004514000b000000000000000'; var BAROMETRIC_PRESSURE_UUID = 'f000aa4004514000b000000000000000'; var TEST_UUID = 'f000aa6004514000b000000000000000'; var OAD_UUID = 'f000ffc004514000b000000000000000'; var ACCELEROMETER_CONFIG_UUID = 'f000aa1204514000b000000000000000'; var ACCELEROMETER_DATA_UUID = 'f000aa1104514000b000000000000000'; var ACCELEROMETER_PERIOD_UUID = 'f000aa1304514000b000000000000000'; var MAGNETOMETER_CONFIG_UUID = 'f000aa3204514000b000000000000000'; var MAGNETOMETER_DATA_UUID = 'f000aa3104514000b000000000000000'; var MAGNETOMETER_PERIOD_UUID = 'f000aa3304514000b000000000000000'; var BAROMETRIC_PRESSURE_CONFIG_UUID = 'f000aa4204514000b000000000000000'; var BAROMETRIC_PRESSURE_CALIBRATION_UUID = 'f000aa4304514000b000000000000000'; var GYROSCOPE_CONFIG_UUID = 'f000aa5204514000b000000000000000'; var GYROSCOPE_DATA_UUID = 'f000aa5104514000b000000000000000'; var GYROSCOPE_PERIOD_UUID = 'f000aa5304514000b000000000000000'; var TEST_DATA_UUID = 'f000aa6104514000b000000000000000'; var TEST_CONFIGURATION_UUID = 'f000aa6204514000b000000000000000'; var CC2540SensorTag = function(peripheral) { NobleDevice.call(this, peripheral); Common.call(this); this.type = 'cc2540'; this.onAccelerometerChangeBinded = this.onAccelerometerChange.bind(this); this.onMagnetometerChangeBinded = this.onMagnetometerChange.bind(this); this.onGyroscopeChangeBinded = this.onGyroscopeChange.bind(this); }; CC2540SensorTag.is = function(peripheral) { var localName = peripheral.advertisement.localName; return (localName === 'SensorTag') || (localName === 'TI BLE Sensor Tag'); }; NobleDevice.Util.inherits(CC2540SensorTag, NobleDevice); NobleDevice.Util.mixin(CC2540SensorTag, NobleDevice.DeviceInformationService); NobleDevice.Util.mixin(CC2540SensorTag, Common); CC2540SensorTag.prototype.convertIrTemperatureData = function(data, callback) { // For computation refer : http://processors.wiki.ti.com/index.php/SensorTag_User_Guide#IR_Temperature_Sensor var ambientTemperature = data.readInt16LE(2) / 128.0; var Vobj2 = data.readInt16LE(0) * 0.00000015625; var Tdie2 = ambientTemperature + 273.15; var S0 = 5.593 * Math.pow(10, -14); var a1 = 1.75 * Math.pow(10 , -3); var a2 = -1.678 * Math.pow(10, -5); var b0 = -2.94 * Math.pow(10, -5); var b1 = -5.7 * Math.pow(10, -7); var b2 = 4.63 * Math.pow(10, -9); var c2 = 13.4; var Tref = 298.15; var S = S0 * (1 + a1 * (Tdie2 - Tref) + a2 * Math.pow((Tdie2 - Tref), 2)); var Vos = b0 + b1 * (Tdie2 - Tref) + b2 * Math.pow((Tdie2 - Tref), 2); var fObj = (Vobj2 - Vos) + c2 * Math.pow((Vobj2 - Vos), 2); var objectTemperature = Math.pow(Math.pow(Tdie2, 4) + (fObj/S), 0.25); objectTemperature = (objectTemperature - 273.15); callback(objectTemperature, ambientTemperature); }; CC2540SensorTag.prototype.convertHumidityData = function(data, callback) { var temperature = -46.85 + 175.72 / 65536.0 * data.readUInt16LE(0); var humidity = -6.0 + 125.0 / 65536.0 * (data.readUInt16LE(2) & ~0x0003); callback(temperature, humidity); }; CC2540SensorTag.prototype.enableBarometricPressure = function(callback) { this.writeUInt8Characteristic(BAROMETRIC_PRESSURE_UUID, BAROMETRIC_PRESSURE_CONFIG_UUID, 0x02, function(error) { if (error) { return callback(error); } this.readDataCharacteristic(BAROMETRIC_PRESSURE_UUID, BAROMETRIC_PRESSURE_CALIBRATION_UUID, function(error, data) { if (error) { return callback(error); } this._barometricPressureCalibrationData = data; this.enableConfigCharacteristic(BAROMETRIC_PRESSURE_UUID, BAROMETRIC_PRESSURE_CONFIG_UUID, callback); }.bind(this)); }.bind(this)); }; CC2540SensorTag.prototype.convertBarometricPressureData = function(data, callback) { // For computation refer : http://processors.wiki.ti.com/index.php/SensorTag_User_Guide#Barometric_Pressure_Sensor_2 var temp; // Temperature raw value from sensor var pressure; // Pressure raw value from sensor var S; // Interim value in calculation var O; // Interim value in calculation var p_a; // Pressure actual value in unit Pascal. var Pa; // Computed value of the function var c0 = this._barometricPressureCalibrationData.readUInt16LE(0); var c1 = this._barometricPressureCalibrationData.readUInt16LE(2); var c2 = this._barometricPressureCalibrationData.readUInt16LE(4); var c3 = this._barometricPressureCalibrationData.readUInt16LE(6); var c4 = this._barometricPressureCalibrationData.readInt16LE(8); var c5 = this._barometricPressureCalibrationData.readInt16LE(10); var c6 = this._barometricPressureCalibrationData.readInt16LE(12); var c7 = this._barometricPressureCalibrationData.readInt16LE(14); temp = data.readInt16LE(0); pressure = data.readUInt16LE(2); S = c2 + ((c3 * temp)/ 131072.0) + ((c4 * (temp * temp)) / 17179869184.0); O = (c5 * 16384.0) + (((c6 * temp) / 8)) + ((c7 * (temp * temp)) / 524288.0); Pa = (((S * pressure) + O) / 16384.0); Pa /= 100.0; callback(Pa); }; CC2540SensorTag.prototype.enableAccelerometer = function(callback) { this.enableConfigCharacteristic(ACCELEROMETER_UUID, ACCELEROMETER_CONFIG_UUID, callback); }; CC2540SensorTag.prototype.disableAccelerometer = function(callback) { this.disableConfigCharacteristic(ACCELEROMETER_UUID, ACCELEROMETER_CONFIG_UUID, callback); }; CC2540SensorTag.prototype.readAccelerometer = function(callback) { this.readDataCharacteristic(ACCELEROMETER_UUID, ACCELEROMETER_DATA_UUID, function(error, data) { if (error) { return callback(error); } this.convertAccelerometerData(data, function(x, y, z) { callback(null, x, y, z); }.bind(this)); }.bind(this)); }; CC2540SensorTag.prototype.onAccelerometerChange = function(data) { this.convertAccelerometerData(data, function(x, y, z) { this.emit('accelerometerChange', x, y, z); }.bind(this)); }; CC2540SensorTag.prototype.convertAccelerometerData = function(data, callback) { var x = data.readInt8(0) / 16.0; var y = data.readInt8(1) / 16.0; var z = data.readInt8(2) / 16.0; callback(x, y, z); }; CC2540SensorTag.prototype.notifyAccelerometer = function(callback) { this.notifyCharacteristic(ACCELEROMETER_UUID, ACCELEROMETER_DATA_UUID, true, this.onAccelerometerChangeBinded, callback); }; CC2540SensorTag.prototype.unnotifyAccelerometer = function(callback) { this.notifyCharacteristic(ACCELEROMETER_UUID, ACCELEROMETER_DATA_UUID, false, this.onAccelerometerChangeBinded, callback); }; CC2540SensorTag.prototype.setAccelerometerPeriod = function(period, callback) { this.writePeriodCharacteristic(ACCELEROMETER_UUID, ACCELEROMETER_PERIOD_UUID, period, callback); }; CC2540SensorTag.prototype.enableMagnetometer = function(callback) { this.enableConfigCharacteristic(MAGNETOMETER_UUID, MAGNETOMETER_CONFIG_UUID, callback); }; CC2540SensorTag.prototype.disableMagnetometer = function(callback) { this.disableConfigCharacteristic(MAGNETOMETER_UUID, MAGNETOMETER_CONFIG_UUID, callback); }; CC2540SensorTag.prototype.readMagnetometer = function(callback) { this.readDataCharacteristic(MAGNETOMETER_UUID, MAGNETOMETER_DATA_UUID, function(error, data) { if (error) { return callback(error); } this.convertMagnetometerData(data, function(x, y, z) { callback(null, x, y, z); }.bind(this)); }.bind(this)); }; CC2540SensorTag.prototype.onMagnetometerChange = function(data) { this.convertMagnetometerData(data, function(x, y, z) { this.emit('magnetometerChange', x, y, z); }.bind(this)); }; CC2540SensorTag.prototype.convertMagnetometerData = function(data, callback) { var x = data.readInt16LE(0) * 2000.0 / 65536.0; var y = data.readInt16LE(2) * 2000.0 / 65536.0; var z = data.readInt16LE(4) * 2000.0 / 65536.0; callback(x, y, z); }; CC2540SensorTag.prototype.notifyMagnetometer = function(callback) { this.notifyCharacteristic(MAGNETOMETER_UUID, MAGNETOMETER_DATA_UUID, true, this.onMagnetometerChangeBinded, callback); }; CC2540SensorTag.prototype.unnotifyMagnetometer = function(callback) { this.notifyCharacteristic(MAGNETOMETER_UUID, MAGNETOMETER_DATA_UUID, false, this.onMagnetometerChangeBinded, callback); }; CC2540SensorTag.prototype.setMagnetometerPeriod = function(period, callback) { this.writePeriodCharacteristic(MAGNETOMETER_UUID, MAGNETOMETER_PERIOD_UUID, period, callback); }; CC2540SensorTag.prototype.setGyroscopePeriod = function(period, callback) { this.writePeriodCharacteristic(GYROSCOPE_UUID, GYROSCOPE_PERIOD_UUID, period, callback); }; CC2540SensorTag.prototype.enableGyroscope = function(callback) { this.writeUInt8Characteristic(GYROSCOPE_UUID, GYROSCOPE_CONFIG_UUID, 0x07, callback); }; CC2540SensorTag.prototype.disableGyroscope = function(callback) { this.disableConfigCharacteristic(GYROSCOPE_UUID, GYROSCOPE_CONFIG_UUID, callback); }; CC2540SensorTag.prototype.readGyroscope = function(callback) { this.readDataCharacteristic(GYROSCOPE_UUID, GYROSCOPE_DATA_UUID, function(error, data) { if (error) { return callback(error); } this.convertGyroscopeData(data, function(x, y, z) { callback(null, x, y, z); }.bind(this)); }.bind(this)); }; CC2540SensorTag.prototype.onGyroscopeChange = function(data) { this.convertGyroscopeData(data, function(x, y, z) { this.emit('gyroscopeChange', x, y, z); }.bind(this)); }; CC2540SensorTag.prototype.convertGyroscopeData = function(data, callback) { var x = data.readInt16LE(0) * (500.0 / 65536.0) * -1; var y = data.readInt16LE(2) * (500.0 / 65536.0); var z = data.readInt16LE(4) * (500.0 / 65536.0); callback(x, y, z); }; CC2540SensorTag.prototype.notifyGyroscope = function(callback) { this.notifyCharacteristic(GYROSCOPE_UUID, GYROSCOPE_DATA_UUID, true, this.onGyroscopeChangeBinded, callback); }; CC2540SensorTag.prototype.unnotifyGyroscope = function(callback) { this.notifyCharacteristic(GYROSCOPE_UUID, GYROSCOPE_DATA_UUID, false, this.onGyroscopeChangeBinded, callback); }; CC2540SensorTag.prototype.readTestData = function(callback) { this.readUInt16LECharacteristic(TEST_UUID, TEST_DATA_UUID, callback); }; CC2540SensorTag.prototype.readTestConfiguration = function(callback) { this.readUInt8Characteristic(TEST_UUID, TEST_CONFIGURATION_UUID, callback); }; module.exports = CC2540SensorTag;
'use strict'; const common = require('../common'); const { Console } = require('console'); const { Writable } = require('stream'); const async_hooks = require('async_hooks'); // Make sure that repeated calls to console.log(), and by extension // stream.write() for the underlying stream, allocate exactly 1 tick object. // At the time of writing, that is enough to ensure a flat memory profile // from repeated console.log() calls, rather than having callbacks pile up // over time, assuming that data can be written synchronously. // Refs: https://github.com/nodejs/node/issues/18013 // Refs: https://github.com/nodejs/node/issues/18367 const checkTickCreated = common.mustCall(); async_hooks.createHook({ init(id, type, triggerId, resoure) { if (type === 'TickObject') checkTickCreated(); } }).enable(); const console = new Console(new Writable({ write: common.mustCall((chunk, encoding, cb) => { cb(); }, 100) })); for (let i = 0; i < 100; i++) console.log(i);
define({ "_widgetLabel": "Список слоев", "titleBasemap": "Базовые карты", "titleLayers": "Рабочие слои", "labelLayer": "Имя слоя", "itemZoomTo": "Приблизить к", "itemTransparency": "Прозрачность", "itemTransparent": "Прозрачный", "itemOpaque": "Непрозрачный", "itemMoveUp": "Выше", "itemMoveDown": "Ниже", "itemDesc": "Описание", "itemDownload": "Загрузить", "itemToAttributeTable": "Открыть таблицу атрибутов", "itemShowItemDetails": "Показать информацию об элементе", "empty": "пусто", "removePopup": "Отключить всплывающее окно", "enablePopup": "Включить всплывающее окно", "turnAllLayersOff": "Выключить все слои", "turnAllLayersOn": "Включить все слои", "expandAllLayers": "Раскрыть все слои", "collapseAlllayers": "Свернуть все слои", "turnAllLabelsOff": "Выключить все надписи", "turnAllLabelsOn": "Включить все надписи", "showLabels": "Показать подписи", "hideLables": "Скрыть надписи" });
import React from 'react' import Header from '../../components/Header' import classes from './CoreLayout.scss' import '../../styles/core.scss' export const CoreLayout = ({ children }) => ( <div className='container text-center'> <Header/> <div className={classes.mainContainer}> {children} </div> </div> ) CoreLayout.propTypes = { children: React.PropTypes.element.isRequired } export default CoreLayout
/* * * * (c) 2010-2021 Torstein Honsi * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; import U from '../Utilities.js'; var addEvent = U.addEvent, getMagnitude = U.getMagnitude, normalizeTickInterval = U.normalizeTickInterval, timeUnits = U.timeUnits; /* * * * Composition * * */ /* eslint-disable valid-jsdoc */ var DateTimeAxis; (function (DateTimeAxis) { /* * * * Declarations * * */ /* * * * Constants * * */ var composedClasses = []; /* * * * Functions * * */ /** * Extends axis class with date and time support. * @private */ function compose(AxisClass) { if (composedClasses.indexOf(AxisClass) === -1) { composedClasses.push(AxisClass); AxisClass.keepProps.push('dateTime'); var axisProto = AxisClass.prototype; axisProto.getTimeTicks = getTimeTicks; addEvent(AxisClass, 'init', onInit); } return AxisClass; } DateTimeAxis.compose = compose; /** * Set the tick positions to a time unit that makes sense, for example * on the first of each month or on every Monday. Return an array with * the time positions. Used in datetime axes as well as for grouping * data on a datetime axis. * * @private * @function Highcharts.Axis#getTimeTicks * * @param {Highcharts.TimeNormalizeObject} normalizedInterval * The interval in axis values (ms) and thecount. * * @param {number} min * The minimum in axis values. * * @param {number} max * The maximum in axis values. * * @param {number} startOfWeek * * @return {Highcharts.AxisTickPositionsArray} */ function getTimeTicks() { return this.chart.time.getTimeTicks.apply(this.chart.time, arguments); } /** * @private */ function onInit(e) { var axis = this; var options = e.userOptions; if (options.type !== 'datetime') { axis.dateTime = void 0; return; } if (!axis.dateTime) { axis.dateTime = new Additions(axis); } } /* * * * Classes * * */ var Additions = /** @class */ (function () { /* * * * Constructors * * */ function Additions(axis) { this.axis = axis; } /* * * * Functions * * */ /** * Get a normalized tick interval for dates. Returns a configuration * object with unit range (interval), count and name. Used to prepare * data for `getTimeTicks`. Previously this logic was part of * getTimeTicks, but as `getTimeTicks` now runs of segments in stock * charts, the normalizing logic was extracted in order to prevent it * for running over again for each segment having the same interval. * #662, #697. * @private */ Additions.prototype.normalizeTimeTickInterval = function (tickInterval, unitsOption) { var units = (unitsOption || [[ 'millisecond', [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples ], [ 'second', [1, 2, 5, 10, 15, 30] ], [ 'minute', [1, 2, 5, 10, 15, 30] ], [ 'hour', [1, 2, 3, 4, 6, 8, 12] ], [ 'day', [1, 2] ], [ 'week', [1, 2] ], [ 'month', [1, 2, 3, 4, 6] ], [ 'year', null ]]); var unit = units[units.length - 1], // default unit is years interval = timeUnits[unit[0]], multiples = unit[1], i; // loop through the units to find the one that best fits the // tickInterval for (i = 0; i < units.length; i++) { unit = units[i]; interval = timeUnits[unit[0]]; multiples = unit[1]; if (units[i + 1]) { // lessThan is in the middle between the highest multiple // and the next unit. var lessThan = (interval * multiples[multiples.length - 1] + timeUnits[units[i + 1][0]]) / 2; // break and keep the current unit if (tickInterval <= lessThan) { break; } } } // prevent 2.5 years intervals, though 25, 250 etc. are allowed if (interval === timeUnits.year && tickInterval < 5 * interval) { multiples = [1, 2, 5]; } // get the count var count = normalizeTickInterval(tickInterval / interval, multiples, unit[0] === 'year' ? // #1913, #2360 Math.max(getMagnitude(tickInterval / interval), 1) : 1); return { unitRange: interval, count: count, unitName: unit[0] }; }; /** * Get the best date format for a specific X value based on the closest * point range on the axis. * * @private * * @param {number} x * * @param {Highcharts.Dictionary<string>} dateTimeLabelFormats * * @return {string} */ Additions.prototype.getXDateFormat = function (x, dateTimeLabelFormats) { var axis = this.axis; return axis.closestPointRange ? axis.chart.time.getDateFormat(axis.closestPointRange, x, axis.options.startOfWeek, dateTimeLabelFormats) || dateTimeLabelFormats.year : // #2546, 2581 dateTimeLabelFormats.day; }; return Additions; }()); DateTimeAxis.Additions = Additions; })(DateTimeAxis || (DateTimeAxis = {})); /* * * * Default Export * * */ export default DateTimeAxis;
define( //begin v1.x content { "field-tue-relative+-1": "지난 화요일", "field-year": "년", "field-wed-relative+0": "이번 수요일", "field-wed-relative+1": "다음 수요일", "timeFormat-short": "a h:mm", "field-minute": "분", "field-tue-narrow-relative+0": "이번 화요일", "field-tue-narrow-relative+1": "다음 화요일", "field-thu-short-relative+0": "이번 목요일", "field-thu-short-relative+1": "다음 목요일", "field-day-relative+0": "오늘", "field-day-relative+1": "내일", "field-day-relative+2": "모레", "field-wed-narrow-relative+-1": "지난 수요일", "field-year-narrow": "년", "field-tue-relative+0": "이번 화요일", "field-tue-relative+1": "다음 화요일", "field-second-short": "초", "dateFormatItem-MMMd": "MMM월 d일", "field-week-relative+0": "이번 주", "field-month-relative+0": "이번 달", "field-week-relative+1": "다음 주", "field-month-relative+1": "다음 달", "field-sun-narrow-relative+0": "이번 일요일", "timeFormat-medium": "a h:mm:ss", "field-mon-short-relative+0": "이번 월요일", "field-sun-narrow-relative+1": "다음 일요일", "field-mon-short-relative+1": "다음 월요일", "field-second-relative+0": "지금", "dateFormatItem-yyyyQQQ": "G y년 QQQ", "field-month-short": "월", "dateFormatItem-GyMMMEd": "G y년 MMM월 d일 (E)", "dateFormatItem-yyyyMd": "G y. M. d.", "field-day": "일", "field-year-relative+-1": "작년", "dayPeriods-format-wide-am": "오전", "field-sat-short-relative+-1": "지난 토요일", "field-hour-relative+0": "현재 시간", "dateFormatItem-yyyyMEd": "G y. M. d. (E)", "field-wed-relative+-1": "지난 수요일", "field-sat-narrow-relative+-1": "지난 토요일", "field-second": "초", "days-standAlone-narrow": [ "일", "월", "화", "수", "목", "금", "토" ], "dayPeriods-standAlone-wide-pm": "오후", "dateFormat-long": "G y년 M월 d일", "dateFormatItem-GyMMMd": "G y년 MMM월 d일", "field-quarter": "분기", "field-week-short": "주", "quarters-standAlone-wide": [ "제 1/4분기", "제 2/4분기", "제 3/4분기", "제 4/4분기" ], "days-format-narrow": [ "일", "월", "화", "수", "목", "금", "토" ], "field-tue-short-relative+0": "이번 화요일", "field-tue-short-relative+1": "다음 화요일", "field-mon-relative+-1": "지난 월요일", "dateFormatItem-GyMMM": "G y년 MMM월", "field-month": "월", "field-day-narrow": "일", "field-minute-short": "분", "field-dayperiod": "오전/오후", "field-sat-short-relative+0": "이번 토요일", "field-sat-short-relative+1": "다음 토요일", "dateFormat-medium": "G y. M. d.", "dateFormatItem-yyyyMMMM": "G y년 MMMM월", "eraAbbr": [ "AH" ], "quarters-standAlone-abbr": [ "1분기", "2분기", "3분기", "4분기" ], "dateFormatItem-yyyyM": "G y. M.", "field-second-narrow": "초", "field-mon-relative+0": "이번 월요일", "field-mon-relative+1": "다음 월요일", "field-year-short": "년", "field-quarter-relative+-1": "지난 분기", "dateFormatItem-yyyyMMMd": "G y년 MMM월 d일", "days-format-short": [ "일", "월", "화", "수", "목", "금", "토" ], "dayPeriods-format-wide-pm": "오후", "field-sat-relative+-1": "지난 토요일", "dateFormatItem-Md": "M. d.", "field-hour": "시", "months-format-wide": [ "무하람", "사파르", "라비 알 아왈", "라비 알 쎄니", "주마다 알 아왈", "주마다 알 쎄니", "라잡", "쉐아반", "라마단", "쉐왈", "듀 알 까다", "듀 알 히자" ], "dateFormat-full": "G y년 M월 d일 EEEE", "field-month-relative+-1": "지난달", "dateFormatItem-Hms": "H시 m분 s초", "field-quarter-short": "분기", "field-sat-narrow-relative+0": "이번 토요일", "field-fri-relative+0": "이번 금요일", "field-sat-narrow-relative+1": "다음 토요일", "field-fri-relative+1": "다음 금요일", "field-sun-short-relative+0": "이번 일요일", "field-sun-short-relative+1": "다음 일요일", "field-week-relative+-1": "지난주", "months-format-abbr": [ "무하람", "사파르", "라비 알 아왈", "라비 알 쎄니", "주마다 알 아왈", "주마다 알 쎄니", "라잡", "쉐아반", "라마단", "쉐왈", "듀 알 까다", "듀 알 히자" ], "field-quarter-relative+0": "이번 분기", "field-minute-relative+0": "현재 분", "timeFormat-long": "a h시 m분 s초 z", "field-quarter-relative+1": "다음 분기", "field-wed-short-relative+-1": "지난 수요일", "dateFormat-short": "G y. M. d.", "field-thu-short-relative+-1": "지난 목요일", "days-standAlone-wide": [ "일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일" ], "dateFormatItem-yyyyMMMEd": "G y년 MMM월 d일 (E)", "field-mon-narrow-relative+-1": "지난 월요일", "dateFormatItem-MMMMd": "MMMM월 d일", "field-thu-narrow-relative+-1": "지난 목요일", "field-tue-narrow-relative+-1": "지난 화요일", "dateFormatItem-H": "H시", "dateFormatItem-yyyy": "G y년", "field-wed-short-relative+0": "이번 수요일", "dateFormatItem-M": "M월", "months-standAlone-wide": [ "무하람", "사파르", "라비 알 아왈", "라비 알 쎄니", "주마다 알 아왈", "주마다 알 쎄니", "라잡", "쉐아반", "라마단", "쉐왈", "듀 알 까다", "듀 알 히자" ], "field-wed-short-relative+1": "다음 수요일", "field-sun-relative+-1": "지난 일요일", "days-standAlone-abbr": [ "일", "월", "화", "수", "목", "금", "토" ], "dateFormatItem-hm": "a h:mm", "dateFormatItem-d": "d일", "field-weekday": "요일", "field-sat-relative+0": "이번 토요일", "dateFormatItem-h": "a h시", "field-sat-relative+1": "다음 토요일", "months-standAlone-abbr": [ "무하람", "사파르", "라비 알 아왈", "라비 알 쎄니", "주마다 알 아왈", "주마다 알 쎄니", "라잡", "쉐아반", "라마단", "쉐왈", "듀 알 까다", "듀 알 히자" ], "timeFormat-full": "a h시 m분 s초 zzzz", "dateFormatItem-MEd": "M. d. (E)", "dateFormatItem-y": "G y년", "field-thu-narrow-relative+0": "이번 목요일", "field-thu-narrow-relative+1": "다음 목요일", "field-sun-narrow-relative+-1": "지난 일요일", "field-mon-short-relative+-1": "지난 월요일", "field-thu-relative+0": "이번 목요일", "field-thu-relative+1": "다음 목요일", "dateFormatItem-hms": "a h:mm:ss", "field-fri-short-relative+-1": "지난 금요일", "field-thu-relative+-1": "지난 목요일", "field-week": "주", "quarters-format-wide": [ "제 1/4분기", "제 2/4분기", "제 3/4분기", "제 4/4분기" ], "dateFormatItem-Ed": "d일 (E)", "field-wed-narrow-relative+0": "이번 수요일", "field-wed-narrow-relative+1": "다음 수요일", "dateFormatItem-yyyyMMM": "G y년 MMM월", "field-fri-short-relative+0": "이번 금요일", "field-fri-short-relative+1": "다음 금요일", "days-standAlone-short": [ "일", "월", "화", "수", "목", "금", "토" ], "dateFormatItem-yyyyQQQQ": "G y년 QQQQ", "field-hour-short": "시", "quarters-format-abbr": [ "1분기", "2분기", "3분기", "4분기" ], "field-month-narrow": "월", "field-hour-narrow": "시", "field-fri-narrow-relative+-1": "지난 금요일", "field-year-relative+0": "올해", "field-year-relative+1": "내년", "field-fri-relative+-1": "지난 금요일", "field-tue-short-relative+-1": "지난 화요일", "field-minute-narrow": "분", "days-format-wide": [ "일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일" ], "field-mon-narrow-relative+0": "이번 월요일", "field-mon-narrow-relative+1": "다음 월요일", "field-zone": "시간대", "dateFormatItem-MMMEd": "MMM월 d일 (E)", "field-quarter-narrow": "분기", "field-sun-short-relative+-1": "지난 일요일", "field-day-relative+-1": "어제", "field-day-relative+-2": "그저께", "days-format-abbr": [ "일", "월", "화", "수", "목", "금", "토" ], "field-sun-relative+0": "이번 일요일", "field-sun-relative+1": "다음 일요일", "dateFormatItem-Gy": "G y년", "field-day-short": "일", "field-week-narrow": "주", "field-era": "연호", "field-fri-narrow-relative+0": "이번 금요일", "field-fri-narrow-relative+1": "다음 금요일", "dayPeriods-standAlone-wide-am": "오전" } //end v1.x content );
hljs.registerLanguage("cpp",(()=>{"use strict";function e(e){ return((...e)=>e.map((e=>(e=>e?"string"==typeof e?e:e.source:null)(e))).join(""))("(",e,")?") }return t=>{const n=t.COMMENT("//","$",{contains:[{begin:/\\\n/}] }),r="[a-zA-Z_]\\w*::",a="(decltype\\(auto\\)|"+e(r)+"[a-zA-Z_]\\w*"+e("<[^<>]+>")+")",i={ className:"keyword",begin:"\\b[a-z\\d_]*_t\\b"},s={className:"string", variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n", contains:[t.BACKSLASH_ESCAPE]},{ begin:"(u8?|U|L)?'(\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)|.)", end:"'",illegal:"."},t.END_SAME_AS_BEGIN({ begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},o={ className:"number",variants:[{begin:"\\b(0b[01']+)"},{ begin:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)" },{ begin:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)" }],relevance:0},c={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{ "meta-keyword":"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include" },contains:[{begin:/\\\n/,relevance:0},t.inherit(s,{className:"meta-string"}),{ className:"meta-string",begin:/<.*?>/,end:/$/,illegal:"\\n" },n,t.C_BLOCK_COMMENT_MODE]},l={className:"title",begin:e(r)+t.IDENT_RE, relevance:0},d=e(r)+t.IDENT_RE+"\\s*\\(",u={ keyword:"int float while private char char8_t char16_t char32_t catch import module export virtual operator sizeof dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace unsigned long volatile static protected bool template mutable if public friend do goto auto void enum else break extern using asm case typeid wchar_t short reinterpret_cast|10 default double register explicit signed typename try this switch continue inline delete alignas alignof constexpr consteval constinit decltype concept co_await co_return co_yield requires noexcept static_assert thread_local restrict final override atomic_bool atomic_char atomic_schar atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong atomic_ullong new throw return and and_eq bitand bitor compl not not_eq or or_eq xor xor_eq", built_in:"std string wstring cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set pair bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap priority_queue make_pair array shared_ptr abort terminate abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf future isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr _Bool complex _Complex imaginary _Imaginary", literal:"true false nullptr NULL"},m=[c,i,n,t.C_BLOCK_COMMENT_MODE,o,s],p={ variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{ beginKeywords:"new throw return else",end:/;/}],keywords:u,contains:m.concat([{ begin:/\(/,end:/\)/,keywords:u,contains:m.concat(["self"]),relevance:0}]), relevance:0},_={className:"function",begin:"("+a+"[\\*&\\s]+)+"+d, returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:u,illegal:/[^\w\s\*&:<>.]/, contains:[{begin:"decltype\\(auto\\)",keywords:u,relevance:0},{begin:d, returnBegin:!0,contains:[l],relevance:0},{className:"params",begin:/\(/, end:/\)/,keywords:u,relevance:0,contains:[n,t.C_BLOCK_COMMENT_MODE,s,o,i,{ begin:/\(/,end:/\)/,keywords:u,relevance:0, contains:["self",n,t.C_BLOCK_COMMENT_MODE,s,o,i]}] },i,n,t.C_BLOCK_COMMENT_MODE,c]};return{name:"C++", aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:u,illegal:"</", contains:[].concat(p,_,m,[c,{ begin:"\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<", end:">",keywords:u,contains:["self",i]},{begin:t.IDENT_RE+"::",keywords:u},{ className:"class",beginKeywords:"enum class struct union",end:/[{;:<>=]/, contains:[{beginKeywords:"final class struct"},t.TITLE_MODE]}]),exports:{ preprocessor:c,strings:s,keywords:u}}}})());
// Chart design based on the recommendations of Stephen Few. Implementation // based on the work of Clint Ivy, Jamie Love, and Jason Davies. // http://projects.instantcognition.com/protovis/bulletchart/ nv.models.bulletChart = function() { "use strict"; //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var bullet = nv.models.bullet() ; var orient = 'left' // TODO top & bottom , reverse = false , margin = {top: 5, right: 40, bottom: 20, left: 120} , ranges = function(d) { return d.ranges } , markers = function(d) { return d.markers ? d.markers : [0] } , measures = function(d) { return d.measures } , width = null , height = 55 , tickFormat = null , tooltips = true , tooltip = function(key, x, y, e, graph) { return '<h3>' + x + '</h3>' + '<p>' + y + '</p>' } , noData = 'No Data Available.' , dispatch = d3.dispatch('tooltipShow', 'tooltipHide') ; //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ) + margin.left, top = e.pos[1] + ( offsetElement.offsetTop || 0) + margin.top, content = tooltip(e.key, e.label, e.value, e, chart); nv.tooltip.show([left, top], content, e.value < 0 ? 'e' : 'w', null, offsetElement); }; function chart(selection) { selection.each(function(d, i) { var container = d3.select(this); nv.utils.initSVG(container); var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, that = this; chart.update = function() { chart(selection) }; chart.container = this; // Display No Data message if there's nothing to show. if (!d || !ranges.call(this, d, i)) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', 18 + margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } var rangez = ranges.call(this, d, i).slice().sort(d3.descending), markerz = markers.call(this, d, i).slice().sort(d3.descending), measurez = measures.call(this, d, i).slice().sort(d3.descending); // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-bulletChart').data([d]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-bulletChart'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-bulletWrap'); gEnter.append('g').attr('class', 'nv-titles'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); // Compute the new x-scale. var x1 = d3.scale.linear() .domain([0, Math.max(rangez[0], markerz[0], measurez[0])]) // TODO: need to allow forceX and forceY, and xDomain, yDomain .range(reverse ? [availableWidth, 0] : [0, availableWidth]); // Retrieve the old x-scale, if this is an update. var x0 = this.__chart__ || d3.scale.linear() .domain([0, Infinity]) .range(x1.range()); // Stash the new scale. this.__chart__ = x1; var w0 = function(d) { return Math.abs(x0(d) - x0(0)) }, // TODO: could optimize by precalculating x0(0) and x1(0) w1 = function(d) { return Math.abs(x1(d) - x1(0)) }; var title = gEnter.select('.nv-titles').append('g') .attr('text-anchor', 'end') .attr('transform', 'translate(-6,' + (height - margin.top - margin.bottom) / 2 + ')'); title.append('text') .attr('class', 'nv-title') .text(function(d) { return d.title; }); title.append('text') .attr('class', 'nv-subtitle') .attr('dy', '1em') .text(function(d) { return d.subtitle; }); bullet .width(availableWidth) .height(availableHeight) var bulletWrap = g.select('.nv-bulletWrap'); d3.transition(bulletWrap).call(bullet); // Compute the tick format. var format = tickFormat || x1.tickFormat( availableWidth / 100 ); // Update the tick groups. var tick = g.selectAll('g.nv-tick') .data(x1.ticks( availableWidth / 50 ), function(d) { return this.textContent || format(d); }); // Initialize the ticks with the old scale, x0. var tickEnter = tick.enter().append('g') .attr('class', 'nv-tick') .attr('transform', function(d) { return 'translate(' + x0(d) + ',0)' }) .style('opacity', 1e-6); tickEnter.append('line') .attr('y1', availableHeight) .attr('y2', availableHeight * 7 / 6); tickEnter.append('text') .attr('text-anchor', 'middle') .attr('dy', '1em') .attr('y', availableHeight * 7 / 6) .text(format); // Transition the updating ticks to the new scale, x1. var tickUpdate = d3.transition(tick) .attr('transform', function(d) { return 'translate(' + x1(d) + ',0)' }) .style('opacity', 1); tickUpdate.select('line') .attr('y1', availableHeight) .attr('y2', availableHeight * 7 / 6); tickUpdate.select('text') .attr('y', availableHeight * 7 / 6); // Transition the exiting ticks to the new scale, x1. d3.transition(tick.exit()) .attr('transform', function(d) { return 'translate(' + x1(d) + ',0)' }) .style('opacity', 1e-6) .remove(); //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ dispatch.on('tooltipShow', function(e) { e.key = d.title; if (tooltips) showTooltip(e, that.parentNode); }); }); d3.timer.flush(); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ bullet.dispatch.on('elementMouseover.tooltip', function(e) { dispatch.tooltipShow(e); }); bullet.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.bullet = bullet; chart.dispatch = dispatch; chart.options = nv.utils.optionsFunc.bind(chart); chart._options = Object.create({}, { // simple options, just get/set the necessary values ranges: {get: function(){return ranges;}, set: function(_){ranges=_;}}, // ranges (bad, satisfactory, good) markers: {get: function(){return markers;}, set: function(_){markers=_;}}, // markers (previous, goal) measures: {get: function(){return measures;}, set: function(_){measures=_;}}, // measures (actual, forecast) width: {get: function(){return width;}, set: function(_){width=_;}}, height: {get: function(){return height;}, set: function(_){height=_;}}, tickFormat: {get: function(){return tickFormat;}, set: function(_){tickFormat=_;}}, tooltips: {get: function(){return tooltips;}, set: function(_){tooltips=_;}}, tooltipContent: {get: function(){return tooltip;}, set: function(_){tooltip=_;}}, noData: {get: function(){return noData;}, set: function(_){noData=_;}}, // options that require extra logic in the setter margin: {get: function(){return margin;}, set: function(_){ margin.top = _.top !== undefined ? _.top : margin.top; margin.right = _.right !== undefined ? _.right : margin.right; margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom; margin.left = _.left !== undefined ? _.left : margin.left; }}, orient: {get: function(){return orient;}, set: function(_){ // left, right, top, bottom orient = _; reverse = orient == 'right' || orient == 'bottom'; }} }); nv.utils.inheritOptions(chart, bullet); nv.utils.initOptions(chart); return chart; };
var styleElement; var exenv; describe('keyframes', () => { beforeEach(() => { styleElement = { textContent: '', sheet: { insertRule: sinon.spy(), cssRules: [] } }; sinon.stub(document, 'createElement', () => { return styleElement; }); sinon.stub(document.head, 'appendChild'); exenv = { canUseDOM: true, canUseEventListeners: true }; }); afterEach(() => { document.createElement.restore(); document.head.appendChild.restore(); }); it('doesn\'t touch the DOM if DOM not available', () => { exenv = { canUseDOM: false, canUseEventListeners: false }; var keyframes = require('inject?-./create-markup-for-styles!keyframes.js')({ 'exenv': exenv, './prefixer': require('__mocks__/prefixer.js') }); expect(document.createElement).not.to.have.been.called; expect(document.head.appendChild).not.to.have.been.called; var name = keyframes({}, 'MyComponent'); expect(name.length).to.be.greaterThan(0); }); it('doesn\'t touch the DOM if animation not supported (IE9)', () => { var Prefixer = require('__mocks__/prefixer.js'); Prefixer.__setNextPrefixedPropertyName(false); var keyframes = require('inject?-./create-markup-for-styles!keyframes.js')({ 'exenv': exenv, './prefixer': Prefixer }); expect(document.createElement).not.to.have.been.called; expect(document.head.appendChild).not.to.have.been.called; var name = keyframes({}, 'MyComponent'); expect(name.length).to.be.greaterThan(0); }); it('returns a name for the keyframes', () => { var keyframes = require('inject?-./create-markup-for-styles!keyframes.js')({ 'exenv': exenv, './prefixer': require('__mocks__/prefixer.js') }); var name = keyframes({}, 'MyComponent'); expect(name.length).to.be.greaterThan(0); }); it('does not always require a component', () => { var keyframes = require('inject?-./create-markup-for-styles!keyframes.js')({ 'exenv': exenv, './prefixer': require('__mocks__/prefixer.js') }); var name = keyframes({}); expect(name.length).to.be.greaterThan(0); }); it('prefixes @keyframes if needed', () => { var keyframes = require('inject?-./create-markup-for-styles!keyframes.js')({ 'exenv': exenv, './prefixer': require('__mocks__/prefixer.js') }); var name = keyframes({}, 'MyComponent'); expect(styleElement.sheet.insertRule.lastCall.args).to.deep.equal([ '@-webkit-keyframes ' + name + ' {\n\n}\n', 0 ]); }); it('doesn\'t prefix @keyframes if not needed', () => { styleElement.sheet.cssRules = [{cssText: 'blah'}]; var keyframes = require('inject?-./create-markup-for-styles!keyframes.js')({ 'exenv': exenv, './prefixer': require('__mocks__/prefixer.js') }); var name = keyframes({}, 'MyComponent'); expect(styleElement.sheet.insertRule.lastCall.args).to.deep.equal([ '@keyframes ' + name + ' {\n\n}\n', 1 ]); }); it('serializes keyframes', () => { var keyframes = require('inject?-./create-markup-for-styles!keyframes.js')({ 'exenv': exenv, './prefixer': require('__mocks__/prefixer.js') }); var name = keyframes({ from: { width: 100 }, to: { width: 200 } }, 'MyComponent'); expect(styleElement.sheet.insertRule.lastCall.args).to.deep.equal([ `@-webkit-keyframes ${name} { from { width: 100; } to { width: 200; } } `, 0 ]); }); });
/*! bespoke-hash v0.1.2 © 2013 Mark Dalgleish, Licensed MIT */ (function(e){e.plugins.hash=function(e){var t,n=function(){var t=window.location.hash.slice(1),n=parseInt(t,10);t&&(n?r(n-1):e.slides.forEach(function(e,n){e.getAttribute("data-bespoke-hash")===t&&r(n)}))},r=function(n){n!==t&&e.slide(n)};setTimeout(function(){n(),e.on("activate",function(e){var n=e.slide.getAttribute("data-bespoke-hash");window.location.hash=n||e.index+1,t=e.index}),window.addEventListener("hashchange",n)},0)}})(bespoke);
/************************************************************* * * MathJax/localization/ru/ru.js * * Copyright (c) 2009-2016 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.Localization.addTranslation("ru",null,{ menuTitle: "\u0440\u0443\u0441\u0441\u043A\u0438\u0439", version: "2.7.0", isLoaded: true, domains: { "_": { version: "2.7.0", isLoaded: true, strings: { CookieConfig: "MathJax \u043D\u0430\u0448\u043B\u0430 \u043A\u0443\u043A\u0438 \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u043E\u0439 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438, \u043A\u043E\u0442\u043E\u0440\u0430\u044F \u0441\u043E\u0434\u0435\u0440\u0436\u0438\u0442 \u043A\u043E\u0434 \u0434\u043B\u044F \u0437\u0430\u043F\u0443\u0441\u043A\u0430. \u0412\u044B \u0445\u043E\u0442\u0438\u0442\u0435 \u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u044C \u0435\u0433\u043E?\n\n(\u0412\u044B \u0434\u043E\u043B\u0436\u043D\u044B \u043D\u0430\u0436\u0430\u0442\u044C \u041E\u0442\u043C\u0435\u043D\u0430, \u0435\u0441\u043B\u0438 \u0432\u044B \u0441\u0430\u043C\u043E\u0441\u0442\u043E\u044F\u0442\u0435\u043B\u044C\u043D\u043E \u043D\u0430\u0441\u0442\u0440\u043E\u0438\u043B\u0438 \u0444\u0430\u0439\u043B \u043A\u0443\u043A\u0438).", MathProcessingError: "\u041E\u0448\u0438\u0431\u043A\u0430 \u043C\u0430\u0442\u0435\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u043E\u0439 \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438", MathError: "\u041C\u0430\u0442\u0435\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0430\u044F \u043E\u0448\u0438\u0431\u043A\u0430", LoadFile: "\u0417\u0430\u0433\u0440\u0443\u0437\u043A\u0430 %1", Loading: "\u0417\u0430\u0433\u0440\u0443\u0437\u043A\u0430", LoadFailed: "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0437\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044C: %1", ProcessMath: "\u041E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0430 \u043C\u0430\u0442\u0435\u043C\u0430\u0442\u0438\u043A\u0438: %1%%", Processing: "\u041E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0430", TypesetMath: "\u0412\u0451\u0440\u0441\u0442\u043A\u0430 \u043C\u0430\u0442\u0435\u043C\u0430\u0442\u0438\u043A\u0438: %1%%", Typesetting: "\u0412\u0451\u0440\u0441\u0442\u043A\u0430", MathJaxNotSupported: "\u0412\u0430\u0448 \u0431\u0440\u0430\u0443\u0437\u0435\u0440 \u043D\u0435 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u0442 MathJax" } }, "FontWarnings": {}, "HTML-CSS": {}, "HelpDialog": {}, "MathML": {}, "MathMenu": {}, "TeX": {} }, plural: function (n) { if (n % 10 === 1 && n % 100 !== 11) return 1; // one if (2 <= n % 10 && n % 10 <= 4 && 12 <= n % 100 && n % 100 <= 14) return 2; // few if (n % 10 === 0 || (5 <= n % 10 && n % 10 <= 9) || (11 <= n % 100 && n % 100 <= 14)) return 2; // many return 3; // other }, number: function (n) { return n; } }); MathJax.Ajax.loadComplete("[MathJax]/localization/ru/ru.js");
(function (arr, i) { if (Array.isArray(arr)) { return arr; } else { var _arr = []; for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { _arr.push(_step.value); if (i && _arr.length === i) break; } return _arr; } });
module.exports = function(hljs) { return { aliases: ['adoc'], contains: [ // block comment hljs.COMMENT( '^/{4,}\\n', '\\n/{4,}$', // can also be done as... //'^/{4,}$', //'^/{4,}$', { relevance: 10 } ), // line comment hljs.COMMENT( '^//', '$', { relevance: 0 } ), // title { className: 'title', begin: '^\\.\\w.*$' }, // example, admonition & sidebar blocks { begin: '^[=\\*]{4,}\\n', end: '\\n^[=\\*]{4,}$', relevance: 10 }, // headings { className: 'section', relevance: 10, variants: [ {begin: '^(={1,5}) .+?( \\1)?$'}, {begin: '^[^\\[\\]\\n]+?\\n[=\\-~\\^\\+]{2,}$'}, ] }, // document attributes { className: 'meta', begin: '^:.+?:', end: '\\s', excludeEnd: true, relevance: 10 }, // block attributes { className: 'meta', begin: '^\\[.+?\\]$', relevance: 0 }, // quoteblocks { className: 'quote', begin: '^_{4,}\\n', end: '\\n_{4,}$', relevance: 10 }, // listing and literal blocks { className: 'code', begin: '^[\\-\\.]{4,}\\n', end: '\\n[\\-\\.]{4,}$', relevance: 10 }, // passthrough blocks { begin: '^\\+{4,}\\n', end: '\\n\\+{4,}$', contains: [ { begin: '<', end: '>', subLanguage: 'xml', relevance: 0 } ], relevance: 10 }, // lists (can only capture indicators) { className: 'bullet', begin: '^(\\*+|\\-+|\\.+|[^\\n]+?::)\\s+' }, // admonition { className: 'symbol', begin: '^(NOTE|TIP|IMPORTANT|WARNING|CAUTION):\\s+', relevance: 10 }, // inline strong { className: 'strong', // must not follow a word character or be followed by an asterisk or space begin: '\\B\\*(?![\\*\\s])', end: '(\\n{2}|\\*)', // allow escaped asterisk followed by word char contains: [ { begin: '\\\\*\\w', relevance: 0 } ] }, // inline emphasis { className: 'emphasis', // must not follow a word character or be followed by a single quote or space begin: '\\B\'(?![\'\\s])', end: '(\\n{2}|\')', // allow escaped single quote followed by word char contains: [ { begin: '\\\\\'\\w', relevance: 0 } ], relevance: 0 }, // inline emphasis (alt) { className: 'emphasis', // must not follow a word character or be followed by an underline or space begin: '_(?![_\\s])', end: '(\\n{2}|_)', relevance: 0 }, // inline smart quotes { className: 'string', variants: [ {begin: "``.+?''"}, {begin: "`.+?'"} ] }, // inline code snippets (TODO should get same treatment as strong and emphasis) { className: 'code', begin: '(`.+?`|\\+.+?\\+)', relevance: 0 }, // indented literal block { className: 'code', begin: '^[ \\t]', end: '$', relevance: 0 }, // horizontal rules { begin: '^\'{3,}[ \\t]*$', relevance: 10 }, // images and links { begin: '(link:)?(http|https|ftp|file|irc|image:?):\\S+\\[.*?\\]', returnBegin: true, contains: [ { begin: '(link|image:?):', relevance: 0 }, { className: 'link', begin: '\\w', end: '[^\\[]+', relevance: 0 }, { className: 'string', begin: '\\[', end: '\\]', excludeBegin: true, excludeEnd: true, relevance: 0 } ], relevance: 10 } ] }; };
import Component from '@ember/component'; import layout from './template'; export default Component.extend({ layout, });
import sinon from 'sinon'; import { expect } from 'chai'; import { shallow } from 'enzyme'; import Immutable from 'immutable'; import React from 'react'; import { Text, View, TouchableHighlight } from 'react-native'; import Counter from '../../src/components/Counter'; const props = { counter: Immutable.Map({ counter: 1 }), increment: sinon.spy(), decrement: sinon.spy(), incrementIfOdd: sinon.spy(), incrementAsync: sinon.spy() }; describe('components <Counter />', function spec() { this.timeout(5000); it('should render correctly', () => { const wrapper = shallow(<Counter {...props} />); expect(wrapper.find(View)).to.have.length(1); const view = wrapper.find(View); expect(view.find(Text)).to.have.length(5); expect(view.find(Text).node.props.children).to.eql(['Clicked: ', 1, ' times']); const touchs = view.find(TouchableHighlight); expect(touchs).to.have.length(4); ['+', '-', 'Increment if odd', 'Increment async'].forEach((text, i) => { expect(touchs.at(i).find(Text).node.props.children).to.equal(text); }); }); ['increment', 'decrement', 'incrementIfOdd', 'incrementAsync'] .forEach((func, i) => { it(`should call ${func} with TouchableHighlight on press`, () => { const wrapper = shallow(<Counter {...props} />); wrapper.find(View).find(TouchableHighlight).nodes[i].props.onPress(); expect(props[func].calledOnce).to.be.true; }); }); });
let testnetWallet = { "privateKey": "", "name": "TestnetSpec", "accounts": { "0": { "brain": true, "algo": "pass:bip32", "encrypted": "c6dcbc8a538c9e2ec9e9be115aa6a1349d1a8a27e574136b4e603f0549474053e026e0771bf8d86a392fccce5b543d0b", "iv": "4c637775236d5a3698c973b9ba67459e", "address": "TAF7BPDV22HCFNRJEWOGLRKBYQF65GBOLQPI5GGO", "network": -104, "child": "e6683b4b03722d0a049a9a21861d90c48e843f421d6ccb587f809d41a4af14c5" } } } let mainnetWallet = { "privateKey": "", "name": "QM", "accounts": { "0": { "brain": true, "algo": "pass:6k", "encrypted": "", "iv": "", "address": "NCTIKLMIWKRZC3TRKD5JYZUQHV76LGS3TTSUIXM6", "network": 104, "child": "NCC7KUVPQYBTPBABABR5D724CJAOMIA2RJERW3N7" } } } let mainnetWalletDoubleAccounts = { "privateKey": "", "name": "Quantum_Mechanics", "accounts": { "0": { "brain": true, "algo": "pass:6k", "encrypted": "", "iv": "", "address": "NCTIKLMIWKRZC3TRKD5JYZUQHV76LGS3TTSUIXM6", "network": 104, "child": "NCC7KUVPQYBTPBABABR5D724CJAOMIA2RJERW3N7" }, "1": { "encrypted": "", "iv": "", "address": "NCTIKLMIWKRZC3TRKD5JYZUQHV76LGS3TTSUIWRE", "child": "NCC7KUVPQYBTPBABABR5D724CJAOMIA2RJERFRTO" } } } module.exports = { testnetWallet, mainnetWallet, mainnetWalletDoubleAccounts }
/** @license * * SoundManager 2: JavaScript Sound for the Web * ---------------------------------------------- * http://schillmania.com/projects/soundmanager2/ * * Copyright (c) 2007, Scott Schiller. All rights reserved. * Code provided under the BSD License: * http://schillmania.com/projects/soundmanager2/license.txt * * V2.97a.20120624 */ (function(ea){function Q(Q,da){function R(a){return c.preferFlash&&t&&!c.ignoreFlash&&"undefined"!==typeof c.flash[a]&&c.flash[a]}function m(a){return function(c){var d=this._t;return!d||!d._a?null:a.call(this,c)}}this.setupOptions={url:Q||null,flashVersion:8,debugMode:!0,debugFlash:!1,useConsole:!0,consoleOnly:!0,waitForWindowLoad:!1,bgColor:"#ffffff",useHighPerformance:!1,flashPollingInterval:null,html5PollingInterval:null,flashLoadTimeout:1E3,wmode:null,allowScriptAccess:"always",useFlashBlock:!1, useHTML5Audio:!0,html5Test:/^(probably|maybe)$/i,preferFlash:!0,noSWFCache:!1};this.defaultOptions={autoLoad:!1,autoPlay:!1,from:null,loops:1,onid3:null,onload:null,whileloading:null,onplay:null,onpause:null,onresume:null,whileplaying:null,onposition:null,onstop:null,onfailure:null,onfinish:null,multiShot:!0,multiShotEvents:!1,position:null,pan:0,stream:!0,to:null,type:null,usePolicyFile:!1,volume:100};this.flash9Options={isMovieStar:null,usePeakData:!1,useWaveformData:!1,useEQData:!1,onbufferchange:null, ondataerror:null};this.movieStarOptions={bufferTime:3,serverURL:null,onconnect:null,duration:null};this.audioFormats={mp3:{type:['audio/mpeg; codecs="mp3"',"audio/mpeg","audio/mp3","audio/MPA","audio/mpa-robust"],required:!0},mp4:{related:["aac","m4a"],type:['audio/mp4; codecs="mp4a.40.2"',"audio/aac","audio/x-m4a","audio/MP4A-LATM","audio/mpeg4-generic"],required:!1},ogg:{type:["audio/ogg; codecs=vorbis"],required:!1},wav:{type:['audio/wav; codecs="1"',"audio/wav","audio/wave","audio/x-wav"],required:!1}}; this.movieID="sm2-container";this.id=da||"sm2movie";this.debugID="soundmanager-debug";this.debugURLParam=/([#?&])debug=1/i;this.versionNumber="V2.97a.20120624";this.altURL=this.movieURL=this.version=null;this.enabled=this.swfLoaded=!1;this.oMC=null;this.sounds={};this.soundIDs=[];this.didFlashBlock=this.muted=!1;this.filePattern=null;this.filePatterns={flash8:/\.mp3(\?.*)?$/i,flash9:/\.mp3(\?.*)?$/i};this.features={buffering:!1,peakData:!1,waveformData:!1,eqData:!1,movieStar:!1};this.sandbox={};var fa; try{fa="undefined"!==typeof Audio&&"undefined"!==typeof(new Audio).canPlayType}catch(Za){fa=!1}this.hasHTML5=fa;this.html5={usingFlash:null};this.flash={};this.ignoreFlash=this.html5Only=!1;var Ca,c=this,i=null,S,q=navigator.userAgent,h=ea,ga=h.location.href.toString(),l=document,ha,Da,ia,j,w=[],J=!1,K=!1,k=!1,s=!1,ja=!1,L,r,ka,T,la,B,C,D,Ea,ma,U,V,E,na,oa,pa,W,F,Fa,qa,Ga,X,Ha,M=null,ra=null,u,sa,G,Y,Z,H,p,N=!1,ta=!1,Ia,Ja,Ka,$=0,O=null,aa,n=null,La,ba,P,x,ua,va,Ma,o,Wa=Array.prototype.slice,z=!1, t,wa,Na,v,Oa,xa=q.match(/(ipad|iphone|ipod)/i),y=q.match(/msie/i),Xa=q.match(/webkit/i),ya=q.match(/safari/i)&&!q.match(/chrome/i),Pa=q.match(/opera/i),za=q.match(/(mobile|pre\/|xoom)/i)||xa,Qa=!ga.match(/usehtml5audio/i)&&!ga.match(/sm2\-ignorebadua/i)&&ya&&!q.match(/silk/i)&&q.match(/OS X 10_6_([3-7])/i),Aa="undefined"!==typeof l.hasFocus?l.hasFocus():null,ca=ya&&("undefined"===typeof l.hasFocus||!l.hasFocus()),Ra=!ca,Sa=/(mp3|mp4|mpa|m4a)/i,Ba=l.location?l.location.protocol.match(/http/i):null, Ta=!Ba?"http://":"",Ua=/^\s*audio\/(?:x-)?(?:mpeg4|aac|flv|mov|mp4||m4v|m4a|mp4v|3gp|3g2)\s*(?:$|;)/i,Va="mpeg4,aac,flv,mov,mp4,m4v,f4v,m4a,mp4v,3gp,3g2".split(","),Ya=RegExp("\\.("+Va.join("|")+")(\\?.*)?$","i");this.mimePattern=/^\s*audio\/(?:x-)?(?:mp(?:eg|3))\s*(?:$|;)/i;this.useAltURL=!Ba;this._global_a=null;if(za&&(c.useHTML5Audio=!0,c.preferFlash=!1,xa))z=c.ignoreFlash=!0;this.setup=function(a){"undefined"!==typeof a&&k&&n&&c.ok()&&("undefined"!==typeof a.flashVersion||"undefined"!==typeof a.url)&& H(u("setupLate"));ka(a);return c};this.supported=this.ok=function(){return n?k&&!s:c.useHTML5Audio&&c.hasHTML5};this.getMovie=function(a){return S(a)||l[a]||h[a]};this.createSound=function(a,e){function d(){b=Y(b);c.sounds[f.id]=new Ca(f);c.soundIDs.push(f.id);return c.sounds[f.id]}var b=null,g=null,f=null;if(!k||!c.ok())return H(void 0),!1;"undefined"!==typeof e&&(a={id:a,url:e});b=r(a);b.url=aa(b.url);f=b;if(p(f.id,!0))return c.sounds[f.id];if(ba(f))g=d(),g._setup_html5(f);else{if(8<j&&null===f.isMovieStar)f.isMovieStar= !(!f.serverURL&&!(f.type&&f.type.match(Ua)||f.url.match(Ya)));f=Z(f,void 0);g=d();if(8===j)i._createSound(f.id,f.loops||1,f.usePolicyFile);else if(i._createSound(f.id,f.url,f.usePeakData,f.useWaveformData,f.useEQData,f.isMovieStar,f.isMovieStar?f.bufferTime:!1,f.loops||1,f.serverURL,f.duration||null,f.autoPlay,!0,f.autoLoad,f.usePolicyFile),!f.serverURL)g.connected=!0,f.onconnect&&f.onconnect.apply(g);!f.serverURL&&(f.autoLoad||f.autoPlay)&&g.load(f)}!f.serverURL&&f.autoPlay&&g.play();return g};this.destroySound= function(a,e){if(!p(a))return!1;var d=c.sounds[a],b;d._iO={};d.stop();d.unload();for(b=0;b<c.soundIDs.length;b++)if(c.soundIDs[b]===a){c.soundIDs.splice(b,1);break}e||d.destruct(!0);delete c.sounds[a];return!0};this.load=function(a,e){return!p(a)?!1:c.sounds[a].load(e)};this.unload=function(a){return!p(a)?!1:c.sounds[a].unload()};this.onposition=this.onPosition=function(a,e,d,b){return!p(a)?!1:c.sounds[a].onposition(e,d,b)};this.clearOnPosition=function(a,e,d){return!p(a)?!1:c.sounds[a].clearOnPosition(e, d)};this.start=this.play=function(a,e){var d=!1;if(!k||!c.ok())return H("soundManager.play(): "+u(!k?"notReady":"notOK")),d;if(!p(a)){e instanceof Object||(e={url:e});if(e&&e.url)e.id=a,d=c.createSound(e).play();return d}return c.sounds[a].play(e)};this.setPosition=function(a,e){return!p(a)?!1:c.sounds[a].setPosition(e)};this.stop=function(a){return!p(a)?!1:c.sounds[a].stop()};this.stopAll=function(){for(var a in c.sounds)c.sounds.hasOwnProperty(a)&&c.sounds[a].stop()};this.pause=function(a){return!p(a)? !1:c.sounds[a].pause()};this.pauseAll=function(){var a;for(a=c.soundIDs.length-1;0<=a;a--)c.sounds[c.soundIDs[a]].pause()};this.resume=function(a){return!p(a)?!1:c.sounds[a].resume()};this.resumeAll=function(){var a;for(a=c.soundIDs.length-1;0<=a;a--)c.sounds[c.soundIDs[a]].resume()};this.togglePause=function(a){return!p(a)?!1:c.sounds[a].togglePause()};this.setPan=function(a,e){return!p(a)?!1:c.sounds[a].setPan(e)};this.setVolume=function(a,e){return!p(a)?!1:c.sounds[a].setVolume(e)};this.mute=function(a){var e= 0;"string"!==typeof a&&(a=null);if(a)return!p(a)?!1:c.sounds[a].mute();for(e=c.soundIDs.length-1;0<=e;e--)c.sounds[c.soundIDs[e]].mute();return c.muted=!0};this.muteAll=function(){c.mute()};this.unmute=function(a){"string"!==typeof a&&(a=null);if(a)return!p(a)?!1:c.sounds[a].unmute();for(a=c.soundIDs.length-1;0<=a;a--)c.sounds[c.soundIDs[a]].unmute();c.muted=!1;return!0};this.unmuteAll=function(){c.unmute()};this.toggleMute=function(a){return!p(a)?!1:c.sounds[a].toggleMute()};this.getMemoryUse=function(){var a= 0;i&&8!==j&&(a=parseInt(i._getMemoryUse(),10));return a};this.disable=function(a){var e;"undefined"===typeof a&&(a=!1);if(s)return!1;s=!0;for(e=c.soundIDs.length-1;0<=e;e--)Ga(c.sounds[c.soundIDs[e]]);L(a);o.remove(h,"load",C);return!0};this.canPlayMIME=function(a){var e;c.hasHTML5&&(e=P({type:a}));!e&&n&&(e=a&&c.ok()?!!(8<j&&a.match(Ua)||a.match(c.mimePattern)):null);return e};this.canPlayURL=function(a){var e;c.hasHTML5&&(e=P({url:a}));!e&&n&&(e=a&&c.ok()?!!a.match(c.filePattern):null);return e}; this.canPlayLink=function(a){return"undefined"!==typeof a.type&&a.type&&c.canPlayMIME(a.type)?!0:c.canPlayURL(a.href)};this.getSoundById=function(a){if(!a)throw Error("soundManager.getSoundById(): sID is null/undefined");return c.sounds[a]};this.onready=function(a,c){var d=!1;if("function"===typeof a)c||(c=h),la("onready",a,c),B();else throw u("needFunction","onready");return!0};this.ontimeout=function(a,c){var d=!1;if("function"===typeof a)c||(c=h),la("ontimeout",a,c),B({type:"ontimeout"});else throw u("needFunction", "ontimeout");return!0};this._wD=this._writeDebug=function(){return!0};this._debug=function(){};this.reboot=function(){var a,e;for(a=c.soundIDs.length-1;0<=a;a--)c.sounds[c.soundIDs[a]].destruct();if(i)try{if(y)ra=i.innerHTML;M=i.parentNode.removeChild(i)}catch(d){}ra=M=n=null;c.enabled=oa=k=N=ta=J=K=s=c.swfLoaded=!1;c.soundIDs=[];c.sounds={};i=null;for(a in w)if(w.hasOwnProperty(a))for(e=w[a].length-1;0<=e;e--)w[a][e].fired=!1;h.setTimeout(c.beginDelayedInit,20)};this.getMoviePercent=function(){return i&& "undefined"!==typeof i.PercentLoaded?i.PercentLoaded():null};this.beginDelayedInit=function(){ja=!0;E();setTimeout(function(){if(ta)return!1;W();V();return ta=!0},20);D()};this.destruct=function(){c.disable(!0)};Ca=function(a){var e,d,b=this,g,f,A,I,h,l,m=!1,k=[],o=0,q,s,n=null;e=null;d=null;this.sID=this.id=a.id;this.url=a.url;this._iO=this.instanceOptions=this.options=r(a);this.pan=this.options.pan;this.volume=this.options.volume;this.isHTML5=!1;this._a=null;this.id3={};this._debug=function(){}; this.load=function(a){var c=null;if("undefined"!==typeof a)b._iO=r(a,b.options),b.instanceOptions=b._iO;else if(a=b.options,b._iO=a,b.instanceOptions=b._iO,n&&n!==b.url)b._iO.url=b.url,b.url=null;if(!b._iO.url)b._iO.url=b.url;b._iO.url=aa(b._iO.url);if(b._iO.url===b.url&&0!==b.readyState&&2!==b.readyState)return 3===b.readyState&&b._iO.onload&&b._iO.onload.apply(b,[!!b.duration]),b;a=b._iO;n=b.url;b.loaded=!1;b.readyState=1;b.playState=0;b.id3={};if(ba(a)){if(c=b._setup_html5(a),!c._called_load){b._html5_canplay= !1;if(b._a.src!==a.url)b._a.src=a.url,b.setPosition(0);b._a.autobuffer="auto";b._a.preload="auto";c._called_load=!0;a.autoPlay&&b.play()}}else try{b.isHTML5=!1,b._iO=Z(Y(a)),a=b._iO,8===j?i._load(b.id,a.url,a.stream,a.autoPlay,a.whileloading?1:0,a.loops||1,a.usePolicyFile):i._load(b.id,a.url,!!a.stream,!!a.autoPlay,a.loops||1,!!a.autoLoad,a.usePolicyFile)}catch(e){F({type:"SMSOUND_LOAD_JS_EXCEPTION",fatal:!0})}return b};this.unload=function(){if(0!==b.readyState){if(b.isHTML5){if(I(),b._a)b._a.pause(), ua(b._a,"about:blank"),b.url="about:blank"}else 8===j?i._unload(b.id,"about:blank"):i._unload(b.id);g()}return b};this.destruct=function(a){if(b.isHTML5){if(I(),b._a)b._a.pause(),ua(b._a),z||A(),b._a._t=null,b._a=null}else b._iO.onfailure=null,i._destroySound(b.id);a||c.destroySound(b.id,!0)};this.start=this.play=function(a,c){var e,d;d=!0;d=null;c="undefined"===typeof c?!0:c;a||(a={});b._iO=r(a,b._iO);b._iO=r(b._iO,b.options);b._iO.url=aa(b._iO.url);b.instanceOptions=b._iO;if(b._iO.serverURL&&!b.connected)return b.getAutoPlay()|| b.setAutoPlay(!0),b;ba(b._iO)&&(b._setup_html5(b._iO),h());if(1===b.playState&&!b.paused)(e=b._iO.multiShot)||(d=b);if(null!==d)return d;if(!b.loaded)if(0===b.readyState){if(!b.isHTML5)b._iO.autoPlay=!0;b.load(b._iO)}else 2===b.readyState&&(d=b);if(null!==d)return d;if(!b.isHTML5&&9===j&&0<b.position&&b.position===b.duration)a.position=0;if(b.paused&&b.position&&0<b.position)b.resume();else{b._iO=r(a,b._iO);if(null!==b._iO.from&&null!==b._iO.to&&0===b.instanceCount&&0===b.playState&&!b._iO.serverURL){e= function(){b._iO=r(a,b._iO);b.play(b._iO)};if(b.isHTML5&&!b._html5_canplay)b.load({_oncanplay:e}),d=!1;else if(!b.isHTML5&&!b.loaded&&(!b.readyState||2!==b.readyState))b.load({onload:e}),d=!1;if(null!==d)return d;b._iO=s()}(!b.instanceCount||b._iO.multiShotEvents||!b.isHTML5&&8<j&&!b.getAutoPlay())&&b.instanceCount++;b._iO.onposition&&0===b.playState&&l(b);b.playState=1;b.paused=!1;b.position="undefined"!==typeof b._iO.position&&!isNaN(b._iO.position)?b._iO.position:0;if(!b.isHTML5)b._iO=Z(Y(b._iO)); b._iO.onplay&&c&&(b._iO.onplay.apply(b),m=!0);b.setVolume(b._iO.volume,!0);b.setPan(b._iO.pan,!0);b.isHTML5?(h(),d=b._setup_html5(),b.setPosition(b._iO.position),d.play()):(d=i._start(b.id,b._iO.loops||1,9===j?b._iO.position:b._iO.position/1E3,b._iO.multiShot),9===j&&!d&&b._iO.onplayerror&&b._iO.onplayerror.apply(b))}return b};this.stop=function(a){var c=b._iO;if(1===b.playState){b._onbufferchange(0);b._resetOnPosition(0);b.paused=!1;if(!b.isHTML5)b.playState=0;q();c.to&&b.clearOnPosition(c.to);if(b.isHTML5){if(b._a)a= b.position,b.setPosition(0),b.position=a,b._a.pause(),b.playState=0,b._onTimer(),I()}else i._stop(b.id,a),c.serverURL&&b.unload();b.instanceCount=0;b._iO={};c.onstop&&c.onstop.apply(b)}return b};this.setAutoPlay=function(a){b._iO.autoPlay=a;b.isHTML5||(i._setAutoPlay(b.id,a),a&&!b.instanceCount&&1===b.readyState&&b.instanceCount++)};this.getAutoPlay=function(){return b._iO.autoPlay};this.setPosition=function(a){"undefined"===typeof a&&(a=0);var c=b.isHTML5?Math.max(a,0):Math.min(b.duration||b._iO.duration, Math.max(a,0));b.position=c;a=b.position/1E3;b._resetOnPosition(b.position);b._iO.position=c;if(b.isHTML5){if(b._a&&b._html5_canplay&&b._a.currentTime!==a)try{b._a.currentTime=a,(0===b.playState||b.paused)&&b._a.pause()}catch(e){}}else a=9===j?b.position:a,b.readyState&&2!==b.readyState&&i._setPosition(b.id,a,b.paused||!b.playState,b._iO.multiShot);b.isHTML5&&b.paused&&b._onTimer(!0);return b};this.pause=function(a){if(b.paused||0===b.playState&&1!==b.readyState)return b;b.paused=!0;b.isHTML5?(b._setup_html5().pause(), I()):(a||"undefined"===typeof a)&&i._pause(b.id,b._iO.multiShot);b._iO.onpause&&b._iO.onpause.apply(b);return b};this.resume=function(){var a=b._iO;if(!b.paused)return b;b.paused=!1;b.playState=1;b.isHTML5?(b._setup_html5().play(),h()):(a.isMovieStar&&!a.serverURL&&b.setPosition(b.position),i._pause(b.id,a.multiShot));!m&&a.onplay?(a.onplay.apply(b),m=!0):a.onresume&&a.onresume.apply(b);return b};this.togglePause=function(){if(0===b.playState)return b.play({position:9===j&&!b.isHTML5?b.position:b.position/ 1E3}),b;b.paused?b.resume():b.pause();return b};this.setPan=function(a,c){"undefined"===typeof a&&(a=0);"undefined"===typeof c&&(c=!1);b.isHTML5||i._setPan(b.id,a);b._iO.pan=a;if(!c)b.pan=a,b.options.pan=a;return b};this.setVolume=function(a,e){"undefined"===typeof a&&(a=100);"undefined"===typeof e&&(e=!1);if(b.isHTML5){if(b._a)b._a.volume=Math.max(0,Math.min(1,a/100))}else i._setVolume(b.id,c.muted&&!b.muted||b.muted?0:a);b._iO.volume=a;if(!e)b.volume=a,b.options.volume=a;return b};this.mute=function(){b.muted= !0;if(b.isHTML5){if(b._a)b._a.muted=!0}else i._setVolume(b.id,0);return b};this.unmute=function(){b.muted=!1;var a="undefined"!==typeof b._iO.volume;if(b.isHTML5){if(b._a)b._a.muted=!1}else i._setVolume(b.id,a?b._iO.volume:b.options.volume);return b};this.toggleMute=function(){return b.muted?b.unmute():b.mute()};this.onposition=this.onPosition=function(a,c,e){k.push({position:parseInt(a,10),method:c,scope:"undefined"!==typeof e?e:b,fired:!1});return b};this.clearOnPosition=function(b,a){var c,b=parseInt(b, 10);if(isNaN(b))return!1;for(c=0;c<k.length;c++)if(b===k[c].position&&(!a||a===k[c].method))k[c].fired&&o--,k.splice(c,1)};this._processOnPosition=function(){var a,c;a=k.length;if(!a||!b.playState||o>=a)return!1;for(a-=1;0<=a;a--)if(c=k[a],!c.fired&&b.position>=c.position)c.fired=!0,o++,c.method.apply(c.scope,[c.position]);return!0};this._resetOnPosition=function(b){var a,c;a=k.length;if(!a)return!1;for(a-=1;0<=a;a--)if(c=k[a],c.fired&&b<=c.position)c.fired=!1,o--;return!0};s=function(){var a=b._iO, c=a.from,e=a.to,d,f;f=function(){b.clearOnPosition(e,f);b.stop()};d=function(){if(null!==e&&!isNaN(e))b.onPosition(e,f)};if(null!==c&&!isNaN(c))a.position=c,a.multiShot=!1,d();return a};l=function(){var a,c=b._iO.onposition;if(c)for(a in c)if(c.hasOwnProperty(a))b.onPosition(parseInt(a,10),c[a])};q=function(){var a,c=b._iO.onposition;if(c)for(a in c)c.hasOwnProperty(a)&&b.clearOnPosition(parseInt(a,10))};h=function(){b.isHTML5&&Ia(b)};I=function(){b.isHTML5&&Ja(b)};g=function(a){a||(k=[],o=0);m=!1; b._hasTimer=null;b._a=null;b._html5_canplay=!1;b.bytesLoaded=null;b.bytesTotal=null;b.duration=b._iO&&b._iO.duration?b._iO.duration:null;b.durationEstimate=null;b.buffered=[];b.eqData=[];b.eqData.left=[];b.eqData.right=[];b.failures=0;b.isBuffering=!1;b.instanceOptions={};b.instanceCount=0;b.loaded=!1;b.metadata={};b.readyState=0;b.muted=!1;b.paused=!1;b.peakData={left:0,right:0};b.waveformData={left:[],right:[]};b.playState=0;b.position=null;b.id3={}};g();this._onTimer=function(a){var c,f=!1,g={}; if(b._hasTimer||a){if(b._a&&(a||(0<b.playState||1===b.readyState)&&!b.paused)){c=b._get_html5_duration();if(c!==e)e=c,b.duration=c,f=!0;b.durationEstimate=b.duration;c=1E3*b._a.currentTime||0;c!==d&&(d=c,f=!0);(f||a)&&b._whileplaying(c,g,g,g,g)}return f}};this._get_html5_duration=function(){var a=b._iO,c=b._a?1E3*b._a.duration:a?a.duration:void 0;return c&&!isNaN(c)&&Infinity!==c?c:a?a.duration:null};this._apply_loop=function(b,a){b.loop=1<a?"loop":""};this._setup_html5=function(a){var a=r(b._iO, a),e=decodeURI,d=z?c._global_a:b._a,i=e(a.url),h=d&&d._t?d._t.instanceOptions:null,A;if(d){if(d._t){if(!z&&i===e(n))A=d;else if(z&&h.url===a.url&&(!n||n===h.url))A=d;if(A)return b._apply_loop(d,a.loops),A}z&&d._t&&d._t.playState&&a.url!==h.url&&d._t.stop();g(h&&h.url?a.url===h.url:n?n===a.url:!1);d.src=a.url;n=b.url=a.url;d._called_load=!1}else if(b._a=a.autoLoad||a.autoPlay?new Audio(a.url):Pa?new Audio(null):new Audio,d=b._a,d._called_load=!1,z)c._global_a=d;b.isHTML5=!0;b._a=d;d._t=b;f();b._apply_loop(d, a.loops);a.autoLoad||a.autoPlay?b.load():(d.autobuffer=!1,d.preload="auto");return d};f=function(){if(b._a._added_events)return!1;var a;b._a._added_events=!0;for(a in v)v.hasOwnProperty(a)&&b._a&&b._a.addEventListener(a,v[a],!1);return!0};A=function(){var a;b._a._added_events=!1;for(a in v)v.hasOwnProperty(a)&&b._a&&b._a.removeEventListener(a,v[a],!1)};this._onload=function(a){a=!!a||!b.isHTML5&&8===j&&b.duration;b.loaded=a;b.readyState=a?3:2;b._onbufferchange(0);b._iO.onload&&b._iO.onload.apply(b, [a]);return!0};this._onbufferchange=function(a){if(0===b.playState||a&&b.isBuffering||!a&&!b.isBuffering)return!1;b.isBuffering=1===a;b._iO.onbufferchange&&b._iO.onbufferchange.apply(b);return!0};this._onsuspend=function(){b._iO.onsuspend&&b._iO.onsuspend.apply(b);return!0};this._onfailure=function(a,c,e){b.failures++;if(b._iO.onfailure&&1===b.failures)b._iO.onfailure(b,a,c,e)};this._onfinish=function(){var a=b._iO.onfinish;b._onbufferchange(0);b._resetOnPosition(0);if(b.instanceCount){b.instanceCount--; if(!b.instanceCount&&(q(),b.playState=0,b.paused=!1,b.instanceCount=0,b.instanceOptions={},b._iO={},I(),b.isHTML5))b.position=0;(!b.instanceCount||b._iO.multiShotEvents)&&a&&a.apply(b)}};this._whileloading=function(a,c,e,d){var f=b._iO;b.bytesLoaded=a;b.bytesTotal=c;b.duration=Math.floor(e);b.bufferLength=d;if(f.isMovieStar)b.durationEstimate=b.duration;else if(b.durationEstimate=f.duration?b.duration>f.duration?b.duration:f.duration:parseInt(b.bytesTotal/b.bytesLoaded*b.duration,10),"undefined"=== typeof b.durationEstimate)b.durationEstimate=b.duration;if(!b.isHTML5)b.buffered=[{start:0,end:b.duration}];(3!==b.readyState||b.isHTML5)&&f.whileloading&&f.whileloading.apply(b)};this._whileplaying=function(a,c,e,d,f){var g=b._iO;if(isNaN(a)||null===a)return!1;b.position=Math.max(0,a);b._processOnPosition();if(!b.isHTML5&&8<j){if(g.usePeakData&&"undefined"!==typeof c&&c)b.peakData={left:c.leftPeak,right:c.rightPeak};if(g.useWaveformData&&"undefined"!==typeof e&&e)b.waveformData={left:e.split(","), right:d.split(",")};if(g.useEQData&&"undefined"!==typeof f&&f&&f.leftEQ&&(a=f.leftEQ.split(","),b.eqData=a,b.eqData.left=a,"undefined"!==typeof f.rightEQ&&f.rightEQ))b.eqData.right=f.rightEQ.split(",")}1===b.playState&&(!b.isHTML5&&8===j&&!b.position&&b.isBuffering&&b._onbufferchange(0),g.whileplaying&&g.whileplaying.apply(b));return!0};this._oncaptiondata=function(a){b.captiondata=a;b._iO.oncaptiondata&&b._iO.oncaptiondata.apply(b)};this._onmetadata=function(a,c){var e={},d,f;for(d=0,f=a.length;d< f;d++)e[a[d]]=c[d];b.metadata=e;b._iO.onmetadata&&b._iO.onmetadata.apply(b)};this._onid3=function(a,c){var e=[],d,f;for(d=0,f=a.length;d<f;d++)e[a[d]]=c[d];b.id3=r(b.id3,e);b._iO.onid3&&b._iO.onid3.apply(b)};this._onconnect=function(a){a=1===a;if(b.connected=a)b.failures=0,p(b.id)&&(b.getAutoPlay()?b.play(void 0,b.getAutoPlay()):b._iO.autoLoad&&b.load()),b._iO.onconnect&&b._iO.onconnect.apply(b,[a])};this._ondataerror=function(){0<b.playState&&b._iO.ondataerror&&b._iO.ondataerror.apply(b)}};pa=function(){return l.body|| l._docElement||l.getElementsByTagName("div")[0]};S=function(a){return l.getElementById(a)};r=function(a,e){var d=a||{},b,g;b="undefined"===typeof e?c.defaultOptions:e;for(g in b)b.hasOwnProperty(g)&&"undefined"===typeof d[g]&&(d[g]="object"!==typeof b[g]||null===b[g]?b[g]:r(d[g],b[g]));return d};T={onready:1,ontimeout:1,defaultOptions:1,flash9Options:1,movieStarOptions:1};ka=function(a,e){var d,b=!0,g="undefined"!==typeof e,f=c.setupOptions;for(d in a)if(a.hasOwnProperty(d))if("object"!==typeof a[d]|| null===a[d]||a[d]instanceof Array)g&&"undefined"!==typeof T[e]?c[e][d]=a[d]:"undefined"!==typeof f[d]?(c.setupOptions[d]=a[d],c[d]=a[d]):"undefined"===typeof T[d]?(H(u("undefined"===typeof c[d]?"setupUndef":"setupError",d),2),b=!1):c[d]instanceof Function?c[d].apply(c,a[d]instanceof Array?a[d]:[a[d]]):c[d]=a[d];else if("undefined"===typeof T[d])H(u("undefined"===typeof c[d]?"setupUndef":"setupError",d),2),b=!1;else return ka(a[d],d);return b};o=function(){function a(a){var a=Wa.call(a),b=a.length; d?(a[1]="on"+a[1],3<b&&a.pop()):3===b&&a.push(!1);return a}function c(a,e){var h=a.shift(),i=[b[e]];if(d)h[i](a[0],a[1]);else h[i].apply(h,a)}var d=h.attachEvent,b={add:d?"attachEvent":"addEventListener",remove:d?"detachEvent":"removeEventListener"};return{add:function(){c(a(arguments),"add")},remove:function(){c(a(arguments),"remove")}}}();v={abort:m(function(){}),canplay:m(function(){var a=this._t,c;if(a._html5_canplay)return!0;a._html5_canplay=!0;a._onbufferchange(0);c="undefined"!==typeof a._iO.position&& !isNaN(a._iO.position)?a._iO.position/1E3:null;if(a.position&&this.currentTime!==c)try{this.currentTime=c}catch(d){}a._iO._oncanplay&&a._iO._oncanplay()}),canplaythrough:m(function(){var a=this._t;a.loaded||(a._onbufferchange(0),a._whileloading(a.bytesLoaded,a.bytesTotal,a._get_html5_duration()),a._onload(!0))}),ended:m(function(){this._t._onfinish()}),error:m(function(){this._t._onload(!1)}),loadeddata:m(function(){var a=this._t;if(!a._loaded&&!ya)a.duration=a._get_html5_duration()}),loadedmetadata:m(function(){}), loadstart:m(function(){this._t._onbufferchange(1)}),play:m(function(){this._t._onbufferchange(0)}),playing:m(function(){this._t._onbufferchange(0)}),progress:m(function(a){var c=this._t,d,b,g=0,g=a.target.buffered;d=a.loaded||0;var f=a.total||1;c.buffered=[];if(g&&g.length){for(d=0,b=g.length;d<b;d++)c.buffered.push({start:g.start(d),end:g.end(d)});g=g.end(0)-g.start(0);d=g/a.target.duration}isNaN(d)||(c._onbufferchange(0),c._whileloading(d,f,c._get_html5_duration()),d&&f&&d===f&&v.canplaythrough.call(this, a))}),ratechange:m(function(){}),suspend:m(function(a){var c=this._t;v.progress.call(this,a);c._onsuspend()}),stalled:m(function(){}),timeupdate:m(function(){this._t._onTimer()}),waiting:m(function(){this._t._onbufferchange(1)})};ba=function(a){return a.serverURL||a.type&&R(a.type)?!1:a.type?P({type:a.type}):P({url:a.url})||c.html5Only};ua=function(a,c){if(a)a.src=c};P=function(a){if(!c.useHTML5Audio||!c.hasHTML5)return!1;var e=a.url||null,a=a.type||null,d=c.audioFormats,b;if(a&&"undefined"!==typeof c.html5[a])return c.html5[a]&& !R(a);if(!x){x=[];for(b in d)d.hasOwnProperty(b)&&(x.push(b),d[b].related&&(x=x.concat(d[b].related)));x=RegExp("\\.("+x.join("|")+")(\\?.*)?$","i")}b=e?e.toLowerCase().match(x):null;!b||!b.length?a&&(e=a.indexOf(";"),b=(-1!==e?a.substr(0,e):a).substr(6)):b=b[1];b&&"undefined"!==typeof c.html5[b]?e=c.html5[b]&&!R(b):(a="audio/"+b,e=c.html5.canPlayType({type:a}),e=(c.html5[b]=e)&&c.html5[a]&&!R(a));return e};Ma=function(){function a(a){var b,d,f=b=!1;if(!e||"function"!==typeof e.canPlayType)return b; if(a instanceof Array){for(b=0,d=a.length;b<d&&!f;b++)if(c.html5[a[b]]||e.canPlayType(a[b]).match(c.html5Test))f=!0,c.html5[a[b]]=!0,c.flash[a[b]]=!!a[b].match(Sa);b=f}else a=e&&"function"===typeof e.canPlayType?e.canPlayType(a):!1,b=!(!a||!a.match(c.html5Test));return b}if(!c.useHTML5Audio||"undefined"===typeof Audio)return!1;var e="undefined"!==typeof Audio?Pa?new Audio(null):new Audio:null,d,b,g={},f;f=c.audioFormats;for(d in f)if(f.hasOwnProperty(d)&&(b="audio/"+d,g[d]=a(f[d].type),g[b]=g[d], d.match(Sa)?(c.flash[d]=!0,c.flash[b]=!0):(c.flash[d]=!1,c.flash[b]=!1),f[d]&&f[d].related))for(b=f[d].related.length-1;0<=b;b--)g["audio/"+f[d].related[b]]=g[d],c.html5[f[d].related[b]]=g[d],c.flash[f[d].related[b]]=g[d];g.canPlayType=e?a:null;c.html5=r(c.html5,g);return!0};u=function(){};Y=function(a){if(8===j&&1<a.loops&&a.stream)a.stream=!1;return a};Z=function(a){if(a&&!a.usePolicyFile&&(a.onid3||a.usePeakData||a.useWaveformData||a.useEQData))a.usePolicyFile=!0;return a};H=function(){};ha=function(){return!1}; Ga=function(a){for(var c in a)a.hasOwnProperty(c)&&"function"===typeof a[c]&&(a[c]=ha)};X=function(a){"undefined"===typeof a&&(a=!1);(s||a)&&c.disable(a)};Ha=function(a){var e=null;if(a)if(a.match(/\.swf(\?.*)?$/i)){if(e=a.substr(a.toLowerCase().lastIndexOf(".swf?")+4))return a}else a.lastIndexOf("/")!==a.length-1&&(a+="/");a=(a&&-1!==a.lastIndexOf("/")?a.substr(0,a.lastIndexOf("/")+1):"./")+c.movieURL;c.noSWFCache&&(a+="?ts="+(new Date).getTime());return a};ma=function(){j=parseInt(c.flashVersion, 10);if(8!==j&&9!==j)c.flashVersion=j=8;var a=c.debugMode||c.debugFlash?"_debug.swf":".swf";if(c.useHTML5Audio&&!c.html5Only&&c.audioFormats.mp4.required&&9>j)c.flashVersion=j=9;c.version=c.versionNumber+(c.html5Only?" (HTML5-only mode)":9===j?" (AS3/Flash 9)":" (AS2/Flash 8)");8<j?(c.defaultOptions=r(c.defaultOptions,c.flash9Options),c.features.buffering=!0,c.defaultOptions=r(c.defaultOptions,c.movieStarOptions),c.filePatterns.flash9=RegExp("\\.(mp3|"+Va.join("|")+")(\\?.*)?$","i"),c.features.movieStar= !0):c.features.movieStar=!1;c.filePattern=c.filePatterns[8!==j?"flash9":"flash8"];c.movieURL=(8===j?"soundmanager2.swf":"soundmanager2_flash9.swf").replace(".swf",a);c.features.peakData=c.features.waveformData=c.features.eqData=8<j};Fa=function(a,c){if(!i)return!1;i._setPolling(a,c)};qa=function(){if(c.debugURLParam.test(ga))c.debugMode=!0};p=this.getSoundById;G=function(){var a=[];c.debugMode&&a.push("sm2_debug");c.debugFlash&&a.push("flash_debug");c.useHighPerformance&&a.push("high_performance"); return a.join(" ")};sa=function(){u("fbHandler");var a=c.getMoviePercent(),e={type:"FLASHBLOCK"};if(c.html5Only)return!1;if(c.ok()){if(c.oMC)c.oMC.className=[G(),"movieContainer","swf_loaded"+(c.didFlashBlock?" swf_unblocked":"")].join(" ")}else{if(n)c.oMC.className=G()+" movieContainer "+(null===a?"swf_timedout":"swf_error");c.didFlashBlock=!0;B({type:"ontimeout",ignoreInit:!0,error:e});F(e)}};la=function(a,c,d){"undefined"===typeof w[a]&&(w[a]=[]);w[a].push({method:c,scope:d||null,fired:!1})};B= function(a){a||(a={type:c.ok()?"onready":"ontimeout"});if(!k&&a&&!a.ignoreInit||"ontimeout"===a.type&&(c.ok()||s&&!a.ignoreInit))return!1;var e={success:a&&a.ignoreInit?c.ok():!s},d=a&&a.type?w[a.type]||[]:[],b=[],g,e=[e],f=n&&c.useFlashBlock&&!c.ok();if(a.error)e[0].error=a.error;for(a=0,g=d.length;a<g;a++)!0!==d[a].fired&&b.push(d[a]);if(b.length)for(a=0,g=b.length;a<g;a++)if(b[a].scope?b[a].method.apply(b[a].scope,e):b[a].method.apply(this,e),!f)b[a].fired=!0;return!0};C=function(){h.setTimeout(function(){c.useFlashBlock&& sa();B();"function"===typeof c.onload&&c.onload.apply(h);c.waitForWindowLoad&&o.add(h,"load",C)},1)};wa=function(){if("undefined"!==typeof t)return t;var a=!1,c=navigator,d=c.plugins,b,g=h.ActiveXObject;if(d&&d.length)(c=c.mimeTypes)&&c["application/x-shockwave-flash"]&&c["application/x-shockwave-flash"].enabledPlugin&&c["application/x-shockwave-flash"].enabledPlugin.description&&(a=!0);else if("undefined"!==typeof g){try{b=new g("ShockwaveFlash.ShockwaveFlash")}catch(f){}a=!!b}return t=a};La=function(){var a, e,d=c.audioFormats;if(xa&&q.match(/os (1|2|3_0|3_1)/i)){if(c.hasHTML5=!1,c.html5Only=!0,c.oMC)c.oMC.style.display="none"}else if(c.useHTML5Audio)c.hasHTML5=!c.html5||!c.html5.canPlayType?!1:!0;if(c.useHTML5Audio&&c.hasHTML5)for(e in d)if(d.hasOwnProperty(e)&&(d[e].required&&!c.html5.canPlayType(d[e].type)||c.preferFlash&&(c.flash[e]||c.flash[d[e].type])))a=!0;c.ignoreFlash&&(a=!1);c.html5Only=c.hasHTML5&&c.useHTML5Audio&&!a;return!c.html5Only};aa=function(a){var e,d,b=0;if(a instanceof Array){for(e= 0,d=a.length;e<d;e++)if(a[e]instanceof Object){if(c.canPlayMIME(a[e].type)){b=e;break}}else if(c.canPlayURL(a[e])){b=e;break}if(a[b].url)a[b]=a[b].url;a=a[b]}return a};Ia=function(a){if(!a._hasTimer)a._hasTimer=!0,!za&&c.html5PollingInterval&&(null===O&&0===$&&(O=h.setInterval(Ka,c.html5PollingInterval)),$++)};Ja=function(a){if(a._hasTimer)a._hasTimer=!1,!za&&c.html5PollingInterval&&$--};Ka=function(){var a;if(null!==O&&!$)return h.clearInterval(O),O=null,!1;for(a=c.soundIDs.length-1;0<=a;a--)c.sounds[c.soundIDs[a]].isHTML5&& c.sounds[c.soundIDs[a]]._hasTimer&&c.sounds[c.soundIDs[a]]._onTimer()};F=function(a){a="undefined"!==typeof a?a:{};"function"===typeof c.onerror&&c.onerror.apply(h,[{type:"undefined"!==typeof a.type?a.type:null}]);"undefined"!==typeof a.fatal&&a.fatal&&c.disable()};Na=function(){if(!Qa||!wa())return!1;var a=c.audioFormats,e,d;for(d in a)if(a.hasOwnProperty(d)&&("mp3"===d||"mp4"===d))if(c.html5[d]=!1,a[d]&&a[d].related)for(e=a[d].related.length-1;0<=e;e--)c.html5[a[d].related[e]]=!1};this._setSandboxType= function(){};this._externalInterfaceOK=function(){if(c.swfLoaded)return!1;(new Date).getTime();c.swfLoaded=!0;ca=!1;Qa&&Na();setTimeout(ia,y?100:1)};W=function(a,e){function d(a,b){return'<param name="'+a+'" value="'+b+'" />'}if(J&&K)return!1;if(c.html5Only)return ma(),c.oMC=S(c.movieID),ia(),K=J=!0,!1;var b=e||c.url,g=c.altURL||b,f;f=pa();var h,i,j=G(),k,m=null,m=(m=l.getElementsByTagName("html")[0])&&m.dir&&m.dir.match(/rtl/i),a="undefined"===typeof a?c.id:a;ma();c.url=Ha(Ba?b:g);e=c.url;c.wmode= !c.wmode&&c.useHighPerformance?"transparent":c.wmode;if(null!==c.wmode&&(q.match(/msie 8/i)||!y&&!c.useHighPerformance)&&navigator.platform.match(/win32|win64/i))c.wmode=null;f={name:a,id:a,src:e,quality:"high",allowScriptAccess:c.allowScriptAccess,bgcolor:c.bgColor,pluginspage:Ta+"www.macromedia.com/go/getflashplayer",title:"JS/Flash audio component (SoundManager 2)",type:"application/x-shockwave-flash",wmode:c.wmode,hasPriority:"true"};if(c.debugFlash)f.FlashVars="debug=1";c.wmode||delete f.wmode; if(y)b=l.createElement("div"),i=['<object id="'+a+'" data="'+e+'" type="'+f.type+'" title="'+f.title+'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="'+Ta+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0">',d("movie",e),d("AllowScriptAccess",c.allowScriptAccess),d("quality",f.quality),c.wmode?d("wmode",c.wmode):"",d("bgcolor",c.bgColor),d("hasPriority","true"),c.debugFlash?d("FlashVars",f.FlashVars):"","</object>"].join("");else for(h in b=l.createElement("embed"), f)f.hasOwnProperty(h)&&b.setAttribute(h,f[h]);qa();j=G();if(f=pa())if(c.oMC=S(c.movieID)||l.createElement("div"),c.oMC.id){k=c.oMC.className;c.oMC.className=(k?k+" ":"movieContainer")+(j?" "+j:"");c.oMC.appendChild(b);if(y)h=c.oMC.appendChild(l.createElement("div")),h.className="sm2-object-box",h.innerHTML=i;K=!0}else{c.oMC.id=c.movieID;c.oMC.className="movieContainer "+j;h=j=null;if(!c.useFlashBlock)if(c.useHighPerformance)j={position:"fixed",width:"8px",height:"8px",bottom:"0px",left:"0px",overflow:"hidden"}; else if(j={position:"absolute",width:"6px",height:"6px",top:"-9999px",left:"-9999px"},m)j.left=Math.abs(parseInt(j.left,10))+"px";if(Xa)c.oMC.style.zIndex=1E4;if(!c.debugFlash)for(k in j)j.hasOwnProperty(k)&&(c.oMC.style[k]=j[k]);try{y||c.oMC.appendChild(b);f.appendChild(c.oMC);if(y)h=c.oMC.appendChild(l.createElement("div")),h.className="sm2-object-box",h.innerHTML=i;K=!0}catch(n){throw Error(u("domError")+" \n"+n.toString());}}return J=!0};V=function(){if(c.html5Only)return W(),!1;if(i)return!1; i=c.getMovie(c.id);if(!i)M?(y?c.oMC.innerHTML=ra:c.oMC.appendChild(M),M=null,J=!0):W(c.id,c.url),i=c.getMovie(c.id);"function"===typeof c.oninitmovie&&setTimeout(c.oninitmovie,1);return!0};D=function(){setTimeout(Ea,1E3)};Ea=function(){var a,e=!1;if(N)return!1;N=!0;o.remove(h,"load",D);if(ca&&!Aa)return!1;k||(a=c.getMoviePercent(),0<a&&100>a&&(e=!0));setTimeout(function(){a=c.getMoviePercent();if(e)return N=!1,h.setTimeout(D,1),!1;!k&&Ra&&(null===a?c.useFlashBlock||0===c.flashLoadTimeout?c.useFlashBlock&& sa():X(!0):0!==c.flashLoadTimeout&&X(!0))},c.flashLoadTimeout)};U=function(){if(Aa||!ca)return o.remove(h,"focus",U),!0;Aa=Ra=!0;N=!1;D();o.remove(h,"focus",U);return!0};Oa=function(){var a,e=[];if(c.useHTML5Audio&&c.hasHTML5)for(a in c.audioFormats)c.audioFormats.hasOwnProperty(a)&&e.push(a+": "+c.html5[a]+(!c.html5[a]&&t&&c.flash[a]?" (using flash)":c.preferFlash&&c.flash[a]&&t?" (preferring flash)":!c.html5[a]?" ("+(c.audioFormats[a].required?"required, ":"")+"and no flash support)":""))};L=function(a){if(k)return!1; if(c.html5Only)return k=!0,C(),!0;var e=!0,d;if(!c.useFlashBlock||!c.flashLoadTimeout||c.getMoviePercent())k=!0,s&&(d={type:!t&&n?"NO_FLASH":"INIT_TIMEOUT"});if(s||a){if(c.useFlashBlock&&c.oMC)c.oMC.className=G()+" "+(null===c.getMoviePercent()?"swf_timedout":"swf_error");B({type:"ontimeout",error:d,ignoreInit:!0});F(d);e=!1}s||(c.waitForWindowLoad&&!ja?o.add(h,"load",C):C());return e};Da=function(){var a,e=c.setupOptions;for(a in e)e.hasOwnProperty(a)&&("undefined"===typeof c[a]?c[a]=e[a]:c[a]!== e[a]&&(c.setupOptions[a]=c[a]))};ia=function(){if(k)return!1;if(c.html5Only){if(!k)o.remove(h,"load",c.beginDelayedInit),c.enabled=!0,L();return!0}V();try{i._externalInterfaceTest(!1),Fa(!0,c.flashPollingInterval||(c.useHighPerformance?10:50)),c.debugMode||i._disableDebug(),c.enabled=!0,c.html5Only||o.add(h,"unload",ha)}catch(a){return F({type:"JS_TO_FLASH_EXCEPTION",fatal:!0}),X(!0),L(),!1}L();o.remove(h,"load",c.beginDelayedInit);return!0};E=function(){if(oa)return!1;oa=!0;Da();qa();!t&&c.hasHTML5&& c.setup({useHTML5Audio:!0,preferFlash:!1});Ma();c.html5.usingFlash=La();n=c.html5.usingFlash;Oa();!t&&n&&c.setup({flashLoadTimeout:1});l.removeEventListener&&l.removeEventListener("DOMContentLoaded",E,!1);V();return!0};va=function(){"complete"===l.readyState&&(E(),l.detachEvent("onreadystatechange",va));return!0};na=function(){ja=!0;o.remove(h,"load",na)};wa();o.add(h,"focus",U);o.add(h,"load",D);o.add(h,"load",na);l.addEventListener?l.addEventListener("DOMContentLoaded",E,!1):l.attachEvent?l.attachEvent("onreadystatechange", va):F({type:"NO_DOM2_EVENTS",fatal:!0});"complete"===l.readyState&&setTimeout(E,100)}var da=null;if("undefined"===typeof SM2_DEFER||!SM2_DEFER)da=new Q;ea.SoundManager=Q;ea.soundManager=da})(window);
module.exports={title:"Big Cartel",slug:"bigcartel",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Big Cartel icon</title><path d="M12 13.068v-1.006c0-.63.252-1.256.88-1.508l7.79-4.9c.503-.252.755-.88.755-1.51V0L12 6.03 2.575 0v12.69c0 3.394 1.51 6.284 4.02 7.917L11.875 24l5.28-3.393c2.513-1.51 4.02-4.398 4.02-7.916V7.036L12 13.068z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://www.bigcartel.com",hex:"222222",license:void 0};
/* version: 0.3.142, born: 8-2-2014 11:48 */ var Organic = (function(w){ var o = { helpers: {}, lib: { atoms: {}, molecules: {} } } var require = function(v) { if(v == "./helpers/extend") { return o.helpers.extend; } else if(v == "/helpers/snippets" || v == "../../helpers/snippets") { return o.helpers.snippets; } else if(v == "/lib/atoms/atoms" || v == "../../lib/atoms/atoms" || v == "../atoms/atoms.js") { return o.lib.atoms.atoms; } else if(v == "../../helpers/units") { return o.helpers.units; } else if(v == "../../helpers/args") { return o.helpers.args; } else if(v == "path") { return { basename: function(f) { return f.split("/").pop(); } } } else { var moduleParts = v.split("/"); return (function getModule(currentModule) { var part = moduleParts.shift().replace(".js", ""); if(currentModule[part]) { if(moduleParts.length == 0) { return currentModule[part]; } else { return getModule(currentModule[part]) } } })(o); } } var __dirname = ''; var walkClientSide = function(res, obj, path) { if(typeof res == 'undefined') res = []; if(typeof obj == 'undefined') obj = o.lib; if(typeof path == 'undefined') path = "lib/"; for(var part in obj) { if(typeof obj[part] == 'function') { res.push(path + part + ".js"); } else { walkClientSide(res, obj[part], path + part + "/"); } } return res; };o.helpers.args = function(value) { value = value.toString().replace(/\/ /g, '/').split('/'); return value; } o.helpers.extend = function() { var process = function(destination, source) { for (var key in source) { if (hasOwnProperty.call(source, key)) { destination[key] = source[key]; } } return destination; }; var result = arguments[0]; for(var i=1; i<arguments.length; i++) { result = process(result, arguments[i]); } return result; } o.helpers.snippets = function() { // http://peters-playground.com/Emmet-Css-Snippets-for-Sublime-Text-2/ return { // Visual Formatting "pos": "position", "pos:s": "position:static", "pos:a": "position:absolute", "pos:r": "position:relative", "pos:f": "position:fixed", // "top": "top", "t:a": "top:auto", "rig": "right", "r:a": "right:auto", "bot": "bottom", // "b:a": "bottom:auto", // breaks the multiple comma selectors "lef": "left", "l:a": "left:auto", "zin": "z-index", "z:a": "z-index:auto", "fl": "float", "fl:n": "float:none", "fl:l": "float:left", "fl:r": "float:right", "cl": "clear", "cl:n": "clear:none", "cl:l": "clear:left", "cl:r": "clear:right", "cl:b": "clear:both", "dis": "display", "d:n": "display:none", "d:b": "display:block", "d:i": "display:inline", "d:ib": "display:inline-block", "d:li": "display:list-item", "d:ri": "display:run-in", "d:cp": "display:compact", "d:tb": "display:table", "d:itb": "display:inline-table", "d:tbcp": "display:table-caption", "d:tbcl": "display:table-column", "d:tbclg": "display:table-column-group", "d:tbhg": "display:table-header-group", "d:tbfg": "display:table-footer-group", "d:tbr": "display:table-row", "d:tbrg": "display:table-row-group", "d:tbc": "display:table-cell", "d:rb": "display:ruby", "d:rbb": "display:ruby-base", "d:rbbg": "display:ruby-base-group", "d:rbt": "display:ruby-text", "d:rbtg": "display:ruby-text-group", "vis": "visibility", "v:v": "visibility:visible", "v:h": "visibility:hidden", "v:c": "visibility:collapse", "ov": "overflow", "ov:v": "overflow:visible", "ov:h": "overflow:hidden", "ov:s": "overflow:scroll", "ov:a": "overflow:auto", "ovx": "overflow-x", "ovx:v": "overflow-x:visible", "ovx:h": "overflow-x:hidden", "ovx:s": "overflow-x:scroll", "ovx:a": "overflow-x:auto", "ovy": "overflow-y", "ovy:v": "overflow-y:visible", "ovy:h": "overflow-y:hidden", "ovy:s": "overflow-y:scroll", "ovy:a": "overflow-y:auto", "ovs": "overflow-style", "ovs:a": "overflow-style:auto", "ovs:s": "overflow-style:scrollbar", "ovs:p": "overflow-style:panner", "ovs:m": "overflow-style:move", "ovs:mq": "overflow-style:marquee", "zoo": "zoom:1", "cp": "clip", "cp:a": "clip:auto", "cp:r": "clip:rect()", "rz": "resize", "rz:n": "resize:none", "rz:b": "resize:both", "rz:h": "resize:horizontal", "rz:v": "resize:vertical", "cur": "cursor", "cur:a": "cursor:auto", "cur:d": "cursor:default", "cur:c": "cursor:crosshair", "cur:ha": "cursor:hand", "cur:he": "cursor:help", "cur:m": "cursor:move", "cur:p": "cursor:pointer", "cur:t": "cursor:text", // Margin & Padding "mar": "margin", "m:au": "margin:0 auto", "mt": "margin-top", "mt:a": "margin-top:auto", "mr": "margin-right", "mr:a": "margin-right:auto", "mb": "margin-bottom", "mb:a": "margin-bottom:auto", "ml": "margin-left", "ml:a": "margin-left:auto", "pad": "padding", "pt": "padding-top", "pr": "padding-right", "pb": "padding-bottom", "pl": "padding-left", // Box Sizing "bxz": "box-sizing", "bxz:cb": "box-sizing:content-box", "bxz:bb": "box-sizing:border-box", "bxsh": "box-shadow", "bxsh:n": "box-shadow:none", "bxsh+": "box-shadow:0 0 0 #000", "wid": "width", "w:a": "width:auto", "hei": "height", "h:a": "height:auto", "maw": "max-width", "maw:n": "max-width:none", "mah": "max-height", "mah:n": "max-height:none", "miw": "min-width", "mih": "min-height", // Font "fon": "font", "fon+": "font:1em Arial, sans-serif", "fw": "font-weight", "fw:n": "font-weight:normal", "fw:b": "font-weight:bold", "fw:br": "font-weight:bolder", "fw:lr": "font-weight:lighter", "fs": "font-style", "fs:n": "font-style:normal", "fs:i": "font-style:italic", "fs:o": "font-style:oblique", "fv": "font-variant", "fv:n": "font-variant:normal", "fv:sc": "font-variant:small-caps", "fz": "font-size", "fza": "font-size-adjust", "fza:n": "font-size-adjust:none", "ff": "font-family", "ff:s": "font-family:serif", "ff:ss": "font-family:sans-serif", "ff:c": "font-family:cursive", "ff:f": "font-family:fantasy", "ff:m": "font-family:monospace", "fef": "font-effect", "fef:n": "font-effect:none", "fef:eg": "font-effect:engrave", "fef:eb": "font-effect:emboss", "fef:o": "font-effect:outline", "fem": "font-emphasize", "femp": "font-emphasize-position", "femp:b": "font-emphasize-position:before", "femp:a": "font-emphasize-position:after", "fems": "font-emphasize-style", "fems:n": "font-emphasize-style:none", "fems:ac": "font-emphasize-style:accent", "fems:dt": "font-emphasize-style:dot", "fems:c": "font-emphasize-style:circle", "fems:ds": "font-emphasize-style:disc", "fsm": "font-smooth", "fsm:au": "font-smooth:auto", "fsm:n": "font-smooth:never", "fsm:al": "font-smooth:always", "fst": "font-stretch", "fst:n": "font-stretch:normal", "fst:uc": "font-stretch:ultra-condensed", "fst:ec": "font-stretch:extra-condensed", "fst:c": "font-stretch:condensed", "fst:sc": "font-stretch:semi-condensed", "fst:se": "font-stretch:semi-expanded", "fst:e": "font-stretch:expanded", "fst:ee": "font-stretch:extra-expanded", "fst:ue": "font-stretch:ultra-expanded", // Text "va": "vertical-align", "va:sup": "vertical-align:super", "va:t": "vertical-align:top", "va:tt": "vertical-align:text-top", "va:m": "vertical-align:middle", "va:bl": "vertical-align:baseline", "va:b": "vertical-align:bottom", "va:tb": "vertical-align:text-bottom", "va:sub": "vertical-align:sub", "ta": "text-align", "ta:le": "text-align:left", "ta:c": "text-align:center", "ta:r": "text-align:right", "ta:j": "text-align:justify", "tal": "text-align-last", "tal:a": "text-align-last:auto", "tal:l": "text-align-last:left", "tal:c": "text-align-last:center", "tal:r": "text-align-last:right", "ted": "text-decoration", "ted:n": "text-decoration:none", "ted:u": "text-decoration:underline", "ted:o": "text-decoration:overline", "ted:l": "text-decoration:line-through", "te": "text-emphasis", "te:n": "text-emphasis:none", "te:ac": "text-emphasis:accent", "te:dt": "text-emphasis:dot", "te:c": "text-emphasis:circle", "te:ds": "text-emphasis:disc", "te:b": "text-emphasis:before", "te:a": "text-emphasis:after", "teh": "text-height", "teh:a": "text-height:auto", "teh:f": "text-height:font-size", "teh:t": "text-height:text-size", "teh:m": "text-height:max-size", "ti": "text-indent", "ti:-": "text-indent:-9999px", "tj": "text-justify", "tj:a": "text-justify:auto", "tj:iw": "text-justify:inter-word", "tj:ii": "text-justify:inter-ideograph", "tj:ic": "text-justify:inter-cluster", "tj:d": "text-justify:distribute", "tj:k": "text-justify:kashida", "tj:t": "text-justify:tibetan", "tol": "text-outline", "tol+": "text-outline:0 0 #000", "tol:n": "text-outline:none", "tr": "text-replace", "tr:n": "text-replace:none", "tt": "text-transform", "tt:n": "text-transform:none", "tt:c": "text-transform:capitalize", "tt:u": "text-transform:uppercase", "tt:l": "text-transform:lowercase", "tw": "text-wrap", "tw:n": "text-wrap:normal", "tw:no": "text-wrap:none", "tw:u": "text-wrap:unrestricted", "tw:s": "text-wrap:suppress", "tsh": "text-shadow", "tsh+": "text-shadow:0 0 0 #000", "tsh:n": "text-shadow:none", "lh": "line-height", "lts": "letter-spacing", "whs": "white-space", "whs:n": "white-space:normal", "whs:p": "white-space:pre", "whs:nw": "white-space:nowrap", "whs:pw": "white-space:pre-wrap", "whs:pl": "white-space:pre-line", "whsc": "white-space-collapse", "whsc:n": "white-space-collapse:normal", "whsc:k": "white-space-collapse:keep-all", "whsc:l": "white-space-collapse:loose", "whsc:bs": "white-space-collapse:break-strict", "whsc:ba": "white-space-collapse:break-all", "wob": "word-break", "wob:n": "word-break:normal", "wob:k": "word-break:keep-all", "wob:l": "word-break:loose", "wob:bs": "word-break:break-strict", "wob:ba": "word-break:break-all", "wos": "word-spacing", "wow": "word-wrap", "wow:nm": "word-wrap:normal", "wow:n": "word-wrap:none", "wow:u": "word-wrap:unrestricted", "wow:s": "word-wrap:suppress", // Background "bg": "background", "bg+": "background:#fff url() 0 0 no-repeat", "bg:n": "background:none", "bgc": "background-color:#fff", "bgc:t": "background-color:transparent", "bgi": "background-image:url()", "bgi:n": "background-image:none", "bgr": "background-repeat", "bgr:r": "background-repeat:repeat", "bgr:n": "background-repeat:no-repeat", "bgr:x": "background-repeat:repeat-x", "bgr:y": "background-repeat:repeat-y", "bga": "background-attachment", "bga:f": "background-attachment:fixed", "bga:s": "background-attachment:scroll", "bgp": "background-position:0 0", "bgpx": "background-position-x", "bgpy": "background-position-y", "bgbk": "background-break", "bgbk:bb": "background-break:bounding-box", "bgbk:eb": "background-break:each-box", "bgbk:c": "background-break:continuous", "bgcp": "background-clip", "bgcp:bb": "background-clip:border-box", "bgcp:pb": "background-clip:padding-box", "bgcp:cb": "background-clip:content-box", "bgcp:nc": "background-clip:no-clip", "bgo": "background-origin", "bgo:pb": "background-origin:padding-box", "bgo:bb": "background-origin:border-box", "bgo:cb": "background-origin:content-box", "bgz": "background-size", "bgz:a": "background-size:auto", "bgz:ct": "background-size:contain", "bgz:cv": "background-size:cover", // Color "col": "color:#000", "op": "opacity", "hsl": "hsl(359,100%,100%)", "hsla": "hsla(359,100%,100%,0.5)", "rgb": "rgb(255,255,255)", "rgba": "rgba(255,255,255,0.5)", // Generated Content "ct": "content", "ct:n": "content:normal", "ct:oq": "content:open-quote", "ct:noq": "content:no-open-quote", "ct:cq": "content:close-quote", "ct:ncq": "content:no-close-quote", "ct:a": "content:attr()", "ct:c": "content:counter()", "ct:cs": "content:counters()", "quo": "quotes", "q:n": "quotes:none", "q:ru": "quotes:'\00AB' '\00BB' '\201E' '\201C'", "q:en": "quotes:'\201C' '\201D' '\2018' '\2019'", "coi": "counter-increment", "cor": "counter-reset", // Outline "out": "outline", "o:n": "outline:none", "oo": "outline-offset", "ow": "outline-width", "os": "outline-style", "oc": "outline-color:#000", "oc:i": "outline-color:invert", // Table "tbl": "table-layout", "tbl:a": "table-layout:auto", "tbl:f": "table-layout:fixed", "cps": "caption-side", "cps:t": "caption-side:top", "cps:b": "caption-side:bottom", "ec": "empty-cells", "ec:s": "empty-cells:show", "ec:h": "empty-cells:hide", // Border "bd": "border", "bd+": "border:1px solid #000", "bd:n": "border:none", "bdbk": "border-break", "bdbk:c": "border-break:close", "bdcl": "border-collapse", "bdcl:c": "border-collapse:collapse", "bdcl:s": "border-collapse:separate", "bdc": "border-color:#000", "bdi": "border-image:url()", "bdi:n": "border-image:none", "bdti": "border-top-image:url()", "bdti:n": "border-top-image:none", "bdri": "border-right-image:url()", "bdri:n": "border-right-image:none", "bdbi": "border-bottom-image:url()", "bdbi:n": "border-bottom-image:none", "bdli": "border-left-image:url()", "bdli:n": "border-left-image:none", "bdci": "border-corner-image:url()", "bdci:n": "border-corner-image:none", "bdci:c": "border-corner-image:continue", "bdtli": "border-top-left-image:url()", "bdtli:n": "border-top-left-image:none", "bdtli:c": "border-top-left-image:continue", "bdtri": "border-top-right-image:url()", "bdtri:n": "border-top-right-image:none", "bdtri:c": "border-top-right-image:continue", "bdbri": "border-bottom-right-image:url()", "bdbri:n": "border-bottom-right-image:none", "bdbri:c": "border-bottom-right-image:continue", "bdbli": "border-bottom-left-image:url()", "bdbli:n": "border-bottom-left-image:none", "bdbli:c": "border-bottom-left-image:continue", "bdf": "border-fit", "bdf:c": "border-fit:clip", "bdf:r": "border-fit:repeat", "bdf:sc": "border-fit:scale", "bdf:st": "border-fit:stretch", "bdf:ow": "border-fit:overwrite", "bdf:of": "border-fit:overflow", "bdf:sp": "border-fit:space", "bdlt": "border-length", "bdlt:a": "border-length:auto", "bdsp": "border-spacing", "bds": "border-style", "bds:n": "border-style:none", "bds:h": "border-style:hidden", "bds:dt": "border-style:dotted", "bds:ds": "border-style:dashed", "bds:s": "border-style:solid", "bds:db": "border-style:double", "bds:dd": "border-style:dot-dash", "bds:ddd": "border-style:dot-dot-dash", "bds:w": "border-style:wave", "bds:g": "border-style:groove", "bds:r": "border-style:ridge", "bds:i": "border-style:inset", "bds:o": "border-style:outset", "bdw": "border-width", "bdt": "border-top", "bdt+": "border-top:1px solid #000", "bdt:n": "border-top:none", "bdtw": "border-top-width", "bdts": "border-top-style", "bdts:n": "border-top-style:none", "bdtc": "border-top-color:#000", "bdr": "border-right", "bdr+": "border-right:1px solid #000", "bdr:n": "border-right:none", "bdrw": "border-right-width", "bdrs": "border-right-style", "bdrs:n": "border-right-style:none", "bdrc": "border-right-color:#000", "bdb": "border-bottom", "bdb+": "border-bottom:1px solid #000", "bdb:n": "border-bottom:none", "bdbw": "border-bottom-width", "bdbs": "border-bottom-style", "bdbs:n": "border-bottom-style:none", "bdbc": "border-bottom-color:#000", "bdl": "border-left", "bdl+": "border-left:1px solid #000", "bdl:n": "border-left:none", "bdlw": "border-left-width", "bdls": "border-left-style", "bdls:n": "border-left-style:none", "bdlc": "border-left-color:#000", "bdrsa": "border-radius", "bdtrrs": "border-top-right-radius", "bdtlrs": "border-top-left-radius", "bdbrrs": "border-bottom-right-radius", "bdblrs": "border-bottom-left-radius", // Lists "lis": "list-style", "lis:n": "list-style:none", "lisp": "list-style-position", "lisp:i": "list-style-position:inside", "lisp:o": "list-style-position:outside", "list": "list-style-type", "list:n": "list-style-type:none", "list:d": "list-style-type:disc", "list:c": "list-style-type:circle", "list:s": "list-style-type:square", "list:dc": "list-style-type:decimal", "list:dclz": "list-style-type:decimal-leading-zero", "list:lr": "list-style-type:lower-roman", "list:ur": "list-style-type:upper-roman", "lisi": "list-style-image", "lisi:n": "list-style-image:none", // Print "pgbb": "page-break-before", "pgbb:au": "page-break-before:auto", "pgbb:al": "page-break-before:always", "pgbb:l": "page-break-before:left", "pgbb:r": "page-break-before:right", "pgbi": "page-break-inside", "pgbi:au": "page-break-inside:auto", "pgbi:av": "page-break-inside:avoid", "pgba": "page-break-after", "pgba:au": "page-break-after:auto", "pgba:al": "page-break-after:always", "pgba:l": "page-break-after:left", "pgba:r": "page-break-after:right", "orp": "orphans", "widows": "widows", // Others "ipt": "!important", "ffa": "@font-family {<br>&nbsp;&nbsp;font-family:;<br>&nbsp;&nbsp;src:url();<br>}", "ffa+": "@font-family {<br>&nbsp;&nbsp;font-family: 'FontName';<br>&nbsp;&nbsp;src: url('FileName.eot');<br>&nbsp;&nbsp;src: url('FileName.eot?#iefix') format('embedded-opentype'),<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;url('FileName.woff') format('woff'),<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;url('FileName.ttf') format('truetype'),<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;url('FileName.svg#FontName') format('svg');<br>&nbsp;&nbsp;font-style: normal;<br>&nbsp;&nbsp;font-weight: normal;<br>}", "imp": "@import url()", "mp": "@media print {}", "bg:ie": "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='x.png',sizingMethod='crop')", "op:ie": "filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=100)", "op:ms": "-ms-filter:'progid:DXImageTransform.Microsoft.Alpha(Opacity=100)'", "trf": "transform", "trf:r": "transform:rotate(90deg)", "trf:sc": "transform:scale(x,y)", "trf:scx": "transform:scaleX(x)", "trf:scy": "transform:scaleY(y)", "trf:skx": "transform:skewX(90deg)", "trf:sky": "transform:skewY(90deg)", "trf:t": "transform:translate(x,y)", "trf:tx": "transform:translateX(x)", "trf:ty": "transform:translateY(y)", "trs": "transition", "trsde": "transition-delay", "trsdu": "transition-duration", "trsp": "transition-property", "trstf": "transition-timing-function", "ani": "animation", "ann": "animation-name", "adu": "animation-duration", "atf": "animation-timing-function", "ade": "animation-delay", "aic": "animation-iteration-count", "adi": "animation-direction", "aps": "animation-play-state", "key": "@keyframes {}", "ms": "@media screen and () {}", "in": "inherit", "tra": "transparent", "beh": "behavior:url()", "cha": "@charset''", // Pseudo Class "ac": " :active{}", "ac:a": "&:active{}", "af": " :after{}", "af:a": "&:after{}", "be": " :before{}", "be:a": "&:before{}", "ch": " :checked{}", "ch:a": "&:checked{}", "dsa": " :disabled{}<i>[da]</i>", "dsa:a": "&:disabled{}<i>[da:a]</i>", "en": " :enabled{}", "en:a": "&:enabled{}", "fc": " :first-child{}", "fc:a": "&:first-child{}", "fle": " :first-letter{}", "fle:a": "&:first-letter{}", "fli": " :first-line{}", "fli:a": "&:first-line{}", "foc": " :focus{}", "foc:a": "&:focus{}", "ho": " :hover{}", "ho:a": "&:hover{}", "ln": " :lang(){}", "ln:a": "&:lang(){}", "lc": " :last-child{}", "lc:a": "&:last-child{}", // "li": " :link{}", // "li:a": "&:link{}", "nc": " :nth-child(){}", "nc:a": "&:nth-child(){}", "vit": " :visited{}", "vit:a": "&:visited{}", "tgt": " :target{}", "tgt:a": "&:target{}", "fot": " :first-of-type{}", "fot:a": "&:first-of-type{}", "lot": " :last-of-type{}", "lot:a": "&:last-of-type{}", "not": " :nth-of-type(){}", "not:a": "&:nth-of-type(){}", // Scss & Sass "ext": "@extend", "inc": "@include", "mix": "@mixin", "ieh": "ie-hex-str()" }; } o.helpers.units = function(v, def) { if(!v.toString().match(/[%|in|cm|mm|em|ex|pt|pc|px|deg|ms|s]/)) return v + (def || '%'); else return v; } var extend = require("./helpers/extend"), fs = require('fs'), path = require('path') var walk = function(dir) { return walkClientSide(); var results = []; var list = fs.readdirSync(dir); for(var i=0; i<list.length; i++) { var file = dir + '/' + list[i]; var stat = fs.statSync(file); if (stat && stat.isDirectory()) { results = results.concat(walk(file)); } else { results.push(file); } } return results; }; o.index = { absurd: null, init: function(decoration) { if(typeof decoration != 'undefined') { this.absurd = decoration; } // getting atoms and molecules var files = walk(__dirname + "/lib/"), self = this; for(var i=0; i<files.length; i++) { var file = path.basename(files[i]); (function(m) { var module = require(m); self.absurd.plugin(file.replace(".js", ""), function(absurd, value) { return module(value); }); })(files[i]); } // converting snippets to plugins var snippets = require(__dirname + "/helpers/snippets")(); for(var atom in snippets) { atom = atom.split(":"); (function(pluginName) { self.absurd.plugin(pluginName, function(absurd, value, prefixes) { if(prefixes === false) { prefixes = ''; } var s, r = {}; if(s = snippets[pluginName + ':' + value]) { s = s.split(':'); r[prefixes + s[0]] = s[1] || ''; } else if(s = snippets[pluginName]){ r[prefixes + s] = value; } return r; }); })(atom.shift()); } return this; } } o.lib.atoms.atoms = function(value) { var toObj = function(value, r) { value = value.replace(/( )?:( )?/, ':').split(':'); r = r || {}; r[value[0]] = value[1] || ''; return r; } var processArr = function(value) { var r = {}; for(var i=0; i<value.length; i++) { toObj(value[i], r); } return r; } if(typeof value == 'string') { return processArr(value.replace(/( )?\/( )?/g, '/').split('/')); } else if(typeof value == 'object') { if(!(value instanceof Array)) { return value; } else { return processArr(value); } } } /*! Animate.css - http://daneden.me/animate Licensed under the MIT license Copyright (c) 2013 Daniel Eden 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. */ o.lib.molecules.animate = function(value) { var r = {}; r['-wmso-animation-name'] = ''; r['-wmso-animation-duration'] = '1s', name = ''; if(typeof value === 'string') { r['-wmso-animation-name'] = value; } else if(typeof value === 'object') { if(value instanceof Array) { if(value.length === 1) { r['-wmso-animation-name'] = value[0]; } else if(value.length === 2) { r = { keyframes: { name: value[0], frames: value[1] } }; } else { value = r = {}; } } else { r['-wmso-animation-name'] = value.name; value.duration ? r['-wmso-animation-duration'] = value.duration : ''; value.fillMode ? r['-wmso-animation-fill-mode'] = value.fillMode : ''; value.timingFunction ? r['-wmso-animation-timing-function'] = value.timingFunction : ''; value.iterationCount ? r['-wmso-animation-iteration-count'] = value.iterationCount : ''; value.delay ? r['-wmso-animation-delay'] = value.delay : ''; value.direction ? r['-wmso-animation-direction'] = value.direction : ''; value.playState ? r['-wmso-animation-play-state'] = value.playState : ''; if(value.frames) { r.keyframes = { name: value.name, frames: value.frames } } } } switch(r['-wmso-animation-name']) { case "blink": r.keyframes = { name: "blink", frames: { "0%, 100%": { transparent: 0 }, "50%": { transparent: 1 } } } break; case "bounce": r.keyframes = { name: "bounce", frames: { "0%, 20%, 50%, 80%, 100%": { "-wmso-transform": "translateY(0)" }, "40%": { "-wmso-transform": "translateY(-30px)" }, "60%": { "-wmso-transform": "translateY(-15px)" } } } break; case "flash": r.keyframes = { name: "flash", frames: { "0%, 50%, 100%": { "opacity": "1" }, "25%, 75%": { "opacity": "0" } } } break; case "pulse": r.keyframes = { name: "pulse", frames: { "0%": { "-wmso-transform": "scale(1)" }, "50%": { "-wmso-transform": "scale(1.1)" }, "100%": { "-wmso-transform": "scale(1)" } } } break; case "shake": r.keyframes = { name: "shake", frames: { "0%, 100%": { "-wmso-transform": "translateX(0)" }, "10%, 30%, 50%, 70%, 90%": { "-wmso-transform": "translateX(-10px)" }, "20%, 40%, 60%, 80%": { "-wmso-transform": "translateX(10px)" } } } break; case "swing": r.keyframes = { name: "swing", frames: { "20%": { "-wmso-transform": "rotate(15deg)" }, "40%": { "-wmso-transform": "rotate(-10deg)" }, "60%": { "-wmso-transform": "rotate(5deg)" }, "80%": { "-wmso-transform": "rotate(-5deg)" }, "100%": { "-wmso-transform": "rotate(0deg)" } } } break; case "tada": r.keyframes = { name: "tada", frames: { "0%": { "-wmso-transform": "scale(1)" }, "10%, 20%": { "-wmso-transform": "scale(0.9) rotate(-3deg)" }, "30%, 50%, 70%, 90%": { "-wmso-transform": "scale(1.1) rotate(3deg)" }, "40%, 60%, 80%": { "-wmso-transform": "scale(1.1) rotate(-3deg)" }, "100%": { "-wmso-transform": "scale(1) rotate(0)" } } } break; case "wobble": r.keyframes = { name: "wobble", frames: { "0%": { "-wmso-transform": "translateX(0%)" }, "15%": { "-wmso-transform": "translateX(-25%) rotate(-5deg)" }, "30%": { "-wmso-transform": "translateX(20%) rotate(3deg)" }, "45%": { "-wmso-transform": "translateX(-15%) rotate(-3deg)" }, "60%": { "-wmso-transform": "translateX(10%) rotate(2deg)" }, "75%": { "-wmso-transform": "translateX(-5%) rotate(-1deg)" }, "100%": { "-wmso-transform": "translateX(0%)" } } } break; case "bounceIn": r.keyframes = { name: "bounceIn", frames: { "0%": { "opacity": "0", "-wmso-transform": "scale(.3)" }, "50%": { "opacity": "1", "-wmso-transform": "scale(1.05)" }, "70%": { "-wmso-transform": "scale(.9)" }, "100%": { "-wmso-transform": "scale(1)" } } } break; case "bounceInDown": r.keyframes = { name: "bounceInDown", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateY(-2000px)" }, "60%": { "opacity": "1", "-wmso-transform": "translateY(30px)" }, "80%": { "-wmso-transform": "translateY(-10px)" }, "100%": { "-wmso-transform": "translateY(0)" } } } break; case "bounceInLeft": r.keyframes = { name: "bounceInLeft", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateX(-2000px)" }, "60%": { "opacity": "1", "-wmso-transform": "translateX(30px)" }, "80%": { "-wmso-transform": "translateX(-10px)" }, "100%": { "-wmso-transform": "translateX(0)" } } } break; case "bounceInRight": r.keyframes = { name: "bounceInRight", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateX(2000px)" }, "60%": { "opacity": "1", "-wmso-transform": "translateX(-30px)" }, "80%": { "-wmso-transform": "translateX(10px)" }, "100%": { "-wmso-transform": "translateX(0)" } } } break; case "bounceInUp": r.keyframes = { name: "bounceInUp", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateY(2000px)" }, "60%": { "opacity": "1", "-wmso-transform": "translateY(-30px)" }, "80%": { "-wmso-transform": "translateY(10px)" }, "100%": { "-wmso-transform": "translateY(0)" } } } break; case "bounceOut": r.keyframes = { name: "bounceOut", frames: { "0%": { "-wmso-transform": "scale(1)" }, "25%": { "-wmso-transform": "scale(.95)" }, "50%": { "opacity": "1", "-wmso-transform": "scale(1.1)" }, "100%": { "opacity": "0", "-wmso-transform": "scale(.3)" } } } break; case "bounceOutDown": r.keyframes = { name: "bounceOutDown", frames: { "0%": { "-wmso-transform": "translateY(0)" }, "20%": { "opacity": "1", "-wmso-transform": "translateY(-20px)" }, "100%": { "opacity": "0", "-wmso-transform": "translateY(2000px)" } } } break; case "bounceOutLeft": r.keyframes = { name: "bounceOutLeft", frames: { "0%": { "-wmso-transform": "translateX(0)" }, "20%": { "opacity": "1", "-wmso-transform": "translateX(20px)" }, "100%": { "opacity": "0", "-wmso-transform": "translateX(-2000px)" } } } break; case "bounceOutRight": r.keyframes = { name: "bounceOutRight", frames: { "0%": { "-wmso-transform": "translateX(0)" }, "20%": { "opacity": "1", "-wmso-transform": "translateX(-20px)" }, "100%": { "opacity": "0", "-wmso-transform": "translateX(2000px)" } } } break; case "bounceOutUp": r.keyframes = { name: "bounceOutUp", frames: { "0%": { "-wmso-transform": "translateY(0)" }, "20%": { "opacity": "1", "-wmso-transform": "translateY(20px)" }, "100%": { "opacity": "0", "-wmso-transform": "translateY(-2000px)" } } } break; case "fadeIn": r.keyframes = { name: "fadeIn", frames: { "0%": { "opacity": "0" }, "100%": { "opacity": "1" } } } break; case "fadeInDown": r.keyframes = { name: "fadeInDown", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateY(-20px)" }, "100%": { "opacity": "1", "-wmso-transform": "translateY(0)" } } } break; case "fadeInDownBig": r.keyframes = { name: "fadeInDownBig", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateY(-2000px)" }, "100%": { "opacity": "1", "-wmso-transform": "translateY(0)" } } } break; case "fadeInLeft": r.keyframes = { name: "fadeInLeft", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateX(-20px)" }, "100%": { "opacity": "1", "-wmso-transform": "translateX(0)" } } } break; case "fadeInLeftBig": r.keyframes = { name: "fadeInLeftBig", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateX(-2000px)" }, "100%": { "opacity": "1", "-wmso-transform": "translateX(0)" } } } break; case "fadeInRight": r.keyframes = { name: "fadeInRight", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateX(20px)" }, "100%": { "opacity": "1", "-wmso-transform": "translateX(0)" } } } break; case "fadeInRightBig": r.keyframes = { name: "fadeInRightBig", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateX(2000px)" }, "100%": { "opacity": "1", "-wmso-transform": "translateX(0)" } } } break; case "fadeInUp": r.keyframes = { name: "fadeInUp", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateY(20px)" }, "100%": { "opacity": "1", "-wmso-transform": "translateY(0)" } } } break; case "fadeInUpBig": r.keyframes = { name: "fadeInUpBig", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateY(2000px)" }, "100%": { "opacity": "1", "-wmso-transform": "translateY(0)" } } } break; case "fadeOut": r.keyframes = { name: "fadeOut", frames: { "0%": { "opacity": "1" }, "100%": { "opacity": "0" } } } break; case "fadeOutDown": r.keyframes = { name: "fadeOutDown", frames: { "0%": { "opacity": "1", "-wmso-transform": "translateY(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateY(20px)" } } } break; case "fadeOutDownBig": r.keyframes = { name: "fadeOutDownBig", frames: { "0%": { "opacity": "1", "-wmso-transform": "translateY(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateY(2000px)" } } } break; case "fadeOutLeft": r.keyframes = { name: "fadeOutLeft", frames: { "0%": { "opacity": "1", "-wmso-transform": "translateX(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateX(-20px)" } } } break; case "fadeOutLeftBig": r.keyframes = { name: "fadeOutLeftBig", frames: { "0%": { "opacity": "1", "-wmso-transform": "translateX(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateX(-2000px)" } } } break; case "fadeOutRight": r.keyframes = { name: "fadeOutRight", frames: { "0%": { "opacity": "1", "-wmso-transform": "translateX(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateX(20px)" } } } break; case "fadeOutRightBig": r.keyframes = { name: "fadeOutRightBig", frames: { "0%": { "opacity": "1", "-wmso-transform": "translateX(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateX(2000px)" } } } break; case "fadeOutUp": r.keyframes = { name: "fadeOutUp", frames: { "0%": { "opacity": "1", "-wmso-transform": "translateY(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateY(-20px)" } } } break; case "fadeOutUpBig": r.keyframes = { name: "fadeOutUpBig", frames: { "0%": { "opacity": "1", "-wmso-transform": "translateY(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateY(-2000px)" } } } break; case "flip": r.keyframes = { name: "flip", frames: { "0%": { "-wmso-transform": "perspective(400px) translateZ(0) rotateY(0) scale(1)", "animation-timing-function": "ease-out" }, "40%": { "-wmso-transform": "perspective(400px) translateZ(150px) rotateY(170deg) scale(1)", "animation-timing-function": "ease-out" }, "50%": { "-wmso-transform": "perspective(400px) translateZ(150px) rotateY(190deg) scale(1)", "animation-timing-function": "ease-in" }, "80%": { "-wmso-transform": "perspective(400px) translateZ(0) rotateY(360deg) scale(.95)", "animation-timing-function": "ease-in" }, "100%": { "-wmso-transform": "perspective(400px) translateZ(0) rotateY(360deg) scale(1)", "animation-timing-function": "ease-in" } } } break; case "flipInX": r.keyframes = { name: "flipInX", frames: { "0%": { "-wmso-transform": "perspective(400px) rotateX(90deg)", "opacity": "0" }, "40%": { "-wmso-transform": "perspective(400px) rotateX(-10deg)" }, "70%": { "-wmso-transform": "perspective(400px) rotateX(10deg)" }, "100%": { "-wmso-transform": "perspective(400px) rotateX(0deg)", "opacity": "1" } } } break; case "flipInY": r.keyframes = { name: "flipInY", frames: { "0%": { "-wmso-transform": "perspective(400px) rotateY(90deg)", "opacity": "0" }, "40%": { "-wmso-transform": "perspective(400px) rotateY(-10deg)" }, "70%": { "-wmso-transform": "perspective(400px) rotateY(10deg)" }, "100%": { "-wmso-transform": "perspective(400px) rotateY(0deg)", "opacity": "1" } } } break; case "flipOutX": r.keyframes = { name: "flipOutX", frames: { "0%": { "-wmso-transform": "perspective(400px) rotateX(0deg)", "opacity": "1" }, "100%": { "-wmso-transform": "perspective(400px) rotateX(90deg)", "opacity": "0" } } } break; case "flipOutY": r.keyframes = { name: "flipOutY", frames: { "0%": { "-wmso-transform": "perspective(400px) rotateY(0deg)", "opacity": "1" }, "100%": { "-wmso-transform": "perspective(400px) rotateY(90deg)", "opacity": "0" } } } break; case "lightSpeedIn": r.keyframes = { name: "lightSpeedIn", frames: { "0%": { "-wmso-transform": "translateX(100%) skewX(-30deg)", "opacity": "0" }, "60%": { "-wmso-transform": "translateX(-20%) skewX(30deg)", "opacity": "1" }, "80%": { "-wmso-transform": "translateX(0%) skewX(-15deg)", "opacity": "1" }, "100%": { "-wmso-transform": "translateX(0%) skewX(0deg)", "opacity": "1" } } } break; case "lightSpeedOut": r.keyframes = { name: "lightSpeedOut", frames: { "0%": { "-wmso-transform": "translateX(0%) skewX(0deg)", "opacity": "1" }, "100%": { "-wmso-transform": "translateX(100%) skewX(-30deg)", "opacity": "0" } } } break; case "rotateIn": r.keyframes = { name: "rotateIn", frames: { "0%": { "transform-origin": "center center", "-wmso-transform": "rotate(-200deg)", "opacity": "0" }, "100%": { "transform-origin": "center center", "-wmso-transform": "rotate(0)", "opacity": "1" } } } break; case "rotateInDownLeft": r.keyframes = { name: "rotateInDownLeft", frames: { "0%": { "transform-origin": "left bottom", "-wmso-transform": "rotate(-90deg)", "opacity": "0" }, "100%": { "transform-origin": "left bottom", "-wmso-transform": "rotate(0)", "opacity": "1" } } } break; case "rotateInDownRight": r.keyframes = { name: "rotateInDownRight", frames: { "0%": { "transform-origin": "right bottom", "-wmso-transform": "rotate(90deg)", "opacity": "0" }, "100%": { "transform-origin": "right bottom", "-wmso-transform": "rotate(0)", "opacity": "1" } } } break; case "rotateInUpLeft": r.keyframes = { name: "rotateInUpLeft", frames: { "0%": { "transform-origin": "left bottom", "-wmso-transform": "rotate(90deg)", "opacity": "0" }, "100%": { "transform-origin": "left bottom", "-wmso-transform": "rotate(0)", "opacity": "1" } } } break; case "rotateInUpRight": r.keyframes = { name: "rotateInUpRight", frames: { "0%": { "transform-origin": "right bottom", "-wmso-transform": "rotate(-90deg)", "opacity": "0" }, "100%": { "transform-origin": "right bottom", "-wmso-transform": "rotate(0)", "opacity": "1" } } } break; case "rotateOut": r.keyframes = { name: "rotateOut", frames: { "0%": { "transform-origin": "center center", "-wmso-transform": "rotate(0)", "opacity": "1" }, "100%": { "transform-origin": "center center", "-wmso-transform": "rotate(200deg)", "opacity": "0" } } } break; case "rotateOutDownLeft": r.keyframes = { name: "rotateOutDownLeft", frames: { "0%": { "transform-origin": "left bottom", "-wmso-transform": "rotate(0)", "opacity": "1" }, "100%": { "transform-origin": "left bottom", "-wmso-transform": "rotate(90deg)", "opacity": "0" } } } break; case "rotateOutDownRight": r.keyframes = { name: "rotateOutDownRight", frames: { "0%": { "transform-origin": "right bottom", "-wmso-transform": "rotate(0)", "opacity": "1" }, "100%": { "transform-origin": "right bottom", "-wmso-transform": "rotate(-90deg)", "opacity": "0" } } } break; case "rotateOutUpLeft": r.keyframes = { name: "rotateOutUpLeft", frames: { "0%": { "transform-origin": "left bottom", "-wmso-transform": "rotate(0)", "opacity": "1" }, "100%": { "transform-origin": "left bottom", "-wmso-transform": "rotate(-90deg)", "opacity": "0" } } } break; case "rotateOutUpRight": r.keyframes = { name: "rotateOutUpRight", frames: { "0%": { "transform-origin": "right bottom", "-wmso-transform": "rotate(0)", "opacity": "1" }, "100%": { "transform-origin": "right bottom", "-wmso-transform": "rotate(90deg)", "opacity": "0" } } } break; case "slideInDown": r.keyframes = { name: "slideInDown", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateY(-2000px)" }, "100%": { "-wmso-transform": "translateY(0)" } } } break; case "slideInLeft": r.keyframes = { name: "slideInLeft", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateX(-2000px)" }, "100%": { "-wmso-transform": "translateX(0)" } } } break; case "slideInRight": r.keyframes = { name: "slideInRight", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateX(2000px)" }, "100%": { "-wmso-transform": "translateX(0)" } } } break; case "slideOutLeft": r.keyframes = { name: "slideOutLeft", frames: { "0%": { "-wmso-transform": "translateX(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateX(-2000px)" } } } break; case "slideOutRight": r.keyframes = { name: "slideOutRight", frames: { "0%": { "-wmso-transform": "translateX(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateX(2000px)" } } } break; case "slideOutUp": r.keyframes = { name: "slideOutUp", frames: { "0%": { "-wmso-transform": "translateY(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateY(-2000px)" } } } break; case "hinge": r.keyframes = { name: "hinge", frames: { "0%": { "-wmso-transform": "rotate(0)", "transform-origin": "top left", "animation-timing-function": "ease-in-out" }, "20%, 60%": { "-wmso-transform": "rotate(80deg)", "transform-origin": "top left", "animation-timing-function": "ease-in-out" }, "40%": { "-wmso-transform": "rotate(60deg)", "transform-origin": "top left", "animation-timing-function": "ease-in-out" }, "80%": { "-wmso-transform": "rotate(60deg) translateY(0)", "opacity": "1", "transform-origin": "top left", "animation-timing-function": "ease-in-out" }, "100%": { "-wmso-transform": "translateY(700px)", "opacity": "0" } } } break; case "rollIn": r.keyframes = { name: "rollIn", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateX(-100%) rotate(-120deg)" }, "100%": { "opacity": "1", "-wmso-transform": "translateX(0px) rotate(0deg)" } } } break; case "rollOut": r.keyframes = { name: "rollOut", frames: { "0%": { "opacity": "1", "-wmso-transform": "translateX(0px) rotate(0deg)" }, "100%": { "opacity": "0", "-wmso-transform": "translateX(100%) rotate(120deg)" } } } break; } return r; } o.lib.molecules.blur = function(value) { return { '-wms-filter': 'blur(' + value + 'px)' } } o.lib.molecules.brightness = function(value) { return { '-wms-filter': 'brightness(' + value + ')' } } o.lib.molecules.calc = function(value) { var args = require('../../helpers/args')(value), r = {}; r['LhProperty'] = '0'; r['~~1~~' + args[0]] = '-webkit-calc(' + args[1] + ')'; r['~~2~~' + args[0]] = '-moz-calc(' + args[1] + ')'; r['~~3~~' + args[0]] = 'calc(' + args[1] + ')'; return r; } o.lib.molecules.cf = function(value) { var r = {}, clearing = { content: '" "', display: 'table', clear: 'both' }; switch(value) { case 'before': r['&:before'] = clearing; break; case 'after': r['&:after'] = clearing; break; default: r['&:before'] = clearing; r['&:after'] = clearing; break; } return r; } o.lib.molecules.contrast = function(value) { return { '-wms-filter': 'contrast(' + value + '%)' } } o.lib.molecules.dropshadow = function(value) { return { '-wms-filter': 'drop-shadow(' + value + ')' } } var getMSColor = function(color) { color = color.toString().replace('#', ''); if(color.length == 3) { var tmp = ''; for(var i=0; i<color.length; i++) { tmp += color[i] + color[i]; } color = tmp; } return '#FF' + color.toUpperCase(); } o.lib.molecules.gradient = function(value) { var r = {}, args = require('../../helpers/args')(value); switch(typeof value) { case 'string': var deg = args[args.length-1]; if(deg.indexOf('deg') > 0) { deg = parseInt(args.pop().replace('deg', '')); } else { deg = 0; } var numOfStops = args.length, stepsPercents = Math.floor(100 / (numOfStops-1)).toFixed(2), gradientValue = [], msGradientType = (deg >= 45 && deg <= 135) || (deg >= 225 && deg <= 315) ? 1 : 0, msStartColor = msGradientType === 0 ? getMSColor(args[args.length-1]) : getMSColor(args[0]), msEndColor = msGradientType === 0 ? getMSColor(args[0]) : getMSColor(args[args.length-1]); for(var i=0; i<numOfStops; i++) { if(args[i].indexOf('%') > 0) { gradientValue.push(args[i]); } else { gradientValue.push(args[i] + ' ' + (i*stepsPercents) + '%'); } } gradientValue = deg + 'deg, ' + gradientValue.join(', '); return [ { 'background': '-webkit-linear-gradient(' + gradientValue + ')' }, { '~~1~~background': '-moz-linear-gradient(' + gradientValue + ')' }, { '~~2~~background': '-ms-linear-gradient(' + gradientValue + ')' }, { '~~3~~background': '-o-linear-gradient(' + gradientValue + ')' }, { '~~4~~background': 'linear-gradient(' + gradientValue + ')' }, { 'filter': 'progid:DXImageTransform.Microsoft.gradient(startColorstr=\'' + msStartColor + '\', endColorstr=\'' + msEndColor + '\',GradientType=' + msGradientType + ')' }, { 'MsFilter': 'progid:DXImageTransform.Microsoft.gradient(startColorstr=\'' + msStartColor + '\',endColorstr=\'' + msEndColor + '\',GradientType=' + msGradientType + ')' } ] break; } return {}; } o.lib.molecules.grid = function(value) { var args = require('../../helpers/args')(value); if(args.length == 2) { var res = { cf: 'both' } res[args[1]] = { fl: 'l', '-mw-bxz': 'bb', wid: (100 / parseInt(args[0])).toFixed(2) + '%' } return res; } else { return {}; } } o.lib.molecules.invert = function(value) { return { '-wms-filter': 'invert(' + value + '%)' } } o.lib.molecules.moveto = function(value) { var units = require('../../helpers/units'), args = require('../../helpers/args')(value), x = units(!args[0] || args[0] == '' ? 0 : args[0], 'px'), y = units(!args[1] || args[1] == '' ? 0 : args[1], 'px'), z = units(!args[2] || args[2] == '' ? 0 : args[2], 'px'); if(args.length == 2) { return {"-ws-trf": ">translate(" + x + "," + y + ")"}; } else if(args.length == 3) { return {"-ws-trf": ">translate3d(" + x + "," + y + "," + z + ")"}; } } o.lib.molecules.rotateto = function(value) { var units = require('../../helpers/units'), args = require('../../helpers/args')(value); if(args.length == 1) { return {"-ws-trf": ">rotate(" + units(args[0], 'deg') + ")"}; } } o.lib.molecules.saturate = function(value) { return { '-wms-filter': 'saturate(' + value + 'deg)' } } o.lib.molecules.scaleto = function(value) { var args = require('../../helpers/args')(value), x = !args[0] || args[0] == '' ? 0 : args[0], y = !args[1] || args[1] == '' ? 0 : args[1]; if(args.length == 2) { return {"-ws-trf": ">scale(" + x + "," + y + ")"}; } } o.lib.molecules.sepia = function(value) { return { '-wms-filter': 'sepia(' + value + '%)' } } o.lib.molecules.size = function(value) { var units = require('../../helpers/units'), args = require('../../helpers/args')(value), r = {}; if(args.length == 2) { if(args[0] != '') { r.width = units(args[0]); } if(args[1] != '') { r.height = units(args[1]); } return r; } else { return { width: units(args[0]), height: units(args[0]) } } } o.lib.molecules.transparent = function(value) { var args = require('../../helpers/args')(value), r = {}; value = parseFloat(value); r['-s-filter'] = 'progid:DXImageTransform.Microsoft.Alpha(Opacity=' + (value * 100) + ')'; r['filter'] = 'alpha(opacity=' + (value * 100) + ')'; r['-m-opacity'] = value; r['opacity'] = value; r['KhtmlOpacity'] = value; return r; }; return o.index; })(window);
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; const u = undefined; function plural(n) { return 5; } global.ng.common.locales['yo-bj'] = [ 'yo-BJ', [['Àárɔ̀', 'Ɔ̀sán'], u, u], u, [ ['À', 'A', 'Ì', 'Ɔ', 'Ɔ', 'Ɛ', 'À'], ['Àìk', 'Aj', 'Ìsɛ́g', 'Ɔjɔ́r', 'Ɔjɔ́b', 'Ɛt', 'Àbám'], ['Ɔjɔ́ Àìkú', 'Ɔjɔ́ Ajé', 'Ɔjɔ́ Ìsɛ́gun', 'Ɔjɔ́rú', 'Ɔjɔ́bɔ', 'Ɔjɔ́ Ɛtì', 'Ɔjɔ́ Àbámɛ́ta'], ['Àìkú', 'Ajé', 'Ìsɛ́gun', 'Ɔjɔ́rú', 'Ɔjɔ́bɔ', 'Ɛtì', 'Àbámɛ́ta'] ], [ ['À', 'A', 'Ì', 'Ɔ', 'Ɔ', 'Ɛ', 'À'], ['Àìk', 'Aj', 'Ìsɛ́g', 'Ɔjɔ́r', 'Ɔjɔ́b', 'Ɛt', 'Àbám'], ['Àìkú', 'Ajé', 'Ìsɛ́gun', 'Ɔjɔ́rú', 'Ɔjɔ́bɔ', 'Ɛtì', 'Àbámɛ́ta'], u ], [ ['S', 'È', 'Ɛ', 'Ì', 'Ɛ̀', 'Ò', 'A', 'Ò', 'O', 'Ɔ̀', 'B', 'Ɔ̀'], ['Shɛ́r', 'Èrèl', 'Ɛrɛ̀n', 'Ìgb', 'Ɛ̀bi', 'Òkú', 'Agɛ', 'Ògú', 'Owe', 'Ɔ̀wà', 'Bél', 'Ɔ̀pɛ'], [ 'Oshù Shɛ́rɛ́', 'Oshù Èrèlè', 'Oshù Ɛrɛ̀nà', 'Oshù Ìgbé', 'Oshù Ɛ̀bibi', 'Oshù Òkúdu', 'Oshù Agɛmɔ', 'Oshù Ògún', 'Oshù Owewe', 'Oshù Ɔ̀wàrà', 'Oshù Bélú', 'Oshù Ɔ̀pɛ̀' ] ], [ ['S', 'È', 'Ɛ', 'Ì', 'Ɛ̀', 'Ò', 'A', 'Ò', 'O', 'Ɔ̀', 'B', 'Ɔ̀'], ['Shɛ́', 'Èr', 'Ɛr', 'Ìg', 'Ɛ̀b', 'Òk', 'Ag', 'Òg', 'Ow', 'Ɔ̀w', 'Bé', 'Ɔ̀p'], [ 'Shɛ́rɛ́', 'Èrèlè', 'Ɛrɛ̀nà', 'Ìgbé', 'Ɛ̀bibi', 'Òkúdu', 'Agɛmɔ', 'Ògún', 'Owewe', 'Ɔ̀wàrà', 'Bélú', 'Ɔ̀pɛ̀' ] ], [['BCE', 'AD'], u, ['Saju Kristi', 'Lehin Kristi']], 1, [6, 0], ['d/M/y', 'd MM y', 'd MMM y', 'EEEE, d MMM y'], ['H:m', 'H:m:s', 'H:mm:ss z', 'HH:mm:ss zzzz'], ['{1} {0}', u, u, u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], 'XOF', 'CFA', 'Faransi ti Orílɛ́ède BIKEAO', {'JPY': ['JP¥', '¥'], 'NGN': ['₦'], 'RUB': ['₽']}, 'ltr', plural, [] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
// const hash = window.location.hash; const queryParamsHelper = (() => { function getQueryParamsFromHash(hash) { hash = String(hash); let params = {}; if (hash.indexOf('?') < 0) { return params; } const inputParams = hash.split('?')[1].split('&'); inputParams.forEach(param => { const split = param.split('='); params[split[0]] = split[1]; }); return params; } return { getQueryParamsFromHash }; })();
for(let i = 0; i < length; i++) { console.log('foo'); }
var Api = require('../../../lib/api.js'); module.exports = { setUp: function (callback) { callback(); }, 'cssProperty assertion passed' : function(test) { var assertionFn = require('../../../lib/selenium/assertions/cssProperty.js'); var client = { options : {}, api : { getCssProperty : function(cssSelector, property, callback) { test.equals(cssSelector, '.test_element'); test.equals(property, 'display'); callback({ value : 'none' }); } }, assertion : function(passed, result, expected, msg, abortOnFailure) { test.equals(passed, true); test.equals(result, 'none'); test.equals(expected, 'none'); test.equals(msg, 'Testing if element <.test_element> has css property "display: none".'); test.equals(abortOnFailure, true); delete assertionFn; test.done(); } }; Api.init(client); var m = Api.createAssertion('cssProperty', assertionFn, true, client); m._commandFn('.test_element', 'display', 'none'); }, 'cssProperty assertion failed' : function(test) { var assertionFn = require('../../../lib/selenium/assertions/cssProperty.js'); var client = { options : {}, api : { getCssProperty : function(cssSelector, property, callback) { test.equals(cssSelector, '.test_element'); test.equals(property, 'display'); callback({ value : 'block' }); } }, assertion : function(passed, result, expected, msg, abortOnFailure) { test.equals(passed, false); test.equals(result, 'block'); test.equals(expected, 'none'); test.equals(abortOnFailure, true); delete assertionFn; test.done(); } }; Api.init(client); var m = Api.createAssertion('cssProperty', assertionFn, true, client); m._commandFn('.test_element', 'display', 'none'); }, 'cssProperty assertion not found' : function(test) { var assertionFn = require('../../../lib/selenium/assertions/cssProperty.js'); var client = { options : {}, api : { getCssProperty : function(cssSelector, property, callback) { callback({ status : -1 }); } }, assertion : function(passed, result, expected, msg, abortOnFailure) { test.equals(passed, false); test.equals(result, null); test.equals(expected, 'none'); test.equals(msg, 'Testing if element <.test_element> has css property display. Element or attribute could not be located.'); test.equals(abortOnFailure, true); delete assertionFn; test.done(); } }; Api.init(client); var m = Api.createAssertion('cssProperty', assertionFn, true, client); m._commandFn('.test_element', 'display', 'none'); }, tearDown : function(callback) { callback(); } }
/*! * ui-grid - v4.6.1 - 2018-07-04 * Copyright (c) 2018 ; License: MIT */ /** * Translated by: R. Salarmehr * M. Hosseynzade * Using Vajje.com online dictionary. */ (function () { angular.module('ui.grid').config(['$provide', function ($provide) { $provide.decorator('i18nService', ['$delegate', function ($delegate) { $delegate.add('fa', { aggregate: { label: 'قلم' }, groupPanel: { description: 'عنوان یک ستون را بگیر و به گروهی از آن ستون رها کن.' }, search: { placeholder: 'جستجو...', showingItems: 'نمایش اقلام:', selectedItems: 'قلم\u200cهای انتخاب شده:', totalItems: 'مجموع اقلام:', size: 'اندازه\u200cی صفحه:', first: 'اولین صفحه', next: 'صفحه\u200cی\u200cبعدی', previous: 'صفحه\u200cی\u200c قبلی', last: 'آخرین صفحه' }, menu: { text: 'ستون\u200cهای انتخابی:' }, sort: { ascending: 'ترتیب صعودی', descending: 'ترتیب نزولی', remove: 'حذف مرتب کردن' }, column: { hide: 'پنهان\u200cکردن ستون' }, aggregation: { count: 'تعداد: ', sum: 'مجموع: ', avg: 'میانگین: ', min: 'کمترین: ', max: 'بیشترین: ' }, pinning: { pinLeft: 'پین کردن سمت چپ', pinRight: 'پین کردن سمت راست', unpin: 'حذف پین' }, gridMenu: { columns: 'ستون\u200cها:', importerTitle: 'وارد کردن فایل', exporterAllAsCsv: 'خروجی تمام داده\u200cها در فایل csv', exporterVisibleAsCsv: 'خروجی داده\u200cهای قابل مشاهده در فایل csv', exporterSelectedAsCsv: 'خروجی داده\u200cهای انتخاب\u200cشده در فایل csv', exporterAllAsPdf: 'خروجی تمام داده\u200cها در فایل pdf', exporterVisibleAsPdf: 'خروجی داده\u200cهای قابل مشاهده در فایل pdf', exporterSelectedAsPdf: 'خروجی داده\u200cهای انتخاب\u200cشده در فایل pdf', clearAllFilters: 'پاک کردن تمام فیلتر' }, importer: { noHeaders: 'نام ستون قابل استخراج نیست. آیا فایل عنوان دارد؟', noObjects: 'اشیا قابل استخراج نیستند. آیا به جز عنوان\u200cها در فایل داده وجود دارد؟', invalidCsv: 'فایل قابل پردازش نیست. آیا فرمت csv معتبر است؟', invalidJson: 'فایل قابل پردازش نیست. آیا فرمت json معتبر است؟', jsonNotArray: 'فایل json وارد شده باید حاوی آرایه باشد. عملیات ساقط شد.' }, pagination: { sizes: 'اقلام در هر صفحه', totalItems: 'اقلام', of: 'از' }, grouping: { group: 'گروه\u200cبندی', ungroup: 'حذف گروه\u200cبندی', aggregate_count: 'Agg: تعداد', aggregate_sum: 'Agg: جمع', aggregate_max: 'Agg: بیشینه', aggregate_min: 'Agg: کمینه', aggregate_avg: 'Agg: میانگین', aggregate_remove: 'Agg: حذف' } }); return $delegate; }]); }]); })();
var debug = require('debug')('keystone:core:routes'); /** * Adds bindings for the keystone routes * * ####Example: * * var app = express(); * app.use(...); // middleware, routes, etc. should come before keystone is initialised * keystone.routes(app); * * @param {Express()} app * @api public */ function routes(app) { this.app = app; var keystone = this; // ensure keystone nav has been initialised if (!this.nav) { debug('setting up nav'); this.nav = this.initNav(); } // Cache compiled view templates if we are in Production mode this.set('view cache', this.get('env') === 'production'); // Session API // TODO: this should respect keystone auth options app.get('/keystone/api/session', require('../../admin/api/session/get')); app.post('/keystone/api/session/signin', require('../../admin/api/session/signin')); app.post('/keystone/api/session/signout', require('../../admin/api/session/signout')); // Bind auth middleware (generic or custom) to /keystone* routes, allowing // access to the generic signin page if generic auth is used if (this.get('auth') === true) { if (!this.get('signout url')) { this.set('signout url', '/keystone/signout'); } if (!this.get('signin url')) { this.set('signin url', '/keystone/signin'); } if (!this.nativeApp || !this.get('session')) { app.all('/keystone*', this.session.persist); } app.all('/keystone/signin', require('../../admin/routes/signin')); app.all('/keystone/signout', require('../../admin/routes/signout')); app.all('/keystone*', this.session.keystoneAuth); } else if ('function' === typeof this.get('auth')) { app.all('/keystone*', this.get('auth')); } function initList(respectHiddenOption) { return function(req, res, next) { req.list = keystone.list(req.params.list); if (!req.list || (respectHiddenOption && req.list.get('hidden'))) { debug('could not find list ', req.params.list); req.flash('error', 'List ' + req.params.list + ' could not be found.'); return res.redirect('/keystone'); } debug('getting list ', req.params.list); next(); }; } debug('setting keystone Admin Route'); app.all('/keystone', require('../../admin/routes/home')); // Email test routes if (this.get('email tests')) { debug('setting email test routes'); this.bindEmailTestRoutes(app, this.get('email tests')); } // Cloudinary API for selecting an existing image / upload a new image if (keystone.get('cloudinary config')) { debug('setting cloudinary api'); app.get('/keystone/api/cloudinary/get', require('../../admin/api/cloudinary').get); app.get('/keystone/api/cloudinary/autocomplete', require('../../admin/api/cloudinary').autocomplete); app.post('/keystone/api/cloudinary/upload', require('../../admin/api/cloudinary').upload); } // S3 API for uploading a new image if (keystone.get('s3 config')) { debug('setting S3 api'); app.post('/keystone/api/s3/upload', require('../../admin/api/s3').upload); } // Init API request helpers app.use('/keystone/api', function(req, res, next) { res.apiError = function(key, err) { var statusCode = 500; if (key === 404) { statusCode = 404; key = null; key = 'not found'; } if (!key) { key = 'unknown error'; } if (!err) { err = 'API Error'; } if (typeof err === 'object' && err.message) { err = err.message; } res.status(statusCode); res.json({ err: err, key: key }); }; next(); }); // Generic Lists API app.all('/keystone/api/counts', require('../../admin/api/counts')); app.all('/keystone/api/:list/:action(autocomplete|order|create|fetch)', initList(), require('../../admin/api/list')); app.post('/keystone/api/:list/delete', initList(), require('../../admin/api/list/delete')); app.get('/keystone/api/:list', initList(), require('../../admin/api/list/get')); app.get('/keystone/api/:list/:id', initList(), require('../../admin/api/item/get')); app.post('/keystone/api/:list/:id/delete', initList(), require('../../admin/api/item/delete')); app.all('/keystone/download/:list', initList(), require('../../admin/api/download')); // Admin-UI API app.all('/keystone/:list/:page([0-9]{1,5})?', initList(true), require('../../admin/routes/list')); app.all('/keystone/:list/:item', initList(true), require('../../admin/routes/item')); return this; } module.exports = routes;
import Ember from 'ember'; import Torii from 'ember-simple-auth/authenticators/torii'; import raw from 'ic-ajax'; const { RSVP } = Ember; const { service } = Ember.inject; export default Torii.extend({ torii: service('torii'), authenticate() { return new RSVP.Promise((resolve, reject) => { this._super(...arguments).then((data) => { raw({ url: '/token', type: 'POST', dataType: 'json', data: { 'grant_type': 'facebook_auth_code', 'auth_code': data.authorizationCode } }).then((response) => { resolve({ // jscs:disable requireCamelCaseOrUpperCaseIdentifiers access_token: response.access_token, // jscs:enable requireCamelCaseOrUpperCaseIdentifiers provider: data.provider }); }, reject); }, reject); }); } });
/* vim: set expandtab sw=4 ts=4 sts=4: */ /** * Functions used in the export tab * */ /** * Disables the "Dump some row(s)" sub-options */ function disable_dump_some_rows_sub_options() { $("label[for='limit_to']").fadeTo('fast', 0.4); $("label[for='limit_from']").fadeTo('fast', 0.4); $("input[type='text'][name='limit_to']").prop('disabled', 'disabled'); $("input[type='text'][name='limit_from']").prop('disabled', 'disabled'); } /** * Enables the "Dump some row(s)" sub-options */ function enable_dump_some_rows_sub_options() { $("label[for='limit_to']").fadeTo('fast', 1); $("label[for='limit_from']").fadeTo('fast', 1); $("input[type='text'][name='limit_to']").prop('disabled', ''); $("input[type='text'][name='limit_from']").prop('disabled', ''); } /** * Return template data as a json object * * @returns template data */ function getTemplateData() { var $form = $('form[name="dump"]'); var blacklist = ['token', 'server', 'db', 'table', 'single_table', 'export_type', 'export_method', 'sql_query', 'template_id']; var obj = {}; var arr = $form.serializeArray(); $.each(arr, function () { if ($.inArray(this.name, blacklist) < 0) { if (obj[this.name] !== undefined) { if (! obj[this.name].push) { obj[this.name] = [obj[this.name]]; } obj[this.name].push(this.value || ''); } else { obj[this.name] = this.value || ''; } } }); // include unchecked checboxes (which are ignored by serializeArray()) with null // to uncheck them when loading the template $form.find('input[type="checkbox"]:not(:checked)').each(function () { if (obj[this.name] === undefined) { obj[this.name] = null; } }); // include empty multiselects $form.find('select').each(function () { if ($(this).find('option:selected').length == 0) { obj[this.name] = []; } }); return obj; } /** * Create a template with selected options * * @param name name of the template */ function createTemplate(name) { var templateData = getTemplateData(); var params = { ajax_request : true, token : PMA_commonParams.get('token'), server : PMA_commonParams.get('server'), db : PMA_commonParams.get('db'), table : PMA_commonParams.get('table'), exportType : $('input[name="export_type"]').val(), templateAction : 'create', templateName : name, templateData : JSON.stringify(templateData) }; PMA_ajaxShowMessage(); $.post('tbl_export.php', params, function (response) { if (response.success === true) { $('#templateName').val(''); $('#template').html(response.data); $("#template").find("option").each(function() { if ($(this).text() == name) { $(this).prop('selected', true); } }); PMA_ajaxShowMessage(PMA_messages.strTemplateCreated); } else { PMA_ajaxShowMessage(response.error, false); } }); } /** * Loads a template * * @param id ID of the template to load */ function loadTemplate(id) { var params = { ajax_request : true, token : PMA_commonParams.get('token'), server : PMA_commonParams.get('server'), db : PMA_commonParams.get('db'), table : PMA_commonParams.get('table'), exportType : $('input[name="export_type"]').val(), templateAction : 'load', templateId : id, }; PMA_ajaxShowMessage(); $.post('tbl_export.php', params, function (response) { if (response.success === true) { var $form = $('form[name="dump"]'); var options = JSON.parse(response.data); $.each(options, function (key, value) { var $element = $form.find('[name="' + key + '"]'); if ($element.length) { if (($element.is('input') && $element.attr('type') == 'checkbox') && value === null) { $element.prop('checked', false); } else { if (($element.is('input') && $element.attr('type') == 'checkbox') || ($element.is('input') && $element.attr('type') == 'radio') || ($element.is('select') && $element.attr('multiple') == 'multiple')) { if (! value.push) { value = [value]; } } $element.val(value); } $element.trigger('change'); } }); $('input[name="template_id"]').val(id); PMA_ajaxShowMessage(PMA_messages.strTemplateLoaded); } else { PMA_ajaxShowMessage(response.error, false); } }); } /** * Updates an existing template with current options * * @param id ID of the template to update */ function updateTemplate(id) { var templateData = getTemplateData(); var params = { ajax_request : true, token : PMA_commonParams.get('token'), server : PMA_commonParams.get('server'), db : PMA_commonParams.get('db'), table : PMA_commonParams.get('table'), exportType : $('input[name="export_type"]').val(), templateAction : 'update', templateId : id, templateData : JSON.stringify(templateData) }; PMA_ajaxShowMessage(); $.post('tbl_export.php', params, function (response) { if (response.success === true) { PMA_ajaxShowMessage(PMA_messages.strTemplateUpdated); } else { PMA_ajaxShowMessage(response.error, false); } }); } /** * Delete a template * * @param id ID of the template to delete */ function deleteTemplate(id) { var params = { ajax_request : true, token : PMA_commonParams.get('token'), server : PMA_commonParams.get('server'), db : PMA_commonParams.get('db'), table : PMA_commonParams.get('table'), exportType : $('input[name="export_type"]').val(), templateAction : 'delete', templateId : id, }; PMA_ajaxShowMessage(); $.post('tbl_export.php', params, function (response) { if (response.success === true) { $('#template').find('option[value="' + id + '"]').remove(); PMA_ajaxShowMessage(PMA_messages.strTemplateDeleted); } else { PMA_ajaxShowMessage(response.error, false); } }); } /** * Unbind all event handlers before tearing down a page */ AJAX.registerTeardown('export.js', function () { $("#plugins").unbind('change'); $("input[type='radio'][name='sql_structure_or_data']").unbind('change'); $("input[type='radio'][name$='_structure_or_data']").off('change'); $("input[type='radio'][name='output_format']").unbind('change'); $("#checkbox_sql_include_comments").unbind('change'); $("input[type='radio'][name='quick_or_custom']").unbind('change'); $("input[type='radio'][name='allrows']").unbind('change'); $('#btn_alias_config').off('click'); $('.alias_remove').off('click'); $('#db_alias_button').off('click'); $('#table_alias_button').off('click'); $('#column_alias_button').off('click'); $('input[name="table_select[]"]').off('change'); $('input[name="table_structure[]"]').off('change'); $('input[name="table_data[]"]').off('change'); $('#table_structure_all').off('change'); $('#table_data_all').off('change'); $('input[name="createTemplate"]').off('click'); $('select[name="template"]').off('change'); $('input[name="updateTemplate"]').off('click'); $('input[name="deleteTemplate"]').off('click'); }); AJAX.registerOnload('export.js', function () { /** * Export template handling code */ // create a new template $('input[name="createTemplate"]').on('click', function (e) { e.preventDefault(); var name = $('input[name="templateName"]').val(); if (name.length) { createTemplate(name); } }); // load an existing template $('select[name="template"]').on('change', function (e) { e.preventDefault(); var id = $(this).val(); if (id.length) { loadTemplate(id); } }); // udpate an existing template with new criteria $('input[name="updateTemplate"]').on('click', function (e) { e.preventDefault(); var id = $('select[name="template"]').val(); if (id.length) { updateTemplate(id); } }); // delete an existing template $('input[name="deleteTemplate"]').on('click', function (e) { e.preventDefault(); var id = $('select[name="template"]').val(); if (id.length) { deleteTemplate(id); } }); /** * Toggles the hiding and showing of each plugin's options * according to the currently selected plugin from the dropdown list */ $("#plugins").change(function () { $("#format_specific_opts").find("div.format_specific_options").hide(); var selected_plugin_name = $("#plugins").find("option:selected").val(); $("#" + selected_plugin_name + "_options").show(); }); /** * Toggles the enabling and disabling of the SQL plugin's comment options that apply only when exporting structure */ $("input[type='radio'][name='sql_structure_or_data']").change(function () { var comments_are_present = $("#checkbox_sql_include_comments").prop("checked"); var show = $("input[type='radio'][name='sql_structure_or_data']:checked").val(); if (show == 'data') { // disable the SQL comment options if (comments_are_present) { $("#checkbox_sql_dates").prop('disabled', true).parent().fadeTo('fast', 0.4); } $("#checkbox_sql_relation").prop('disabled', true).parent().fadeTo('fast', 0.4); $("#checkbox_sql_mime").prop('disabled', true).parent().fadeTo('fast', 0.4); } else { // enable the SQL comment options if (comments_are_present) { $("#checkbox_sql_dates").prop('disabled', false).parent().fadeTo('fast', 1); } $("#checkbox_sql_relation").prop('disabled', false).parent().fadeTo('fast', 1); $("#checkbox_sql_mime").prop('disabled', false).parent().fadeTo('fast', 1); } if (show == 'structure') { $('#checkbox_sql_auto_increment').prop('disabled', true).parent().fadeTo('fast', 0.4); } else { $("#checkbox_sql_auto_increment").prop('disabled', false).parent().fadeTo('fast', 1); } }); // For separate-file exports only ZIP compression is allowed $('input[type="checkbox"][name="as_separate_files"]').change(function(){ if ($(this).is(':checked')) { $('#compression').val('zip'); } }); $('#compression').change(function(){ if ($('option:selected').val() !== 'zip') { $('input[type="checkbox"][name="as_separate_files"]').prop('checked', false); } }); }); function setup_table_structure_or_data() { if ($("input[name='export_type']").val() != 'database') { return; } var pluginName = $("#plugins").find("option:selected").val(); var formElemName = pluginName + "_structure_or_data"; var force_structure_or_data = !($("input[name='" + formElemName + "_default']").length); if (force_structure_or_data === true) { $('input[name="structure_or_data_forced"]').val(1); $('.export_structure input[type="checkbox"], .export_data input[type="checkbox"]') .prop('disabled', true); $('.export_structure, .export_data').fadeTo('fast', 0.4); } else { $('input[name="structure_or_data_forced"]').val(0); $('.export_structure input[type="checkbox"], .export_data input[type="checkbox"]') .prop('disabled', false); $('.export_structure, .export_data').fadeTo('fast', 1); var structure_or_data = $('input[name="' + formElemName + '_default"]').val(); if (structure_or_data == 'structure') { $('.export_data input[type="checkbox"]') .prop('checked', false); } else if (structure_or_data == 'data') { $('.export_structure input[type="checkbox"]') .prop('checked', false); } if (structure_or_data == 'structure' || structure_or_data == 'structure_and_data') { if (!$('.export_structure input[type="checkbox"]:checked').length) { $('input[name="table_select[]"]:checked') .closest('tr') .find('.export_structure input[type="checkbox"]') .prop('checked', true); } } if (structure_or_data == 'data' || structure_or_data == 'structure_and_data') { if (!$('.export_data input[type="checkbox"]:checked').length) { $('input[name="table_select[]"]:checked') .closest('tr') .find('.export_data input[type="checkbox"]') .prop('checked', true); } } check_selected_tables(); check_table_select_all(); } } /** * Toggles the hiding and showing of plugin structure-specific and data-specific * options */ function toggle_structure_data_opts() { var pluginName = $("select#plugins").val(); var radioFormName = pluginName + "_structure_or_data"; var dataDiv = "#" + pluginName + "_data"; var structureDiv = "#" + pluginName + "_structure"; var show = $("input[type='radio'][name='" + radioFormName + "']:checked").val(); if (show == 'data') { $(dataDiv).slideDown('slow'); $(structureDiv).slideUp('slow'); } else { $(structureDiv).slideDown('slow'); if (show == 'structure') { $(dataDiv).slideUp('slow'); } else { $(dataDiv).slideDown('slow'); } } } /** * Toggles the disabling of the "save to file" options */ function toggle_save_to_file() { var $ulSaveAsfile = $("#ul_save_asfile"); if (!$("#radio_dump_asfile").prop("checked")) { $ulSaveAsfile.find("> li").fadeTo('fast', 0.4); $ulSaveAsfile.find("> li > input").prop('disabled', true); $ulSaveAsfile.find("> li > select").prop('disabled', true); } else { $ulSaveAsfile.find("> li").fadeTo('fast', 1); $ulSaveAsfile.find("> li > input").prop('disabled', false); $ulSaveAsfile.find("> li > select").prop('disabled', false); } } AJAX.registerOnload('export.js', function () { toggle_save_to_file(); $("input[type='radio'][name='output_format']").change(toggle_save_to_file); }); /** * For SQL plugin, toggles the disabling of the "display comments" options */ function toggle_sql_include_comments() { $("#checkbox_sql_include_comments").change(function () { var $ulIncludeComments = $("#ul_include_comments"); if (!$("#checkbox_sql_include_comments").prop("checked")) { $ulIncludeComments.find("> li").fadeTo('fast', 0.4); $ulIncludeComments.find("> li > input").prop('disabled', true); } else { // If structure is not being exported, the comment options for structure should not be enabled if ($("#radio_sql_structure_or_data_data").prop("checked")) { $("#text_sql_header_comment").prop('disabled', false).parent("li").fadeTo('fast', 1); } else { $ulIncludeComments.find("> li").fadeTo('fast', 1); $ulIncludeComments.find("> li > input").prop('disabled', false); } } }); } function check_table_select_all() { var total = $('input[name="table_select[]"]').length; var str_checked = $('input[name="table_structure[]"]:checked').length; var data_checked = $('input[name="table_data[]"]:checked').length; var str_all = $('#table_structure_all'); var data_all = $('#table_data_all'); if (str_checked == total) { str_all .prop("indeterminate", false) .prop('checked', true); } else if (str_checked === 0) { str_all .prop("indeterminate", false) .prop('checked', false); } else { str_all .prop("indeterminate", true) .prop('checked', false); } if (data_checked == total) { data_all .prop("indeterminate", false) .prop('checked', true); } else if (data_checked === 0) { data_all .prop("indeterminate", false) .prop('checked', false); } else { data_all .prop("indeterminate", true) .prop('checked', false); } } function toggle_table_select_all_str() { var str_all = $('#table_structure_all').is(':checked'); if (str_all) { $('input[name="table_structure[]"]').prop('checked', true); } else { $('input[name="table_structure[]"]').prop('checked', false); } } function toggle_table_select_all_data() { var data_all = $('#table_data_all').is(':checked'); if (data_all) { $('input[name="table_data[]"]').prop('checked', true); } else { $('input[name="table_data[]"]').prop('checked', false); } } function check_selected_tables(argument) { $('.export_table_select tbody tr').each(function() { check_table_selected(this); }); } function check_table_selected(row) { var $row = $(row); var table_select = $row.find('input[name="table_select[]"]'); var str_check = $row.find('input[name="table_structure[]"]'); var data_check = $row.find('input[name="table_data[]"]'); var data = data_check.is(':checked:not(:disabled)'); var structure = str_check.is(':checked:not(:disabled)'); if (data && structure) { table_select.prop({checked: true, indeterminate: false}); $row.addClass('marked'); } else if (data || structure) { table_select.prop({checked: true, indeterminate: true}); $row.removeClass('marked'); } else { table_select.prop({checked: false, indeterminate: false}); $row.removeClass('marked'); } } function toggle_table_select(row) { var $row = $(row); var table_selected = $row.find('input[name="table_select[]"]').is(':checked'); if (table_selected) { $row.find('input[type="checkbox"]:not(:disabled)').prop('checked', true); $row.addClass('marked'); } else { $row.find('input[type="checkbox"]:not(:disabled)').prop('checked', false); $row.removeClass('marked'); } } function handleAddProcCheckbox() { if ($('#table_structure_all').is(':checked') === true && $('#table_data_all').is(':checked') === true ) { $('#checkbox_sql_procedure_function').prop('checked', true); } else { $('#checkbox_sql_procedure_function').prop('checked', false); } } AJAX.registerOnload('export.js', function () { /** * For SQL plugin, if "CREATE TABLE options" is checked/unchecked, check/uncheck each of its sub-options */ var $create = $("#checkbox_sql_create_table_statements"); var $create_options = $("#ul_create_table_statements").find("input"); $create.change(function () { $create_options.prop('checked', $(this).prop("checked")); }); $create_options.change(function () { if ($create_options.is(":checked")) { $create.prop('checked', true); } }); /** * Disables the view output as text option if the output must be saved as a file */ $("#plugins").change(function () { var active_plugin = $("#plugins").find("option:selected").val(); var force_file = $("#force_file_" + active_plugin).val(); if (force_file == "true") { if ($("#radio_dump_asfile").prop('checked') !== true) { $("#radio_dump_asfile").prop('checked', true); toggle_save_to_file(); } $("#radio_view_as_text").prop('disabled', true).parent().fadeTo('fast', 0.4); } else { $("#radio_view_as_text").prop('disabled', false).parent().fadeTo('fast', 1); } }); $("input[type='radio'][name$='_structure_or_data']").on('change', function () { toggle_structure_data_opts(); }); $('input[name="table_select[]"]').on('change', function() { toggle_table_select($(this).closest('tr')); check_table_select_all(); handleAddProcCheckbox(); }); $('input[name="table_structure[]"]').on('change', function() { check_table_selected($(this).closest('tr')); check_table_select_all(); handleAddProcCheckbox(); }); $('input[name="table_data[]"]').on('change', function() { check_table_selected($(this).closest('tr')); check_table_select_all(); handleAddProcCheckbox(); }); $('#table_structure_all').on('change', function() { toggle_table_select_all_str(); check_selected_tables(); handleAddProcCheckbox(); }); $('#table_data_all').on('change', function() { toggle_table_select_all_data(); check_selected_tables(); handleAddProcCheckbox(); }); if ($("input[name='export_type']").val() == 'database') { // Hide structure or data radio buttons $("input[type='radio'][name$='_structure_or_data']").each(function() { var $this = $(this); var name = $this.prop('name'); var val = $('input[name="' + name + '"]:checked').val(); var name_default = name + '_default'; if (!$('input[name="' + name_default + '"]').length) { $this .after( $('<input type="hidden" name="' + name_default + '" value="' + val + '" disabled>') ) .after( $('<input type="hidden" name="' + name + '" value="structure_and_data">') ); $this.parent().find('label').remove(); } else { $this.parent().remove(); } }); $("input[type='radio'][name$='_structure_or_data']").remove(); // Disable CREATE table checkbox for sql var createTableCheckbox = $('#checkbox_sql_create_table'); createTableCheckbox.prop('checked', true); var dummyCreateTable = $('#checkbox_sql_create_table') .clone() .removeAttr('id') .attr('type', 'hidden'); createTableCheckbox .prop('disabled', true) .after(dummyCreateTable) .parent() .fadeTo('fast', 0.4); setup_table_structure_or_data(); } /** * Handle force structure_or_data */ $("#plugins").change(setup_table_structure_or_data); }); /** * Toggles display of options when quick and custom export are selected */ function toggle_quick_or_custom() { if ($("input[name='quick_or_custom']").length === 0 // custom_no_form option || $("#radio_custom_export").prop("checked") // custom ) { $("#databases_and_tables").show(); $("#rows").show(); $("#output").show(); $("#format_specific_opts").show(); $("#output_quick_export").hide(); var selected_plugin_name = $("#plugins").find("option:selected").val(); $("#" + selected_plugin_name + "_options").show(); } else { // quick $("#databases_and_tables").hide(); $("#rows").hide(); $("#output").hide(); $("#format_specific_opts").hide(); $("#output_quick_export").show(); } } var time_out; function check_time_out(time_limit) { if (typeof time_limit === 'undefined' || time_limit === 0) { return true; } //margin of one second to avoid race condition to set/access session variable time_limit = time_limit + 1; var href = "export.php"; var params = { 'ajax_request' : true, 'token' : PMA_commonParams.get('token'), 'check_time_out' : true }; clearTimeout(time_out); time_out = setTimeout(function(){ $.get(href, params, function (data) { if (data.message === 'timeout') { PMA_ajaxShowMessage( '<div class="error">' + PMA_messages.strTimeOutError + '</div>', false ); } }); }, time_limit * 1000); } /** * Handler for Database/table alias select * * @param event object the event object * * @return void */ function aliasSelectHandler(event) { var sel = event.data.sel; var type = event.data.type; var inputId = $(this).val(); var $label = $(this).next('label'); $('input#' + $label.attr('for')).addClass('hide'); $('input#' + inputId).removeClass('hide'); $label.attr('for', inputId); $('#alias_modal ' + sel + '[id$=' + type + ']:visible').addClass('hide'); var $inputWrapper = $('#alias_modal ' + sel + '#' + inputId + type); $inputWrapper.removeClass('hide'); if (type === '_cols' && $inputWrapper.length > 0) { var outer = $inputWrapper[0].outerHTML; // Replace opening tags var regex = /<dummy_inp/gi; if (outer.match(regex)) { var newTag = outer.replace(regex, '<input'); // Replace closing tags regex = /<\/dummy_inp/gi; newTag = newTag.replace(regex, '</input'); // Assign replacement $inputWrapper.replaceWith(newTag); } } else if (type === '_tables') { $('.table_alias_select:visible').change(); } $("#alias_modal").dialog("option", "position", "center"); } /** * Handler for Alias dialog box * * @param event object the event object * * @return void */ function createAliasModal(event) { event.preventDefault(); var dlgButtons = {}; dlgButtons[PMA_messages.strSaveAndClose] = function() { $(this).dialog("close"); $('#alias_modal').parent().appendTo($('form[name="dump"]')); }; $('#alias_modal').dialog({ width: Math.min($(window).width() - 100, 700), maxHeight: $(window).height(), modal: true, dialogClass: "alias-dialog", buttons: dlgButtons, create: function() { $(this).css('maxHeight', $(window).height() - 150); var db = PMA_commonParams.get('db'); if (db) { var option = $('<option></option>'); option.text(db); option.attr('value', db); $('#db_alias_select').append(option).val(db).change(); } else { var params = { ajax_request : true, token : PMA_commonParams.get('token'), server : PMA_commonParams.get('server'), type: 'list-databases' }; $.post('ajax.php', params, function (response) { if (response.success === true) { $.each(response.databases, function (idx, value) { var option = $('<option></option>'); option.text(value); option.attr('value', value); $('#db_alias_select').append(option); }); } else { PMA_ajaxShowMessage(response.error, false); } }); } }, close: function() { var isEmpty = true; $(this).find('input[type="text"]').each(function() { // trim empty input fields on close if ($(this).val()) { isEmpty = false; } else { $(this).parents('tr').remove(); } }); // Toggle checkbox based on aliases $('input#btn_alias_config').prop('checked', !isEmpty); }, position: { my: "center top", at: "center top", of: window } }); } function aliasToggleRow(elm) { var inputs = elm.parents('tr').find('input,button'); if (elm.val()) { inputs.attr('disabled', false); } else { inputs.attr('disabled', true); } } function addAlias(type, name, field, value) { if (value === '') { return; } var row = $('#alias_data tfoot tr').clone(); row.find('th').text(type); row.find('td:first').text(name); row.find('input').attr('name', field); row.find('input').val(value); row.find('.alias_remove').on('click', function () { $(this).parents('tr').remove(); }); var matching = $('#alias_data [name="' + $.escapeSelector(field) + '"]'); if (matching.length > 0) { matching.parents('tr').remove(); } $('#alias_data tbody').append(row); } AJAX.registerOnload('export.js', function () { $("input[type='radio'][name='quick_or_custom']").change(toggle_quick_or_custom); $("#scroll_to_options_msg").hide(); $("#format_specific_opts").find("div.format_specific_options") .hide() .css({ "border": 0, "margin": 0, "padding": 0 }) .find("h3") .remove(); toggle_quick_or_custom(); toggle_structure_data_opts(); toggle_sql_include_comments(); check_table_select_all(); handleAddProcCheckbox(); /** * Initially disables the "Dump some row(s)" sub-options */ disable_dump_some_rows_sub_options(); /** * Disables the "Dump some row(s)" sub-options when it is not selected */ $("input[type='radio'][name='allrows']").change(function () { if ($("input[type='radio'][name='allrows']").prop("checked")) { enable_dump_some_rows_sub_options(); } else { disable_dump_some_rows_sub_options(); } }); // Open Alias Modal Dialog on click $('#btn_alias_config').on('click', createAliasModal); $('.alias_remove').on('click', function () { $(this).parents('tr').remove(); }); $('#db_alias_select').on('change', function () { aliasToggleRow($(this)); var db = $(this).val(); var table = PMA_commonParams.get('table'); if (table) { var option = $('<option></option>'); option.text(table); option.attr('value', table); $('#table_alias_select').append(option).val(table).change(); } else { var params = { ajax_request : true, token : PMA_commonParams.get('token'), server : PMA_commonParams.get('server'), db : $(this).val(), type: 'list-tables' }; $.post('ajax.php', params, function (response) { if (response.success === true) { $.each(response.tables, function (idx, value) { var option = $('<option></option>'); option.text(value); option.attr('value', value); $('#table_alias_select').append(option); }); } else { PMA_ajaxShowMessage(response.error, false); } }); } }); $('#table_alias_select').on('change', function () { aliasToggleRow($(this)); var params = { ajax_request : true, token : PMA_commonParams.get('token'), server : PMA_commonParams.get('server'), db : $('#db_alias_select').val(), table: $(this).val(), type: 'list-columns' }; $.post('ajax.php', params, function (response) { if (response.success === true) { $.each(response.columns, function (idx, value) { var option = $('<option></option>'); option.text(value); option.attr('value', value); $('#column_alias_select').append(option); }); } else { PMA_ajaxShowMessage(response.error, false); } }); }); $('#column_alias_select').on('change', function () { aliasToggleRow($(this)); }); $('#db_alias_button').on('click', function (e) { e.preventDefault(); var db = $('#db_alias_select').val(); addAlias( PMA_messages.strAliasDatabase, db, 'aliases[' + db + '][alias]', $('#db_alias_name').val() ); $('#db_alias_name').val(''); }); $('#table_alias_button').on('click', function (e) { e.preventDefault(); var db = $('#db_alias_select').val(); var table = $('#table_alias_select').val(); addAlias( PMA_messages.strAliasTable, db + '.' + table, 'aliases[' + db + '][tables][' + table + '][alias]', $('#table_alias_name').val() ); $('#table_alias_name').val(''); }); $('#column_alias_button').on('click', function (e) { e.preventDefault(); var db = $('#db_alias_select').val(); var table = $('#table_alias_select').val(); var column = $('#column_alias_select').val(); addAlias( PMA_messages.strAliasColumn, db + '.' + table + '.' + column, 'aliases[' + db + '][tables][' + table + '][colums][' + column + ']', $('#column_alias_name').val() ); $('#column_alias_name').val(''); }); });
/* globals isRtl */ this.menu = new class { constructor() { this.updateUnreadBars = _.throttle(() => { if (this.list == null) { return; } const listOffset = this.list.offset(); const listHeight = this.list.height(); let showTop = false; let showBottom = false; $('li.has-alert').each(function() { if ($(this).offset().top < listOffset.top - $(this).height()) { showTop = true; } if ($(this).offset().top > listOffset.top + listHeight) { return showBottom = true; } }); if (showTop === true) { $('.top-unread-rooms').removeClass('hidden'); } else { $('.top-unread-rooms').addClass('hidden'); } if (showBottom === true) { return $('.bottom-unread-rooms').removeClass('hidden'); } else { return $('.bottom-unread-rooms').addClass('hidden'); } }, 200); } init() { this.mainContent = $('.main-content'); this.list = $('.rooms-list'); Session.set('isMenuOpen', false); } isOpen() { return Session.get('isMenuOpen'); } open() { Session.set('isMenuOpen', true); this.mainContent && this.mainContent.css('transform', `translateX(${ isRtl(localStorage.getItem('userLanguage'))?'-':'' }260px)`); } close() { Session.set('isMenuOpen', false); this.mainContent && this.mainContent .css('transform', 'translateX(0)'); } toggle() { return this.isOpen() ? this.close() : this.open(); } };
import Ember from 'ember'; import PaginationMixin from 'ghost/mixins/pagination-controller'; import SettingsMenuMixin from 'ghost/mixins/settings-menu-controller'; import boundOneWay from 'ghost/utils/bound-one-way'; export default Ember.ArrayController.extend(PaginationMixin, SettingsMenuMixin, { tags: Ember.computed.alias('model'), activeTag: null, activeTagNameScratch: boundOneWay('activeTag.name'), activeTagSlugScratch: boundOneWay('activeTag.slug'), activeTagDescriptionScratch: boundOneWay('activeTag.description'), activeTagMetaTitleScratch: boundOneWay('activeTag.meta_title'), activeTagMetaDescriptionScratch: boundOneWay('activeTag.meta_description'), init: function (options) { options = options || {}; options.modelType = 'tag'; this._super(options); }, application: Ember.inject.controller(), config: Ember.inject.service(), notifications: Ember.inject.service(), showErrors: function (errors) { errors = Ember.isArray(errors) ? errors : [errors]; this.get('notifications').showErrors(errors); }, saveActiveTagProperty: function (propKey, newValue) { var activeTag = this.get('activeTag'), currentValue = activeTag.get(propKey), self = this; newValue = newValue.trim(); // Quit if there was no change if (newValue === currentValue) { return; } activeTag.set(propKey, newValue); this.get('notifications').closePassive(); activeTag.save().catch(function (errors) { self.showErrors(errors); }); }, seoTitle: Ember.computed('scratch', 'activeTagNameScratch', 'activeTagMetaTitleScratch', function () { var metaTitle = this.get('activeTagMetaTitleScratch') || ''; metaTitle = metaTitle.length > 0 ? metaTitle : this.get('activeTagNameScratch'); if (metaTitle && metaTitle.length > 70) { metaTitle = metaTitle.substring(0, 70).trim(); metaTitle = Ember.Handlebars.Utils.escapeExpression(metaTitle); metaTitle = Ember.String.htmlSafe(metaTitle + '&hellip;'); } return metaTitle; }), seoURL: Ember.computed('activeTagSlugScratch', function () { var blogUrl = this.get('config.blogUrl'), seoSlug = this.get('activeTagSlugScratch') ? this.get('activeTagSlugScratch') : '', seoURL = blogUrl + '/tag/' + seoSlug; // only append a slash to the URL if the slug exists if (seoSlug) { seoURL += '/'; } if (seoURL.length > 70) { seoURL = seoURL.substring(0, 70).trim(); seoURL = Ember.String.htmlSafe(seoURL + '&hellip;'); } return seoURL; }), seoDescription: Ember.computed('scratch', 'activeTagDescriptionScratch', 'activeTagMetaDescriptionScratch', function () { var metaDescription = this.get('activeTagMetaDescriptionScratch') || ''; metaDescription = metaDescription.length > 0 ? metaDescription : this.get('activeTagDescriptionScratch'); if (metaDescription && metaDescription.length > 156) { metaDescription = metaDescription.substring(0, 156).trim(); metaDescription = Ember.Handlebars.Utils.escapeExpression(metaDescription); metaDescription = Ember.String.htmlSafe(metaDescription + '&hellip;'); } return metaDescription; }), actions: { newTag: function () { this.set('activeTag', this.store.createRecord('tag', {post_count: 0})); this.send('openSettingsMenu'); }, editTag: function (tag) { this.set('activeTag', tag); this.send('openSettingsMenu'); }, saveActiveTagName: function (name) { this.saveActiveTagProperty('name', name); }, saveActiveTagSlug: function (slug) { this.saveActiveTagProperty('slug', slug); }, saveActiveTagDescription: function (description) { this.saveActiveTagProperty('description', description); }, saveActiveTagMetaTitle: function (metaTitle) { this.saveActiveTagProperty('meta_title', metaTitle); }, saveActiveTagMetaDescription: function (metaDescription) { this.saveActiveTagProperty('meta_description', metaDescription); }, setCoverImage: function (image) { this.saveActiveTagProperty('image', image); }, clearCoverImage: function () { this.saveActiveTagProperty('image', ''); }, closeNavMenu: function () { this.get('application').send('closeNavMenu'); } } });
define(['jquery','jqueryui/datepicker'], function (jQuery) { /* German initialisation for the jQuery UI date picker plugin. */ /* Written by Milian Wolff (mail@milianw.de). */ jQuery(function($){ $.datepicker.regional['de'] = { closeText: 'schließen', prevText: '&#x3c;zurück', nextText: 'Vor&#x3e;', currentText: 'heute', monthNames: ['Januar','Februar','März','April','Mai','Juni', 'Juli','August','September','Oktober','November','Dezember'], monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun', 'Jul','Aug','Sep','Okt','Nov','Dez'], dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'], dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'], dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'], weekHeader: 'Wo', dateFormat: 'dd.mm.yy', firstDay: 1, isRTL: false, showMonthAfterYear: false, yearSuffix: ''}; $.datepicker.setDefaults($.datepicker.regional['de']); }); });
/* Copyright (c) 2006-2015 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the 2-clause BSD license. * See license.txt in the OpenLayers distribution or repository for the * full text of the license. */ /** * @requires OpenLayers/Control.js * @requires OpenLayers/Lang.js * @requires OpenLayers/Rule.js * @requires OpenLayers/StyleMap.js * @requires OpenLayers/Layer/Vector.js */ /** * Class: OpenLayers.Control.Graticule * The Graticule displays a grid of latitude/longitude lines reprojected on * the map. * The grid is specified by a list of widths in degrees (with height the same as * the width). The grid height can be specified as a multiple of the width. * This allows making the grid more regular in specific regions of some * projections. The grid can also be specified by lists of both widths and * heights. This allows matching externally-defined grid systems. * * Inherits from: * - <OpenLayers.Control> * */ OpenLayers.Control.Graticule = OpenLayers.Class(OpenLayers.Control, { /** * APIProperty: autoActivate * {Boolean} Activate the control when it is added to a map. Default is * true. */ autoActivate: true, /** * APIProperty: intervals * {Array(Float)} A list of possible graticule widths in degrees. */ intervals: [90, 45, 30, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.01, 0.005, 0.002, 0.001 ], /** * APIProperty: intervalHeights * {Array(Float)} A list of possible graticule heights in degrees. * Length must match intervals array. * Default is null (same as widths). */ intervalHeights: null, /** * Property: intervalHeightFactor * {Number} Factor to compute graticule height from the width. * Can be used to match existing grid systems, or improve regularity of * grid. Default is 1. * Ignored if intervalHeights are set explicitly. */ intervalHeightFactor: 1, /** * APIProperty: displayInLayerSwitcher * {Boolean} Allows the Graticule control to be switched on and off by * LayerSwitcher control. Defaults is true. */ displayInLayerSwitcher: true, /** * APIProperty: visible * {Boolean} should the graticule be initially visible (default=true) */ visible: true, /** * APIProperty: numPoints * {Integer} The number of points to use in each graticule line. Higher * numbers result in a smoother curve for projected maps. * *Deprecated*. The number of points is now determined by adaptive * quantization. */ numPoints: 50, /** * APIProperty: targetSize * {Integer} The maximum size of the grid in pixels on the map */ targetSize: 200, /** * APIProperty: layerName * {String} The name to be displayed in the layer switcher, default is set * by {<OpenLayers.Lang>}. */ layerName: null, /** * APIProperty: labelled * {Boolean} Should the graticule lines be labelled?. default=true */ labelled: true, /** * APIProperty: labelFormat * {String} the format of the labels, default = 'dm'. See * <OpenLayers.Util.getFormattedLonLat> for other options. */ labelFormat: 'dm', /** * APIProperty: labelLonYOffset * {Integer} the offset of the longitude (X) label from the bottom of the * map. */ labelLonYOffset: 2, /** * APIProperty: labelLatXOffset * {Integer} the offset of the latitude (Y) label from the right of the map. */ labelLatXOffset: -2, /** * APIProperty: lineSymbolizer * {symbolizer} the symbolizer used to render lines */ lineSymbolizer: { strokeColor: "#333", strokeWidth: 1, strokeOpacity: 0.5 }, /** * APIProperty: labelSymbolizer * {symbolizer} the symbolizer used to render labels */ labelSymbolizer: null, /** * Property: gratLayer * {<OpenLayers.Layer.Vector>} vector layer used to draw the graticule on */ gratLayer: null, /** * Property: epsg4326Projection * {OpenLayers.Projection} */ epsg4326Projection: null, /** * Property: projection * {OpenLayers.Projection} The projection of the graticule. */ projection: null, /** * Property: projectionCenterLonLat * {OpenLayers.LonLat} The center of the projection's validity extent. */ projectionCenterLonLat: null, /** * Property: maxLat * {number} */ maxLat: Infinity, /** * Propety: maxLon * {number} */ maxLon: Infinity, /** * Property: minLat * {number} */ minLat: -Infinity, /** * Property: minLon * {number} */ minLon: -Infinity, /** * Property: meridians * {Array.<OpenLayers.Feature.Vector>} */ meridians: null, /** * Property. parallels * {Array.<OpenLayers.Feature.Vector>} */ parallels: null, /** * Constructor: OpenLayers.Control.Graticule * Create a new graticule control to display a grid of latitude longitude * lines. * * Parameters: * options - {Object} An optional object whose properties will be used * to extend the control. */ initialize: function(options) { options = options || {}; options.layerName = options.layerName || OpenLayers.i18n("Graticule"); OpenLayers.Control.prototype.initialize.apply(this, [options]); this.labelSymbolizer = { stroke: false, fill: false, label: "${label}", labelAlign: "${labelAlign}", labelXOffset: "${xOffset}", labelYOffset: "${yOffset}" }; this.epsg4326Projection = new OpenLayers.Projection('EPSG:4326'); this.parallels = []; this.meridians = []; }, /** * APIMethod: destroy */ destroy: function() { this.deactivate(); OpenLayers.Control.prototype.destroy.apply(this, arguments); if (this.gratLayer) { this.gratLayer.destroy(); this.gratLayer = null; } }, /** * Method: draw * * initializes the graticule layer and does the initial update * * Returns: * {DOMElement} */ draw: function() { OpenLayers.Control.prototype.draw.apply(this, arguments); if (!this.gratLayer) { var gratStyle = new OpenLayers.Style({}, { rules: [new OpenLayers.Rule({ 'symbolizer': { "Point": this.labelSymbolizer, "Line": this.lineSymbolizer } })] }); this.gratLayer = new OpenLayers.Layer.Vector(this.layerName, { styleMap: new OpenLayers.StyleMap({ 'default': gratStyle }), visibility: this.visible, displayInLayerSwitcher: this.displayInLayerSwitcher, // Prefer the canvas renderer to avoid coordinate range issues // with graticule lines renderers: ['Canvas', 'VML', 'SVG'] }); } return this.div; }, /** * APIMethod: activate */ activate: function() { if (OpenLayers.Control.prototype.activate.apply(this, arguments)) { this.map.addLayer(this.gratLayer); this.map.events.register('moveend', this, this.update); this.update(); return true; } else { return false; } }, /** * APIMethod: deactivate */ deactivate: function() { if (OpenLayers.Control.prototype.deactivate.apply(this, arguments)) { this.map.events.unregister('moveend', this, this.update); this.map.removeLayer(this.gratLayer); return true; } else { return false; } }, /** * Method: update * * calculates the grid to be displayed and actually draws it * * Returns: * {DOMElement} */ update: function() { var map = this.map; //wait for the map to be initialized before proceeding var extent = this.map.getExtent(); if (!extent) { return; } var center = map.getCenter(); var projection = map.getProjectionObject(); var resolution = map.getResolution(); var squaredTolerance = resolution * resolution / 4; var updateProjectionInfo = !this.projection || !this.projection.equals(projection); if (updateProjectionInfo) { this.updateProjectionInfo(projection); } this.createGraticule(extent, center, resolution, squaredTolerance); // Draw the lines this.gratLayer.destroyFeatures(); this.gratLayer.addFeatures(this.meridians); this.gratLayer.addFeatures(this.parallels); // Draw the labels if (this.labelled) { var left = new OpenLayers.Geometry.LineString([ new OpenLayers.Geometry.Point(extent.left, extent.bottom), new OpenLayers.Geometry.Point(extent.left, extent.top) ]); var top = new OpenLayers.Geometry.LineString([ new OpenLayers.Geometry.Point(extent.left, extent.top), new OpenLayers.Geometry.Point(extent.right, extent.top) ]); var labels = []; var i, ii, line, labelPoint, split, labelAlign; for (i = 0, ii = this.meridians.length; i < ii; ++i) { line = this.meridians[i]; labelPoint = line.attributes.labelPoint; labelAlign = 'cb'; // If there is no intersection with the bottom of the viewport, // intersect with the left. if (!labelPoint) { split = line.geometry.split(left); if (split) { labelPoint = split[0].components[1]; labelAlign = 'lt'; } } if (labelPoint) { labels.push(new OpenLayers.Feature.Vector(labelPoint, { value: line.attributes.lon, label: OpenLayers.Util.getFormattedLonLat( line.attributes.lon, 'lon', this.labelFormat), labelAlign: labelAlign, xOffset: 0, yOffset: this.labelLonYOffset })); } } for (i = 0, ii = this.parallels.length; i < ii; ++i) { line = this.parallels[i]; labelPoint = line.attributes.labelPoint; labelAlign = 'rb'; // If there is no intersection with the right of the viewport, // intersect with the top. if (!labelPoint) { split = line.geometry.split(top); if (split) { labelPoint = split[0].components[1]; labelAlign = 'ct'; } } if (labelPoint) { labels.push(new OpenLayers.Feature.Vector(labelPoint, { value: line.attributes.lat, label: OpenLayers.Util.getFormattedLonLat( line.attributes.lat, 'lat', this.labelFormat), labelAlign: labelAlign, xOffset: this.labelLatXOffset, yOffset: 2 })); } } this.gratLayer.addFeatures(labels); } }, /** * Method: createGraticule * * Parameters: * extent - {OpenLayers.Bounds} Extent. * center - {OpenLayers.LonLat} Center. * resolution - {number} Resolution. * squaredTolerance - {number} Squared tolerance. */ createGraticule: function(extent, center, resolution, squaredTolerance) { var centerLonLat = center.clone().transform( this.projection, this.epsg4326Projection); // If centerLonLat could not be transformed (e.g. [0, 0] in polar // projections), we shift the center a bit to get a result. if (isNaN(centerLonLat.lon) || isNaN(centerLonLat.lat)) { centerLonLat = center.add(0.000000001, 0.000000001).transform( this.projection, this.epsg4326Projection); } var extentGeom = extent.toGeometry(); var extent4326 = extent.clone() .transform(this.projection, this.epsg4326Projection); // Optimize the length of graticule lines: Instead of always calculating // and rendering them from one end of the world to the other, we only // want to create them for the visible map viewport. To make sure that // our graticule lines are long enough (even in polar projections), we // only make this optimization under certain conditions: // * When we look at a small subset of the world // * When coordinates increase south -> north and west -> east // * When the projection center is not inside the extent. // With these conditions, a valid grid will be available for all // projections within their validity extent. Outside the validity // extent, partial grid lines may occur. var minLon, minLat, maxLon, maxLat; var pixelSize = this.map.getGeodesicPixelSize(); if (pixelSize.w < 0.5 && pixelSize.h < 0.5 && extent4326.right > extent4326.left && extent4326.top > extent4326.bottom && Math.abs(extent4326.bottom) / extent4326.bottom == Math.abs(extent4326.top) / extent4326.top && Math.abs(extent4326.left) / extent4326.left == Math.abs(extent4326.right) / extent4326.right) { minLon = Math.max(extent4326.left, this.minLon); minLat = Math.max(extent4326.bottom, this.minLat); maxLon = Math.min(extent4326.right, this.maxLon); maxLat = Math.min(extent4326.top, this.maxLat); } else { minLon = this.minLon; minLat = this.minLat; maxLon = this.maxLon; maxLat = this.maxLat; } var size = this.map.getSize(); var idx, prevIdx, lon, lat, visibleIntervals, interval, intervalIndex; var centerLon, centerLat; // Create meridians // Start with the coarsest interval, then refine until we reach the // desired targetSize visibleIntervals = Math.ceil(size.w / this.targetSize); intervalIndex = 0; do { interval = this.intervals[intervalIndex++]; centerLon = Math.floor(centerLonLat.lon / interval) * interval; lon = Math.max(centerLon, this.minLon); lon = Math.min(lon, this.maxLon); idx = this.addMeridian( lon, minLat, maxLat, squaredTolerance, extentGeom, 0); while (lon != this.minLon) { lon = Math.max(lon - interval, this.minLon); prevIdx = idx; idx = this.addMeridian( lon, minLat, maxLat, squaredTolerance, extentGeom, idx); if (prevIdx == idx) { // bail out if we're producing lines that are not visible break; } } lon = Math.max(centerLon, this.minLon); lon = Math.min(lon, this.maxLon); while (lon != this.maxLon) { lon = Math.min(lon + interval, this.maxLon); prevIdx = idx; idx = this.addMeridian( lon, minLat, maxLat, squaredTolerance, extentGeom, idx); if (prevIdx == idx) { // bail out if we're producing lines that are not visible break; } } } while (intervalIndex < this.intervals.length && idx <= visibleIntervals); this.meridians.length = idx; // Create parallels // Start with the coarsest interval, then refine until we reach the // desired targetSize visibleIntervals = Math.ceil(size.h / this.targetSize); intervalIndex = 0; do { interval = this.intervalHeights ? this.intervalHeights[intervalIndex++] : this.intervals[intervalIndex++] * this.intervalHeightFactor; centerLat = Math.floor(centerLonLat.lat / interval) * interval; lat = Math.max(centerLat, this.minLat); lat = Math.min(lat, this.maxLat); idx = this.addParallel( lat, minLon, maxLon, squaredTolerance, extentGeom, 0); while (lat != this.minLat) { lat = Math.max(lat - interval, this.minLat); prevIdx = idx; idx = this.addParallel( lat, minLon, maxLon, squaredTolerance, extentGeom, idx); if (prevIdx == idx) { // bail out if we're producing lines that are not visible break; } } lat = Math.max(centerLat, this.minLat); lat = Math.min(lat, this.maxLat); while (lat != this.maxLat) { lat = Math.min(lat + interval, this.maxLat); prevIdx = idx; idx = this.addParallel( lat, minLon, maxLon, squaredTolerance, extentGeom, idx); if (prevIdx == idx) { // bail out if we're producing lines that are not visible break; } } } while (intervalIndex < this.intervals.length && idx <= visibleIntervals); this.parallels.length = idx; }, /** * Method: updateProjectionInfo * * Parameters: * projection - {OpenLayers.Projection} Projection. */ updateProjectionInfo: function(projection) { var defaults = OpenLayers.Projection.defaults[projection.getCode()]; var extent = defaults && defaults.maxExtent ? OpenLayers.Bounds.fromArray(defaults.maxExtent) : this.map.getMaxExtent(); var worldExtent = defaults && defaults.worldExtent ? defaults.worldExtent : [-180, -90, 180, 90]; this.maxLat = worldExtent[3]; this.maxLon = worldExtent[2]; this.minLat = worldExtent[1]; this.minLon = worldExtent[0]; // Use the center of the transformed projection extent rather than the // transformed center of the projection extent. This way we avoid issues // with polar projections where [0, 0] cannot be transformed. this.projectionCenterLonLat = extent.clone().transform( projection, this.epsg4326Projection).getCenterLonLat(); this.projection = projection; }, /** * Method: addMeridian * * Parameters: * lon - {number} Longitude. * minLat - {number} Minimum latitude. * maxLat - {number} Maximum latitude. * squaredTolerance - {number} Squared tolerance. * extentGeom - {OpenLayers.Geometry.Polygon} Extent. * index {number} Index. * * Returns: * {number} Index. */ addMeridian: function( lon, minLat, maxLat, squaredTolerance, extentGeom, index) { var lineString = OpenLayers.Geometry.LineString.geodesicMeridian( lon, minLat, maxLat, this.projection, squaredTolerance); var split = lineString.split(new OpenLayers.Geometry.LineString( extentGeom.components[0].components.slice(0, 2))); if (split || extentGeom.intersects(lineString)) { this.meridians[index++] = new OpenLayers.Feature.Vector(lineString, { lon: lon, labelPoint: split ? split[0].components[1] : undefined }); } return index; }, /** * Method: addParallel * * Parameters: * lat - {number} Latitude. * minLon - {number} Minimum longitude. * maxLon - {number} Maximum longitude. * squaredTolerance - {number} Squared tolerance. * extentGeom - {OpenLayers.Geometry.Polygon} Extent. * index - {number} Index. * * Returns: * {number} Index. */ addParallel: function( lat, minLon, maxLon, squaredTolerance, extentGeom, index) { var lineString = OpenLayers.Geometry.LineString.geodesicParallel( lat, minLon, maxLon, this.projection, squaredTolerance); var split = lineString.split(new OpenLayers.Geometry.LineString( extentGeom.components[0].components.slice(1, 3))); if (split || extentGeom.intersects(lineString)) { this.parallels[index++] = new OpenLayers.Feature.Vector(lineString, { lat: lat, labelPoint: split ? split[0].components[1] : undefined }); } return index; }, CLASS_NAME: "OpenLayers.Control.Graticule" });
version https://git-lfs.github.com/spec/v1 oid sha256:dbea3ca3f5ac4645a1a47289cf98c5277816fbb47afccee5887354dee8ed9037 size 932
dojo.provide("dojo.tests.store.Memory"); dojo.require("dojo.store.Memory"); (function(){ var store = new dojo.store.Memory({ data: [ {id: 1, name: "one", prime: false, mappedTo: "E"}, {id: 2, name: "two", even: true, prime: true, mappedTo: "D"}, {id: 3, name: "three", prime: true, mappedTo: "C"}, {id: 4, name: "four", even: true, prime: false, mappedTo: null}, {id: 5, name: "five", prime: true, mappedTo: "A"} ] }); tests.register("dojo.tests.store.Memory", [ function testGet(t){ t.is(store.get(1).name, "one"); t.is(store.get(4).name, "four"); t.t(store.get(5).prime); }, function testQuery(t){ t.is(store.query({prime: true}).length, 3); t.is(store.query({even: true})[1].name, "four"); }, function testQueryWithString(t){ t.is(store.query({name: "two"}).length, 1); t.is(store.query({name: "two"})[0].name, "two"); }, function testQueryWithRegExp(t){ t.is(store.query({name: /^t/}).length, 2); t.is(store.query({name: /^t/})[1].name, "three"); t.is(store.query({name: /^o/}).length, 1); t.is(store.query({name: /o/}).length, 3); }, function testQueryWithTestFunction(t){ t.is(store.query({id: {test: function(id){ return id < 4;}}}).length, 3); t.is(store.query({even: {test: function(even, object){ return even && object.id > 2;}}}).length, 1); }, function testQueryWithSort(t){ t.is(store.query({prime: true}, {sort:[{attribute:"name"}]}).length, 3); t.is(store.query({even: true}, {sort:[{attribute:"name"}]})[1].name, "two"); t.is(store.query({even: true}, {sort:function(a, b){ return a.name < b.name ? -1 : 1; }})[1].name, "two"); t.is(store.query(null, {sort:[{attribute:"mappedTo"}]})[4].name, "four"); }, function testQueryWithPaging(t){ t.is(store.query({prime: true}, {start: 1, count: 1}).length, 1); t.is(store.query({even: true}, {start: 1, count: 1})[0].name, "four"); }, function testPutUpdate(t){ var four = store.get(4); four.square = true; store.put(four); four = store.get(4); t.t(four.square); }, function testPutNew(t){ store.put({ id: 6, perfect: true }); t.t(store.get(6).perfect); }, function testAddDuplicate(t){ var threw; try{ store.add({ id: 6, perfect: true }); }catch(e){ threw = true; } t.t(threw); }, function testAddNew(t){ store.add({ id: 7, prime: true }); t.t(store.get(7).prime); }, function testRemove(t){ t.t(store.remove(7)); t.is(store.get(7), undefined); }, function testRemoveMissing(t){ t.f(store.remove(77)); // make sure nothing changed t.is(store.get(1).id, 1); }, function testQueryAfterChanges(t){ t.is(store.query({prime: true}).length, 3); t.is(store.query({perfect: true}).length, 1); }, function testIFRSStyleData(t){ var anotherStore = new dojo.store.Memory({ data: { items:[ {name: "one", prime: false}, {name: "two", even: true, prime: true}, {name: "three", prime: true} ], identifier: "name" } }); t.is(anotherStore.get("one").name,"one"); t.is(anotherStore.query({name:"one"})[0].name,"one"); }, function testAddNewIdAssignment(t){ var object = { random: true }; store.add(object); t.t(!!object.id); } ] ); })();
var NS=(document.layers);var IE=(document.all);function obj_enable(objid) {var e=document.getElementById(objid);e.disabled=false;} function obj_disable(objid) {var e=document.getElementById(objid);e.disabled=true;} function setactiveMenuFromContent() {var a=parent.MySQL_Dumper_content.location.href;var menuid=1;if(a.indexOf("config_overview.php")!=-1)menuid=2;if(a.indexOf("filemanagement.php")!=-1) {if(a.indexOf("action=dump")!=-1)menuid=3;if(a.indexOf("action=restore")!=-1)menuid=4;if(a.indexOf("action=files")!=-1)menuid=5;} if(a.indexOf("sql.php")!=-1)menuid=6;if(a.indexOf("log.php")!=-1)menuid=7;if(a.indexOf("help.php")!=-1)menuid=8;setMenuActive('m'+menuid);} function setMenuActive(id){for(var i=1;i<=10;i++){var objid='m'+i;if(id==objid) {parent.frames[0].document.getElementById(objid).className='active';} else {if(parent.frames[0].document.getElementById(objid))parent.frames[0].document.getElementById(objid).className='';}}} function GetSelectedFilename() {var a="";var obj=document.getElementsByName("file[]");var anz=0;if(!obj.length) {if(obj.checked){a+=obj.value;}} else {for(i=0;i<obj.length;i++) {if(obj[i].checked){a+="\n"+obj[i].value;anz++;}}} return a;} function Check(i,k) {var anz=0;var s="";var smp;var ids=document.getElementsByName("file[]");var mp=document.getElementsByName("multipart[]");for(var j=0;j<ids.length;j++){if(ids[j].checked) {s=ids[j].value;smp=(mp[j].value==0)?"":" (Multipart: "+mp[j].value+" files)";anz++;if(k==0)break;}} if(anz==0){WP("","gd");}else if(anz==1){WP(s+smp,"gd");}else{WP("> 1","gd");}} function SelectMD(v,anz) {for(i=0;i<anz;i++){n="db_multidump_"+i;obj=document.getElementsByName(n)[0];if(obj&&!obj.disabled){obj.checked=v;}}} function Sel(v) {var a=document.frm_tbl;if(!a.chk_tbl.length) {a.chk_tbl.checked=v;}else{for(i=0;i<a.chk_tbl.length;i++){a.chk_tbl[i].checked=v;}}} function ConfDBSel(v,adb) {for(i=0;i<adb;i++){var a=document.getElementsByName("db_multidump["+i+"]");if(a)a.checked=v;}} function chkFormular() {var a=document.frm_tbl;a.tbl_array.value="";if(!a.chk_tbl.length) {if(a.chk_tbl.checked==true) a.tbl_array.value+=a.chk_tbl.value+"|";}else{for(i=0;i<a.chk_tbl.length;i++){if(a.chk_tbl[i].checked==true) a.tbl_array.value+=a.chk_tbl[i].value+"|";}} if(a.tbl_array.value==""){alert("Choose tables!");return false;}else{return true;}} function insertHTA(s,tb) {if(s==1)ins="AddHandler php-fastcgi .php .php4\nAddhandler cgi-script .cgi .pl\nOptions +ExecCGI";if(s==101)ins="DirectoryIndex /cgi-bin/script.pl" if(s==102)ins="AddHandler cgi-script .extension";if(s==103)ins="Options +ExecCGI";if(s==104)ins="Options +Indexes";if(s==105)ins="ErrorDocument 400 /errordocument.html";if(s==106)ins="# (macht aus http://domain.de/xyz.html ein\n# http://domain.de/main.php?xyz)\nRewriteEngine on\nRewriteBase /\nRewriteRule ^([a-z]+)\.html$ /main.php?$1 [R,L]";if(s==107)ins="Deny from IPADRESS\nAllow from IPADRESS";if(s==108)ins="Redirect /service http://foo2.bar.com/service";if(s==109)ins="ErrorLog /path/logfile" tb.value+="\n"+ins;} function WP(s,obj){document.getElementById(obj).innerHTML=s;} function resizeSQL(i){var obj=document.getElementById("sqltextarea");var h=0;if(i==0){obj.style.height='4px';}else{if(i==1)h=-20;if(i==2)h=20;var oh=obj.style.height;var s=Number(oh.substring(0,oh.length-2))+h;if(s<24)s=24;obj.style.height=s+'px';}} function getObj(element,docname){if(document.layers){docname=(docname)?docname:self;if(f.document.layers[element]){return f.document.layers[element];} for(W=0;i<f.document.layers.length;W++){return(getElement(element,fdocument.layers[W]));}} if(document.all){return document.all[element];} return document.getElementById(element);} function InsertLib(i){var obj=document.getElementsByName('sqllib')[0];if(obj.selectedIndex>0){document.getElementById('sqlstring'+i).value=obj.options[obj.selectedIndex].value;document.getElementById('sqlname'+i).value=obj.options[obj.selectedIndex].text;}} function DisplayExport(s){document.getElementById("export_working").InnerHTML=s;} function SelectedTableCount(){var obj=document.getElementsByName('f_export_tables[]')[0];var anz=0;for(var i=0;i<obj.options.length;i++) {if(obj.options[i].selected){anz++;}} return anz;} function SelectTableList(s){var obj=document.getElementsByName('f_export_tables[]')[0];for(var i=0;i<obj.options.length;i++){obj.options[i].selected=s;}} function hide_csvdivs(i){document.getElementById("csv0").style.display='none';if(i==0){document.getElementById("csv1").style.display='none';document.getElementById("csv4").style.display='none';document.getElementById("csv5").style.display='none';}} function check_csvdivs(i){hide_csvdivs(i);if(document.getElementById("radio_csv0").checked){document.getElementById("csv0").style.display='block';} if(i==0){if(document.getElementById("radio_csv1").checked){document.getElementById("csv1").style.display='block';}else if(document.getElementById("radio_csv2").checked){document.getElementById("csv1").style.display='block';}else if(document.getElementById("radio_csv4").checked){document.getElementById("csv4").style.display='block';}else if(document.getElementById("radio_csv5").checked){document.getElementById("csv5").style.display='block';}}}