code
stringlengths
2
1.05M
module.exports = require('./lib/kt-client');
'use strict'; import app from '../../app'; describe('NotFound controller', () => { let NotFoundPageCtrl; beforeEach(() => { angular.mock.module(app); angular.mock.inject(($controller) => { NotFoundPageCtrl = $controller('NotFoundPageCtrl'); }); }); it('should have right title', () => { NotFoundPageCtrl.should.exist; NotFoundPageCtrl.title.should.be.a('string'); NotFoundPageCtrl.title.should.equal('404 Not found'); }); });
exports.hello = function() { console.log("Hello Node.js"); };
// warning: This file is auto generated by `npm run build:tests` // Do not edit by hand! process.env.TZ = 'UTC' var expect = require('chai').expect var ini_set = require('../../../../src/php/info/ini_set') // eslint-disable-line no-unused-vars,camelcase var ini_get = require('../../../../src/php/info/ini_get') // eslint-disable-line no-unused-vars,camelcase var urlencode = require('../../../../src/php/url/urlencode.js') // eslint-disable-line no-unused-vars,camelcase describe('src/php/url/urlencode.js (tested in test/languages/php/url/test-urlencode.js)', function () { it('should pass example 1', function (done) { var expected = 'Kevin+van+Zonneveld%21' var result = urlencode('Kevin van Zonneveld!') expect(result).to.deep.equal(expected) done() }) it('should pass example 2', function (done) { var expected = 'https%3A%2F%2Fkvz.io%2F' var result = urlencode('https://kvz.io/') expect(result).to.deep.equal(expected) done() }) it('should pass example 3', function (done) { var expected = 'https%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3DLocutus%26ie%3Dutf-8' var result = urlencode('https://www.google.nl/search?q=Locutus&ie=utf-8') expect(result).to.deep.equal(expected) done() }) })
$.easing.doubleSqrt = function (t, millisecondsSince, startValue, endValue, totalDuration) { var res = Math.sqrt(Math.sqrt(t)); return res; }; (function ($) { $.tileBlockSlider = function (element, options) { // 薪邪褋褌褉芯泄泻懈 锌芯 褍屑芯谢褔邪薪懈褞 var defaults = { // 锌械褉懈芯写 褋屑械薪褘 泻邪褉褌懈薪芯泻 period: 2000, // 锌褉芯写芯谢卸懈褌械谢褜薪芯褋褌褜 邪薪懈屑邪褑懈懈 duration: 1000, // 薪邪锌褉邪胁谢械薪懈械 邪薪懈屑邪褑懈懈 (up, down, left, right) direction: 'up' }; // 芯斜褗械泻褌 锌谢邪谐懈薪邪 var plugin = this; // 薪邪褋褌褉芯泄泻懈 泻芯薪泻褉械褌薪芯谐芯 芯斜褗械泻褌邪 plugin.settings = {}; var $element = $(element), // reference to the jQuery version of DOM element element = element; // reference to the actual DOM element var blocks, // 胁褋械 泻邪褉褌懈薪泻懈 currentBlockIndex, // 懈薪写械泻褋 褌械泻褍褖械谐芯 斜谢芯泻邪 slideInPosition, // 褋褌邪褉褌芯胁芯械 锌芯谢芯卸械薪懈械 斜谢芯泻邪 锌械褉械写 薪邪褔邪谢芯屑 锌芯褟胁谢械薪懈褟 slideOutPosition, // 褎懈薪邪谢褜薪芯械 锌芯谢芯卸械薪懈械 斜谢芯泻邪 锌褉懈 褋泻褉褘褌懈懈 tileWidth, // 褉邪蟹屑械褉褘 锌谢懈褌泻懈 tileHeight; // 懈薪懈褑懈邪谢懈蟹懈褉褍械屑 plugin.init = function () { plugin.settings = $.extend({}, defaults, options); // 胁褋械 斜谢芯泻懈 blocks = $element.children(".tile-content"); // 械褋谢懈 斜谢芯泻 胁褋械谐芯 1, 褌芯 褋谢邪泄写懈薪谐 薪械 薪褍卸械薪 if (blocks.length <= 1) { return; } // 懈薪写械泻褋 邪泻褌懈胁薪芯谐芯 胁 写邪薪薪褘泄 屑芯屑械薪褌 斜谢芯泻邪 currentBlockIndex = 0; // 褉邪蟹屑械褉褘 褌械泻褍褖械泄 锌谢懈褌泻懈 tileWidth = $element.innerWidth(); tileHeight = $element.innerHeight(); // 锌芯谢芯卸械薪懈械 斜谢芯泻芯胁 slideInPosition = getSlideInPosition(); slideOutPosition = getSlideOutPosition(); // 锌芯写谐芯褌邪胁谢懈胁邪械屑 斜谢芯泻懈 泻 邪薪懈屑邪褑懈懈 blocks.each(function (index, block) { block = $(block); // 斜谢芯泻懈 写芯谢卸薪褘 斜褘褌褜 position:absolute // 胁芯蟹屑芯卸薪芯 褝褌芯褌 锌邪褉邪屑械褌褉 蟹邪写邪薪 褔械褉械蟹 泻谢邪褋褋 褋褌懈谢械泄 // 锌褉芯胁械褉褟械屑, 懈 写芯斜邪胁谢褟械屑 械褋谢懈 褝褌芯 薪械 褌邪泻 if (block.css('position') !== 'absolute') { block.css('position', 'absolute'); } // 褋泻褉褘胁邪械屑 胁褋械 斜谢芯泻懈 泻褉芯屑械 锌械褉胁芯谐芯 if (index !== 0) { block.css('left', tileWidth); } }); // 蟹邪锌褍褋泻邪械屑 懈薪褌械褉胁邪谢 写谢褟 褋屑械薪褘 斜谢芯泻芯胁 setInterval(function () { slideBlock(); }, plugin.settings.period); }; // 褋屑械薪邪 斜谢芯泻芯胁 var slideBlock = function () { var slideOutBlock, // 斜谢芯泻 泻芯褌芯褉褘泄 薪邪写芯 褋泻褉褘褌褜 slideInBlock, // 斜谢芯泻 泻芯褌芯褉褘泄 薪邪写芯 锌芯泻邪蟹邪褌褜 mainPosition = {'left': 0, 'top': 0}, options; slideOutBlock = $(blocks[currentBlockIndex]); currentBlockIndex++; if (currentBlockIndex >= blocks.length) { currentBlockIndex = 0; } slideInBlock = $(blocks[currentBlockIndex]); slideInBlock.css(slideInPosition); options = { duration: plugin.settings.duration, easing: 'doubleSqrt' }; slideOutBlock.animate(slideOutPosition, options); slideInBlock.animate(mainPosition, options); }; /** * 胁芯蟹胁褉邪褖邪械褌 褋褌邪褉褌芯胁褍褞 锌芯蟹懈褑懈褞 写谢褟 斜谢芯泻邪 泻芯褌芯褉褘泄 写芯谢卸械薪 锌芯褟胁懈褌褜褋褟 {left: xxx, top: yyy} */ var getSlideInPosition = function () { var pos; if (plugin.settings.direction === 'left') { pos = { 'left': tileWidth, 'top': 0 } } else if (plugin.settings.direction === 'right') { pos = { 'left': -tileWidth, 'top': 0 } } else if (plugin.settings.direction === 'up') { pos = { 'left': 0, 'top': tileHeight } } else if (plugin.settings.direction === 'down') { pos = { 'left': 0, 'top': -tileHeight } } return pos; }; /** * 胁芯蟹胁褉邪褖邪械褌 褎懈薪邪谢褜薪褍褞 锌芯蟹懈褑懈褞 写谢褟 斜谢芯泻邪 泻芯褌芯褉褘泄 写芯谢卸械薪 褋泻褉褘褌褜褋褟 {left: xxx, top: yyy} */ var getSlideOutPosition = function () { var pos; if (plugin.settings.direction === 'left') { pos = { 'left': -tileWidth, 'top': 0 } } else if (plugin.settings.direction === 'right') { pos = { 'left': tileWidth, 'top': 0 } } else if (plugin.settings.direction === 'up') { pos = { 'left': 0, 'top': -tileHeight } } else if (plugin.settings.direction === 'down') { pos = { 'left': 0, 'top': tileHeight } } return pos; }; plugin.getParams = function () { // code goes here } plugin.init(); } $.fn.tileBlockSlider = function (options) { return this.each(function () { if (undefined == $(this).data('tileBlockSlider')) { var plugin = new $.tileBlockSlider(this, options); $(this).data('tileBlockSlider', plugin); } }); } })(jQuery); $(window).ready(function () { var slidedTiles = $('[data-role=tile-slider], .block-slider, .tile-slider'); slidedTiles.each(function (index, tile) { var params = {}; tile = $(tile); params.direction = tile.data('paramDirection'); params.duration = tile.data('paramDuration'); params.period = tile.data('paramPeriod'); tile.tileBlockSlider(params); }) });
var app = require('express')(), wizard = require('hmpo-form-wizard'), steps = require('./steps'), fields = require('./fields'); app.use(require('hmpo-template-mixins')(fields, { sharedTranslationKey: 'prototype' })); app.use(wizard(steps, fields, { templatePath: 'priority_service_170118/upload' })); module.exports = app;
/** * Visual Blocks Editor * * Copyright 2012 Google Inc. * http://blockly.googlecode.com/ * * 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 Object representing a warning. * @author fraser@google.com (Neil Fraser) */ 'use strict'; goog.provide('Blockly.Warning'); /** * Class for a warning. * @param {!Blockly.Block} block The block associated with this warning. * @constructor */ Blockly.Warning = function(block) { this.block_ = block; this.createIcon_(); }; /** * Radius of the warning icon. */ Blockly.Warning.ICON_RADIUS = 8; /** * Bubble UI (if visible). * @type {Blockly.Bubble} * @private */ Blockly.Warning.prototype.bubble_ = null; /** * Warning text (if bubble is not visible). * @private */ Blockly.Warning.prototype.text_ = ''; /** * Absolute X coordinate of icon's center. * @type {number} * @private */ Blockly.Warning.prototype.iconX_ = 0; /** * Absolute Y coordinate of icon's centre. * @type {number} * @private */ Blockly.Warning.prototype.iconY_ = 0; /** * Create the icon on the block. * @private */ Blockly.Warning.prototype.createIcon_ = function() { /* Here's the markup that will be generated: <g class="blocklyIconGroup"> <path class="blocklyIconShield" d="..."/> <text class="blocklyIconMark" x="8" y="13">!</text> </g> */ this.iconGroup_ = Blockly.createSvgElement('g', {}, null); if (!this.block_.isInFlyout) { this.iconGroup_.setAttribute('class', 'blocklyIconGroup'); } var iconShield = Blockly.createSvgElement('path', {'class': 'blocklyIconShield', 'd': 'M 2,15 Q -1,15 0.5,12 L 6.5,1.7 Q 8,-1 9.5,1.7 L 15.5,12 ' + 'Q 17,15 14,15 z'}, this.iconGroup_); this.iconMark_ = Blockly.createSvgElement('text', {'class': 'blocklyIconMark', 'x': Blockly.Warning.ICON_RADIUS, 'y': 2 * Blockly.Warning.ICON_RADIUS - 3}, this.iconGroup_); this.iconMark_.appendChild(document.createTextNode('!')); this.block_.getSvgRoot().appendChild(this.iconGroup_); Blockly.bindEvent_(this.iconGroup_, 'mouseup', this, this.iconClick_); }; /** * Create the text for the warning's bubble. * @param {string} text The text to display. * @return {!SVGTextElement} The top-level node of the text. * @private */ Blockly.Warning.prototype.textToDom_ = function(text) { var paragraph = /** @type {!SVGTextElement} */ ( Blockly.createSvgElement( 'text', {'class': 'blocklyText', 'y': Blockly.Bubble.BORDER_WIDTH}, null)); var lines = text.split('\n'); for (var i = 0; i < lines.length; i++) { var tspanElement = Blockly.createSvgElement('tspan', {'dy': '1em', 'x': Blockly.Bubble.BORDER_WIDTH}, paragraph); var textNode = document.createTextNode(lines[i]); tspanElement.appendChild(textNode); } return paragraph; }; /** * Is the warning bubble visible? * @return {boolean} True if the bubble is visible. */ Blockly.Warning.prototype.isVisible = function() { return !!this.bubble_; }; /** * Show or hide the warning bubble. * @param {boolean} visible True if the bubble should be visible. */ Blockly.Warning.prototype.setVisible = function(visible) { if (visible == this.isVisible()) { // No change. return; } if (visible) { // Create the bubble. var paragraph = this.textToDom_(this.text_); this.bubble_ = new Blockly.Bubble( /** @type {!Blockly.Workspace} */ (this.block_.workspace), paragraph, this.block_.svg_.svgGroup_, this.iconX_, this.iconY_, null, null); if (Blockly.RTL) { // Right-align the paragraph. // This cannot be done until the bubble is rendered on screen. var maxWidth = paragraph.getBBox().width; for (var x = 0, textElement; textElement = paragraph.childNodes[x]; x++) { textElement.setAttribute('text-anchor', 'end'); textElement.setAttribute('x', maxWidth + Blockly.Bubble.BORDER_WIDTH); } } this.updateColour(); // Bump the warning into the right location. var size = this.bubble_.getBubbleSize(); this.bubble_.setBubbleSize(size.width, size.height); } else { // Dispose of the bubble. this.bubble_.dispose(); this.bubble_ = null; this.body_ = null; this.foreignObject_ = null; } }; /** * Clicking on the icon toggles if the bubble is visible. * @param {!Event} e Mouse click event. * @private */ Blockly.Warning.prototype.iconClick_ = function(e) { this.setVisible(!this.isVisible()); }; /** * Bring the warning to the top of the stack when clicked on. * @param {!Event} e Mouse up event. * @private */ Blockly.Warning.prototype.bodyFocus_ = function(e) { this.bubble_.promote_(); }; /** * Set this warning's text. * @param {string} text Warning text. */ Blockly.Warning.prototype.setText = function(text) { this.text_ = text; if (this.isVisible()) { this.setVisible(false); this.setVisible(true); } }; /** * Change the colour of a warning to match its block. */ Blockly.Warning.prototype.updateColour = function() { if (this.isVisible()) { var hexColour = Blockly.makeColour(this.block_.getColour()); this.bubble_.setColour(hexColour); } }; /** * Dispose of this warning. */ Blockly.Warning.prototype.dispose = function() { // Dispose of and unlink the icon. goog.dom.removeNode(this.iconGroup_); this.iconGroup_ = null; // Dispose of and unlink the bubble. this.setVisible(false); // Disconnect links between the block and the warning. this.block_.warning = null; this.block_ = null; }; /** * Render the icon for this warning. * @param {number} cursorX Horizontal offset at which to position the icon. * @return {number} Horizontal offset for next item to draw. */ Blockly.Warning.prototype.renderIcon = function(cursorX) { if (this.block_.collapsed) { this.iconGroup_.setAttribute('display', 'none'); return cursorX; } this.iconGroup_.setAttribute('display', 'block'); var TOP_MARGIN = 5; var diameter = 2 * Blockly.Warning.ICON_RADIUS; if (Blockly.RTL) { cursorX -= diameter; } this.iconGroup_.setAttribute('transform', 'translate(' + cursorX + ', ' + TOP_MARGIN + ')'); this.computeIconLocation(); if (Blockly.RTL) { cursorX -= Blockly.BlockSvg.SEP_SPACE_X; } else { cursorX += diameter + Blockly.BlockSvg.SEP_SPACE_X; } return cursorX; }; /** * Notification that the icon has moved. Update the arrow accordingly. * @param {number} x Absolute horizontal location. * @param {number} y Absolute vertical location. */ Blockly.Warning.prototype.setIconLocation = function(x, y) { this.iconX_ = x; this.iconY_ = y; if (this.isVisible()) { this.bubble_.setAnchorLocation(x, y); } }; /** * Notification that the icon has moved, but we don't really know where. * Recompute the icon's location from scratch. */ Blockly.Warning.prototype.computeIconLocation = function() { // Find coordinates for the centre of the icon and update the arrow. var blockXY = this.block_.getRelativeToSurfaceXY(); var iconXY = Blockly.getRelativeXY_(this.iconGroup_); var newX = blockXY.x + iconXY.x + Blockly.Warning.ICON_RADIUS; var newY = blockXY.y + iconXY.y + Blockly.Warning.ICON_RADIUS; if (newX !== this.iconX_ || newY !== this.iconY_) { this.setIconLocation(newX, newY); } }; /** * Returns the center of the block's icon relative to the surface. * @return {!Object} Object with x and y properties. */ Blockly.Warning.prototype.getIconLocation = function() { return {x: this.iconX_, y: this.iconY_}; };
define(function(require) { 'use strict'; var EmailNotificationCollection; var EmailNotificationModel = require('./email-notification-model'); var BaseCollection = require('oroui/js/app/models/base/collection'); /** * @export oroemail/js/app/models/email-notification-collection */ EmailNotificationCollection = BaseCollection.extend({ model: EmailNotificationModel, markAllAsRead: function() { for (var i in this.models) { if (this.models.hasOwnProperty(i)) { this.models[i].set({'seen': 1}); } } } }); return EmailNotificationCollection; });
import {localeModule, test} from '../qunit'; import moment from '../../moment'; localeModule('fr-ca'); test('parse', function (assert) { var i, tests = 'janvier janv._février févr._mars mars_avril avr._mai mai_juin juin_juillet juil._août août_septembre sept._octobre oct._novembre nov._décembre déc.'.split('_'); function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'dimanche, février 14e 2010, 3:25:50 pm'], ['ddd, hA', 'dim., 3PM'], ['M Mo MM MMMM MMM', '2 2e 02 février févr.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14e 14'], ['d do dddd ddd dd', '0 0e dimanche dim. di'], ['DDD DDDo DDDD', '45 45e 045'], ['w wo ww', '8 8e 08'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[le] Do [jour du mois]', 'le 14e jour du mois'], ['[le] DDDo [jour de l’année]', 'le 45e jour de l’année'], ['LTS', '15:25:50'], ['L', '2010-02-14'], ['LL', '14 février 2010'], ['LLL', '14 février 2010 15:25'], ['LLLL', 'dimanche 14 février 2010 15:25'], ['l', '2010-2-14'], ['ll', '14 févr. 2010'], ['lll', '14 févr. 2010 15:25'], ['llll', 'dim. 14 févr. 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2017, 0, 1]).format('Mo'), '1er', '1er'); assert.equal(moment([2017, 1, 1]).format('Mo'), '2e', '2e'); assert.equal(moment([2017, 0, 1]).format('Qo'), '1er', '1er'); assert.equal(moment([2017, 3, 1]).format('Qo'), '2e', '2e'); assert.equal(moment([2017, 0, 1]).format('Do'), '1er', '1er'); assert.equal(moment([2017, 0, 2]).format('Do'), '2e', '2e'); assert.equal(moment([2011, 0, 1]).format('DDDo'), '1er', '1er'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2e', '2e'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3e', '3e'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4e', '4e'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5e', '5e'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6e', '6e'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7e', '7e'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8e', '8e'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9e', '9e'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10e', '10e'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11e', '11e'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12e', '12e'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13e', '13e'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14e', '14e'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15e', '15e'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16e', '16e'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17e', '17e'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18e', '18e'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19e', '19e'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20e', '20e'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21e', '21e'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22e', '22e'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23e', '23e'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24e', '24e'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25e', '25e'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26e', '26e'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27e', '27e'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28e', '28e'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29e', '29e'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30e', '30e'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31e', '31e'); assert.equal(moment([2017, 0, 1]).format('do'), '0e', '0e'); assert.equal(moment([2017, 0, 2]).format('do'), '1er', '1er'); assert.equal(moment([2017, 0, 4]).format('wo Wo'), '1re 1re', '1re 1re'); assert.equal(moment([2017, 0, 11]).format('wo Wo'), '2e 2e', '2e 2e'); }); test('format month', function (assert) { var i, expected = 'janvier janv._février févr._mars mars_avril avr._mai mai_juin juin_juillet juil._août août_septembre sept._octobre oct._novembre nov._décembre déc.'.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var i, expected = 'dimanche dim. di_lundi lun. lu_mardi mar. ma_mercredi mer. me_jeudi jeu. je_vendredi ven. ve_samedi sam. sa'.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'quelques secondes', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'une minute', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'une minute', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutes', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutes', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'une heure', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'une heure', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 heures', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 heures', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 heures', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'un jour', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'un jour', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 jours', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'un jour', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 jours', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 jours', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'un mois', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'un mois', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'un mois', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mois', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mois', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mois', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'un mois', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mois', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'un an', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ans', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'un an', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ans', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'dans quelques secondes', 'prefix'); assert.equal(moment(0).from(30000), 'il y a quelques secondes', 'suffix'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'dans quelques secondes', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'dans 5 jours', 'in 5 days'); }); test('same day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Aujourd’hui à 12:00', 'Today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Aujourd’hui à 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Aujourd’hui à 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Demain à 12:00', 'Tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Aujourd’hui à 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Hier à 12:00', 'Yesterday at the same time'); }); test('same next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [à] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [à] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [à] LT'), 'Today + ' + i + ' days end of day'); } }); test('same last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('dddd [dernier à] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [dernier à] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [dernier à] LT'), 'Today - ' + i + ' days end of day'); } }); test('same all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1re', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1re', 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2e', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2e', 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3e', 'Jan 15 2012 should be week 3'); });
'use strict'; // Configuring the Articles module angular.module('articles').run(['Menus', function(Menus) { } ]);
YUI.add('gallery-uuid-test', function (Y) { var Assert = Y.Assert, suite; // -- Suite ----------- suite = new Y.Test.Suite({ name: 'gallery-uuid' }); // -- Formatting ------- suite.add(new Y.Test.Case({ name: 'Formatting', 'uuid matches should have expected value': function() { var expected = 'f81d4fae-7dec-11d0-a765-00a0c91e6bf6', actual = Y.Crypto.UUID._formatUUIDString('f81d4fae7dec11d0a76500a0c91e6bf6'); Assert.areEqual(expected, actual); } })); // -- Generation ------- suite.add(new Y.Test.Case({ name: 'Generation', 'raw uuid should be correctly formatted': function() { var uuid = Y.Crypto.UUID(); Assert.areEqual(32, uuid.length); Assert.isFalse(/[^0-9a-f]/.test(uuid)); }, 'formatted uuid should have correct length': function() { var uuid = Y.Crypto.UUID(true); Assert.areEqual(36, uuid.length); Assert.isFalse(/[^0-9a-f\-]/.test(uuid)); } })); // -- Integer to Hex Conversion suite.add(new Y.Test.Case({ name: 'Hex Conversion', '32-bit digit with all bits set should be formatted correctly': function() { var num = 0xffffffff, expected = 'ffffffff', actual = Y.Crypto.UUID._intToHex(num); Assert.areEqual(expected, actual); }, '32-bit digit with no bits set should be formatted correctly': function() { var num = 0x0, expected = '00000000', actual = Y.Crypto.UUID._intToHex(num); Assert.areEqual(expected, actual); } })); Y.Test.Runner.add(suite); }, '@VERSION@', { requires: ['gallery-uuid', 'test'] });
'use strict'; module.exports = function(api) { var core = require('../controllers/core.controller'); api.route('/').get(core.index); }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UIMessage = void 0; var _react = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _classnames = _interopRequireDefault(require("classnames")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } 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 _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var UIMessage = /*#__PURE__*/function (_Component) { _inherits(UIMessage, _Component); var _super = _createSuper(UIMessage); function UIMessage(props) { var _this; _classCallCheck(this, UIMessage); _this = _super.call(this, props); _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onClose = _this.onClose.bind(_assertThisInitialized(_this)); return _this; } _createClass(UIMessage, [{ key: "componentDidMount", value: function componentDidMount() { var _this2 = this; if (!this.props.message.sticky) { this.timeout = setTimeout(function () { _this2.onClose(null); }, this.props.message.life || 3000); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.timeout) { clearTimeout(this.timeout); } } }, { key: "onClose", value: function onClose(event) { if (this.timeout) { clearTimeout(this.timeout); } if (this.props.onClose) { this.props.onClose(this.props.message); } if (event) { event.preventDefault(); event.stopPropagation(); } } }, { key: "onClick", value: function onClick() { if (this.props.onClick) { this.props.onClick(this.props.message); } } }, { key: "renderCloseIcon", value: function renderCloseIcon() { if (this.props.message.closable !== false) { return /*#__PURE__*/_react.default.createElement("button", { type: "button", className: "p-messages-close p-link", onClick: this.onClose }, /*#__PURE__*/_react.default.createElement("i", { className: "p-messages-close-icon pi pi-times" })); } else { return null; } } }, { key: "renderMessages", value: function renderMessages() { if (this.props.message) { return /*#__PURE__*/_react.default.createElement("ul", null, /*#__PURE__*/_react.default.createElement("li", { key: this.props.message.id }, /*#__PURE__*/_react.default.createElement("span", { className: "p-messages-summary" }, this.props.message.summary), /*#__PURE__*/_react.default.createElement("span", { className: "p-messages-detail" }, this.props.message.detail))); } else { return null; } } }, { key: "render", value: function render() { var _this3 = this; var className = 'p-messages p-component p-messages-' + this.props.message.severity; var icon = (0, _classnames.default)('p-messages-icon pi ', { 'pi-info-circle': this.props.message.severity === 'info', 'pi-exclamation-triangle': this.props.message.severity === 'warn', 'pi-times': this.props.message.severity === 'error', 'pi-check': this.props.message.severity === 'success' }); var closeIcon = this.renderCloseIcon(); var messages = this.renderMessages(); return /*#__PURE__*/_react.default.createElement("div", { ref: function ref(el) { _this3.container = el; }, className: className, onClick: this.onClick }, /*#__PURE__*/_react.default.createElement("div", { className: "p-messages-wrapper" }, closeIcon, /*#__PURE__*/_react.default.createElement("span", { className: icon }), messages)); } }]); return UIMessage; }(_react.Component); exports.UIMessage = UIMessage; _defineProperty(UIMessage, "defaultProps", { message: null, onClose: null, onClick: null }); _defineProperty(UIMessage, "propTypes", { message: _propTypes.default.object, onClose: _propTypes.default.func, onClick: _propTypes.default.func });
/* * * * (c) 2009-2020 Øystein Moseng * * Default options for accessibility. * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ /** * Formatter callback for the accessibility announcement. * * @callback Highcharts.AccessibilityAnnouncementFormatter * * @param {Array<Highcharts.Series>} updatedSeries * Array of all series that received updates. If an announcement is already * queued, the series that received updates for that announcement are also * included in this array. * * @param {Highcharts.Series} [addedSeries] * This is provided if {@link Highcharts.Chart#addSeries} was called, and there * is a new series. In that case, this argument is a reference to the new * series. * * @param {Highcharts.Point} [addedPoint] * This is provided if {@link Highcharts.Series#addPoint} was called, and there * is a new point. In that case, this argument is a reference to the new point. * * @return {false|string} * The function should return a string with the text to announce to the user. * Return empty string to not announce anything. Return `false` to use the * default announcement format. */ /** * @interface Highcharts.PointAccessibilityOptionsObject */ /** * Provide a description of the data point, announced to screen readers. * @name Highcharts.PointAccessibilityOptionsObject#description * @type {string|undefined} * @requires modules/accessibility * @since 7.1.0 */ /* * * @interface Highcharts.PointOptionsObject in parts/Point.ts */ /** * @name Highcharts.PointOptionsObject#accessibility * @type {Highcharts.PointAccessibilityOptionsObject|undefined} * @requires modules/accessibility * @since 7.1.0 */ /** * @callback Highcharts.ScreenReaderClickCallbackFunction * * @param {global.MouseEvent} evt * Mouse click event * * @return {void} */ /** * Creates a formatted string for the screen reader module. * * @callback Highcharts.ScreenReaderFormatterCallbackFunction<T> * * @param {T} context * Context to format * * @return {string} * Formatted string for the screen reader module. */ var options = { /** * Options for configuring accessibility for the chart. Requires the * [accessibility module](https://code.highcharts.com/modules/accessibility.js) * to be loaded. For a description of the module and information * on its features, see * [Highcharts Accessibility](https://www.highcharts.com/docs/accessibility/accessibility-module). * * @since 5.0.0 * @requires modules/accessibility * @optionparent accessibility */ accessibility: { /** * Enable accessibility functionality for the chart. * * @since 5.0.0 */ enabled: true, /** * Accessibility options for the screen reader information sections * added before and after the chart. * * @since 8.0.0 */ screenReaderSection: { /** * Function to run upon clicking the "View as Data Table" link in * the screen reader region. * * By default Highcharts will insert and set focus to a data table * representation of the chart. * * @type {Highcharts.ScreenReaderClickCallbackFunction} * @since 8.0.0 * @apioption accessibility.screenReaderSection.onViewDataTableClick */ /** * Function to run upon clicking the "Play as sound" button in * the screen reader region. * * By default Highcharts will call the `chart.sonify` function. * * @type {Highcharts.ScreenReaderClickCallbackFunction} * @since 8.0.1 * @apioption accessibility.screenReaderSection.onPlayAsSoundClick */ /** * A formatter function to create the HTML contents of the hidden * screen reader information region before the chart. Receives one * argument, `chart`, referring to the chart object. Should return a * string with the HTML content of the region. By default this * returns an automatic description of the chart based on * [beforeChartFormat](#accessibility.screenReaderSection.beforeChartFormat). * * @type {Highcharts.ScreenReaderFormatterCallbackFunction<Highcharts.Chart>} * @since 8.0.0 * @apioption accessibility.screenReaderSection.beforeChartFormatter */ /** * Format for the screen reader information region before the chart. * Supported HTML tags are `<h1-7>`, `<p>`, `<div>`, `<a>`, `<ul>`, * `<ol>`, `<li>`, and `<button>`. Attributes are not supported, * except for id on `<div>`, `<a>`, and `<button>`. Id is required * on `<a>` and `<button>` in the format `<tag id="abcd">`. Numbers, * lower- and uppercase letters, "-" and "#" are valid characters in * IDs. * * @since 8.0.0 */ beforeChartFormat: '<h5>{chartTitle}</h5>' + '<div>{typeDescription}</div>' + '<div>{chartSubtitle}</div>' + '<div>{chartLongdesc}</div>' + '<div>{playAsSoundButton}</div>' + '<div>{viewTableButton}</div>' + '<div>{xAxisDescription}</div>' + '<div>{yAxisDescription}</div>' + '<div>{annotationsTitle}{annotationsList}</div>', /** * A formatter function to create the HTML contents of the hidden * screen reader information region after the chart. Analogous to * [beforeChartFormatter](#accessibility.screenReaderSection.beforeChartFormatter). * * @type {Highcharts.ScreenReaderFormatterCallbackFunction<Highcharts.Chart>} * @since 8.0.0 * @apioption accessibility.screenReaderSection.afterChartFormatter */ /** * Format for the screen reader information region after the chart. * Analogous to [beforeChartFormat](#accessibility.screenReaderSection.beforeChartFormat). * * @since 8.0.0 */ afterChartFormat: '{endOfChartMarker}', /** * Date format to use to describe range of datetime axes. * * For an overview of the replacement codes, see * [dateFormat](/class-reference/Highcharts#dateFormat). * * @see [point.dateFormat](#accessibility.point.dateFormat) * * @since 8.0.0 */ axisRangeDateFormat: '%Y-%m-%d %H:%M:%S' }, /** * Accessibility options global to all data series. Individual series * can also have specific [accessibility options](#plotOptions.series.accessibility) * set. * * @since 8.0.0 */ series: { /** * Formatter function to use instead of the default for series * descriptions. Receives one argument, `series`, referring to the * series to describe. Should return a string with the description * of the series for a screen reader user. If `false` is returned, * the default formatter will be used for that series. * * @see [series.description](#plotOptions.series.description) * * @type {Highcharts.ScreenReaderFormatterCallbackFunction<Highcharts.Series>} * @since 8.0.0 * @apioption accessibility.series.descriptionFormatter */ /** * Whether or not to add series descriptions to charts with a single * series. * * @since 8.0.0 */ describeSingleSeries: false, /** * When a series contains more points than this, we no longer expose * information about individual points to screen readers. * * Set to `false` to disable. * * @type {boolean|number} * @since 8.0.0 */ pointDescriptionEnabledThreshold: 200 }, /** * Options for descriptions of individual data points. * * @since 8.0.0 */ point: { /** * Date format to use for points on datetime axes when describing * them to screen reader users. * * Defaults to the same format as in tooltip. * * For an overview of the replacement codes, see * [dateFormat](/class-reference/Highcharts#dateFormat). * * @see [dateFormatter](#accessibility.point.dateFormatter) * * @type {string} * @since 8.0.0 * @apioption accessibility.point.dateFormat */ /** * Formatter function to determine the date/time format used with * points on datetime axes when describing them to screen reader * users. Receives one argument, `point`, referring to the point * to describe. Should return a date format string compatible with * [dateFormat](/class-reference/Highcharts#dateFormat). * * @see [dateFormat](#accessibility.point.dateFormat) * * @type {Highcharts.ScreenReaderFormatterCallbackFunction<Highcharts.Point>} * @since 8.0.0 * @apioption accessibility.point.dateFormatter */ /** * Prefix to add to the values in the point descriptions. Uses * [tooltip.valuePrefix](#tooltip.valuePrefix) if not defined. * * @type {string} * @since 8.0.0 * @apioption accessibility.point.valuePrefix */ /** * Suffix to add to the values in the point descriptions. Uses * [tooltip.valueSuffix](#tooltip.valueSuffix) if not defined. * * @type {string} * @since 8.0.0 * @apioption accessibility.point.valueSuffix */ /** * Decimals to use for the values in the point descriptions. Uses * [tooltip.valueDecimals](#tooltip.valueDecimals) if not defined. * * @type {number} * @since 8.0.0 * @apioption accessibility.point.valueDecimals */ /** * Formatter function to use instead of the default for point * descriptions. * * Receives one argument, `point`, referring to the point to * describe. Should return a string with the description of the * point for a screen reader user. If `false` is returned, the * default formatter will be used for that point. * * Note: Prefer using [accessibility.point.valueDescriptionFormat](#accessibility.point.valueDescriptionFormat) * instead if possible, as default functionality such as describing * annotations will be preserved. * * @see [accessibility.point.valueDescriptionFormat](#accessibility.point.valueDescriptionFormat) * @see [point.accessibility.description](#series.line.data.accessibility.description) * * @type {Highcharts.ScreenReaderFormatterCallbackFunction<Highcharts.Point>} * @since 8.0.0 * @apioption accessibility.point.descriptionFormatter */ /** * Format to use for describing the values of data points * to assistive technology - including screen readers. * The point context is available as `{point}`. * * Additionally, the series name, annotation info, and * description added in `point.accessibility.description` * is added by default if relevant. To override this, use the * [accessibility.point.descriptionFormatter](#accessibility.point.descriptionFormatter) * option. * * @see [point.accessibility.description](#series.line.data.accessibility.description) * @see [accessibility.point.descriptionFormatter](#accessibility.point.descriptionFormatter) * * @type {string} * @since 8.0.1 */ valueDescriptionFormat: '{index}. {xDescription}{separator}{value}.' }, /** * Amount of landmarks/regions to create for screen reader users. More * landmarks can make navigation with screen readers easier, but can * be distracting if there are lots of charts on the page. Three modes * are available: * - `all`: Adds regions for all series, legend, menu, information * region. * - `one`: Adds a single landmark per chart. * - `disabled`: No landmarks are added. * * @since 7.1.0 * @validvalue ["all", "one", "disabled"] */ landmarkVerbosity: 'all', /** * Link the chart to an HTML element describing the contents of the * chart. * * It is always recommended to describe charts using visible text, to * improve SEO as well as accessibility for users with disabilities. * This option lets an HTML element with a description be linked to the * chart, so that screen reader users can connect the two. * * By setting this option to a string, Highcharts runs the string as an * HTML selector query on the entire document. If there is only a single * match, this element is linked to the chart. The content of the linked * element will be included in the chart description for screen reader * users. * * By default, the chart looks for an adjacent sibling element with the * `highcharts-description` class. * * The feature can be disabled by setting the option to an empty string, * or overridden by providing the * [accessibility.description](#accessibility.description) option. * Alternatively, the HTML element to link can be passed in directly as * an HTML node. * * If you need the description to be part of the exported image, * consider using the [caption](#caption) feature. * * If you need the description to be hidden visually, use the * [accessibility.description](#accessibility.description) option. * * @see [caption](#caption) * @see [description](#accessibility.description) * @see [typeDescription](#accessibility.typeDescription) * * @sample highcharts/accessibility/accessible-line * Accessible line chart * * @type {string|Highcharts.HTMLDOMElement} * @since 8.0.0 */ linkedDescription: '*[data-highcharts-chart="{index}"] + .highcharts-description', /** * A hook for adding custom components to the accessibility module. * Should be an object mapping component names to instances of classes * inheriting from the Highcharts.AccessibilityComponent base class. * Remember to add the component to the * [keyboardNavigation.order](#accessibility.keyboardNavigation.order) * for the keyboard navigation to be usable. * * @sample highcharts/accessibility/custom-component * Custom accessibility component * * @type {*} * @since 7.1.0 * @apioption accessibility.customComponents */ /** * Theme to apply to the chart when Windows High Contrast Mode is * detected. By default, a high contrast theme matching the high * contrast system system colors is used. * * @type {*} * @since 7.1.3 * @apioption accessibility.highContrastTheme */ /** * A text description of the chart. * * **Note: Prefer using [linkedDescription](#accessibility.linkedDescription) * or [caption](#caption.text) instead.** * * If the Accessibility module is loaded, this option is included by * default as a long description of the chart in the hidden screen * reader information region. * * Note: Since Highcharts now supports captions and linked descriptions, * it is preferred to define the description using those methods, as a * visible caption/description benefits all users. If the * `accessibility.description` option is defined, the linked description * is ignored, and the caption is hidden from screen reader users. * * @see [linkedDescription](#accessibility.linkedDescription) * @see [caption](#caption) * @see [typeDescription](#accessibility.typeDescription) * * @type {string} * @since 5.0.0 * @apioption accessibility.description */ /** * A text description of the chart type. * * If the Accessibility module is loaded, this will be included in the * description of the chart in the screen reader information region. * * Highcharts will by default attempt to guess the chart type, but for * more complex charts it is recommended to specify this property for * clarity. * * @type {string} * @since 5.0.0 * @apioption accessibility.typeDescription */ /** * Options for keyboard navigation. * * @declare Highcharts.KeyboardNavigationOptionsObject * @since 5.0.0 */ keyboardNavigation: { /** * Enable keyboard navigation for the chart. * * @since 5.0.0 */ enabled: true, /** * Options for the focus border drawn around elements while * navigating through them. * * @sample highcharts/accessibility/custom-focus * Custom focus ring * * @declare Highcharts.KeyboardNavigationFocusBorderOptionsObject * @since 6.0.3 */ focusBorder: { /** * Enable/disable focus border for chart. * * @since 6.0.3 */ enabled: true, /** * Hide the browser's default focus indicator. * * @since 6.0.4 */ hideBrowserFocusOutline: true, /** * Style options for the focus border drawn around elements * while navigating through them. Note that some browsers in * addition draw their own borders for focused elements. These * automatic borders can not be styled by Highcharts. * * In styled mode, the border is given the * `.highcharts-focus-border` class. * * @type {Highcharts.CSSObject} * @since 6.0.3 */ style: { /** @internal */ color: '#335cad', /** @internal */ lineWidth: 2, /** @internal */ borderRadius: 3 }, /** * Focus border margin around the elements. * * @since 6.0.3 */ margin: 2 }, /** * Order of tab navigation in the chart. Determines which elements * are tabbed to first. Available elements are: `series`, `zoom`, * `rangeSelector`, `chartMenu`, `legend`. In addition, any custom * components can be added here. * * @type {Array<string>} * @since 7.1.0 */ order: ['series', 'zoom', 'rangeSelector', 'legend', 'chartMenu'], /** * Whether or not to wrap around when reaching the end of arrow-key * navigation for an element in the chart. * @since 7.1.0 */ wrapAround: true, /** * Options for the keyboard navigation of data points and series. * * @declare Highcharts.KeyboardNavigationSeriesNavigationOptionsObject * @since 8.0.0 */ seriesNavigation: { /** * Set the keyboard navigation mode for the chart. Can be * "normal" or "serialize". In normal mode, left/right arrow * keys move between points in a series, while up/down arrow * keys move between series. Up/down navigation acts * intelligently to figure out which series makes sense to move * to from any given point. * * In "serialize" mode, points are instead navigated as a single * list. Left/right behaves as in "normal" mode. Up/down arrow * keys will behave like left/right. This can be useful for * unifying navigation behavior with/without screen readers * enabled. * * @type {string} * @default normal * @since 8.0.0 * @validvalue ["normal", "serialize"] * @apioption accessibility.keyboardNavigation.seriesNavigation.mode */ /** * Skip null points when navigating through points with the * keyboard. * * @since 8.0.0 */ skipNullPoints: true, /** * When a series contains more points than this, we no longer * allow keyboard navigation for it. * * Set to `false` to disable. * * @type {boolean|number} * @since 8.0.0 */ pointNavigationEnabledThreshold: false } }, /** * Options for announcing new data to screen reader users. Useful * for dynamic data applications and drilldown. * * Keep in mind that frequent announcements will not be useful to * users, as they won't have time to explore the new data. For these * applications, consider making snapshots of the data accessible, and * do the announcements in batches. * * @declare Highcharts.AccessibilityAnnounceNewDataOptionsObject * @since 7.1.0 */ announceNewData: { /** * Optional formatter callback for the announcement. Receives * up to three arguments. The first argument is always an array * of all series that received updates. If an announcement is * already queued, the series that received updates for that * announcement are also included in this array. The second * argument is provided if `chart.addSeries` was called, and * there is a new series. In that case, this argument is a * reference to the new series. The third argument, similarly, * is provided if `series.addPoint` was called, and there is a * new point. In that case, this argument is a reference to the * new point. * * The function should return a string with the text to announce * to the user. Return empty string to not announce anything. * Return `false` to use the default announcement format. * * @sample highcharts/accessibility/custom-dynamic * High priority live alerts * * @type {Highcharts.AccessibilityAnnouncementFormatter} * @apioption accessibility.announceNewData.announcementFormatter */ /** * Enable announcing new data to screen reader users * @sample highcharts/accessibility/accessible-dynamic * Dynamic data accessible */ enabled: false, /** * Minimum interval between announcements in milliseconds. If * new data arrives before this amount of time has passed, it is * queued for announcement. If another new data event happens * while an announcement is queued, the queued announcement is * dropped, and the latest announcement is queued instead. Set * to 0 to allow all announcements, but be warned that frequent * announcements are disturbing to users. */ minAnnounceInterval: 5000, /** * Choose whether or not the announcements should interrupt the * screen reader. If not enabled, the user will be notified once * idle. It is recommended not to enable this setting unless * there is a specific reason to do so. */ interruptUser: false } }, /** * Accessibility options for a data point. * * @declare Highcharts.PointAccessibilityOptionsObject * @since 7.1.0 * @apioption series.line.data.accessibility */ /** * Provide a description of the data point, announced to screen readers. * * @type {string} * @since 7.1.0 * @apioption series.line.data.accessibility.description */ /** * Accessibility options for a series. * * @declare Highcharts.SeriesAccessibilityOptionsObject * @since 7.1.0 * @requires modules/accessibility * @apioption plotOptions.series.accessibility */ /** * Enable/disable accessibility functionality for a specific series. * * @type {boolean} * @since 7.1.0 * @apioption plotOptions.series.accessibility.enabled */ /** * Provide a description of the series, announced to screen readers. * * @type {string} * @since 7.1.0 * @apioption plotOptions.series.accessibility.description */ /** * Formatter function to use instead of the default for point * descriptions. Same as `accessibility.point.descriptionFormatter`, but for * a single series. * * @see [accessibility.point.descriptionFormatter](#accessibility.point.descriptionFormatter) * * @type {Highcharts.ScreenReaderFormatterCallbackFunction<Highcharts.Point>} * @since 7.1.0 * @apioption plotOptions.series.accessibility.pointDescriptionFormatter */ /** * Expose only the series element to screen readers, not its points. * * @type {boolean} * @since 7.1.0 * @apioption plotOptions.series.accessibility.exposeAsGroupOnly */ /** * Keyboard navigation for a series * * @declare Highcharts.SeriesAccessibilityKeyboardNavigationOptionsObject * @since 7.1.0 * @apioption plotOptions.series.accessibility.keyboardNavigation */ /** * Enable/disable keyboard navigation support for a specific series. * * @type {boolean} * @since 7.1.0 * @apioption plotOptions.series.accessibility.keyboardNavigation.enabled */ /** * Accessibility options for an annotation label. * * @declare Highcharts.AnnotationLabelAccessibilityOptionsObject * @since 8.0.1 * @requires modules/accessibility * @apioption annotations.labelOptions.accessibility */ /** * Description of an annotation label for screen readers and other assistive * technology. * * @type {string} * @since 8.0.1 * @apioption annotations.labelOptions.accessibility.description */ /** * Accessibility options for an axis. Requires the accessibility module. * * @declare Highcharts.AxisAccessibilityOptionsObject * @since 7.1.0 * @requires modules/accessibility * @apioption xAxis.accessibility */ /** * Enable axis accessibility features, including axis information in the * screen reader information region. If this is disabled on the xAxis, the * x values are not exposed to screen readers for the individual data points * by default. * * @type {boolean} * @since 7.1.0 * @apioption xAxis.accessibility.enabled */ /** * Description for an axis to expose to screen reader users. * * @type {string} * @since 7.1.0 * @apioption xAxis.accessibility.description */ /** * Range description for an axis. Overrides the default range description. * Set to empty to disable range description for this axis. * * @type {string} * @since 7.1.0 * @apioption xAxis.accessibility.rangeDescription */ /** * @optionparent legend */ legend: { /** * Accessibility options for the legend. Requires the Accessibility * module. * * @since 7.1.0 * @requires modules/accessibility */ accessibility: { /** * Enable accessibility support for the legend. * * @since 7.1.0 */ enabled: true, /** * Options for keyboard navigation for the legend. * * @since 7.1.0 * @requires modules/accessibility */ keyboardNavigation: { /** * Enable keyboard navigation for the legend. * * @see [accessibility.keyboardNavigation](#accessibility.keyboardNavigation.enabled) * * @since 7.1.0 */ enabled: true } } }, /** * @optionparent exporting */ exporting: { /** * Accessibility options for the exporting menu. Requires the * Accessibility module. * * @since 7.1.0 * @requires modules/accessibility */ accessibility: { /** * Enable accessibility support for the export menu. * * @since 7.1.0 */ enabled: true } } }; export default options;
import React, { Component } from 'react' class Links extends Component { prepareNoLinksMessage() { return ( <div className="empty mt-5"> <i className="icon icon-people"></i> <p className="empty-title">You have no links</p> <p className="empty-meta">Click the button to add new link.</p> <button className="empty-action btn btn-primary">Add Link</button> </div> ) } prepareLink(link){ return ( <div className="columns" key={link._id}> <div className="column col-xs-9">{link.title}</div> <div className="column col-xs-2">{link.body}</div> <div className="column col-xs-1"> <button onClick={() => this.props.deleteLink(link._id) } className={this.props.delLinkId === link._id ? "btn loading disabled" : "btn btn-primary btn-block"}> {this.props.delLinkId === link._id ? "Deleting" : "Delete"} </button> </div> </div> ) } prepareLinkListing() { return ( <div className="container bg-gray mt-5"> <div className="columns"> <div className="column col-xs-9 text-bold">Title</div> <div className="column col-xs-2 text-bold">Body</div> <div className="column col-xs-1 text-bold">Action</div> </div> {!this.props.isLoading && this.props.links.map(this.prepareLink.bind(this))} {this.props.isLoading && <div className="center loading"></div>} </div> ) } render(){ var btnClass = this.props.isLoading ? "btn centered btn-primary loading" : "btn centered btn-primary" return ( <section className="section"> <button className={btnClass} onClick={() => this.props.getLinks() }>Refresh</button> {!!this.props.links.length && this.prepareLinkListing() } {!this.props.links.length && this.prepareNoLinksMessage() } </section> ) } } export default Links
import Details from './details'; export { Details };
'use strict'; const chai = require('chai'), expect = chai.expect, sinon = require('sinon'), Support = require('../support'), Sequelize = require('../../../index'), DataTypes = require('../../../lib/data-types'); describe(Support.getTestDialectTeaser('Paranoid'), () => { beforeEach(function( ) { const S = this.sequelize, DT = DataTypes, A = this.A = S.define('A', { name: DT.STRING }, { paranoid: true }), B = this.B = S.define('B', { name: DT.STRING }, { paranoid: true }), C = this.C = S.define('C', { name: DT.STRING }, { paranoid: true }), D = this.D = S.define('D', { name: DT.STRING }, { paranoid: true }); A.belongsTo(B); A.belongsToMany(D, { through: 'a_d' }); A.hasMany(C); B.hasMany(A); B.hasMany(C); C.belongsTo(A); C.belongsTo(B); D.belongsToMany(A, { through: 'a_d' }); return S.sync({ force: true }); }); before(function() { this.clock = sinon.useFakeTimers(); }); after(function() { this.clock.restore(); }); it('paranoid with timestamps: false should be ignored / not crash', function() { const S = this.sequelize, Test = S.define('Test', { name: DataTypes.STRING }, { timestamps: false, paranoid: true }); return S.sync({ force: true }).then(() => { return Test.findByPk(1); }); }); it('test if non required is marked as false', function( ) { const A = this.A, B = this.B, options = { include: [ { model: B, required: false } ] }; return A.findOne(options).then(() => { expect(options.include[0].required).to.be.equal(false); }); }); it('test if required is marked as true', function( ) { const A = this.A, B = this.B, options = { include: [ { model: B, required: true } ] }; return A.findOne(options).then(() => { expect(options.include[0].required).to.be.equal(true); }); }); it('should not load paranoid, destroyed instances, with a non-paranoid parent', function() { const X = this.sequelize.define('x', { name: DataTypes.STRING }, { paranoid: false }); const Y = this.sequelize.define('y', { name: DataTypes.STRING }, { timestamps: true, paranoid: true }); X.hasMany(Y); return this.sequelize.sync({ force: true }).then(() => { return Sequelize.Promise.all([ X.create(), Y.create() ]); }).then(([x, y]) => { this.x = x; this.y = y; return x.addY(y); }).then(() => { return this.y.destroy(); }).then(() => { //prevent CURRENT_TIMESTAMP to be same this.clock.tick(1000); return X.findAll({ include: [Y] }).get(0); }).then(x => { expect(x.ys).to.have.length(0); }); }); });
Spontaneous.Field.Select = (function($, S) { 'use strict'; var dom = S.Dom , ajax = S.Ajax; var SelectField = new JS.Class(Spontaneous.Field.String, { edit: function() { var self = this , type = this.type , option_list = type.option_list , wrapper = dom.div('.select-field-type') , callback; if (!option_list) { // dynamic, make ajax call callback = function(data) { self.append_select(wrapper, data); }; ajax.get(this.optionsURL(), callback); } else { self.append_select(wrapper, option_list); } return wrapper; }, optionsURL: function() { return ['/field/options', this.type.schema_id, this.content.id()].join('/'); }, append_select: function(wrapper, option_list) { var select = dom.select() , options = {} , selected = this.selectedValue(); option_list.forEach(function(val) { var value = val[0] , label = val[1] , option = dom.option({'value': value}).text(label); options[value] = label; if (value == selected) { // only == so that strings successfully match ints option.attr('selected', 'selected'); } select.append(option); }); this._select = select; this._options = options; wrapper.append(select); }, preview: function() { return this.parsedValue()[1]; }, parsedValue: function() { var value = this.get('value'); if (!value) { return []; } return JSON.parse(this.get('value')); }, selectedValue: function() { return this.parsedValue()[0]; }, edited_value: function() { var value = this._select.val() , label = this._options[value]; return JSON.stringify([value, label]); } }); return SelectField; })(jQuery, Spontaneous);
/** * @memberOf Jymfony.Component.DependencyInjection.Fixtures */ class CaseSensitiveClass { __construct(identifier = null) { this._identifier = identifier; } } module.exports = CaseSensitiveClass;
import { Field } from '@rocket.chat/fuselage'; import React from 'react'; import { AssetSettingInput } from './AssetSettingInput'; export default { title: 'admin/settings/inputs/AssetSettingInput', component: AssetSettingInput, decorators: [ (storyFn) => <div className='rc-old'> <div className='page-settings'> <Field>{storyFn()}</Field> </div> </div>, ], }; export const _default = () => <AssetSettingInput _id='setting_id' label='Label' />; export const disabled = () => <AssetSettingInput _id='setting_id' label='Label' disabled />; export const withValue = () => <AssetSettingInput _id='setting_id' label='Label' value={{ src: 'https://open.rocket.chat/images/logo/logo.svg' }} disabled />; export const withFileConstraints = () => <AssetSettingInput _id='setting_id' label='Label' fileConstraints={{ extensions: ['png', 'jpg', 'gif'] }} disabled />;
/** * widget.js - high-level interface for blessed * Copyright (c) 2013-2015, Christopher Jeffrey and contributors (MIT License). * https://github.com/chjj/blessed */ var widget = exports; widget.classes = [ 'Node', 'Screen', 'Element', 'Box', 'Text', 'Line', 'ScrollableBox', 'ScrollableText', 'List', 'Form', 'Input', 'Textarea', 'Textbox', 'Button', 'ProgressBar', 'FileManager', 'Checkbox', 'RadioSet', 'RadioButton', 'Prompt', 'Question', 'Message', 'Loading', 'Listbar', 'Log', 'Table', 'ListTable', 'Terminal', 'Image', 'Layout' ]; widget.classes.forEach(function(name) { var file = name.toLowerCase(); widget[name] = widget[file] = require('./widgets/' + file); });
class InsertMode extends Mode { constructor(options) { super(); if (options == null) options = {}; // There is one permanently-installed instance of InsertMode. It tracks focus changes and // activates/deactivates itself (by setting @insertModeLock) accordingly. this.permanent = options.permanent; // If truthy, then we were activated by the user (with "i"). this.global = options.global; const handleKeyEvent = event => { if (!this.isActive(event)) return this.continueBubbling; // See comment here: https://github.com/philc/vimium/commit/48c169bd5a61685bb4e67b1e76c939dbf360a658. const activeElement = this.getActiveElement(); if ((activeElement === document.body) && activeElement.isContentEditable) return this.passEventToPage; // Check for a pass-next-key key. const keyString = KeyboardUtils.getKeyCharString(event); if (Settings.get("passNextKeyKeys").includes(keyString)) { new PassNextKeyMode(); } else if ((event.type === 'keydown') && KeyboardUtils.isEscape(event)) { if (DomUtils.isFocusable(activeElement)) activeElement.blur(); if (!this.permanent) this.exit(); } else { return this.passEventToPage; } return this.suppressEvent; }; const defaults = { name: "insert", indicator: !this.permanent && !Settings.get("hideHud") ? "Insert mode" : null, keypress: handleKeyEvent, keydown: handleKeyEvent }; super.init(Object.assign(defaults, options)); // Only for tests. This gives us a hook to test the status of the permanently-installed instance. if (this.permanent) InsertMode.permanentInstance = this; } isActive(event) { if (event === InsertMode.suppressedEvent) return false; if (this.global) return true; return DomUtils.isFocusable(this.getActiveElement()); } getActiveElement() { let activeElement = document.activeElement; while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) activeElement = activeElement.shadowRoot.activeElement; return activeElement; } static suppressEvent(event) { return this.suppressedEvent = event; } } // This allows PostFindMode to suppress the permanently-installed InsertMode instance. InsertMode.suppressedEvent = null; // This implements the pasNexKey command. class PassNextKeyMode extends Mode { constructor(count) { if (count == null) count = 1; super(); let seenKeyDown = false; let keyDownCount = 0; super.init({ name: "pass-next-key", indicator: "Pass next key.", // We exit on blur because, once we lose the focus, we can no longer track key events. exitOnBlur: window, keypress: () => { return this.passEventToPage; }, keydown: () => { seenKeyDown = true; keyDownCount += 1; return this.passEventToPage; }, keyup: () => { if (seenKeyDown) { if (!(--keyDownCount > 0)) { if (!(--count > 0)) { this.exit(); } } } return this.passEventToPage; } }); } } global.InsertMode = InsertMode; global.PassNextKeyMode = PassNextKeyMode;
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionSpeakerNotesOff = (props) => ( <SvgIcon {...props}> <path d="M10.54 11l-.54-.54L7.54 8 6 6.46 2.38 2.84 1.27 1.73 0 3l2.01 2.01L2 22l4-4h9l5.73 5.73L22 22.46 17.54 18l-7-7zM8 14H6v-2h2v2zm-2-3V9l2 2H6zm14-9H4.08L10 7.92V6h8v2h-7.92l1 1H18v2h-4.92l6.99 6.99C21.14 17.95 22 17.08 22 16V4c0-1.1-.9-2-2-2z"/> </SvgIcon> ); ActionSpeakerNotesOff.displayName = 'ActionSpeakerNotesOff'; ActionSpeakerNotesOff.muiName = 'SvgIcon'; export default ActionSpeakerNotesOff;
/*! flat-embed v0.1.0 | (c) 2017 Tutteo Ltd. (Flat) | Apache-2.0 License | https://github.com/FlatIO/embed-client */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.Flat = global.Flat || {}, global.Flat.Embed = factory()); }(this, (function () { 'use strict'; function unwrapExports (x) { return x && x.__esModule ? x['default'] : x; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } // 7.1.4 ToInteger var ceil = Math.ceil; var floor = Math.floor; var _toInteger = function(it){ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; // 7.2.1 RequireObjectCoercible(argument) var _defined = function(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; }; // true -> String#at // false -> String#codePointAt var _stringAt = function(TO_STRING){ return function(that, pos){ var s = String(_defined(that)) , i = _toInteger(pos) , l = s.length , a, b; if(i < 0 || i >= l)return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; var _library = true; var _global = createCommonjsModule(function (module) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef }); var _core = createCommonjsModule(function (module) { var core = module.exports = {version: '2.4.0'}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef }); var _aFunction = function(it){ if(typeof it != 'function')throw TypeError(it + ' is not a function!'); return it; }; // optional / simple context binding var _ctx = function(fn, that, length){ _aFunction(fn); if(that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); }; case 2: return function(a, b){ return fn.call(that, a, b); }; case 3: return function(a, b, c){ return fn.call(that, a, b, c); }; } return function(/* ...args */){ return fn.apply(that, arguments); }; }; var _isObject = function(it){ return typeof it === 'object' ? it !== null : typeof it === 'function'; }; var _anObject = function(it){ if(!_isObject(it))throw TypeError(it + ' is not an object!'); return it; }; var _fails = function(exec){ try { return !!exec(); } catch(e){ return true; } }; // Thank's IE8 for his funny defineProperty var _descriptors = !_fails(function(){ return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; }); var document$1 = _global.document; var is = _isObject(document$1) && _isObject(document$1.createElement); var _domCreate = function(it){ return is ? document$1.createElement(it) : {}; }; var _ie8DomDefine = !_descriptors && !_fails(function(){ return Object.defineProperty(_domCreate('div'), 'a', {get: function(){ return 7; }}).a != 7; }); // 7.1.1 ToPrimitive(input [, PreferredType]) // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string var _toPrimitive = function(it, S){ if(!_isObject(it))return it; var fn, val; if(S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it)))return val; if(typeof (fn = it.valueOf) == 'function' && !_isObject(val = fn.call(it)))return val; if(!S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it)))return val; throw TypeError("Can't convert object to primitive value"); }; var dP = Object.defineProperty; var f = _descriptors ? Object.defineProperty : function defineProperty(O, P, Attributes){ _anObject(O); P = _toPrimitive(P, true); _anObject(Attributes); if(_ie8DomDefine)try { return dP(O, P, Attributes); } catch(e){ /* empty */ } if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); if('value' in Attributes)O[P] = Attributes.value; return O; }; var _objectDp = { f: f }; var _propertyDesc = function(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value }; }; var _hide = _descriptors ? function(object, key, value){ return _objectDp.f(object, key, _propertyDesc(1, value)); } : function(object, key, value){ object[key] = value; return object; }; var PROTOTYPE = 'prototype'; var $export = function(type, name, source){ var IS_FORCED = type & $export.F , IS_GLOBAL = type & $export.G , IS_STATIC = type & $export.S , IS_PROTO = type & $export.P , IS_BIND = type & $export.B , IS_WRAP = type & $export.W , exports = IS_GLOBAL ? _core : _core[name] || (_core[name] = {}) , expProto = exports[PROTOTYPE] , target = IS_GLOBAL ? _global : IS_STATIC ? _global[name] : (_global[name] || {})[PROTOTYPE] , key, own, out; if(IS_GLOBAL)source = name; for(key in source){ // contains in native own = !IS_FORCED && target && target[key] !== undefined; if(own && key in exports)continue; // export native or passed out = own ? target[key] : source[key]; // prevent global pollution for namespaces exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] // bind timers to global for call from export context : IS_BIND && own ? _ctx(out, _global) // wrap global constructors for prevent change them in library : IS_WRAP && target[key] == out ? (function(C){ var F = function(a, b, c){ if(this instanceof C){ switch(arguments.length){ case 0: return new C; case 1: return new C(a); case 2: return new C(a, b); } return new C(a, b, c); } return C.apply(this, arguments); }; F[PROTOTYPE] = C[PROTOTYPE]; return F; // make static versions for prototype methods })(out) : IS_PROTO && typeof out == 'function' ? _ctx(Function.call, out) : out; // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% if(IS_PROTO){ (exports.virtual || (exports.virtual = {}))[key] = out; // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% if(type & $export.R && expProto && !expProto[key])_hide(expProto, key, out); } } }; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` var _export = $export; var _redefine = _hide; var hasOwnProperty = {}.hasOwnProperty; var _has = function(it, key){ return hasOwnProperty.call(it, key); }; var _iterators = {}; var toString = {}.toString; var _cof = function(it){ return toString.call(it).slice(8, -1); }; // fallback for non-array-like ES3 and non-enumerable old V8 strings var _iobject = Object('z').propertyIsEnumerable(0) ? Object : function(it){ return _cof(it) == 'String' ? it.split('') : Object(it); }; // to indexed object, toObject with fallback for non-array-like ES3 strings var _toIobject = function(it){ return _iobject(_defined(it)); }; // 7.1.15 ToLength var min = Math.min; var _toLength = function(it){ return it > 0 ? min(_toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; var max = Math.max; var min$1 = Math.min; var _toIndex = function(index, length){ index = _toInteger(index); return index < 0 ? max(index + length, 0) : min$1(index, length); }; // false -> Array#indexOf // true -> Array#includes var _arrayIncludes = function(IS_INCLUDES){ return function($this, el, fromIndex){ var O = _toIobject($this) , length = _toLength(O.length) , index = _toIndex(fromIndex, length) , value; // Array#includes uses SameValueZero equality algorithm if(IS_INCLUDES && el != el)while(length > index){ value = O[index++]; if(value != value)return true; // Array#toIndex ignores holes, Array#includes - not } else for(;length > index; index++)if(IS_INCLUDES || index in O){ if(O[index] === el)return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; var SHARED = '__core-js_shared__'; var store = _global[SHARED] || (_global[SHARED] = {}); var _shared = function(key){ return store[key] || (store[key] = {}); }; var id = 0; var px = Math.random(); var _uid = function(key){ return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; var shared = _shared('keys'); var _sharedKey = function(key){ return shared[key] || (shared[key] = _uid(key)); }; var arrayIndexOf = _arrayIncludes(false); var IE_PROTO$1 = _sharedKey('IE_PROTO'); var _objectKeysInternal = function(object, names){ var O = _toIobject(object) , i = 0 , result = [] , key; for(key in O)if(key != IE_PROTO$1)_has(O, key) && result.push(key); // Don't enum bug & hidden keys while(names.length > i)if(_has(O, key = names[i++])){ ~arrayIndexOf(result, key) || result.push(key); } return result; }; // IE 8- don't enum bug keys var _enumBugKeys = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); // 19.1.2.14 / 15.2.3.14 Object.keys(O) var _objectKeys = Object.keys || function keys(O){ return _objectKeysInternal(O, _enumBugKeys); }; var _objectDps = _descriptors ? Object.defineProperties : function defineProperties(O, Properties){ _anObject(O); var keys = _objectKeys(Properties) , length = keys.length , i = 0 , P; while(length > i)_objectDp.f(O, P = keys[i++], Properties[P]); return O; }; var _html = _global.document && document.documentElement; // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var IE_PROTO = _sharedKey('IE_PROTO'); var Empty = function(){ /* empty */ }; var PROTOTYPE$1 = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype var createDict = function(){ // Thrash, waste and sodomy: IE GC bug var iframe = _domCreate('iframe') , i = _enumBugKeys.length , lt = '<' , gt = '>' , iframeDocument; iframe.style.display = 'none'; _html.appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict[PROTOTYPE$1][_enumBugKeys[i]]; return createDict(); }; var _objectCreate = Object.create || function create(O, Properties){ var result; if(O !== null){ Empty[PROTOTYPE$1] = _anObject(O); result = new Empty; Empty[PROTOTYPE$1] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : _objectDps(result, Properties); }; var _wks = createCommonjsModule(function (module) { var store = _shared('wks') , Symbol = _global.Symbol , USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function(name){ return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : _uid)('Symbol.' + name)); }; $exports.store = store; }); var def = _objectDp.f; var TAG = _wks('toStringTag'); var _setToStringTag = function(it, tag, stat){ if(it && !_has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); }; var IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() _hide(IteratorPrototype, _wks('iterator'), function(){ return this; }); var _iterCreate = function(Constructor, NAME, next){ Constructor.prototype = _objectCreate(IteratorPrototype, {next: _propertyDesc(1, next)}); _setToStringTag(Constructor, NAME + ' Iterator'); }; // 7.1.13 ToObject(argument) var _toObject = function(it){ return Object(_defined(it)); }; // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var IE_PROTO$2 = _sharedKey('IE_PROTO'); var ObjectProto = Object.prototype; var _objectGpo = Object.getPrototypeOf || function(O){ O = _toObject(O); if(_has(O, IE_PROTO$2))return O[IE_PROTO$2]; if(typeof O.constructor == 'function' && O instanceof O.constructor){ return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }; var ITERATOR = _wks('iterator'); var BUGGY = !([].keys && 'next' in [].keys()); var FF_ITERATOR = '@@iterator'; var KEYS = 'keys'; var VALUES = 'values'; var returnThis = function(){ return this; }; var _iterDefine = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ _iterCreate(Constructor, NAME, next); var getMethod = function(kind){ if(!BUGGY && kind in proto)return proto[kind]; switch(kind){ case KEYS: return function keys(){ return new Constructor(this, kind); }; case VALUES: return function values(){ return new Constructor(this, kind); }; } return function entries(){ return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator' , DEF_VALUES = DEFAULT == VALUES , VALUES_BUG = false , proto = Base.prototype , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] , $default = $native || getMethod(DEFAULT) , $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined , $anyNative = NAME == 'Array' ? proto.entries || $native : $native , methods, key, IteratorPrototype; // Fix native if($anyNative){ IteratorPrototype = _objectGpo($anyNative.call(new Base)); if(IteratorPrototype !== Object.prototype){ // Set @@toStringTag to native iterators _setToStringTag(IteratorPrototype, TAG, true); // fix for some old engines if(!_library && !_has(IteratorPrototype, ITERATOR))_hide(IteratorPrototype, ITERATOR, returnThis); } } // fix Array#{values, @@iterator}.name in V8 / FF if(DEF_VALUES && $native && $native.name !== VALUES){ VALUES_BUG = true; $default = function values(){ return $native.call(this); }; } // Define iterator if((!_library || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ _hide(proto, ITERATOR, $default); } // Plug for library _iterators[NAME] = $default; _iterators[TAG] = returnThis; if(DEFAULT){ methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: $entries }; if(FORCED)for(key in methods){ if(!(key in proto))_redefine(proto, key, methods[key]); } else _export(_export.P + _export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; var $at = _stringAt(true); // 21.1.3.27 String.prototype[@@iterator]() _iterDefine(String, 'String', function(iterated){ this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var O = this._t , index = this._i , point; if(index >= O.length)return {value: undefined, done: true}; point = $at(O, index); this._i += point.length; return {value: point, done: false}; }); var _addToUnscopables = function(){ /* empty */ }; var _iterStep = function(done, value){ return {value: value, done: !!done}; }; // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() var es6_array_iterator = _iterDefine(Array, 'Array', function(iterated, kind){ this._t = _toIobject(iterated); // target this._i = 0; // next index this._k = kind; // kind // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var O = this._t , kind = this._k , index = this._i++; if(!O || index >= O.length){ this._t = undefined; return _iterStep(1); } if(kind == 'keys' )return _iterStep(0, index); if(kind == 'values')return _iterStep(0, O[index]); return _iterStep(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) _iterators.Arguments = _iterators.Array; _addToUnscopables('keys'); _addToUnscopables('values'); _addToUnscopables('entries'); var TO_STRING_TAG = _wks('toStringTag'); for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){ var NAME = collections[i] , Collection = _global[NAME] , proto = Collection && Collection.prototype; if(proto && !proto[TO_STRING_TAG])_hide(proto, TO_STRING_TAG, NAME); _iterators[NAME] = _iterators.Array; } var f$1 = _wks; var _wksExt = { f: f$1 }; var iterator$2 = _wksExt.f('iterator'); var iterator = createCommonjsModule(function (module) { module.exports = { "default": iterator$2, __esModule: true }; }); var _meta = createCommonjsModule(function (module) { var META = _uid('meta') , setDesc = _objectDp.f , id = 0; var isExtensible = Object.isExtensible || function(){ return true; }; var FREEZE = !_fails(function(){ return isExtensible(Object.preventExtensions({})); }); var setMeta = function(it){ setDesc(it, META, {value: { i: 'O' + ++id, // object ID w: {} // weak collections IDs }}); }; var fastKey = function(it, create){ // return primitive with prefix if(!_isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if(!_has(it, META)){ // can't set metadata to uncaught frozen object if(!isExtensible(it))return 'F'; // not necessary to add metadata if(!create)return 'E'; // add missing metadata setMeta(it); // return object ID } return it[META].i; }; var getWeak = function(it, create){ if(!_has(it, META)){ // can't set metadata to uncaught frozen object if(!isExtensible(it))return true; // not necessary to add metadata if(!create)return false; // add missing metadata setMeta(it); // return hash weak collections IDs } return it[META].w; }; // add metadata on freeze-family methods calling var onFreeze = function(it){ if(FREEZE && meta.NEED && isExtensible(it) && !_has(it, META))setMeta(it); return it; }; var meta = module.exports = { KEY: META, NEED: false, fastKey: fastKey, getWeak: getWeak, onFreeze: onFreeze }; }); var defineProperty = _objectDp.f; var _wksDefine = function(name){ var $Symbol = _core.Symbol || (_core.Symbol = _library ? {} : _global.Symbol || {}); if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: _wksExt.f(name)}); }; var _keyof = function(object, el){ var O = _toIobject(object) , keys = _objectKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; }; var f$2 = Object.getOwnPropertySymbols; var _objectGops = { f: f$2 }; var f$3 = {}.propertyIsEnumerable; var _objectPie = { f: f$3 }; // all enumerable object keys, includes symbols var _enumKeys = function(it){ var result = _objectKeys(it) , getSymbols = _objectGops.f; if(getSymbols){ var symbols = getSymbols(it) , isEnum = _objectPie.f , i = 0 , key; while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key); } return result; }; // 7.2.2 IsArray(argument) var _isArray = Array.isArray || function isArray(arg){ return _cof(arg) == 'Array'; }; // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) var hiddenKeys = _enumBugKeys.concat('length', 'prototype'); var f$5 = Object.getOwnPropertyNames || function getOwnPropertyNames(O){ return _objectKeysInternal(O, hiddenKeys); }; var _objectGopn = { f: f$5 }; // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var gOPN$1 = _objectGopn.f; var toString$1 = {}.toString; var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; var getWindowNames = function(it){ try { return gOPN$1(it); } catch(e){ return windowNames.slice(); } }; var f$4 = function getOwnPropertyNames(it){ return windowNames && toString$1.call(it) == '[object Window]' ? getWindowNames(it) : gOPN$1(_toIobject(it)); }; var _objectGopnExt = { f: f$4 }; var gOPD$1 = Object.getOwnPropertyDescriptor; var f$6 = _descriptors ? gOPD$1 : function getOwnPropertyDescriptor(O, P){ O = _toIobject(O); P = _toPrimitive(P, true); if(_ie8DomDefine)try { return gOPD$1(O, P); } catch(e){ /* empty */ } if(_has(O, P))return _propertyDesc(!_objectPie.f.call(O, P), O[P]); }; var _objectGopd = { f: f$6 }; // ECMAScript 6 symbols shim var META = _meta.KEY; var gOPD = _objectGopd.f; var dP$1 = _objectDp.f; var gOPN = _objectGopnExt.f; var $Symbol = _global.Symbol; var $JSON = _global.JSON; var _stringify = $JSON && $JSON.stringify; var PROTOTYPE$2 = 'prototype'; var HIDDEN = _wks('_hidden'); var TO_PRIMITIVE = _wks('toPrimitive'); var isEnum = {}.propertyIsEnumerable; var SymbolRegistry = _shared('symbol-registry'); var AllSymbols = _shared('symbols'); var OPSymbols = _shared('op-symbols'); var ObjectProto$1 = Object[PROTOTYPE$2]; var USE_NATIVE = typeof $Symbol == 'function'; var QObject = _global.QObject; // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 var setter = !QObject || !QObject[PROTOTYPE$2] || !QObject[PROTOTYPE$2].findChild; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 var setSymbolDesc = _descriptors && _fails(function(){ return _objectCreate(dP$1({}, 'a', { get: function(){ return dP$1(this, 'a', {value: 7}).a; } })).a != 7; }) ? function(it, key, D){ var protoDesc = gOPD(ObjectProto$1, key); if(protoDesc)delete ObjectProto$1[key]; dP$1(it, key, D); if(protoDesc && it !== ObjectProto$1)dP$1(ObjectProto$1, key, protoDesc); } : dP$1; var wrap = function(tag){ var sym = AllSymbols[tag] = _objectCreate($Symbol[PROTOTYPE$2]); sym._k = tag; return sym; }; var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){ return typeof it == 'symbol'; } : function(it){ return it instanceof $Symbol; }; var $defineProperty = function defineProperty(it, key, D){ if(it === ObjectProto$1)$defineProperty(OPSymbols, key, D); _anObject(it); key = _toPrimitive(key, true); _anObject(D); if(_has(AllSymbols, key)){ if(!D.enumerable){ if(!_has(it, HIDDEN))dP$1(it, HIDDEN, _propertyDesc(1, {})); it[HIDDEN][key] = true; } else { if(_has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; D = _objectCreate(D, {enumerable: _propertyDesc(0, false)}); } return setSymbolDesc(it, key, D); } return dP$1(it, key, D); }; var $defineProperties = function defineProperties(it, P){ _anObject(it); var keys = _enumKeys(P = _toIobject(P)) , i = 0 , l = keys.length , key; while(l > i)$defineProperty(it, key = keys[i++], P[key]); return it; }; var $create = function create(it, P){ return P === undefined ? _objectCreate(it) : $defineProperties(_objectCreate(it), P); }; var $propertyIsEnumerable = function propertyIsEnumerable(key){ var E = isEnum.call(this, key = _toPrimitive(key, true)); if(this === ObjectProto$1 && _has(AllSymbols, key) && !_has(OPSymbols, key))return false; return E || !_has(this, key) || !_has(AllSymbols, key) || _has(this, HIDDEN) && this[HIDDEN][key] ? E : true; }; var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){ it = _toIobject(it); key = _toPrimitive(key, true); if(it === ObjectProto$1 && _has(AllSymbols, key) && !_has(OPSymbols, key))return; var D = gOPD(it, key); if(D && _has(AllSymbols, key) && !(_has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; return D; }; var $getOwnPropertyNames = function getOwnPropertyNames(it){ var names = gOPN(_toIobject(it)) , result = [] , i = 0 , key; while(names.length > i){ if(!_has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key); } return result; }; var $getOwnPropertySymbols = function getOwnPropertySymbols(it){ var IS_OP = it === ObjectProto$1 , names = gOPN(IS_OP ? OPSymbols : _toIobject(it)) , result = [] , i = 0 , key; while(names.length > i){ if(_has(AllSymbols, key = names[i++]) && (IS_OP ? _has(ObjectProto$1, key) : true))result.push(AllSymbols[key]); } return result; }; // 19.4.1.1 Symbol([description]) if(!USE_NATIVE){ $Symbol = function Symbol(){ if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!'); var tag = _uid(arguments.length > 0 ? arguments[0] : undefined); var $set = function(value){ if(this === ObjectProto$1)$set.call(OPSymbols, value); if(_has(this, HIDDEN) && _has(this[HIDDEN], tag))this[HIDDEN][tag] = false; setSymbolDesc(this, tag, _propertyDesc(1, value)); }; if(_descriptors && setter)setSymbolDesc(ObjectProto$1, tag, {configurable: true, set: $set}); return wrap(tag); }; _redefine($Symbol[PROTOTYPE$2], 'toString', function toString(){ return this._k; }); _objectGopd.f = $getOwnPropertyDescriptor; _objectDp.f = $defineProperty; _objectGopn.f = _objectGopnExt.f = $getOwnPropertyNames; _objectPie.f = $propertyIsEnumerable; _objectGops.f = $getOwnPropertySymbols; if(_descriptors && !_library){ _redefine(ObjectProto$1, 'propertyIsEnumerable', $propertyIsEnumerable, true); } _wksExt.f = function(name){ return wrap(_wks(name)); }; } _export(_export.G + _export.W + _export.F * !USE_NATIVE, {Symbol: $Symbol}); for(var symbols = ( // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' ).split(','), i$1 = 0; symbols.length > i$1; )_wks(symbols[i$1++]); for(var symbols = _objectKeys(_wks.store), i$1 = 0; symbols.length > i$1; )_wksDefine(symbols[i$1++]); _export(_export.S + _export.F * !USE_NATIVE, 'Symbol', { // 19.4.2.1 Symbol.for(key) 'for': function(key){ return _has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(key){ if(isSymbol(key))return _keyof(SymbolRegistry, key); throw TypeError(key + ' is not a symbol!'); }, useSetter: function(){ setter = true; }, useSimple: function(){ setter = false; } }); _export(_export.S + _export.F * !USE_NATIVE, 'Object', { // 19.1.2.2 Object.create(O [, Properties]) create: $create, // 19.1.2.4 Object.defineProperty(O, P, Attributes) defineProperty: $defineProperty, // 19.1.2.3 Object.defineProperties(O, Properties) defineProperties: $defineProperties, // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $getOwnPropertyDescriptor, // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: $getOwnPropertyNames, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: $getOwnPropertySymbols }); // 24.3.2 JSON.stringify(value [, replacer [, space]]) $JSON && _export(_export.S + _export.F * (!USE_NATIVE || _fails(function(){ var S = $Symbol(); // MS Edge converts symbol values to JSON as {} // WebKit converts symbol values to JSON as null // V8 throws on boxed symbols return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}'; })), 'JSON', { stringify: function stringify(it){ if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined var args = [it] , i = 1 , replacer, $replacer; while(arguments.length > i)args.push(arguments[i++]); replacer = args[1]; if(typeof replacer == 'function')$replacer = replacer; if($replacer || !_isArray(replacer))replacer = function(key, value){ if($replacer)value = $replacer.call(this, key, value); if(!isSymbol(value))return value; }; args[1] = replacer; return _stringify.apply($JSON, args); } }); // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) $Symbol[PROTOTYPE$2][TO_PRIMITIVE] || _hide($Symbol[PROTOTYPE$2], TO_PRIMITIVE, $Symbol[PROTOTYPE$2].valueOf); // 19.4.3.5 Symbol.prototype[@@toStringTag] _setToStringTag($Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] _setToStringTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] _setToStringTag(_global.JSON, 'JSON', true); _wksDefine('asyncIterator'); _wksDefine('observable'); var index = _core.Symbol; var symbol = createCommonjsModule(function (module) { module.exports = { "default": index, __esModule: true }; }); var _typeof_1 = createCommonjsModule(function (module, exports) { "use strict"; exports.__esModule = true; var _iterator2 = _interopRequireDefault(iterator); var _symbol2 = _interopRequireDefault(symbol); var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { return typeof obj === "undefined" ? "undefined" : _typeof(obj); } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); }; }); var _typeof = unwrapExports(_typeof_1); // getting tag from 19.1.3.6 Object.prototype.toString() var TAG$1 = _wks('toStringTag'); var ARG = _cof(function(){ return arguments; }()) == 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function(it, key){ try { return it[key]; } catch(e){ /* empty */ } }; var _classof = function(it){ var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (T = tryGet(O = Object(it), TAG$1)) == 'string' ? T // builtinTag case : ARG ? _cof(O) // ES3 arguments fallback : (B = _cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; var _anInstance = function(it, Constructor, name, forbiddenField){ if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){ throw TypeError(name + ': incorrect invocation!'); } return it; }; // call something on iterator step with safe closing on error var _iterCall = function(iterator, fn, value, entries){ try { return entries ? fn(_anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) } catch(e){ var ret = iterator['return']; if(ret !== undefined)_anObject(ret.call(iterator)); throw e; } }; // check on default Array iterator var ITERATOR$1 = _wks('iterator'); var ArrayProto = Array.prototype; var _isArrayIter = function(it){ return it !== undefined && (_iterators.Array === it || ArrayProto[ITERATOR$1] === it); }; var ITERATOR$2 = _wks('iterator'); var core_getIteratorMethod = _core.getIteratorMethod = function(it){ if(it != undefined)return it[ITERATOR$2] || it['@@iterator'] || _iterators[_classof(it)]; }; var _forOf = createCommonjsModule(function (module) { var BREAK = {} , RETURN = {}; var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){ var iterFn = ITERATOR ? function(){ return iterable; } : core_getIteratorMethod(iterable) , f = _ctx(fn, that, entries ? 2 : 1) , index = 0 , length, step, iterator, result; if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!'); // fast case for arrays with default iterator if(_isArrayIter(iterFn))for(length = _toLength(iterable.length); length > index; index++){ result = entries ? f(_anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); if(result === BREAK || result === RETURN)return result; } else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){ result = _iterCall(iterator, f, step.value, entries); if(result === BREAK || result === RETURN)return result; } }; exports.BREAK = BREAK; exports.RETURN = RETURN; }); // 7.3.20 SpeciesConstructor(O, defaultConstructor) var SPECIES = _wks('species'); var _speciesConstructor = function(O, D){ var C = _anObject(O).constructor, S; return C === undefined || (S = _anObject(C)[SPECIES]) == undefined ? D : _aFunction(S); }; // fast apply, http://jsperf.lnkit.com/fast-apply/5 var _invoke = function(fn, args, that){ var un = that === undefined; switch(args.length){ case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); } return fn.apply(that, args); }; var process$1 = _global.process; var setTask = _global.setImmediate; var clearTask = _global.clearImmediate; var MessageChannel = _global.MessageChannel; var counter = 0; var queue = {}; var ONREADYSTATECHANGE = 'onreadystatechange'; var defer; var channel; var port; var run = function(){ var id = +this; if(queue.hasOwnProperty(id)){ var fn = queue[id]; delete queue[id]; fn(); } }; var listener = function(event){ run.call(event.data); }; // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if(!setTask || !clearTask){ setTask = function setImmediate(fn){ var args = [], i = 1; while(arguments.length > i)args.push(arguments[i++]); queue[++counter] = function(){ _invoke(typeof fn == 'function' ? fn : Function(fn), args); }; defer(counter); return counter; }; clearTask = function clearImmediate(id){ delete queue[id]; }; // Node.js 0.8- if(_cof(process$1) == 'process'){ defer = function(id){ process$1.nextTick(_ctx(run, id, 1)); }; // Browsers with MessageChannel, includes WebWorkers } else if(MessageChannel){ channel = new MessageChannel; port = channel.port2; channel.port1.onmessage = listener; defer = _ctx(port.postMessage, port, 1); // Browsers with postMessage, skip WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' } else if(_global.addEventListener && typeof postMessage == 'function' && !_global.importScripts){ defer = function(id){ _global.postMessage(id + '', '*'); }; _global.addEventListener('message', listener, false); // IE8- } else if(ONREADYSTATECHANGE in _domCreate('script')){ defer = function(id){ _html.appendChild(_domCreate('script'))[ONREADYSTATECHANGE] = function(){ _html.removeChild(this); run.call(id); }; }; // Rest old browsers } else { defer = function(id){ setTimeout(_ctx(run, id, 1), 0); }; } } var _task = { set: setTask, clear: clearTask }; var macrotask = _task.set; var Observer = _global.MutationObserver || _global.WebKitMutationObserver; var process$2 = _global.process; var Promise = _global.Promise; var isNode$1 = _cof(process$2) == 'process'; var _microtask = function(){ var head, last, notify; var flush = function(){ var parent, fn; if(isNode$1 && (parent = process$2.domain))parent.exit(); while(head){ fn = head.fn; head = head.next; try { fn(); } catch(e){ if(head)notify(); else last = undefined; throw e; } } last = undefined; if(parent)parent.enter(); }; // Node.js if(isNode$1){ notify = function(){ process$2.nextTick(flush); }; // browsers with MutationObserver } else if(Observer){ var toggle = true , node = document.createTextNode(''); new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new notify = function(){ node.data = toggle = !toggle; }; // environments with maybe non-completely correct, but existent Promise } else if(Promise && Promise.resolve){ var promise = Promise.resolve(); notify = function(){ promise.then(flush); }; // for other environments - macrotask based on: // - setImmediate // - MessageChannel // - window.postMessag // - onreadystatechange // - setTimeout } else { notify = function(){ // strange IE + webpack dev server bug - use .call(global) macrotask.call(_global, flush); }; } return function(fn){ var task = {fn: fn, next: undefined}; if(last)last.next = task; if(!head){ head = task; notify(); } last = task; }; }; var _redefineAll = function(target, src, safe){ for(var key in src){ if(safe && target[key])target[key] = src[key]; else _hide(target, key, src[key]); } return target; }; var SPECIES$1 = _wks('species'); var _setSpecies = function(KEY){ var C = typeof _core[KEY] == 'function' ? _core[KEY] : _global[KEY]; if(_descriptors && C && !C[SPECIES$1])_objectDp.f(C, SPECIES$1, { configurable: true, get: function(){ return this; } }); }; var ITERATOR$3 = _wks('iterator'); var SAFE_CLOSING = false; try { var riter = [7][ITERATOR$3](); riter['return'] = function(){ SAFE_CLOSING = true; }; Array.from(riter, function(){ throw 2; }); } catch(e){ /* empty */ } var _iterDetect = function(exec, skipClosing){ if(!skipClosing && !SAFE_CLOSING)return false; var safe = false; try { var arr = [7] , iter = arr[ITERATOR$3](); iter.next = function(){ return {done: safe = true}; }; arr[ITERATOR$3] = function(){ return iter; }; exec(arr); } catch(e){ /* empty */ } return safe; }; var task = _task.set; var microtask = _microtask(); var PROMISE = 'Promise'; var TypeError$1 = _global.TypeError; var process = _global.process; var $Promise = _global[PROMISE]; var process = _global.process; var isNode = _classof(process) == 'process'; var empty = function(){ /* empty */ }; var Internal; var GenericPromiseCapability; var Wrapper; var USE_NATIVE$1 = !!function(){ try { // correct subclassing with @@species support var promise = $Promise.resolve(1) , FakePromise = (promise.constructor = {})[_wks('species')] = function(exec){ exec(empty, empty); }; // unhandled rejections tracking support, NodeJS Promise without it fails @@species test return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise; } catch(e){ /* empty */ } }(); // helpers var sameConstructor = function(a, b){ // with library wrapper special case return a === b || a === $Promise && b === Wrapper; }; var isThenable = function(it){ var then; return _isObject(it) && typeof (then = it.then) == 'function' ? then : false; }; var newPromiseCapability = function(C){ return sameConstructor($Promise, C) ? new PromiseCapability(C) : new GenericPromiseCapability(C); }; var PromiseCapability = GenericPromiseCapability = function(C){ var resolve, reject; this.promise = new C(function($$resolve, $$reject){ if(resolve !== undefined || reject !== undefined)throw TypeError$1('Bad Promise constructor'); resolve = $$resolve; reject = $$reject; }); this.resolve = _aFunction(resolve); this.reject = _aFunction(reject); }; var perform = function(exec){ try { exec(); } catch(e){ return {error: e}; } }; var notify = function(promise, isReject){ if(promise._n)return; promise._n = true; var chain = promise._c; microtask(function(){ var value = promise._v , ok = promise._s == 1 , i = 0; var run = function(reaction){ var handler = ok ? reaction.ok : reaction.fail , resolve = reaction.resolve , reject = reaction.reject , domain = reaction.domain , result, then; try { if(handler){ if(!ok){ if(promise._h == 2)onHandleUnhandled(promise); promise._h = 1; } if(handler === true)result = value; else { if(domain)domain.enter(); result = handler(value); if(domain)domain.exit(); } if(result === reaction.promise){ reject(TypeError$1('Promise-chain cycle')); } else if(then = isThenable(result)){ then.call(result, resolve, reject); } else resolve(result); } else reject(value); } catch(e){ reject(e); } }; while(chain.length > i)run(chain[i++]); // variable length - can't use forEach promise._c = []; promise._n = false; if(isReject && !promise._h)onUnhandled(promise); }); }; var onUnhandled = function(promise){ task.call(_global, function(){ var value = promise._v , abrupt, handler, console; if(isUnhandled(promise)){ abrupt = perform(function(){ if(isNode){ process.emit('unhandledRejection', value, promise); } else if(handler = _global.onunhandledrejection){ handler({promise: promise, reason: value}); } else if((console = _global.console) && console.error){ console.error('Unhandled promise rejection', value); } }); // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should promise._h = isNode || isUnhandled(promise) ? 2 : 1; } promise._a = undefined; if(abrupt)throw abrupt.error; }); }; var isUnhandled = function(promise){ if(promise._h == 1)return false; var chain = promise._a || promise._c , i = 0 , reaction; while(chain.length > i){ reaction = chain[i++]; if(reaction.fail || !isUnhandled(reaction.promise))return false; } return true; }; var onHandleUnhandled = function(promise){ task.call(_global, function(){ var handler; if(isNode){ process.emit('rejectionHandled', promise); } else if(handler = _global.onrejectionhandled){ handler({promise: promise, reason: promise._v}); } }); }; var $reject = function(value){ var promise = this; if(promise._d)return; promise._d = true; promise = promise._w || promise; // unwrap promise._v = value; promise._s = 2; if(!promise._a)promise._a = promise._c.slice(); notify(promise, true); }; var $resolve = function(value){ var promise = this , then; if(promise._d)return; promise._d = true; promise = promise._w || promise; // unwrap try { if(promise === value)throw TypeError$1("Promise can't be resolved itself"); if(then = isThenable(value)){ microtask(function(){ var wrapper = {_w: promise, _d: false}; // wrap try { then.call(value, _ctx($resolve, wrapper, 1), _ctx($reject, wrapper, 1)); } catch(e){ $reject.call(wrapper, e); } }); } else { promise._v = value; promise._s = 1; notify(promise, false); } } catch(e){ $reject.call({_w: promise, _d: false}, e); // wrap } }; // constructor polyfill if(!USE_NATIVE$1){ // 25.4.3.1 Promise(executor) $Promise = function Promise(executor){ _anInstance(this, $Promise, PROMISE, '_h'); _aFunction(executor); Internal.call(this); try { executor(_ctx($resolve, this, 1), _ctx($reject, this, 1)); } catch(err){ $reject.call(this, err); } }; Internal = function Promise(executor){ this._c = []; // <- awaiting reactions this._a = undefined; // <- checked in isUnhandled reactions this._s = 0; // <- state this._d = false; // <- done this._v = undefined; // <- value this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled this._n = false; // <- notify }; Internal.prototype = _redefineAll($Promise.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected){ var reaction = newPromiseCapability(_speciesConstructor(this, $Promise)); reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; reaction.fail = typeof onRejected == 'function' && onRejected; reaction.domain = isNode ? process.domain : undefined; this._c.push(reaction); if(this._a)this._a.push(reaction); if(this._s)notify(this, false); return reaction.promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); PromiseCapability = function(){ var promise = new Internal; this.promise = promise; this.resolve = _ctx($resolve, promise, 1); this.reject = _ctx($reject, promise, 1); }; } _export(_export.G + _export.W + _export.F * !USE_NATIVE$1, {Promise: $Promise}); _setToStringTag($Promise, PROMISE); _setSpecies(PROMISE); Wrapper = _core[PROMISE]; // statics _export(_export.S + _export.F * !USE_NATIVE$1, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r){ var capability = newPromiseCapability(this) , $$reject = capability.reject; $$reject(r); return capability.promise; } }); _export(_export.S + _export.F * (_library || !USE_NATIVE$1), PROMISE, { // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x){ // instanceof instead of internal slot check because we should fix it without replacement native Promise core if(x instanceof $Promise && sameConstructor(x.constructor, this))return x; var capability = newPromiseCapability(this) , $$resolve = capability.resolve; $$resolve(x); return capability.promise; } }); _export(_export.S + _export.F * !(USE_NATIVE$1 && _iterDetect(function(iter){ $Promise.all(iter)['catch'](empty); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable){ var C = this , capability = newPromiseCapability(C) , resolve = capability.resolve , reject = capability.reject; var abrupt = perform(function(){ var values = [] , index = 0 , remaining = 1; _forOf(iterable, false, function(promise){ var $index = index++ , alreadyCalled = false; values.push(undefined); remaining++; C.resolve(promise).then(function(value){ if(alreadyCalled)return; alreadyCalled = true; values[$index] = value; --remaining || resolve(values); }, reject); }); --remaining || resolve(values); }); if(abrupt)reject(abrupt.error); return capability.promise; }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable){ var C = this , capability = newPromiseCapability(C) , reject = capability.reject; var abrupt = perform(function(){ _forOf(iterable, false, function(promise){ C.resolve(promise).then(capability.resolve, reject); }); }); if(abrupt)reject(abrupt.error); return capability.promise; } }); var promise$1 = _core.Promise; var promise = createCommonjsModule(function (module) { module.exports = { "default": promise$1, __esModule: true }; }); var _Promise = unwrapExports(promise); var classCallCheck = createCommonjsModule(function (module, exports) { "use strict"; exports.__esModule = true; exports.default = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; }); var _classCallCheck = unwrapExports(classCallCheck); // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) _export(_export.S + _export.F * !_descriptors, 'Object', {defineProperty: _objectDp.f}); var $Object = _core.Object; var defineProperty$3 = function defineProperty(it, key, desc){ return $Object.defineProperty(it, key, desc); }; var defineProperty$1 = createCommonjsModule(function (module) { module.exports = { "default": defineProperty$3, __esModule: true }; }); var createClass = createCommonjsModule(function (module, exports) { "use strict"; exports.__esModule = true; var _defineProperty2 = _interopRequireDefault(defineProperty$1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; (0, _defineProperty2.default)(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); }); var _createClass = unwrapExports(createClass); var SPECIES$2 = _wks('species'); var _arraySpeciesConstructor = function(original){ var C; if(_isArray(original)){ C = original.constructor; // cross-realm fallback if(typeof C == 'function' && (C === Array || _isArray(C.prototype)))C = undefined; if(_isObject(C)){ C = C[SPECIES$2]; if(C === null)C = undefined; } } return C === undefined ? Array : C; }; // 9.4.2.3 ArraySpeciesCreate(originalArray, length) var _arraySpeciesCreate = function(original, length){ return new (_arraySpeciesConstructor(original))(length); }; // 0 -> Array#forEach // 1 -> Array#map // 2 -> Array#filter // 3 -> Array#some // 4 -> Array#every // 5 -> Array#find // 6 -> Array#findIndex var _arrayMethods = function(TYPE, $create){ var IS_MAP = TYPE == 1 , IS_FILTER = TYPE == 2 , IS_SOME = TYPE == 3 , IS_EVERY = TYPE == 4 , IS_FIND_INDEX = TYPE == 6 , NO_HOLES = TYPE == 5 || IS_FIND_INDEX , create = $create || _arraySpeciesCreate; return function($this, callbackfn, that){ var O = _toObject($this) , self = _iobject(O) , f = _ctx(callbackfn, that, 3) , length = _toLength(self.length) , index = 0 , result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined , val, res; for(;length > index; index++)if(NO_HOLES || index in self){ val = self[index]; res = f(val, index, O); if(TYPE){ if(IS_MAP)result[index] = res; // map else if(res)switch(TYPE){ case 3: return true; // some case 5: return val; // find case 6: return index; // findIndex case 2: result.push(val); // filter } else if(IS_EVERY)return false; // every } } return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; }; }; // 19.1.2.1 Object.assign(target, source, ...) var $assign = Object.assign; // should work with symbols and should have deterministic property order (V8 bug) var _objectAssign = !$assign || _fails(function(){ var A = {} , B = {} , S = Symbol() , K = 'abcdefghijklmnopqrst'; A[S] = 7; K.split('').forEach(function(k){ B[k] = k; }); return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; }) ? function assign(target, source){ // eslint-disable-line no-unused-vars var T = _toObject(target) , aLen = arguments.length , index = 1 , getSymbols = _objectGops.f , isEnum = _objectPie.f; while(aLen > index){ var S = _iobject(arguments[index++]) , keys = getSymbols ? _objectKeys(S).concat(getSymbols(S)) : _objectKeys(S) , length = keys.length , j = 0 , key; while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key]; } return T; } : $assign; var getWeak = _meta.getWeak; var arrayFind = _arrayMethods(5); var arrayFindIndex = _arrayMethods(6); var id$1 = 0; // fallback for uncaught frozen keys var uncaughtFrozenStore = function(that){ return that._l || (that._l = new UncaughtFrozenStore); }; var UncaughtFrozenStore = function(){ this.a = []; }; var findUncaughtFrozen = function(store, key){ return arrayFind(store.a, function(it){ return it[0] === key; }); }; UncaughtFrozenStore.prototype = { get: function(key){ var entry = findUncaughtFrozen(this, key); if(entry)return entry[1]; }, has: function(key){ return !!findUncaughtFrozen(this, key); }, set: function(key, value){ var entry = findUncaughtFrozen(this, key); if(entry)entry[1] = value; else this.a.push([key, value]); }, 'delete': function(key){ var index = arrayFindIndex(this.a, function(it){ return it[0] === key; }); if(~index)this.a.splice(index, 1); return !!~index; } }; var _collectionWeak = { getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ var C = wrapper(function(that, iterable){ _anInstance(that, C, NAME, '_i'); that._i = id$1++; // collection id that._l = undefined; // leak store for uncaught frozen objects if(iterable != undefined)_forOf(iterable, IS_MAP, that[ADDER], that); }); _redefineAll(C.prototype, { // 23.3.3.2 WeakMap.prototype.delete(key) // 23.4.3.3 WeakSet.prototype.delete(value) 'delete': function(key){ if(!_isObject(key))return false; var data = getWeak(key); if(data === true)return uncaughtFrozenStore(this)['delete'](key); return data && _has(data, this._i) && delete data[this._i]; }, // 23.3.3.4 WeakMap.prototype.has(key) // 23.4.3.4 WeakSet.prototype.has(value) has: function has(key){ if(!_isObject(key))return false; var data = getWeak(key); if(data === true)return uncaughtFrozenStore(this).has(key); return data && _has(data, this._i); } }); return C; }, def: function(that, key, value){ var data = getWeak(_anObject(key), true); if(data === true)uncaughtFrozenStore(that).set(key, value); else data[that._i] = value; return that; }, ufstore: uncaughtFrozenStore }; var dP$2 = _objectDp.f; var each = _arrayMethods(0); var _collection = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){ var Base = _global[NAME] , C = Base , ADDER = IS_MAP ? 'set' : 'add' , proto = C && C.prototype , O = {}; if(!_descriptors || typeof C != 'function' || !(IS_WEAK || proto.forEach && !_fails(function(){ new C().entries().next(); }))){ // create collection constructor C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); _redefineAll(C.prototype, methods); _meta.NEED = true; } else { C = wrapper(function(target, iterable){ _anInstance(target, C, NAME, '_c'); target._c = new Base; if(iterable != undefined)_forOf(iterable, IS_MAP, target[ADDER], target); }); each('add,clear,delete,forEach,get,has,set,keys,values,entries,toJSON'.split(','),function(KEY){ var IS_ADDER = KEY == 'add' || KEY == 'set'; if(KEY in proto && !(IS_WEAK && KEY == 'clear'))_hide(C.prototype, KEY, function(a, b){ _anInstance(this, C, KEY); if(!IS_ADDER && IS_WEAK && !_isObject(a))return KEY == 'get' ? undefined : false; var result = this._c[KEY](a === 0 ? 0 : a, b); return IS_ADDER ? this : result; }); }); if('size' in proto)dP$2(C.prototype, 'size', { get: function(){ return this._c.size; } }); } _setToStringTag(C, NAME); O[NAME] = C; _export(_export.G + _export.W + _export.F, O); if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP); return C; }; var es6_weakMap = createCommonjsModule(function (module) { 'use strict'; var each = _arrayMethods(0) , getWeak = _meta.getWeak , isExtensible = Object.isExtensible , uncaughtFrozenStore = _collectionWeak.ufstore , tmp = {} , InternalMap; var wrapper = function(get){ return function WeakMap(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }; var methods = { // 23.3.3.3 WeakMap.prototype.get(key) get: function get(key){ if(_isObject(key)){ var data = getWeak(key); if(data === true)return uncaughtFrozenStore(this).get(key); return data ? data[this._i] : undefined; } }, // 23.3.3.5 WeakMap.prototype.set(key, value) set: function set(key, value){ return _collectionWeak.def(this, key, value); } }; // 23.3 WeakMap Objects var $WeakMap = module.exports = _collection('WeakMap', wrapper, methods, _collectionWeak, true, true); // IE11 WeakMap frozen keys fix if(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){ InternalMap = _collectionWeak.getConstructor(wrapper); _objectAssign(InternalMap.prototype, methods); _meta.NEED = true; each(['delete', 'has', 'get', 'set'], function(key){ var proto = $WeakMap.prototype , method = proto[key]; _redefine(proto, key, function(a, b){ // store frozen objects on internal weakmap shim if(_isObject(a) && !isExtensible(a)){ if(!this._f)this._f = new InternalMap; var result = this._f[key](a, b); return key == 'set' ? this : result; // store all the rest on native weakmap } return method.call(this, a, b); }); }); } }); var weakMap$1 = _core.WeakMap; var weakMap = createCommonjsModule(function (module) { module.exports = { "default": weakMap$1, __esModule: true }; }); var _WeakMap = unwrapExports(weakMap); if (typeof window.postMessage === 'undefined') { throw new Error('The Flat Embed JS API is not supported in this browser'); } /** * Select and normalize the DOM element input * * @param {(HTMLIFrameElement|HTMLElement|string|jQuery)} element * @return {(HTMLIFrameElement|HTMLElement)} */ function normalizeElement(element) { if (window.jQuery && element instanceof window.jQuery) { element = element[0]; } // Find an element by identifier if (typeof element === 'string') { element = document.getElementById(element); } // Check if a DOM element if (!(element instanceof window.HTMLElement)) { throw new TypeError('The first parameter must be an existing DOM element or an identifier.'); } // The element is not an embed iframe? if (element.nodeName !== 'IFRAME') { // check if already present in the element var iframe = element.querySelector('iframe'); if (iframe) { element = iframe; } } return element; } // most Object methods by ES6 should accept primitives var _objectSap = function(KEY, exec){ var fn = (_core.Object || {})[KEY] || Object[KEY] , exp = {}; exp[KEY] = exec(fn); _export(_export.S + _export.F * _fails(function(){ fn(1); }), 'Object', exp); }; // 19.1.2.14 Object.keys(O) _objectSap('keys', function(){ return function keys(it){ return _objectKeys(_toObject(it)); }; }); var keys$1 = _core.Object.keys; var keys = createCommonjsModule(function (module) { module.exports = { "default": keys$1, __esModule: true }; }); var _Object$keys = unwrapExports(keys); // 19.1.3.1 Object.assign(target, source) _export(_export.S + _export.F, 'Object', {assign: _objectAssign}); var assign$1 = _core.Object.assign; var assign = createCommonjsModule(function (module) { module.exports = { "default": assign$1, __esModule: true }; }); var _Object$assign = unwrapExports(assign); /** * Build url for the new iframe * * @param {object} parameters */ function buildIframeUrl(parameters) { var url = parameters.baseUrl || 'https://flat.io/embed'; // Score id or blank embed url += '/' + (parameters.score || 'blank'); // Build qs parameters var urlParameters = _Object$assign({ jsapi: true }, parameters.embedParams); var qs = _Object$keys(urlParameters).map(function (k) { return encodeURIComponent(k) + '=' + encodeURIComponent(urlParameters[k]); }).join('&'); return url + '?' + qs; } /** * Create an iframe inside a specified element * * @param {HTMLElement} element * @param {object} parameters */ function createEmbedIframe(element, parameters) { var url = buildIframeUrl(parameters); var iframe = document.createElement('iframe'); iframe.setAttribute('src', url); iframe.setAttribute('width', parameters.width || '100%'); iframe.setAttribute('height', parameters.height || '100%'); iframe.setAttribute('allowfullscreen', true); iframe.setAttribute('frameborder', '0'); element.appendChild(iframe); return iframe; } /** * Send a message to the embed via postMessage * * @param {Embed} embed * @param {string} method The name of the method to call * @param {string} parameters The parameters to pass to the method */ function postMessage$1(embed, method, parameters) { if (!embed.element.contentWindow || !embed.element.contentWindow.postMessage) { throw new Error('No `contentWindow` or `contentWindow.postMessage` avaialble on the element'); } var message = { method: method, parameters: parameters }; embed.element.contentWindow.postMessage(message, embed.origin); } /** * Parse a message received from postMessage * * @param {string|object} data The data received from postMessage * @return {object} */ function parseMessage(data) { if (typeof data === 'string') { data = JSON.parse(data); } return data; } var EmbedCallback = function () { function EmbedCallback(embed) { _classCallCheck(this, EmbedCallback); this.embed = embed; this.promises = {}; this.eventCallbacks = {}; return this; } _createClass(EmbedCallback, [{ key: "pushCall", value: function pushCall(name, resolve, reject) { this.promises[name] = this.promises[name] || []; this.promises[name].push({ resolve: resolve, reject: reject }); } /** * Register a callback for a specified event * * @param {string} event The name of the event. * @param {function} callback The function to call when receiving an event * @return {boolen} `true` if it is the first subscriber, `false otherwise` */ }, { key: "subscribeEvent", value: function subscribeEvent(event, callback) { this.eventCallbacks[event] = this.eventCallbacks[event] || []; this.eventCallbacks[event].push(callback); return this.eventCallbacks[event].length === 1; } /** * Unregister a callback for a specified event * * @param {string} event The name of the event. * @param {function} [callback] The function to call when receiving an event * @return {boolen} `true` if it is the last subscriber, `false otherwise` */ }, { key: "unsubscribeEvent", value: function unsubscribeEvent(event, callback) { // Was not subscribed if (!this.eventCallbacks[event]) { return false; } // If a callback is specified, unsub this one if (callback) { var idx = this.eventCallbacks[event].indexOf(callback); if (idx >= 0) { this.eventCallbacks[event].splice(idx, 1); } } // Unsub all else { this.eventCallbacks[event] = []; } return !callback || this.eventCallbacks[event].length === 0; } /** * Process a message received from postMessage * * @param {object} data The data received from postMessage */ }, { key: "process", value: function process(data) { if (data.method) { this.processMethodResponse(data); } else if (data.event) { this.processEvent(data); } } /** * Process a method response * * @param {object} data The data received from postMessage */ }, { key: "processMethodResponse", value: function processMethodResponse(data) { var promise = this.promises[data.method].shift(); if (!promise) { return; } if (data.error) { promise.reject(data.error); } else { promise.resolve(data.response); } } /** * Process a receieved event * * @param {object} data The data received from postMessage */ }, { key: "processEvent", value: function processEvent(data) { var _this = this; if (!this.eventCallbacks[data.event] || this.eventCallbacks[data.event].length === 0) { return; } this.eventCallbacks[data.event].forEach(function (callback) { callback.call(_this.embed, data.parameters); }); } }]); return EmbedCallback; }(); var embeds = new _WeakMap(); var embedsReady = new _WeakMap(); var Embed = function () { /** * Create a new Flat Embed * * @param {(HTMLIFrameElement|HTMLElement|string|jQuery)} element A reference to a Flat Embed iframe or a container for the new iframe * @param {object} [params] Parameters for the new iframe * @return {Embed} */ function Embed(element) { var _this = this; var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _classCallCheck(this, Embed); element = normalizeElement(element); // Keep a single object instance per iframe if (embeds.has(element)) { return embeds.get(element); } // Create new element iframe if needed if (element.nodeName !== 'IFRAME') { element = createEmbedIframe(element, params); } this.origin = '*'; this.element = element; this.embedCallback = new EmbedCallback(); var onReady = new _Promise(function (resolve) { // Handle incoming messages from embed var onMessage = function onMessage(event) { if (element.contentWindow !== event.source) { return; } if (_this.origin === '*') { _this.origin = event.origin; } // Parse inbound message var data = parseMessage(event.data); // Mark the embed as ready if (data.event === 'ready' || data.method === 'ping') { resolve(); return; } // Process regular messages from the embed _this.embedCallback.process(data); }; window.addEventListener('message', onMessage, false); postMessage$1(_this, 'ping'); }); embeds.set(this.element, this); embedsReady.set(this, onReady); return this; } _createClass(Embed, [{ key: 'ready', value: function ready() { return _Promise.resolve(embedsReady.get(this)); } }, { key: 'call', value: function call(method) { var _this2 = this; var parameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return new _Promise(function (resolve, reject) { return _this2.ready().then(function () { _this2.embedCallback.pushCall(method, resolve, reject); postMessage$1(_this2, method, parameters); }); }); } /** * Subscribe to a specific event * * @param {string} event The name of the event. * @param {function} callback The function to call when receiving an event */ }, { key: 'on', value: function on(event, callback) { if (typeof event !== 'string') { throw new TypeError('An event name (string) is required'); } if (typeof callback !== 'function') { throw new TypeError('An callback (function) is required'); } if (this.embedCallback.subscribeEvent(event, callback)) { this.call('addEventListener', event).catch(function () {}); } } /** * Unsubscribe to a specific event * * @param {string} event The name of the event. * @param {function} [callback] The function to unsubscribe */ }, { key: 'off', value: function off(event, callback) { if (typeof event !== 'string') { throw new TypeError('An event name (string) is required'); } if (this.embedCallback.unsubscribeEvent(event, callback)) { this.call('removeEventListener', event).catch(function () {}); } } /** * Load a score hosted on Flat * * @param {string} score The unique identifier of the score * @param {string} [revision] The unique identifier of the revision * @return {ReadyPromise} * @reject {ApiError} Unable to load the score */ }, { key: 'loadFlatScore', value: function loadFlatScore(score, revision) { return this.call('loadFlatScore', { score: score, revision: revision }); } /** * Load a MusicXML score * * @param {string} score The MusicXML file * @return {ReadyPromise} * @reject {Error} Unable to load the score */ }, { key: 'loadMusicXML', value: function loadMusicXML(score) { return this.call('loadMusicXML', score); } /** * Load a Flat JSON score * * @param {object|string} score The JSON of the score * @return {ReadyPromise} * @reject {Error} Unable to load the score */ }, { key: 'loadJSON', value: function loadJSON(score) { return this.call('loadJSON', score); } /** * Get the score in Flat JSON format * * @return {ReadyPromise} * @fulfill {object} The Flat data format */ }, { key: 'getJSON', value: function getJSON() { return this.call('getJSON'); } /** * Convert the displayed score in MusicXML * * @param {object} options Conversion options (`compressed`) * @return {ReadyPromise} * @fullfill {string|Uint8Array} MusicXML File * @reject {Error} Conversion error */ }, { key: 'getMusicXML', value: function getMusicXML(options) { var _this3 = this; return new _Promise(function (resolve, reject) { options = options || {}; if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) !== 'object') { return reject(new TypeError('Options must be an object')); } _this3.call('getMusicXML', options).then(function (data) { // Plain XML if (typeof data === 'string') { return resolve(data); } // Compressed, re-create Uint8Array return resolve(new Uint8Array(data.data)); }).catch(reject); }); } /** * Get the metadata of the score (for scores hosted on Flat) * * @return {ReadyPromise} * @fulfill {object} The Flat data format (result from https://flat.io/developers/api/reference/#operation/getScore) */ }, { key: 'getFlatScoreMetadata', value: function getFlatScoreMetadata() { return this.call('getFlatScoreMetadata'); } /** * Toggle fullscreen state * * @param {boolean} active `true` to switch on fullscreen, `false` to switch off * @return {ReadyPromise} Once the state changed */ }, { key: 'fullscreen', value: function fullscreen(active) { return this.call('fullscreen', active); } /** * Start the playback * * @return {ReadyPromise} */ }, { key: 'play', value: function play() { return this.call('play'); } /** * Pause the playback * * @return {ReadyPromise} */ }, { key: 'pause', value: function pause() { return this.call('pause'); } /** * Stop the playback * * @return {ReadyPromise} */ }, { key: 'stop', value: function stop() { return this.call('stop'); } /** * Print the score * * @return {ReadyPromise} */ }, { key: 'print', value: function print() { return this.call('print'); } /** * Get the current zoom ratio * * @return {ReadyPromise} * @fullfill {number} The current scale ratio (0.5 to 3) */ }, { key: 'getZoom', value: function getZoom() { return this.call('getZoom'); } /** * Set a new zoom ratio (this will disable the zoom auto if set) * * @param {number} zoom The scale ratio (0.5 to 3) * @return {ReadyPromise} * @fullfill {number} The scale ratio applied */ }, { key: 'setZoom', value: function setZoom(zoom) { return this.call('setZoom', zoom); } /** * Get the auto-zoom * * @return {ReadyPromise} * @fullfill {boolean} `true` if enabled, `false` if disabled */ }, { key: 'getAutoZoom', value: function getAutoZoom() { return this.call('getAutoZoom'); } /** * Enable or disable the auto-zoom * * @param {boolean} state `true` if enabled, `false` if disabled * @return {ReadyPromise} * @fullfill {boolean} The auto-zoom mode */ }, { key: 'setAutoZoom', value: function setAutoZoom(state) { return this.call('setAutoZoom', state); } }]); return Embed; }(); return Embed; }))); //# sourceMappingURL=embed.js.map
/** * Created by tgdflto1 on 08/01/17. */ $(document).ready(function(){ $('.datetimepicker').datetimepicker({ format: 'd.m.Y H:i', }); });
//http://stackoverflow.com/questions/20101603/how-do-i-convert-between-date-formats-used-by-jquery-ui-datepicker-and-moment-js var dateFormatConverter; (function (dateFormatConverter) { if (!String.prototype.replaceAll) { String.prototype.replaceAll = function (pattern, replacement) { return this.split(pattern).join(replacement); }; } if (!String.prototype.contains) { String.prototype.contains = function (part) { return this.indexOf(part) >= 0; }; } if (!Array.prototype.first) { Array.prototype.first = function (callback) { if (!callback) return this.length ? this[0] : null; for (var i = 0; i < this.length; i++) { var item = this[i]; if (callback(item)) { return item; } } return null; }; } if (!Array.prototype.map) { Array.prototype.map = function (callback, thisArg) { var T, A, k; if (this == null) { throw new TypeError(' this is null or not defined'); } var O = Object(this); var len = O.length >>> 0; if (typeof callback !== 'function') { throw new TypeError(callback + ' is not a function'); } if (arguments.length > 1) { T = thisArg; } A = new Array(len); k = 0; while (k < len) { var kValue, mappedValue; if (k in O) { kValue = O[k]; mappedValue = callback.call(T, kValue, k, O); A[k] = mappedValue; } k++; } return A; }; } if (!Object.keys) { Object.keys = (function () { 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'), dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ], dontEnumsLength = dontEnums.length; return function (obj) { if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) { throw new TypeError('Object.keys called on non-object'); } var result = [], prop, i; for (prop in obj) { if (hasOwnProperty.call(obj, prop)) { result.push(prop); } } if (hasDontEnumBug) { for (i = 0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; }()); } function convert(format, sourceRules, destRules) { if (sourceRules == destRules) return format; format = format || ''; var result = ''; var index = 0; var destTokens = getTokens(destRules); var sourceMap = getTokenMap(getTokens(sourceRules)); while (index < format.length) { var part = locateNextToken(sourceRules, format, index); if (part.literal.length > 0) result += destRules.MakeLiteral(part.literal); if (part.token.length > 0) result += destTokens[sourceMap[part.token]]; index = part.nextBegin; } return result; } dateFormatConverter.convert = convert; function locateNextToken(rules, format, begin) { var literal = ''; var index = begin; var sequence = getTokenSequence(getTokenMap(getTokens(rules))); while (index < format.length) { var escaped = rules.ReadEscapedPart(format, index); if (escaped.length > 0) { literal += escaped.value; index += escaped.length; continue; } var token = sequence.first(function(x) { return format.indexOf(x, index) == index; }); if (!token) { literal += format.charAt(index); index++; continue; } return { token: token, literal: literal, nextBegin: index + token.length }; } return { token: '', literal: literal, nextBegin: index }; } function getTokens(rules) { return [ rules.DayOfMonthShort, rules.DayOfMonthLong, rules.DayOfWeekShort, rules.DayOfWeekLong, rules.DayOfYearShort, rules.DayOfYearLong, rules.MonthOfYearShort, rules.MonthOfYearLong, rules.MonthNameShort, rules.MonthNameLong, rules.YearShort, rules.YearLong, rules.AmPm, rules.Hour24Short, rules.Hour24Long, rules.Hour12Short, rules.Hour12Long, rules.MinuteShort, rules.MinuteLong, rules.SecondShort, rules.SecondLong, rules.FractionalSecond1, rules.FractionalSecond2, rules.FractionalSecond3, rules.TimeZone, rules.UnixTimestamp ].map(function(x) { return x || ''; }); } function getTokenMap(tokens) { var map = {}; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (token) { map[token] = i; } } return map; } function getTokenSequence(map) { var tokens = Object.keys(map); tokens.sort(function(a, b) { return b.length - a.length; }); return tokens; } function indexOfAny(s, chars) { for (var i = 0; i < s.length; i++) { var c = s.charAt(i); for (var j = 0; j < chars.length; j++) { if (c === chars.charAt(j)) return i; } } return -1; } dateFormatConverter.standard = { DayOfMonthShort: 'd', DayOfMonthLong: 'dd', DayOfWeekShort: 'ddd', DayOfWeekLong: 'dddd', DayOfYearShort: 'D', DayOfYearLong: 'DD', MonthOfYearShort: 'M', MonthOfYearLong: 'MM', MonthNameShort: 'MMM', MonthNameLong: 'MMMM', YearShort: 'yy', YearLong: 'yyyy', AmPm: 'tt', Hour24Short: 'H', Hour24Long: 'HH', Hour12Short: 'h', Hour12Long: 'hh', MinuteShort: 'm', MinuteLong: 'mm', SecondShort: 's', SecondLong: 'ss', FractionalSecond1: 'f', FractionalSecond2: 'ff', FractionalSecond3: 'fff', TimeZone: 'Z', UnixTimestamp: 'X', MakeLiteral: function(literal) { var reserved = 'dDMytHhmsfZX'; if (indexOfAny(literal, reserved) < 0) return literal; var result = ''; for (var i = 0; i < literal.length; i++) { var c = literal.charAt(i); if (reserved.contains(c)) result += '\\'; result += c; } return result; }, ReadEscapedPart: function(format, startIndex) { var result = ''; var index = startIndex; while (index < format.length) { var c = format.charAt(index); if (c == '\\') { result += index == format.length - 1 ? '\\' : format[++index]; index++; continue; } break; } return { value: result, length: index - startIndex }; } }; dateFormatConverter.dotNet = { DayOfMonthShort: 'd', DayOfMonthLong: 'dd', DayOfWeekShort: 'ddd', DayOfWeekLong: 'dddd', DayOfYearShort: null, DayOfYearLong: null, MonthOfYearShort: 'M', MonthOfYearLong: 'MM', MonthNameShort: 'MMM', MonthNameLong: 'MMMM', YearShort: 'yy', YearLong: 'yyyy', AmPm: 'tt', Hour24Short: 'H', Hour24Long: 'HH', Hour12Short: 'h', Hour12Long: 'hh', MinuteShort: 'm', MinuteLong: 'mm', SecondShort: 's', SecondLong: 'ss', FractionalSecond1: 'f', FractionalSecond2: 'ff', FractionalSecond3: 'fff', TimeZone: 'zzz', UnixTimestamp: null, MakeLiteral: function(literal) { var reserved = 'dfFghHKmMstyz\'"'; if (indexOfAny(literal, reserved) < 0) return literal; var result = ''; for (var i = 0; i < literal.length; i++) { var c = literal.charAt(i); if (reserved.contains(c)) result += '\\'; result += c; } return result; }, ReadEscapedPart: function(format, startIndex) { var result = ''; var index = startIndex; while (index < format.length) { var c = format.charAt(index); if (c == '\\') { result += index == format.length - 1 ? '\\' : format[++index]; index++; continue; } if (c == '"') { while (++index < format.length) { var cc = format.charAt(index); if (cc == '"') break; if (cc == '\\') { result += index == format.length - 1 ? '\\' : format[++index]; } else { result += cc; } } index++; continue; } if (c == "'") { while (++index < format.length) { var cc = format.charAt(index); if (cc == "'") break; if (cc == '\\') { result += index == format.length - 1 ? '\\' : format[++index]; } else { result += cc; } } index++; continue; } break; } return { value: result, length: index - startIndex }; } }; dateFormatConverter.momentJs = { DayOfMonthShort: 'D', DayOfMonthLong: 'DD', DayOfWeekShort: 'ddd', DayOfWeekLong: 'dddd', DayOfYearShort: 'DDD', DayOfYearLong: 'DDDD', MonthOfYearShort: 'M', MonthOfYearLong: 'MM', MonthNameShort: 'MMM', MonthNameLong: 'MMMM', YearShort: 'YY', YearLong: 'YYYY', AmPm: 'A', Hour24Short: 'H', Hour24Long: 'HH', Hour12Short: 'h', Hour12Long: 'hh', MinuteShort: 'm', MinuteLong: 'mm', SecondShort: 's', SecondLong: 'ss', FractionalSecond1: 'S', FractionalSecond2: 'SS', FractionalSecond3: 'SSS', TimeZone: 'Z', UnixTimestamp: 'X', MakeLiteral: function(literal) { var reserved = 'MoDdeEwWYgGAaHhmsSzZX'; literal = literal.replaceAll("[", "(").replaceAll("]", ")"); if (indexOfAny(literal, reserved) < 0) return literal; return '[' + literal + ']'; }, ReadEscapedPart: function(format, startIndex) { if (format.charAt(startIndex) != '[') return { value: '', length: 0 }; var result = ''; var index = startIndex; while (index < format.length) { var c = format.charAt(index); if (c == ']') { break; } result += c; } return { value: result, length: index - startIndex }; } }; })(dateFormatConverter || (dateFormatConverter = {})); $(document).ready(function () { $.each($('h3>a'), function (i, v) { var title = $(v).attr('title'); if (title!=null && !title.trim()) { $(v).attr('title', $(v).text()); } }); });
asynctest( 'browser.tinymce.plugins.preview.PreviewContentStyleTest', [ 'ephox.agar.api.Pipeline', 'ephox.agar.api.RawAssertions', 'ephox.agar.api.Step', 'ephox.mcagar.api.TinyApis', 'ephox.mcagar.api.TinyLoader', 'tinymce.plugins.preview.Plugin', 'tinymce.plugins.preview.ui.IframeContent', 'tinymce.themes.modern.Theme' ], function (Pipeline, RawAssertions, Step, TinyApis, TinyLoader, PreviewPlugin, IframeContent, ModernTheme) { var success = arguments[arguments.length - 2]; var failure = arguments[arguments.length - 1]; ModernTheme(); PreviewPlugin(); var assertIframeContains = function (editor, text, expected) { var actual = IframeContent.getPreviewHtml(editor); var regexp = new RegExp(text); RawAssertions.assertEq('Should be same html', expected, regexp.test(actual)); }; var sAssertIframeHtmlContains = function (editor, text) { return Step.sync(function () { assertIframeContains(editor, text, true); }); }; var sAssertIframeHtmlNotContains = function (editor, text) { return Step.sync(function () { assertIframeContains(editor, text, false); }); }; TinyLoader.setup(function (editor, onSuccess, onFailure) { var tinyApis = TinyApis(editor); Pipeline.async({}, [ tinyApis.sSetContent('<p>hello world</p>'), tinyApis.sSetSetting('content_style', 'p {color: blue;}'), sAssertIframeHtmlContains(editor, '<style type="text/css">p {color: blue;}</style>'), tinyApis.sDeleteSetting('content_style'), sAssertIframeHtmlNotContains(editor, '<style type="text/css">p {color: blue;}</style>') ], onSuccess, onFailure); }, { plugins: 'preview', skin_url: '/project/src/skins/lightgray/dist/lightgray' }, success, failure); } );
/** * @ngdoc controller * @name Umbraco.PrevalueEditors.ListViewLayoutsPreValsController * @function * * @description * The controller for configuring layouts for list views */ (function() { "use strict"; function ListViewLayoutsPreValsController($scope, editorService) { var vm = this; vm.focusLayoutName = false; vm.layoutsSortableOptions = { distance: 10, tolerance: "pointer", opacity: 0.7, scroll: true, cursor: "move", handle: ".list-view-layout__sort-handle" }; vm.addLayout = addLayout; vm.showPrompt = showPrompt; vm.hidePrompt = hidePrompt; vm.removeLayout = removeLayout; vm.openIconPicker = openIconPicker; function addLayout() { vm.focusLayoutName = false; var layout = { "name": "", "path": "", "icon": "icon-stop", "selected": true }; $scope.model.value.push(layout); } function showPrompt(layout) { layout.deletePrompt = true; } function hidePrompt(layout) { layout.deletePrompt = false; } function removeLayout($index, layout) { $scope.model.value.splice($index, 1); } function openIconPicker(layout) { var iconPicker = { icon: layout.icon.split(' ')[0], color: layout.icon.split(' ')[1], submit: function (model) { if (model.icon) { if (model.color) { layout.icon = model.icon + " " + model.color; } else { layout.icon = model.icon; } } vm.focusLayoutName = true; editorService.close(); }, close: function() { editorService.close(); } }; editorService.iconPicker(iconPicker); } } angular.module("umbraco").controller("Umbraco.PrevalueEditors.ListViewLayoutsPreValsController", ListViewLayoutsPreValsController); })();
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M5 19h14V5H5v14zM16.5 6c.83 0 1.5.67 1.5 1.5S17.33 9 16.5 9 15 8.33 15 7.5 15.67 6 16.5 6zm0 9c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5-1.5-.67-1.5-1.5.67-1.5 1.5-1.5zM12 10.5c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5-1.5-.67-1.5-1.5.67-1.5 1.5-1.5zM7.5 6C8.33 6 9 6.67 9 7.5S8.33 9 7.5 9 6 8.33 6 7.5 6.67 6 7.5 6zm0 9c.83 0 1.5.67 1.5 1.5S8.33 18 7.5 18 6 17.33 6 16.5 6.67 15 7.5 15z" opacity=".3" /><path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14z" /><circle cx="7.5" cy="16.5" r="1.5" /><circle cx="7.5" cy="7.5" r="1.5" /><circle cx="12" cy="12" r="1.5" /><circle cx="16.5" cy="16.5" r="1.5" /><circle cx="16.5" cy="7.5" r="1.5" /></React.Fragment> , 'CasinoTwoTone');
CKEDITOR.plugins.setLang('oembed', 'ru', { title: "Внедрить медиа-контент (видео, аудио, фото и т.д.)", button: "Внедрить медиа-контент с различных сайтов", pasteUrl: "Вставьте ссылку на страницу с медиа-контентом (например YouTube, Flickr, Qik, Vimeo, Hulu, Viddler, MyOpera, и т.д.)", invalidUrl: "Вы ввели некорректный URL", noEmbedCode: "Не обнаружен код для вставки. Возможно, вы ввели ссылку с неподдерживаемого сайта.", embedTitle: "Title (or aria-label) <span class='oembed-required'>[Required]</span>:", url: "URL <span class='oembed-required'>[Required]</span>:", width: "Ширина:", height: "Высота:", widthTitle: "Ширина внедряемого медиа-контента", heightTitle: "Высота внедряемого медиа-контента", maxWidth: "Макс. ширина:", maxHeight: "Макс. высота:", maxWidthTitle: "Максимальная ширина внедряемого медиа-контента", maxHeightTitle: "Максимальная высота внедряемого медиа-контента", resizeType: "Изменение размера (только для видео):", none: 'None', noresize: "Без изменения (стандартный размер)", responsive: "Задать максимальный размер", custom: "Задать конкретный размер", noVimeo: "Владелец этого видео установил ограничения на домен, и вы не можете его встроить на ваш сайт.", Error: "Невозможно получить медиа-контент. Попробуйте другой URL.", titleError: "Media Title is required to meet accessibility standards." });
/* * Checkbox control * */ (function($) { $(document).on('keydown', 'div.custom-checkbox', function(e) { if (e.keyCode == 32) e.preventDefault() }) $(document).on('keyup', 'div.custom-checkbox', function(e) { if (e.keyCode == 32) { var $cb = $('input', this) if ($cb.data('oc-space-timestamp') == e.timeStamp) return $cb.get(0).checked = !$cb.get(0).checked $cb.data('oc-space-timestamp', e.timeStamp) $cb.trigger('change') return false } }) // // Intermediate checkboxes // $(document).render(function() { $('div.custom-checkbox.is-indeterminate > input').each(function() { var $el = $(this), checked = $el.data('checked') switch (checked) { // Unchecked case 1: $el.prop('indeterminate', true) break // Checked case 2: $el.prop('indeterminate', false) $el.prop('checked', true) break // Unchecked default: $el.prop('indeterminate', false) $el.prop('checked', false) } }) }) $(document).on('click', 'div.custom-checkbox.is-indeterminate > label', function() { var $el = $(this).parent().find('input:first'), checked = $el.data('checked') if (checked === undefined) { checked = $el.is(':checked') ? 1 : 0 } switch (checked) { // Unchecked, going indeterminate case 0: $el.data('checked', 1) $el.prop('indeterminate', true) break // Indeterminate, going checked case 1: $el.data('checked', 2) $el.prop('indeterminate', false) $el.prop('checked', true) break // Checked, going unchecked default: $el.data('checked', 0) $el.prop('indeterminate', false) $el.prop('checked', false) } $el.trigger('change') return false }) })(jQuery);
/*! { "name": "Shared Workers", "property": "sharedworkers", "caniuse" : "sharedworkers", "tags": ["performance", "workers"], "builderAliases": ["workers_sharedworkers"], "notes": [{ "name": "W3C Reference", "href": "http://www.w3.org/TR/workers/" }] } !*/ /* DOC Detects support for the `SharedWorker` API from the Web Workers spec. */ define(['Modernizr'], function( Modernizr ) { Modernizr.addTest('sharedworkers', 'SharedWorker' in window); });
/* * Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com) * * sisane: The stunning micro-library that helps you to develop easily * AJAX web applications by using Angular.js 1.x & sisane-server * sisane is distributed under the MIT License (MIT) * Sources at https://github.com/rafaelaznar/ * * 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'; moduloTipomuestra.controller('TipomuestraEditController', ['$scope', '$routeParams', '$location', 'tipomuestraService', 'serverService', 'sharedSpaceService', '$filter', '$uibModal', function ($scope, $routeParams, $location, tipomuestraService, serverService, sharedSpaceService, $filter, $uibModal) { $scope.fields = tipomuestraService.getFields(); $scope.obtitle = tipomuestraService.getObTitle(); $scope.icon = tipomuestraService.getIcon(); $scope.ob = tipomuestraService.getTitle(); $scope.title = "Editando " + $scope.obtitle; $scope.op = "plist"; $scope.status = null; $scope.error = true; $scope.debugging = serverService.debugging(); $scope.id = $routeParams.id; //--------------------------------- serverService.promise_getOne($scope.ob, $scope.id).then(function (response) { if (response.status == 200) { if (response.data.status == 200) { $scope.status = null; $scope.bean = response.data.message; } else { $scope.status = "Error en la recepción de datos del servidor"; } } else { $scope.status = "Error en la recepción de datos del servidor"; } }).catch(function (data) { $scope.status = "Error en la recepción de datos del servidor"; }); $scope.save = function () { $scope.bean.creation = $filter('date')($scope.bean.creation, "dd/MM/yyyy"); $scope.bean.modification = $filter('date')($scope.bean.modification, "dd/MM/yyyy"); var jsonToSend = {json: JSON.stringify(serverService.array_identificarArray($scope.bean))}; serverService.promise_setOne($scope.ob, jsonToSend).then(function (response) { if (response.status == 200) { if (response.data.status == 200) { $scope.response = response; $scope.status = "El registro " + $scope.obtitle + " se ha modificado ... id = " + $scope.bean.id; $scope.bean.id = $scope.bean.id; } else { $scope.status = "Error en la recepción de datos del servidor"; } } else { $scope.status = "Error en la recepción de datos del servidor"; } }).catch(function (data) { $scope.status = "Error en la recepción de datos del servidor"; }); ; }; $scope.back = function () { window.history.back(); }; $scope.close = function () { $location.path('/home'); }; $scope.plist = function () { $location.path('/' + $scope.ob + '/plist'); }; $scope.chooseOne = function (nameForeign, foreignObjectName, contollerName) { var modalInstance = $uibModal.open({ templateUrl: 'js/' + foreignObjectName + '/selection.html', controller: contollerName, size: 'lg' }).result.then(function (modalResult) { $scope.bean[nameForeign].id = modalResult; }); }; }]);
describe('standalone', function () { uit.url('../ui/fixtures/test-fixture-standalone.html'); it('should work in standalone mode and call the mobileInit function', function () { uit.append(function($) { var page = $('#start'); page.append('<div data-role="content">' + '<ul data-role="listview" ng-init="list=[1,2,3]" id="list">' + '<li ng-repeat="l in list">{{l}}</li>' + '</ul>' + '</div>'); }); uit.runs(function (window, $) { expect(window.mobileInitTest).toBe(true); var list = $("#list"); var lis = list.children(); expect(lis.length).toBe(3); for (var i = 0; i < 3; i++) { expect(lis.eq(i).hasClass("ui-li")).toBe(true); } }); }); });
/*global QUnit*/ import Emblem from '../../emblem'; import { w } from '../support/utils'; import { compilesTo } from '../support/integration-assertions'; QUnit.module("html: single line"); QUnit.test("element only", function(){ compilesTo("p", "<p></p>"); }); QUnit.test("with text", function(){ compilesTo("p Hello", "<p>Hello</p>"); }); QUnit.test("with more complex text", function(){ compilesTo( "p Hello, how's it going with you today?", "<p>Hello, how's it going with you today?</p>" ); }); QUnit.test("with inline html", function(){ compilesTo( "p Hello, how are you <strong>man</strong>", "<p>Hello, how are you <strong>man</strong></p>" ); }); QUnit.test("with trailing space", function(){ compilesTo("p Hello ", "<p>Hello </p>"); }); QUnit.test("can start with angle bracket html", function(){ var emblem = "<span>Hello</span>"; compilesTo(emblem, "<span>Hello</span>"); }); QUnit.module("html: multiple lines"); QUnit.test("two lines", function(){ var emblem = w( "p This is", " pretty cool." ); compilesTo(emblem, "<p>This is pretty cool.</p>"); }); QUnit.test("three lines", function(){ var emblem = w( "p This is", " pretty damn", " cool." ); compilesTo(emblem, "<p>This is pretty damn cool.</p>"); }); QUnit.test("three lines w/ embedded html", function(){ var emblem = w( "p This is", " pretty <span>damn</span>", " cool." ); compilesTo(emblem, "<p>This is pretty <span>damn</span> cool.</p>"); }); QUnit.test("indentation doesn't need to match starting inline content's", function(){ var emblem = w( " span Hello,", " How are you?" ); compilesTo(emblem, "<span>Hello, How are you?</span>"); }); QUnit.test("indentation may vary between parent/child, must be consistent within inline-block", function(){ var emblem = w( "div", " span Hello,", " How are you?", " Excellent.", " p asd" ); compilesTo(emblem, "<div><span>Hello, How are you? Excellent.</span><p>asd</p></div>"); emblem = w( "div", " span Hello,", " How are you?", " Excellent." ); QUnit.throws(function(){ Emblem.compile(emblem); }); }); QUnit.test("indentation may vary between parent/child, must be consistent within inline-block pt 2", function(){ var emblem = w( "div", " span Hello,", " How are you?", " Excellent." ); compilesTo(emblem, "<div><span>Hello, How are you? Excellent.</span></div>"); }); QUnit.test("w/ mustaches", function(){ var emblem = w( "div", " span Hello,", " {{foo}} are you?", " Excellent." ); compilesTo(emblem, "<div><span>Hello, {{foo}} are you? Excellent.</span></div>"); }); QUnit.test("with followup", function(){ var emblem = w( "p This is", " pretty cool.", "p Hello." ); compilesTo(emblem, "<p>This is pretty cool.</p><p>Hello.</p>"); }); QUnit.test("can start with angle bracket html and go to multiple lines", function(){ var emblem = w( "<span>Hello dude,", " what's up?</span>" ); compilesTo(emblem, "<span>Hello dude, what's up?</span>"); }); QUnit.module("html: nested"); test("basic", function(){ var emblem = w( "p", " span Hello", " strong Hi", "div", " p Hooray" ); compilesTo(emblem, '<p><span>Hello</span><strong>Hi</strong></p><div><p>Hooray</p></div>'); }); test("empty nest", function(){ var emblem = w( "p", " span", " strong", " i" ); compilesTo(emblem, '<p><span><strong><i></i></strong></span></p>'); }); test("empty nest w/ attribute shorthand", function(){ var emblem = w( "p.woo", " span#yes", " strong.no.yes", " i" ); compilesTo(emblem, '<p class="woo"><span id="yes"><strong class="no yes"><i></i></strong></span></p>'); }); QUnit.module("html: self-closing html tags"); test("br", function() { var emblem; emblem = "br"; compilesTo(emblem, '<br>'); }); test("hr", function(assert) { var emblem; emblem = "hr"; compilesTo(emblem, '<hr>'); }); test("br paragraph example", function() { var emblem; emblem = "p\n | LOL!\n br\n | BORF!"; compilesTo(emblem, '<p>LOL!<br>BORF!</p>'); }); test("input", function() { var emblem; emblem = "input type=\"text\""; compilesTo(emblem, '<input type="text">'); }); test("nested content under self-closing tag should fail", function() { var emblem = "hr\n | here is text"; QUnit.throws( function(){ Emblem.compile(emblem); }, /cannot nest/i); });
define(function defineFocusTrap(require) { 'use strict'; /* Trap focus within a given element, wrapping focus to first/last element when boundaries are hit. This is useful when making sure that you cannot escape a modal dialog. trapFocus(context) returns a function to disengage containing the focus. This function is also exposed on context._untrapFocusHandler; Having multiple (nested) contexts containing the focus is technically not possible. Note: It is, unlike the native <dialog> implementation in Blink, not possible to tab to the browser chrome while focusContain() is active. see http://www.w3.org/WAI/PF/aria-practices/#trap_focus_div */ var queryTabbable = require('../dom/query-tabbable'); var focusFirst = require('./first'); var trapByFocusEvent = require('./trap.focusevent'); var trapByKeyEvent = require('./trap.keyevent'); var observeBodyFocus = require('./trap.observe-body'); var canDispatchFocusout = require('../supports/focusout-event'); function trapFocus(context, _focusFirst) { var _handle = trapByFocusEvent.bind(context); var _event = 'focusout'; var _capture = true; // Gecko and Trident don't expose relatedTarget on blur events and it does not support focusout // so there is no way to react to a focus event before it actually happened. We cannot // focus another element in a focus handler, because that would emit two FocusEvents to // the Accessibility API and cause screen readers to alert two focus changes where only // one should've happened. That's why we intercept the KeyEvent and do things manually… // Gecko: https://bugzilla.mozilla.org/show_bug.cgi?id=687787 (implement FocusEvent(focusout)) // Gecko: https://bugzilla.mozilla.org/show_bug.cgi?id=962251 (no FocusEvent(blur).relatedTarget) // Trident: https://connect.microsoft.com/IE/Feedback/Details/814285 (no FocusEvent(blur).relatedTarget) // Blink: https://code.google.com/p/chromium/issues/detail?id=378163 (about to remove FocusEvent(focusout)?) if (!context.compareDocumentPosition || !canDispatchFocusout) { _handle = trapByKeyEvent.bind(context); _event = 'keydown'; _capture = false; // unlike focusout the keyevents can't detect when context lost focus observeBodyFocus(context); } var sequence = queryTabbable(context); if (!sequence.length) { // cannot contain focus in something without anything to focus return null; } context.addEventListener(_event, _handle, _capture); context._untrapFocusHandler = function untrapFocus() { context.removeEventListener(_event, _handle, _capture); delete context._untrapFocusHandler; context._undoObserveBodyFocus && context._undoObserveBodyFocus(); context._undoCaptureBodyFocus && context._undoCaptureBodyFocus(); }; if (_focusFirst) { focusFirst(sequence); } return context._untrapFocusHandler; } return trapFocus; });
/* @flow */ import createRenderer from './createRenderer' import combineRules from './combineRules' import enhance from './enhance' export { createRenderer, combineRules, enhance }
import TestResolverApplicationTestCase from './test-resolver-application'; import Application from '@ember/application'; import { Router } from '@ember/-internals/routing'; import { runTask, runLoopSettled } from '../run'; export default class ApplicationTestCase extends TestResolverApplicationTestCase { constructor() { super(...arguments); let { applicationOptions } = this; this.application = runTask(this.createApplication.bind(this, applicationOptions)); this.resolver = this.application.__registry__.resolver; if (this.resolver) { this.resolver.add('router:main', Router.extend(this.routerOptions)); } } createApplication(myOptions = {}, MyApplication = Application) { return MyApplication.create(myOptions); } get applicationOptions() { return Object.assign(super.applicationOptions, { autoboot: false, }); } get appRouter() { return this.applicationInstance.lookup('router:main'); } get currentURL() { return this.appRouter.get('currentURL'); } async transitionTo() { await this.appRouter.transitionTo(...arguments); await runLoopSettled(); } controllerFor(name) { return this.applicationInstance.lookup(`controller:${name}`); } }
var createHtml = function (settings) { var viewportStyle = ' style="height:' + (settings.viewportHeight || 200) + 'px"'; var itemStyle = settings.itemHeight ? ' style="height:' + settings.itemHeight + 'px"' : ''; var bufferSize = settings.bufferSize ? ' buffer-size="' + settings.bufferSize + '"' : ''; var isLoading = settings.isLoading ? ' is-loading="' + settings.isLoading + '"' : ''; var adapter = settings.adapter ? ' adapter="' + settings.adapter + '"' : ''; var template = settings.template ? settings.template : '{{$index}}: {{item}}'; return '<div ui-scroll-viewport' + viewportStyle + '>' + '<div ui-scroll="item in ' + settings.datasource + '"' + adapter + itemStyle + bufferSize + isLoading + '>' + template + '</div>' + '</div>'; }; var runTest = function (scrollSettings, run, options) { inject(function ($rootScope, $compile, $window, $timeout) { var scroller = angular.element(createHtml(scrollSettings)); var scope = $rootScope.$new(); angular.element(document).find('body').append(scroller); $compile(scroller)(scope); scope.$apply(); $timeout.flush(); run(scroller, scope, $timeout); scroller.remove(); if (options && typeof options.cleanupTest === 'function') { options.cleanupTest(scroller, scope, $timeout); } } ); };
'use strict'; import app from '../..'; import User from './user.model'; var user; var genUser = function() { user = new User({ provider: 'local', name: 'Fake User', email: 'test@example.com', password: 'password' }); return user; }; describe('User Model', function() { before(function() { // Clear users before testing return User.remove(); }); beforeEach(function() { genUser(); }); afterEach(function() { return User.remove(); }); it('should begin with no users', function() { return User.find({}).exec().should .eventually.have.length(0); }); it('should fail when saving a duplicate user', function() { return user.save() .then(function() { var userDup = genUser(); return userDup.save(); }).should.be.rejected; }); describe('#email', function() { it('should fail when saving with a blank email', function() { user.email = ''; return user.save().should.be.rejected; }); it('should fail when saving with a null email', function() { user.email = null; return user.save().should.be.rejected; }); it('should fail when saving without an email', function() { user.email = undefined; return user.save().should.be.rejected; }); }); describe('#password', function() { it('should fail when saving with a blank password', function() { user.password = ''; return user.save().should.be.rejected; }); it('should fail when saving with a null password', function() { user.password = null; return user.save().should.be.rejected; }); it('should fail when saving without a password', function() { user.password = undefined; return user.save().should.be.rejected; }); describe('given the user has been previously saved', function() { beforeEach(function() { return user.save(); }); it('should authenticate user if valid', function() { user.authenticate('password').should.be.true; }); it('should not authenticate user if invalid', function() { user.authenticate('blah').should.not.be.true; }); it('should remain the same hash unless the password is updated', function() { user.name = 'Test User'; return user.save() .then(function(u) { return u.authenticate('password'); }).should.eventually.be.true; }); }); }); });
(function() { "use strict"; var TRANSITION_FALLBACK_DURATION = 500; var hideElement = function(el) { if (! el) { return; } var removeThis = function() { if (el && el.parentNode) { el.parentNode.removeChild(el); } }; el.classList.remove("show"); el.classList.add("hide"); el.addEventListener("transitionend", removeThis); // Fallback for no transitions. setTimeout(removeThis, TRANSITION_FALLBACK_DURATION); }; function Alertify() { /** * Alertify private object * @type {Object} */ var _alertify = { parent: document.body, version: "1.0.10", defaultOkLabel: "Ok", okLabel: "Ok", defaultCancelLabel: "Cancel", cancelLabel: "Cancel", defaultMaxLogItems: 2, maxLogItems: 2, promptValue: "", promptPlaceholder: "", closeLogOnClick: false, closeLogOnClickDefault: false, delay: 5000, defaultDelay: 5000, logContainerClass: "alertify-logs", logContainerDefaultClass: "alertify-logs", dialogs: { buttons: { holder: "<nav>{{buttons}}</nav>", ok: "<button class='ok' tabindex='1'>{{ok}}</button>", cancel: "<button class='cancel' tabindex='2'>{{cancel}}</button>" }, input: "<input type='text'>", message: "<p class='msg'>{{message}}</p>", log: "<div class='{{class}}'>{{message}}</div>" }, defaultDialogs: { buttons: { holder: "<nav>{{buttons}}</nav>", ok: "<button class='ok' tabindex='1'>{{ok}}</button>", cancel: "<button class='cancel' tabindex='2'>{{cancel}}</button>" }, input: "<input type='text'>", message: "<p class='msg'>{{message}}</p>", log: "<div class='{{class}}'>{{message}}</div>" }, /** * Build the proper message box * * @param {Object} item Current object in the queue * * @return {String} An HTML string of the message box */ build: function(item) { var btnTxt = this.dialogs.buttons.ok; var html = "<div class='dialog'>" + "<div>" + this.dialogs.message.replace("{{message}}", item.message); if(item.type === "confirm" || item.type === "prompt") { btnTxt = this.dialogs.buttons.cancel + this.dialogs.buttons.ok; } if (item.type === "prompt") { html += this.dialogs.input; } html = (html + this.dialogs.buttons.holder + "</div>" + "</div>") .replace("{{buttons}}", btnTxt) .replace("{{ok}}", this.okLabel) .replace("{{cancel}}", this.cancelLabel); return html; }, setCloseLogOnClick: function(bool) { this.closeLogOnClick = !! bool; }, /** * Close the log messages * * @param {Object} elem HTML Element of log message to close * @param {Number} wait [optional] Time (in ms) to wait before automatically hiding the message, if 0 never hide * * @return {undefined} */ close: function(elem, wait) { if (this.closeLogOnClick) { elem.addEventListener("click", function(ev) { hideElement(ev.srcElement); }); } wait = wait && !isNaN(+wait) ? +wait : this.delay; if (wait < 0) { hideElement(elem); } else if(wait > 0) { setTimeout(function() { hideElement(elem); }, wait); } }, /** * Create a dialog box * * @param {String} message The message passed from the callee * @param {String} type Type of dialog to create * @param {Function} onOkay [Optional] Callback function when clicked okay. * @param {Function} onCancel [Optional] Callback function when cancelled. * * @return {Object} */ dialog: function(message, type, onOkay, onCancel) { return this.setup({ type: type, message: message, onOkay: onOkay, onCancel: onCancel }); }, /** * Show a new log message box * * @param {String} message The message passed from the callee * @param {String} type [Optional] Optional type of log message * @param {Number} wait [Optional] Time (in ms) to wait before auto-hiding the log * * @return {Object} */ log: function(message, type, click) { var existing = document.querySelectorAll(".alertify-logs > div"); if (existing) { var diff = existing.length - this.maxLogItems; if (diff >= 0) { for (var i = 0, _i = diff + 1; i < _i; i++) { this.close(existing[i], -1); } } } this.notify(message, type, click); }, setLogPosition: function(str) { this.logContainerClass = "alertify-logs " + str; }, setupLogContainer: function() { var elLog = document.querySelector(".alertify-logs"); var className = this.logContainerClass; if (! elLog) { elLog = document.createElement("div"); elLog.className = className; this.parent.appendChild(elLog); } // Make sure it's positioned properly. if (elLog.className !== className) { elLog.className = className; } return elLog; }, /** * Add new log message * If a type is passed, a class name "{type}" will get added. * This allows for custom look and feel for various types of notifications. * * @param {String} message The message passed from the callee * @param {String} type [Optional] Type of log message * @param {Number} wait [Optional] Time (in ms) to wait before auto-hiding * * @return {undefined} */ notify: function(message, type, click) { var elLog = this.setupLogContainer(); var log = document.createElement("div"); log.className = (type || "default"); if (_alertify.logTemplateMethod) { log.innerHTML = _alertify.logTemplateMethod(message); } else { log.innerHTML = message; } // Add the click handler, if specified. if ("function" === typeof click) { log.addEventListener("click", click); } elLog.appendChild(log); setTimeout(function() { log.className += " show"; }, 10); this.close(log, this.delay); }, /** * Initiate all the required pieces for the dialog box * * @return {undefined} */ setup: function(item) { var el = document.createElement("div"); el.className = "alertify hide"; el.innerHTML = this.build(item); var btnOK = el.querySelector(".ok"); var btnCancel = el.querySelector(".cancel"); var input = el.querySelector("input"); var label = el.querySelector("label"); // Set default value/placeholder of input if (input) { if (typeof this.promptPlaceholder === "string") { // Set the label, if available, for MDL, etc. if (label) { label.textContent = this.promptPlaceholder; } else { input.placeholder = this.promptPlaceholder; } } if (typeof this.promptValue === "string") { input.value = this.promptValue; } } function setupHandlers(resolve) { if ("function" !== typeof resolve) { // promises are not available so resolve is a no-op resolve = function () {}; } if (btnOK) { btnOK.addEventListener("click", function(ev) { if (item.onOkay && "function" === typeof item.onOkay) { if (input) { item.onOkay(input.value, ev); } else { item.onOkay(ev); } } if (input) { resolve({ buttonClicked: "ok", inputValue: input.value, event: ev }); } else { resolve({ buttonClicked: "ok", event: ev }); } hideElement(el); }); } if (btnCancel) { btnCancel.addEventListener("click", function(ev) { if (item.onCancel && "function" === typeof item.onCancel) { item.onCancel(ev); } resolve({ buttonClicked: "cancel", event: ev }); hideElement(el); }); } } var promise; if (typeof Promise === "function") { promise = new Promise(setupHandlers); } else { setupHandlers(); } this.parent.appendChild(el); setTimeout(function() { el.classList.remove("hide"); if(input && item.type && item.type === "prompt") { input.select(); input.focus(); } else { if (btnOK) { btnOK.focus(); } } }, 100); return promise; }, okBtn: function(label) { this.okLabel = label; return this; }, setDelay: function(time) { time = time || 0; this.delay = isNaN(time) ? this.defaultDelay : parseInt(time, 10); return this; }, cancelBtn: function(str) { this.cancelLabel = str; return this; }, setMaxLogItems: function(num) { this.maxLogItems = parseInt(num || this.defaultMaxLogItems); }, theme: function(themeStr) { switch(themeStr.toLowerCase()) { case "bootstrap": this.dialogs.buttons.ok = "<button class='ok btn btn-primary' tabindex='1'>{{ok}}</button>"; this.dialogs.buttons.cancel = "<button class='cancel btn btn-default' tabindex='2'>{{cancel}}</button>"; this.dialogs.input = "<input type='text' class='form-control'>"; break; case "purecss": this.dialogs.buttons.ok = "<button class='ok pure-button' tabindex='1'>{{ok}}</button>"; this.dialogs.buttons.cancel = "<button class='cancel pure-button' tabindex='2'>{{cancel}}</button>"; break; case "mdl": case "material-design-light": this.dialogs.buttons.ok = "<button class='ok mdl-button mdl-js-button mdl-js-ripple-effect' tabindex='1'>{{ok}}</button>"; this.dialogs.buttons.cancel = "<button class='cancel mdl-button mdl-js-button mdl-js-ripple-effect' tabindex='2'>{{cancel}}</button>"; this.dialogs.input = "<div class='mdl-textfield mdl-js-textfield'><input class='mdl-textfield__input'><label class='md-textfield__label'></label></div>"; break; case "angular-material": this.dialogs.buttons.ok = "<button class='ok md-primary md-button' tabindex='1'>{{ok}}</button>"; this.dialogs.buttons.cancel = "<button class='cancel md-button' tabindex='2'>{{cancel}}</button>"; this.dialogs.input = "<div layout='column'><md-input-container md-no-float><input type='text'></md-input-container></div>"; break; case "default": default: this.dialogs.buttons.ok = this.defaultDialogs.buttons.ok; this.dialogs.buttons.cancel = this.defaultDialogs.buttons.cancel; this.dialogs.input = this.defaultDialogs.input; break; } }, reset: function() { this.parent = document.body; this.theme("default"); this.okBtn(this.defaultOkLabel); this.cancelBtn(this.defaultCancelLabel); this.setMaxLogItems(); this.promptValue = ""; this.promptPlaceholder = ""; this.delay = this.defaultDelay; this.setCloseLogOnClick(this.closeLogOnClickDefault); this.setLogPosition("bottom left"); this.logTemplateMethod = null; }, injectCSS: function() { if (!document.querySelector("#alertifyCSS")) { var head = document.getElementsByTagName("head")[0]; var css = document.createElement("style"); css.type = "text/css"; css.id = "alertifyCSS"; css.innerHTML = "/* style.css */"; head.insertBefore(css, head.firstChild); } }, removeCSS: function() { var css = document.querySelector("#alertifyCSS"); if (css && css.parentNode) { css.parentNode.removeChild(css); } } }; _alertify.injectCSS(); return { _$$alertify: _alertify, parent: function(elem) { _alertify.parent = elem; }, reset: function() { _alertify.reset(); return this; }, alert: function(message, onOkay, onCancel) { return _alertify.dialog(message, "alert", onOkay, onCancel) || this; }, confirm: function(message, onOkay, onCancel) { return _alertify.dialog(message, "confirm", onOkay, onCancel) || this; }, prompt: function(message, onOkay, onCancel) { return _alertify.dialog(message, "prompt", onOkay, onCancel) || this; }, log: function(message, click) { _alertify.log(message, "default", click); return this; }, theme: function(themeStr) { _alertify.theme(themeStr); return this; }, success: function(message, click) { var symbol = '<p><i class="material-icons mdl-color-text--green f-left m-r-5">check_circle</i>'; _alertify.log(symbol + message + '</p>', "success", click); return this; }, error: function(message, click) { var symbol = '<p><i class="material-icons mdl-color-text--red f-left m-r-5">error</i>'; _alertify.log(symbol + message + '</p>', "error", click); return this; }, cancelBtn: function(label) { _alertify.cancelBtn(label); return this; }, okBtn: function(label) { _alertify.okBtn(label); return this; }, delay: function(time) { _alertify.setDelay(time); return this; }, placeholder: function(str) { _alertify.promptPlaceholder = str; return this; }, defaultValue: function(str) { _alertify.promptValue = str; return this; }, maxLogItems: function(num) { _alertify.setMaxLogItems(num); return this; }, closeLogOnClick: function(bool) { _alertify.setCloseLogOnClick(!! bool); return this; }, logPosition: function(str) { _alertify.setLogPosition(str || ""); return this; }, setLogTemplate: function(templateMethod) { _alertify.logTemplateMethod = templateMethod; return this; }, clearLogs: function() { _alertify.setupLogContainer().innerHTML = ""; return this; }, version: _alertify.version }; } // AMD, window, and NPM support if ("undefined" !== typeof module && !! module && !! module.exports) { // Preserve backwards compatibility module.exports = function() { return new Alertify(); }; var obj = new Alertify(); for (var key in obj) { module.exports[key] = obj[key]; } } else if (typeof define === "function" && define.amd) { define(function() { return new Alertify(); }); } else { window.alertify = new Alertify(); } }());
define({ "setSelectionColor": "Đặt màu lựa chọn", "selectionMode": "Chế độ lựa chọn tương tác", "partiallyWithin": "Một phần trong", "whollyWithin": "Toàn bộ trong", "allowExport": "Cho phép xuất các đối tượng được chọn" });
/** Used to match template delimiters. */ const reEscape = /<%-([\s\S]+?)%>/g export default reEscape
import assert from 'assert'; import { unhex } from './testutil'; import { Parser } from '../src/parse'; describe('parse.js', function() { describe('parseUShortList', function() { it('can parse an empty list', function() { const p = new Parser(unhex('0000'), 0); assert.deepEqual(p.parseUShortList(), []); }); it('can parse a list', function() { const p = new Parser(unhex('0003 1234 DEAD BEEF'), 0); assert.deepEqual(p.parseUShortList(), [0x1234, 0xdead, 0xbeef]); }); it('can parse a list of predefined length', function() { const p = new Parser(unhex('1234 DEAD BEEF 5678 9ABC'), 2); assert.deepEqual(p.parseUShortList(3), [0xdead, 0xbeef, 0x5678]); }); }); describe('parseList', function() { it('can parse a list of values', function() { const data = '0003 12 34 56 78 9A BC'; const p = new Parser(unhex(data), 0); assert.deepEqual(p.parseList(Parser.uShort), [0x1234, 0x5678, 0x9abc]); assert.equal(p.relativeOffset, 8); }); it('can parse a list of values of predefined length', function() { const data = '12 34 56 78 9A BC'; const p = new Parser(unhex(data), 0); assert.deepEqual(p.parseList(3, Parser.uShort), [0x1234, 0x5678, 0x9abc]); assert.equal(p.relativeOffset, 6); }); }); describe('parseRecordList', function() { it('can parse a list of records', function() { const data = '0002 12 34 56 78 9A BC'; const p = new Parser(unhex(data), 0); assert.deepEqual(p.parseRecordList({ a: Parser.byte, b: Parser.uShort }), [ { a: 0x12, b: 0x3456 }, { a: 0x78, b: 0x9abc } ]); assert.equal(p.relativeOffset, 8); }); it('can parse an empty list of records', function() { const data = '0000'; const p = new Parser(unhex(data), 0); assert.deepEqual(p.parseRecordList({ a: Parser.byte, b: Parser.uShort }), []); assert.equal(p.relativeOffset, 2); }); it('can parse a list of records of predefined length', function() { const data = '12 34 56 78 9A BC'; const p = new Parser(unhex(data), 0); assert.deepEqual(p.parseRecordList(2, { a: Parser.byte, b: Parser.uShort }), [ { a: 0x12, b: 0x3456 }, { a: 0x78, b: 0x9abc } ]); assert.equal(p.relativeOffset, 6); }); }); describe('parseListOfLists', function() { it('can parse a list of lists of 16-bit integers', function() { const data = '0003 0008 000E 0016' + // 3 lists '0002 1234 5678' + // list 1 '0003 DEAD BEEF FADE' + // list 2 '0001 9876'; // list 3 const p = new Parser(unhex(data), 0); assert.deepEqual(p.parseListOfLists(), [ [0x1234, 0x5678], [0xdead, 0xbeef, 0xfade], [0x9876] ]); }); it('can parse an empty list of lists', function() { const p = new Parser(unhex('0000'), 0); assert.deepEqual(p.parseListOfLists(), []); }); it('can parse list of empty lists', function() { const p = new Parser(unhex('0001 0004 0000'), 0); assert.deepEqual(p.parseListOfLists(), [[]]); }); it('can parse a list of lists of records', function() { const data = '0002 0006 0012' + // 2 lists '0002 0006 0009 12 34 56 78 9A BC' + // list 1 '0001 0004 DE F0 12'; // list 2 const p = new Parser(unhex(data), 0); function parseRecord() { return { a: p.parseByte(), b: p.parseUShort() }; } assert.deepEqual(p.parseListOfLists(parseRecord), [ [{ a: 0x12, b: 0x3456 }, { a: 0x78, b: 0x9abc }], [{ a: 0xde, b: 0xf012 }] ]); }); }); describe('parseCoverage', function() { it('should parse a CoverageFormat1 table', function() { // https://www.microsoft.com/typography/OTSPEC/chapter2.htm Example 5 const data = '0004 1234' + // coverageOffset + filler '0001 0005 0038 003B 0041 0042 004A'; const p = new Parser(unhex(data), 4); assert.deepEqual(p.parseCoverage(), { format: 1, glyphs: [0x38, 0x3b, 0x41, 0x42, 0x4a] }); assert.equal(p.relativeOffset, 14); }); it('should parse a CoverageFormat2 table', function() { // https://www.microsoft.com/typography/OTSPEC/chapter2.htm Example 6 const data = '0004 1234' + // coverageOffset + filler '0002 0001 004E 0057 0000'; const p = new Parser(unhex(data), 4); assert.deepEqual(p.parseCoverage(), { format: 2, ranges: [{ start: 0x4e, end: 0x57, index: 0 }] }); assert.equal(p.relativeOffset, 10); }); }); describe('parseClassDef', function() { it('should parse a ClassDefFormat1 table', function() { // https://www.microsoft.com/typography/OTSPEC/chapter2.htm Example 7 const data = '0001 0032 001A' + '0000 0001 0000 0001 0000 0001 0002 0001 0000 0002 0001 0001 0000' + '0000 0000 0002 0002 0000 0000 0001 0000 0000 0000 0000 0002 0001'; const p = new Parser(unhex(data), 0); assert.deepEqual(p.parseClassDef(), { format: 1, startGlyph: 0x32, classes: [ 0, 1, 0, 1, 0, 1, 2, 1, 0, 2, 1, 1, 0, 0, 0, 2, 2, 0, 0, 1, 0, 0, 0, 0, 2, 1 ] }); assert.equal(p.relativeOffset, 58); }); it('should parse a ClassDefFormat2 table', function() { // https://www.microsoft.com/typography/OTSPEC/chapter2.htm Example 8 const data = '0002 0003 0030 0031 0002 0040 0041 0003 00D2 00D3 0001'; const p = new Parser(unhex(data), 0); assert.deepEqual(p.parseClassDef(), { format: 2, ranges: [ { start: 0x30, end: 0x31, classId: 2 }, { start: 0x40, end: 0x41, classId: 3 }, { start: 0xd2, end: 0xd3, classId: 1 } ] }); assert.equal(p.relativeOffset, 22); }); }); describe('parseScriptList', function() { it('should parse a ScriptList table', function() { // https://www.microsoft.com/typography/OTSPEC/chapter2.htm Examples 1 & 2 const data = '0004 1234' + // coverageOffset + filler '0003 68616E69 0014 6B616E61 0018 6C61746E 001C' + // Example 1 '0000 0000 0000 0000' + // 2 empty Script Tables '000A 0001 55524420 0016' + // Example 2 '0000 FFFF 0003 0000 0001 0002' + // DefLangSys '0000 0003 0003 0000 0001 0002'; // UrduLangSys const p = new Parser(unhex(data), 0); assert.deepEqual(p.parseScriptList(), [ { tag: 'hani', script: { defaultLangSys: undefined, langSysRecords: [] } }, { tag: 'kana', script: { defaultLangSys: undefined, langSysRecords: [] } }, { tag: 'latn', script: { defaultLangSys: { reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: [0, 1, 2] }, langSysRecords: [{ tag: 'URD ', langSys: { reserved: 0, reqFeatureIndex: 3, featureIndexes: [0, 1, 2] } }] } }, ]); assert.equal(p.relativeOffset, 2); }); }); describe('parseFeatureList', function() { it('should parse a FeatureList table', function() { // https://www.microsoft.com/typography/OTSPEC/chapter2.htm Example 3 const data = '0004 0000' + // table offset + filler '0003 6C696761 0014 6C696761 001A 6C696761 0022' + // feature list // There is an error in the online example, count is 3 for the 3rd feature. '0000 0001 0000 0000 0002 0000 0001 0000 0003 0000 0001 0002'; const p = new Parser(unhex(data), 0); assert.deepEqual(p.parseFeatureList(), [ { tag: 'liga', feature: { featureParams: 0, lookupListIndexes: [0] } }, { tag: 'liga', feature: { featureParams: 0, lookupListIndexes: [0, 1] } }, { tag: 'liga', feature: { featureParams: 0, lookupListIndexes: [0, 1, 2] } } ]); assert.equal(p.relativeOffset, 2); }); }); describe('parseLookupList', function() { it('should parse a LookupList table', function() { // https://www.microsoft.com/typography/OTSPEC/chapter2.htm Example 4 const data = '0004 0000' + // table offset + filler '0003 0008 0010 0018' + // lookup list '0004 000C 0001 0018' + // FfiFi lookup '0004 000C 0001 0028' + // FflFlFf lookup '0004 000C 0001 0038' + // Eszet lookup '1234 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000' + '5678 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000' + '9ABC'; const lookupTableParsers = [0, 0, 0, 0, Parser.uShort]; const p = new Parser(unhex(data), 0); assert.deepEqual(p.parseLookupList(lookupTableParsers), [ { lookupType: 4, lookupFlag: 0x000c, subtables: [0x1234], markFilteringSet: undefined }, { lookupType: 4, lookupFlag: 0x000c, subtables: [0x5678], markFilteringSet: undefined }, { lookupType: 4, lookupFlag: 0x000c, subtables: [0x9abc], markFilteringSet: undefined }, ]); assert.equal(p.relativeOffset, 2); }); }); });
/* globals AdminLTEOptions: false */ /* globals FastClick: false */ /*! AdminLTE app.js * ================ * Main JS application file for AdminLTE v2. This file * should be included in all pages. It controls some layout * options and implements exclusive AdminLTE plugins. * * @Author Almsaeed Studio * @Support <http://www.almsaeedstudio.com> * @Email <support@almsaeedstudio.com> * @version 2.1.2 * @license MIT <http://opensource.org/licenses/MIT> */ 'use strict'; //Make sure jQuery has been loaded before app.js if (typeof jQuery === 'undefined') { throw new Error('AdminLTE requires jQuery'); } /* AdminLTE * * @type Object * @description $.AdminLTE is the main object for the template's app. * It's used for implementing functions and options related * to the template. Keeping everything wrapped in an object * prevents conflict with other plugins and is a better * way to organize our code. */ $.AdminLTE = {}; /* -------------------- * - AdminLTE Options - * -------------------- * Modify these options to suit your implementation */ $.AdminLTE.options = { //Add slimscroll to navbar menus //This requires you to load the slimscroll plugin //in every page before app.js navbarMenuSlimscroll: true, navbarMenuSlimscrollWidth: '3px', //The width of the scroll bar navbarMenuHeight: '200px', //The height of the inner menu //General animation speed for JS animated elements such as box collapse/expand and //sidebar treeview slide up/down. This options accepts an integer as milliseconds, //'fast', 'normal', or 'slow' animationSpeed: 500, //Sidebar push menu toggle button selector sidebarToggleSelector: '[data-toggle="offcanvas"]', //Activate sidebar push menu sidebarPushMenu: true, //Activate sidebar slimscroll if the fixed layout is set (requires SlimScroll Plugin) sidebarSlimScroll: true, //Enable sidebar expand on hover effect for sidebar mini //This option is forced to true if both the fixed layout and sidebar mini //are used together sidebarExpandOnHover: false, //BoxRefresh Plugin enableBoxRefresh: true, //Bootstrap.js tooltip enableBSToppltip: true, BSTooltipSelector: '[data-toggle="tooltip"]', //Enable Fast Click. Fastclick.js creates a more //native touch experience with touch devices. If you //choose to enable the plugin, make sure you load the script //before AdminLTE's app.js enableFastclick: true, //Control Sidebar Options enableControlSidebar: true, controlSidebarOptions: { //Which button should trigger the open/close event toggleBtnSelector: '[data-toggle="control-sidebar"]', //The sidebar selector selector: '.control-sidebar', //Enable slide over content slide: true }, //Box Widget Plugin. Enable this plugin //to allow boxes to be collapsed and/or removed enableBoxWidget: true, //Box Widget plugin options boxWidgetOptions: { boxWidgetIcons: { //Collapse icon collapse: 'fa-minus', //Open icon open: 'fa-plus', //Remove icon remove: 'fa-times' }, boxWidgetSelectors: { //Remove button selector remove: '[data-widget="remove"]', //Collapse button selector collapse: '[data-widget="collapse"]' } }, //Direct Chat plugin options directChat: { //Enable direct chat by default enable: true, //The button to open and close the chat contacts pane contactToggleSelector: '[data-widget="chat-pane-toggle"]' }, //Define the set of colors to use globally around the website colors: { lightBlue: '#3c8dbc', red: '#f56954', green: '#00a65a', aqua: '#00c0ef', yellow: '#f39c12', blue: '#0073b7', navy: '#001F3F', teal: '#39CCCC', olive: '#3D9970', lime: '#01FF70', orange: '#FF851B', fuchsia: '#F012BE', purple: '#8E24AA', maroon: '#D81B60', black: '#222222', gray: '#d2d6de' }, //The standard screen sizes that bootstrap uses. //If you change these in the variables.less file, change //them here too. screenSizes: { xs: 480, sm: 768, md: 992, lg: 1200 } }; /* ------------------ * - Implementation - * ------------------ * The next block of code implements AdminLTE's * functions and plugins as specified by the * options above. */ $(function () { //Extend options if external options exist if (typeof AdminLTEOptions !== 'undefined') { $.extend(true, $.AdminLTE.options, AdminLTEOptions); } //Easy access to options var o = $.AdminLTE.options; //Set up the object _init(); //Activate the layout maker $.AdminLTE.layout.activate(); //Enable sidebar tree view controls $.AdminLTE.tree('.sidebar'); //Enable control sidebar if (o.enableControlSidebar) { $.AdminLTE.controlSidebar.activate(); } //Add slimscroll to navbar dropdown if (o.navbarMenuSlimscroll && typeof $.fn.slimscroll !== 'undefined') { $('.navbar .menu').slimscroll({ height: o.navbarMenuHeight, alwaysVisible: false, size: o.navbarMenuSlimscrollWidth }).css('width', '100%'); } //Activate sidebar push menu if (o.sidebarPushMenu) { $.AdminLTE.pushMenu.activate(o.sidebarToggleSelector); } //Activate Bootstrap tooltip if (o.enableBSToppltip) { $('body').tooltip({ selector: o.BSTooltipSelector }); } //Activate box widget if (o.enableBoxWidget) { $.AdminLTE.boxWidget.activate(); } //Activate fast click if (o.enableFastclick && typeof FastClick !== 'undefined') { FastClick.attach(document.body); } //Activate direct chat widget if (o.directChat.enable) { $(o.directChat.contactToggleSelector).on('click', function () { var box = $(this).parents('.direct-chat').first(); box.toggleClass('direct-chat-contacts-open'); }); } /* * INITIALIZE BUTTON TOGGLE * ------------------------ */ $('.btn-group[data-toggle="btn-toggle"]').each(function () { var group = $(this); $(this).find('.btn').on('click', function (e) { group.find('.btn.active').removeClass('active'); $(this).addClass('active'); e.preventDefault(); }); }); }); /* ---------------------------------- * - Initialize the AdminLTE Object - * ---------------------------------- * All AdminLTE functions are implemented below. */ function _init() { /* Layout * ====== * Fixes the layout height in case min-height fails. * * @type Object * @usage $.AdminLTE.layout.activate() * $.AdminLTE.layout.fix() * $.AdminLTE.layout.fixSidebar() */ $.AdminLTE.layout = { activate: function () { var _this = this; _this.fix(); _this.fixSidebar(); $(window, '.wrapper').resize(function () { _this.fix(); _this.fixSidebar(); }); }, fix: function () { //Get window height and the wrapper height var neg = $('.main-header').outerHeight() + $('.main-footer').outerHeight(); var windowHeight = $(window).height(); var sidebarHeight = $('.sidebar').height(); //Set the min-height of the content and sidebar based on the //the height of the document. if ($('body').hasClass('fixed')) { $('.content-wrapper, .right-side').css('min-height', windowHeight - $('.main-footer').outerHeight()); } else { var postSetWidth; if (windowHeight >= sidebarHeight) { $('.content-wrapper, .right-side').css('min-height', windowHeight - neg); postSetWidth = windowHeight - neg; } else { $('.content-wrapper, .right-side').css('min-height', sidebarHeight); postSetWidth = sidebarHeight; } //Fix for the control sidebar height var controlSidebar = $($.AdminLTE.options.controlSidebarOptions.selector); if (typeof controlSidebar !== 'undefined') { if (controlSidebar.height() > postSetWidth) { $('.content-wrapper, .right-side').css('min-height', controlSidebar.height()); } } } }, fixSidebar: function () { //Make sure the body tag has the .fixed class if (!$('body').hasClass('fixed')) { if (typeof $.fn.slimScroll !== 'undefined') { $('.sidebar').slimScroll({destroy: true}).height('auto'); } return; } else if (typeof $.fn.slimScroll === 'undefined' && console) { console.error('Error: the fixed layout requires the slimscroll plugin!'); } //Enable slimscroll for fixed layout if ($.AdminLTE.options.sidebarSlimScroll) { if (typeof $.fn.slimScroll !== 'undefined') { //Destroy if it exists $('.sidebar').slimScroll({destroy: true}).height('auto'); //Add slimscroll $('.sidebar').slimscroll({ height: ($(window).height() - $('.main-header').height()) + 'px', color: 'rgba(0,0,0,0.2)', size: '3px' }); } } } }; /* PushMenu() * ========== * Adds the push menu functionality to the sidebar. * * @type Function * @usage: $.AdminLTE.pushMenu("[data-toggle='offcanvas']") */ $.AdminLTE.pushMenu = { activate: function (toggleBtn) { //Get the screen sizes var screenSizes = $.AdminLTE.options.screenSizes; //Enable sidebar toggle $(toggleBtn).on('click', function (e) { e.preventDefault(); //Enable sidebar push menu if ($(window).width() > (screenSizes.sm - 1)) { $('body').toggleClass('sidebar-collapse'); } //Handle sidebar push menu for small screens else { if ($('body').hasClass('sidebar-open')) { $('body').removeClass('sidebar-open'); $('body').removeClass('sidebar-collapse'); } else { $('body').addClass('sidebar-open'); } } }); $('.content-wrapper').click(function () { //Enable hide menu when clicking on the content-wrapper on small screens if ($(window).width() <= (screenSizes.sm - 1) && $('body').hasClass('sidebar-open')) { $('body').removeClass('sidebar-open'); } }); //Enable expand on hover for sidebar mini if ($.AdminLTE.options.sidebarExpandOnHover || ($('body').hasClass('fixed') && $('body').hasClass('sidebar-mini'))) { this.expandOnHover(); } }, expandOnHover: function () { var _this = this; var screenWidth = $.AdminLTE.options.screenSizes.sm - 1; //Expand sidebar on hover $('.main-sidebar').hover(function () { if ($('body').hasClass('sidebar-mini') && $('body').hasClass('sidebar-collapse') && $(window).width() > screenWidth) { _this.expand(); } }, function () { if ($('body').hasClass('sidebar-mini') && $('body').hasClass('sidebar-expanded-on-hover') && $(window).width() > screenWidth) { _this.collapse(); } }); }, expand: function () { $('body').removeClass('sidebar-collapse').addClass('sidebar-expanded-on-hover'); }, collapse: function () { if ($('body').hasClass('sidebar-expanded-on-hover')) { $('body').removeClass('sidebar-expanded-on-hover').addClass('sidebar-collapse'); } } }; /* Tree() * ====== * Converts the sidebar into a multilevel * tree view menu. * * @type Function * @Usage: $.AdminLTE.tree('.sidebar') */ $.AdminLTE.tree = function (menu) { var _this = this; var animationSpeed = $.AdminLTE.options.animationSpeed; $('li a', $(menu)).on('click', function (e) { //Get the clicked link and the next element var $this = $(this); var checkElement = $this.next(); //Check if the next element is a menu and is visible if ((checkElement.is('.treeview-menu')) && (checkElement.is(':visible'))) { //Close the menu checkElement.slideUp(animationSpeed, function () { checkElement.removeClass('menu-open'); //Fix the layout in case the sidebar stretches over the height of the window //_this.layout.fix(); }); checkElement.parent('li').removeClass('active'); } //If the menu is not visible else if ((checkElement.is('.treeview-menu')) && (!checkElement.is(':visible'))) { //Get the parent menu var parent = $this.parents('ul').first(); //Close all open menus within the parent var ul = parent.find('ul:visible').slideUp(animationSpeed); //Remove the menu-open class from the parent ul.removeClass('menu-open'); //Get the parent li var liParent = $this.parent('li'); //Open the target menu and add the menu-open class checkElement.slideDown(animationSpeed, function () { //Add the class active to the parent li checkElement.addClass('menu-open'); parent.find('li.active').removeClass('active'); liParent.addClass('active'); //Fix the layout in case the sidebar stretches over the height of the window _this.layout.fix(); }); } //if this isn't a link, prevent the page from being redirected if (checkElement.is('.treeview-menu')) { e.preventDefault(); } }); }; /* ControlSidebar * ============== * Adds functionality to the right sidebar * * @type Object * @usage $.AdminLTE.controlSidebar.activate(options) */ $.AdminLTE.controlSidebar = { //instantiate the object activate: function () { //Get the object var _this = this; //Update options var o = $.AdminLTE.options.controlSidebarOptions; //Get the sidebar var sidebar = $(o.selector); //The toggle button var btn = $(o.toggleBtnSelector); //Listen to the click event btn.on('click', function (e) { e.preventDefault(); //If the sidebar is not open if (!sidebar.hasClass('control-sidebar-open') && !$('body').hasClass('control-sidebar-open')) { //Open the sidebar _this.open(sidebar, o.slide); } else { _this.close(sidebar, o.slide); } }); //If the body has a boxed layout, fix the sidebar bg position var bg = $('.control-sidebar-bg'); _this._fix(bg); //If the body has a fixed layout, make the control sidebar fixed if ($('body').hasClass('fixed')) { _this._fixForFixed(sidebar); } else { //If the content height is less than the sidebar's height, force max height if ($('.content-wrapper, .right-side').height() < sidebar.height()) { _this._fixForContent(sidebar); } } }, //Open the control sidebar open: function (sidebar, slide) { // var _this = this; //Slide over content if (slide) { sidebar.addClass('control-sidebar-open'); } else { //Push the content by adding the open class to the body instead //of the sidebar itself $('body').addClass('control-sidebar-open'); } }, //Close the control sidebar close: function (sidebar, slide) { if (slide) { sidebar.removeClass('control-sidebar-open'); } else { $('body').removeClass('control-sidebar-open'); } }, _fix: function (sidebar) { var _this = this; if ($('body').hasClass('layout-boxed')) { sidebar.css('position', 'absolute'); sidebar.height($('.wrapper').height()); $(window).resize(function () { _this._fix(sidebar); }); } else { sidebar.css({ 'position': 'fixed', 'height': 'auto' }); } }, _fixForFixed: function (sidebar) { sidebar.css({ 'position': 'fixed', 'max-height': '100%', 'overflow': 'auto', 'padding-bottom': '50px' }); }, _fixForContent: function (sidebar) { $('.content-wrapper, .right-side').css('min-height', sidebar.height()); } }; /* BoxWidget * ========= * BoxWidget is a plugin to handle collapsing and * removing boxes from the screen. * * @type Object * @usage $.AdminLTE.boxWidget.activate() * Set all your options in the main $.AdminLTE.options object */ $.AdminLTE.boxWidget = { selectors: $.AdminLTE.options.boxWidgetOptions.boxWidgetSelectors, icons: $.AdminLTE.options.boxWidgetOptions.boxWidgetIcons, animationSpeed: $.AdminLTE.options.animationSpeed, activate: function (_box) { var _this = this; if (! _box) { _box = document; // activate all boxes per default } //Listen for collapse event triggers $(_box).find(_this.selectors.collapse).on('click', function (e) { e.preventDefault(); _this.collapse($(this)); }); //Listen for remove event triggers $(_box).find(_this.selectors.remove).on('click', function (e) { e.preventDefault(); _this.remove($(this)); }); }, collapse: function (element) { var _this = this; //Find the box parent var box = element.parents('.box').first(); //Find the body and the footer var boxContent = box.find('> .box-body, > .box-footer'); if (!box.hasClass('collapsed-box')) { //Convert minus into plus element.children(':first') .removeClass(_this.icons.collapse) .addClass(_this.icons.open); //Hide the content boxContent.slideUp(_this.animationSpeed, function () { box.addClass('collapsed-box'); }); } else { //Convert plus into minus element.children(':first') .removeClass(_this.icons.open) .addClass(_this.icons.collapse); //Show the content boxContent.slideDown(_this.animationSpeed, function () { box.removeClass('collapsed-box'); }); } }, remove: function (element) { //Find the box parent var box = element.parents('.box').first(); box.slideUp(this.animationSpeed); } }; } /* ------------------ * - Custom Plugins - * ------------------ * All custom plugins are defined below. */ /* * BOX REFRESH BUTTON * ------------------ * This is a custom plugin to use with the component BOX. It allows you to add * a refresh button to the box. It converts the box's state to a loading state. * * @type plugin * @usage $('#box-widget').boxRefresh( options ); */ (function ($) { $.fn.boxRefresh = function (options) { // Render options var settings = $.extend({ //Refresh button selector trigger: '.refresh-btn', //File source to be loaded (e.g: ajax/src.php) source: '', //Callbacks onLoadStart: function (box) { }, //Right after the button has been clicked onLoadDone: function (box) { } //When the source has been loaded }, options); //The overlay var overlay = $('<div class="overlay"><div class="fa fa-refresh fa-spin"></div></div>'); return this.each(function () { //if a source is specified if (settings.source === '') { if (console) { console.log('Please specify a source first - boxRefresh()'); } return; } //the box var box = $(this); //the button var rBtn = box.find(settings.trigger).first(); //On trigger click rBtn.on('click', function (e) { e.preventDefault(); //Add loading overlay start(box); //Perform ajax call box.find('.box-body').load(settings.source, function () { done(box); }); }); }); function start(box) { //Add overlay and loading img box.append(overlay); settings.onLoadStart.call(box); } function done(box) { //Remove overlay and loading img box.find(overlay).remove(); settings.onLoadDone.call(box); } }; })(jQuery); /* * EXPLICIT BOX ACTIVATION * ----------------------- * This is a custom plugin to use with the component BOX. It allows you to activate * a box inserted in the DOM after the app.js was loaded. * * @type plugin * @usage $('#box-widget').activateBox(); */ (function ($) { $.fn.activateBox = function () { $.AdminLTE.boxWidget.activate(this); }; })(jQuery); /* * TODO LIST CUSTOM PLUGIN * ----------------------- * This plugin depends on iCheck plugin for checkbox and radio inputs * * @type plugin * @usage $('#todo-widget').todolist( options ); */ (function ($) { $.fn.todolist = function (options) { // Render options var settings = $.extend({ //When the user checks the input onCheck: function (ele) { }, //When the user unchecks the input onUncheck: function (ele) { } }, options); return this.each(function () { if (typeof $.fn.iCheck !== 'undefined') { $('input', this).on('ifChecked', function (event) { var ele = $(this).parents('li').first(); ele.toggleClass('done'); settings.onCheck.call(ele); }); $('input', this).on('ifUnchecked', function (event) { var ele = $(this).parents('li').first(); ele.toggleClass('done'); settings.onUncheck.call(ele); }); } else { $('input', this).on('change', function (event) { var ele = $(this).parents('li').first(); ele.toggleClass('done'); settings.onCheck.call(ele); }); } }); }; }(jQuery));
var nconf = require('nconf'), jsYaml = require('js-yaml'); var yaml = { parse: jsYaml.safeLoad, stringify: jsYaml.safeDump }; nconf.argv(); nconf.env(); nconf.file('local', { file: 'config/local.yml', format: yaml }); nconf.file('defaults', { file: 'config/default.yml', format: yaml }); module.exports = nconf;
;(function () { function getInterpolatedValues ( from, current, targetState, position, easing) { return Tweenable.tweenProps( position, current, from, targetState, 1, 0, easing); } // Fake a Tweenable and patch some internals. This approach allows us to // skip uneccessary processing and object recreation, cutting down on garbage // collection pauses. var mockTweenable = new Tweenable(); mockTweenable._filterArgs = []; /** * Compute the midpoint of two Objects. This method effectively calculates a specific frame of animation that [Tweenable#tween](shifty.core.js.html#tween) does many times over the course of a tween. * * Example: * * ``` * var interpolatedValues = Tweenable.interpolate({ * width: '100px', * opacity: 0, * color: '#fff' * }, { * width: '200px', * opacity: 1, * color: '#000' * }, 0.5); * * console.log(interpolatedValues); * // {opacity: 0.5, width: "150px", color: "rgb(127,127,127)"} * ``` * * @param {Object} from The starting values to tween from. * @param {Object} targetState The ending values to tween to. * @param {number} position The normalized position value (between 0.0 and 1.0) to interpolate the values between `from` and `to` for. `from` represents 0 and `to` represents `1`. * @param {string|Object} easing The easing curve(s) to calculate the midpoint against. You can reference any easing function attached to `Tweenable.prototype.formula`. If omitted, this defaults to "linear". * @return {Object} */ Tweenable.interpolate = function (from, targetState, position, easing) { var current = Tweenable.shallowCopy({}, from); var easingObject = Tweenable.composeEasingObject( from, easing || 'linear'); mockTweenable.set({}); // Alias and reuse the _filterArgs array instead of recreating it. var filterArgs = mockTweenable._filterArgs; filterArgs.length = 0; filterArgs[0] = current; filterArgs[1] = from; filterArgs[2] = targetState; filterArgs[3] = easingObject; // Any defined value transformation must be applied Tweenable.applyFilter(mockTweenable, 'tweenCreated'); Tweenable.applyFilter(mockTweenable, 'beforeTween'); var interpolatedValues = getInterpolatedValues( from, current, targetState, position, easingObject); // Transform values back into their original format Tweenable.applyFilter(mockTweenable, 'afterTween'); return interpolatedValues; }; }());
'use strict'; module.exports = srcPath => { const Broadcast = require(srcPath + 'Broadcast'); return { command: state => (args, player) => { state.CommandManager.get('help').execute('credits', player); } }; };
import {set} from "./schedule.js"; function easeVarying(id, value) { return function() { var v = value.apply(this, arguments); if (typeof v !== "function") throw new Error; set(this, id).ease = v; }; } export default function(value) { if (typeof value !== "function") throw new Error; return this.each(easeVarying(this._id, value)); }
// Simple serial sync/async chriso/validator.js wrapper with promises. import ValidationError from './ValidationError'; import validator from 'validator'; export default class Validation { constructor(object) { this._object = object; this._prop = null; this._validator = validator; this.promise = Promise.resolve(); } custom(callback, { required } = {}) { const prop = this._prop; const value = this._object[prop]; const object = this._object; this.promise = this.promise.then(() => { if (required && !this._isEmptyString(value)) return; callback(value, prop, object); }); return this; } _isEmptyString(value) { return !this._validator.toString(value).trim(); } prop(prop) { this._prop = prop; return this; } required(getRequiredMessage) { return this.custom((value, prop) => { const msg = getRequiredMessage ? getRequiredMessage(prop, value) : this.getRequiredMessage(prop, value); throw new ValidationError(msg, prop); }, { required: true }); } getRequiredMessage(prop) { return `Please fill out '${prop}' field.`; } email() { return this.custom((value, prop) => { if (this._validator.isEmail(value)) return; throw new ValidationError( this.getEmailMessage(prop, value), prop ); }); } getEmailMessage() { return 'Email address is not valid.'; } simplePassword() { return this.custom((value, prop) => { const minLength = 5; if (value.length >= minLength) return; throw new ValidationError( this.getSimplePasswordMessage(minLength), prop ); }); } getSimplePasswordMessage(minLength) { return `Password must contain at least ${minLength} characters.`; } }
export var NumberFormatStyle; (function (NumberFormatStyle) { NumberFormatStyle[NumberFormatStyle["Decimal"] = 0] = "Decimal"; NumberFormatStyle[NumberFormatStyle["Percent"] = 1] = "Percent"; NumberFormatStyle[NumberFormatStyle["Currency"] = 2] = "Currency"; })(NumberFormatStyle || (NumberFormatStyle = {})); export class NumberFormatter { static format(num, locale, style, { minimumIntegerDigits = 1, minimumFractionDigits = 0, maximumFractionDigits = 3, currency, currencyAsSymbol = false } = {}) { var intlOptions = { minimumIntegerDigits: minimumIntegerDigits, minimumFractionDigits: minimumFractionDigits, maximumFractionDigits: maximumFractionDigits }; intlOptions.style = NumberFormatStyle[style].toLowerCase(); if (style == NumberFormatStyle.Currency) { intlOptions.currency = currency; intlOptions.currencyDisplay = currencyAsSymbol ? 'symbol' : 'code'; } return new Intl.NumberFormat(locale, intlOptions).format(num); } } var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwGjJ']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|J+|j+|m+|s+|a|Z|G+|w+))(.*)/; var PATTERN_ALIASES = { yMMMdjms: datePartGetterFactory(combine([ digitCondition('year', 1), nameCondition('month', 3), digitCondition('day', 1), digitCondition('hour', 1), digitCondition('minute', 1), digitCondition('second', 1), ])), yMdjm: datePartGetterFactory(combine([ digitCondition('year', 1), digitCondition('month', 1), digitCondition('day', 1), digitCondition('hour', 1), digitCondition('minute', 1) ])), yMMMMEEEEd: datePartGetterFactory(combine([ digitCondition('year', 1), nameCondition('month', 4), nameCondition('weekday', 4), digitCondition('day', 1) ])), yMMMMd: datePartGetterFactory(combine([digitCondition('year', 1), nameCondition('month', 4), digitCondition('day', 1)])), yMMMd: datePartGetterFactory(combine([digitCondition('year', 1), nameCondition('month', 3), digitCondition('day', 1)])), yMd: datePartGetterFactory(combine([digitCondition('year', 1), digitCondition('month', 1), digitCondition('day', 1)])), jms: datePartGetterFactory(combine([digitCondition('hour', 1), digitCondition('second', 1), digitCondition('minute', 1)])), jm: datePartGetterFactory(combine([digitCondition('hour', 1), digitCondition('minute', 1)])) }; var DATE_FORMATS = { yyyy: datePartGetterFactory(digitCondition('year', 4)), yy: datePartGetterFactory(digitCondition('year', 2)), y: datePartGetterFactory(digitCondition('year', 1)), MMMM: datePartGetterFactory(nameCondition('month', 4)), MMM: datePartGetterFactory(nameCondition('month', 3)), MM: datePartGetterFactory(digitCondition('month', 2)), M: datePartGetterFactory(digitCondition('month', 1)), LLLL: datePartGetterFactory(nameCondition('month', 4)), dd: datePartGetterFactory(digitCondition('day', 2)), d: datePartGetterFactory(digitCondition('day', 1)), HH: hourExtracter(datePartGetterFactory(hour12Modify(digitCondition('hour', 2), false))), H: hourExtracter(datePartGetterFactory(hour12Modify(digitCondition('hour', 1), false))), hh: hourExtracter(datePartGetterFactory(hour12Modify(digitCondition('hour', 2), true))), h: hourExtracter(datePartGetterFactory(hour12Modify(digitCondition('hour', 1), true))), jj: datePartGetterFactory(digitCondition('hour', 2)), j: datePartGetterFactory(digitCondition('hour', 1)), mm: datePartGetterFactory(digitCondition('minute', 2)), m: datePartGetterFactory(digitCondition('minute', 1)), ss: datePartGetterFactory(digitCondition('second', 2)), s: datePartGetterFactory(digitCondition('second', 1)), // while ISO 8601 requires fractions to be prefixed with `.` or `,` // we can be just safely rely on using `sss` since we currently don't support single or two digit // fractions sss: datePartGetterFactory(digitCondition('second', 3)), EEEE: datePartGetterFactory(nameCondition('weekday', 4)), EEE: datePartGetterFactory(nameCondition('weekday', 3)), EE: datePartGetterFactory(nameCondition('weekday', 2)), E: datePartGetterFactory(nameCondition('weekday', 1)), a: hourClockExtracter(datePartGetterFactory(hour12Modify(digitCondition('hour', 1), true))), Z: datePartGetterFactory({ timeZoneName: 'long' }), z: datePartGetterFactory({ timeZoneName: 'short' }), ww: datePartGetterFactory({}), // first Thursday of the year. not support ? w: datePartGetterFactory({}), // of the year not support ? G: datePartGetterFactory(nameCondition('era', 1)), GG: datePartGetterFactory(nameCondition('era', 2)), GGG: datePartGetterFactory(nameCondition('era', 3)), GGGG: datePartGetterFactory(nameCondition('era', 4)) }; function hourClockExtracter(inner) { return function (date, locale) { var result = inner(date, locale); return result.split(' ')[1]; }; } function hourExtracter(inner) { return function (date, locale) { var result = inner(date, locale); return result.split(' ')[0]; }; } function hour12Modify(options, value) { options.hour12 = value; return options; } function digitCondition(prop, len) { var result = {}; result[prop] = len == 2 ? '2-digit' : 'numeric'; return result; } function nameCondition(prop, len) { var result = {}; result[prop] = len < 4 ? 'short' : 'long'; return result; } function combine(options) { var result = {}; options.forEach(option => { Object.assign(result, option); }); return result; } function datePartGetterFactory(ret) { return function (date, locale) { return new Intl.DateTimeFormat(locale, ret).format(date); }; } var datePartsFormatterCache = new Map(); function dateFormatter(format, date, locale) { var text = ''; var match; var fn; var parts = []; if (PATTERN_ALIASES[format]) { return PATTERN_ALIASES[format](date, locale); } if (datePartsFormatterCache.has(format)) { parts = datePartsFormatterCache.get(format); } else { var matchs = DATE_FORMATS_SPLIT.exec(format); while (format) { match = DATE_FORMATS_SPLIT.exec(format); if (match) { parts = concat(parts, match, 1); format = parts.pop(); } else { parts.push(format); format = null; } } datePartsFormatterCache.set(format, parts); } parts.forEach(part => { fn = DATE_FORMATS[part]; text += fn ? fn(date, locale) : part === '\'\'' ? '\'' : part.replace(/(^'|'$)/g, '').replace(/''/g, '\''); }); return text; } var slice = [].slice; function concat(array1 /** TODO #9100 */, array2 /** TODO #9100 */, index /** TODO #9100 */) { return array1.concat(slice.call(array2, index)); } export class DateFormatter { static format(date, locale, pattern) { return dateFormatter(pattern, date, locale); } } //# sourceMappingURL=intl.js.map
jq = $; // some weird jquery bug, themes overriding or something something // screws up .modal calls $(function() { var edit = $("#edit"); var inputs = edit.find("input, textarea").val(""); var resume = {}; function update() { // Clone resume object. var json = $.extend({}, resume ); (function iterate(obj, key) { if ($.type(obj) == "object") { for (var i in obj) { var k = key ? [key, i].join(".") : i; iterate(obj[i], k); } return; } var value = ""; var self = edit.find("[data-name='" + key + "']"); if (!self.length) { return; } if (self.prop("tagName") == "INPUT" || self.prop("tagName") == "TEXTAREA") { value = self.val(); } else { value = []; self.each(function() { var self = $(this); var hash = {}; self.find("input, textarea").each(function() { var self = $(this); hash[self.attr("name")] = self.hasClass("list") ? self.val().split(",") : self.val(); }); value.push(hash); }); } var keys = key.split("."); (function(obj) { while (keys.length > 1) { obj = obj[keys.shift()]; } obj[keys[0]] = value; })(json); })(json); output.html(JSON.stringify(json, null, " ")); output.trigger("input"); } function resetBuilder(resumeObj) { (function iterate(obj, key) { if ($.type(obj) == "object") { for (var i in obj) { var k = key ? [key, i].join(".") : i; iterate(obj[i], k); } return; } else if ($.type(obj) == "array") { var item = edit.find("[data-name='" + key + "']").eq(0); if (!item.length) { return; } var clone = item[0].outerHTML; item.next(".add").data("clone", clone); for (var i in obj) { for (var ii in obj[i]) { var value = obj[i][ii]; item.find("[name='" + ii + "']").val( $.type(value) == "array" ? value.join(", ") : value ); } } return; } inputs.each(function() { var self = $(this); if (self.data("name") == key) { self.val(obj); } }); })(resumeObj); resume = resumeObj; update(); } function reset() { $.getJSON("default.json", function(json) { resetBuilder(json); }); } var output = $("#output"); var timer = null; output.on("input", function() { clearTimeout(timer); preview.addClass("loading"); timer = setTimeout(function() { edit.trigger("output"); }, 200); }); $("#export, #save").tooltip({ container: "body" }); edit.on("input", "input, textarea", function() { update(); }); edit.on("output", function(e) { e.preventDefault(); var json = ""; try { var json = JSON.parse(output.val()); } catch (e) { return; } var theme = edit.find(".dropdown").data("selected") || "flat"; var data = JSON.stringify({ resume: json }); $.ajax({ type: "POST", contentType: "application/json", data: data, url: "http://themes.jsonresume.org/theme/" + theme, success: function(html) { $("#iframe").contents().find("body").html(html); preview.removeClass("loading"); } }); }); var themes = $(".dropdown-menu"); (function populateThemeMenu() { themes.empty(); $.getJSON("http://themes.jsonresume.org/themes.json", function(json) { if (!json.themes) { return; } for (var t in json.themes) { var version = $("<div class='version'>" + json.themes[t].versions.pop() + "</div>"); var link = $("<a href='#" + t + "'>" + t + "</a>").append(version); var item = $("<li>").append(link); themes.append(item); } var hash = window.location.hash; if (hash != "") { var theme = edit.find(".dropdown a[href='" + hash + "']"); theme.trigger("click"); } }); })(); edit.on("click", "input", function() { $(this).select(); }); edit.on("click", ".dropdown a", function() { var theme = $(this).attr("href").substring(1); edit.find(".dropdown").data("selected", theme).find("button").html(theme); edit.trigger("output"); }); edit.on("click", ".add", function() { var self = $(this); var clone = self.data("clone"); if (clone) { self.before(clone); } }); edit.on("click", ".delete", function() { var self = $(this); self.closest(".array").remove(); update(); }); $("#reset").on("click", function() { if (confirm("Are you sure you want to start over? This action will clear the input fields and reload the theme.")) { reset(); } }); $("#export").on("click", function() { download(output.val(), "resume.json", "text/plain"); }); var rows = $(".row"); rows.sortable({ containment: "parent", items: ".array", handle: ".handle", placeholder: "placeholder", forcePlaceholderSize: true, scroll: false, update: function() { update(); } }); rows.on("click", ".handle", function() { var self = $(this); self.next(".collapse").toggle(); }); var preview = $("#preview"); $("#sidebar").resizable({ handles: "e", minWidth: 200, maxWidth: 800 }).on("resize", function(e, ui) { preview.css({ left: ui.size.width }); }); setTimeout(function() { // Turn on transitions. $("body").removeClass("preload"); }, 500); var proxiedSync = Backbone.sync; Backbone.sync = function(method, model, options) { options || (options = {}); console.log(options, 'a'); if (!options.crossDomain) { options.crossDomain = true; } if (!options.xhrFields) { options.xhrFields = {withCredentials:true}; } options.url = 'http://registry.jsonresume.org' + model.url(); return proxiedSync(method, model, options); }; /* Session */ var SessionModel = Backbone.Model.extend({ urlRoot: '/session', initialize: function() { var that = this; // Hook into jquery // Use withCredentials to send the server cookies // The server must allow this through response headers /* $.ajaxPrefilter(function(options, originalOptions, jqXHR) { if (options.url.indexOf('session') !== -1 || options.url.indexOf('user') !== -1) { options.url = 'http://registry.jsonresume.org/' + options.url; //options.url = 'http://localhost:5000' + options.url; options.xhrFields = { withCredentials: true }; // If we have a csrf token send it through with the next request if (typeof that.get('_csrf') !== 'undefined') { jqXHR.setRequestHeader('X-CSRF-Token', that.get('_csrf')); } } });*/ }, login: function(creds, callback) { // Do a POST to /session and send the serialized form creds this.save(creds, { success: callback }); }, logout: function() { // Do a DELETE to /session and clear the clientside data var that = this; this.destroy({ success: function(model, resp) { model.clear() model.id = null; // Set auth to false to trigger a change:auth event // The server also returns a new csrf token so that // the user can relogin without refreshing the page that.set({ auth: false }); //, _csrf: resp._csrf}); } }); }, getAuth: function(callback) { // getAuth is wrapped around our router // before we start any routers let us see if the user is valid this.fetch({ success: callback }); } }); var Session = new SessionModel(); Session.getAuth(function(session) { if (session.get('auth')) { $('#logout-button').fadeIn(200); $.ajax('http://registry.jsonresume.org/' + session.get('username') + '.json', { xhrFields: { withCredentials: true }, success: function(res) { var resumeObj = res; resetBuilder(resumeObj); var theme = $(".dropdown a[href='#" + resumeObj.jsonresume.theme + "']"); console.log('a', theme); theme.trigger("click"); } }); } else { $('#register-button').fadeIn(200); $('#login-button').fadeIn(200); reset(); } //$.ajax('http://localhost:5000/thomasdavis.json', { /*$.ajax('http://registry.jsonresume.org/'+session.get('username')+'.json', { success: function (res) { var resumeObj = res; console.log(resumeObj); resetBuilder(resumeObj); update(); } })*/ //resetBuilder(json); }); Session.on('change:auth', function(session) {}) $('#login-button').on('click', function(ev) { jq('#login-modal').modal('show'); }); $('#register-button').on('click', function(ev) { jq('#register-modal').modal('show'); }); $('#save-button').on('click', function(ev) { if(Session.get('auth')) { var resume = JSON.parse(output.val()); $('#publish-modal .modal-body').html('<p>Publishing...</p>'); jq('#publish-modal').modal('show'); var resumeM = new ResumeModel(); alert($(".dropdown").data("selected")); resumeM.save({resume:resume, theme: $(".dropdown").data("selected")}, { success: function () { $('#publish-modal .modal-body').html('<p>Beautiful! Access your published resume at<br /><a style="color: #007eff" href="http://registry.jsonresume.org/'+Session.get('username')+'" target="_blank">http://registry.jsonresume.org/'+Session.get('username')+'</a></p>'); console.log('whoa', arguments); } }) } else { jq('#register-modal').modal('show'); } }); $('#logout-button').on('click', function(ev) { Session.logout(); $('#logout-button').toggle(); $('#register-button').toggle(); $('#login-button').toggle(); reset(); //$('#login-modal').modal('show'); }); $('.login-form').on('submit', function(ev) { var form = $(ev.currentTarget); var email = $('.login-email', form).val(); var password = $('.login-password', form).val(); Session.login({ email: email, password: password }, function() { console.log('a'); jq('#login-modal').modal('hide'); $.ajax('http://registry.jsonresume.org/' + Session.get('username') + '.json', { success: function(res) { var resumeObj = res; resetBuilder(resumeObj); } }); $('#logout-button').toggle(); $('#register-button').toggle(); $('#login-button').toggle(); }); }); var UserModel = Backbone.Model.extend({ urlRoot: '/user' }); var ResumeModel = Backbone.Model.extend({ urlRoot: '/resume' }); $('.register-form').on('submit', function(ev) { var form = $(ev.currentTarget); var email = $('.register-email', form).val(); var username = $('.register-username', form).val(); var password = $('.register-password', form).val(); var user = new UserModel(); user.save({email: email, username:username, password:password}, { success: function () { $('.register-form .modal-body').html('<p>Excellent! We are now saving your first resume....</p>'); $('.register-form .modal-footer').remove(); var resume = JSON.parse(output.val()); console.log(resume); Session.getAuth(function() { $('#logout-button').toggle(); $('#register-button').toggle(); $('#login-button').toggle(); var resumeM = new ResumeModel(); resumeM.save({resume:resume, theme: $(".dropdown").data("selected")}, { success: function () { $('.register-form .modal-body').html('<p>Beautiful! Access your published resume at<br /><a style="color: #007eff" href="http://registry.jsonresume.org/'+Session.get('username')+'" target="_blank">http://registry.jsonresume.org/'+Session.get('username')+'</a></p>'); console.log('whoa', arguments); } }) console.log('hey', arguments); }) } }) return false; }); });
'use strict'; const assert = require('assert'); const app = require('../../../index'); describe('GeolocationController', () => { it('should exist', () => { assert(app.api.controllers.GeolocationController); }); });
/* * Copyright (c) 2016, Globo.com (https://github.com/globocom) * * License: MIT */ import React from "react"; export default class extends React.Component { render() { return ( <svg width="24" height="24" viewBox="0 0 24 24" ><path d="M10 5v3h2.21l-3.42 8H6v3h8v-3h-2.21l3.42-8H18V5z" fill="currentColor" fillRule="evenodd"/></svg> ); } }
a !== b
'use strict'; angular.module('mgcrea.ngStrap.timepicker', ['mgcrea.ngStrap.helpers.dateParser', 'mgcrea.ngStrap.tooltip']) .provider('$timepicker', function() { var defaults = this.defaults = { animation: 'am-fade', prefixClass: 'timepicker', placement: 'bottom-left', template: 'timepicker/timepicker.tpl.html', trigger: 'focus', container: false, keyboard: true, html: false, delay: 0, // lang: $locale.id, useNative: true, timeType: 'date', timeFormat: 'shortTime', autoclose: false, minTime: -Infinity, maxTime: +Infinity, length: 5, hourStep: 1, minuteStep: 5 }; this.$get = function($window, $document, $rootScope, $sce, $locale, dateFilter, $tooltip) { var bodyEl = angular.element($window.document.body); var isTouch = 'createTouch' in $window.document; var isNative = /(ip(a|o)d|iphone|android)/ig.test($window.navigator.userAgent); if(!defaults.lang) defaults.lang = $locale.id; function timepickerFactory(element, controller, config) { var $timepicker = $tooltip(element, angular.extend({}, defaults, config)); var parentScope = config.scope; var options = $timepicker.$options; var scope = $timepicker.$scope; // View vars var selectedIndex = 0; var startDate = controller.$dateValue || new Date(); var viewDate = {hour: startDate.getHours(), meridian: startDate.getHours() < 12, minute: startDate.getMinutes(), second: startDate.getSeconds(), millisecond: startDate.getMilliseconds()}; var format = $locale.DATETIME_FORMATS[options.timeFormat] || options.timeFormat; var formats = /(h+)[:]?(m+)[ ]?(a?)/i.exec(format).slice(1); // Scope methods scope.$select = function(date, index) { $timepicker.select(date, index); }; scope.$moveIndex = function(value, index) { $timepicker.$moveIndex(value, index); }; scope.$switchMeridian = function(date) { $timepicker.switchMeridian(date); }; // Public methods $timepicker.update = function(date) { // console.warn('$timepicker.update() newValue=%o', date); if(angular.isDate(date) && !isNaN(date.getTime())) { $timepicker.$date = date; angular.extend(viewDate, {hour: date.getHours(), minute: date.getMinutes(), second: date.getSeconds(), millisecond: date.getMilliseconds()}); $timepicker.$build(); } else if(!$timepicker.$isBuilt) { $timepicker.$build(); } }; $timepicker.select = function(date, index, keep) { // console.warn('$timepicker.select', date, scope.$mode); if(!controller.$dateValue || isNaN(controller.$dateValue.getTime())) controller.$dateValue = new Date(1970, 0, 1); if(!angular.isDate(date)) date = new Date(date); if(index === 0) controller.$dateValue.setHours(date.getHours()); else if(index === 1) controller.$dateValue.setMinutes(date.getMinutes()); controller.$setViewValue(controller.$dateValue); controller.$render(); if(options.autoclose && !keep) { $timepicker.hide(true); } }; $timepicker.switchMeridian = function(date) { var hours = (date || controller.$dateValue).getHours(); controller.$dateValue.setHours(hours < 12 ? hours + 12 : hours - 12); controller.$setViewValue(controller.$dateValue); controller.$render(); }; // Protected methods $timepicker.$build = function() { // console.warn('$timepicker.$build() viewDate=%o', viewDate); var i, midIndex = scope.midIndex = parseInt(options.length / 2, 10); var hours = [], hour; for(i = 0; i < options.length; i++) { hour = new Date(1970, 0, 1, viewDate.hour - (midIndex - i) * options.hourStep); hours.push({date: hour, label: dateFilter(hour, formats[0]), selected: $timepicker.$date && $timepicker.$isSelected(hour, 0), disabled: $timepicker.$isDisabled(hour, 0)}); } var minutes = [], minute; for(i = 0; i < options.length; i++) { minute = new Date(1970, 0, 1, 0, viewDate.minute - (midIndex - i) * options.minuteStep); minutes.push({date: minute, label: dateFilter(minute, formats[1]), selected: $timepicker.$date && $timepicker.$isSelected(minute, 1), disabled: $timepicker.$isDisabled(minute, 1)}); } var rows = []; for(i = 0; i < options.length; i++) { rows.push([hours[i], minutes[i]]); } scope.rows = rows; scope.showAM = !!formats[2]; scope.isAM = ($timepicker.$date || hours[midIndex].date).getHours() < 12; $timepicker.$isBuilt = true; }; $timepicker.$isSelected = function(date, index) { if(!$timepicker.$date) return false; else if(index === 0) { return date.getHours() === $timepicker.$date.getHours(); } else if(index === 1) { return date.getMinutes() === $timepicker.$date.getMinutes(); } }; $timepicker.$isDisabled = function(date, index) { var selectedTime; if(index === 0) { selectedTime = date.getTime() + viewDate.minute * 6e4; } else if(index === 1) { selectedTime = date.getTime() + viewDate.hour * 36e5; } return selectedTime < options.minTime * 1 || selectedTime > options.maxTime * 1; }; $timepicker.$moveIndex = function(value, index) { var targetDate; if(index === 0) { targetDate = new Date(1970, 0, 1, viewDate.hour + (value * options.length), viewDate.minute); angular.extend(viewDate, {hour: targetDate.getHours()}); } else if(index === 1) { targetDate = new Date(1970, 0, 1, viewDate.hour, viewDate.minute + (value * options.length * options.minuteStep)); angular.extend(viewDate, {minute: targetDate.getMinutes()}); } $timepicker.$build(); }; $timepicker.$onMouseDown = function(evt) { // Prevent blur on mousedown on .dropdown-menu if(evt.target.nodeName.toLowerCase() !== 'input') evt.preventDefault(); evt.stopPropagation(); // Emulate click for mobile devices if(isTouch) { var targetEl = angular.element(evt.target); if(targetEl[0].nodeName.toLowerCase() !== 'button') { targetEl = targetEl.parent(); } targetEl.triggerHandler('click'); } }; $timepicker.$onKeyDown = function(evt) { if (!/(38|37|39|40|13)/.test(evt.keyCode) || evt.shiftKey || evt.altKey) return; evt.preventDefault(); evt.stopPropagation(); // Close on enter if(evt.keyCode === 13) return $timepicker.hide(true); // Navigate with keyboard var newDate = new Date($timepicker.$date); var hours = newDate.getHours(), hoursLength = dateFilter(newDate, 'h').length; var minutes = newDate.getMinutes(), minutesLength = dateFilter(newDate, 'mm').length; var lateralMove = /(37|39)/.test(evt.keyCode); var count = 2 + !!formats[2] * 1; // Navigate indexes (left, right) if (lateralMove) { if(evt.keyCode === 37) selectedIndex = selectedIndex < 1 ? count - 1 : selectedIndex - 1; else if(evt.keyCode === 39) selectedIndex = selectedIndex < count - 1 ? selectedIndex + 1 : 0; } // Update values (up, down) var selectRange = [0, hoursLength]; if(selectedIndex === 0) { if(evt.keyCode === 38) newDate.setHours(hours - parseInt(options.hourStep, 10)); else if(evt.keyCode === 40) newDate.setHours(hours + parseInt(options.hourStep, 10)); selectRange = [0, hoursLength]; } else if(selectedIndex === 1) { if(evt.keyCode === 38) newDate.setMinutes(minutes - parseInt(options.minuteStep, 10)); else if(evt.keyCode === 40) newDate.setMinutes(minutes + parseInt(options.minuteStep, 10)); selectRange = [hoursLength + 1, hoursLength + 1 + minutesLength]; } else if(selectedIndex === 2) { if(!lateralMove) $timepicker.switchMeridian(); selectRange = [hoursLength + 1 + minutesLength + 1, hoursLength + 1 + minutesLength + 3]; } $timepicker.select(newDate, selectedIndex, true); createSelection(selectRange[0], selectRange[1]); parentScope.$digest(); }; // Private function createSelection(start, end) { if(element[0].createTextRange) { var selRange = element[0].createTextRange(); selRange.collapse(true); selRange.moveStart('character', start); selRange.moveEnd('character', end); selRange.select(); } else if(element[0].setSelectionRange) { element[0].setSelectionRange(start, end); } else if(angular.isUndefined(element[0].selectionStart)) { element[0].selectionStart = start; element[0].selectionEnd = end; } } function focusElement() { element[0].focus(); } // Overrides var _init = $timepicker.init; $timepicker.init = function() { if(isNative && options.useNative) { element.prop('type', 'time'); element.css('-webkit-appearance', 'textfield'); return; } else if(isTouch) { element.prop('type', 'text'); element.attr('readonly', 'true'); element.on('click', focusElement); } _init(); }; var _destroy = $timepicker.destroy; $timepicker.destroy = function() { if(isNative && options.useNative) { element.off('click', focusElement); } _destroy(); }; var _show = $timepicker.show; $timepicker.show = function() { _show(); setTimeout(function() { $timepicker.$element.on(isTouch ? 'touchstart' : 'mousedown', $timepicker.$onMouseDown); if(options.keyboard) { element.on('keydown', $timepicker.$onKeyDown); } }); }; var _hide = $timepicker.hide; $timepicker.hide = function(blur) { $timepicker.$element.off(isTouch ? 'touchstart' : 'mousedown', $timepicker.$onMouseDown); if(options.keyboard) { element.off('keydown', $timepicker.$onKeyDown); } _hide(blur); }; return $timepicker; } timepickerFactory.defaults = defaults; return timepickerFactory; }; }) .directive('bsTimepicker', function($window, $parse, $q, $locale, dateFilter, $timepicker, $dateParser, $timeout) { var defaults = $timepicker.defaults; var isNative = /(ip(a|o)d|iphone|android)/ig.test($window.navigator.userAgent); var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout; return { restrict: 'EAC', require: 'ngModel', link: function postLink(scope, element, attr, controller) { // Directive options var options = {scope: scope, controller: controller}; angular.forEach(['placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'autoclose', 'timeType', 'timeFormat', 'useNative', 'hourStep', 'minuteStep', 'length'], function(key) { if(angular.isDefined(attr[key])) options[key] = attr[key]; }); // Initialize timepicker if(isNative && (options.useNative || defaults.useNative)) options.timeFormat = 'HH:mm'; var timepicker = $timepicker(element, controller, options); options = timepicker.$options; // Initialize parser var dateParser = $dateParser({format: options.timeFormat, lang: options.lang}); // Observe attributes for changes angular.forEach(['minTime', 'maxTime'], function(key) { // console.warn('attr.$observe(%s)', key, attr[key]); angular.isDefined(attr[key]) && attr.$observe(key, function(newValue) { if(newValue === 'now') { timepicker.$options[key] = new Date().setFullYear(1970, 0, 1); } else if(angular.isString(newValue) && newValue.match(/^".+"$/)) { timepicker.$options[key] = +new Date(newValue.substr(1, newValue.length - 2)); } else { timepicker.$options[key] = dateParser.parse(newValue, new Date(1970, 0, 1, 0)); } !isNaN(timepicker.$options[key]) && timepicker.$build(); }); }); // Watch model for changes scope.$watch(attr.ngModel, function(newValue, oldValue) { // console.warn('scope.$watch(%s)', attr.ngModel, newValue, oldValue, controller.$dateValue); timepicker.update(controller.$dateValue); }, true); // viewValue -> $parsers -> modelValue controller.$parsers.unshift(function(viewValue) { // console.warn('$parser("%s"): viewValue=%o', element.attr('ng-model'), viewValue); // Null values should correctly reset the model value & validity if(!viewValue) { controller.$setValidity('date', true); return; } var parsedTime = dateParser.parse(viewValue, controller.$dateValue); if(!parsedTime || isNaN(parsedTime.getTime())) { controller.$setValidity('date', false); } else { var isValid = parsedTime.getTime() >= options.minTime && parsedTime.getTime() <= options.maxTime; controller.$setValidity('date', isValid); // Only update the model when we have a valid date if(isValid) controller.$dateValue = parsedTime; } if(options.timeType === 'string') { return dateFilter(viewValue, options.timeFormat); } else if(options.timeType === 'number') { return controller.$dateValue.getTime(); } else if(options.timeType === 'iso') { return controller.$dateValue.toISOString(); } else { return new Date(controller.$dateValue); } }); // modelValue -> $formatters -> viewValue controller.$formatters.push(function(modelValue) { // console.warn('$formatter("%s"): modelValue=%o (%o)', element.attr('ng-model'), modelValue, typeof modelValue); var date; if(angular.isUndefined(modelValue) || modelValue === null) { date = NaN; } else if(angular.isDate(modelValue)) { date = modelValue; } else if(options.timeType === 'string') { date = dateParser.parse(modelValue); } else { date = new Date(modelValue); } // Setup default value? // if(isNaN(date.getTime())) date = new Date(new Date().setMinutes(0) + 36e5); controller.$dateValue = date; return controller.$dateValue; }); // viewValue -> element controller.$render = function() { // console.warn('$render("%s"): viewValue=%o', element.attr('ng-model'), controller.$viewValue); element.val(!controller.$dateValue || isNaN(controller.$dateValue.getTime()) ? '' : dateFilter(controller.$dateValue, options.timeFormat)); }; // Garbage collection scope.$on('$destroy', function() { timepicker.destroy(); options = null; timepicker = null; }); } }; });
/*-------------------------------------------------------------------------------------*/ /* Don't open internal links in standalone iOS Mode in safari * prevents links from apps from oppening in mobile safari, this javascript must be the first script in your <head> */ (function (document, navigator, standalone) { 'use strict'; if ((typeof (navigator.standalone) !== 'undefined') && navigator.standalone) { var curnode, location = document.location, stop = /^(a|html)$/i; document.addEventListener('click', function (e) { curnode = e.target; while (!(stop).test(curnode.nodeName)) { curnode = curnode.parentNode; } // Condidions to do this only on links to your own app // if you want all links, use if('href' in curnode) instead. if ('href' in curnode && (curnode.href.indexOf('http') || ~curnode.href.indexOf(location.host))) { e.preventDefault(); location.href = curnode.href; } }, false); } }(document, window.navigator, 'standalone'));
"use strict"; var portScanner = require("portscanner"); module.exports = { /** * Get port range with default fallbacks * @param {Number} minCount * @param {Number} [min] * @param {Number} [max] * @returns {{min: (Number), max: (Number)} */ getPortRange: function (minCount, min, max) { if (min && max) { if ((max - min + 1) < minCount) { return false; } return { min: min, max: max }; } if (min) { max = min + 500; return { min: min, max: max < 10000 ? max : 9999 }; } return { min: 3000, max: 4000 }; }, /** * @param {Number} count * @param {Function} callback * @param {Number} [min] * @param {Number} [max] */ getPorts: function (count, callback, min, max) { var ports = []; var lastFound = min - 1 || 2999; // get a port (async) var getPort = function () { portScanner.findAPortNotInUse(lastFound + 1, max || 4000, "localhost", function (error, port) { ports.push(port); lastFound = port; runAgain(); }); }; // run again if number of ports not reached var runAgain = function () { if (ports.length < count) { getPort(); } else { return callback(ports); } return false; }; // Get the first port getPort(); } };
/** * Developer: Stepan Burguchev * Date: 9/1/2015 * Copyright: 2009-2016 Comindware® * All Rights Reserved * Published under the MIT license */ /* global module */ "use strict"; import LocalizationService from '../../services/LocalizationService'; module.exports = function(textId) { return LocalizationService.get(textId); };
/* Copyright (c) 2012, Yahoo! Inc. All rights reserved. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ /*global esprima, escodegen, window */ (function (isNode) { "use strict"; var SYNTAX, nodeType, ESP = isNode ? require('esprima-harmony') : esprima, ESPGEN = isNode ? require('escodegen') : escodegen, //TODO - package as dependency crypto = isNode ? require('crypto') : null, LEADER_WRAP = '(function () { ', TRAILER_WRAP = '\n}());', COMMENT_RE = /^\s*istanbul\s+ignore\s+(if|else|next)(?=\W|$)/, astgen, preconditions, cond, isArray = Array.isArray; /* istanbul ignore if: untestable */ if (!isArray) { isArray = function (thing) { return thing && Object.prototype.toString.call(thing) === '[object Array]'; }; } if (!isNode) { preconditions = { 'Could not find esprima': ESP, 'Could not find escodegen': ESPGEN, 'JSON object not in scope': JSON, 'Array does not implement push': [].push, 'Array does not implement unshift': [].unshift }; /* istanbul ignore next: untestable */ for (cond in preconditions) { if (preconditions.hasOwnProperty(cond)) { if (!preconditions[cond]) { throw new Error(cond); } } } } function generateTrackerVar(filename, omitSuffix) { var hash, suffix; if (crypto !== null) { hash = crypto.createHash('md5'); hash.update(filename); suffix = hash.digest('base64'); //trim trailing equal signs, turn identifier unsafe chars to safe ones + => _ and / => $ suffix = suffix.replace(new RegExp('=', 'g'), '') .replace(new RegExp('\\+', 'g'), '_') .replace(new RegExp('/', 'g'), '$'); } else { window.__cov_seq = window.__cov_seq || 0; window.__cov_seq += 1; suffix = window.__cov_seq; } return '__cov_' + (omitSuffix ? '' : suffix); } function pushAll(ary, thing) { if (!isArray(thing)) { thing = [ thing ]; } Array.prototype.push.apply(ary, thing); } SYNTAX = { ArrayExpression: [ 'elements' ], //ES6: ArrayPattern: [ 'elements' ], //ES6: ArrowFunctionExpression: [ 'id', 'params', 'defaults', 'body', 'rest', 'generator', 'expression' ], AssignmentExpression: ['left', 'right'], BinaryExpression: ['left', 'right' ], BlockStatement: [ 'body' ], BreakStatement: [ 'label' ], CallExpression: [ 'callee', 'arguments'], CatchClause: ['param', 'body'], //ES6: ClassBody: [ 'body' ], //ES6: ClassDeclaration: [ 'id', 'superClass', 'body' ], //ES6: ClassExpression: [ 'id', 'superClass', 'body'], //ES6: ClassHeritage: [ ], //ES6: ComprehensionBlock: [], //ES6: ComprehensionExpression: [ 'filter', 'blocks', 'body' ], ConditionalExpression: [ 'test', 'consequent', 'alternate' ], ContinueStatement: [ 'label' ], DebuggerStatement: [ ], DoWhileStatement: [ 'test', 'body' ], EmptyStatement: [], //ES6: ExportDeclaration: [ 'declaration', 'specifiers', 'source'], //ES6: ExportBatchSpecifier: [ /* no children? */], //ES6: ExportSpecifier: [ 'id', 'name'], ExpressionStatement: [ 'expression'], ForInStatement: [ 'left', 'right', 'body' ], ForOfStatement: [ 'left', 'right', 'body' ], ForStatement: ['init', 'test', 'update', 'body' ], FunctionDeclaration: ['id', 'params', 'body' ], FunctionExpression: ['id', 'params', 'defaults', 'body' ], Identifier: [], IfStatement: ['test', 'consequent', 'alternate'], //ES6: ImportDeclaration: [ 'specifiers', 'kind', 'source' ], //ES6: ImportSpecifier: [ 'id', 'name' ], LabeledStatement: ['label', 'body'], Literal: [], LogicalExpression: [ 'left', 'right' ], MemberExpression: ['object', 'property'], //ES6: MethodDefinition: [ 'key', 'value', 'kind', 'static' ], //ES6: ModuleDeclaration: [ 'id', 'source', 'body' ], NewExpression: ['callee', 'arguments'], ObjectExpression: [ 'properties' ], //ES6: ObjectPattern: [ 'properties' ], Program: [ 'body' ], Property: [ 'key', 'value'], ReturnStatement: ['argument'], SequenceExpression: ['expressions'], //ES6: SpreadElement: [ 'argument' ], SwitchCase: [ 'test', 'consequent' ], SwitchStatement: ['discriminant', 'cases' ], //ES6: TaggedTemplateExpression: [ 'tag', 'quasi' ], //ES6: TemplateElement: [ 'value', 'tail' ], //ES6: TemplateLiteral: [ 'quasis', 'expressions' ], ThisExpression: [], ThrowStatement: ['argument'], TryStatement: [ 'block', 'handlers', 'finalizer' ], UnaryExpression: ['argument'], UpdateExpression: [ 'argument' ], VariableDeclaration: [ 'declarations' ], VariableDeclarator: [ 'id', 'init' ], WhileStatement: [ 'test', 'body' ], WithStatement: [ 'object', 'body' ], YieldExpression: [ 'argument' ] }; for (nodeType in SYNTAX) { /* istanbul ignore else: has own property */ if (SYNTAX.hasOwnProperty(nodeType)) { SYNTAX[nodeType] = { name: nodeType, children: SYNTAX[nodeType] }; } } astgen = { variable: function (name) { return { type: SYNTAX.Identifier.name, name: name }; }, stringLiteral: function (str) { return { type: SYNTAX.Literal.name, value: String(str) }; }, numericLiteral: function (num) { return { type: SYNTAX.Literal.name, value: Number(num) }; }, statement: function (contents) { return { type: SYNTAX.ExpressionStatement.name, expression: contents }; }, dot: function (obj, field) { return { type: SYNTAX.MemberExpression.name, computed: false, object: obj, property: field }; }, subscript: function (obj, sub) { return { type: SYNTAX.MemberExpression.name, computed: true, object: obj, property: sub }; }, postIncrement: function (obj) { return { type: SYNTAX.UpdateExpression.name, operator: '++', prefix: false, argument: obj }; }, sequence: function (one, two) { return { type: SYNTAX.SequenceExpression.name, expressions: [one, two] }; } }; function Walker(walkMap, preprocessor, scope, debug) { this.walkMap = walkMap; this.preprocessor = preprocessor; this.scope = scope; this.debug = debug; if (this.debug) { this.level = 0; this.seq = true; } } function defaultWalker(node, walker) { var type = node.type, preprocessor, postprocessor, children = SYNTAX[type].children, // don't run generated nodes thru custom walks otherwise we will attempt to instrument the instrumentation code :) applyCustomWalker = !!node.loc || node.type === SYNTAX.Program.name, walkerFn = applyCustomWalker ? walker.walkMap[type] : null, i, j, walkFnIndex, childType, childNode, ret, childArray, childElement, pathElement, assignNode, isLast; /* istanbul ignore if: guard */ if (node.walking) { throw new Error('Infinite regress: Custom walkers may NOT call walker.apply(node)'); } node.walking = true; ret = walker.apply(node, walker.preprocessor); preprocessor = ret.preprocessor; if (preprocessor) { delete ret.preprocessor; ret = walker.apply(node, preprocessor); } if (isArray(walkerFn)) { for (walkFnIndex = 0; walkFnIndex < walkerFn.length; walkFnIndex += 1) { isLast = walkFnIndex === walkerFn.length - 1; ret = walker.apply(ret, walkerFn[walkFnIndex]); /*istanbul ignore next: paranoid check */ if (ret.type !== type && !isLast) { throw new Error('Only the last walker is allowed to change the node type: [type was: ' + type + ' ]'); } } } else { if (walkerFn) { ret = walker.apply(node, walkerFn); } } for (i = 0; i < children.length; i += 1) { childType = children[i]; childNode = node[childType]; if (childNode && !childNode.skipWalk) { pathElement = { node: node, property: childType }; if (isArray(childNode)) { childArray = []; for (j = 0; j < childNode.length; j += 1) { childElement = childNode[j]; pathElement.index = j; if (childElement) { assignNode = walker.apply(childElement, null, pathElement); if (isArray(assignNode.prepend)) { pushAll(childArray, assignNode.prepend); delete assignNode.prepend; } } pushAll(childArray, assignNode); } node[childType] = childArray; } else { assignNode = walker.apply(childNode, null, pathElement); /*istanbul ignore if: paranoid check */ if (isArray(assignNode.prepend)) { throw new Error('Internal error: attempt to prepend statements in disallowed (non-array) context'); /* if this should be allowed, this is how to solve it tmpNode = { type: 'BlockStatement', body: [] }; pushAll(tmpNode.body, assignNode.prepend); pushAll(tmpNode.body, assignNode); node[childType] = tmpNode; delete assignNode.prepend; */ } else { node[childType] = assignNode; } } } } postprocessor = ret.postprocessor; if (postprocessor) { delete ret.postprocessor; ret = walker.apply(ret, postprocessor); } delete node.walking; return ret; } Walker.prototype = { startWalk: function (node) { this.path = []; this.apply(node); }, apply: function (node, walkFn, pathElement) { var ret, i, seq, prefix; walkFn = walkFn || defaultWalker; if (this.debug) { this.seq += 1; this.level += 1; seq = this.seq; prefix = ''; for (i = 0; i < this.level; i += 1) { prefix += ' '; } console.log(prefix + 'Enter (' + seq + '):' + node.type); } if (pathElement) { this.path.push(pathElement); } ret = walkFn.call(this.scope, node, this); if (pathElement) { this.path.pop(); } if (this.debug) { this.level -= 1; console.log(prefix + 'Return (' + seq + '):' + node.type); } return ret || node; }, startLineForNode: function (node) { return node && node.loc && node.loc.start ? node.loc.start.line : /* istanbul ignore next: guard */ null; }, ancestor: function (n) { return this.path.length > n - 1 ? this.path[this.path.length - n] : /* istanbul ignore next: guard */ null; }, parent: function () { return this.ancestor(1); }, isLabeled: function () { var el = this.parent(); return el && el.node.type === SYNTAX.LabeledStatement.name; } }; /** * mechanism to instrument code for coverage. It uses the `esprima` and * `escodegen` libraries for JS parsing and code generation respectively. * * Works on `node` as well as the browser. * * Usage on nodejs * --------------- * * var instrumenter = new require('istanbul').Instrumenter(), * changed = instrumenter.instrumentSync('function meaningOfLife() { return 42; }', 'filename.js'); * * Usage in a browser * ------------------ * * Load `esprima.js`, `escodegen.js` and `instrumenter.js` (this file) using `script` tags or other means. * * Create an instrumenter object as: * * var instrumenter = new Instrumenter(), * changed = instrumenter.instrumentSync('function meaningOfLife() { return 42; }', 'filename.js'); * * Aside from demonstration purposes, it is unclear why you would want to instrument code in a browser. * * @class Instrumenter * @constructor * @param {Object} options Optional. Configuration options. * @param {String} [options.coverageVariable] the global variable name to use for * tracking coverage. Defaults to `__coverage__` * @param {Boolean} [options.embedSource] whether to embed the source code of every * file as an array in the file coverage object for that file. Defaults to `false` * @param {Boolean} [options.preserveComments] whether comments should be preserved in the output. Defaults to `false` * @param {Boolean} [options.noCompact] emit readable code when set. Defaults to `false` * @param {Boolean} [options.noAutoWrap] do not automatically wrap the source in * an anonymous function before covering it. By default, code is wrapped in * an anonymous function before it is parsed. This is done because * some nodejs libraries have `return` statements outside of * a function which is technically invalid Javascript and causes the parser to fail. * This construct, however, works correctly in node since module loading * is done in the context of an anonymous function. * * Note that the semantics of the code *returned* by the instrumenter does not change in any way. * The function wrapper is "unwrapped" before the instrumented code is generated. * @param {Object} [options.codeGenerationOptions] an object that is directly passed to the `escodegen` * library as configuration for code generation. The `noCompact` setting is not honored when this * option is specified * @param {Boolean} [options.debug] assist in debugging. Currently, the only effect of * setting this option is a pretty-print of the coverage variable. Defaults to `false` * @param {Boolean} [options.walkDebug] assist in debugging of the AST walker used by this class. * */ function Instrumenter(options) { this.opts = options || { debug: false, walkDebug: false, coverageVariable: '__coverage__', codeGenerationOptions: undefined, noAutoWrap: false, noCompact: false, embedSource: false, preserveComments: false }; this.walker = new Walker({ ExpressionStatement: this.coverStatement, BreakStatement: this.coverStatement, ContinueStatement: this.coverStatement, DebuggerStatement: this.coverStatement, ReturnStatement: this.coverStatement, ThrowStatement: this.coverStatement, TryStatement: this.coverStatement, VariableDeclaration: this.coverStatement, IfStatement: [ this.ifBlockConverter, this.coverStatement, this.ifBranchInjector ], ForStatement: [ this.skipInit, this.loopBlockConverter, this.coverStatement ], ForInStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ], ForOfStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ], WhileStatement: [ this.loopBlockConverter, this.coverStatement ], DoWhileStatement: [ this.loopBlockConverter, this.coverStatement ], SwitchStatement: [ this.coverStatement, this.switchBranchInjector ], SwitchCase: [ this.switchCaseInjector ], WithStatement: this.coverStatement, FunctionDeclaration: [ this.coverFunction, this.coverStatement ], FunctionExpression: this.coverFunction, LabeledStatement: this.coverStatement, ConditionalExpression: this.conditionalBranchInjector, LogicalExpression: this.logicalExpressionBranchInjector, ObjectExpression: this.maybeAddType }, this.extractCurrentHint, this, this.opts.walkDebug); //unit testing purposes only if (this.opts.backdoor && this.opts.backdoor.omitTrackerSuffix) { this.omitTrackerSuffix = true; } } Instrumenter.prototype = { /** * synchronous instrumentation method. Throws when illegal code is passed to it * @method instrumentSync * @param {String} code the code to be instrumented as a String * @param {String} filename Optional. The name of the file from which * the code was read. A temporary filename is generated when not specified. * Not specifying a filename is only useful for unit tests and demonstrations * of this library. */ instrumentSync: function (code, filename) { var program; //protect from users accidentally passing in a Buffer object instead if (typeof code !== 'string') { throw new Error('Code must be string'); } if (code.charAt(0) === '#') { //shebang, 'comment' it out, won't affect syntax tree locations for things we care about code = '//' + code; } if (!this.opts.noAutoWrap) { code = LEADER_WRAP + code + TRAILER_WRAP; } program = ESP.parse(code, { loc: true, range: true, tokens: this.opts.preserveComments, comment: true }); if (this.opts.preserveComments) { program = ESPGEN.attachComments(program, program.comments, program.tokens); } if (!this.opts.noAutoWrap) { program = { type: SYNTAX.Program.name, body: program.body[0].expression.callee.body.body, comments: program.comments }; } return this.instrumentASTSync(program, filename, code); }, filterHints: function (comments) { var ret = [], i, comment, groups; if (!(comments && isArray(comments))) { return ret; } for (i = 0; i < comments.length; i += 1) { comment = comments[i]; /* istanbul ignore else: paranoid check */ if (comment && comment.value && comment.range && isArray(comment.range)) { groups = String(comment.value).match(COMMENT_RE); if (groups) { ret.push({ type: groups[1], start: comment.range[0], end: comment.range[1] }); } } } return ret; }, extractCurrentHint: function (node) { if (!node.range) { return; } var i = this.currentState.lastHintPosition + 1, hints = this.currentState.hints, nodeStart = node.range[0], hint; this.currentState.currentHint = null; while (i < hints.length) { hint = hints[i]; if (hint.end < nodeStart) { this.currentState.currentHint = hint; this.currentState.lastHintPosition = i; i += 1; } else { break; } } }, /** * synchronous instrumentation method that instruments an AST instead. * @method instrumentASTSync * @param {String} program the AST to be instrumented * @param {String} filename Optional. The name of the file from which * the code was read. A temporary filename is generated when not specified. * Not specifying a filename is only useful for unit tests and demonstrations * of this library. * @param {String} originalCode the original code corresponding to the AST, * used for embedding the source into the coverage object */ instrumentASTSync: function (program, filename, originalCode) { var usingStrict = false, codegenOptions; filename = filename || String(new Date().getTime()) + '.js'; this.coverState = { path: filename, s: {}, b: {}, f: {}, fnMap: {}, statementMap: {}, branchMap: {} }; this.currentState = { trackerVar: generateTrackerVar(filename, this.omitTrackerSuffix), func: 0, branch: 0, variable: 0, statement: 0, hints: this.filterHints(program.comments), currentHint: null, lastHintPosition: -1, ignoring: 0 }; if (program.body && program.body.length > 0 && this.isUseStrictExpression(program.body[0])) { //nuke it program.body.shift(); //and add it back at code generation time usingStrict = true; } this.walker.startWalk(program); codegenOptions = this.opts.codeGenerationOptions || { format: { compact: !this.opts.noCompact }}; codegenOptions.comment = this.opts.preserveComments; //console.log(JSON.stringify(program, undefined, 2)); return this.getPreamble(originalCode || '', usingStrict) + '\n' + ESPGEN.generate(program, codegenOptions) + '\n'; }, /** * Callback based instrumentation. Note that this still executes synchronously in the same process tick * and calls back immediately. It only provides the options for callback style error handling as * opposed to a `try-catch` style and nothing more. Implemented as a wrapper over `instrumentSync` * * @method instrument * @param {String} code the code to be instrumented as a String * @param {String} filename Optional. The name of the file from which * the code was read. A temporary filename is generated when not specified. * Not specifying a filename is only useful for unit tests and demonstrations * of this library. * @param {Function(err, instrumentedCode)} callback - the callback function */ instrument: function (code, filename, callback) { if (!callback && typeof filename === 'function') { callback = filename; filename = null; } try { callback(null, this.instrumentSync(code, filename)); } catch (ex) { callback(ex); } }, /** * returns the file coverage object for the code that was instrumented * just before calling this method. Note that this represents a * "zero-coverage" object which is not even representative of the code * being loaded in node or a browser (which would increase the statement * counts for mainline code). * @return {Object} a "zero-coverage" file coverage object for the code last instrumented * by this instrumenter */ lastFileCoverage: function () { return this.coverState; }, fixColumnPositions: function (coverState) { var offset = LEADER_WRAP.length, fixer = function (loc) { if (loc.start.line === 1) { loc.start.column -= offset; } if (loc.end.line === 1) { loc.end.column -= offset; } }, k, obj, i, locations; obj = coverState.statementMap; for (k in obj) { /* istanbul ignore else: has own property */ if (obj.hasOwnProperty(k)) { fixer(obj[k]); } } obj = coverState.fnMap; for (k in obj) { /* istanbul ignore else: has own property */ if (obj.hasOwnProperty(k)) { fixer(obj[k].loc); } } obj = coverState.branchMap; for (k in obj) { /* istanbul ignore else: has own property */ if (obj.hasOwnProperty(k)) { locations = obj[k].locations; for (i = 0; i < locations.length; i += 1) { fixer(locations[i]); } } } }, getPreamble: function (sourceCode, emitUseStrict) { var varName = this.opts.coverageVariable || '__coverage__', file = this.coverState.path.replace(/\\/g, '\\\\'), tracker = this.currentState.trackerVar, coverState, strictLine = emitUseStrict ? '"use strict";' : '', // return replacements using the function to ensure that the replacement is // treated like a dumb string and not as a string with RE replacement patterns replacer = function (s) { return function () { return s; }; }, code; if (!this.opts.noAutoWrap) { this.fixColumnPositions(this.coverState); } if (this.opts.embedSource) { this.coverState.code = sourceCode.split(/(?:\r?\n)|\r/); } coverState = this.opts.debug ? JSON.stringify(this.coverState, undefined, 4) : JSON.stringify(this.coverState); code = [ "%STRICT%", "var %VAR% = (Function('return this'))();", "if (!%VAR%.%GLOBAL%) { %VAR%.%GLOBAL% = {}; }", "%VAR% = %VAR%.%GLOBAL%;", "if (!(%VAR%['%FILE%'])) {", " %VAR%['%FILE%'] = %OBJECT%;", "}", "%VAR% = %VAR%['%FILE%'];" ].join("\n") .replace(/%STRICT%/g, replacer(strictLine)) .replace(/%VAR%/g, replacer(tracker)) .replace(/%GLOBAL%/g, replacer(varName)) .replace(/%FILE%/g, replacer(file)) .replace(/%OBJECT%/g, replacer(coverState)); return code; }, startIgnore: function () { this.currentState.ignoring += 1; }, endIgnore: function () { this.currentState.ignoring -= 1; }, convertToBlock: function (node) { if (!node) { return { type: 'BlockStatement', body: [] }; } else if (node.type === 'BlockStatement') { return node; } else { return { type: 'BlockStatement', body: [ node ] }; } }, ifBlockConverter: function (node) { node.consequent = this.convertToBlock(node.consequent); node.alternate = this.convertToBlock(node.alternate); }, loopBlockConverter: function (node) { node.body = this.convertToBlock(node.body); }, statementName: function (location, initValue) { var sName, ignoring = !!this.currentState.ignoring; location.skip = ignoring || undefined; initValue = initValue || 0; this.currentState.statement += 1; sName = this.currentState.statement; this.coverState.statementMap[sName] = location; this.coverState.s[sName] = initValue; return sName; }, skipInit: function (node /*, walker */) { if (node.init) { node.init.skipWalk = true; } }, skipLeft: function (node /*, walker */) { node.left.skipWalk = true; }, isUseStrictExpression: function (node) { return node && node.type === SYNTAX.ExpressionStatement.name && node.expression && node.expression.type === SYNTAX.Literal.name && node.expression.value === 'use strict'; }, maybeSkipNode: function (node, type) { var alreadyIgnoring = !!this.currentState.ignoring, hint = this.currentState.currentHint, ignoreThis = !alreadyIgnoring && hint && hint.type === type; if (ignoreThis) { this.startIgnore(); node.postprocessor = this.endIgnore; return true; } return false; }, coverStatement: function (node, walker) { var sName, incrStatementCount, grandParent; this.maybeSkipNode(node, 'next'); if (this.isUseStrictExpression(node)) { grandParent = walker.ancestor(2); /* istanbul ignore else: difficult to test */ if (grandParent) { if ((grandParent.node.type === SYNTAX.FunctionExpression.name || grandParent.node.type === SYNTAX.FunctionDeclaration.name) && walker.parent().node.body[0] === node) { return; } } } if (node.type === SYNTAX.FunctionDeclaration.name) { sName = this.statementName(node.loc, 1); } else { sName = this.statementName(node.loc); incrStatementCount = astgen.statement( astgen.postIncrement( astgen.subscript( astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('s')), astgen.stringLiteral(sName) ) ) ); this.splice(incrStatementCount, node, walker); } }, splice: function (statements, node, walker) { var targetNode = walker.isLabeled() ? walker.parent().node : node; targetNode.prepend = targetNode.prepend || []; pushAll(targetNode.prepend, statements); }, functionName: function (node, line, location) { this.currentState.func += 1; var id = this.currentState.func, ignoring = !!this.currentState.ignoring, name = node.id ? node.id.name : '(anonymous_' + id + ')'; this.coverState.fnMap[id] = { name: name, line: line, loc: location, skip: ignoring || undefined }; this.coverState.f[id] = 0; return id; }, coverFunction: function (node, walker) { var id, body = node.body, blockBody = body.body, popped; this.maybeSkipNode(node, 'next'); id = this.functionName(node, walker.startLineForNode(node), { start: node.loc.start, end: { line: node.body.loc.start.line, column: node.body.loc.start.column } }); if (blockBody.length > 0 && this.isUseStrictExpression(blockBody[0])) { popped = blockBody.shift(); } blockBody.unshift( astgen.statement( astgen.postIncrement( astgen.subscript( astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('f')), astgen.stringLiteral(id) ) ) ) ); if (popped) { blockBody.unshift(popped); } }, branchName: function (type, startLine, pathLocations) { var bName, paths = [], locations = [], i, ignoring = !!this.currentState.ignoring; this.currentState.branch += 1; bName = this.currentState.branch; for (i = 0; i < pathLocations.length; i += 1) { pathLocations[i].skip = pathLocations[i].skip || ignoring || undefined; locations.push(pathLocations[i]); paths.push(0); } this.coverState.b[bName] = paths; this.coverState.branchMap[bName] = { line: startLine, type: type, locations: locations }; return bName; }, branchIncrementExprAst: function (varName, branchIndex, down) { var ret = astgen.postIncrement( astgen.subscript( astgen.subscript( astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('b')), astgen.stringLiteral(varName) ), astgen.numericLiteral(branchIndex) ), down ); return ret; }, locationsForNodes: function (nodes) { var ret = [], i; for (i = 0; i < nodes.length; i += 1) { ret.push(nodes[i].loc); } return ret; }, ifBranchInjector: function (node, walker) { var alreadyIgnoring = !!this.currentState.ignoring, hint = this.currentState.currentHint, ignoreThen = !alreadyIgnoring && hint && hint.type === 'if', ignoreElse = !alreadyIgnoring && hint && hint.type === 'else', line = node.loc.start.line, col = node.loc.start.column, start = { line: line, column: col }, end = { line: line, column: col }, bName = this.branchName('if', walker.startLineForNode(node), [ { start: start, end: end, skip: ignoreThen || undefined }, { start: start, end: end, skip: ignoreElse || undefined } ]), thenBody = node.consequent.body, elseBody = node.alternate.body, child; thenBody.unshift(astgen.statement(this.branchIncrementExprAst(bName, 0))); elseBody.unshift(astgen.statement(this.branchIncrementExprAst(bName, 1))); if (ignoreThen) { child = node.consequent; child.preprocessor = this.startIgnore; child.postprocessor = this.endIgnore; } if (ignoreElse) { child = node.alternate; child.preprocessor = this.startIgnore; child.postprocessor = this.endIgnore; } }, branchLocationFor: function (name, index) { return this.coverState.branchMap[name].locations[index]; }, switchBranchInjector: function (node, walker) { var cases = node.cases, bName, i; if (!(cases && cases.length > 0)) { return; } bName = this.branchName('switch', walker.startLineForNode(node), this.locationsForNodes(cases)); for (i = 0; i < cases.length; i += 1) { cases[i].branchLocation = this.branchLocationFor(bName, i); cases[i].consequent.unshift(astgen.statement(this.branchIncrementExprAst(bName, i))); } }, switchCaseInjector: function (node) { var location = node.branchLocation; delete node.branchLocation; if (this.maybeSkipNode(node, 'next')) { location.skip = true; } }, conditionalBranchInjector: function (node, walker) { var bName = this.branchName('cond-expr', walker.startLineForNode(node), this.locationsForNodes([ node.consequent, node.alternate ])), ast1 = this.branchIncrementExprAst(bName, 0), ast2 = this.branchIncrementExprAst(bName, 1); node.consequent.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, 0)); node.alternate.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, 1)); node.consequent = astgen.sequence(ast1, node.consequent); node.alternate = astgen.sequence(ast2, node.alternate); }, maybeAddSkip: function (branchLocation) { return function (node) { var alreadyIgnoring = !!this.currentState.ignoring, hint = this.currentState.currentHint, ignoreThis = !alreadyIgnoring && hint && hint.type === 'next'; if (ignoreThis) { this.startIgnore(); node.postprocessor = this.endIgnore; } if (ignoreThis || alreadyIgnoring) { branchLocation.skip = true; } }; }, logicalExpressionBranchInjector: function (node, walker) { var parent = walker.parent(), leaves = [], bName, tuple, i; this.maybeSkipNode(node, 'next'); if (parent && parent.node.type === SYNTAX.LogicalExpression.name) { //already covered return; } this.findLeaves(node, leaves); bName = this.branchName('binary-expr', walker.startLineForNode(node), this.locationsForNodes(leaves.map(function (item) { return item.node; })) ); for (i = 0; i < leaves.length; i += 1) { tuple = leaves[i]; tuple.parent[tuple.property] = astgen.sequence(this.branchIncrementExprAst(bName, i), tuple.node); tuple.node.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, i)); } }, findLeaves: function (node, accumulator, parent, property) { if (node.type === SYNTAX.LogicalExpression.name) { this.findLeaves(node.left, accumulator, node, 'left'); this.findLeaves(node.right, accumulator, node, 'right'); } else { accumulator.push({ node: node, parent: parent, property: property }); } }, maybeAddType: function (node /*, walker */) { var props = node.properties, i, child; for (i = 0; i < props.length; i += 1) { child = props[i]; if (!child.type) { child.type = SYNTAX.Property.name; } } } }; if (isNode) { module.exports = Instrumenter; } else { window.Instrumenter = Instrumenter; } }(typeof module !== 'undefined' && typeof module.exports !== 'undefined' && typeof exports !== 'undefined'));
/* * jsPlumb * * Title:jsPlumb 1.4.0 * * Provides a way to visually connect elements on an HTML page, using either SVG or VML. * * This file contains the util functions * * Copyright (c) 2010 - 2013 Simon Porritt (http://jsplumb.org) * * http://jsplumb.org * http://github.com/sporritt/jsplumb * http://code.google.com/p/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ;(function() { var pointHelper = function(p1, p2, fn) { p1 = jsPlumbUtil.isArray(p1) ? p1 : [p1.x, p1.y]; p2 = jsPlumbUtil.isArray(p2) ? p2 : [p2.x, p2.y]; return fn(p1, p2); }; jsPlumbUtil = { isArray : function(a) { return Object.prototype.toString.call(a) === "[object Array]"; }, isString : function(s) { return typeof s === "string"; }, isBoolean: function(s) { return typeof s === "boolean"; }, isObject : function(o) { return Object.prototype.toString.call(o) === "[object Object]"; }, isDate : function(o) { return Object.prototype.toString.call(o) === "[object Date]"; }, isFunction: function(o) { return Object.prototype.toString.call(o) === "[object Function]"; }, clone : function(a) { if (this.isString(a)) return "" + a; else if (this.isBoolean(a)) return !!a; else if (this.isDate(a)) return new Date(a.getTime()); else if (this.isFunction(a)) return a; else if (this.isArray(a)) { var b = []; for (var i = 0; i < a.length; i++) b.push(this.clone(a[i])); return b; } else if (this.isObject(a)) { var b = {}; for (var i in a) b[i] = this.clone(a[i]); return b; } else return a; }, merge : function(a, b) { var c = this.clone(a); for (var i in b) { if (c[i] == null || this.isString(b[i]) || this.isBoolean(b[i])) c[i] = b[i]; else { if (this.isArray(b[i])/* && this.isArray(c[i])*/) { var ar = []; // if c's object is also an array we can keep its values. if (this.isArray(c[i])) ar.push.apply(ar, c[i]); ar.push.apply(ar, b[i]); c[i] = ar; } else if(this.isObject(b[i])) { // overwite c's value with an object if it is not already one. if (!this.isObject(c[i])) c[i] = {}; for (var j in b[i]) c[i][j] = b[i][j]; } } } return c; }, copyValues:function(names, from, to) { for (var i = 0; i < names.length; i++) to[names[i]] = from[names[i]]; }, // // chain a list of functions, supplied by [ object, method name, args ], and return on the first // one that returns the failValue. if none return the failValue, return the successValue. // functionChain : function(successValue, failValue, fns) { for (var i = 0; i < fns.length; i++) { var o = fns[i][0][fns[i][1]].apply(fns[i][0], fns[i][2]); if (o === failValue) { return o; } } return successValue; }, // take the given model and expand out any parameters. populate : function(model, values) { // for a string, see if it has parameter matches, and if so, try to make the substitutions. var getValue = function(fromString) { var matches = fromString.match(/(\${.*?})/g); if (matches != null) { for (var i = 0; i < matches.length; i++) { var val = values[matches[i].substring(2, matches[i].length - 1)]; if (val) { fromString = fromString.replace(matches[i], val); } } } return fromString; }, // process one entry. _one = function(d) { if (d != null) { if (jsPlumbUtil.isString(d)) { return getValue(d); } else if (jsPlumbUtil.isArray(d)) { var r = []; for (var i = 0; i < d.length; i++) r.push(_one(d[i])); return r; } else if (jsPlumbUtil.isObject(d)) { var r = {}; for (var i in d) { r[i] = _one(d[i]); } return r; } else { return d; } } }; return _one(model); }, convertStyle : function(s, ignoreAlpha) { // TODO: jsPlumb should support a separate 'opacity' style member. if ("transparent" === s) return s; var o = s, pad = function(n) { return n.length == 1 ? "0" + n : n; }, hex = function(k) { return pad(Number(k).toString(16)); }, pattern = /(rgb[a]?\()(.*)(\))/; if (s.match(pattern)) { var parts = s.match(pattern)[2].split(","); o = "#" + hex(parts[0]) + hex(parts[1]) + hex(parts[2]); if (!ignoreAlpha && parts.length == 4) o = o + hex(parts[3]); } return o; }, gradient : function(p1, p2) { return pointHelper(p1, p2, function(_p1, _p2) { if (_p2[0] == _p1[0]) return _p2[1] > _p1[1] ? Infinity : -Infinity; else if (_p2[1] == _p1[1]) return _p2[0] > _p1[0] ? 0 : -0; else return (_p2[1] - _p1[1]) / (_p2[0] - _p1[0]); }); }, normal : function(p1, p2) { return -1 / this.gradient(p1, p2); }, lineLength : function(p1, p2) { return pointHelper(p1, p2, function(_p1, _p2) { return Math.sqrt(Math.pow(_p2[1] - _p1[1], 2) + Math.pow(_p2[0] - _p1[0], 2)); }); }, segment : function(p1, p2) { return pointHelper(p1, p2, function(_p1, _p2) { if (_p2[0] > _p1[0]) { return (_p2[1] > _p1[1]) ? 2 : 1; } else if (_p2[0] == _p1[0]) { return _p2[1] > _p1[1] ? 2 : 1; } else { return (_p2[1] > _p1[1]) ? 3 : 4; } }); }, theta : function(p1, p2) { return pointHelper(p1, p2, function(_p1, _p2) { var m = jsPlumbUtil.gradient(_p1, _p2), t = Math.atan(m), s = jsPlumbUtil.segment(_p1, _p2); if ((s == 4 || s== 3)) t += Math.PI; if (t < 0) t += (2 * Math.PI); return t; }); }, intersects : function(r1, r2) { var x1 = r1.x, x2 = r1.x + r1.w, y1 = r1.y, y2 = r1.y + r1.h, a1 = r2.x, a2 = r2.x + r2.w, b1 = r2.y, b2 = r2.y + r2.h; return ( (x1 <= a1 && a1 <= x2) && (y1 <= b1 && b1 <= y2) ) || ( (x1 <= a2 && a2 <= x2) && (y1 <= b1 && b1 <= y2) ) || ( (x1 <= a1 && a1 <= x2) && (y1 <= b2 && b2 <= y2) ) || ( (x1 <= a2 && a1 <= x2) && (y1 <= b2 && b2 <= y2) ) || ( (a1 <= x1 && x1 <= a2) && (b1 <= y1 && y1 <= b2) ) || ( (a1 <= x2 && x2 <= a2) && (b1 <= y1 && y1 <= b2) ) || ( (a1 <= x1 && x1 <= a2) && (b1 <= y2 && y2 <= b2) ) || ( (a1 <= x2 && x1 <= a2) && (b1 <= y2 && y2 <= b2) ); }, segmentMultipliers : [null, [1, -1], [1, 1], [-1, 1], [-1, -1] ], inverseSegmentMultipliers : [null, [-1, -1], [-1, 1], [1, 1], [1, -1] ], pointOnLine : function(fromPoint, toPoint, distance) { var m = jsPlumbUtil.gradient(fromPoint, toPoint), s = jsPlumbUtil.segment(fromPoint, toPoint), segmentMultiplier = distance > 0 ? jsPlumbUtil.segmentMultipliers[s] : jsPlumbUtil.inverseSegmentMultipliers[s], theta = Math.atan(m), y = Math.abs(distance * Math.sin(theta)) * segmentMultiplier[1], x = Math.abs(distance * Math.cos(theta)) * segmentMultiplier[0]; return { x:fromPoint.x + x, y:fromPoint.y + y }; }, /** * calculates a perpendicular to the line fromPoint->toPoint, that passes through toPoint and is 'length' long. * @param fromPoint * @param toPoint * @param length */ perpendicularLineTo : function(fromPoint, toPoint, length) { var m = jsPlumbUtil.gradient(fromPoint, toPoint), theta2 = Math.atan(-1 / m), y = length / 2 * Math.sin(theta2), x = length / 2 * Math.cos(theta2); return [{x:toPoint.x + x, y:toPoint.y + y}, {x:toPoint.x - x, y:toPoint.y - y}]; }, findWithFunction : function(a, f) { if (a) for (var i = 0; i < a.length; i++) if (f(a[i])) return i; return -1; }, clampToGrid : function(x, y, grid, dontClampX, dontClampY) { var _gridClamp = function(n, g) { var e = n % g, f = Math.floor(n / g), inc = e >= (g / 2) ? 1 : 0; return (f + inc) * g; }; return [ dontClampX || grid == null ? x : _gridClamp(x, grid[0]), dontClampY || grid == null ? y : _gridClamp(y, grid[1]) ]; }, indexOf : function(l, v) { return jsPlumbUtil.findWithFunction(l, function(_v) { return _v == v; }); }, removeWithFunction : function(a, f) { var idx = jsPlumbUtil.findWithFunction(a, f); if (idx > -1) a.splice(idx, 1); return idx != -1; }, remove : function(l, v) { var idx = jsPlumbUtil.indexOf(l, v); if (idx > -1) l.splice(idx, 1); return idx != -1; }, // TODO support insert index addWithFunction : function(list, item, hashFunction) { if (jsPlumbUtil.findWithFunction(list, hashFunction) == -1) list.push(item); }, addToList : function(map, key, value) { var l = map[key]; if (l == null) { l = [], map[key] = l; } l.push(value); return l; }, /** * EventGenerator * Superclass for objects that generate events - jsPlumb extends this, as does jsPlumbUIComponent, which all the UI elements extend. */ EventGenerator : function() { var _listeners = {}, self = this, eventsSuspended = false; // this is a list of events that should re-throw any errors that occur during their dispatch. as of 1.3.0 this is private to // jsPlumb, but it seems feasible that people might want to manipulate this list. the thinking is that we don't want event // listeners to bring down jsPlumb - or do we. i can't make up my mind about this, but i know i want to hear about it if the "ready" // event fails, because then my page has most likely not initialised. so i have this halfway-house solution. it will be interesting // to hear what other people think. var eventsToDieOn = [ "ready" ]; /* * Binds a listener to an event. * * Parameters: * event - name of the event to bind to. * listener - function to execute. */ this.bind = function(event, listener) { jsPlumbUtil.addToList(_listeners, event, listener); return self; }; /* * Fires an update for the given event. * * Parameters: * event - event to fire * value - value to pass to the event listener(s). * originalEvent - the original event from the browser */ this.fire = function(event, value, originalEvent) { if (!eventsSuspended && _listeners[event]) { for ( var i = 0; i < _listeners[event].length; i++) { // doing it this way rather than catching and then possibly re-throwing means that an error propagated by this // method will have the whole call stack available in the debugger. if (jsPlumbUtil.findWithFunction(eventsToDieOn, function(e) { return e === event}) != -1) _listeners[event][i](value, originalEvent); else { // for events we don't want to die on, catch and log. try { _listeners[event][i](value, originalEvent); } catch (e) { jsPlumbUtil.log("jsPlumb: fire failed for event " + event + " : " + e); } } } } return self; }; /* * Clears either all listeners, or listeners for some specific event. * * Parameters: * event - optional. constrains the clear to just listeners for this event. */ this.unbind = function(event) { if (event) delete _listeners[event]; else { _listeners = {}; } return self; }; this.getListener = function(forEvent) { return _listeners[forEvent]; }; this.setSuspendEvents = function(val) { eventsSuspended = val; }; this.isSuspendEvents = function() { return eventsSuspended; }; }, logEnabled : true, log : function() { if (jsPlumbUtil.logEnabled && typeof console != "undefined") { try { var msg = arguments[arguments.length - 1]; console.log(msg); } catch (e) {} } }, group : function(g) { if (jsPlumbUtil.logEnabled && typeof console != "undefined") console.group(g); }, groupEnd : function(g) { if (jsPlumbUtil.logEnabled && typeof console != "undefined") console.groupEnd(g); }, time : function(t) { if (jsPlumbUtil.logEnabled && typeof console != "undefined") console.time(t); }, timeEnd : function(t) { if (jsPlumbUtil.logEnabled && typeof console != "undefined") console.timeEnd(t); }, /** * helper to remove an element from the DOM. */ removeElement : function(element) { if (element != null && element.parentNode != null) { element.parentNode.removeChild(element); } }, /** * helper to remove a list of elements from the DOM. */ removeElements : function(elements) { for ( var i = 0; i < elements.length; i++) jsPlumbUtil.removeElement(elements[i]); } }; })();/* * jsPlumb * * Title:jsPlumb 1.4.0 * * Provides a way to visually connect elements on an HTML page, using either SVG, Canvas * elements, or VML. * * This file contains the base functionality for DOM type adapters. * * Copyright (c) 2010 - 2013 Simon Porritt (http://jsplumb.org) * * http://jsplumb.org * http://github.com/sporritt/jsplumb * http://code.google.com/p/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ;(function() { var canvasAvailable = !!document.createElement('canvas').getContext, svgAvailable = !!window.SVGAngle || document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"), // http://stackoverflow.com/questions/654112/how-do-you-detect-support-for-vml-or-svg-in-a-browser vmlAvailable = function() { if (vmlAvailable.vml == undefined) { var a = document.body.appendChild(document.createElement('div')); a.innerHTML = '<v:shape id="vml_flag1" adj="1" />'; var b = a.firstChild; b.style.behavior = "url(#default#VML)"; vmlAvailable.vml = b ? typeof b.adj == "object": true; a.parentNode.removeChild(a); } return vmlAvailable.vml; }; /** Manages dragging for some instance of jsPlumb. */ var DragManager = function(_currentInstance) { var _draggables = {}, _dlist = [], _delements = {}, _elementsWithEndpoints = {}, // elementids mapped to the draggable to which they belong. _draggablesForElements = {}; /** register some element as draggable. right now the drag init stuff is done elsewhere, and it is possible that will continue to be the case. */ this.register = function(el) { var jpcl = jsPlumb.CurrentLibrary; el = jpcl.getElementObject(el); var id = _currentInstance.getId(el), domEl = jpcl.getDOMElement(el), parentOffset = jpcl.getOffset(el); if (!_draggables[id]) { _draggables[id] = el; _dlist.push(el); _delements[id] = {}; } // look for child elements that have endpoints and register them against this draggable. var _oneLevel = function(p, startOffset) { if (p) { for (var i = 0; i < p.childNodes.length; i++) { if (p.childNodes[i].nodeType != 3 && p.childNodes[i].nodeType != 8) { var cEl = jpcl.getElementObject(p.childNodes[i]), cid = _currentInstance.getId(cEl, null, true); if (cid && _elementsWithEndpoints[cid] && _elementsWithEndpoints[cid] > 0) { var cOff = jpcl.getOffset(cEl); _delements[id][cid] = { id:cid, offset:{ left:cOff.left - parentOffset.left, top:cOff.top - parentOffset.top } }; _draggablesForElements[cid] = id; } _oneLevel(p.childNodes[i]); } } } }; _oneLevel(domEl); }; // refresh the offsets for child elements of this element. this.updateOffsets = function(elId) { var jpcl = jsPlumb.CurrentLibrary, el = jpcl.getElementObject(elId), id = _currentInstance.getId(el), children = _delements[id], parentOffset = jpcl.getOffset(el); if (children) { for (var i in children) { var cel = jpcl.getElementObject(i), cOff = jpcl.getOffset(cel); _delements[id][i] = { id:i, offset:{ left:cOff.left - parentOffset.left, top:cOff.top - parentOffset.top } }; _draggablesForElements[i] = id; } } }; /** notification that an endpoint was added to the given el. we go up from that el's parent node, looking for a parent that has been registered as a draggable. if we find one, we add this el to that parent's list of elements to update on drag (if it is not there already) */ this.endpointAdded = function(el) { var jpcl = jsPlumb.CurrentLibrary, b = document.body, id = _currentInstance.getId(el), c = jpcl.getDOMElement(el), p = c.parentNode, done = p == b; _elementsWithEndpoints[id] = _elementsWithEndpoints[id] ? _elementsWithEndpoints[id] + 1 : 1; while (p != null && p != b) { var pid = _currentInstance.getId(p, null, true); if (pid && _draggables[pid]) { var idx = -1, pEl = jpcl.getElementObject(p), pLoc = jpcl.getOffset(pEl); if (_delements[pid][id] == null) { var cLoc = jsPlumb.CurrentLibrary.getOffset(el); _delements[pid][id] = { id:id, offset:{ left:cLoc.left - pLoc.left, top:cLoc.top - pLoc.top } }; _draggablesForElements[id] = pid; } break; } p = p.parentNode; } }; this.endpointDeleted = function(endpoint) { if (_elementsWithEndpoints[endpoint.elementId]) { _elementsWithEndpoints[endpoint.elementId]--; if (_elementsWithEndpoints[endpoint.elementId] <= 0) { for (var i in _delements) { if (_delements[i]) { delete _delements[i][endpoint.elementId]; delete _draggablesForElements[endpoint.elementId]; } } } } }; this.changeId = function(oldId, newId) { _delements[newId] = _delements[oldId]; _delements[oldId] = {}; _draggablesForElements[newId] = _draggablesForElements[oldId]; _draggablesForElements[oldId] = null; }; this.getElementsForDraggable = function(id) { return _delements[id]; }; this.elementRemoved = function(elementId) { var elId = _draggablesForElements[elementId]; if (elId) { delete _delements[elId][elementId]; delete _draggablesForElements[elementId]; } }; this.reset = function() { _draggables = {}; _dlist = []; _delements = {}; _elementsWithEndpoints = {}; }; }; // for those browsers that dont have it. they still don't have it! but at least they won't crash. if (!window.console) window.console = { time:function(){}, timeEnd:function(){}, group:function(){}, groupEnd:function(){}, log:function(){} }; window.jsPlumbAdapter = { headless:false, appendToRoot : function(node) { document.body.appendChild(node); }, getRenderModes : function() { return [ "canvas", "svg", "vml" ] }, isRenderModeAvailable : function(m) { return { "canvas":canvasAvailable, "svg":svgAvailable, "vml":vmlAvailable() }[m]; }, getDragManager : function(_jsPlumb) { return new DragManager(_jsPlumb); }, setRenderMode : function(mode) { var renderMode; if (mode) { mode = mode.toLowerCase(); var canvasAvailable = this.isRenderModeAvailable("canvas"), svgAvailable = this.isRenderModeAvailable("svg"), vmlAvailable = this.isRenderModeAvailable("vml"); // now test we actually have the capability to do this. if (mode === "svg") { if (svgAvailable) renderMode = "svg" else if (canvasAvailable) renderMode = "canvas" else if (vmlAvailable) renderMode = "vml" } else if (mode === "canvas" && canvasAvailable) renderMode = "canvas"; else if (vmlAvailable) renderMode = "vml"; } return renderMode; } }; })();/* * jsPlumb * * Title:jsPlumb 1.4.0 * * Provides a way to visually connect elements on an HTML page, using either SVG, Canvas * elements, or VML. * * This file contains the jsPlumb core code. * * Copyright (c) 2010 - 2013 Simon Porritt (simon.porritt@gmail.com) * * http://jsplumb.org * http://github.com/sporritt/jsplumb * http://code.google.com/p/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ;(function() { var _findWithFunction = jsPlumbUtil.findWithFunction, _indexOf = jsPlumbUtil.indexOf, _removeWithFunction = jsPlumbUtil.removeWithFunction, _remove = jsPlumbUtil.remove, // TODO support insert index _addWithFunction = jsPlumbUtil.addWithFunction, _addToList = jsPlumbUtil.addToList, /** an isArray function that even works across iframes...see here: http://tobyho.com/2011/01/28/checking-types-in-javascript/ i was originally using "a.constructor == Array" as a test. */ _isArray = jsPlumbUtil.isArray, _isString = jsPlumbUtil.isString, _isObject = jsPlumbUtil.isObject; var _att = function(el, attName) { return jsPlumb.CurrentLibrary.getAttribute(_gel(el), attName); }, _setAttribute = function(el, attName, attValue) { jsPlumb.CurrentLibrary.setAttribute(_gel(el), attName, attValue); }, _addClass = function(el, clazz) { jsPlumb.CurrentLibrary.addClass(_gel(el), clazz); }, _hasClass = function(el, clazz) { return jsPlumb.CurrentLibrary.hasClass(_gel(el), clazz); }, _removeClass = function(el, clazz) { jsPlumb.CurrentLibrary.removeClass(_gel(el), clazz); }, _gel = function(el) { return jsPlumb.CurrentLibrary.getElementObject(el); }, _getOffset = function(el, _instance) { var o = jsPlumb.CurrentLibrary.getOffset(_gel(el)); if (_instance != null) { var z = _instance.getZoom(); if (typeof o === 'undefined') { console.log("DEBUG ME!!"); // TODO: how can this happen?? return {left:0, top:0}; } else { return {left:o.left / z, top:o.top / z }; } } else return o; }, _getSize = function(el) { return jsPlumb.CurrentLibrary.getSize(_gel(el)); }, _log = jsPlumbUtil.log, _group = jsPlumbUtil.group, _groupEnd = jsPlumbUtil.groupEnd, _time = jsPlumbUtil.time, _timeEnd = jsPlumbUtil.timeEnd, /** * creates a timestamp, using milliseconds since 1970, but as a string. */ _timestamp = function() { return "" + (new Date()).getTime(); }, /* * Class:jsPlumbUIComponent * Abstract superclass for UI components Endpoint and Connection. Provides the abstraction of paintStyle/hoverPaintStyle, * and also extends jsPlumbUtil.EventGenerator to provide the bind and fire methods. */ jsPlumbUIComponent = window.jsPlumbUIComponent = function(params) { var self = this, a = arguments, _hover = false, parameters = params.parameters || {}, idPrefix = self.idPrefix, id = idPrefix + (new Date()).getTime(), paintStyle = null, hoverPaintStyle = null; self._jsPlumb = params["_jsPlumb"]; self.getId = function() { return id; }; self.hoverClass = params.hoverClass || self._jsPlumb.Defaults.HoverClass || jsPlumb.Defaults.HoverClass; // all components can generate events jsPlumbUtil.EventGenerator.apply(this); if (params.events) { for (var i in params.events) self.bind(i, params.events[i]); } // all components get this clone function. // TODO issue 116 showed a problem with this - it seems 'a' that is in // the clone function's scope is shared by all invocations of it, the classic // JS closure problem. for now, jsPlumb does a version of this inline where // it used to call clone. but it would be nice to find some time to look // further at this. this.clone = function() { var o = new Object(); self.constructor.apply(o, a); return o; }; this.getParameter = function(name) { return parameters[name]; }, this.getParameters = function() { return parameters; }, this.setParameter = function(name, value) { parameters[name] = value; }, this.setParameters = function(p) { parameters = p; }, this.overlayPlacements = []; // user can supply a beforeDetach callback, which will be executed before a detach // is performed; returning false prevents the detach. var beforeDetach = params.beforeDetach; this.isDetachAllowed = function(connection) { var r = true; if (beforeDetach) { try { r = beforeDetach(connection); } catch (e) { _log("jsPlumb: beforeDetach callback failed", e); } } return r; }; // user can supply a beforeDrop callback, which will be executed before a dropped // connection is confirmed. user can return false to reject connection. var beforeDrop = params.beforeDrop; this.isDropAllowed = function(sourceId, targetId, scope, connection, dropEndpoint) { var r = self._jsPlumb.checkCondition("beforeDrop", { sourceId:sourceId, targetId:targetId, scope:scope, connection:connection, dropEndpoint:dropEndpoint }); if (beforeDrop) { try { r = beforeDrop({ sourceId:sourceId, targetId:targetId, scope:scope, connection:connection, dropEndpoint:dropEndpoint }); } catch (e) { _log("jsPlumb: beforeDrop callback failed", e); } } return r; }; // helper method to update the hover style whenever it, or paintStyle, changes. // we use paintStyle as the foundation and merge hoverPaintStyle over the // top. var _updateHoverStyle = function() { if (paintStyle && hoverPaintStyle) { var mergedHoverStyle = {}; jsPlumb.extend(mergedHoverStyle, paintStyle); jsPlumb.extend(mergedHoverStyle, hoverPaintStyle); delete self["hoverPaintStyle"]; // we want the fillStyle of paintStyle to override a gradient, if possible. if (mergedHoverStyle.gradient && paintStyle.fillStyle) delete mergedHoverStyle["gradient"]; hoverPaintStyle = mergedHoverStyle; } }; /* * Sets the paint style and then repaints the element. * * Parameters: * style - Style to use. */ this.setPaintStyle = function(style, doNotRepaint) { paintStyle = style; self.paintStyleInUse = paintStyle; _updateHoverStyle(); if (!doNotRepaint) self.repaint(); }; /** * Gets the component's paint style. * * Returns: * the component's paint style. if there is no hoverPaintStyle set then this will be the paint style used all the time, otherwise this is the style used when the mouse is not hovering. */ this.getPaintStyle = function() { return paintStyle; }; /* * Sets the paint style to use when the mouse is hovering over the element. This is null by default. * The hover paint style is applied as extensions to the paintStyle; it does not entirely replace * it. This is because people will most likely want to change just one thing when hovering, say the * color for example, but leave the rest of the appearance the same. * * Parameters: * style - Style to use when the mouse is hovering. * doNotRepaint - if true, the component will not be repainted. useful when setting things up initially. */ this.setHoverPaintStyle = function(style, doNotRepaint) { hoverPaintStyle = style; _updateHoverStyle(); if (!doNotRepaint) self.repaint(); }; /** * Gets the component's hover paint style. * * Returns: * the component's hover paint style. may be null. */ this.getHoverPaintStyle = function() { return hoverPaintStyle; }; /* * sets/unsets the hover state of this element. * * Parameters: * hover - hover state boolean * ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state. used mostly to avoid infinite loops. */ this.setHover = function(hover, ignoreAttachedElements, timestamp) { // while dragging, we ignore these events. this keeps the UI from flashing and // swishing and whatevering. if (!self._jsPlumb.currentlyDragging && !self._jsPlumb.isHoverSuspended()) { _hover = hover; if (self.canvas != null) { if (self.hoverClass != null) { if (hover) jpcl.addClass(self.canvas, self.hoverClass); else jpcl.removeClass(self.canvas, self.hoverClass); } if (hover) jpcl.addClass(self.canvas, self._jsPlumb.hoverClass); else jpcl.removeClass(self.canvas, self._jsPlumb.hoverClass); } if (hoverPaintStyle != null) { self.paintStyleInUse = hover ? hoverPaintStyle : paintStyle; timestamp = timestamp || _timestamp(); self.repaint({timestamp:timestamp, recalc:false}); } // get the list of other affected elements, if supported by this component. // for a connection, its the endpoints. for an endpoint, its the connections! surprise. if (self.getAttachedElements && !ignoreAttachedElements) _updateAttachedElements(hover, _timestamp(), self); } }; this.isHover = function() { return _hover; }; this.bindListeners = function(obj, _self, _hoverFunction) { obj.bind("click", function(ep, e) { _self.fire("click", _self, e); }); obj.bind("dblclick", function(ep, e) { _self.fire("dblclick", _self, e); }); obj.bind("contextmenu", function(ep, e) { _self.fire("contextmenu", _self, e); }); obj.bind("mouseenter", function(ep, e) { if (!_self.isHover()) { _hoverFunction(true); _self.fire("mouseenter", _self, e); } }); obj.bind("mouseexit", function(ep, e) { if (_self.isHover()) { _hoverFunction(false); _self.fire("mouseexit", _self, e); } }); obj.bind("mousedown", function(ep, e) { _self.fire("mousedown", _self, e); }); obj.bind("mouseup", function(ep, e) { _self.fire("mouseup", _self, e); }); }; var jpcl = jsPlumb.CurrentLibrary, events = [ "click", "dblclick", "mouseenter", "mouseout", "mousemove", "mousedown", "mouseup", "contextmenu" ], eventFilters = { "mouseout":"mouseexit" }, bindOne = function(o, c, evt) { var filteredEvent = eventFilters[evt] || evt; jpcl.bind(o, evt, function(ee) { c.fire(filteredEvent, c, ee); }); }, unbindOne = function(o, evt) { var filteredEvent = eventFilters[evt] || evt; jpcl.unbind(o, evt); }; this.attachListeners = function(o, c) { for (var i = 0, j = events.length; i < j; i++) { bindOne(o, c, events[i]); } }; var _updateAttachedElements = function(state, timestamp, sourceElement) { var affectedElements = self.getAttachedElements(); // implemented in subclasses if (affectedElements) { for (var i = 0, j = affectedElements.length; i < j; i++) { if (!sourceElement || sourceElement != affectedElements[i]) affectedElements[i].setHover(state, true, timestamp); // tell the attached elements not to inform their own attached elements. } } }; this.reattachListenersForElement = function(o) { if (arguments.length > 1) { for (var i = 0, j = events.length; i < j; i++) unbindOne(o, events[i]); for (var i = 1, j = arguments.length; i < j; i++) self.attachListeners(o, arguments[i]); } }; /* * TYPES */ var _types = [], _splitType = function(t) { return t == null ? null : t.split(" ")}, _applyTypes = function(params, doNotRepaint) { if (self.getDefaultType) { var td = self.getTypeDescriptor(); var o = jsPlumbUtil.merge({}, self.getDefaultType()); for (var i = 0, j = _types.length; i < j; i++) o = jsPlumbUtil.merge(o, self._jsPlumb.getType(_types[i], td)); if (params) { o = jsPlumbUtil.populate(o, params); } self.applyType(o, doNotRepaint); if (!doNotRepaint) self.repaint(); } }; /* Function: setType Sets the type, removing all existing types. */ self.setType = function(typeId, params, doNotRepaint) { _types = _splitType(typeId) || []; _applyTypes(params, doNotRepaint); }; /* * Function : getType * Gets the 'types' of this component. */ self.getType = function() { return _types; }; /** Function: reapplyTypes Reapply all existing types, but with the given new params. */ self.reapplyTypes = function(params, doNotRepaint) { _applyTypes(params, doNotRepaint); }; self.hasType = function(typeId) { return jsPlumbUtil.indexOf(_types, typeId) != -1; }; /* Function: addType adds a type. will not be re-added it already exists. */ self.addType = function(typeId, params, doNotRepaint) { var t = _splitType(typeId), _cont = false; if (t != null) { for (var i = 0, j = t.length; i < j; i++) { if (!self.hasType(t[i])) { _types.push(t[i]); _cont = true; } } if (_cont) _applyTypes(params, doNotRepaint); } }; self.removeType = function(typeId, doNotRepaint) { var t = _splitType(typeId), _cont = false, _one = function(tt) { var idx = jsPlumbUtil.indexOf(_types, tt); if (idx != -1) { _types.splice(idx, 1); return true; } return false; }; if (t != null) { for (var i = 0,j = t.length; i < j; i++) { _cont = _one(t[i]) || _cont; } if (_cont) _applyTypes(null, doNotRepaint); } }; self.toggleType = function(typeId, params, doNotRepaint) { var t = _splitType(typeId); if (t != null) { for (var i = 0, j = t.length; i < j; i++) { var idx = jsPlumbUtil.indexOf(_types, t[i]); if (idx != -1) _types.splice(idx, 1); else _types.push(t[i]); } _applyTypes(params, doNotRepaint); } }; this.applyType = function(t, doNotRepaint) { self.setPaintStyle(t.paintStyle, doNotRepaint); self.setHoverPaintStyle(t.hoverPaintStyle, doNotRepaint); if (t.parameters){ for (var i in t.parameters) self.setParameter(i, t.parameters[i]); } }; // CSS classes this.addClass = function(clazz) { if (self.canvas != null) _addClass(self.canvas, clazz); }; this.removeClass = function(clazz) { if (self.canvas != null) _removeClass(self.canvas, clazz); }; }, overlayCapableJsPlumbUIComponent = window.overlayCapableJsPlumbUIComponent = function(params) { jsPlumbUIComponent.apply(this, arguments); var self = this; this.overlays = []; var processOverlay = function(o) { var _newOverlay = null; if (_isArray(o)) { // this is for the shorthand ["Arrow", { width:50 }] syntax // there's also a three arg version: // ["Arrow", { width:50 }, {location:0.7}] // which merges the 3rd arg into the 2nd. var type = o[0], // make a copy of the object so as not to mess up anyone else's reference... p = jsPlumb.extend({component:self, _jsPlumb:self._jsPlumb}, o[1]); if (o.length == 3) jsPlumb.extend(p, o[2]); _newOverlay = new jsPlumb.Overlays[self._jsPlumb.getRenderMode()][type](p); } else if (o.constructor == String) { _newOverlay = new jsPlumb.Overlays[self._jsPlumb.getRenderMode()][o]({component:self, _jsPlumb:self._jsPlumb}); } else { _newOverlay = o; } self.overlays.push(_newOverlay); }, calculateOverlaysToAdd = function(params) { var defaultKeys = self.defaultOverlayKeys || [], o = params.overlays, checkKey = function(k) { return self._jsPlumb.Defaults[k] || jsPlumb.Defaults[k] || []; }; if (!o) o = []; for (var i = 0, j = defaultKeys.length; i < j; i++) o.unshift.apply(o, checkKey(defaultKeys[i])); return o; } var _overlays = calculateOverlaysToAdd(params); if (_overlays) { for (var i = 0, j = _overlays.length; i < j; i++) { processOverlay(_overlays[i]); } } // overlay finder helper method var _getOverlayIndex = function(id) { var idx = -1; for (var i = 0, j = self.overlays.length; i < j; i++) { if (id === self.overlays[i].id) { idx = i; break; } } return idx; }; this.addOverlay = function(overlay, doNotRepaint) { processOverlay(overlay); if (!doNotRepaint) self.repaint(); }; this.getOverlay = function(id) { var idx = _getOverlayIndex(id); return idx >= 0 ? self.overlays[idx] : null; }; this.getOverlays = function() { return self.overlays; }; this.hideOverlay = function(id) { var o = self.getOverlay(id); if (o) o.hide(); }; this.hideOverlays = function() { for (var i = 0, j = self.overlays.length; i < j; i++) self.overlays[i].hide(); }; this.showOverlay = function(id) { var o = self.getOverlay(id); if (o) o.show(); }; this.showOverlays = function() { for (var i = 0, j = self.overlays.length; i < j; i++) self.overlays[i].show(); }; this.removeAllOverlays = function() { for (var i = 0, j = self.overlays.length; i < j; i++) { if (self.overlays[i].cleanup) self.overlays[i].cleanup(); } self.overlays.splice(0, self.overlays.length); self.repaint(); }; this.removeOverlay = function(overlayId) { var idx = _getOverlayIndex(overlayId); if (idx != -1) { var o = self.overlays[idx]; if (o.cleanup) o.cleanup(); self.overlays.splice(idx, 1); } }; this.removeOverlays = function() { for (var i = 0, j = arguments.length; i < j; i++) self.removeOverlay(arguments[i]); }; // this is a shortcut helper method to let people add a label as // overlay. var _internalLabelOverlayId = "__label", _makeLabelOverlay = function(params) { var _params = { cssClass:params.cssClass, labelStyle : this.labelStyle, id:_internalLabelOverlayId, component:self, _jsPlumb:self._jsPlumb }, mergedParams = jsPlumb.extend(_params, params); return new jsPlumb.Overlays[self._jsPlumb.getRenderMode()].Label( mergedParams ); }; if (params.label) { var loc = params.labelLocation || self.defaultLabelLocation || 0.5, labelStyle = params.labelStyle || self._jsPlumb.Defaults.LabelStyle || jsPlumb.Defaults.LabelStyle; this.overlays.push(_makeLabelOverlay({ label:params.label, location:loc, labelStyle:labelStyle })); } this.setLabel = function(l) { var lo = self.getOverlay(_internalLabelOverlayId); if (!lo) { var params = l.constructor == String || l.constructor == Function ? { label:l } : l; lo = _makeLabelOverlay(params); this.overlays.push(lo); } else { if (l.constructor == String || l.constructor == Function) lo.setLabel(l); else { if (l.label) lo.setLabel(l.label); if (l.location) lo.setLocation(l.location); } } if (!self._jsPlumb.isSuspendDrawing()) self.repaint(); }; this.getLabel = function() { var lo = self.getOverlay(_internalLabelOverlayId); return lo != null ? lo.getLabel() : null; }; this.getLabelOverlay = function() { return self.getOverlay(_internalLabelOverlayId); }; var superAt = this.applyType; this.applyType = function(t, doNotRepaint) { superAt(t, doNotRepaint); self.removeAllOverlays(); if (t.overlays) { for (var i = 0, j = t.overlays.length; i < j; i++) self.addOverlay(t.overlays[i], true); } }; var superHover = this.setHover; this.setHover = function(hover, ignoreAttachedElements, timestamp) { superHover.apply(self, arguments); for (var i = 0, j = self.overlays.length; i < j; i++) { self.overlays[i][hover ? "addClass":"removeClass"](self._jsPlumb.hoverClass); } }; }; var _jsPlumbInstanceIndex = 0, getInstanceIndex = function() { var i = _jsPlumbInstanceIndex + 1; _jsPlumbInstanceIndex++; return i; }; var jsPlumbInstance = function(_defaults) { this.Defaults = { Anchor : "BottomCenter", Anchors : [ null, null ], ConnectionsDetachable : true, ConnectionOverlays : [ ], Connector : "Bezier", Container : null, DoNotThrowErrors:false, DragOptions : { }, DropOptions : { }, Endpoint : "Dot", EndpointOverlays : [ ], Endpoints : [ null, null ], EndpointStyle : { fillStyle : "#456" }, EndpointStyles : [ null, null ], EndpointHoverStyle : null, EndpointHoverStyles : [ null, null ], HoverPaintStyle : null, LabelStyle : { color : "black" }, LogEnabled : false, Overlays : [ ], MaxConnections : 1, PaintStyle : { lineWidth : 8, strokeStyle : "#456" }, ReattachConnections:false, RenderMode : "svg", Scope : "jsPlumb_DefaultScope" }; if (_defaults) jsPlumb.extend(this.Defaults, _defaults); this.logEnabled = this.Defaults.LogEnabled; var _connectionTypes = { }, _endpointTypes = {}; this.registerConnectionType = function(id, type) { _connectionTypes[id] = jsPlumb.extend({}, type); }; this.registerConnectionTypes = function(types) { for (var i in types) _connectionTypes[i] = jsPlumb.extend({}, types[i]); }; this.registerEndpointType = function(id, type) { _endpointTypes[id] = jsPlumb.extend({}, type); }; this.registerEndpointTypes = function(types) { for (var i in types) _endpointTypes[i] = jsPlumb.extend({}, types[i]); }; this.getType = function(id, typeDescriptor) { return typeDescriptor === "connection" ? _connectionTypes[id] : _endpointTypes[id]; }; jsPlumbUtil.EventGenerator.apply(this); var _currentInstance = this, _instanceIndex = getInstanceIndex(), _bb = _currentInstance.bind, _initialDefaults = {}, _zoom = 1; this.getInstanceIndex = function() { return _instanceIndex; }; this.setZoom = function(z, repaintEverything) { _zoom = z; if (repaintEverything) _currentInstance.repaintEverything(); }; this.getZoom = function() { return _zoom; }; for (var i in this.Defaults) _initialDefaults[i] = this.Defaults[i]; this.bind = function(event, fn) { if ("ready" === event && initialized) fn(); else _bb.apply(_currentInstance,[event, fn]); }; _currentInstance.importDefaults = function(d) { for (var i in d) { _currentInstance.Defaults[i] = d[i]; } }; _currentInstance.restoreDefaults = function() { _currentInstance.Defaults = jsPlumb.extend({}, _initialDefaults); }; var log = null, resizeTimer = null, initialized = false, _connectionBeingDragged = null, connectionsByScope = {}, /** * map of element id -> endpoint lists. an element can have an arbitrary * number of endpoints on it, and not all of them have to be connected * to anything. */ endpointsByElement = {}, endpointsByUUID = {}, offsets = {}, offsetTimestamps = {}, floatingConnections = {}, draggableStates = {}, canvasList = [], sizes = [], //listeners = {}, // a map: keys are event types, values are lists of listeners. DEFAULT_SCOPE = this.Defaults.Scope, renderMode = null, // will be set in init() /** * appends an element to some other element, which is calculated as follows: * * 1. if _currentInstance.Defaults.Container exists, use that element. * 2. if the 'parent' parameter exists, use that. * 3. otherwise just use the root element (for DOM usage, the document body). * */ _appendElement = function(el, parent) { if (_currentInstance.Defaults.Container) jsPlumb.CurrentLibrary.appendElement(el, _currentInstance.Defaults.Container); else if (!parent) jsPlumbAdapter.appendToRoot(el); else jsPlumb.CurrentLibrary.appendElement(el, parent); }, _curIdStamp = 1, _idstamp = function() { return "" + _curIdStamp++; }, /** * YUI, for some reason, put the result of a Y.all call into an object that contains * a '_nodes' array, instead of handing back an array-like object like the other * libraries do. */ _convertYUICollection = function(c) { return c._nodes ? c._nodes : c; }, /** * Draws an endpoint and its connections. this is the main entry point into drawing connections as well * as endpoints, since jsPlumb is endpoint-centric under the hood. * * @param element element to draw (of type library specific element object) * @param ui UI object from current library's event system. optional. * @param timestamp timestamp for this paint cycle. used to speed things up a little by cutting down the amount of offset calculations we do. */ _draw = function(element, ui, timestamp, clearEdits) { // TODO is it correct to filter by headless at this top level? how would a headless adapter ever repaint? if (!jsPlumbAdapter.headless && !_suspendDrawing) { var id = _att(element, "id"), repaintEls = _currentInstance.dragManager.getElementsForDraggable(id); if (timestamp == null) timestamp = _timestamp(); _currentInstance.anchorManager.redraw(id, ui, timestamp, null, clearEdits); if (repaintEls) { for (var i in repaintEls) { _currentInstance.anchorManager.redraw(repaintEls[i].id, ui, timestamp, repaintEls[i].offset, clearEdits); } } } }, /** * executes the given function against the given element if the first * argument is an object, or the list of elements, if the first argument * is a list. the function passed in takes (element, elementId) as * arguments. */ _elementProxy = function(element, fn) { var retVal = null; if (_isArray(element)) { retVal = []; for ( var i = 0, j = element.length; i < j; i++) { var el = _gel(element[i]), id = _att(el, "id"); retVal.push(fn(el, id)); // append return values to what we will return } } else { var el = _gel(element), id = _att(el, "id"); retVal = fn(el, id); } return retVal; }, /** * gets an Endpoint by uuid. */ _getEndpoint = function(uuid) { return endpointsByUUID[uuid]; }, /** * inits a draggable if it's not already initialised. */ _initDraggableIfNecessary = function(element, isDraggable, dragOptions) { // TODO move to DragManager? if (!jsPlumbAdapter.headless) { var draggable = isDraggable == null ? false : isDraggable, jpcl = jsPlumb.CurrentLibrary; if (draggable) { if (jpcl.isDragSupported(element) && !jpcl.isAlreadyDraggable(element)) { var options = dragOptions || _currentInstance.Defaults.DragOptions || jsPlumb.Defaults.DragOptions; options = jsPlumb.extend( {}, options); // make a copy. var dragEvent = jpcl.dragEvents["drag"], stopEvent = jpcl.dragEvents["stop"], startEvent = jpcl.dragEvents["start"]; options[startEvent] = _wrap(options[startEvent], function() { _currentInstance.setHoverSuspended(true); _currentInstance.select({source:element}).addClass(_currentInstance.elementDraggingClass + " " + _currentInstance.sourceElementDraggingClass, true); _currentInstance.select({target:element}).addClass(_currentInstance.elementDraggingClass + " " + _currentInstance.targetElementDraggingClass, true); }); options[dragEvent] = _wrap(options[dragEvent], function() { var ui = jpcl.getUIPosition(arguments, _currentInstance.getZoom()); _draw(element, ui, null, true); _addClass(element, "jsPlumb_dragged"); }); options[stopEvent] = _wrap(options[stopEvent], function() { var ui = jpcl.getUIPosition(arguments, _currentInstance.getZoom()); _draw(element, ui); _removeClass(element, "jsPlumb_dragged"); _currentInstance.setHoverSuspended(false); _currentInstance.select({source:element}).removeClass(_currentInstance.elementDraggingClass + " " + _currentInstance.sourceElementDraggingClass, true); _currentInstance.select({target:element}).removeClass(_currentInstance.elementDraggingClass + " " + _currentInstance.targetElementDraggingClass, true); }); var elId = _getId(element); // need ID draggableStates[elId] = true; var draggable = draggableStates[elId]; options.disabled = draggable == null ? false : !draggable; jpcl.initDraggable(element, options, false, _currentInstance); _currentInstance.dragManager.register(element); } } } }, /* * prepares a final params object that can be passed to _newConnection, taking into account defaults, events, etc. */ _prepareConnectionParams = function(params, referenceParams) { var _p = jsPlumb.extend( { sourceIsNew:true, targetIsNew:true }, params); if (referenceParams) jsPlumb.extend(_p, referenceParams); // hotwire endpoints passed as source or target to sourceEndpoint/targetEndpoint, respectively. if (_p.source && _p.source.endpoint) _p.sourceEndpoint = _p.source; if (_p.target && _p.target.endpoint) _p.targetEndpoint = _p.target; // test for endpoint uuids to connect if (params.uuids) { _p.sourceEndpoint = _getEndpoint(params.uuids[0]); _p.targetEndpoint = _getEndpoint(params.uuids[1]); } // now ensure that if we do have Endpoints already, they're not full. // source: if (_p.sourceEndpoint && _p.sourceEndpoint.isFull()) { _log(_currentInstance, "could not add connection; source endpoint is full"); return; } // target: if (_p.targetEndpoint && _p.targetEndpoint.isFull()) { _log(_currentInstance, "could not add connection; target endpoint is full"); return; } // at this point, if we have source or target Endpoints, they were not new and we should mark the // flag to reflect that. this is for use later with the deleteEndpointsOnDetach flag. if (_p.sourceEndpoint && !_p.sourceEndpoint.addedViaMouse) _p.sourceIsNew = false; if (_p.targetEndpoint && !_p.targetEndpoint.addedViaMouse) _p.targetIsNew = false; // if source endpoint mandates connection type and nothing specified in our params, use it. if (!_p.type && _p.sourceEndpoint) _p.type = _p.sourceEndpoint.connectionType; // copy in any connectorOverlays that were specified on the source endpoint. // it doesnt copy target endpoint overlays. i'm not sure if we want it to or not. if (_p.sourceEndpoint && _p.sourceEndpoint.connectorOverlays) { _p.overlays = _p.overlays || []; for (var i = 0, j = _p.sourceEndpoint.connectorOverlays.length; i < j; i++) { _p.overlays.push(_p.sourceEndpoint.connectorOverlays[i]); } } // pointer events if (!_p["pointer-events"] && _p.sourceEndpoint && _p.sourceEndpoint.connectorPointerEvents) _p["pointer-events"] = _p.sourceEndpoint.connectorPointerEvents; // if there's a target specified (which of course there should be), and there is no // target endpoint specified, and 'newConnection' was not set to true, then we check to // see if a prior call to makeTarget has provided us with the specs for the target endpoint, and // we use those if so. additionally, if the makeTarget call was specified with 'uniqueEndpoint' set // to true, then if that target endpoint has already been created, we re-use it. if (_p.target && !_p.target.endpoint && !_p.targetEndpoint && !_p.newConnection) { var tid = _getId(_p.target), tep =_targetEndpointDefinitions[tid], existingUniqueEndpoint = _targetEndpoints[tid]; if (tep) { // if target not enabled, return. if (!_targetsEnabled[tid]) return; // check for max connections?? var newEndpoint = existingUniqueEndpoint != null ? existingUniqueEndpoint : _currentInstance.addEndpoint(_p.target, tep); if (_targetEndpointsUnique[tid]) _targetEndpoints[tid] = newEndpoint; _p.targetEndpoint = newEndpoint; newEndpoint._makeTargetCreator = true; _p.targetIsNew = true; } } // same thing, but for source. if (_p.source && !_p.source.endpoint && !_p.sourceEndpoint && !_p.newConnection) { var tid = _getId(_p.source), tep = _sourceEndpointDefinitions[tid], existingUniqueEndpoint = _sourceEndpoints[tid]; if (tep) { // if source not enabled, return. if (!_sourcesEnabled[tid]) return; var newEndpoint = existingUniqueEndpoint != null ? existingUniqueEndpoint : _currentInstance.addEndpoint(_p.source, tep); if (_sourceEndpointsUnique[tid]) _sourceEndpoints[tid] = newEndpoint; _p.sourceEndpoint = newEndpoint; _p.sourceIsNew = true; } } return _p; }, _newConnection = function(params) { var connectionFunc = _currentInstance.Defaults.ConnectionType || _currentInstance.getDefaultConnectionType(), endpointFunc = _currentInstance.Defaults.EndpointType || jsPlumb.Endpoint, parent = jsPlumb.CurrentLibrary.getParent; if (params.container) params["parent"] = params.container; else { if (params.sourceEndpoint) params["parent"] = params.sourceEndpoint.parent; else if (params.source.constructor == endpointFunc) params["parent"] = params.source.parent; else params["parent"] = parent(params.source); } params["_jsPlumb"] = _currentInstance; params.newConnection = _newConnection; params.newEndpoint = _newEndpoint; params.endpointsByUUID = endpointsByUUID; params.endpointsByElement = endpointsByElement; params.finaliseConnection = _finaliseConnection; var con = new connectionFunc(params); con.id = "con_" + _idstamp(); _eventFireProxy("click", "click", con); _eventFireProxy("dblclick", "dblclick", con); _eventFireProxy("contextmenu", "contextmenu", con); return con; }, /** * adds the connection to the backing model, fires an event if necessary and then redraws */ _finaliseConnection = function(jpc, params, originalEvent) { params = params || {}; // add to list of connections (by scope). if (!jpc.suspendedEndpoint) _addToList(connectionsByScope, jpc.scope, jpc); // always inform the anchor manager // except that if jpc has a suspended endpoint it's not true to say the // connection is new; it has just (possibly) moved. the question is whether // to make that call here or in the anchor manager. i think perhaps here. _currentInstance.anchorManager.newConnection(jpc); // force a paint _draw(jpc.source); // fire an event if (!params.doNotFireConnectionEvent && params.fireEvent !== false) { var eventArgs = { connection:jpc, source : jpc.source, target : jpc.target, sourceId : jpc.sourceId, targetId : jpc.targetId, sourceEndpoint : jpc.endpoints[0], targetEndpoint : jpc.endpoints[1] }; _currentInstance.fire("jsPlumbConnection", eventArgs, originalEvent); // this is from 1.3.11 onwards. "jsPlumbConnection" always felt so unnecessary, so // I've added this alias in 1.3.11, with a view to removing "jsPlumbConnection" completely in a future version. be aware, of course, you should only register listeners for one or the other of these events. _currentInstance.fire("connection", eventArgs, originalEvent); } }, _eventFireProxy = function(event, proxyEvent, obj) { obj.bind(event, function(originalObject, originalEvent) { _currentInstance.fire(proxyEvent, obj, originalEvent); }); }, /** * for the given endpoint params, returns an appropriate parent element for the UI elements that will be added. * this function is used by _newEndpoint (directly below), and also in the makeSource function in jsPlumb. * * the logic is to first look for a "container" member of params, and pass that back if found. otherwise we * handoff to the 'getParent' function in the current library. */ _getParentFromParams = function(params) { if (params.container) return params.container; else { var tag = jsPlumb.CurrentLibrary.getTagName(params.source), p = jsPlumb.CurrentLibrary.getParent(params.source); if (tag && tag.toLowerCase() === "td") return jsPlumb.CurrentLibrary.getParent(p); else return p; } }, /** factory method to prepare a new endpoint. this should always be used instead of creating Endpoints manually, since this method attaches event listeners and an id. */ _newEndpoint = function(params) { var endpointFunc = _currentInstance.Defaults.EndpointType || jsPlumb.Endpoint; var _p = jsPlumb.extend({}, params); _p.parent = _getParentFromParams(_p); _p["_jsPlumb"] = _currentInstance; _p.newConnection = _newConnection; _p.newEndpoint = _newEndpoint; _p.endpointsByUUID = endpointsByUUID; _p.endpointsByElement = endpointsByElement; _p.finaliseConnection = _finaliseConnection; _p.fireDetachEvent = fireDetachEvent; _p.floatingConnections = floatingConnections; _p.getParentFromParams = _getParentFromParams; _p.connectionsByScope = connectionsByScope; var ep = new endpointFunc(_p); ep.id = "ep_" + _idstamp(); _eventFireProxy("click", "endpointClick", ep); _eventFireProxy("dblclick", "endpointDblClick", ep); _eventFireProxy("contextmenu", "contextmenu", ep); if (!jsPlumbAdapter.headless) _currentInstance.dragManager.endpointAdded(params.source); return ep; }, /** * performs the given function operation on all the connections found * for the given element id; this means we find all the endpoints for * the given element, and then for each endpoint find the connectors * connected to it. then we pass each connection in to the given * function. */ _operation = function(elId, func, endpointFunc) { var endpoints = endpointsByElement[elId]; if (endpoints && endpoints.length) { for ( var i = 0, ii = endpoints.length; i < ii; i++) { for ( var j = 0, jj = endpoints[i].connections.length; j < jj; j++) { var retVal = func(endpoints[i].connections[j]); // if the function passed in returns true, we exit. // most functions return false. if (retVal) return; } if (endpointFunc) endpointFunc(endpoints[i]); } } }, /** * perform an operation on all elements. */ _operationOnAll = function(func) { for ( var elId in endpointsByElement) { _operation(elId, func); } }, /** * Sets whether or not the given element(s) should be draggable, * regardless of what a particular plumb command may request. * * @param element * May be a string, a element objects, or a list of * strings/elements. * @param draggable * Whether or not the given element(s) should be draggable. */ _setDraggable = function(element, draggable) { return _elementProxy(element, function(el, id) { draggableStates[id] = draggable; if (jsPlumb.CurrentLibrary.isDragSupported(el)) { jsPlumb.CurrentLibrary.setDraggable(el, draggable); } }); }, /** * private method to do the business of hiding/showing. * * @param el * either Id of the element in question or a library specific * object for the element. * @param state * String specifying a value for the css 'display' property * ('block' or 'none'). */ _setVisible = function(el, state, alsoChangeEndpoints) { state = state === "block"; var endpointFunc = null; if (alsoChangeEndpoints) { if (state) endpointFunc = function(ep) { ep.setVisible(true, true, true); }; else endpointFunc = function(ep) { ep.setVisible(false, true, true); }; } var id = _att(el, "id"); _operation(id, function(jpc) { if (state && alsoChangeEndpoints) { // this test is necessary because this functionality is new, and i wanted to maintain backwards compatibility. // this block will only set a connection to be visible if the other endpoint in the connection is also visible. var oidx = jpc.sourceId === id ? 1 : 0; if (jpc.endpoints[oidx].isVisible()) jpc.setVisible(true); } else // the default behaviour for show, and what always happens for hide, is to just set the visibility without getting clever. jpc.setVisible(state); }, endpointFunc); }, /** * toggles the draggable state of the given element(s). * * @param el * either an id, or an element object, or a list of * ids/element objects. */ _toggleDraggable = function(el) { return _elementProxy(el, function(el, elId) { var state = draggableStates[elId] == null ? false : draggableStates[elId]; state = !state; draggableStates[elId] = state; jsPlumb.CurrentLibrary.setDraggable(el, state); return state; }); }, /** * private method to do the business of toggling hiding/showing. * * @param elId * Id of the element in question */ _toggleVisible = function(elId, changeEndpoints) { var endpointFunc = null; if (changeEndpoints) { endpointFunc = function(ep) { var state = ep.isVisible(); ep.setVisible(!state); }; } _operation(elId, function(jpc) { var state = jpc.isVisible(); jpc.setVisible(!state); }, endpointFunc); // todo this should call _elementProxy, and pass in the // _operation(elId, f) call as a function. cos _toggleDraggable does // that. }, /** * updates the offset and size for a given element, and stores the * values. if 'offset' is not null we use that (it would have been * passed in from a drag call) because it's faster; but if it is null, * or if 'recalc' is true in order to force a recalculation, we get the current values. */ _updateOffset = function(params) { var timestamp = params.timestamp, recalc = params.recalc, offset = params.offset, elId = params.elId; if (_suspendDrawing && !timestamp) timestamp = _suspendedAt; if (!recalc) { if (timestamp && timestamp === offsetTimestamps[elId]) return {o:offsets[elId], s:sizes[elId]}; } if (recalc || !offset) { // if forced repaint or no offset available, we recalculate. // get the current size and offset, and store them var s = _gel(elId); if (s != null) { sizes[elId] = _getSize(s); offsets[elId] = _getOffset(s, _currentInstance); offsetTimestamps[elId] = timestamp; } } else { offsets[elId] = offset; if (sizes[elId] == null) { var s = _gel(elId); if (s != null) sizes[elId] = _getSize(s); } } if(offsets[elId] && !offsets[elId].right) { offsets[elId].right = offsets[elId].left + sizes[elId][0]; offsets[elId].bottom = offsets[elId].top + sizes[elId][1]; offsets[elId].width = sizes[elId][0]; offsets[elId].height = sizes[elId][1]; offsets[elId].centerx = offsets[elId].left + (offsets[elId].width / 2); offsets[elId].centery = offsets[elId].top + (offsets[elId].height / 2); } //return offsets[elId]; return {o:offsets[elId], s:sizes[elId]}; }, // TODO comparison performance _getCachedData = function(elId) { var o = offsets[elId]; if (!o) return _updateOffset({elId:elId}); else return {o:o, s:sizes[elId]}; }, /** * gets an id for the given element, creating and setting one if * necessary. the id is of the form * * jsPlumb_<instance index>_<index in instance> * * where "index in instance" is a monotonically increasing integer that starts at 0, * for each instance. this method is used not only to assign ids to elements that do not * have them but also to connections and endpoints. */ _getId = function(element, uuid, doNotCreateIfNotFound) { var ele = _gel(element); var id = _att(ele, "id"); if (!id || id == "undefined") { // check if fixed uuid parameter is given if (arguments.length == 2 && arguments[1] != undefined) id = uuid; else if (arguments.length == 1 || (arguments.length == 3 && !arguments[2])) id = "jsPlumb_" + _instanceIndex + "_" + _idstamp(); if (!doNotCreateIfNotFound) _setAttribute(ele, "id", id); } return id; }, /** * wraps one function with another, creating a placeholder for the * wrapped function if it was null. this is used to wrap the various * drag/drop event functions - to allow jsPlumb to be notified of * important lifecycle events without imposing itself on the user's * drag/drop functionality. TODO: determine whether or not we should * support an error handler concept, if one of the functions fails. * * @param wrappedFunction original function to wrap; may be null. * @param newFunction function to wrap the original with. * @param returnOnThisValue Optional. Indicates that the wrappedFunction should * not be executed if the newFunction returns a value matching 'returnOnThisValue'. * note that this is a simple comparison and only works for primitives right now. */ // TODO move to util. _wrap = function(wrappedFunction, newFunction, returnOnThisValue) { wrappedFunction = wrappedFunction || function() { }; newFunction = newFunction || function() { }; return function() { var r = null; try { r = newFunction.apply(this, arguments); } catch (e) { _log(_currentInstance, "jsPlumb function failed : " + e); } if (returnOnThisValue == null || (r !== returnOnThisValue)) { try { wrappedFunction.apply(this, arguments); } catch (e) { _log(_currentInstance, "wrapped function failed : " + e); } } return r; }; }; this.isConnectionBeingDragged = function() { return _connectionBeingDragged != null; }; this.setConnectionBeingDragged = function(c) {_connectionBeingDragged = c; }; this.connectorClass = "_jsPlumb_connector"; this.hoverClass = "_jsPlumb_hover"; this.endpointClass = "_jsPlumb_endpoint"; this.endpointConnectedClass = "_jsPlumb_endpoint_connected"; this.endpointFullClass = "_jsPlumb_endpoint_full"; this.endpointDropAllowedClass = "_jsPlumb_endpoint_drop_allowed"; this.endpointDropForbiddenClass = "_jsPlumb_endpoint_drop_forbidden"; this.overlayClass = "_jsPlumb_overlay"; this.draggingClass = "_jsPlumb_dragging"; this.elementDraggingClass = "_jsPlumb_element_dragging"; this.sourceElementDraggingClass = "_jsPlumb_source_element_dragging"; this.targetElementDraggingClass = "_jsPlumb_target_element_dragging"; this.endpointAnchorClassPrefix = "_jsPlumb_endpoint_anchor"; this.Anchors = {}; this.Connectors = { "canvas":{}, "svg":{}, "vml":{} }; this.Endpoints = { "canvas":{}, "svg":{}, "vml":{} }; this.Overlays = { "canvas":{}, "svg":{}, "vml":{}}; this.ConnectorRenderers = {}; // --------------------------- jsPLumbInstance public API --------------------------------------------------------- this.addClass = function(el, clazz) { return jsPlumb.CurrentLibrary.addClass(el, clazz); }; this.removeClass = function(el, clazz) { return jsPlumb.CurrentLibrary.removeClass(el, clazz); }; this.hasClass = function(el, clazz) { return jsPlumb.CurrentLibrary.hasClass(el, clazz); }; this.addEndpoint = function(el, params, referenceParams) { referenceParams = referenceParams || {}; var p = jsPlumb.extend({}, referenceParams); jsPlumb.extend(p, params); p.endpoint = p.endpoint || _currentInstance.Defaults.Endpoint || jsPlumb.Defaults.Endpoint; p.paintStyle = p.paintStyle || _currentInstance.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle; // YUI wrapper el = _convertYUICollection(el); var results = [], inputs = el.length && el.constructor != String ? el : [ el ]; for (var i = 0, j = inputs.length; i < j; i++) { var _el = _gel(inputs[i]), id = _getId(_el); p.source = _el; _updateOffset({ elId : id, timestamp:_suspendedAt }); var e = _newEndpoint(p); if (p.parentAnchor) e.parentAnchor = p.parentAnchor; _addToList(endpointsByElement, id, e); var myOffset = offsets[id], myWH = sizes[id]; var anchorLoc = e.anchor.compute( { xy : [ myOffset.left, myOffset.top ], wh : myWH, element : e, timestamp:_suspendedAt }); var endpointPaintParams = { anchorLoc : anchorLoc, timestamp:_suspendedAt }; if (_suspendDrawing) endpointPaintParams.recalc = false; e.paint(endpointPaintParams); results.push(e); //if (!jsPlumbAdapter.headless) //_currentInstance.dragManager.endpointAdded(_el); } return results.length == 1 ? results[0] : results; }; this.addEndpoints = function(el, endpoints, referenceParams) { var results = []; for ( var i = 0, j = endpoints.length; i < j; i++) { var e = _currentInstance.addEndpoint(el, endpoints[i], referenceParams); if (_isArray(e)) Array.prototype.push.apply(results, e); else results.push(e); } return results; }; this.animate = function(el, properties, options) { var ele = _gel(el), id = _att(el, "id"); options = options || {}; var stepFunction = jsPlumb.CurrentLibrary.dragEvents['step']; var completeFunction = jsPlumb.CurrentLibrary.dragEvents['complete']; options[stepFunction] = _wrap(options[stepFunction], function() { _currentInstance.repaint(id); }); // onComplete repaints, just to make sure everything looks good at the end of the animation. options[completeFunction] = _wrap(options[completeFunction], function() { _currentInstance.repaint(id); }); jsPlumb.CurrentLibrary.animate(ele, properties, options); }; /** * checks for a listener for the given condition, executing it if found, passing in the given value. * condition listeners would have been attached using "bind" (which is, you could argue, now overloaded, since * firing click events etc is a bit different to what this does). i thought about adding a "bindCondition" * or something, but decided against it, for the sake of simplicity. jsPlumb will never fire one of these * condition events anyway. */ this.checkCondition = function(conditionName, value) { var l = _currentInstance.getListener(conditionName), r = true; if (l && l.length > 0) { try { for (var i = 0, j = l.length; i < j; i++) { r = r && l[i](value); } } catch (e) { _log(_currentInstance, "cannot check condition [" + conditionName + "]" + e); } } return r; }; /** * checks a condition asynchronously: fires the event handler and passes the handler * a 'proceed' function and a 'stop' function. The handler MUST execute one or other * of these once it has made up its mind. * * Note that although this reads the listener list for the given condition, it * does not loop through and hit each listener, because that, with asynchronous * callbacks, would be messy. so it uses only the first listener registered. */ this.checkASyncCondition = function(conditionName, value, proceed, stop) { var l = _currentInstance.getListener(conditionName); if (l && l.length > 0) { try { l[0](value, proceed, stop); } catch (e) { _log(_currentInstance, "cannot asynchronously check condition [" + conditionName + "]" + e); } } }; this.connect = function(params, referenceParams) { // prepare a final set of parameters to create connection with var _p = _prepareConnectionParams(params, referenceParams), jpc; // TODO probably a nicer return value if the connection was not made. _prepareConnectionParams // will return null (and log something) if either endpoint was full. what would be nicer is to // create a dedicated 'error' object. if (_p) { // a connect call will delete its created endpoints on detach, unless otherwise specified. // this is because the endpoints belong to this connection only, and are no use to // anyone else, so they hang around like a bad smell. if (_p.deleteEndpointsOnDetach == null) _p.deleteEndpointsOnDetach = true; // create the connection. it is not yet registered jpc = _newConnection(_p); // now add it the model, fire an event, and redraw _finaliseConnection(jpc, _p); } return jpc; }; // delete the given endpoint: either an Endpoint here, or its UUID. this.deleteEndpoint = function(object) { var endpoint = (typeof object == "string") ? endpointsByUUID[object] : object; if (endpoint) { var uuid = endpoint.getUuid(); if (uuid) endpointsByUUID[uuid] = null; endpoint.detachAll(); endpoint.cleanup(); if (endpoint.endpoint.cleanup) endpoint.endpoint.cleanup(); jsPlumbUtil.removeElements(endpoint.endpoint.getDisplayElements()); _currentInstance.anchorManager.deleteEndpoint(endpoint); for (var e in endpointsByElement) { var endpoints = endpointsByElement[e]; if (endpoints) { var newEndpoints = []; for (var i = 0, j = endpoints.length; i < j; i++) if (endpoints[i] != endpoint) newEndpoints.push(endpoints[i]); endpointsByElement[e] = newEndpoints; } if(endpointsByElement[e].length <1){ delete endpointsByElement[e]; } } if (!jsPlumbAdapter.headless) _currentInstance.dragManager.endpointDeleted(endpoint); } return _currentInstance; }; // delete every endpoint and their connections. distinct from reset because we dont clear listeners here. this.deleteEveryEndpoint = function() { _currentInstance.setSuspendDrawing(true); for ( var id in endpointsByElement) { var endpoints = endpointsByElement[id]; if (endpoints && endpoints.length) { for ( var i = 0, j = endpoints.length; i < j; i++) { _currentInstance.deleteEndpoint(endpoints[i]); } } } endpointsByElement = {}; endpointsByUUID = {}; _currentInstance.anchorManager.reset(); _currentInstance.dragManager.reset(); _currentInstance.setSuspendDrawing(false, true); return _currentInstance; }; var fireDetachEvent = function(jpc, doFireEvent, originalEvent) { // may have been given a connection, or in special cases, an object var connType = _currentInstance.Defaults.ConnectionType || _currentInstance.getDefaultConnectionType(), argIsConnection = jpc.constructor == connType, params = argIsConnection ? { connection:jpc, source : jpc.source, target : jpc.target, sourceId : jpc.sourceId, targetId : jpc.targetId, sourceEndpoint : jpc.endpoints[0], targetEndpoint : jpc.endpoints[1] } : jpc; if (doFireEvent) { _currentInstance.fire("jsPlumbConnectionDetached", params, originalEvent); // introduced in 1.3.11..an alias because the original event name is unwieldy. in future versions this will be the only event and the other will no longer be fired. _currentInstance.fire("connectionDetached", params, originalEvent); } _currentInstance.anchorManager.connectionDetached(params); }; // detach a connection this.detach = function() { if (arguments.length == 0) return; var connType = _currentInstance.Defaults.ConnectionType || _currentInstance.getDefaultConnectionType(), firstArgIsConnection = arguments[0].constructor == connType, params = arguments.length == 2 ? firstArgIsConnection ? (arguments[1] || {}) : arguments[0] : arguments[0], fireEvent = (params.fireEvent !== false), forceDetach = params.forceDetach, conn = firstArgIsConnection ? arguments[0] : params.connection; if (conn) { if (forceDetach || jsPlumbUtil.functionChain(true, false, [ [ conn.endpoints[0], "isDetachAllowed", [ conn ] ], [ conn.endpoints[1], "isDetachAllowed", [ conn ] ], [ conn, "isDetachAllowed", [ conn ] ], [ _currentInstance, "checkCondition", [ "beforeDetach", conn ] ] ])) { conn.endpoints[0].detach(conn, false, true, fireEvent); } } else { var _p = jsPlumb.extend( {}, params); // a backwards compatibility hack: source should be thought of as 'params' in this case. // test for endpoint uuids to detach if (_p.uuids) { _getEndpoint(_p.uuids[0]).detachFrom(_getEndpoint(_p.uuids[1]), fireEvent); } else if (_p.sourceEndpoint && _p.targetEndpoint) { _p.sourceEndpoint.detachFrom(_p.targetEndpoint); } else { var sourceId = _getId(_p.source), targetId = _getId(_p.target); _operation(sourceId, function(jpc) { if ((jpc.sourceId == sourceId && jpc.targetId == targetId) || (jpc.targetId == sourceId && jpc.sourceId == targetId)) { if (_currentInstance.checkCondition("beforeDetach", jpc)) { jpc.endpoints[0].detach(jpc, false, true, fireEvent); } } }); } } }; // detach all connections from some element. this.detachAllConnections = function(el, params) { params = params || {}; el = _gel(el); var id = _att(el, "id"), endpoints = endpointsByElement[id]; if (endpoints && endpoints.length) { for ( var i = 0, j = endpoints.length; i < j; i++) { endpoints[i].detachAll(params.fireEvent); } } return _currentInstance; }; // detach every connection but leave endpoints in place (unless a connection is set to auto delete them) this.detachEveryConnection = function(params) { params = params || {}; for ( var id in endpointsByElement) { var endpoints = endpointsByElement[id]; if (endpoints && endpoints.length) { for ( var i = 0, j = endpoints.length; i < j; i++) { endpoints[i].detachAll(params.fireEvent); } } } connectionsByScope = {}; return _currentInstance; }; this.draggable = function(el, options) { if (typeof el == 'object' && el.length) { for ( var i = 0, j = el.length; i < j; i++) { var ele = _gel(el[i]); if (ele) _initDraggableIfNecessary(ele, true, options); } } else if (el._nodes) { // TODO this is YUI specific; really the logic should be forced // into the library adapters (for jquery and mootools aswell) for ( var i = 0, j = el._nodes.length; i < j; i++) { var ele = _gel(el._nodes[i]); if (ele) _initDraggableIfNecessary(ele, true, options); } } else { var ele = _gel(el); if (ele) _initDraggableIfNecessary(ele, true, options); } return _currentInstance; }; // just a library-agnostic wrapper. this.extend = function(o1, o2) { return jsPlumb.CurrentLibrary.extend(o1, o2); }; // gets the default endpoint type. used when subclassing. see wiki. this.getDefaultEndpointType = function() { return jsPlumb.Endpoint; }; // gets the default connection type. used when subclassing. see wiki. this.getDefaultConnectionType = function() { return jsPlumb.Connection; }; // helpers for select/selectEndpoints var _setOperation = function(list, func, args, selector) { for (var i = 0, j = list.length; i < j; i++) { list[i][func].apply(list[i], args); } return selector(list); }, _getOperation = function(list, func, args) { var out = []; for (var i = 0, j = list.length; i < j; i++) { out.push([ list[i][func].apply(list[i], args), list[i] ]); } return out; }, setter = function(list, func, selector) { return function() { return _setOperation(list, func, arguments, selector); }; }, getter = function(list, func) { return function() { return _getOperation(list, func, arguments); }; }, prepareList = function(input, doNotGetIds) { var r = []; if (input) { if (typeof input == 'string') { if (input === "*") return input; r.push(input); } else { if (doNotGetIds) r = input; else { for (var i = 0, j = input.length; i < j; i++) r.push(_getId(_gel(input[i]))); } } } return r; }, filterList = function(list, value, missingIsFalse) { if (list === "*") return true; return list.length > 0 ? _indexOf(list, value) != -1 : !missingIsFalse; }; // get some connections, specifying source/target/scope this.getConnections = function(options, flat) { if (!options) { options = {}; } else if (options.constructor == String) { options = { "scope": options }; } var scope = options.scope || _currentInstance.getDefaultScope(), scopes = prepareList(scope, true), sources = prepareList(options.source), targets = prepareList(options.target), results = (!flat && scopes.length > 1) ? {} : [], _addOne = function(scope, obj) { if (!flat && scopes.length > 1) { var ss = results[scope]; if (ss == null) { ss = []; results[scope] = ss; } ss.push(obj); } else results.push(obj); }; for ( var i in connectionsByScope) { if (filterList(scopes, i)) { for ( var j = 0, jj = connectionsByScope[i].length; j < jj; j++) { var c = connectionsByScope[i][j]; if (filterList(sources, c.sourceId) && filterList(targets, c.targetId)) _addOne(i, c); } } } return results; }; var _curryEach = function(list, executor) { return function(f) { for (var i = 0, ii = list.length; i < ii; i++) { f(list[i]); } return executor(list); }; }, _curryGet = function(list) { return function(idx) { return list[idx]; }; }; var _makeCommonSelectHandler = function(list, executor) { var out = { length:list.length, each:_curryEach(list, executor), get:_curryGet(list) }, setters = ["setHover", "removeAllOverlays", "setLabel", "addClass", "addOverlay", "removeOverlay", "removeOverlays", "showOverlay", "hideOverlay", "showOverlays", "hideOverlays", "setPaintStyle", "setHoverPaintStyle", "setSuspendEvents", "setParameter", "setParameters", "setVisible", "repaint", "addType", "toggleType", "removeType", "removeClass", "setType", "bind", "unbind" ], getters = ["getLabel", "getOverlay", "isHover", "getParameter", "getParameters", "getPaintStyle", "getHoverPaintStyle", "isVisible", "hasType", "getType", "isSuspendEvents" ]; for (var i = 0, ii = setters.length; i < ii; i++) out[setters[i]] = setter(list, setters[i], executor); for (var i = 0, ii = getters.length; i < ii; i++) out[getters[i]] = getter(list, getters[i]); return out; }; var _makeConnectionSelectHandler = function(list) { var common = _makeCommonSelectHandler(list, _makeConnectionSelectHandler); return jsPlumb.CurrentLibrary.extend(common, { // setters setDetachable:setter(list, "setDetachable", _makeConnectionSelectHandler), setReattach:setter(list, "setReattach", _makeConnectionSelectHandler), setConnector:setter(list, "setConnector", _makeConnectionSelectHandler), detach:function() { for (var i = 0, ii = list.length; i < ii; i++) _currentInstance.detach(list[i]); }, // getters isDetachable:getter(list, "isDetachable"), isReattach:getter(list, "isReattach") }); }; var _makeEndpointSelectHandler = function(list) { var common = _makeCommonSelectHandler(list, _makeEndpointSelectHandler); return jsPlumb.CurrentLibrary.extend(common, { setEnabled:setter(list, "setEnabled", _makeEndpointSelectHandler), setAnchor:setter(list, "setAnchor", _makeEndpointSelectHandler), isEnabled:getter(list, "isEnabled"), detachAll:function() { for (var i = 0, ii = list.length; i < ii; i++) list[i].detachAll(); }, "remove":function() { for (var i = 0, ii = list.length; i < ii; i++) _currentInstance.deleteEndpoint(list[i]); } }); }; this.select = function(params) { params = params || {}; params.scope = params.scope || "*"; var c = params.connections || _currentInstance.getConnections(params, true); return _makeConnectionSelectHandler(c); }; this.selectEndpoints = function(params) { params = params || {}; params.scope = params.scope || "*"; var noElementFilters = !params.element && !params.source && !params.target, elements = noElementFilters ? "*" : prepareList(params.element), sources = noElementFilters ? "*" : prepareList(params.source), targets = noElementFilters ? "*" : prepareList(params.target), scopes = prepareList(params.scope, true); var ep = []; for (var el in endpointsByElement) { var either = filterList(elements, el, true), source = filterList(sources, el, true), sourceMatchExact = sources != "*", target = filterList(targets, el, true), targetMatchExact = targets != "*"; // if they requested 'either' then just match scope. otherwise if they requested 'source' (not as a wildcard) then we have to match only endpoints that have isSource set to to true, and the same thing with isTarget. if ( either || source || target ) { inner: for (var i = 0, ii = endpointsByElement[el].length; i < ii; i++) { var _ep = endpointsByElement[el][i]; if (filterList(scopes, _ep.scope, true)) { var noMatchSource = (sourceMatchExact && sources.length > 0 && !_ep.isSource), noMatchTarget = (targetMatchExact && targets.length > 0 && !_ep.isTarget); if (noMatchSource || noMatchTarget) continue inner; ep.push(_ep); } } } } return _makeEndpointSelectHandler(ep); }; // get all connections managed by the instance of jsplumb. this.getAllConnections = function() { return connectionsByScope; }; this.getDefaultScope = function() { return DEFAULT_SCOPE; }; // get an endpoint by uuid. this.getEndpoint = _getEndpoint; // get endpoints for some element. this.getEndpoints = function(el) { return endpointsByElement[_getId(el)]; }; /* * Gets an element's id, creating one if necessary. really only exposed * for the lib-specific functionality to access; would be better to pass * the current instance into the lib-specific code (even though this is * a static call. i just don't want to expose it to the public API). */ this.getId = _getId; this.getOffset = function(id) { var o = offsets[id]; return _updateOffset({elId:id}); }; // gets a library-agnostic selector. not necessary for use outside of jsplumb, since // you already know what library you're using it with. this.getSelector = function() { return jsPlumb.CurrentLibrary.getSelector.apply(null, arguments); }; // get the size of the element with the given id, perhaps from cache. this.getSize = function(id) { var s = sizes[id]; if (!s) _updateOffset({elId:id}); return sizes[id]; }; this.appendElement = _appendElement; var _hoverSuspended = false; this.isHoverSuspended = function() { return _hoverSuspended; }; this.setHoverSuspended = function(s) { _hoverSuspended = s; }; var _isAvailable = function(m) { return function() { return jsPlumbAdapter.isRenderModeAvailable(m); }; } this.isCanvasAvailable = _isAvailable("canvas"); this.isSVGAvailable = _isAvailable("svg"); this.isVMLAvailable = _isAvailable("vml"); // set an element's connections to be hidden this.hide = function(el, changeEndpoints) { _setVisible(el, "none", changeEndpoints); return _currentInstance; }; // exposed for other objects to use to get a unique id. this.idstamp = _idstamp; /** * callback from the current library to tell us to prepare ourselves (attach * mouse listeners etc; can't do that until the library has provided a bind method) */ this.init = function() { if (!initialized) { _currentInstance.anchorManager = new jsPlumb.AnchorManager({jsPlumbInstance:_currentInstance}); _currentInstance.setRenderMode(_currentInstance.Defaults.RenderMode); // calling the method forces the capability logic to be run. initialized = true; _currentInstance.fire("ready", _currentInstance); } }; this.log = log; this.jsPlumbUIComponent = jsPlumbUIComponent; /* * Creates an anchor with the given params. * * * Returns: The newly created Anchor. * Throws: an error if a named anchor was not found. */ this.makeAnchor = function() { var _a = function(t, p) { if (jsPlumb.Anchors[t]) return new jsPlumb.Anchors[t](p); if (!_currentInstance.Defaults.DoNotThrowErrors) throw { msg:"jsPlumb: unknown anchor type '" + t + "'" }; }; if (arguments.length == 0) return null; var specimen = arguments[0], elementId = arguments[1], jsPlumbInstance = arguments[2], newAnchor = null; // if it appears to be an anchor already... if (specimen.compute && specimen.getOrientation) return specimen; //TODO hazy here about whether it should be added or is already added somehow. // is it the name of an anchor type? else if (typeof specimen == "string") { //newAnchor = jsPlumb.Anchors[arguments[0]]({elementId:elementId, jsPlumbInstance:_currentInstance}); newAnchor = _a(arguments[0], {elementId:elementId, jsPlumbInstance:_currentInstance}); } // is it an array? it will be one of: // an array of [name, params] - this defines a single anchor // an array of arrays - this defines some dynamic anchors // an array of numbers - this defines a single anchor. else if (_isArray(specimen)) { if (_isArray(specimen[0]) || _isString(specimen[0])) { if (specimen.length == 2 && _isString(specimen[0]) && _isObject(specimen[1])) { var pp = jsPlumb.extend({elementId:elementId, jsPlumbInstance:_currentInstance}, specimen[1]); //newAnchor = new jsPlumb.Anchors[specimen[0]](pp); newAnchor = _a(specimen[0], pp); } else newAnchor = new jsPlumb.DynamicAnchor({anchors:specimen, selector:null, elementId:elementId, jsPlumbInstance:jsPlumbInstance}); } else { var anchorParams = { x:specimen[0], y:specimen[1], orientation : (specimen.length >= 4) ? [ specimen[2], specimen[3] ] : [0,0], offsets : (specimen.length >= 6) ? [ specimen[4], specimen[5] ] : [ 0, 0 ], elementId:elementId, jsPlumbInstance:jsPlumbInstance, cssClass:specimen.length == 7 ? specimen[6] : null }; newAnchor = new jsPlumb.Anchor(anchorParams); newAnchor.clone = function() { return new jsPlumb.Anchor(anchorParams); }; } } if (!newAnchor.id) newAnchor.id = "anchor_" + _idstamp(); return newAnchor; }; /** * makes a list of anchors from the given list of types or coords, eg * ["TopCenter", "RightMiddle", "BottomCenter", [0, 1, -1, -1] ] */ this.makeAnchors = function(types, elementId, jsPlumbInstance) { var r = []; for ( var i = 0, ii = types.length; i < ii; i++) { if (typeof types[i] == "string") r.push(jsPlumb.Anchors[types[i]]({elementId:elementId, jsPlumbInstance:jsPlumbInstance})); else if (_isArray(types[i])) r.push(_currentInstance.makeAnchor(types[i], elementId, jsPlumbInstance)); } return r; }; /** * Makes a dynamic anchor from the given list of anchors (which may be in shorthand notation as strings or dimension arrays, or Anchor * objects themselves) and the given, optional, anchorSelector function (jsPlumb uses a default if this is not provided; most people will * not need to provide this - i think). */ this.makeDynamicAnchor = function(anchors, anchorSelector) { return new jsPlumb.DynamicAnchor({anchors:anchors, selector:anchorSelector, elementId:null, jsPlumbInstance:_currentInstance}); }; var _targetEndpointDefinitions = {}, _targetEndpoints = {}, _targetEndpointsUnique = {}, _targetMaxConnections = {}, _setEndpointPaintStylesAndAnchor = function(ep, epIndex) { ep.paintStyle = ep.paintStyle || _currentInstance.Defaults.EndpointStyles[epIndex] || _currentInstance.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyles[epIndex] || jsPlumb.Defaults.EndpointStyle; ep.hoverPaintStyle = ep.hoverPaintStyle || _currentInstance.Defaults.EndpointHoverStyles[epIndex] || _currentInstance.Defaults.EndpointHoverStyle || jsPlumb.Defaults.EndpointHoverStyles[epIndex] || jsPlumb.Defaults.EndpointHoverStyle; ep.anchor = ep.anchor || _currentInstance.Defaults.Anchors[epIndex] || _currentInstance.Defaults.Anchor || jsPlumb.Defaults.Anchors[epIndex] || jsPlumb.Defaults.Anchor; ep.endpoint = ep.endpoint || _currentInstance.Defaults.Endpoints[epIndex] || _currentInstance.Defaults.Endpoint || jsPlumb.Defaults.Endpoints[epIndex] || jsPlumb.Defaults.Endpoint; }; // see API docs this.makeTarget = function(el, params, referenceParams) { var p = jsPlumb.extend({_jsPlumb:_currentInstance}, referenceParams); jsPlumb.extend(p, params); _setEndpointPaintStylesAndAnchor(p, 1); var jpcl = jsPlumb.CurrentLibrary, targetScope = p.scope || _currentInstance.Defaults.Scope, deleteEndpointsOnDetach = !(p.deleteEndpointsOnDetach === false), maxConnections = p.maxConnections || -1, onMaxConnections = p.onMaxConnections; _doOne = function(_el) { // get the element's id and store the endpoint definition for it. jsPlumb.connect calls will look for one of these, // and use the endpoint definition if found. var elid = _getId(_el); _targetEndpointDefinitions[elid] = p; _targetEndpointsUnique[elid] = p.uniqueEndpoint, _targetMaxConnections[elid] = maxConnections, _targetsEnabled[elid] = true, proxyComponent = new jsPlumbUIComponent(p); var dropOptions = jsPlumb.extend({}, p.dropOptions || {}), _drop = function() { var originalEvent = jsPlumb.CurrentLibrary.getDropEvent(arguments), targetCount = _currentInstance.select({target:elid}).length; _currentInstance.currentlyDragging = false; var draggable = _gel(jpcl.getDragObject(arguments)), id = _att(draggable, "dragId"), // restore the original scope if necessary (issue 57) scope = _att(draggable, "originalScope"), jpc = floatingConnections[id], source = jpc.endpoints[0], _endpoint = p.endpoint ? jsPlumb.extend({}, p.endpoint) : {}; if (!_targetsEnabled[elid] || _targetMaxConnections[elid] > 0 && targetCount >= _targetMaxConnections[elid]){ if (onMaxConnections) { onMaxConnections({ element:_el, connection:jpc }, originalEvent); } return false; } // unlock the source anchor to allow it to refresh its position if necessary source.anchor.locked = false; if (scope) jpcl.setDragScope(draggable, scope); // check if drop is allowed here. //var _continue = jpc.isDropAllowed(jpc.sourceId, _getId(_el), jpc.scope); var _continue = proxyComponent.isDropAllowed(jpc.sourceId, _getId(_el), jpc.scope, jpc, null); // regardless of whether the connection is ok, reconfigure the existing connection to // point at the current info. we need this to be correct for the detach event that will follow. // clear the source endpoint from the list to detach. we will detach this connection at this // point, but we want to keep the source endpoint. the target is a floating endpoint and should // be removed. TODO need to figure out whether this code can result in endpoints kicking around // when they shouldnt be. like is this a full detach of a connection? can it be? if (jpc.endpointsToDeleteOnDetach) { if (source === jpc.endpointsToDeleteOnDetach[0]) jpc.endpointsToDeleteOnDetach[0] = null; else if (source === jpc.endpointsToDeleteOnDetach[1]) jpc.endpointsToDeleteOnDetach[1] = null; } // reinstate any suspended endpoint; this just puts the connection back into // a state in which it will report sensible values if someone asks it about // its target. we're going to throw this connection away shortly so it doesnt matter // if we manipulate it a bit. if (jpc.suspendedEndpoint) { jpc.targetId = jpc.suspendedEndpoint.elementId; jpc.target = jpcl.getElementObject(jpc.suspendedEndpoint.elementId); jpc.endpoints[1] = jpc.suspendedEndpoint; } if (_continue) { // detach this connection from the source. source.detach(jpc, false, true, false); // make a new Endpoint for the target var newEndpoint = _targetEndpoints[elid] || _currentInstance.addEndpoint(_el, p); if (p.uniqueEndpoint) _targetEndpoints[elid] = newEndpoint; // may of course just store what it just pulled out. that's ok. newEndpoint._makeTargetCreator = true; // if the anchor has a 'positionFinder' set, then delegate to that function to find // out where to locate the anchor. if (newEndpoint.anchor.positionFinder != null) { var dropPosition = jpcl.getUIPosition(arguments, _currentInstance.getZoom()), elPosition = _getOffset(_el, _currentInstance), elSize = _getSize(_el), ap = newEndpoint.anchor.positionFinder(dropPosition, elPosition, elSize, newEndpoint.anchor.constructorParams); newEndpoint.anchor.x = ap[0]; newEndpoint.anchor.y = ap[1]; // now figure an orientation for it..kind of hard to know what to do actually. probably the best thing i can do is to // support specifying an orientation in the anchor's spec. if one is not supplied then i will make the orientation // be what will cause the most natural link to the source: it will be pointing at the source, but it needs to be // specified in one axis only, and so how to make that choice? i think i will use whichever axis is the one in which // the target is furthest away from the source. } var c = _currentInstance.connect({ source:source, target:newEndpoint, scope:scope, previousConnection:jpc, container:jpc.parent, deleteEndpointsOnDetach:deleteEndpointsOnDetach, endpointsToDeleteOnDetach : deleteEndpointsOnDetach ? [ source, newEndpoint ] : null, // 'endpointWillMoveAfterConnection' is set by the makeSource function, and it indicates that the // given endpoint will actually transfer from the element it is currently attached to to some other // element after a connection has been established. in that case, we do not want to fire the // connection event, since it will have the wrong data in it; makeSource will do it for us. // this is controlled by the 'parent' parameter on a makeSource call. doNotFireConnectionEvent:source.endpointWillMoveAfterConnection }); // delete the original target endpoint. but only want to do this if the endpoint was created // automatically and has no other connections. if (jpc.endpoints[1]._makeTargetCreator && jpc.endpoints[1].connections.length < 2) _currentInstance.deleteEndpoint(jpc.endpoints[1]); c.repaint(); } // if not allowed to drop... else { // TODO this code is identical (pretty much) to what happens when a connection // dragged from a normal endpoint is in this situation. refactor. // is this an existing connection, and will we reattach? if (jpc.suspendedEndpoint) { //if (source.isReattach) { if (jpc.isReattach()) { jpc.setHover(false); jpc.floatingAnchorIndex = null; jpc.suspendedEndpoint.addConnection(jpc); _currentInstance.repaint(source.elementId); } else source.detach(jpc, false, true, true, originalEvent); // otherwise, detach the connection and tell everyone about it. } } }; var dropEvent = jpcl.dragEvents['drop']; dropOptions["scope"] = dropOptions["scope"] || targetScope; dropOptions[dropEvent] = _wrap(dropOptions[dropEvent], _drop); jpcl.initDroppable(_el, dropOptions, true); }; el = _convertYUICollection(el); var inputs = el.length && el.constructor != String ? el : [ el ]; for (var i = 0, ii = inputs.length; i < ii; i++) { _doOne(_gel(inputs[i])); } return _currentInstance; }; // see api docs this.unmakeTarget = function(el, doNotClearArrays) { el = jsPlumb.CurrentLibrary.getElementObject(el); var elid = _getId(el); // TODO this is not an exhaustive unmake of a target, since it does not remove the droppable stuff from // the element. the effect will be to prevent it form behaving as a target, but it's not completely purged. if (!doNotClearArrays) { delete _targetEndpointDefinitions[elid]; delete _targetEndpointsUnique[elid]; delete _targetMaxConnections[elid]; delete _targetsEnabled[elid]; } return _currentInstance; }; // see api docs this.makeTargets = function(els, params, referenceParams) { for ( var i = 0, ii = els.length; i < ii; i++) { _currentInstance.makeTarget(els[i], params, referenceParams); } }; var _sourceEndpointDefinitions = {}, _sourceEndpoints = {}, _sourceEndpointsUnique = {}, _sourcesEnabled = {}, _sourceTriggers = {}, _sourceMaxConnections = {}, _targetsEnabled = {}, selectorFilter = function(evt, _el, selector) { var t = evt.target || evt.srcElement, ok = false, sel = _currentInstance.getSelector(_el, selector); for (var j = 0; j < sel.length; j++) { if (sel[j] == t) { ok = true; break; } } return ok; }; // see api docs this.makeSource = function(el, params, referenceParams) { var p = jsPlumb.extend({}, referenceParams); jsPlumb.extend(p, params); _setEndpointPaintStylesAndAnchor(p, 0); var jpcl = jsPlumb.CurrentLibrary, maxConnections = p.maxConnections || -1, onMaxConnections = p.onMaxConnections, _doOne = function(_el) { // get the element's id and store the endpoint definition for it. jsPlumb.connect calls will look for one of these, // and use the endpoint definition if found. var elid = _getId(_el), parentElement = function() { return p.parent == null ? p.parent : p.parent === "parent" ? jpcl.getElementObject(jpcl.getDOMElement(_el).parentNode) : jpcl.getElementObject(p.parent); }, idToRegisterAgainst = p.parent != null ? _currentInstance.getId(parentElement()) : elid; _sourceEndpointDefinitions[idToRegisterAgainst] = p; _sourceEndpointsUnique[idToRegisterAgainst] = p.uniqueEndpoint; _sourcesEnabled[idToRegisterAgainst] = true; var stopEvent = jpcl.dragEvents["stop"], dragEvent = jpcl.dragEvents["drag"], dragOptions = jsPlumb.extend({ }, p.dragOptions || {}), existingDrag = dragOptions.drag, existingStop = dragOptions.stop, ep = null, endpointAddedButNoDragYet = false; _sourceMaxConnections[idToRegisterAgainst] = maxConnections; // set scope if its not set in dragOptions but was passed in in params dragOptions["scope"] = dragOptions["scope"] || p.scope; dragOptions[dragEvent] = _wrap(dragOptions[dragEvent], function() { if (existingDrag) existingDrag.apply(this, arguments); endpointAddedButNoDragYet = false; }); dragOptions[stopEvent] = _wrap(dragOptions[stopEvent], function() { if (existingStop) existingStop.apply(this, arguments); //_currentlyDown = false; _currentInstance.currentlyDragging = false; if (ep.connections.length == 0) _currentInstance.deleteEndpoint(ep); else { jpcl.unbind(ep.canvas, "mousedown"); // reset the anchor to the anchor that was initially provided. the one we were using to drag // the connection was just a placeholder that was located at the place the user pressed the // mouse button to initiate the drag. var anchorDef = p.anchor || _currentInstance.Defaults.Anchor, oldAnchor = ep.anchor, oldConnection = ep.connections[0]; ep.setAnchor(_currentInstance.makeAnchor(anchorDef, elid, _currentInstance)); if (p.parent) { var parent = parentElement(); if (parent) { var currentId = ep.elementId, potentialParent = p.container || _currentInstance.Defaults.Container || jsPlumb.Defaults.Container; ep.setElement(parent, potentialParent); ep.endpointWillMoveAfterConnection = false; _currentInstance.anchorManager.rehomeEndpoint(currentId, parent); oldConnection.previousConnection = null; // remove from connectionsByScope _removeWithFunction(connectionsByScope[oldConnection.scope], function(c) { return c.id === oldConnection.id; }); _currentInstance.anchorManager.connectionDetached({ sourceId:oldConnection.sourceId, targetId:oldConnection.targetId, connection:oldConnection }); _finaliseConnection(oldConnection); } } ep.repaint(); _currentInstance.repaint(ep.elementId); _currentInstance.repaint(oldConnection.targetId); } }); // when the user presses the mouse, add an Endpoint, if we are enabled. var mouseDownListener = function(e) { // if disabled, return. if (!_sourcesEnabled[idToRegisterAgainst]) return; // if a filter was given, run it, and return if it says no. if (p.filter) { var evt = jpcl.getOriginalEvent(e), r = jsPlumbUtil.isString(p.filter) ? selectorFilter(evt, _el, p.filter) : p.filter(evt, _el); if (r === false) return; } // if maxConnections reached var sourceCount = _currentInstance.select({source:idToRegisterAgainst}).length if (_sourceMaxConnections[idToRegisterAgainst] >= 0 && sourceCount >= _sourceMaxConnections[idToRegisterAgainst]) { if (onMaxConnections) { onMaxConnections({ element:_el, maxConnections:maxConnections }, e); } return false; } // make sure we have the latest offset for this div var myOffsetInfo = _updateOffset({elId:elid}).o, z = _currentInstance.getZoom(), x = ( ((e.pageX || e.page.x) / z) - myOffsetInfo.left) / myOffsetInfo.width, y = ( ((e.pageY || e.page.y) / z) - myOffsetInfo.top) / myOffsetInfo.height, parentX = x, parentY = y; // if there is a parent, the endpoint will actually be added to it now, rather than the div // that was the source. in that case, we have to adjust the anchor position so it refers to // the parent. if (p.parent) { var pEl = parentElement(), pId = _getId(pEl); myOffsetInfo = _updateOffset({elId:pId}).o; parentX = ((e.pageX || e.page.x) - myOffsetInfo.left) / myOffsetInfo.width, parentY = ((e.pageY || e.page.y) - myOffsetInfo.top) / myOffsetInfo.height; } // we need to override the anchor in here, and force 'isSource', but we don't want to mess with // the params passed in, because after a connection is established we're going to reset the endpoint // to have the anchor we were given. var tempEndpointParams = {}; jsPlumb.extend(tempEndpointParams, p); tempEndpointParams.isSource = true; tempEndpointParams.anchor = [x,y,0,0]; tempEndpointParams.parentAnchor = [ parentX, parentY, 0, 0 ]; tempEndpointParams.dragOptions = dragOptions; // if a parent was given we need to turn that into a "container" argument. this is, by default, // the parent of the element we will move to, so parent of p.parent in this case. however, if // the user has specified a 'container' on the endpoint definition or on // the defaults, we should use that. if (p.parent) { var potentialParent = tempEndpointParams.container || _currentInstance.Defaults.Container || jsPlumb.Defaults.Container; if (potentialParent) tempEndpointParams.container = potentialParent; else tempEndpointParams.container = jsPlumb.CurrentLibrary.getParent(parentElement()); } ep = _currentInstance.addEndpoint(elid, tempEndpointParams); endpointAddedButNoDragYet = true; // we set this to prevent connections from firing attach events before this function has had a chance // to move the endpoint. ep.endpointWillMoveAfterConnection = p.parent != null; ep.endpointWillMoveTo = p.parent ? parentElement() : null; ep.addedViaMouse = true; var _delTempEndpoint = function() { // this mouseup event is fired only if no dragging occurred, by jquery and yui, but for mootools // it is fired even if dragging has occurred, in which case we would blow away a perfectly // legitimate endpoint, were it not for this check. the flag is set after adding an // endpoint and cleared in a drag listener we set in the dragOptions above. if(endpointAddedButNoDragYet) { _currentInstance.deleteEndpoint(ep); } }; _currentInstance.registerListener(ep.canvas, "mouseup", _delTempEndpoint); _currentInstance.registerListener(_el, "mouseup", _delTempEndpoint); // and then trigger its mousedown event, which will kick off a drag, which will start dragging // a new connection from this endpoint. jpcl.trigger(ep.canvas, "mousedown", e); }; // register this on jsPlumb so that it can be cleared by a reset. _currentInstance.registerListener(_el, "mousedown", mouseDownListener); _sourceTriggers[elid] = mouseDownListener; // lastly, if a filter was provided, set it as a dragFilter on the element, // to prevent the element drag function from kicking in when we want to // drag a new connection if (p.filter && jsPlumbUtil.isString(p.filter)) { jpcl.setDragFilter(_el, p.filter); } }; el = _convertYUICollection(el); var inputs = el.length && el.constructor != String ? el : [ el ]; for (var i = 0, ii = inputs.length; i < ii; i++) { _doOne(_gel(inputs[i])); } return _currentInstance; }; // see api docs this.unmakeSource = function(el, doNotClearArrays) { el = jsPlumb.CurrentLibrary.getElementObject(el); var id = _getId(el), mouseDownListener = _sourceTriggers[id]; if (mouseDownListener) _currentInstance.unregisterListener(el, "mousedown", mouseDownListener); if (!doNotClearArrays) { delete _sourceEndpointDefinitions[id]; delete _sourceEndpointsUnique[id]; delete _sourcesEnabled[id]; delete _sourceTriggers[id]; delete _sourceMaxConnections[id]; } return _currentInstance; }; // see api docs this.unmakeEverySource = function() { for (var i in _sourcesEnabled) _currentInstance.unmakeSource(i, true); _sourceEndpointDefinitions = {}; _sourceEndpointsUnique = {}; _sourcesEnabled = {}; _sourceTriggers = {}; }; // see api docs this.unmakeEveryTarget = function() { for (var i in _targetsEnabled) _currentInstance.unmakeTarget(i, true); _targetEndpointDefinitions = {}; _targetEndpointsUnique = {}; _targetMaxConnections = {}; _targetsEnabled = {}; return _currentInstance; }; this.makeSources = function(els, params, referenceParams) { for ( var i = 0, ii = els.length; i < ii; i++) { _currentInstance.makeSource(els[i], params, referenceParams); } return _currentInstance; }; // does the work of setting a source enabled or disabled. var _setEnabled = function(type, el, state, toggle) { var a = type == "source" ? _sourcesEnabled : _targetsEnabled; if (_isString(el)) a[el] = toggle ? !a[el] : state; else if (el.length) { el = _convertYUICollection(el); for (var i = 0, ii = el.length; i < ii; i++) { var id = _el = jsPlumb.CurrentLibrary.getElementObject(el[i]), id = _getId(_el); a[id] = toggle ? !a[id] : state; } } return _currentInstance; }; this.setSourceEnabled = function(el, state) { return _setEnabled("source", el, state); }; this.toggleSourceEnabled = function(el) { _setEnabled("source", el, null, true); return _currentInstance.isSourceEnabled(el); }; this.isSource = function(el) { el = jsPlumb.CurrentLibrary.getElementObject(el); return _sourcesEnabled[_getId(el)] != null; }; this.isSourceEnabled = function(el) { el = jsPlumb.CurrentLibrary.getElementObject(el); return _sourcesEnabled[_getId(el)] === true; }; this.setTargetEnabled = function(el, state) { return _setEnabled("target", el, state); }; this.toggleTargetEnabled = function(el) { _setEnabled("target", el, null, true); return _currentInstance.isTargetEnabled(el); }; this.isTarget = function(el) { el = jsPlumb.CurrentLibrary.getElementObject(el); return _targetsEnabled[_getId(el)] != null; }; this.isTargetEnabled = function(el) { el = jsPlumb.CurrentLibrary.getElementObject(el); return _targetsEnabled[_getId(el)] === true; }; this.ready = function(fn) { _currentInstance.bind("ready", fn); }; // repaint some element's endpoints and connections this.repaint = function(el, ui, timestamp) { // support both lists... if (typeof el == 'object' && el.length) for ( var i = 0, ii = el.length; i < ii; i++) { _draw(_gel(el[i]), ui, timestamp); } else // ...and single strings. _draw(_gel(el), ui, timestamp); return _currentInstance; }; // repaint every endpoint and connection. this.repaintEverything = function() { var timestamp = _timestamp(); for ( var elId in endpointsByElement) { _draw(_gel(elId), null, timestamp); } return _currentInstance; }; this.removeAllEndpoints = function(el, recurse) { var _one = function(_el) { var elId = jsPlumbUtil.isString(_el) ? _el : _getId(_gel(_el)), ebe = endpointsByElement[elId]; if (ebe) { for ( var i = 0, ii = ebe.length; i < ii; i++) _currentInstance.deleteEndpoint(ebe[i]); } delete endpointsByElement[elId]; if (recurse) { var del = jsPlumb.CurrentLibrary.getDOMElement(_gel(_el)); if (del && del.nodeType != 3 && del.nodeType != 8 ) { for (var i = 0, ii = del.childNodes.length; i < ii; i++) { _one(del.childNodes[i]); } } } }; _one(el); return _currentInstance; }; this.remove = function(el) { var _el = _gel(el); var id = jsPlumbUtil.isString(el) ? el : _getId(_el); _currentInstance.doWhileSuspended(function() { _currentInstance.removeAllEndpoints(id, true); }); jsPlumb.CurrentLibrary.removeElement(_el); }; var _registeredListeners = {}, _unbindRegisteredListeners = function() { for (var i in _registeredListeners) { for (var j = 0, jj = _registeredListeners[i].length; j < jj; j++) { var info = _registeredListeners[i][j]; jsPlumb.CurrentLibrary.unbind(info.el, info.event, info.listener); } } _registeredListeners = {}; }; // internal register listener method. gives us a hook to clean things up // with if the user calls jsPlumb.reset. this.registerListener = function(el, type, listener) { jsPlumb.CurrentLibrary.bind(el, type, listener); _addToList(_registeredListeners, type, {el:el, event:type, listener:listener}); }; this.unregisterListener = function(el, type, listener) { jsPlumb.CurrentLibrary.unbind(el, type, listener); _removeWithFunction(_registeredListeners, function(rl) { return rl.type == type && rl.listener == listener; }); }; this.reset = function() { _currentInstance.deleteEveryEndpoint(); _currentInstance.unbind(); _targetEndpointDefinitions = {}; _targetEndpoints = {}; _targetEndpointsUnique = {}; _targetMaxConnections = {}; _sourceEndpointDefinitions = {}; _sourceEndpoints = {}; _sourceEndpointsUnique = {}; _sourceMaxConnections = {}; _unbindRegisteredListeners(); _currentInstance.anchorManager.reset(); if (!jsPlumbAdapter.headless) _currentInstance.dragManager.reset(); }; this.setDefaultScope = function(scope) { DEFAULT_SCOPE = scope; return _currentInstance; }; // sets whether or not some element should be currently draggable. this.setDraggable = _setDraggable; // sets the id of some element, changing whatever we need to to keep track. this.setId = function(el, newId, doNotSetAttribute) { var id = el.constructor == String ? el : _currentInstance.getId(el), sConns = _currentInstance.getConnections({source:id, scope:'*'}, true), tConns = _currentInstance.getConnections({target:id, scope:'*'}, true); newId = "" + newId; if (!doNotSetAttribute) { el = jsPlumb.CurrentLibrary.getElementObject(id); jsPlumb.CurrentLibrary.setAttribute(el, "id", newId); } el = jsPlumb.CurrentLibrary.getElementObject(newId); endpointsByElement[newId] = endpointsByElement[id] || []; for (var i = 0, ii = endpointsByElement[newId].length; i < ii; i++) { endpointsByElement[newId][i].setElementId(newId); endpointsByElement[newId][i].setReferenceElement(el); } delete endpointsByElement[id]; _currentInstance.anchorManager.changeId(id, newId); if (!jsPlumbAdapter.headless) _currentInstance.dragManager.changeId(id, newId); var _conns = function(list, epIdx, type) { for (var i = 0, ii = list.length; i < ii; i++) { list[i].endpoints[epIdx].setElementId(newId); list[i].endpoints[epIdx].setReferenceElement(el); list[i][type + "Id"] = newId; list[i][type] = el; } }; _conns(sConns, 0, "source"); _conns(tConns, 1, "target"); _currentInstance.repaint(newId); }; // called to notify us that an id WAS changed, and we should do our changes, but we // dont need to change the element's DOM attribute. this.setIdChanged = function(oldId, newId) { _currentInstance.setId(oldId, newId, true); }; this.setDebugLog = function(debugLog) { log = debugLog; }; var _suspendDrawing = false, _suspendedAt = null; // set whether or not drawing is suspended. you should use this when doing bulk painting, // like when first drawing a UI. this.setSuspendDrawing = function(val, repaintAfterwards) { _suspendDrawing = val; if (val) _suspendedAt = new Date().getTime(); else _suspendedAt = null; if (repaintAfterwards) _currentInstance.repaintEverything(); }; // returns whether or not drawing is currently suspended. this.isSuspendDrawing = function() { return _suspendDrawing; }; // return timestamp for when drawing was suspended. this.getSuspendedAt = function() { return _suspendedAt; }; // suspends drawing, runs the given function, then re-enables drawing (and repaints, // unless you tell it not to) this.doWhileSuspended = function(fn, doNotRepaintAfterwards) { _currentInstance.setSuspendDrawing(true); try { fn(); } catch (e) { _log("Function run while suspended failed", e); } _currentInstance.setSuspendDrawing(false, !doNotRepaintAfterwards); }; this.updateOffset = _updateOffset; this.getOffset = function(elId) { return offsets[elId]; }; this.getSize = function(elId) { return sizes[elId]; }; this.getCachedData = _getCachedData; this.timestamp = _timestamp; /* * Property: SVG * Constant for use with the setRenderMode method */ /* * Property: VML * Constant for use with the setRenderMode method */ /* * Property: CANVAS * Constant for use with the setRenderMode method */ this.SVG = "svg"; this.CANVAS = "canvas"; this.VML = "vml"; /* * Function: setRenderMode * Sets render mode: jsPlumb.SVG or jsPlumb.VML. jsPlumb will fall back to VML if it determines that * what you asked for is not supported (and that VML is). If you asked for VML but the browser does * not support it, jsPlumb uses SVG. * * Parameters: * mode - a string representing the mode. Use one of the jsPlumb render mode constants as discussed above. * * Returns: * The render mode that jsPlumb set, which of course may be different from that requested. */ this.setRenderMode = function(mode) { renderMode = jsPlumbAdapter.setRenderMode(mode); return renderMode; }; /* * Function: getRenderMode * * Returns: * The current render mode. */ this.getRenderMode = function() { return renderMode; }; this.show = function(el, changeEndpoints) { _setVisible(el, "block", changeEndpoints); return _currentInstance; }; /* * Function: sizeCanvas * Helper to size a canvas. You would typically use * this when writing your own Connector or Endpoint implementation. * * Parameters: * x - [int] x position for the Canvas origin * y - [int] y position for the Canvas origin * w - [int] width of the canvas * h - [int] height of the canvas * * Returns: * The current jsPlumb instance */ this.sizeCanvas = function(canvas, x, y, w, h) { if (canvas) { canvas.style.height = h + "px"; canvas.height = h; canvas.style.width = w + "px"; canvas.width = w; canvas.style.left = x + "px"; canvas.style.top = y + "px"; } return _currentInstance; }; /** * gets some test hooks. nothing writable. */ this.getTestHarness = function() { return { endpointsByElement : endpointsByElement, endpointCount : function(elId) { var e = endpointsByElement[elId]; return e ? e.length : 0; }, connectionCount : function(scope) { scope = scope || DEFAULT_SCOPE; var c = connectionsByScope[scope]; return c ? c.length : 0; }, //findIndex : _findIndex, getId : _getId, makeAnchor:self.makeAnchor, makeDynamicAnchor:self.makeDynamicAnchor }; }; // TODO: update this method to return the current state. this.toggleVisible = _toggleVisible; this.toggleDraggable = _toggleDraggable; /* * Helper method to wrap an existing function with one of * your own. This is used by the various implementations to wrap event * callbacks for drag/drop etc; it allows jsPlumb to be transparent in * its handling of these things. If a user supplies their own event * callback, for anything, it will always be called. */ this.wrap = _wrap; this.addListener = this.bind; /* helper method to take an xy location and adjust it for the parent's offset and scroll. */ this.adjustForParentOffsetAndScroll = function(xy, el) { var offsetParent = null, result = xy; if (el.tagName.toLowerCase() === "svg" && el.parentNode) { offsetParent = el.parentNode; } else if (el.offsetParent) { offsetParent = el.offsetParent; } if (offsetParent != null) { var po = offsetParent.tagName.toLowerCase() === "body" ? {left:0,top:0} : _getOffset(offsetParent, _currentInstance), so = offsetParent.tagName.toLowerCase() === "body" ? {left:0,top:0} : {left:offsetParent.scrollLeft, top:offsetParent.scrollTop}; // i thought it might be cool to do this: // lastReturnValue[0] = lastReturnValue[0] - offsetParent.offsetLeft + offsetParent.scrollLeft; // lastReturnValue[1] = lastReturnValue[1] - offsetParent.offsetTop + offsetParent.scrollTop; // but i think it ignores margins. my reasoning was that it's quicker to not hand off to some underlying // library. result[0] = xy[0] - po.left + so.left; result[1] = xy[1] - po.top + so.top; } return result; }; if (!jsPlumbAdapter.headless) { _currentInstance.dragManager = jsPlumbAdapter.getDragManager(_currentInstance); _currentInstance.recalculateOffsets = _currentInstance.dragManager.updateOffsets; } }; // --------------------- static instance + AMD registration ------------------------------------------- // create static instance and assign to window if window exists. var jsPlumb = new jsPlumbInstance(); if (typeof window != 'undefined') window.jsPlumb = jsPlumb; // add 'getInstance' method to static instance jsPlumb.getInstance = function(_defaults) { var j = new jsPlumbInstance(_defaults); j.init(); return j; }; // maybe register static instance as an AMD module, and getInstance method too. if ( typeof define === "function") { define( "jsplumb", [], function () { return jsPlumb; } ); define( "jsplumbinstance", [], function () { return jsPlumb.getInstance(); } ); } // CommonJS if (typeof exports !== 'undefined') { exports.jsPlumb = jsPlumb; } // --------------------- end static instance + AMD registration ------------------------------------------- })(); /* * jsPlumb * * Title:jsPlumb 1.4.0 * * Provides a way to visually connect elements on an HTML page, using either SVG, Canvas * elements, or VML. * * This file contains the code for creating and manipulating anchors. * * Copyright (c) 2010 - 2013 Simon Porritt (simon.porritt@gmail.com) * * http://jsplumb.org * http://github.com/sporritt/jsplumb * http://code.google.com/p/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ;(function() { // // manages anchors for all elements. // jsPlumb.AnchorManager = function(params) { var _amEndpoints = {}, continuousAnchors = {}, continuousAnchorLocations = {}, userDefinedContinuousAnchorLocations = {}, continuousAnchorOrientations = {}, Orientation = { HORIZONTAL : "horizontal", VERTICAL : "vertical", DIAGONAL : "diagonal", IDENTITY:"identity" }, connectionsByElementId = {}, self = this, anchorLists = {}, jsPlumbInstance = params.jsPlumbInstance, jpcl = jsPlumb.CurrentLibrary, floatingConnections = {}, // TODO this functions uses a crude method of determining orientation between two elements. // 'diagonal' should be chosen when the angle of the line between the two centers is around // one of 45, 135, 225 and 315 degrees. maybe +- 15 degrees. // used by AnchorManager.redraw calculateOrientation = function(sourceId, targetId, sd, td, sourceAnchor, targetAnchor) { if (sourceId === targetId) return { orientation:Orientation.IDENTITY, a:["top", "top"] }; var theta = Math.atan2((td.centery - sd.centery) , (td.centerx - sd.centerx)), theta2 = Math.atan2((sd.centery - td.centery) , (sd.centerx - td.centerx)), h = ((sd.left <= td.left && sd.right >= td.left) || (sd.left <= td.right && sd.right >= td.right) || (sd.left <= td.left && sd.right >= td.right) || (td.left <= sd.left && td.right >= sd.right)), v = ((sd.top <= td.top && sd.bottom >= td.top) || (sd.top <= td.bottom && sd.bottom >= td.bottom) || (sd.top <= td.top && sd.bottom >= td.bottom) || (td.top <= sd.top && td.bottom >= sd.bottom)), possiblyTranslateEdges = function(edges) { // this function checks to see if either anchor is Continuous, and if so, runs the suggested edge // through the anchor: Continuous anchors can say which faces they support, and they get to choose // whether a certain face is honoured, or, if not, which face to replace it with. the behaviour when // choosing an alternate face is to try for the opposite face first, then the next one clockwise, and then // the opposite of that one. return [ sourceAnchor.isContinuous ? sourceAnchor.verifyEdge(edges[0]) : edges[0], targetAnchor.isContinuous ? targetAnchor.verifyEdge(edges[1]) : edges[1] ]; }, out = { orientation:Orientation.DIAGONAL, theta:theta, theta2:theta2 }; if (! (h || v)) { if (td.left > sd.left && td.top > sd.top) out.a = ["right", "top"]; else if (td.left > sd.left && sd.top > td.top) out.a = [ "top", "left"]; else if (td.left < sd.left && td.top < sd.top) out.a = [ "top", "right"]; else if (td.left < sd.left && td.top > sd.top) out.a = ["left", "top" ]; } else if (h) { out.orientation = Orientation.HORIZONTAL; out.a = sd.top < td.top ? ["bottom", "top"] : ["top", "bottom"]; } else { out.orientation = Orientation.VERTICAL; out.a = sd.left < td.left ? ["right", "left"] : ["left", "right"]; } out.a = possiblyTranslateEdges(out.a); return out; }, // used by placeAnchors function placeAnchorsOnLine = function(desc, elementDimensions, elementPosition, connections, horizontal, otherMultiplier, reverse) { var a = [], step = elementDimensions[horizontal ? 0 : 1] / (connections.length + 1); for (var i = 0; i < connections.length; i++) { var val = (i + 1) * step, other = otherMultiplier * elementDimensions[horizontal ? 1 : 0]; if (reverse) val = elementDimensions[horizontal ? 0 : 1] - val; var dx = (horizontal ? val : other), x = elementPosition[0] + dx, xp = dx / elementDimensions[0], dy = (horizontal ? other : val), y = elementPosition[1] + dy, yp = dy / elementDimensions[1]; a.push([ x, y, xp, yp, connections[i][1], connections[i][2] ]); } return a; }, // used by edgeSortFunctions currySort = function(reverseAngles) { return function(a,b) { var r = true; if (reverseAngles) { if (a[0][0] < b[0][0]) r = true; else r = a[0][1] > b[0][1]; } else { if (a[0][0] > b[0][0]) r= true; else r =a[0][1] > b[0][1]; } return r === false ? -1 : 1; }; }, // used by edgeSortFunctions leftSort = function(a,b) { // first get adjusted values var p1 = a[0][0] < 0 ? -Math.PI - a[0][0] : Math.PI - a[0][0], p2 = b[0][0] < 0 ? -Math.PI - b[0][0] : Math.PI - b[0][0]; if (p1 > p2) return 1; else return a[0][1] > b[0][1] ? 1 : -1; }, // used by placeAnchors edgeSortFunctions = { "top":function(a, b) { return a[0] > b[0] ? 1 : -1 }, "right":currySort(true), "bottom":currySort(true), "left":leftSort }, // used by placeAnchors _sortHelper = function(_array, _fn) { return _array.sort(_fn); }, // used by AnchorManager.redraw placeAnchors = function(elementId, _anchorLists) { var cd = jsPlumbInstance.getCachedData(elementId), sS = cd.s, sO = cd.o, placeSomeAnchors = function(desc, elementDimensions, elementPosition, unsortedConnections, isHorizontal, otherMultiplier, orientation) { if (unsortedConnections.length > 0) { var sc = _sortHelper(unsortedConnections, edgeSortFunctions[desc]), // puts them in order based on the target element's pos on screen reverse = desc === "right" || desc === "top", anchors = placeAnchorsOnLine(desc, elementDimensions, elementPosition, sc, isHorizontal, otherMultiplier, reverse ); // takes a computed anchor position and adjusts it for parent offset and scroll, then stores it. var _setAnchorLocation = function(endpoint, anchorPos) { var a = jsPlumbInstance.adjustForParentOffsetAndScroll([anchorPos[0], anchorPos[1]], endpoint.canvas); continuousAnchorLocations[endpoint.id] = [ a[0], a[1], anchorPos[2], anchorPos[3] ]; continuousAnchorOrientations[endpoint.id] = orientation; }; for (var i = 0; i < anchors.length; i++) { var c = anchors[i][4], weAreSource = c.endpoints[0].elementId === elementId, weAreTarget = c.endpoints[1].elementId === elementId; if (weAreSource) _setAnchorLocation(c.endpoints[0], anchors[i]); else if (weAreTarget) _setAnchorLocation(c.endpoints[1], anchors[i]); } } }; placeSomeAnchors("bottom", sS, [sO.left,sO.top], _anchorLists.bottom, true, 1, [0,1]); placeSomeAnchors("top", sS, [sO.left,sO.top], _anchorLists.top, true, 0, [0,-1]); placeSomeAnchors("left", sS, [sO.left,sO.top], _anchorLists.left, false, 0, [-1,0]); placeSomeAnchors("right", sS, [sO.left,sO.top], _anchorLists.right, false, 1, [1,0]); }; this.reset = function() { _amEndpoints = {}; connectionsByElementId = {}; anchorLists = {}; }; this.addFloatingConnection = function(key, conn) { floatingConnections[key] = conn; }; this.removeFloatingConnection = function(key) { delete floatingConnections[key]; }; this.newConnection = function(conn) { var sourceId = conn.sourceId, targetId = conn.targetId, ep = conn.endpoints, doRegisterTarget = true, registerConnection = function(otherIndex, otherEndpoint, otherAnchor, elId, c) { if ((sourceId == targetId) && otherAnchor.isContinuous){ // remove the target endpoint's canvas. we dont need it. jpcl.removeElement(ep[1].canvas); doRegisterTarget = false; } jsPlumbUtil.addToList(connectionsByElementId, elId, [c, otherEndpoint, otherAnchor.constructor == jsPlumb.DynamicAnchor]); }; registerConnection(0, ep[0], ep[0].anchor, targetId, conn); if (doRegisterTarget) registerConnection(1, ep[1], ep[1].anchor, sourceId, conn); }; var removeEndpointFromAnchorLists = function(endpoint) { (function(list, eId) { if (list) { // transient anchors dont get entries in this list. var f = function(e) { return e[4] == eId; }; jsPlumbUtil.removeWithFunction(list["top"], f); jsPlumbUtil.removeWithFunction(list["left"], f); jsPlumbUtil.removeWithFunction(list["bottom"], f); jsPlumbUtil.removeWithFunction(list["right"], f); } })(anchorLists[endpoint.elementId], endpoint.id); }; this.connectionDetached = function(connInfo) { var connection = connInfo.connection || connInfo, sourceId = connInfo.sourceId, targetId = connInfo.targetId, ep = connection.endpoints, removeConnection = function(otherIndex, otherEndpoint, otherAnchor, elId, c) { if (otherAnchor.constructor == jsPlumb.FloatingAnchor) { // no-op } else { jsPlumbUtil.removeWithFunction(connectionsByElementId[elId], function(_c) { return _c[0].id == c.id; }); } }; removeConnection(1, ep[1], ep[1].anchor, sourceId, connection); removeConnection(0, ep[0], ep[0].anchor, targetId, connection); // remove from anchorLists removeEndpointFromAnchorLists(connection.endpoints[0]); removeEndpointFromAnchorLists(connection.endpoints[1]); self.redraw(connection.sourceId); self.redraw(connection.targetId); }; this.add = function(endpoint, elementId) { jsPlumbUtil.addToList(_amEndpoints, elementId, endpoint); }; this.changeId = function(oldId, newId) { connectionsByElementId[newId] = connectionsByElementId[oldId]; _amEndpoints[newId] = _amEndpoints[oldId]; delete connectionsByElementId[oldId]; delete _amEndpoints[oldId]; }; this.getConnectionsFor = function(elementId) { return connectionsByElementId[elementId] || []; }; this.getEndpointsFor = function(elementId) { return _amEndpoints[elementId] || []; }; this.deleteEndpoint = function(endpoint) { jsPlumbUtil.removeWithFunction(_amEndpoints[endpoint.elementId], function(e) { return e.id == endpoint.id; }); removeEndpointFromAnchorLists(endpoint); }; this.clearFor = function(elementId) { delete _amEndpoints[elementId]; _amEndpoints[elementId] = []; }; // updates the given anchor list by either updating an existing anchor's info, or adding it. this function // also removes the anchor from its previous list, if the edge it is on has changed. // all connections found along the way (those that are connected to one of the faces this function // operates on) are added to the connsToPaint list, as are their endpoints. in this way we know to repaint // them wthout having to calculate anything else about them. var _updateAnchorList = function(lists, theta, order, conn, aBoolean, otherElId, idx, reverse, edgeId, elId, connsToPaint, endpointsToPaint) { // first try to find the exact match, but keep track of the first index of a matching element id along the way.s var exactIdx = -1, firstMatchingElIdx = -1, endpoint = conn.endpoints[idx], endpointId = endpoint.id, oIdx = [1,0][idx], values = [ [ theta, order ], conn, aBoolean, otherElId, endpointId ], listToAddTo = lists[edgeId], listToRemoveFrom = endpoint._continuousAnchorEdge ? lists[endpoint._continuousAnchorEdge] : null; if (listToRemoveFrom) { var rIdx = jsPlumbUtil.findWithFunction(listToRemoveFrom, function(e) { return e[4] == endpointId }); if (rIdx != -1) { listToRemoveFrom.splice(rIdx, 1); // get all connections from this list for (var i = 0; i < listToRemoveFrom.length; i++) { jsPlumbUtil.addWithFunction(connsToPaint, listToRemoveFrom[i][1], function(c) { return c.id == listToRemoveFrom[i][1].id }); jsPlumbUtil.addWithFunction(endpointsToPaint, listToRemoveFrom[i][1].endpoints[idx], function(e) { return e.id == listToRemoveFrom[i][1].endpoints[idx].id }); } } } for (var i = 0; i < listToAddTo.length; i++) { if (params.idx == 1 && listToAddTo[i][3] === otherElId && firstMatchingElIdx == -1) firstMatchingElIdx = i; jsPlumbUtil.addWithFunction(connsToPaint, listToAddTo[i][1], function(c) { return c.id == listToAddTo[i][1].id }); jsPlumbUtil.addWithFunction(endpointsToPaint, listToAddTo[i][1].endpoints[idx], function(e) { return e.id == listToAddTo[i][1].endpoints[idx].id }); } if (exactIdx != -1) { listToAddTo[exactIdx] = values; } else { var insertIdx = reverse ? firstMatchingElIdx != -1 ? firstMatchingElIdx : 0 : listToAddTo.length; // of course we will get this from having looked through the array shortly. listToAddTo.splice(insertIdx, 0, values); } // store this for next time. endpoint._continuousAnchorEdge = edgeId; }; this.redraw = function(elementId, ui, timestamp, offsetToUI, clearEdits) { if (!jsPlumbInstance.isSuspendDrawing()) { // get all the endpoints for this element var ep = _amEndpoints[elementId] || [], endpointConnections = connectionsByElementId[elementId] || [], connectionsToPaint = [], endpointsToPaint = [], anchorsToUpdate = []; timestamp = timestamp || jsPlumbInstance.timestamp(); // offsetToUI are values that would have been calculated in the dragManager when registering // an endpoint for an element that had a parent (somewhere in the hierarchy) that had been // registered as draggable. offsetToUI = offsetToUI || {left:0, top:0}; if (ui) { ui = { left:ui.left + offsetToUI.left, top:ui.top + offsetToUI.top } } // valid for one paint cycle. var myOffset = jsPlumbInstance.updateOffset( { elId : elementId, offset : ui, recalc : false, timestamp : timestamp }), orientationCache = {}; // actually, first we should compute the orientation of this element to all other elements to which // this element is connected with a continuous anchor (whether both ends of the connection have // a continuous anchor or just one) for (var i = 0; i < endpointConnections.length; i++) { var conn = endpointConnections[i][0], sourceId = conn.sourceId, targetId = conn.targetId, sourceContinuous = conn.endpoints[0].anchor.isContinuous, targetContinuous = conn.endpoints[1].anchor.isContinuous; if (sourceContinuous || targetContinuous) { var oKey = sourceId + "_" + targetId, oKey2 = targetId + "_" + sourceId, o = orientationCache[oKey], oIdx = conn.sourceId == elementId ? 1 : 0; if (sourceContinuous && !anchorLists[sourceId]) anchorLists[sourceId] = { top:[], right:[], bottom:[], left:[] }; if (targetContinuous && !anchorLists[targetId]) anchorLists[targetId] = { top:[], right:[], bottom:[], left:[] }; if (elementId != targetId) jsPlumbInstance.updateOffset( { elId : targetId, timestamp : timestamp }); if (elementId != sourceId) jsPlumbInstance.updateOffset( { elId : sourceId, timestamp : timestamp }); var td = jsPlumbInstance.getCachedData(targetId), sd = jsPlumbInstance.getCachedData(sourceId); if (targetId == sourceId && (sourceContinuous || targetContinuous)) { // here we may want to improve this by somehow determining the face we'd like // to put the connector on. ideally, when drawing, the face should be calculated // by determining which face is closest to the point at which the mouse button // was released. for now, we're putting it on the top face. _updateAnchorList( anchorLists[sourceId], -Math.PI / 2, 0, conn, false, targetId, 0, false, "top", sourceId, connectionsToPaint, endpointsToPaint); } else { if (!o) { o = calculateOrientation(sourceId, targetId, sd.o, td.o, conn.endpoints[0].anchor, conn.endpoints[1].anchor); orientationCache[oKey] = o; // this would be a performance enhancement, but the computed angles need to be clamped to //the (-PI/2 -> PI/2) range in order for the sorting to work properly. /* orientationCache[oKey2] = { orientation:o.orientation, a:[o.a[1], o.a[0]], theta:o.theta + Math.PI, theta2:o.theta2 + Math.PI };*/ } if (sourceContinuous) _updateAnchorList(anchorLists[sourceId], o.theta, 0, conn, false, targetId, 0, false, o.a[0], sourceId, connectionsToPaint, endpointsToPaint); if (targetContinuous) _updateAnchorList(anchorLists[targetId], o.theta2, -1, conn, true, sourceId, 1, true, o.a[1], targetId, connectionsToPaint, endpointsToPaint); } if (sourceContinuous) jsPlumbUtil.addWithFunction(anchorsToUpdate, sourceId, function(a) { return a === sourceId; }); if (targetContinuous) jsPlumbUtil.addWithFunction(anchorsToUpdate, targetId, function(a) { return a === targetId; }); jsPlumbUtil.addWithFunction(connectionsToPaint, conn, function(c) { return c.id == conn.id; }); if ((sourceContinuous && oIdx == 0) || (targetContinuous && oIdx == 1)) jsPlumbUtil.addWithFunction(endpointsToPaint, conn.endpoints[oIdx], function(e) { return e.id == conn.endpoints[oIdx].id; }); } } // place Endpoints whose anchors are continuous but have no Connections for (var i = 0; i < ep.length; i++) { if (ep[i].connections.length == 0 && ep[i].anchor.isContinuous) { if (!anchorLists[elementId]) anchorLists[elementId] = { top:[], right:[], bottom:[], left:[] }; _updateAnchorList(anchorLists[elementId], -Math.PI / 2, 0, {endpoints:[ep[i], ep[i]], paint:function(){}}, false, elementId, 0, false, "top", elementId, connectionsToPaint, endpointsToPaint) jsPlumbUtil.addWithFunction(anchorsToUpdate, elementId, function(a) { return a === elementId; }) } } // now place all the continuous anchors we need to; for (var i = 0; i < anchorsToUpdate.length; i++) { placeAnchors(anchorsToUpdate[i], anchorLists[anchorsToUpdate[i]]); } // now that continuous anchors have been placed, paint all the endpoints for this element // TODO performance: add the endpoint ids to a temp array, and then when iterating in the next // loop, check that we didn't just paint that endpoint. we can probably shave off a few more milliseconds this way. for (var i = 0; i < ep.length; i++) { ep[i].paint( { timestamp : timestamp, offset : myOffset, dimensions : myOffset.s }); } // ... and any other endpoints we came across as a result of the continuous anchors. for (var i = 0; i < endpointsToPaint.length; i++) { var cd = jsPlumbInstance.getCachedData(endpointsToPaint[i].elementId); endpointsToPaint[i].paint( { timestamp : timestamp, offset : cd, dimensions : cd.s }); } // paint all the standard and "dynamic connections", which are connections whose other anchor is // static and therefore does need to be recomputed; we make sure that happens only one time. // TODO we could have compiled a list of these in the first pass through connections; might save some time. for (var i = 0; i < endpointConnections.length; i++) { var otherEndpoint = endpointConnections[i][1]; if (otherEndpoint.anchor.constructor == jsPlumb.DynamicAnchor) { otherEndpoint.paint({ elementWithPrecedence:elementId }); jsPlumbUtil.addWithFunction(connectionsToPaint, endpointConnections[i][0], function(c) { return c.id == endpointConnections[i][0].id; }); // all the connections for the other endpoint now need to be repainted for (var k = 0; k < otherEndpoint.connections.length; k++) { if (otherEndpoint.connections[k] !== endpointConnections[i][0]) jsPlumbUtil.addWithFunction(connectionsToPaint, otherEndpoint.connections[k], function(c) { return c.id == otherEndpoint.connections[k].id; }); } } else if (otherEndpoint.anchor.constructor == jsPlumb.Anchor) { jsPlumbUtil.addWithFunction(connectionsToPaint, endpointConnections[i][0], function(c) { return c.id == endpointConnections[i][0].id; }); } } // paint current floating connection for this element, if there is one. var fc = floatingConnections[elementId]; if (fc) fc.paint({timestamp:timestamp, recalc:false, elId:elementId}); // paint all the connections for (var i = 0; i < connectionsToPaint.length; i++) { connectionsToPaint[i].paint({elId:elementId, timestamp:timestamp, recalc:false, clearEdits:clearEdits}); } } }; this.rehomeEndpoint = function(currentId, element) { var eps = _amEndpoints[currentId] || [], elementId = jsPlumbInstance.getId(element); if (elementId !== currentId) { for (var i = 0; i < eps.length; i++) { self.add(eps[i], elementId); } eps.splice(0, eps.length); } }; var ContinuousAnchor = function(anchorParams) { jsPlumbUtil.EventGenerator.apply(this); this.type = "Continuous"; this.isDynamic = true; this.isContinuous = true; var faces = anchorParams.faces || ["top", "right", "bottom", "left"], clockwise = !(anchorParams.clockwise === false), availableFaces = { }, opposites = { "top":"bottom", "right":"left","left":"right","bottom":"top" }, clockwiseOptions = { "top":"right", "right":"bottom","left":"top","bottom":"left" }, antiClockwiseOptions = { "top":"left", "right":"top","left":"bottom","bottom":"right" }, secondBest = clockwise ? clockwiseOptions : antiClockwiseOptions, lastChoice = clockwise ? antiClockwiseOptions : clockwiseOptions, cssClass = anchorParams.cssClass || ""; for (var i = 0; i < faces.length; i++) { availableFaces[faces[i]] = true; } // if the given edge is suported, returns it. otherwise looks for a substitute that _is_ // supported. if none supported we also return the request edge. this.verifyEdge = function(edge) { if (availableFaces[edge]) return edge; else if (availableFaces[opposites[edge]]) return opposites[edge]; else if (availableFaces[secondBest[edge]]) return secondBest[edge]; else if (availableFaces[lastChoice[edge]]) return lastChoice[edge]; return edge; // we have to give them something. }; this.compute = function(params) { return userDefinedContinuousAnchorLocations[params.element.id] || continuousAnchorLocations[params.element.id] || [0,0]; }; this.getCurrentLocation = function(endpoint) { return userDefinedContinuousAnchorLocations[endpoint.id] || continuousAnchorLocations[endpoint.id] || [0,0]; }; this.getOrientation = function(endpoint) { return continuousAnchorOrientations[endpoint.id] || [0,0]; }; this.clearUserDefinedLocation = function() { delete userDefinedContinuousAnchorLocations[anchorParams.elementId]; }; this.setUserDefinedLocation = function(loc) { userDefinedContinuousAnchorLocations[anchorParams.elementId] = loc; }; this.getCssClass = function() { return cssClass; }; this.setCssClass = function(c) { cssClass = c; }; }; // continuous anchors jsPlumbInstance.continuousAnchorFactory = { get:function(params) { var existing = continuousAnchors[params.elementId]; if (!existing) { existing = new ContinuousAnchor(params); continuousAnchors[params.elementId] = existing; } return existing; } }; }; /** * Anchors model a position on some element at which an Endpoint may be located. They began as a first class citizen of jsPlumb, ie. a user * was required to create these themselves, but over time this has been replaced by the concept of referring to them either by name (eg. "TopMiddle"), * or by an array describing their coordinates (eg. [ 0, 0.5, 0, -1 ], which is the same as "TopMiddle"). jsPlumb now handles all of the * creation of Anchors without user intervention. */ jsPlumb.Anchor = function(params) { var self = this; this.x = params.x || 0; this.y = params.y || 0; this.elementId = params.elementId; jsPlumbUtil.EventGenerator.apply(this); var orientation = params.orientation || [ 0, 0 ], jsPlumbInstance = params.jsPlumbInstance, lastTimestamp = null, lastReturnValue = null, userDefinedLocation = null, cssClass = params.cssClass || ""; this.getCssClass = function() { return cssClass; }; this.offsets = params.offsets || [ 0, 0 ]; self.timestamp = null; this.compute = function(params) { var xy = params.xy, wh = params.wh, element = params.element, timestamp = params.timestamp; if(params.clearUserDefinedLocation) userDefinedLocation = null; if (timestamp && timestamp === self.timestamp) return lastReturnValue; if (userDefinedLocation != null) { lastReturnValue = userDefinedLocation; } else { lastReturnValue = [ xy[0] + (self.x * wh[0]) + self.offsets[0], xy[1] + (self.y * wh[1]) + self.offsets[1] ]; // adjust loc if there is an offsetParent lastReturnValue = jsPlumbInstance.adjustForParentOffsetAndScroll(lastReturnValue, element.canvas); } self.timestamp = timestamp; return lastReturnValue; }; this.getOrientation = function(_endpoint) { return orientation; }; this.equals = function(anchor) { if (!anchor) return false; var ao = anchor.getOrientation(); var o = this.getOrientation(); return this.x == anchor.x && this.y == anchor.y && this.offsets[0] == anchor.offsets[0] && this.offsets[1] == anchor.offsets[1] && o[0] == ao[0] && o[1] == ao[1]; }; this.getCurrentLocation = function() { return lastReturnValue; }; this.getUserDefinedLocation = function() { return userDefinedLocation; }; this.setUserDefinedLocation = function(l) { userDefinedLocation = l; }; this.clearUserDefinedLocation = function() { userDefinedLocation = null; }; }; /** * An Anchor that floats. its orientation is computed dynamically from * its position relative to the anchor it is floating relative to. It is used when creating * a connection through drag and drop. * * TODO FloatingAnchor could totally be refactored to extend Anchor just slightly. */ jsPlumb.FloatingAnchor = function(params) { jsPlumb.Anchor.apply(this, arguments); // this is the anchor that this floating anchor is referenced to for // purposes of calculating the orientation. var ref = params.reference, jpcl = jsPlumb.CurrentLibrary, jsPlumbInstance = params.jsPlumbInstance, // the canvas this refers to. refCanvas = params.referenceCanvas, size = jpcl.getSize(jpcl.getElementObject(refCanvas)), // these are used to store the current relative position of our // anchor wrt the reference anchor. they only indicate // direction, so have a value of 1 or -1 (or, very rarely, 0). these // values are written by the compute method, and read // by the getOrientation method. xDir = 0, yDir = 0, // temporary member used to store an orientation when the floating // anchor is hovering over another anchor. orientation = null, _lastResult = null; // set these to 0 each; they are used by certain types of connectors in the loopback case, // when the connector is trying to clear the element it is on. but for floating anchor it's not // very important. this.x = 0; this.y = 0; this.isFloating = true; this.compute = function(params) { var xy = params.xy, element = params.element, result = [ xy[0] + (size[0] / 2), xy[1] + (size[1] / 2) ]; // return origin of the element. we may wish to improve this so that any object can be the drag proxy. // adjust loc if there is an offsetParent result = jsPlumbInstance.adjustForParentOffsetAndScroll(result, element.canvas); _lastResult = result; return result; }; this.getOrientation = function(_endpoint) { if (orientation) return orientation; else { var o = ref.getOrientation(_endpoint); // here we take into account the orientation of the other // anchor: if it declares zero for some direction, we declare zero too. this might not be the most awesome. perhaps we can come // up with a better way. it's just so that the line we draw looks like it makes sense. maybe this wont make sense. return [ Math.abs(o[0]) * xDir * -1, Math.abs(o[1]) * yDir * -1 ]; } }; /** * notification the endpoint associated with this anchor is hovering * over another anchor; we want to assume that anchor's orientation * for the duration of the hover. */ this.over = function(anchor) { orientation = anchor.getOrientation(); }; /** * notification the endpoint associated with this anchor is no * longer hovering over another anchor; we should resume calculating * orientation as we normally do. */ this.out = function() { orientation = null; }; this.getCurrentLocation = function() { return _lastResult; }; }; /* * A DynamicAnchor is an Anchor that contains a list of other Anchors, which it cycles * through at compute time to find the one that is located closest to * the center of the target element, and returns that Anchor's compute * method result. this causes endpoints to follow each other with * respect to the orientation of their target elements, which is a useful * feature for some applications. * */ jsPlumb.DynamicAnchor = function(params) { jsPlumb.Anchor.apply(this, arguments); this.isSelective = true; this.isDynamic = true; var _anchors = [], self = this, _convert = function(anchor) { return anchor.constructor == jsPlumb.Anchor ? anchor: params.jsPlumbInstance.makeAnchor(anchor, params.elementId, params.jsPlumbInstance); }; for (var i = 0; i < params.anchors.length; i++) _anchors[i] = _convert(params.anchors[i]); this.addAnchor = function(anchor) { _anchors.push(_convert(anchor)); }; this.getAnchors = function() { return _anchors; }; this.locked = false; var _curAnchor = _anchors.length > 0 ? _anchors[0] : null, _curIndex = _anchors.length > 0 ? 0 : -1, _lastAnchor = _curAnchor, self = this, // helper method to calculate the distance between the centers of the two elements. _distance = function(anchor, cx, cy, xy, wh) { var ax = xy[0] + (anchor.x * wh[0]), ay = xy[1] + (anchor.y * wh[1]), acx = xy[0] + (wh[0] / 2), acy = xy[1] + (wh[1] / 2); return (Math.sqrt(Math.pow(cx - ax, 2) + Math.pow(cy - ay, 2)) + Math.sqrt(Math.pow(acx - ax, 2) + Math.pow(acy - ay, 2))); }, // default method uses distance between element centers. you can provide your own method in the dynamic anchor // constructor (and also to jsPlumb.makeDynamicAnchor). the arguments to it are four arrays: // xy - xy loc of the anchor's element // wh - anchor's element's dimensions // txy - xy loc of the element of the other anchor in the connection // twh - dimensions of the element of the other anchor in the connection. // anchors - the list of selectable anchors _anchorSelector = params.selector || function(xy, wh, txy, twh, anchors) { var cx = txy[0] + (twh[0] / 2), cy = txy[1] + (twh[1] / 2); var minIdx = -1, minDist = Infinity; for ( var i = 0; i < anchors.length; i++) { var d = _distance(anchors[i], cx, cy, xy, wh); if (d < minDist) { minIdx = i + 0; minDist = d; } } return anchors[minIdx]; }; this.compute = function(params) { var xy = params.xy, wh = params.wh, timestamp = params.timestamp, txy = params.txy, twh = params.twh; if(params.clearUserDefinedLocation) userDefinedLocation = null; var udl = self.getUserDefinedLocation(); if (udl != null) { return udl; } // if anchor is locked or an opposite element was not given, we // maintain our state. anchor will be locked // if it is the source of a drag and drop. if (self.locked || txy == null || twh == null) return _curAnchor.compute(params); else params.timestamp = null; // otherwise clear this, i think. we want the anchor to compute. _curAnchor = _anchorSelector(xy, wh, txy, twh, _anchors); self.x = _curAnchor.x; self.y = _curAnchor.y; if (_curAnchor != _lastAnchor) self.fire("anchorChanged", _curAnchor); _lastAnchor = _curAnchor; return _curAnchor.compute(params); }; this.getCurrentLocation = function() { return self.getUserDefinedLocation() || (_curAnchor != null ? _curAnchor.getCurrentLocation() : null); }; this.getOrientation = function(_endpoint) { return _curAnchor != null ? _curAnchor.getOrientation(_endpoint) : [ 0, 0 ]; }; this.over = function(anchor) { if (_curAnchor != null) _curAnchor.over(anchor); }; this.out = function() { if (_curAnchor != null) _curAnchor.out(); }; this.getCssClass = function() { return (_curAnchor && _curAnchor.getCssClass()) || ""; }; }; // -------- basic anchors ------------------ var _curryAnchor = function(x, y, ox, oy, type, fnInit) { jsPlumb.Anchors[type] = function(params) { var a = params.jsPlumbInstance.makeAnchor([ x, y, ox, oy, 0, 0 ], params.elementId, params.jsPlumbInstance); a.type = type; if (fnInit) fnInit(a, params); return a; }; }; _curryAnchor(0.5, 0, 0,-1, "TopCenter"); _curryAnchor(0.5, 1, 0, 1, "BottomCenter"); _curryAnchor(0, 0.5, -1, 0, "LeftMiddle"); _curryAnchor(1, 0.5, 1, 0, "RightMiddle"); // from 1.4.0: Top, Right, Bottom, Left _curryAnchor(0.5, 0, 0,-1, "Top"); _curryAnchor(0.5, 1, 0, 1, "Bottom"); _curryAnchor(0, 0.5, -1, 0, "Left"); _curryAnchor(1, 0.5, 1, 0, "Right"); _curryAnchor(0.5, 0.5, 0, 0, "Center"); _curryAnchor(1, 0, 0,-1, "TopRight"); _curryAnchor(1, 1, 0, 1, "BottomRight"); _curryAnchor(0, 0, 0, -1, "TopLeft"); _curryAnchor(0, 1, 0, 1, "BottomLeft"); // ------- dynamic anchors ------------------- // default dynamic anchors chooses from Top, Right, Bottom, Left jsPlumb.Defaults.DynamicAnchors = function(params) { return params.jsPlumbInstance.makeAnchors(["TopCenter", "RightMiddle", "BottomCenter", "LeftMiddle"], params.elementId, params.jsPlumbInstance); }; // default dynamic anchors bound to name 'AutoDefault' jsPlumb.Anchors["AutoDefault"] = function(params) { var a = params.jsPlumbInstance.makeDynamicAnchor(jsPlumb.Defaults.DynamicAnchors(params)); a.type = "AutoDefault"; return a; }; // ------- continuous anchors ------------------- var _curryContinuousAnchor = function(type, faces) { jsPlumb.Anchors[type] = function(params) { var a = params.jsPlumbInstance.makeAnchor(["Continuous", { faces:faces }], params.elementId, params.jsPlumbInstance); a.type = type; return a; }; }; jsPlumb.Anchors["Continuous"] = function(params) { return params.jsPlumbInstance.continuousAnchorFactory.get(params); }; _curryContinuousAnchor("ContinuousLeft", ["left"]); _curryContinuousAnchor("ContinuousTop", ["top"]); _curryContinuousAnchor("ContinuousBottom", ["bottom"]); _curryContinuousAnchor("ContinuousRight", ["right"]); // ------- position assign anchors ------------------- // this anchor type lets you assign the position at connection time. jsPlumb.Anchors["Assign"] = _curryAnchor(0, 0, 0, 0, "Assign", function(anchor, params) { // find what to use as the "position finder". the user may have supplied a String which represents // the id of a position finder in jsPlumb.AnchorPositionFinders, or the user may have supplied the // position finder as a function. we find out what to use and then set it on the anchor. var pf = params.position || "Fixed"; anchor.positionFinder = pf.constructor == String ? params.jsPlumbInstance.AnchorPositionFinders[pf] : pf; // always set the constructor params; the position finder might need them later (the Grid one does, // for example) anchor.constructorParams = params; }); // these are the default anchor positions finders, which are used by the makeTarget function. supplying // a position finder argument to that function allows you to specify where the resulting anchor will // be located jsPlumb.AnchorPositionFinders = { "Fixed": function(dp, ep, es, params) { return [ (dp.left - ep.left) / es[0], (dp.top - ep.top) / es[1] ]; }, "Grid":function(dp, ep, es, params) { var dx = dp.left - ep.left, dy = dp.top - ep.top, gx = es[0] / (params.grid[0]), gy = es[1] / (params.grid[1]), mx = Math.floor(dx / gx), my = Math.floor(dy / gy); return [ ((mx * gx) + (gx / 2)) / es[0], ((my * gy) + (gy / 2)) / es[1] ]; } }; // ------- perimeter anchors ------------------- jsPlumb.Anchors["Perimeter"] = function(params) { params = params || {}; var anchorCount = params.anchorCount || 60, shape = params.shape; if (!shape) throw new Error("no shape supplied to Perimeter Anchor type"); var _circle = function() { var r = 0.5, step = Math.PI * 2 / anchorCount, current = 0, a = []; for (var i = 0; i < anchorCount; i++) { var x = r + (r * Math.sin(current)), y = r + (r * Math.cos(current)); a.push( [ x, y, 0, 0 ] ); current += step; } return a; }, _path = function(segments) { var anchorsPerFace = anchorCount / segments.length, a = [], _computeFace = function(x1, y1, x2, y2, fractionalLength) { anchorsPerFace = anchorCount * fractionalLength; var dx = (x2 - x1) / anchorsPerFace, dy = (y2 - y1) / anchorsPerFace; for (var i = 0; i < anchorsPerFace; i++) { a.push( [ x1 + (dx * i), y1 + (dy * i), 0, 0 ]); } }; for (var i = 0; i < segments.length; i++) _computeFace.apply(null, segments[i]); return a; }, _shape = function(faces) { var s = []; for (var i = 0; i < faces.length; i++) { s.push([faces[i][0], faces[i][1], faces[i][2], faces[i][3], 1 / faces.length]); } return _path(s); }, _rectangle = function() { return _shape([ [ 0, 0, 1, 0 ], [ 1, 0, 1, 1 ], [ 1, 1, 0, 1 ], [ 0, 1, 0, 0 ] ]); }; var _shapes = { "Circle":_circle, "Ellipse":_circle, "Diamond":function() { return _shape([ [ 0.5, 0, 1, 0.5 ], [ 1, 0.5, 0.5, 1 ], [ 0.5, 1, 0, 0.5 ], [ 0, 0.5, 0.5, 0 ] ]); }, "Rectangle":_rectangle, "Square":_rectangle, "Triangle":function() { return _shape([ [ 0.5, 0, 1, 1 ], [ 1, 1, 0, 1 ], [ 0, 1, 0.5, 0] ]); }, "Path":function(params) { var points = params.points, p = [], tl = 0; for (var i = 0; i < points.length - 1; i++) { var l = Math.sqrt(Math.pow(points[i][2] - points[i][0]) + Math.pow(points[i][3] - points[i][1])); tl += l; p.push([points[i][0], points[i][1], points[i+1][0], points[i+1][1], l]); } for (var i = 0; i < p.length; i++) { p[i][4] = p[i][4] / tl; } return _path(p); } }, _rotate = function(points, amountInDegrees) { var o = [], theta = amountInDegrees / 180 * Math.PI ; for (var i = 0; i < points.length; i++) { var _x = points[i][0] - 0.5, _y = points[i][1] - 0.5; o.push([ 0.5 + ((_x * Math.cos(theta)) - (_y * Math.sin(theta))), 0.5 + ((_x * Math.sin(theta)) + (_y * Math.cos(theta))), points[i][2], points[i][3] ]); } return o; }; if (!_shapes[shape]) throw new Error("Shape [" + shape + "] is unknown by Perimeter Anchor type"); var da = _shapes[shape](params); if (params.rotation) da = _rotate(da, params.rotation); var a = params.jsPlumbInstance.makeDynamicAnchor(da); a.type = "Perimeter"; return a; }; })();;(function() { // create the drag handler for a connection var _makeConnectionDragHandler = function(placeholder, _jsPlumb) { var stopped = false; return { drag : function() { if (stopped) { stopped = false; return true; } var _ui = jsPlumb.CurrentLibrary.getUIPosition(arguments, _jsPlumb.getZoom()); if (placeholder.element) { jsPlumb.CurrentLibrary.setOffset(placeholder.element, _ui); _jsPlumb.repaint(placeholder.element, _ui); } }, stopDrag : function() { stopped = true; } }; }; // creates a placeholder div for dragging purposes, adds it to the DOM, and pre-computes its offset. var _makeDraggablePlaceholder = function(placeholder, parent, _jsPlumb) { var n = document.createElement("div"); n.style.position = "absolute"; var placeholderDragElement = jsPlumb.CurrentLibrary.getElementObject(n); jsPlumb.CurrentLibrary.appendElement(n, parent); var id = _jsPlumb.getId(placeholderDragElement); _jsPlumb.updateOffset( { elId : id }); // create and assign an id, and initialize the offset. placeholder.id = id; placeholder.element = placeholderDragElement; }; // create a floating endpoint (for drag connections) var _makeFloatingEndpoint = function(paintStyle, referenceAnchor, endpoint, referenceCanvas, sourceElement, _jsPlumb, _newEndpoint) { var floatingAnchor = new jsPlumb.FloatingAnchor( { reference : referenceAnchor, referenceCanvas : referenceCanvas, jsPlumbInstance:_jsPlumb }); //setting the scope here should not be the way to fix that mootools issue. it should be fixed by not // adding the floating endpoint as a droppable. that makes more sense anyway! return _newEndpoint({ paintStyle : paintStyle, endpoint : endpoint, anchor : floatingAnchor, source : sourceElement, scope:"__floating" }); }; var typeParameters = [ "connectorStyle", "connectorHoverStyle", "connectorOverlays", "connector", "connectionType", "connectorClass", "connectorHoverClass" ]; jsPlumb.Endpoint = function(params) { var self = this, _jsPlumb = params["_jsPlumb"], jpcl = jsPlumb.CurrentLibrary, _att = jpcl.getAttribute, _gel = jpcl.getElementObject, _ju = jsPlumbUtil, _getOffset = jpcl.getOffset, _newConnection = params.newConnection, _newEndpoint = params.newEndpoint, _finaliseConnection = params.finaliseConnection, _fireDetachEvent = params.fireDetachEvent, floatingConnections = params.floatingConnections; self.idPrefix = "_jsplumb_e_"; self.defaultLabelLocation = [ 0.5, 0.5 ]; self.defaultOverlayKeys = ["Overlays", "EndpointOverlays"]; this.parent = params.parent; overlayCapableJsPlumbUIComponent.apply(this, arguments); params = params || {}; // TYPE this.getTypeDescriptor = function() { return "endpoint"; }; this.getDefaultType = function() { return { parameters:{}, scope:null, maxConnections:self._jsPlumb.Defaults.MaxConnections, paintStyle:self._jsPlumb.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle, endpoint:self._jsPlumb.Defaults.Endpoint || jsPlumb.Defaults.Endpoint, hoverPaintStyle:self._jsPlumb.Defaults.EndpointHoverStyle || jsPlumb.Defaults.EndpointHoverStyle, overlays:self._jsPlumb.Defaults.EndpointOverlays || jsPlumb.Defaults.EndpointOverlays, connectorStyle:params.connectorStyle, connectorHoverStyle:params.connectorHoverStyle, connectorClass:params.connectorClass, connectorHoverClass:params.connectorHoverClass, connectorOverlays:params.connectorOverlays, connector:params.connector, connectorTooltip:params.connectorTooltip }; }; var superAt = this.applyType; this.applyType = function(t, doNotRepaint) { superAt(t, doNotRepaint); if (t.maxConnections != null) _maxConnections = t.maxConnections; if (t.scope) self.scope = t.scope; _ju.copyValues(typeParameters, t, self); }; // END TYPE var visible = true, __enabled = !(params.enabled === false); this.isVisible = function() { return visible; }; this.setVisible = function(v, doNotChangeConnections, doNotNotifyOtherEndpoint) { visible = v; if (self.canvas) self.canvas.style.display = v ? "block" : "none"; self[v ? "showOverlays" : "hideOverlays"](); if (!doNotChangeConnections) { for (var i = 0; i < self.connections.length; i++) { self.connections[i].setVisible(v); if (!doNotNotifyOtherEndpoint) { var oIdx = self === self.connections[i].endpoints[0] ? 1 : 0; // only change the other endpoint if this is its only connection. if (self.connections[i].endpoints[oIdx].connections.length == 1) self.connections[i].endpoints[oIdx].setVisible(v, true, true); } } } }; this.isEnabled = function() { return __enabled; }; this.setEnabled = function(e) { __enabled = e; }; var _element = params.source, _uuid = params.uuid, floatingEndpoint = null, inPlaceCopy = null; if (_uuid) params.endpointsByUUID[_uuid] = self; var _elementId = _att(_element, "id"); this.elementId = _elementId; this.element = _element; self.setElementId = function(_elId) { _elementId = _elId; self.elementId = _elId; self.anchor.elementId = _elId }; self.setReferenceElement = function(_el) { _element = _el; self.element = _el; }; var _connectionCost = params.connectionCost; this.getConnectionCost = function() { return _connectionCost; }; this.setConnectionCost = function(c) { _connectionCost = c; }; var _connectionsDirected = params.connectionsDirected; this.areConnectionsDirected = function() { return _connectionsDirected; }; this.setConnectionsDirected = function(b) { _connectionsDirected = b; }; var _currentAnchorClass = "", _updateAnchorClass = function() { jpcl.removeClass(_element, _jsPlumb.endpointAnchorClassPrefix + "_" + _currentAnchorClass); self.removeClass(_jsPlumb.endpointAnchorClassPrefix + "_" + _currentAnchorClass); _currentAnchorClass = self.anchor.getCssClass(); self.addClass(_jsPlumb.endpointAnchorClassPrefix + "_" + _currentAnchorClass); jpcl.addClass(_element, _jsPlumb.endpointAnchorClassPrefix + "_" + _currentAnchorClass); }; this.setAnchor = function(anchorParams, doNotRepaint) { self.anchor = _jsPlumb.makeAnchor(anchorParams, _elementId, _jsPlumb); _updateAnchorClass(); self.anchor.bind("anchorChanged", function(currentAnchor) { self.fire("anchorChanged", {endpoint:self, anchor:currentAnchor}); _updateAnchorClass(); }); if (!doNotRepaint) _jsPlumb.repaint(_elementId); }; this.cleanup = function() { jpcl.removeClass(_element, _jsPlumb.endpointAnchorClassPrefix + "_" + _currentAnchorClass); }; var anchorParamsToUse = params.anchor ? params.anchor : params.anchors ? params.anchors : (_jsPlumb.Defaults.Anchor || "Top"); self.setAnchor(anchorParamsToUse, true); // ANCHOR MANAGER if (!params._transient) // in place copies, for example, are transient. they will never need to be retrieved during a paint cycle, because they dont move, and then they are deleted. _jsPlumb.anchorManager.add(self, _elementId); var _endpoint = null, originalEndpoint = null; this.setEndpoint = function(ep) { var _e = function(t, p) { var rm = _jsPlumb.getRenderMode(); if (jsPlumb.Endpoints[rm][t]) return new jsPlumb.Endpoints[rm][t](p); if (!_jsPlumb.Defaults.DoNotThrowErrors) throw { msg:"jsPlumb: unknown endpoint type '" + t + "'" }; }; var endpointArgs = { _jsPlumb:self._jsPlumb, cssClass:params.cssClass, parent:params.parent, container:params.container, tooltip:params.tooltip, connectorTooltip:params.connectorTooltip, endpoint:self }; if (_ju.isString(ep)) _endpoint = _e(ep, endpointArgs); else if (_ju.isArray(ep)) { endpointArgs = _ju.merge(ep[1], endpointArgs); _endpoint = _e(ep[0], endpointArgs); } else { _endpoint = ep.clone(); } // assign a clone function using a copy of endpointArgs. this is used when a drag starts: the endpoint that was dragged is cloned, // and the clone is left in its place while the original one goes off on a magical journey. // the copy is to get around a closure problem, in which endpointArgs ends up getting shared by // the whole world. var argsForClone = jsPlumb.extend({}, endpointArgs); _endpoint.clone = function() { var o = new Object(); _endpoint.constructor.apply(o, [argsForClone]); return o; }; self.endpoint = _endpoint; self.type = self.endpoint.type; }; this.setEndpoint(params.endpoint || _jsPlumb.Defaults.Endpoint || jsPlumb.Defaults.Endpoint || "Dot"); originalEndpoint = _endpoint; // override setHover to pass it down to the underlying endpoint var _sh = self.setHover; self.setHover = function() { self.endpoint.setHover.apply(self.endpoint, arguments); _sh.apply(self, arguments); }; // endpoint delegates to first connection for hover, if there is one. var internalHover = function(state) { if (self.connections.length > 0) self.connections[0].setHover(state, false); else self.setHover(state); }; // bind listeners from endpoint to self, with the internal hover function defined above. self.bindListeners(self.endpoint, self, internalHover); this.setPaintStyle(params.paintStyle || params.style || _jsPlumb.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle, true); this.setHoverPaintStyle(params.hoverPaintStyle || _jsPlumb.Defaults.EndpointHoverStyle || jsPlumb.Defaults.EndpointHoverStyle, true); this.paintStyleInUse = this.getPaintStyle(); var originalPaintStyle = this.getPaintStyle(); _ju.copyValues(typeParameters, params, this); this.isSource = params.isSource || false; this.isTarget = params.isTarget || false; var _maxConnections = params.maxConnections || _jsPlumb.Defaults.MaxConnections; // maximum number of connections this endpoint can be the source of. this.getAttachedElements = function() { return self.connections; }; this.canvas = this.endpoint.canvas; // add anchor class (need to do this on construction because we set anchor first) self.addClass(_jsPlumb.endpointAnchorClassPrefix + "_" + _currentAnchorClass); jpcl.addClass(_element, _jsPlumb.endpointAnchorClassPrefix + "_" + _currentAnchorClass); this.connections = params.connections || []; this.connectorPointerEvents = params["connector-pointer-events"]; this.scope = params.scope || _jsPlumb.getDefaultScope(); this.timestamp = null; self.reattachConnections = params.reattach || _jsPlumb.Defaults.ReattachConnections; self.connectionsDetachable = _jsPlumb.Defaults.ConnectionsDetachable; if (params.connectionsDetachable === false || params.detachable === false) self.connectionsDetachable = false; var dragAllowedWhenFull = params.dragAllowedWhenFull || true; if (params.onMaxConnections) self.bind("maxConnections", params.onMaxConnections); this.computeAnchor = function(params) { return self.anchor.compute(params); }; this.addConnection = function(connection) { self.connections.push(connection); self[(self.connections.length > 0 ? "add" : "remove") + "Class"](_jsPlumb.endpointConnectedClass); self[(self.isFull() ? "add" : "remove") + "Class"](_jsPlumb.endpointFullClass); }; this.detach = function(connection, ignoreTarget, forceDetach, fireEvent, originalEvent) { var idx = _ju.findWithFunction(self.connections, function(c) { return c.id == connection.id}), actuallyDetached = false; fireEvent = (fireEvent !== false); if (idx >= 0) { // 1. does the connection have a before detach (note this also checks jsPlumb's bound // detach handlers; but then Endpoint's check will, too, hmm.) if (forceDetach || connection._forceDetach || connection.isDetachable() || connection.isDetachAllowed(connection)) { // get the target endpoint var t = connection.endpoints[0] == self ? connection.endpoints[1] : connection.endpoints[0]; if (forceDetach || connection._forceDetach || (self.isDetachAllowed(connection) /*&& t.isDetachAllowed(connection)*/)) { self.connections.splice(idx, 1); // avoid circular loop if (!ignoreTarget) { t.detach(connection, true, forceDetach); // check connection to see if we want to delete the endpoints associated with it. // we only detach those that have just this connection; this scenario is most // likely if we got to this bit of code because it is set by the methods that // create their own endpoints, like .connect or .makeTarget. the user is // not likely to have interacted with those endpoints. if (connection.endpointsToDeleteOnDetach){ for (var i = 0; i < connection.endpointsToDeleteOnDetach.length; i++) { var cde = connection.endpointsToDeleteOnDetach[i]; if (cde && cde.connections.length == 0) _jsPlumb.deleteEndpoint(cde); } } } if (connection.getConnector() != null) _ju.removeElements(connection.getConnector().getDisplayElements(), connection.parent); _ju.removeWithFunction(params.connectionsByScope[connection.scope], function(c) { return c.id == connection.id; }); self[(self.connections.length > 0 ? "add" : "remove") + "Class"](_jsPlumb.endpointConnectedClass); self[(self.isFull() ? "add" : "remove") + "Class"](_jsPlumb.endpointFullClass); actuallyDetached = true; _fireDetachEvent(connection, (!ignoreTarget && fireEvent), originalEvent); } } } return actuallyDetached; }; this.detachAll = function(fireEvent, originalEvent) { while (self.connections.length > 0) { self.detach(self.connections[0], false, true, fireEvent, originalEvent); } }; this.detachFrom = function(targetEndpoint, fireEvent, originalEvent) { var c = []; for ( var i = 0; i < self.connections.length; i++) { if (self.connections[i].endpoints[1] == targetEndpoint || self.connections[i].endpoints[0] == targetEndpoint) { c.push(self.connections[i]); } } for ( var i = 0; i < c.length; i++) { if (self.detach(c[i], false, true, fireEvent, originalEvent)) c[i].setHover(false, false); } }; this.detachFromConnection = function(connection) { var idx = _ju.findWithFunction(self.connections, function(c) { return c.id == connection.id}); if (idx >= 0) { self.connections.splice(idx, 1); self[(self.connections.length > 0 ? "add" : "remove") + "Class"](_jsPlumb.endpointConnectedClass); self[(self.isFull() ? "add" : "remove") + "Class"](_jsPlumb.endpointFullClass); } }; this.getElement = function() { return _element; }; this.setElement = function(el, container) { var parentId = _jsPlumb.getId(el); // remove the endpoint from the list for the current endpoint's element _ju.removeWithFunction(params.endpointsByElement[self.elementId], function(e) { return e.id == self.id; }); _element = _gel(el); _elementId = _jsPlumb.getId(_element); self.elementId = _elementId; // need to get the new parent now var newParentElement = params.getParentFromParams({source:parentId, container:container}), curParent = jpcl.getParent(self.canvas); jpcl.removeElement(self.canvas, curParent); jpcl.appendElement(self.canvas, newParentElement); // now move connection(s)...i would expect there to be only one but we will iterate. for (var i = 0; i < self.connections.length; i++) { self.connections[i].moveParent(newParentElement); self.connections[i].sourceId = _elementId; self.connections[i].source = _element; } _ju.addToList(params.endpointsByElement, parentId, self); }; this.getUuid = function() { return _uuid; }; /** * private but must be exposed. */ self.makeInPlaceCopy = function() { var loc = self.anchor.getCurrentLocation(self), o = self.anchor.getOrientation(self), acc = self.anchor.getCssClass(), inPlaceAnchor = { bind:function() { }, compute:function() { return [ loc[0], loc[1] ]}, getCurrentLocation : function() { return [ loc[0], loc[1] ]}, getOrientation:function() { return o; }, getCssClass:function() { return acc; } }; return _newEndpoint( { anchor : inPlaceAnchor, source : _element, paintStyle : this.getPaintStyle(), endpoint : params.hideOnDrag ? "Blank" : _endpoint, _transient:true, scope:self.scope }); }; this.isConnectedTo = function(endpoint) { var found = false; if (endpoint) { for ( var i = 0; i < self.connections.length; i++) { if (self.connections[i].endpoints[1] == endpoint) { found = true; break; } } } return found; }; /** * private but needs to be exposed. */ this.isFloating = function() { return floatingEndpoint != null; }; /** * returns a connection from the pool; used when dragging starts. just gets the head of the array if it can. */ this.connectorSelector = function() { var candidate = self.connections[0]; if (self.isTarget && candidate) return candidate; else { return (self.connections.length < _maxConnections) || _maxConnections == -1 ? null : candidate; } }; this.isFull = function() { return !(self.isFloating() || _maxConnections < 1 || self.connections.length < _maxConnections); }; this.setDragAllowedWhenFull = function(allowed) { dragAllowedWhenFull = allowed; }; this.setStyle = self.setPaintStyle; /** * a deep equals check. everything must match, including the anchor, * styles, everything. TODO: finish Endpoint.equals */ this.equals = function(endpoint) { return this.anchor.equals(endpoint.anchor); }; // a helper function that tries to find a connection to the given element, and returns it if so. if elementWithPrecedence is null, // or no connection to it is found, we return the first connection in our list. var findConnectionToUseForDynamicAnchor = function(elementWithPrecedence) { var idx = 0; if (elementWithPrecedence != null) { for (var i = 0; i < self.connections.length; i++) { if (self.connections[i].sourceId == elementWithPrecedence || self.connections[i].targetId == elementWithPrecedence) { idx = i; break; } } } return self.connections[idx]; }; this.paint = function(params) { params = params || {}; var timestamp = params.timestamp, recalc = !(params.recalc === false); if (!timestamp || self.timestamp !== timestamp) { var info = _jsPlumb.updateOffset({ elId:_elementId, timestamp:timestamp, recalc:recalc }); var xy = params.offset ? params.offset.o : info.o; if(xy) { var ap = params.anchorPoint,connectorPaintStyle = params.connectorPaintStyle; if (ap == null) { var wh = params.dimensions || info.s; if (xy == null || wh == null) { info = _jsPlumb.updateOffset( { elId : _elementId, timestamp : timestamp }); xy = info.o; wh = info.s; } var anchorParams = { xy : [ xy.left, xy.top ], wh : wh, element : self, timestamp : timestamp }; if (recalc && self.anchor.isDynamic && self.connections.length > 0) { var c = findConnectionToUseForDynamicAnchor(params.elementWithPrecedence), oIdx = c.endpoints[0] == self ? 1 : 0, oId = oIdx == 0 ? c.sourceId : c.targetId, oInfo = _jsPlumb.getCachedData(oId), oOffset = oInfo.o, oWH = oInfo.s; anchorParams.txy = [ oOffset.left, oOffset.top ]; anchorParams.twh = oWH; anchorParams.tElement = c.endpoints[oIdx]; } ap = self.anchor.compute(anchorParams); } _endpoint.compute(ap, self.anchor.getOrientation(self), self.paintStyleInUse, connectorPaintStyle || self.paintStyleInUse); _endpoint.paint(self.paintStyleInUse, self.anchor); self.timestamp = timestamp; // paint overlays for ( var i = 0; i < self.overlays.length; i++) { var o = self.overlays[i]; if (o.isVisible()) { self.overlayPlacements[i] = o.draw(self.endpoint, self.paintStyleInUse); o.paint(self.overlayPlacements[i]); } } } } }; this.repaint = this.paint; // is this a connection source? we make it draggable and have the // drag listener maintain a connection with a floating endpoint. if (jpcl.isDragSupported(_element)) { var placeholderInfo = { id:null, element:null }, jpc = null, existingJpc = false, existingJpcParams = null, _dragHandler = _makeConnectionDragHandler(placeholderInfo, _jsPlumb); var start = function() { // drag might have started on an endpoint that is not actually a source, but which has // one or more connections. jpc = self.connectorSelector(); var _continue = true; // if not enabled, return if (!self.isEnabled()) _continue = false; // if no connection and we're not a source, return. if (jpc == null && !params.isSource) _continue = false; // otherwise if we're full and not allowed to drag, also return false. if (params.isSource && self.isFull() && !dragAllowedWhenFull) _continue = false; // if the connection was setup as not detachable or one of its endpoints // was setup as connectionsDetachable = false, or Defaults.ConnectionsDetachable // is set to false... if (jpc != null && !jpc.isDetachable()) _continue = false; if (_continue === false) { // this is for mootools and yui. returning false from this causes jquery to stop drag. // the events are wrapped in both mootools and yui anyway, but i don't think returning // false from the start callback would stop a drag. if (jpcl.stopDrag) jpcl.stopDrag(); _dragHandler.stopDrag(); return false; } self.addClass("endpointDrag"); // if we're not full but there was a connection, make it null. we'll create a new one. if (jpc && !self.isFull() && params.isSource) jpc = null; _jsPlumb.updateOffset( { elId : _elementId }); inPlaceCopy = self.makeInPlaceCopy(); inPlaceCopy.referenceEndpoint = self; inPlaceCopy.paint(); _makeDraggablePlaceholder(placeholderInfo, self.parent, _jsPlumb); // set the offset of this div to be where 'inPlaceCopy' is, to start with. // TODO merge this code with the code in both Anchor and FloatingAnchor, because it // does the same stuff. var ipcoel = _gel(inPlaceCopy.canvas), ipco = _getOffset(ipcoel, _jsPlumb), po = _jsPlumb.adjustForParentOffsetAndScroll([ipco.left, ipco.top], inPlaceCopy.canvas), canvasElement = _gel(self.canvas); jpcl.setOffset(placeholderInfo.element, {left:po[0], top:po[1]}); // when using makeSource and a parent, we first draw the source anchor on the source element, then // move it to the parent. note that this happens after drawing the placeholder for the // first time. if (self.parentAnchor) self.anchor = _jsPlumb.makeAnchor(self.parentAnchor, self.elementId, _jsPlumb); // store the id of the dragging div and the source element. the drop function will pick these up. jpcl.setAttribute(canvasElement, "dragId", placeholderInfo.id); jpcl.setAttribute(canvasElement, "elId", _elementId); floatingEndpoint = _makeFloatingEndpoint(self.getPaintStyle(), self.anchor, _endpoint, self.canvas, placeholderInfo.element, _jsPlumb, _newEndpoint); self.canvas.style.visibility = "hidden"; if (jpc == null) { self.anchor.locked = true; self.setHover(false, false); // create a connection. one end is this endpoint, the other is a floating endpoint. jpc = _newConnection({ sourceEndpoint : self, targetEndpoint : floatingEndpoint, source : self.endpointWillMoveTo || _element, // for makeSource with parent option. ensure source element is represented correctly. target : placeholderInfo.element, anchors : [ self.anchor, floatingEndpoint.anchor ], paintStyle : params.connectorStyle, // this can be null. Connection will use the default. hoverPaintStyle:params.connectorHoverStyle, connector : params.connector, // this can also be null. Connection will use the default. overlays : params.connectorOverlays, type:self.connectionType, cssClass:self.connectorClass, hoverClass:self.connectorHoverClass }); jpc.addClass(_jsPlumb.draggingClass); floatingEndpoint.addClass(_jsPlumb.draggingClass); // fire an event that informs that a connection is being dragged _jsPlumb.fire("connectionDrag", jpc); } else { existingJpc = true; jpc.setHover(false); // if existing connection, allow to be dropped back on the source endpoint (issue 51). _initDropTarget(ipcoel, false, true); // new anchor idx var anchorIdx = jpc.endpoints[0].id == self.id ? 0 : 1; jpc.floatingAnchorIndex = anchorIdx; // save our anchor index as the connection's floating index. self.detachFromConnection(jpc); // detach from the connection while dragging is occurring. // store the original scope (issue 57) var dragScope = jsPlumb.CurrentLibrary.getDragScope(canvasElement); jpcl.setAttribute(canvasElement, "originalScope", dragScope); // now we want to get this endpoint's DROP scope, and set it for now: we can only be dropped on drop zones // that have our drop scope (issue 57). var dropScope = jpcl.getDropScope(canvasElement); jpcl.setDragScope(canvasElement, dropScope); // now we replace ourselves with the temporary div we created above: if (anchorIdx == 0) { existingJpcParams = [ jpc.source, jpc.sourceId, i, dragScope ]; jpc.source = placeholderInfo.element; jpc.sourceId = placeholderInfo.id; } else { existingJpcParams = [ jpc.target, jpc.targetId, i, dragScope ]; jpc.target = placeholderInfo.element; jpc.targetId = placeholderInfo.id; } // lock the other endpoint; if it is dynamic it will not move while the drag is occurring. jpc.endpoints[anchorIdx == 0 ? 1 : 0].anchor.locked = true; // store the original endpoint and assign the new floating endpoint for the drag. jpc.suspendedEndpoint = jpc.endpoints[anchorIdx]; jpc.suspendedEndpoint.setHover(false); floatingEndpoint.referenceEndpoint = jpc.suspendedEndpoint; jpc.endpoints[anchorIdx] = floatingEndpoint; jpc.addClass(_jsPlumb.draggingClass); floatingEndpoint.addClass(_jsPlumb.draggingClass); // fire an event that informs that a connection is being dragged _jsPlumb.fire("connectionDrag", jpc); } // register it and register connection on it. floatingConnections[placeholderInfo.id] = jpc; _jsPlumb.anchorManager.addFloatingConnection(placeholderInfo.id, jpc); floatingEndpoint.addConnection(jpc); // only register for the target endpoint; we will not be dragging the source at any time // before this connection is either discarded or made into a permanent connection. _ju.addToList(params.endpointsByElement, placeholderInfo.id, floatingEndpoint); // tell jsplumb about it _jsPlumb.currentlyDragging = true; }; var dragOptions = params.dragOptions || {}, defaultOpts = jsPlumb.extend( {}, jpcl.defaultDragOptions), startEvent = jpcl.dragEvents["start"], stopEvent = jpcl.dragEvents["stop"], dragEvent = jpcl.dragEvents["drag"]; dragOptions = jsPlumb.extend(defaultOpts, dragOptions); dragOptions.scope = dragOptions.scope || self.scope; dragOptions[startEvent] = _jsPlumb.wrap(dragOptions[startEvent], start); // extracted drag handler function so can be used by makeSource dragOptions[dragEvent] = _jsPlumb.wrap(dragOptions[dragEvent], _dragHandler.drag); dragOptions[stopEvent] = _jsPlumb.wrap(dragOptions[stopEvent], function() { var originalEvent = jpcl.getDropEvent(arguments); _ju.removeWithFunction(params.endpointsByElement[placeholderInfo.id], function(e) { return e.id == floatingEndpoint.id; }); _ju.removeElement(inPlaceCopy.canvas, _element); _jsPlumb.anchorManager.clearFor(placeholderInfo.id); var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex; jpc.endpoints[idx == 0 ? 1 : 0].anchor.locked = false; // commented out pending decision on drag proxy stuff. // self.setPaintStyle(originalPaintStyle); // reset to original; may have been changed by drag proxy. if (jpc.endpoints[idx] == floatingEndpoint) { // if the connection was an existing one: if (existingJpc && jpc.suspendedEndpoint) { // fix for issue35, thanks Sylvain Gizard: when firing the detach event make sure the // floating endpoint has been replaced. if (idx == 0) { jpc.source = existingJpcParams[0]; jpc.sourceId = existingJpcParams[1]; } else { jpc.target = existingJpcParams[0]; jpc.targetId = existingJpcParams[1]; } // restore the original scope (issue 57) jpcl.setDragScope(existingJpcParams[2], existingJpcParams[3]); jpc.endpoints[idx] = jpc.suspendedEndpoint; if (jpc.isReattach() || jpc._forceReattach || jpc._forceDetach || !jpc.endpoints[idx == 0 ? 1 : 0].detach(jpc, false, false, true, originalEvent)) { jpc.setHover(false); jpc.floatingAnchorIndex = null; jpc.suspendedEndpoint.addConnection(jpc); _jsPlumb.repaint(existingJpcParams[1]); } jpc._forceDetach = null; jpc._forceReattach = null; } else { // TODO this looks suspiciously kind of like an Endpoint.detach call too. // i wonder if this one should post an event though. maybe this is good like this. _ju.removeElements(jpc.getConnector().getDisplayElements(), self.parent); self.detachFromConnection(jpc); } } // remove floating endpoint _after_ checking beforeDetach _ju.removeElements( [ placeholderInfo.element[0], floatingEndpoint.canvas ], _element); // TODO: clean up the connection canvas (if the user aborted) _jsPlumb.dragManager.elementRemoved(floatingEndpoint.elementId); self.canvas.style.visibility = "visible"; self.anchor.locked = false; self.paint({recalc:false}); jpc.removeClass(_jsPlumb.draggingClass); floatingEndpoint.removeClass(_jsPlumb.draggingClass); _jsPlumb.fire("connectionDragStop", jpc); jpc = null; inPlaceCopy = null; delete params.endpointsByElement[floatingEndpoint.elementId]; floatingEndpoint.anchor = null; floatingEndpoint = null; _jsPlumb.currentlyDragging = false; }); var i = _gel(self.canvas); jpcl.initDraggable(i, dragOptions, true, _jsPlumb); } // pulled this out into a function so we can reuse it for the inPlaceCopy canvas; you can now drop detached connections // back onto the endpoint you detached it from. var _initDropTarget = function(canvas, forceInit, isTransient, endpoint) { if ((params.isTarget || forceInit) && jpcl.isDropSupported(_element)) { var dropOptions = params.dropOptions || _jsPlumb.Defaults.DropOptions || jsPlumb.Defaults.DropOptions; dropOptions = jsPlumb.extend( {}, dropOptions); dropOptions.scope = dropOptions.scope || self.scope; var dropEvent = jpcl.dragEvents['drop'], overEvent = jpcl.dragEvents['over'], outEvent = jpcl.dragEvents['out'], drop = function() { self["removeClass"](_jsPlumb.endpointDropAllowedClass); self["removeClass"](_jsPlumb.endpointDropForbiddenClass); var originalEvent = jpcl.getDropEvent(arguments), draggable = _gel(jpcl.getDragObject(arguments)), id = _att(draggable, "dragId"), elId = _att(draggable, "elId"), scope = _att(draggable, "originalScope"), jpc = floatingConnections[id]; // if this is a drop back where the connection came from, mark it force rettach and // return; the stop handler will reattach. without firing an event. var redrop = jpc.suspendedEndpoint && (jpc.suspendedEndpoint.id == self.id || self.referenceEndpoint && jpc.suspendedEndpoint.id == self.referenceEndpoint.id) ; if (redrop) { jpc._forceReattach = true; return; } if (jpc != null) { var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex, oidx = idx == 0 ? 1 : 0; // restore the original scope if necessary (issue 57) if (scope) jsPlumb.CurrentLibrary.setDragScope(draggable, scope); var endpointEnabled = endpoint != null ? endpoint.isEnabled() : true; if (self.isFull()) { self.fire("maxConnections", { endpoint:self, connection:jpc, maxConnections:_maxConnections }, originalEvent); } if (!self.isFull() && !(idx == 0 && !self.isSource) && !(idx == 1 && !self.isTarget) && endpointEnabled) { var _doContinue = true; // the second check here is for the case that the user is dropping it back // where it came from. if (jpc.suspendedEndpoint && jpc.suspendedEndpoint.id != self.id) { if (idx == 0) { jpc.source = jpc.suspendedEndpoint.element; jpc.sourceId = jpc.suspendedEndpoint.elementId; } else { jpc.target = jpc.suspendedEndpoint.element; jpc.targetId = jpc.suspendedEndpoint.elementId; } if (!jpc.isDetachAllowed(jpc) || !jpc.endpoints[idx].isDetachAllowed(jpc) || !jpc.suspendedEndpoint.isDetachAllowed(jpc) || !_jsPlumb.checkCondition("beforeDetach", jpc)) _doContinue = false; } // these have to be set before testing for beforeDrop. if (idx == 0) { jpc.source = self.element; jpc.sourceId = self.elementId; } else { jpc.target = self.element; jpc.targetId = self.elementId; } // ------------ wrap the execution path in a function so we can support asynchronous beforeDrop // we want to execute this regardless. var commonFunction = function() { jpc.floatingAnchorIndex = null; }; var continueFunction = function() { // remove this jpc from the current endpoint jpc.endpoints[idx].detachFromConnection(jpc); if (jpc.suspendedEndpoint) jpc.suspendedEndpoint.detachFromConnection(jpc); jpc.endpoints[idx] = self; self.addConnection(jpc); // copy our parameters in to the connection: var params = self.getParameters(); for (var aParam in params) jpc.setParameter(aParam, params[aParam]); if (!jpc.suspendedEndpoint) { if (params.draggable) jsPlumb.CurrentLibrary.initDraggable(self.element, dragOptions, true, _jsPlumb); } else { var suspendedElement = jpc.suspendedEndpoint.getElement(), suspendedElementId = jpc.suspendedEndpoint.elementId; // fire a detach event _fireDetachEvent({ source : idx == 0 ? suspendedElement : jpc.source, target : idx == 1 ? suspendedElement : jpc.target, sourceId : idx == 0 ? suspendedElementId : jpc.sourceId, targetId : idx == 1 ? suspendedElementId : jpc.targetId, sourceEndpoint : idx == 0 ? jpc.suspendedEndpoint : jpc.endpoints[0], targetEndpoint : idx == 1 ? jpc.suspendedEndpoint : jpc.endpoints[1], connection : jpc }, true, originalEvent); } // mark endpoints to delete on detach if (jpc.endpoints[0].addedViaMouse) jpc.endpointsToDeleteOnDetach[0] = jpc.endpoints[0]; if (jpc.endpoints[1].addedViaMouse) jpc.endpointsToDeleteOnDetach[1] = jpc.endpoints[1]; // finalise will inform the anchor manager and also add to // connectionsByScope if necessary. _finaliseConnection(jpc, null, originalEvent); commonFunction(); }; var dontContinueFunction = function() { // otherwise just put it back on the endpoint it was on before the drag. if (jpc.suspendedEndpoint) { jpc.endpoints[idx] = jpc.suspendedEndpoint; jpc.setHover(false); jpc._forceDetach = true; if (idx == 0) { jpc.source = jpc.suspendedEndpoint.element; jpc.sourceId = jpc.suspendedEndpoint.elementId; } else { jpc.target = jpc.suspendedEndpoint.element; jpc.targetId = jpc.suspendedEndpoint.elementId;; } jpc.suspendedEndpoint.addConnection(jpc); jpc.endpoints[0].repaint(); jpc.repaint(); _jsPlumb.repaint(jpc.sourceId); jpc._forceDetach = false; } commonFunction(); }; // -------------------------------------- // now check beforeDrop. this will be available only on Endpoints that are setup to // have a beforeDrop condition (although, secretly, under the hood all Endpoints and // the Connection have them, because they are on jsPlumbUIComponent. shhh!), because // it only makes sense to have it on a target endpoint. _doContinue = _doContinue && self.isDropAllowed(jpc.sourceId, jpc.targetId, jpc.scope, jpc, self); if (_doContinue) { continueFunction(); } else { dontContinueFunction(); } //commonFunction(); } _jsPlumb.currentlyDragging = false; delete floatingConnections[id]; _jsPlumb.anchorManager.removeFloatingConnection(id); } }; dropOptions[dropEvent] = _jsPlumb.wrap(dropOptions[dropEvent], drop); dropOptions[overEvent] = _jsPlumb.wrap(dropOptions[overEvent], function() { var draggable = jpcl.getDragObject(arguments), id = _att( _gel(draggable), "dragId"), _jpc = floatingConnections[id]; if (_jpc != null) { var idx = _jpc.floatingAnchorIndex == null ? 1 : _jpc.floatingAnchorIndex; // here we should fire the 'over' event if we are a target and this is a new connection, // or we are the same as the floating endpoint. var _cont = (self.isTarget && _jpc.floatingAnchorIndex != 0) || (_jpc.suspendedEndpoint && self.referenceEndpoint && self.referenceEndpoint.id == _jpc.suspendedEndpoint.id); if (_cont) { var bb = _jsPlumb.checkCondition("checkDropAllowed", { sourceEndpoint:_jpc.endpoints[idx], targetEndpoint:self, connection:_jpc }); self[(bb ? "add" : "remove") + "Class"](_jsPlumb.endpointDropAllowedClass); self[(bb ? "remove" : "add") + "Class"](_jsPlumb.endpointDropForbiddenClass); _jpc.endpoints[idx].anchor.over(self.anchor); } } }); dropOptions[outEvent] = _jsPlumb.wrap(dropOptions[outEvent], function() { var draggable = jpcl.getDragObject(arguments), id = _att( _gel(draggable), "dragId"), _jpc = floatingConnections[id]; if (_jpc != null) { var idx = _jpc.floatingAnchorIndex == null ? 1 : _jpc.floatingAnchorIndex; var _cont = (self.isTarget && _jpc.floatingAnchorIndex != 0) || (_jpc.suspendedEndpoint && self.referenceEndpoint && self.referenceEndpoint.id == _jpc.suspendedEndpoint.id); if (_cont) { self["removeClass"](_jsPlumb.endpointDropAllowedClass); self["removeClass"](_jsPlumb.endpointDropForbiddenClass); _jpc.endpoints[idx].anchor.out(); } } }); jpcl.initDroppable(canvas, dropOptions, true, isTransient); } }; // initialise the endpoint's canvas as a drop target. this will be ignored if the endpoint is not a target or drag is not supported. _initDropTarget(_gel(self.canvas), true, !(params._transient || self.anchor.isFloating), self); // finally, set type if it was provided if (params.type) self.addType(params.type, params.data, _jsPlumb.isSuspendDrawing()); return self; }; })();;(function() { jsPlumb.Connection = function(params) { var self = this, visible = true, _internalHover, _superClassHover, _jsPlumb = params["_jsPlumb"], jpcl = jsPlumb.CurrentLibrary, _att = jpcl.getAttribute, _gel = jpcl.getElementObject, _ju = jsPlumbUtil, _getOffset = jpcl.getOffset, _newConnection = params.newConnection, _newEndpoint = params.newEndpoint, connector = null; self.idPrefix = "_jsplumb_c_"; self.defaultLabelLocation = 0.5; self.defaultOverlayKeys = ["Overlays", "ConnectionOverlays"]; this.parent = params.parent; overlayCapableJsPlumbUIComponent.apply(this, arguments); // ************** get the source and target and register the connection. ******************* // VISIBILITY this.isVisible = function() { return visible; }; this.setVisible = function(v) { visible = v; self[v ? "showOverlays" : "hideOverlays"](); if (connector && connector.canvas) connector.canvas.style.display = v ? "block" : "none"; self.repaint(); }; // END VISIBILITY // EDITABLE var editable = params.editable === true; this.setEditable = function(e) { if (connector && connector.isEditable()) editable = e; return editable; }; this.isEditable = function() { return editable; }; this.editStarted = function() { self.fire("editStarted", { path:connector.getPath() }); _jsPlumb.setHoverSuspended(true); }; this.editCompleted = function() { self.fire("editCompleted", { path:connector.getPath() }); self.setHover(false); _jsPlumb.setHoverSuspended(false); }; this.editCanceled = function() { self.fire("editCanceled", { path:connector.getPath() }); self.setHover(false); _jsPlumb.setHoverSuspended(false); }; // END EDITABLE // ADD CLASS/REMOVE CLASS - override to support adding/removing to/from endpoints var _ac = this.addClass, _rc = this.removeClass; this.addClass = function(c, informEndpoints) { _ac(c); if (informEndpoints) { self.endpoints[0].addClass(c); self.endpoints[1].addClass(c); } }; this.removeClass = function(c, informEndpoints) { _rc(c); if (informEndpoints) { self.endpoints[0].removeClass(c); self.endpoints[1].removeClass(c); } }; // TYPE this.getTypeDescriptor = function() { return "connection"; }; this.getDefaultType = function() { return { parameters:{}, scope:null, detachable:self._jsPlumb.Defaults.ConnectionsDetachable, rettach:self._jsPlumb.Defaults.ReattachConnections, paintStyle:self._jsPlumb.Defaults.PaintStyle || jsPlumb.Defaults.PaintStyle, connector:self._jsPlumb.Defaults.Connector || jsPlumb.Defaults.Connector, hoverPaintStyle:self._jsPlumb.Defaults.HoverPaintStyle || jsPlumb.Defaults.HoverPaintStyle, overlays:self._jsPlumb.Defaults.ConnectorOverlays || jsPlumb.Defaults.ConnectorOverlays }; }; var superAt = this.applyType; this.applyType = function(t, doNotRepaint) { superAt(t, doNotRepaint); if (t.detachable != null) self.setDetachable(t.detachable); if (t.reattach != null) self.setReattach(t.reattach); if (t.scope) self.scope = t.scope; editable = t.editable; self.setConnector(t.connector, doNotRepaint); }; // END TYPE // HOVER // override setHover to pass it down to the underlying connector _superClassHover = self.setHover; self.setHover = function(state) { connector.setHover.apply(connector, arguments); _superClassHover.apply(self, arguments); }; _internalHover = function(state) { if (!_jsPlumb.isConnectionBeingDragged()) { self.setHover(state, false); } }; // END HOVER var makeConnector = function(renderMode, connectorName, connectorArgs) { var c = new Object(); if (!_jsPlumb.Defaults.DoNotThrowErrors && jsPlumb.Connectors[connectorName] == null) throw { msg:"jsPlumb: unknown connector type '" + connectorName + "'" }; jsPlumb.Connectors[connectorName].apply(c, [connectorArgs]); jsPlumb.ConnectorRenderers[renderMode].apply(c, [connectorArgs]); return c; }; this.setConnector = function(connectorSpec, doNotRepaint) { if (connector != null) _ju.removeElements(connector.getDisplayElements()); var connectorArgs = { _jsPlumb:self._jsPlumb, parent:params.parent, cssClass:params.cssClass, container:params.container, tooltip:self.tooltip, "pointer-events":params["pointer-events"] }, renderMode = _jsPlumb.getRenderMode(); if (_ju.isString(connectorSpec)) connector = makeConnector(renderMode, connectorSpec, connectorArgs); // lets you use a string as shorthand. else if (_ju.isArray(connectorSpec)) { if (connectorSpec.length == 1) connector = makeConnector(renderMode, connectorSpec[0], connectorArgs); else connector = makeConnector(renderMode, connectorSpec[0], _ju.merge(connectorSpec[1], connectorArgs)); } // binds mouse listeners to the current connector. self.bindListeners(connector, self, _internalHover); self.canvas = connector.canvas; if (editable && jsPlumb.ConnectorEditors != null && jsPlumb.ConnectorEditors[connector.type] && connector.isEditable()) { new jsPlumb.ConnectorEditors[connector.type]({ connector:connector, connection:self, params:params.editorParams || { } }); } else { editable = false; } if (!doNotRepaint) self.repaint(); }; this.getConnector = function() { return connector; }; // INITIALISATION CODE this.source = _gel(params.source); this.target = _gel(params.target); // sourceEndpoint and targetEndpoint override source/target, if they are present. but // source is not overridden if the Endpoint has declared it is not the final target of a connection; // instead we use the source that the Endpoint declares will be the final source element. if (params.sourceEndpoint) this.source = params.sourceEndpoint.endpointWillMoveTo || params.sourceEndpoint.getElement(); if (params.targetEndpoint) this.target = params.targetEndpoint.getElement(); // if a new connection is the result of moving some existing connection, params.previousConnection // will have that Connection in it. listeners for the jsPlumbConnection event can look for that // member and take action if they need to. self.previousConnection = params.previousConnection; this.sourceId = _att(this.source, "id"); this.targetId = _att(this.target, "id"); this.scope = params.scope; // scope may have been passed in to the connect call. if it wasn't, we will pull it from the source endpoint, after having initialised the endpoints. this.endpoints = []; this.endpointStyles = []; // wrapped the main function to return null if no input given. this lets us cascade defaults properly. var _makeAnchor = function(anchorParams, elementId) { return (anchorParams) ? _jsPlumb.makeAnchor(anchorParams, elementId, _jsPlumb) : null; }, prepareEndpoint = function(existing, index, params, element, elementId, connectorPaintStyle, connectorHoverPaintStyle) { var e; if (existing) { self.endpoints[index] = existing; existing.addConnection(self); } else { if (!params.endpoints) params.endpoints = [ null, null ]; var ep = params.endpoints[index] || params.endpoint || _jsPlumb.Defaults.Endpoints[index] || jsPlumb.Defaults.Endpoints[index] || _jsPlumb.Defaults.Endpoint || jsPlumb.Defaults.Endpoint; if (!params.endpointStyles) params.endpointStyles = [ null, null ]; if (!params.endpointHoverStyles) params.endpointHoverStyles = [ null, null ]; var es = params.endpointStyles[index] || params.endpointStyle || _jsPlumb.Defaults.EndpointStyles[index] || jsPlumb.Defaults.EndpointStyles[index] || _jsPlumb.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle; // Endpoints derive their fillStyle from the connector's strokeStyle, if no fillStyle was specified. if (es.fillStyle == null && connectorPaintStyle != null) es.fillStyle = connectorPaintStyle.strokeStyle; // TODO: decide if the endpoint should derive the connection's outline width and color. currently it does: //* if (es.outlineColor == null && connectorPaintStyle != null) es.outlineColor = connectorPaintStyle.outlineColor; if (es.outlineWidth == null && connectorPaintStyle != null) es.outlineWidth = connectorPaintStyle.outlineWidth; //*/ var ehs = params.endpointHoverStyles[index] || params.endpointHoverStyle || _jsPlumb.Defaults.EndpointHoverStyles[index] || jsPlumb.Defaults.EndpointHoverStyles[index] || _jsPlumb.Defaults.EndpointHoverStyle || jsPlumb.Defaults.EndpointHoverStyle; // endpoint hover fill style is derived from connector's hover stroke style. TODO: do we want to do this by default? for sure? if (connectorHoverPaintStyle != null) { if (ehs == null) ehs = {}; if (ehs.fillStyle == null) { ehs.fillStyle = connectorHoverPaintStyle.strokeStyle; } } var a = params.anchors ? params.anchors[index] : params.anchor ? params.anchor : _makeAnchor(_jsPlumb.Defaults.Anchors[index], elementId) || _makeAnchor(jsPlumb.Defaults.Anchors[index], elementId) || _makeAnchor(_jsPlumb.Defaults.Anchor, elementId) || _makeAnchor(jsPlumb.Defaults.Anchor, elementId), u = params.uuids ? params.uuids[index] : null; e = _newEndpoint({ paintStyle : es, hoverPaintStyle:ehs, endpoint : ep, connections : [ self ], uuid : u, anchor : a, source : element, scope : params.scope, container:params.container, reattach:params.reattach || _jsPlumb.Defaults.ReattachConnections, detachable:params.detachable || _jsPlumb.Defaults.ConnectionsDetachable }); self.endpoints[index] = e; if (params.drawEndpoints === false) e.setVisible(false, true, true); } return e; }; var eS = prepareEndpoint(params.sourceEndpoint, 0, params, self.source, self.sourceId, params.paintStyle, params.hoverPaintStyle); if (eS) _ju.addToList(params.endpointsByElement, this.sourceId, eS); var eT = prepareEndpoint(params.targetEndpoint, 1, params, self.target, self.targetId, params.paintStyle, params.hoverPaintStyle); if (eT) _ju.addToList(params.endpointsByElement, this.targetId, eT); // if scope not set, set it to be the scope for the source endpoint. if (!this.scope) this.scope = this.endpoints[0].scope; // if delete endpoints on detach, keep a record of just exactly which endpoints they are. self.endpointsToDeleteOnDetach = [null, null]; if (params.deleteEndpointsOnDetach) { if (params.sourceIsNew) self.endpointsToDeleteOnDetach[0] = self.endpoints[0]; if (params.targetIsNew) self.endpointsToDeleteOnDetach[1] = self.endpoints[1]; } // or if the endpoints were supplied, use them. if (params.endpointsToDeleteOnDetach) self.endpointsToDeleteOnDetach = params.endpointsToDeleteOnDetach; // TODO these could surely be refactored into some method that tries them one at a time until something exists self.setConnector(this.endpoints[0].connector || this.endpoints[1].connector || params.connector || _jsPlumb.Defaults.Connector || jsPlumb.Defaults.Connector, true); if (params.path) connector.setPath(params.path); this.setPaintStyle(this.endpoints[0].connectorStyle || this.endpoints[1].connectorStyle || params.paintStyle || _jsPlumb.Defaults.PaintStyle || jsPlumb.Defaults.PaintStyle, true); this.setHoverPaintStyle(this.endpoints[0].connectorHoverStyle || this.endpoints[1].connectorHoverStyle || params.hoverPaintStyle || _jsPlumb.Defaults.HoverPaintStyle || jsPlumb.Defaults.HoverPaintStyle, true); this.paintStyleInUse = this.getPaintStyle(); var _suspendedAt = _jsPlumb.getSuspendedAt(); _jsPlumb.updateOffset( { elId : this.sourceId, timestamp:_suspendedAt }); _jsPlumb.updateOffset( { elId : this.targetId, timestamp:_suspendedAt }); // paint the endpoints var myInfo = _jsPlumb.getCachedData(this.sourceId), myOffset = myInfo.o, myWH = myInfo.s, otherInfo = _jsPlumb.getCachedData(this.targetId), otherOffset = otherInfo.o, otherWH = otherInfo.s, initialTimestamp = _suspendedAt || _jsPlumb.timestamp(), anchorLoc = this.endpoints[0].anchor.compute( { xy : [ myOffset.left, myOffset.top ], wh : myWH, element : this.endpoints[0], elementId:this.endpoints[0].elementId, txy : [ otherOffset.left, otherOffset.top ], twh : otherWH, tElement : this.endpoints[1], timestamp:initialTimestamp }); this.endpoints[0].paint( { anchorLoc : anchorLoc, timestamp:initialTimestamp }); anchorLoc = this.endpoints[1].anchor.compute( { xy : [ otherOffset.left, otherOffset.top ], wh : otherWH, element : this.endpoints[1], elementId:this.endpoints[1].elementId, txy : [ myOffset.left, myOffset.top ], twh : myWH, tElement : this.endpoints[0], timestamp:initialTimestamp }); this.endpoints[1].paint({ anchorLoc : anchorLoc, timestamp:initialTimestamp }); // END INITIALISATION CODE // DETACHABLE var _detachable = _jsPlumb.Defaults.ConnectionsDetachable; if (params.detachable === false) _detachable = false; if(self.endpoints[0].connectionsDetachable === false) _detachable = false; if(self.endpoints[1].connectionsDetachable === false) _detachable = false; this.isDetachable = function() { return _detachable === true; }; this.setDetachable = function(detachable) { _detachable = detachable === true; }; // END DETACHABLE // REATTACH var _reattach = params.reattach || self.endpoints[0].reattachConnections || self.endpoints[1].reattachConnections || _jsPlumb.Defaults.ReattachConnections; this.isReattach = function() { return _reattach === true; }; this.setReattach = function(reattach) { _reattach = reattach === true; }; // END REATTACH // COST + DIRECTIONALITY // if cost not supplied, try to inherit from source endpoint var _cost = params.cost || self.endpoints[0].getConnectionCost(); self.getCost = function() { return _cost; }; self.setCost = function(c) { _cost = c; }; var directed = params.directed; // inherit directed flag if set no source endpoint if (params.directed == null) directed = self.endpoints[0].areConnectionsDirected(); self.isDirected = function() { return directed === true; }; // END COST + DIRECTIONALITY // PARAMETERS // merge all the parameters objects into the connection. parameters set // on the connection take precedence; then target endpoint params, then // finally source endpoint params. // TODO jsPlumb.extend could be made to take more than two args, and it would // apply the second through nth args in order. var _p = jsPlumb.extend({}, this.endpoints[0].getParameters()); jsPlumb.extend(_p, this.endpoints[1].getParameters()); jsPlumb.extend(_p, self.getParameters()); self.setParameters(_p); // END PARAMETERS // MISCELLANEOUS this.getAttachedElements = function() { return self.endpoints; }; // // changes the parent element of this connection to newParent. not exposed for the public API. // this.moveParent = function(newParent) { var jpcl = jsPlumb.CurrentLibrary, curParent = jpcl.getParent(connector.canvas); if (connector.bgCanvas) { jpcl.removeElement(connector.bgCanvas); jpcl.appendElement(connector.bgCanvas, newParent); } jpcl.removeElement(connector.canvas); jpcl.appendElement(connector.canvas, newParent); // this only applies for DOMOverlays for (var i = 0; i < self.overlays.length; i++) { if (self.overlays[i].isAppendedAtTopLevel) { jpcl.removeElement(self.overlays[i].canvas); jpcl.appendElement(self.overlays[i].canvas, newParent); if (self.overlays[i].reattachListeners) self.overlays[i].reattachListeners(connector); } } if (connector.reattachListeners) // this is for SVG/VML; change an element's parent and you have to reinit its listeners. connector.reattachListeners(); // the Canvas implementation doesn't have to care about this }; // END MISCELLANEOUS // PAINTING /* * Paints the Connection. Not exposed for public usage. * * Parameters: * elId - Id of the element that is in motion. * ui - current library's event system ui object (present if we came from a drag to get here). * recalc - whether or not to recalculate all anchors etc before painting. * timestamp - timestamp of this paint. If the Connection was last painted with the same timestamp, it does not paint again. */ var lastPaintedAt = null; this.paint = function(params) { if (visible) { params = params || {}; var elId = params.elId, ui = params.ui, recalc = params.recalc, timestamp = params.timestamp, // if the moving object is not the source we must transpose the two references. swap = false, tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId, tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0; if (timestamp == null || timestamp != lastPaintedAt) { var sourceInfo = _jsPlumb.updateOffset( { elId : elId, offset : ui, recalc : recalc, timestamp : timestamp }).o, targetInfo = _jsPlumb.updateOffset( { elId : tId, timestamp : timestamp }).o, // update the target if this is a forced repaint. otherwise, only the source has been moved. sE = this.endpoints[sIdx], tE = this.endpoints[tIdx]; if (params.clearEdits) { sE.anchor.clearUserDefinedLocation(); tE.anchor.clearUserDefinedLocation(); connector.setEdited(false); } var sAnchorP = sE.anchor.getCurrentLocation(sE), tAnchorP = tE.anchor.getCurrentLocation(tE); connector.resetBounds(); connector.compute({ sourcePos:sAnchorP, targetPos:tAnchorP, sourceEndpoint:this.endpoints[sIdx], targetEndpoint:this.endpoints[tIdx], lineWidth:self.paintStyleInUse.lineWidth, sourceInfo:sourceInfo, targetInfo:targetInfo, clearEdits:params.clearEdits === true }); var overlayExtents = { minX:Infinity, minY:Infinity, maxX:-Infinity, maxY:-Infinity }; // compute overlays. we do this first so we can get their placements, and adjust the // container if needs be (if an overlay would be clipped) for ( var i = 0; i < self.overlays.length; i++) { var o = self.overlays[i]; if (o.isVisible()) { self.overlayPlacements[i] = o.draw(connector, self.paintStyleInUse); overlayExtents.minX = Math.min(overlayExtents.minX, self.overlayPlacements[i].minX); overlayExtents.maxX = Math.max(overlayExtents.maxX, self.overlayPlacements[i].maxX); overlayExtents.minY = Math.min(overlayExtents.minY, self.overlayPlacements[i].minY); overlayExtents.maxY = Math.max(overlayExtents.maxY, self.overlayPlacements[i].maxY); } } var lineWidth = (self.paintStyleInUse.lineWidth || 1) / 2, outlineWidth = self.paintStyleInUse.lineWidth || 0, extents = { xmin : Math.min(connector.bounds.minX - (lineWidth + outlineWidth), overlayExtents.minX), ymin : Math.min(connector.bounds.minY - (lineWidth + outlineWidth), overlayExtents.minY), xmax : Math.max(connector.bounds.maxX + (lineWidth + outlineWidth), overlayExtents.maxX), ymax : Math.max(connector.bounds.maxY + (lineWidth + outlineWidth), overlayExtents.maxY) }; // paint the connector. connector.paint(self.paintStyleInUse, null, extents); // and then the overlays for ( var i = 0; i < self.overlays.length; i++) { var o = self.overlays[i]; if (o.isVisible()) { o.paint(self.overlayPlacements[i], extents); } } } lastPaintedAt = timestamp; } }; /* * Function: repaint * Repaints the Connection. No parameters exposed to public API. */ this.repaint = function(params) { params = params || {}; var recalc = !(params.recalc === false); this.paint({ elId : this.sourceId, recalc : recalc, timestamp:params.timestamp, clearEdits:params.clearEdits }); }; // the very last thing we do is check to see if a 'type' was supplied in the params var _type = params.type || self.endpoints[0].connectionType || self.endpoints[1].connectionType; if (_type) self.addType(_type, params.data, _jsPlumb.isSuspendDrawing()); // END PAINTING }; // END Connection class })();/* * jsPlumb * * Title:jsPlumb 1.4.0 * * Provides a way to visually connect elements on an HTML page, using either SVG, Canvas * elements, or VML. * * This file contains the default Connectors, Endpoint and Overlay definitions. * * Copyright (c) 2010 - 2013 Simon Porritt (http://jsplumb.org) * * http://jsplumb.org * http://github.com/sporritt/jsplumb * http://code.google.com/p/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ;(function() { /** * * Helper class to consume unused mouse events by components that are DOM elements and * are used by all of the different rendering modes. * */ jsPlumb.DOMElementComponent = function(params) { jsPlumb.jsPlumbUIComponent.apply(this, arguments); // when render mode is canvas, these functions may be called by the canvas mouse handler. // this component is safe to pipe this stuff to /dev/null. this.mousemove = this.dblclick = this.click = this.mousedown = this.mouseup = function(e) { }; }; jsPlumb.Segments = { /* * Class: AbstractSegment * A Connector is made up of 1..N Segments, each of which has a Type, such as 'Straight', 'Arc', * 'Bezier'. This is new from 1.4.0, and gives us a lot more flexibility when drawing connections: things such * as rounded corners for flowchart connectors, for example, or a straight line stub for Bezier connections, are * much easier to do now. * * A Segment is responsible for providing coordinates for painting it, and also must be able to report its length. * */ AbstractSegment : function(params) { this.params = params; /** * Function: findClosestPointOnPath * Finds the closest point on this segment to the given [x, y], * returning both the x and y of the point plus its distance from * the supplied point, and its location along the length of the * path inscribed by the segment. This implementation returns * Infinity for distance and null values for everything else; * subclasses are expected to override. */ this.findClosestPointOnPath = function(x, y) { return { d:Infinity, x:null, y:null, l:null }; }; this.getBounds = function() { return { minX:Math.min(params.x1, params.x2), minY:Math.min(params.y1, params.y2), maxX:Math.max(params.x1, params.x2), maxY:Math.max(params.y1, params.y2) }; }; }, Straight : function(params) { var self = this, _super = jsPlumb.Segments.AbstractSegment.apply(this, arguments), length, m, m2, x1, x2, y1, y2, _recalc = function() { length = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); m = jsPlumbUtil.gradient({x:x1, y:y1}, {x:x2, y:y2}); m2 = -1 / m; }; this.type = "Straight"; self.getLength = function() { return length; }; self.getGradient = function() { return m; }; this.getCoordinates = function() { return { x1:x1,y1:y1,x2:x2,y2:y2 }; }; this.setCoordinates = function(coords) { x1 = coords.x1; y1 = coords.y1; x2 = coords.x2; y2 = coords.y2; _recalc(); }; this.setCoordinates({x1:params.x1, y1:params.y1, x2:params.x2, y2:params.y2}); this.getBounds = function() { return { minX:Math.min(x1, x2), minY:Math.min(y1, y2), maxX:Math.max(x1, x2), maxY:Math.max(y1, y2) }; }; /** * returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from * 0 to 1 inclusive. for the straight line segment this is simple maths. */ this.pointOnPath = function(location, absolute) { if (location == 0 && !absolute) return { x:x1, y:y1 }; else if (location == 1 && !absolute) return { x:x2, y:y2 }; else { var l = absolute ? location > 0 ? location : length + location : location * length; return jsPlumbUtil.pointOnLine({x:x1, y:y1}, {x:x2, y:y2}, l); } }; /** * returns the gradient of the segment at the given point - which for us is constant. */ this.gradientAtPoint = function(_) { return m; }; /** * returns the point on the segment's path that is 'distance' along the length of the path from 'location', where * 'location' is a decimal from 0 to 1 inclusive, and 'distance' is a number of pixels. * this hands off to jsPlumbUtil to do the maths, supplying two points and the distance. */ this.pointAlongPathFrom = function(location, distance, absolute) { var p = self.pointOnPath(location, absolute), farAwayPoint = location == 1 ? { x:x1 + ((x2 - x1) * 10), y:y1 + ((y1 - y2) * 10) } : distance <= 0 ? {x:x1, y:y1} : {x:x2, y:y2 }; if (distance <= 0 && Math.abs(distance) > 1) distance *= -1; return jsPlumbUtil.pointOnLine(p, farAwayPoint, distance); }; /** Function: findClosestPointOnPath Finds the closest point on this segment to [x,y]. See notes on this method in AbstractSegment. */ this.findClosestPointOnPath = function(x, y) { if (m == 0) { return { x:x, y:y1, d:Math.abs(y - y1) }; } else if (m == Infinity || m == -Infinity) { return { x:x1, y:y, d:Math.abs(x - 1) }; } else { // closest point lies on normal from given point to this line. var b = y1 - (m * x1), b2 = y - (m2 * x), // y1 = m.x1 + b and y1 = m2.x1 + b2 // so m.x1 + b = m2.x1 + b2 // x1(m - m2) = b2 - b // x1 = (b2 - b) / (m - m2) _x1 = (b2 -b) / (m - m2), _y1 = (m * _x1) + b, d = jsPlumbUtil.lineLength([ x, y ], [ _x1, _y1 ]), fractionInSegment = jsPlumbUtil.lineLength([ _x1, _y1 ], [ x1, y1 ]); return { d:d, x:_x1, y:_y1, l:fractionInSegment / length}; } }; }, /* Arc Segment. You need to supply: r - radius cx - center x for the arc cy - center y for the arc ac - whether the arc is anticlockwise or not. default is clockwise. and then either: startAngle - startAngle for the arc. endAngle - endAngle for the arc. or: x1 - x for start point y1 - y for start point x2 - x for end point y2 - y for end point */ Arc : function(params) { var self = this, _super = jsPlumb.Segments.AbstractSegment.apply(this, arguments), _calcAngle = function(_x, _y) { return jsPlumbUtil.theta([params.cx, params.cy], [_x, _y]); }, _calcAngleForLocation = function(location) { if (self.anticlockwise) { var sa = self.startAngle < self.endAngle ? self.startAngle + TWO_PI : self.startAngle, s = Math.abs(sa - self.endAngle); return sa - (s * location); } else { var ea = self.endAngle < self.startAngle ? self.endAngle + TWO_PI : self.endAngle, s = Math.abs (ea - self.startAngle); return self.startAngle + (s * location); } }, TWO_PI = 2 * Math.PI; this.radius = params.r; this.anticlockwise = params.ac; this.type = "Arc"; if (params.startAngle && params.endAngle) { this.startAngle = params.startAngle; this.endAngle = params.endAngle; this.x1 = params.cx + (self.radius * Math.cos(params.startAngle)); this.y1 = params.cy + (self.radius * Math.sin(params.startAngle)); this.x2 = params.cx + (self.radius * Math.cos(params.endAngle)); this.y2 = params.cy + (self.radius * Math.sin(params.endAngle)); } else { this.startAngle = _calcAngle(params.x1, params.y1); this.endAngle = _calcAngle(params.x2, params.y2); this.x1 = params.x1; this.y1 = params.y1; this.x2 = params.x2; this.y2 = params.y2; } if (this.endAngle < 0) this.endAngle += TWO_PI; if (this.startAngle < 0) this.startAngle += TWO_PI; // segment is used by vml this.segment = jsPlumbUtil.segment([this.x1, this.y1], [this.x2, this.y2]); // we now have startAngle and endAngle as positive numbers, meaning the // absolute difference (|d|) between them is the sweep (s) of this arc, unless the // arc is 'anticlockwise' in which case 's' is given by 2PI - |d|. var ea = self.endAngle < self.startAngle ? self.endAngle + TWO_PI : self.endAngle; self.sweep = Math.abs (ea - self.startAngle); if (self.anticlockwise) self.sweep = TWO_PI - self.sweep; var circumference = 2 * Math.PI * self.radius, frac = self.sweep / TWO_PI, length = circumference * frac; this.getLength = function() { return length; }; this.getBounds = function() { return { minX:params.cx - params.r, maxX:params.cx + params.r, minY:params.cy - params.r, maxY:params.cy + params.r } }; var VERY_SMALL_VALUE = 0.0000000001, gentleRound = function(n) { var f = Math.floor(n), r = Math.ceil(n); if (n - f < VERY_SMALL_VALUE) return f; else if (r - n < VERY_SMALL_VALUE) return r; return n; }; /** * returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from * 0 to 1 inclusive. */ this.pointOnPath = function(location, absolute) { if (location == 0) { return { x:self.x1, y:self.y1, theta:self.startAngle }; } else if (location == 1) { return { x:self.x2, y:self.y2, theta:self.endAngle }; } if (absolute) { location = location / length; } var angle = _calcAngleForLocation(location), _x = params.cx + (params.r * Math.cos(angle)), _y = params.cy + (params.r * Math.sin(angle)); return { x:gentleRound(_x), y:gentleRound(_y), theta:angle }; }; /** * returns the gradient of the segment at the given point. */ this.gradientAtPoint = function(location, absolute) { var p = self.pointOnPath(location, absolute); var m = jsPlumbUtil.normal( [ params.cx, params.cy ], [p.x, p.y ] ); if (!self.anticlockwise && (m == Infinity || m == -Infinity)) m *= -1; return m; }; this.pointAlongPathFrom = function(location, distance, absolute) { var p = self.pointOnPath(location, absolute), arcSpan = distance / circumference * 2 * Math.PI, dir = self.anticlockwise ? -1 : 1, startAngle = p.theta + (dir * arcSpan), startX = params.cx + (self.radius * Math.cos(startAngle)), startY = params.cy + (self.radius * Math.sin(startAngle)); return {x:startX, y:startY}; }; }, Bezier : function(params) { var self = this, _super = jsPlumb.Segments.AbstractSegment.apply(this, arguments), curve = [ { x:params.x1, y:params.y1}, { x:params.cp1x, y:params.cp1y }, { x:params.cp2x, y:params.cp2y }, { x:params.x2, y:params.y2 } ], // although this is not a strictly rigorous determination of bounds // of a bezier curve, it works for the types of curves that this segment // type produces. bounds = { minX:Math.min(params.x1, params.x2, params.cp1x, params.cp2x), minY:Math.min(params.y1, params.y2, params.cp1y, params.cp2y), maxX:Math.max(params.x1, params.x2, params.cp1x, params.cp2x), maxY:Math.max(params.y1, params.y2, params.cp1y, params.cp2y) }; this.type = "Bezier"; var _translateLocation = function(_curve, location, absolute) { if (absolute) location = jsBezier.locationAlongCurveFrom(_curve, location > 0 ? 0 : 1, location); return location; }; /** * returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from * 0 to 1 inclusive. */ this.pointOnPath = function(location, absolute) { location = _translateLocation(curve, location, absolute); return jsBezier.pointOnCurve(curve, location); }; /** * returns the gradient of the segment at the given point. */ this.gradientAtPoint = function(location, absolute) { location = _translateLocation(curve, location, absolute); return jsBezier.gradientAtPoint(curve, location); }; this.pointAlongPathFrom = function(location, distance, absolute) { location = _translateLocation(curve, location, absolute); return jsBezier.pointAlongCurveFrom(curve, location, distance); }; this.getLength = function() { return jsBezier.getLength(curve); }; this.getBounds = function() { return bounds; }; } }; /* Class: AbstractComponent Superclass for AbstractConnector and AbstractEndpoint. */ var AbstractComponent = function() { var self = this; self.resetBounds = function() { self.bounds = { minX:Infinity, minY:Infinity, maxX:-Infinity, maxY:-Infinity }; }; self.resetBounds(); }; /* * Class: AbstractConnector * Superclass for all Connectors; here is where Segments are managed. This is exposed on jsPlumb just so it * can be accessed from other files. You should not try to instantiate one of these directly. * * When this class is asked for a pointOnPath, or gradient etc, it must first figure out which segment to dispatch * that request to. This is done by keeping track of the total connector length as segments are added, and also * their cumulative ratios to the total length. Then when the right segment is found it is a simple case of dispatching * the request to it (and adjusting 'location' so that it is relative to the beginning of that segment.) */ jsPlumb.Connectors.AbstractConnector = function(params) { AbstractComponent.apply(this, arguments); var self = this, segments = [], editing = false, totalLength = 0, segmentProportions = [], segmentProportionalLengths = [], stub = params.stub || 0, sourceStub = jsPlumbUtil.isArray(stub) ? stub[0] : stub, targetStub = jsPlumbUtil.isArray(stub) ? stub[1] : stub, gap = params.gap || 0, sourceGap = jsPlumbUtil.isArray(gap) ? gap[0] : gap, targetGap = jsPlumbUtil.isArray(gap) ? gap[1] : gap, userProvidedSegments = null, edited = false, paintInfo = null; // subclasses should override. this.isEditable = function() { return false; }; this.setEdited = function(ed) { edited = ed; }; // to be overridden by subclasses. this.getPath = function() { }; this.setPath = function(path) { }; /** * Function: findSegmentForPoint * Returns the segment that is closest to the given [x,y], * null if nothing found. This function returns a JS * object with: * * d - distance from segment * l - proportional location in segment * x - x point on the segment * y - y point on the segment * s - the segment itself. */ this.findSegmentForPoint = function(x, y) { var out = { d:Infinity, s:null, x:null, y:null, l:null }; for (var i = 0; i < segments.length; i++) { var _s = segments[i].findClosestPointOnPath(x, y); if (_s.d < out.d) { out.d = _s.d; out.l = _s.l; out.x = _s.x; out.y = _s.y; out.s = segments[i]; } } return out; }; var _updateSegmentProportions = function() { var curLoc = 0; for (var i = 0; i < segments.length; i++) { var sl = segments[i].getLength(); segmentProportionalLengths[i] = sl / totalLength; segmentProportions[i] = [curLoc, (curLoc += (sl / totalLength)) ]; } }, /** * returns [segment, proportion of travel in segment, segment index] for the segment * that contains the point which is 'location' distance along the entire path, where * 'location' is a decimal between 0 and 1 inclusive. in this connector type, paths * are made up of a list of segments, each of which contributes some fraction to * the total length. * From 1.3.10 this also supports the 'absolute' property, which lets us specify a location * as the absolute distance in pixels, rather than a proportion of the total path. */ _findSegmentForLocation = function(location, absolute) { if (absolute) { location = location > 0 ? location / totalLength : (totalLength + location) / totalLength; } var idx = segmentProportions.length - 1, inSegmentProportion = 1; //if (location < 1) { for (var i = 0; i < segmentProportions.length; i++) { if (segmentProportions[i][1] >= location) { idx = i; // todo is this correct for all connector path types? inSegmentProportion = location == 1 ? 1 : location == 0 ? 0 : (location - segmentProportions[i][0]) / segmentProportionalLengths[i]; break; } } //} return { segment:segments[idx], proportion:inSegmentProportion, index:idx }; }, _addSegment = function(type, params) { var s = new jsPlumb.Segments[type](params); segments.push(s); totalLength += s.getLength(); self.updateBounds(s); }, _clearSegments = function() { totalLength = 0; segments.splice(0, segments.length); segmentProportions.splice(0, segmentProportions.length); segmentProportionalLengths.splice(0, segmentProportionalLengths.length); }; this.setSegments = function(_segs) { userProvidedSegments = []; totalLength = 0; for (var i = 0; i < _segs.length; i++) { userProvidedSegments.push(_segs[i]); totalLength += _segs[i].getLength(); } }; var _prepareCompute = function(params) { self.lineWidth = params.lineWidth; var segment = jsPlumbUtil.segment(params.sourcePos, params.targetPos), swapX = params.targetPos[0] < params.sourcePos[0], swapY = params.targetPos[1] < params.sourcePos[1], lw = params.lineWidth || 1, so = params.sourceEndpoint.anchor.orientation || params.sourceEndpoint.anchor.getOrientation(params.sourceEndpoint), to = params.targetEndpoint.anchor.orientation || params.targetEndpoint.anchor.getOrientation(params.targetEndpoint), x = swapX ? params.targetPos[0] : params.sourcePos[0], y = swapY ? params.targetPos[1] : params.sourcePos[1], w = Math.abs(params.targetPos[0] - params.sourcePos[0]), h = Math.abs(params.targetPos[1] - params.sourcePos[1]); // if either anchor does not have an orientation set, we derive one from their relative // positions. we fix the axis to be the one in which the two elements are further apart, and // point each anchor at the other element. this is also used when dragging a new connection. if (so[0] == 0 && so[1] == 0 || to[0] == 0 && to[1] == 0) { var index = w > h ? 0 : 1, oIndex = [1,0][index]; so = []; to = []; so[index] = params.sourcePos[index] > params.targetPos[index] ? -1 : 1; to[index] = params.sourcePos[index] > params.targetPos[index] ? 1 : -1; so[oIndex] = 0; to[oIndex] = 0; } var sx = swapX ? w + (sourceGap * so[0]) : sourceGap * so[0], sy = swapY ? h + (sourceGap * so[1]) : sourceGap * so[1], tx = swapX ? targetGap * to[0] : w + (targetGap * to[0]), ty = swapY ? targetGap * to[1] : h + (targetGap * to[1]), oProduct = ((so[0] * to[0]) + (so[1] * to[1])); var result = { sx:sx, sy:sy, tx:tx, ty:ty, lw:lw, xSpan:Math.abs(tx - sx), ySpan:Math.abs(ty - sy), mx:(sx + tx) / 2, my:(sy + ty) / 2, so:so, to:to, x:x, y:y, w:w, h:h, segment : segment, startStubX : sx + (so[0] * sourceStub), startStubY : sy + (so[1] * sourceStub), endStubX : tx + (to[0] * targetStub), endStubY : ty + (to[1] * targetStub), isXGreaterThanStubTimes2 : Math.abs(sx - tx) > (sourceStub + targetStub), isYGreaterThanStubTimes2 : Math.abs(sy - ty) > (sourceStub + targetStub), opposite:oProduct == -1, perpendicular:oProduct == 0, orthogonal:oProduct == 1, sourceAxis : so[0] == 0 ? "y" : "x", points:[x, y, w, h, sx, sy, tx, ty ] }; result.anchorOrientation = result.opposite ? "opposite" : result.orthogonal ? "orthogonal" : "perpendicular"; return result; }; this.getSegments = function() { return segments; }; self.updateBounds = function(segment) { var segBounds = segment.getBounds(); self.bounds.minX = Math.min(self.bounds.minX, segBounds.minX); self.bounds.maxX = Math.max(self.bounds.maxX, segBounds.maxX); self.bounds.minY = Math.min(self.bounds.minY, segBounds.minY); self.bounds.maxY = Math.max(self.bounds.maxY, segBounds.maxY); }; var dumpSegmentsToConsole = function() { console.log("SEGMENTS:"); for (var i = 0; i < segments.length; i++) { console.log(segments[i].type, segments[i].getLength(), segmentProportions[i]); } }; this.pointOnPath = function(location, absolute) { //console.log("point on path", location); var seg = _findSegmentForLocation(location, absolute); //console.log("point on path", location, seg); return seg.segment.pointOnPath(seg.proportion, absolute); }; this.gradientAtPoint = function(location) { var seg = _findSegmentForLocation(location, absolute); return seg.segment.gradientAtPoint(seg.proportion, absolute); }; this.pointAlongPathFrom = function(location, distance, absolute) { var seg = _findSegmentForLocation(location, absolute); // TODO what happens if this crosses to the next segment? return seg.segment.pointAlongPathFrom(seg.proportion, distance, absolute); }; this.compute = function(params) { if (!edited) paintInfo = _prepareCompute(params); _clearSegments(); this._compute(paintInfo, params); self.x = paintInfo.points[0]; self.y = paintInfo.points[1]; self.w = paintInfo.points[2]; self.h = paintInfo.points[3]; self.segment = paintInfo.segment; _updateSegmentProportions(); }; return { addSegment:_addSegment, prepareCompute:_prepareCompute, sourceStub:sourceStub, targetStub:targetStub, maxStub:Math.max(sourceStub, targetStub), sourceGap:sourceGap, targetGap:targetGap, maxGap:Math.max(sourceGap, targetGap) }; }; /** * Class: Connectors.Straight * The Straight connector draws a simple straight line between the two anchor points. It does not have any constructor parameters. */ jsPlumb.Connectors.Straight = function() { this.type = "Straight"; var _super = jsPlumb.Connectors.AbstractConnector.apply(this, arguments); this._compute = function(paintInfo, _) { _super.addSegment("Straight", {x1:paintInfo.sx, y1:paintInfo.sy, x2:paintInfo.startStubX, y2:paintInfo.startStubY}); _super.addSegment("Straight", {x1:paintInfo.startStubX, y1:paintInfo.startStubY, x2:paintInfo.endStubX, y2:paintInfo.endStubY}); _super.addSegment("Straight", {x1:paintInfo.endStubX, y1:paintInfo.endStubY, x2:paintInfo.tx, y2:paintInfo.ty}); }; }; /** * Class:Connectors.Bezier * This Connector draws a Bezier curve with two control points. You can provide a 'curviness' value which gets applied to jsPlumb's * internal voodoo machine and ends up generating locations for the two control points. See the constructor documentation below. */ /** * Function:Constructor * * Parameters: * curviness - How 'curvy' you want the curve to be! This is a directive for the placement of control points, not endpoints of the curve, so your curve does not * actually touch the given point, but it has the tendency to lean towards it. The larger this value, the greater the curve is pulled from a straight line. * Optional; defaults to 150. * stub - optional value for a distance to travel from the connector's endpoint before beginning the Bezier curve. defaults to 0. * */ jsPlumb.Connectors.Bezier = function(params) { params = params || {}; var self = this, _super = jsPlumb.Connectors.AbstractConnector.apply(this, arguments), stub = params.stub || 50, majorAnchor = params.curviness || 150, minorAnchor = 10; this.type = "Bezier"; this.getCurviness = function() { return majorAnchor; }; this._findControlPoint = function(point, sourceAnchorPosition, targetAnchorPosition, sourceEndpoint, targetEndpoint) { // determine if the two anchors are perpendicular to each other in their orientation. we swap the control // points around if so (code could be tightened up) var soo = sourceEndpoint.anchor.getOrientation(sourceEndpoint), too = targetEndpoint.anchor.getOrientation(targetEndpoint), perpendicular = soo[0] != too[0] || soo[1] == too[1], p = []; if (!perpendicular) { if (soo[0] == 0) // X p.push(sourceAnchorPosition[0] < targetAnchorPosition[0] ? point[0] + minorAnchor : point[0] - minorAnchor); else p.push(point[0] - (majorAnchor * soo[0])); if (soo[1] == 0) // Y p.push(sourceAnchorPosition[1] < targetAnchorPosition[1] ? point[1] + minorAnchor : point[1] - minorAnchor); else p.push(point[1] + (majorAnchor * too[1])); } else { if (too[0] == 0) // X p.push(targetAnchorPosition[0] < sourceAnchorPosition[0] ? point[0] + minorAnchor : point[0] - minorAnchor); else p.push(point[0] + (majorAnchor * too[0])); if (too[1] == 0) // Y p.push(targetAnchorPosition[1] < sourceAnchorPosition[1] ? point[1] + minorAnchor : point[1] - minorAnchor); else p.push(point[1] + (majorAnchor * soo[1])); } return p; }; this._compute = function(paintInfo, p) { var sp = p.sourcePos, tp = p.targetPos, _w = Math.abs(sp[0] - tp[0]), _h = Math.abs(sp[1] - tp[1]), _sx = sp[0] < tp[0] ? _w : 0, _sy = sp[1] < tp[1] ? _h : 0, _tx = sp[0] < tp[0] ? 0 : _w, _ty = sp[1] < tp[1] ? 0 : _h, _CP = self._findControlPoint([_sx, _sy], sp, tp, p.sourceEndpoint, p.targetEndpoint), _CP2 = self._findControlPoint([_tx, _ty], tp, sp, p.targetEndpoint, p.sourceEndpoint); _super.addSegment("Bezier", { x1:_sx, y1:_sy, x2:_tx, y2:_ty, cp1x:_CP[0], cp1y:_CP[1], cp2x:_CP2[0], cp2y:_CP2[1] }); }; }; // ********************************* END OF CONNECTOR TYPES ******************************************************************* // ********************************* ENDPOINT TYPES ******************************************************************* jsPlumb.Endpoints.AbstractEndpoint = function(params) { AbstractComponent.apply(this, arguments); var self = this; this.compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) { var out = self._compute.apply(self, arguments); self.x = out[0]; self.y = out[1]; self.w = out[2]; self.h = out[3]; self.bounds.minX = self.x; self.bounds.minY = self.y; self.bounds.maxX = self.x + self.w; self.bounds.maxY = self.y + self.h; return out; }; return { compute:self.compute, cssClass:params.cssClass }; }; /** * Class: Endpoints.Dot * A round endpoint, with default radius 10 pixels. */ /** * Function: Constructor * * Parameters: * * radius - radius of the endpoint. defaults to 10 pixels. */ jsPlumb.Endpoints.Dot = function(params) { this.type = "Dot"; var self = this, _super = jsPlumb.Endpoints.AbstractEndpoint.apply(this, arguments); params = params || {}; this.radius = params.radius || 10; this.defaultOffset = 0.5 * this.radius; this.defaultInnerRadius = this.radius / 3; this._compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) { self.radius = endpointStyle.radius || self.radius; var x = anchorPoint[0] - self.radius, y = anchorPoint[1] - self.radius, w = self.radius * 2, h = self.radius * 2; if (endpointStyle.strokeStyle) { var lw = endpointStyle.lineWidth || 1; x -= lw; y -= lw; w += (lw * 2); h += (lw * 2); } return [ x, y, w, h, self.radius ]; }; }; /** * Class: Endpoints.Rectangle * A Rectangular Endpoint, with default size 20x20. */ /** * Function: Constructor * * Parameters: * * width - width of the endpoint. defaults to 20 pixels. * height - height of the endpoint. defaults to 20 pixels. */ jsPlumb.Endpoints.Rectangle = function(params) { this.type = "Rectangle"; var self = this, _super = jsPlumb.Endpoints.AbstractEndpoint.apply(this, arguments); params = params || {}; this.width = params.width || 20; this.height = params.height || 20; this._compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) { var width = endpointStyle.width || self.width, height = endpointStyle.height || self.height, x = anchorPoint[0] - (width/2), y = anchorPoint[1] - (height/2); return [ x, y, width, height]; }; }; var DOMElementEndpoint = function(params) { jsPlumb.DOMElementComponent.apply(this, arguments); var self = this; var displayElements = [ ]; this.getDisplayElements = function() { return displayElements; }; this.appendDisplayElement = function(el) { displayElements.push(el); }; }; /** * Class: Endpoints.Image * Draws an image as the Endpoint. */ /** * Function: Constructor * * Parameters: * * src - location of the image to use. */ jsPlumb.Endpoints.Image = function(params) { this.type = "Image"; DOMElementEndpoint.apply(this, arguments); var self = this, _super = jsPlumb.Endpoints.AbstractEndpoint.apply(this, arguments), initialized = false, deleted = false, widthToUse = params.width, heightToUse = params.height, _onload = null, _endpoint = params.endpoint; this.img = new Image(); self.ready = false; this.img.onload = function() { self.ready = true; widthToUse = widthToUse || self.img.width; heightToUse = heightToUse || self.img.height; if (_onload) { _onload(self); } }; /* Function: setImage Sets the Image to use in this Endpoint. Parameters: img - may be a URL or an Image object onload - optional; a callback to execute once the image has loaded. */ _endpoint.setImage = function(img, onload) { var s = img.constructor == String ? img : img.src; _onload = onload; self.img.src = img; if (self.canvas != null) self.canvas.setAttribute("src", img); }; _endpoint.setImage(params.src || params.url, params.onload); this._compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) { self.anchorPoint = anchorPoint; if (self.ready) return [anchorPoint[0] - widthToUse / 2, anchorPoint[1] - heightToUse / 2, widthToUse, heightToUse]; else return [0,0,0,0]; }; self.canvas = document.createElement("img"), initialized = false; self.canvas.style["margin"] = 0; self.canvas.style["padding"] = 0; self.canvas.style["outline"] = 0; self.canvas.style["position"] = "absolute"; var clazz = params.cssClass ? " " + params.cssClass : ""; self.canvas.className = jsPlumb.endpointClass + clazz; if (widthToUse) self.canvas.setAttribute("width", widthToUse); if (heightToUse) self.canvas.setAttribute("height", heightToUse); jsPlumb.appendElement(self.canvas, params.parent); self.attachListeners(self.canvas, self); self.cleanup = function() { deleted = true; }; var actuallyPaint = function(d, style, anchor) { if (!deleted) { if (!initialized) { self.canvas.setAttribute("src", self.img.src); self.appendDisplayElement(self.canvas); initialized = true; } var x = self.anchorPoint[0] - (widthToUse / 2), y = self.anchorPoint[1] - (heightToUse / 2); jsPlumb.sizeCanvas(self.canvas, x, y, widthToUse, heightToUse); } }; this.paint = function(style, anchor) { if (self.ready) { actuallyPaint(style, anchor); } else { window.setTimeout(function() { self.paint(style, anchor); }, 200); } }; }; /* * Class: Endpoints.Blank * An Endpoint that paints nothing (visible) on the screen. Supports cssClass and hoverClass parameters like all Endpoints. */ jsPlumb.Endpoints.Blank = function(params) { var self = this, _super = jsPlumb.Endpoints.AbstractEndpoint.apply(this, arguments); this.type = "Blank"; DOMElementEndpoint.apply(this, arguments); this._compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) { return [anchorPoint[0], anchorPoint[1],10,0]; }; self.canvas = document.createElement("div"); self.canvas.style.display = "block"; self.canvas.style.width = "1px"; self.canvas.style.height = "1px"; self.canvas.style.background = "transparent"; self.canvas.style.position = "absolute"; self.canvas.className = self._jsPlumb.endpointClass; jsPlumb.appendElement(self.canvas, params.parent); this.paint = function(style, anchor) { jsPlumb.sizeCanvas(self.canvas, self.x, self.y, self.w, self.h); }; }; /* * Class: Endpoints.Triangle * A triangular Endpoint. */ /* * Function: Constructor * * Parameters: * * width - width of the triangle's base. defaults to 55 pixels. * height - height of the triangle from base to apex. defaults to 55 pixels. */ jsPlumb.Endpoints.Triangle = function(params) { this.type = "Triangle"; var self = this, _super = jsPlumb.Endpoints.AbstractEndpoint.apply(this, arguments); params = params || { }; params.width = params.width || 55; params.height = params.height || 55; this.width = params.width; this.height = params.height; this._compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) { var width = endpointStyle.width || self.width, height = endpointStyle.height || self.height, x = anchorPoint[0] - (width/2), y = anchorPoint[1] - (height/2); return [ x, y, width, height ]; }; }; // ********************************* END OF ENDPOINT TYPES ******************************************************************* // ********************************* OVERLAY DEFINITIONS *********************************************************************** var AbstractOverlay = jsPlumb.Overlays.AbstractOverlay = function(params) { var visible = true, self = this; this.isAppendedAtTopLevel = true; this.component = params.component; this.loc = params.location == null ? 0.5 : params.location; this.endpointLoc = params.endpointLocation == null ? [ 0.5, 0.5] : params.endpointLocation; this.setVisible = function(val) { visible = val; self.component.repaint(); }; this.isVisible = function() { return visible; }; this.hide = function() { self.setVisible(false); }; this.show = function() { self.setVisible(true); }; this.incrementLocation = function(amount) { self.loc += amount; self.component.repaint(); }; this.setLocation = function(l) { self.loc = l; self.component.repaint(); }; this.getLocation = function() { return self.loc; }; }; /* * Class: Overlays.Arrow * * An arrow overlay, defined by four points: the head, the two sides of the tail, and a 'foldback' point at some distance along the length * of the arrow that lines from each tail point converge into. The foldback point is defined using a decimal that indicates some fraction * of the length of the arrow and has a default value of 0.623. A foldback point value of 1 would mean that the arrow had a straight line * across the tail. */ /* * Function: Constructor * * Parameters: * * length - distance in pixels from head to tail baseline. default 20. * width - width in pixels of the tail baseline. default 20. * fillStyle - style to use when filling the arrow. defaults to "black". * strokeStyle - style to use when stroking the arrow. defaults to null, which means the arrow is not stroked. * lineWidth - line width to use when stroking the arrow. defaults to 1, but only used if strokeStyle is not null. * foldback - distance (as a decimal from 0 to 1 inclusive) along the length of the arrow marking the point the tail points should fold back to. defaults to 0.623. * location - distance (as a decimal from 0 to 1 inclusive) marking where the arrow should sit on the connector. defaults to 0.5. * direction - indicates the direction the arrow points in. valid values are -1 and 1; 1 is default. */ jsPlumb.Overlays.Arrow = function(params) { this.type = "Arrow"; AbstractOverlay.apply(this, arguments); this.isAppendedAtTopLevel = false; params = params || {}; var self = this, _ju = jsPlumbUtil; this.length = params.length || 20; this.width = params.width || 20; this.id = params.id; var direction = (params.direction || 1) < 0 ? -1 : 1, paintStyle = params.paintStyle || { lineWidth:1 }, // how far along the arrow the lines folding back in come to. default is 62.3%. foldback = params.foldback || 0.623; this.computeMaxSize = function() { return self.width * 1.5; }; this.cleanup = function() { }; // nothing to clean up for Arrows this.draw = function(component, currentConnectionPaintStyle) { var hxy, mid, txy, tail, cxy; if (component.pointAlongPathFrom) { if (_ju.isString(self.loc) || self.loc > 1 || self.loc < 0) { var l = parseInt(self.loc); hxy = component.pointAlongPathFrom(l, direction * self.length / 2, true), mid = component.pointOnPath(l, true), txy = _ju.pointOnLine(hxy, mid, self.length); } else if (self.loc == 1) { hxy = component.pointOnPath(self.loc); mid = component.pointAlongPathFrom(self.loc, -1); txy = _ju.pointOnLine(hxy, mid, self.length); if (direction == -1) { var _ = txy; txy = hxy; hxy = _; } } else if (self.loc == 0) { txy = component.pointOnPath(self.loc); mid = component.pointAlongPathFrom(self.loc, 1); hxy = _ju.pointOnLine(txy, mid, self.length); if (direction == -1) { var _ = txy; txy = hxy; hxy = _; } } else { hxy = component.pointAlongPathFrom(self.loc, direction * self.length / 2), mid = component.pointOnPath(self.loc), txy = _ju.pointOnLine(hxy, mid, self.length); } tail = _ju.perpendicularLineTo(hxy, txy, self.width); cxy = _ju.pointOnLine(hxy, txy, foldback * self.length); var d = { hxy:hxy, tail:tail, cxy:cxy }, strokeStyle = paintStyle.strokeStyle || currentConnectionPaintStyle.strokeStyle, fillStyle = paintStyle.fillStyle || currentConnectionPaintStyle.strokeStyle, lineWidth = paintStyle.lineWidth || currentConnectionPaintStyle.lineWidth, info = { component:component, d:d, lineWidth:lineWidth, strokeStyle:strokeStyle, fillStyle:fillStyle, minX:Math.min(hxy.x, tail[0].x, tail[1].x), maxX:Math.max(hxy.x, tail[0].x, tail[1].x), minY:Math.min(hxy.y, tail[0].y, tail[1].y), maxY:Math.max(hxy.y, tail[0].y, tail[1].y) }; return info; } else return {component:component, minX:0,maxX:0,minY:0,maxY:0}; }; }; /* * Class: Overlays.PlainArrow * * A basic arrow. This is in fact just one instance of the more generic case in which the tail folds back on itself to some * point along the length of the arrow: in this case, that foldback point is the full length of the arrow. so it just does * a 'call' to Arrow with foldback set appropriately. */ /* * Function: Constructor * See <Overlays.Arrow> for allowed parameters for this overlay. */ jsPlumb.Overlays.PlainArrow = function(params) { params = params || {}; var p = jsPlumb.extend(params, {foldback:1}); jsPlumb.Overlays.Arrow.call(this, p); this.type = "PlainArrow"; }; /* * Class: Overlays.Diamond * * A diamond. Like PlainArrow, this is a concrete case of the more generic case of the tail points converging on some point...it just * happens that in this case, that point is greater than the length of the the arrow. * * this could probably do with some help with positioning...due to the way it reuses the Arrow paint code, what Arrow thinks is the * center is actually 1/4 of the way along for this guy. but we don't have any knowledge of pixels at this point, so we're kind of * stuck when it comes to helping out the Arrow class. possibly we could pass in a 'transpose' parameter or something. the value * would be -l/4 in this case - move along one quarter of the total length. */ /* * Function: Constructor * See <Overlays.Arrow> for allowed parameters for this overlay. */ jsPlumb.Overlays.Diamond = function(params) { params = params || {}; var l = params.length || 40, p = jsPlumb.extend(params, {length:l/2, foldback:2}); jsPlumb.Overlays.Arrow.call(this, p); this.type = "Diamond"; }; // abstract superclass for overlays that add an element to the DOM. var AbstractDOMOverlay = function(params) { jsPlumb.DOMElementComponent.apply(this, arguments); AbstractOverlay.apply(this, arguments); var self = this, initialised = false, jpcl = jsPlumb.CurrentLibrary; params = params || {}; this.id = params.id; var div; var makeDiv = function() { div = params.create(params.component); div = jpcl.getDOMElement(div); div.style["position"] = "absolute"; var clazz = params["_jsPlumb"].overlayClass + " " + (self.cssClass ? self.cssClass : params.cssClass ? params.cssClass : ""); div.className = clazz; params["_jsPlumb"].appendElement(div, params.component.parent); params["_jsPlumb"].getId(div); self.attachListeners(div, self); self.canvas = div; }; this.getElement = function() { if (div == null) { makeDiv(); } return div; }; this.getDimensions = function() { return jpcl.getSize(jpcl.getElementObject(self.getElement())); }; var cachedDimensions = null, _getDimensions = function(component) { if (cachedDimensions == null) cachedDimensions = self.getDimensions(); return cachedDimensions; }; /* * Function: clearCachedDimensions * Clears the cached dimensions for the label. As a performance enhancement, label dimensions are * cached from 1.3.12 onwards. The cache is cleared when you change the label text, of course, but * there are other reasons why the text dimensions might change - if you make a change through CSS, for * example, you might change the font size. in that case you should explicitly call this method. */ this.clearCachedDimensions = function() { cachedDimensions = null; }; this.computeMaxSize = function() { var td = _getDimensions(); return Math.max(td[0], td[1]); }; //override setVisible var osv = self.setVisible; self.setVisible = function(state) { osv(state); // call superclass div.style.display = state ? "block" : "none"; }; this.cleanup = function() { if (div != null) jpcl.removeElement(div); }; this.paint = function(params, containerExtents) { if (!initialised) { self.getElement(); params.component.appendDisplayElement(div); self.attachListeners(div, params.component); initialised = true; } div.style.left = (params.component.x + params.d.minx) + "px"; div.style.top = (params.component.y + params.d.miny) + "px"; }; this.draw = function(component, currentConnectionPaintStyle) { var td = _getDimensions(); if (td != null && td.length == 2) { var cxy = {x:0,y:0}; if (component.pointOnPath) { var loc = self.loc, absolute = false; if (jsPlumbUtil.isString(self.loc) || self.loc < 0 || self.loc > 1) { loc = parseInt(self.loc); absolute = true; } cxy = component.pointOnPath(loc, absolute); // a connection } else { var locToUse = self.loc.constructor == Array ? self.loc : self.endpointLoc; cxy = { x:locToUse[0] * component.w, y:locToUse[1] * component.h }; } var minx = cxy.x - (td[0] / 2), miny = cxy.y - (td[1] / 2); return { component:component, d:{ minx:minx, miny:miny, td:td, cxy:cxy }, minX:minx, maxX:minx + td[0], minY:miny, maxY:miny + td[1] }; } else return {minX:0,maxX:0,minY:0,maxY:0}; }; this.reattachListeners = function(connector) { if (div) { self.reattachListenersForElement(div, self, connector); } }; }; /* * Class: Overlays.Custom * A Custom overlay. You supply a 'create' function which returns some DOM element, and jsPlumb positions it. * The 'create' function is passed a Connection or Endpoint. */ /* * Function: Constructor * * Parameters: * create - function for jsPlumb to call that returns a DOM element. * location - distance (as a decimal from 0 to 1 inclusive) marking where the label should sit on the connector. defaults to 0.5. * id - optional id to use for later retrieval of this overlay. * */ jsPlumb.Overlays.Custom = function(params) { this.type = "Custom"; AbstractDOMOverlay.apply(this, arguments); }; jsPlumb.Overlays.GuideLines = function() { var self = this; self.length = 50; self.lineWidth = 5; this.type = "GuideLines"; AbstractOverlay.apply(this, arguments); jsPlumb.jsPlumbUIComponent.apply(this, arguments); this.draw = function(connector, currentConnectionPaintStyle) { var head = connector.pointAlongPathFrom(self.loc, self.length / 2), mid = connector.pointOnPath(self.loc), tail = jsPlumbUtil.pointOnLine(head, mid, self.length), tailLine = jsPlumbUtil.perpendicularLineTo(head, tail, 40), headLine = jsPlumbUtil.perpendicularLineTo(tail, head, 20); return { connector:connector, head:head, tail:tail, headLine:headLine, tailLine:tailLine, minX:Math.min(head.x, tail.x, headLine[0].x, headLine[1].x), minY:Math.min(head.y, tail.y, headLine[0].y, headLine[1].y), maxX:Math.max(head.x, tail.x, headLine[0].x, headLine[1].x), maxY:Math.max(head.y, tail.y, headLine[0].y, headLine[1].y) }; }; this.cleanup = function() { }; // nothing to clean up for GuideLines }; /* * Class: Overlays.Label * A Label overlay. For all different renderer types (SVG/Canvas/VML), jsPlumb draws a Label overlay as a styled DIV. Version 1.3.0 of jsPlumb * introduced the ability to set css classes on the label; this is now the preferred way for you to style a label. The 'labelStyle' parameter * is still supported in 1.3.0 but its usage is deprecated. Under the hood, jsPlumb just turns that object into a bunch of CSS directive that it * puts on the Label's 'style' attribute, so the end result is the same. */ /* * Function: Constructor * * Parameters: * cssClass - optional css class string to append to css class. This string is appended "as-is", so you can of course have multiple classes * defined. This parameter is preferred to using labelStyle, borderWidth and borderStyle. * label - the label to paint. May be a string or a function that returns a string. Nothing will be painted if your label is null or your * label function returns null. empty strings _will_ be painted. * location - distance (as a decimal from 0 to 1 inclusive) marking where the label should sit on the connector. defaults to 0.5. * id - optional id to use for later retrieval of this overlay. * */ jsPlumb.Overlays.Label = function(params) { var self = this; this.labelStyle = params.labelStyle || jsPlumb.Defaults.LabelStyle; this.cssClass = this.labelStyle != null ? this.labelStyle.cssClass : null; params.create = function() { return document.createElement("div"); }; jsPlumb.Overlays.Custom.apply(this, arguments); this.type = "Label"; var label = params.label || "", self = this, labelText = null; /* * Function: setLabel * sets the label's, um, label. you would think i'd call this function * 'setText', but you can pass either a Function or a String to this, so * it makes more sense as 'setLabel'. This uses innerHTML on the label div, so keep * that in mind if you need escaped HTML. */ this.setLabel = function(l) { label = l; labelText = null; self.clearCachedDimensions(); _update(); self.component.repaint(); }; var _update = function() { if (typeof label == "function") { var lt = label(self); self.getElement().innerHTML = lt.replace(/\r\n/g, "<br/>"); } else { if (labelText == null) { labelText = label; self.getElement().innerHTML = labelText.replace(/\r\n/g, "<br/>"); } } }; this.getLabel = function() { return label; }; var superGD = this.getDimensions; this.getDimensions = function() { _update(); return superGD(); }; }; // ********************************* END OF OVERLAY DEFINITIONS *********************************************************************** })();/* * jsPlumb * * Title:jsPlumb 1.4.0 * * Provides a way to visually connect elements on an HTML page, using either SVG, Canvas * elements, or VML. * * This file contains the state machine connectors. * * Thanks to Brainstorm Mobile Solutions for supporting the development of these. * * Copyright (c) 2010 - 2013 Simon Porritt (simon.porritt@gmail.com) * * http://jsplumb.org * http://github.com/sporritt/jsplumb * http://code.google.com/p/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ;(function() { var Line = function(x1, y1, x2, y2) { this.m = (y2 - y1) / (x2 - x1); this.b = -1 * ((this.m * x1) - y1); this.rectIntersect = function(x,y,w,h) { var results = []; // try top face // the equation of the top face is y = (0 * x) + b; y = b. var xInt = (y - this.b) / this.m; // test that the X value is in the line's range. if (xInt >= x && xInt <= (x + w)) results.push([ xInt, (this.m * xInt) + this.b ]); // try right face var yInt = (this.m * (x + w)) + this.b; if (yInt >= y && yInt <= (y + h)) results.push([ (yInt - this.b) / this.m, yInt ]); // bottom face var xInt = ((y + h) - this.b) / this.m; // test that the X value is in the line's range. if (xInt >= x && xInt <= (x + w)) results.push([ xInt, (this.m * xInt) + this.b ]); // try left face var yInt = (this.m * x) + this.b; if (yInt >= y && yInt <= (y + h)) results.push([ (yInt - this.b) / this.m, yInt ]); if (results.length == 2) { var midx = (results[0][0] + results[1][0]) / 2, midy = (results[0][1] + results[1][1]) / 2; results.push([ midx,midy ]); // now calculate the segment inside the rectangle where the midpoint lies. var xseg = midx <= x + (w / 2) ? -1 : 1, yseg = midy <= y + (h / 2) ? -1 : 1; results.push([xseg, yseg]); return results; } return null; }; }, _segment = function(x1, y1, x2, y2) { if (x1 <= x2 && y2 <= y1) return 1; else if (x1 <= x2 && y1 <= y2) return 2; else if (x2 <= x1 && y2 >= y1) return 3; return 4; }, // the control point we will use depends on the faces to which each end of the connection is assigned, specifically whether or not the // two faces are parallel or perpendicular. if they are parallel then the control point lies on the midpoint of the axis in which they // are parellel and varies only in the other axis; this variation is proportional to the distance that the anchor points lie from the // center of that face. if the two faces are perpendicular then the control point is at some distance from both the midpoints; the amount and // direction are dependent on the orientation of the two elements. 'seg', passed in to this method, tells you which segment the target element // lies in with respect to the source: 1 is top right, 2 is bottom right, 3 is bottom left, 4 is top left. // // sourcePos and targetPos are arrays of info about where on the source and target each anchor is located. their contents are: // // 0 - absolute x // 1 - absolute y // 2 - proportional x in element (0 is left edge, 1 is right edge) // 3 - proportional y in element (0 is top edge, 1 is bottom edge) // _findControlPoint = function(midx, midy, segment, sourceEdge, targetEdge, dx, dy, distance, proximityLimit) { // TODO (maybe) // - if anchor pos is 0.5, make the control point take into account the relative position of the elements. if (distance <= proximityLimit) return [midx, midy]; if (segment === 1) { if (sourceEdge[3] <= 0 && targetEdge[3] >= 1) return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ]; else if (sourceEdge[2] >= 1 && targetEdge[2] <= 0) return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ]; else return [ midx + (-1 * dx) , midy + (-1 * dy) ]; } else if (segment === 2) { if (sourceEdge[3] >= 1 && targetEdge[3] <= 0) return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ]; else if (sourceEdge[2] >= 1 && targetEdge[2] <= 0) return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ]; else return [ midx + (1 * dx) , midy + (-1 * dy) ]; } else if (segment === 3) { if (sourceEdge[3] >= 1 && targetEdge[3] <= 0) return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ]; else if (sourceEdge[2] <= 0 && targetEdge[2] >= 1) return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ]; else return [ midx + (-1 * dx) , midy + (-1 * dy) ]; } else if (segment === 4) { if (sourceEdge[3] <= 0 && targetEdge[3] >= 1) return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ]; else if (sourceEdge[2] <= 0 && targetEdge[2] >= 1) return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ]; else return [ midx + (1 * dx) , midy + (-1 * dy) ]; } }; /** * Class: Connectors.StateMachine * Provides 'state machine' connectors. */ /* * Function: Constructor * * Parameters: * curviness - measure of how "curvy" the connectors will be. this is translated as the distance that the * Bezier curve's control point is from the midpoint of the straight line connecting the two * endpoints, and does not mean that the connector is this wide. The Bezier curve never reaches * its control points; they act as gravitational masses. defaults to 10. * margin - distance from element to start and end connectors, in pixels. defaults to 5. * proximityLimit - sets the distance beneath which the elements are consider too close together to bother * with fancy curves. by default this is 80 pixels. * loopbackRadius - the radius of a loopback connector. optional; defaults to 25. * showLoopback - If set to false this tells the connector that it is ok to paint connections whose source and target is the same element with a connector running through the element. The default value for this is true; the connector always makes a loopback connection loop around the element rather than passing through it. */ jsPlumb.Connectors.StateMachine = function(params) { params = params || {}; this.type = "StateMachine"; var self = this, _super = jsPlumb.Connectors.AbstractConnector.apply(this, arguments), curviness = params.curviness || 10, margin = params.margin || 5, proximityLimit = params.proximityLimit || 80, clockwise = params.orientation && params.orientation === "clockwise", loopbackRadius = params.loopbackRadius || 25, showLoopback = params.showLoopback !== false; this._compute = function(paintInfo, params) { var w = Math.abs(params.sourcePos[0] - params.targetPos[0]), h = Math.abs(params.sourcePos[1] - params.targetPos[1]), x = Math.min(params.sourcePos[0], params.targetPos[0]), y = Math.min(params.sourcePos[1], params.targetPos[1]); if (!showLoopback || (params.sourceEndpoint.elementId !== params.targetEndpoint.elementId)) { var _sx = params.sourcePos[0] < params.targetPos[0] ? 0 : w, _sy = params.sourcePos[1] < params.targetPos[1] ? 0:h, _tx = params.sourcePos[0] < params.targetPos[0] ? w : 0, _ty = params.sourcePos[1] < params.targetPos[1] ? h : 0; // now adjust for the margin if (params.sourcePos[2] === 0) _sx -= margin; if (params.sourcePos[2] === 1) _sx += margin; if (params.sourcePos[3] === 0) _sy -= margin; if (params.sourcePos[3] === 1) _sy += margin; if (params.targetPos[2] === 0) _tx -= margin; if (params.targetPos[2] === 1) _tx += margin; if (params.targetPos[3] === 0) _ty -= margin; if (params.targetPos[3] === 1) _ty += margin; // // these connectors are quadratic bezier curves, having a single control point. if both anchors // are located at 0.5 on their respective faces, the control point is set to the midpoint and you // get a straight line. this is also the case if the two anchors are within 'proximityLimit', since // it seems to make good aesthetic sense to do that. outside of that, the control point is positioned // at 'curviness' pixels away along the normal to the straight line connecting the two anchors. // // there may be two improvements to this. firstly, we might actually support the notion of avoiding nodes // in the UI, or at least making a good effort at doing so. if a connection would pass underneath some node, // for example, we might increase the distance the control point is away from the midpoint in a bid to // steer it around that node. this will work within limits, but i think those limits would also be the likely // limits for, once again, aesthetic good sense in the layout of a chart using these connectors. // // the second possible change is actually two possible changes: firstly, it is possible we should gradually // decrease the 'curviness' as the distance between the anchors decreases; start tailing it off to 0 at some // point (which should be configurable). secondly, we might slightly increase the 'curviness' for connectors // with respect to how far their anchor is from the center of its respective face. this could either look cool, // or stupid, and may indeed work only in a way that is so subtle as to have been a waste of time. // var _midx = (_sx + _tx) / 2, _midy = (_sy + _ty) / 2, m2 = (-1 * _midx) / _midy, theta2 = Math.atan(m2), dy = (m2 == Infinity || m2 == -Infinity) ? 0 : Math.abs(curviness / 2 * Math.sin(theta2)), dx = (m2 == Infinity || m2 == -Infinity) ? 0 : Math.abs(curviness / 2 * Math.cos(theta2)), segment = _segment(_sx, _sy, _tx, _ty), distance = Math.sqrt(Math.pow(_tx - _sx, 2) + Math.pow(_ty - _sy, 2)), // calculate the control point. this code will be where we'll put in a rudimentary element avoidance scheme; it // will work by extending the control point to force the curve to be, um, curvier. _controlPoint = _findControlPoint(_midx, _midy, segment, params.sourcePos, params.targetPos, curviness, curviness, distance, proximityLimit); _super.addSegment("Bezier", { x1:_tx, y1:_ty, x2:_sx, y2:_sy, cp1x:_controlPoint[0], cp1y:_controlPoint[1], cp2x:_controlPoint[0], cp2y:_controlPoint[1] }); } else { // a loopback connector. draw an arc from one anchor to the other. var x1 = params.sourcePos[0], x2 = params.sourcePos[0], y1 = params.sourcePos[1] - margin, y2 = params.sourcePos[1] - margin, cx = x1, cy = y1 - loopbackRadius; // canvas sizing stuff, to ensure the whole painted area is visible. w = 2 * loopbackRadius, h = 2 * loopbackRadius, x = cx - loopbackRadius, y = cy - loopbackRadius; paintInfo.points[0] = x; paintInfo.points[1] = y; paintInfo.points[2] = w; paintInfo.points[3] = h; // ADD AN ARC SEGMENT. _super.addSegment("Arc", { x1:(x1-x) + 4, y1:y1-y, startAngle:0, endAngle: 2 * Math.PI, r:loopbackRadius, ac:!clockwise, x2:(x1-x) - 4, y2:y1-y, cx:cx-x, cy:cy-y }); } }; }; })(); /* // a possible rudimentary avoidance scheme, old now, perhaps not useful. // if (avoidSelector) { // var testLine = new Line(sourcePos[0] + _sx,sourcePos[1] + _sy,sourcePos[0] + _tx,sourcePos[1] + _ty); // var sel = jsPlumb.getSelector(avoidSelector); // for (var i = 0; i < sel.length; i++) { // var id = jsPlumb.getId(sel[i]); // if (id != sourceEndpoint.elementId && id != targetEndpoint.elementId) { // o = jsPlumb.getOffset(id), s = jsPlumb.getSize(id); // // if (o && s) { // var collision = testLine.rectIntersect(o.left,o.top,s[0],s[1]); // if (collision) { // set the control point to be a certain distance from the midpoint of the two points that // the line crosses on the rectangle. // TODO where will this 75 number come from? // _controlX = collision[2][0] + (75 * collision[3][0]); // / _controlY = collision[2][1] + (75 * collision[3][1]); // } // } // } // } //} *//* * jsPlumb * * Title:jsPlumb 1.4.0 * * Provides a way to visually connect elements on an HTML page, using either SVG, Canvas * elements, or VML. * * This file contains the 'flowchart' connectors, consisting of vertical and horizontal line segments. * * Copyright (c) 2010 - 2013 Simon Porritt (simon.porritt@gmail.com) * * http://jsplumb.org * http://github.com/sporritt/jsplumb * http://code.google.com/p/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ;(function() { /** * Function: Constructor * * Parameters: * stub - minimum length for the stub at each end of the connector. This can be an integer, giving a value for both ends of the connections, * or an array of two integers, giving separate values for each end. The default is an integer with value 30 (pixels). * gap - gap to leave between the end of the connector and the element on which the endpoint resides. if you make this larger than stub then you will see some odd looking behaviour. Like stub, this can be an array or a single value. defaults to 0 pixels for each end. * cornerRadius - optional, defines the radius of corners between segments. defaults to 0 (hard edged corners). */ jsPlumb.Connectors.Flowchart = function(params) { this.type = "Flowchart"; params = params || {}; params.stub = params.stub || 30; var self = this, _super = jsPlumb.Connectors.AbstractConnector.apply(this, arguments), midpoint = params.midpoint || 0.5, points = [], segments = [], grid = params.grid, userSuppliedSegments = null, lastx = null, lasty = null, lastOrientation, cornerRadius = params.cornerRadius != null ? params.cornerRadius : 0, sgn = function(n) { return n < 0 ? -1 : n == 0 ? 0 : 1; }, /** * helper method to add a segment. */ addSegment = function(segments, x, y, sx, sy) { // if segment would have length zero, dont add it. if (sx == lastx && sy == lasty) return; if (x == lastx && y == lasty) return; var lx = lastx == null ? sx : lastx, ly = lasty == null ? sy : lasty, o = lx == x ? "v" : "h", sgnx = sgn(x - lx), sgny = sgn(y - ly); lastx = x; lasty = y; segments.push([lx, ly, x, y, o, sgnx, sgny]); }, segLength = function(s) { return Math.sqrt(Math.pow(s[0] - s[2], 2) + Math.pow(s[1] - s[3], 2)); }, _cloneArray = function(a) { var _a = []; _a.push.apply(_a, a); return _a;}, updateMinMax = function(a1) { self.bounds.minX = Math.min(self.bounds.minX, a1[2]); self.bounds.maxX = Math.max(self.bounds.maxX, a1[2]); self.bounds.minY = Math.min(self.bounds.minY, a1[3]); self.bounds.maxY = Math.max(self.bounds.maxY, a1[3]); }, writeSegments = function(segments, paintInfo) { var current, next; for (var i = 0; i < segments.length - 1; i++) { current = current || _cloneArray(segments[i]); next = _cloneArray(segments[i + 1]); if (cornerRadius > 0 && current[4] != next[4]) { var radiusToUse = Math.min(cornerRadius, segLength(current), segLength(next)); // right angle. adjust current segment's end point, and next segment's start point. current[2] -= current[5] * radiusToUse; current[3] -= current[6] * radiusToUse; next[0] += next[5] * radiusToUse; next[1] += next[6] * radiusToUse; var ac = (current[6] == next[5] && next[5] == 1) || ((current[6] == next[5] && next[5] == 0) && current[5] != next[6]) || (current[6] == next[5] && next[5] == -1), sgny = next[1] > current[3] ? 1 : -1, sgnx = next[0] > current[2] ? 1 : -1, sgnEqual = sgny == sgnx, cx = (sgnEqual && ac || (!sgnEqual && !ac)) ? next[0] : current[2], cy = (sgnEqual && ac || (!sgnEqual && !ac)) ? current[3] : next[1]; _super.addSegment("Straight", { x1:current[0], y1:current[1], x2:current[2], y2:current[3] }); _super.addSegment("Arc", { r:radiusToUse, x1:current[2], y1:current[3], x2:next[0], y2:next[1], cx:cx, cy:cy, ac:ac }); } else { // dx + dy are used to adjust for line width. var dx = (current[2] == current[0]) ? 0 : (current[2] > current[0]) ? (paintInfo.lw / 2) : -(paintInfo.lw / 2), dy = (current[3] == current[1]) ? 0 : (current[3] > current[1]) ? (paintInfo.lw / 2) : -(paintInfo.lw / 2); _super.addSegment("Straight", { x1:current[0]- dx, y1:current[1]-dy, x2:current[2] + dx, y2:current[3] + dy }); } current = next; } // last segment _super.addSegment("Straight", { x1:next[0], y1:next[1], x2:next[2], y2:next[3] }); }; this.setSegments = function(s) { userSuppliedSegments = s; }; this.isEditable = function() { return true; }; /* Function: getOriginalSegments Gets the segments before the addition of rounded corners. This is used by the flowchart connector editor, since it only wants to concern itself with the original segments. */ this.getOriginalSegments = function() { return userSuppliedSegments || segments; }; this._compute = function(paintInfo, params) { if (params.clearEdits) userSuppliedSegments = null; if (userSuppliedSegments != null) { writeSegments(userSuppliedSegments, paintInfo); return; } segments = []; lastx = null; lasty = null; lastOrientation = null; var midx = paintInfo.startStubX + ((paintInfo.endStubX - paintInfo.startStubX) * midpoint), midy = paintInfo.startStubY + ((paintInfo.endStubY - paintInfo.startStubY) * midpoint); // add the start stub segment. addSegment(segments, paintInfo.startStubX, paintInfo.startStubY, paintInfo.sx, paintInfo.sy); var findClearedLine = function(start, mult, anchorPos, dimension) { return start + (mult * (( 1 - anchorPos) * dimension) + _super.maxStub); }, orientations = { x:[ 0, 1 ], y:[ 1, 0 ] }, lineCalculators = { perpendicular : function(axis) { with (paintInfo) { var sis = { x:[ [ [ 1,2,3,4 ], null, [ 2,1,4,3 ] ], null, [ [ 4,3,2,1 ], null, [ 3,4,1,2 ] ] ], y:[ [ [ 3,2,1,4 ], null, [ 2,3,4,1 ] ], null, [ [ 4,1,2,3 ], null, [ 1,4,3,2 ] ] ] }, stubs = { x:[ [ startStubX, endStubX ] , null, [ endStubX, startStubX ] ], y:[ [ startStubY, endStubY ] , null, [ endStubY, startStubY ] ] }, midLines = { x:[ [ midx, startStubY ], [ midx, endStubY ] ], y:[ [ startStubX, midy ], [ endStubX, midy ] ] }, linesToEnd = { x:[ [ endStubX, startStubY ] ], y:[ [ startStubX, endStubY ] ] }, startToEnd = { x:[ [ startStubX, endStubY ], [ endStubX, endStubY ] ], y:[ [ endStubX, startStubY ], [ endStubX, endStubY ] ] }, startToMidToEnd = { x:[ [ startStubX, midy ], [ endStubX, midy ], [ endStubX, endStubY ] ], y:[ [ midx, startStubY ], [ midx, endStubY ], [ endStubX, endStubY ] ] }, otherStubs = { x:[ startStubY, endStubY ], y:[ startStubX, endStubX ] }, soIdx = orientations[axis][0], toIdx = orientations[axis][1], _so = so[soIdx] + 1, _to = to[toIdx] + 1, otherFlipped = (to[toIdx] == -1 && (otherStubs[axis][1] < otherStubs[axis][0])) || (to[toIdx] == 1 && (otherStubs[axis][1] > otherStubs[axis][0])), stub1 = stubs[axis][_so][0], stub2 = stubs[axis][_so][1], segmentIndexes = sis[axis][_so][_to]; if (segment == segmentIndexes[3] || (segment == segmentIndexes[2] && otherFlipped)) { return midLines[axis]; } else if (segment == segmentIndexes[2] && stub2 < stub1) { return linesToEnd[axis]; } else if ((segment == segmentIndexes[2] && stub2 >= stub1) || (segment == segmentIndexes[1] && !otherFlipped)) { return startToMidToEnd[axis]; } else if (segment == segmentIndexes[0] || (segment == segmentIndexes[1] && otherFlipped)) { return startToEnd[axis]; } } }, orthogonal : function(axis) { var pi = paintInfo, extent = { "x":pi.so[0] == -1 ? Math.min(pi.startStubX, pi.endStubX) : Math.max(pi.startStubX, pi.endStubX), "y":pi.so[1] == -1 ? Math.min(pi.startStubY, pi.endStubY) : Math.max(pi.startStubY, pi.endStubY) }[axis]; return { "x":[ [ extent, pi.startStubY ],[ extent, pi.endStubY ], [ pi.endStubX, pi.endStubY ] ], "y":[ [ pi.startStubX, extent ], [ pi.endStubX, extent ],[ pi.endStubX, pi.endStubY ] ] }[axis]; }, opposite : function(axis) { var pi = paintInfo, otherAxis = {"x":"y","y":"x"}[axis], stub = "Stub" + axis.toUpperCase(), otherStub = "Stub" + otherAxis.toUpperCase(), otherStartStub = pi["start" + otherStub], startStub = pi["start" + stub], otherEndStub = pi["end" + otherStub], endStub = pi["end" + stub], dim = {"x":"height","y":"width"}[axis], comparator = pi["is" + axis.toUpperCase() + "GreaterThanStubTimes2"], idx = axis == "x" ? 0 : 1; if (params.sourceEndpoint.elementId == params.targetEndpoint.elementId) { var _val = otherStartStub + ((1 - params.sourceAnchor[otherAxis]) * params.sourceInfo[dim]) + _super.maxStub; return { "x":[ [ startStub, _val ], [ endStub, _val ] ], "y":[ [ _val, startStub ], [ _val, endStub ] ] }[axis]; } else if (!comparator || (pi.so[idx] == 1 && startStub > endStub) || (pi.so[idx] == -1 && startStub < endStub)) { return { "x":[[ startStub, midy ], [ endStub, midy ]], "y":[[ midx, startStub ], [ midx, endStub ]] }[axis]; } else if ((pi.so[idx] == 1 && startStub < endStub) || (pi.so[idx] == -1 && startStub > endStub)) { return { "x":[[ midx, pi.sy ], [ midx, pi.ty ]], "y":[[ pi.sx, midy ], [ pi.tx, midy ]] }[axis]; } } }, p = lineCalculators[paintInfo.anchorOrientation](paintInfo.sourceAxis); if (p) { for (var i = 0; i < p.length; i++) { addSegment(segments, p[i][0], p[i][1]); } } addSegment(segments, paintInfo.endStubX, paintInfo.endStubY); // end stub addSegment(segments, paintInfo.tx, paintInfo.ty); writeSegments(segments, paintInfo); }; this.getPath = function() { var _last = null, _lastAxis = null, s = [], segs = userSuppliedSegments || segments; for (var i = 0; i < segs.length; i++) { var seg = segs[i], axis = seg[4], axisIndex = (axis == "v" ? 3 : 2); if (_last != null && _lastAxis === axis) { _last[axisIndex] = seg[axisIndex]; } else { if (seg[0] != seg[2] || seg[1] != seg[3]) { s.push({ start:[ seg[0], seg[1] ], end:[ seg[2], seg[3] ] }); _last = seg; _lastAxis = seg[4]; } } } return s; }; this.setPath = function(path) { userSuppliedSegments = []; for (var i = 0; i < path.length; i++) { var lx = path[i].start[0], ly = path[i].start[1], x = path[i].end[0], y = path[i].end[1], o = lx == x ? "v" : "h", sgnx = sgn(x - lx), sgny = sgn(y - ly); userSuppliedSegments.push([lx, ly, x, y, o, sgnx, sgny]); } }; }; })();/* * jsPlumb * * Title:jsPlumb 1.4.0 * * Provides a way to visually connect elements on an HTML page, using either SVG, Canvas * elements, or VML. * * This file contains the VML renderers. * * Copyright (c) 2010 - 2013 Simon Porritt (http://jsplumb.org) * * http://jsplumb.org * http://github.com/sporritt/jsplumb * http://code.google.com/p/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ;(function() { // http://ajaxian.com/archives/the-vml-changes-in-ie-8 // http://www.nczonline.net/blog/2010/01/19/internet-explorer-8-document-and-browser-modes/ // http://www.louisremi.com/2009/03/30/changes-in-vml-for-ie8-or-what-feature-can-the-ie-dev-team-break-for-you-today/ var vmlAttributeMap = { "stroke-linejoin":"joinstyle", "joinstyle":"joinstyle", "endcap":"endcap", "miterlimit":"miterlimit" }, jsPlumbStylesheet = null; if (document.createStyleSheet && document.namespaces) { var ruleClasses = [ ".jsplumb_vml", "jsplumb\\:textbox", "jsplumb\\:oval", "jsplumb\\:rect", "jsplumb\\:stroke", "jsplumb\\:shape", "jsplumb\\:group" ], rule = "behavior:url(#default#VML);position:absolute;"; jsPlumbStylesheet = document.createStyleSheet(); for (var i = 0; i < ruleClasses.length; i++) jsPlumbStylesheet.addRule(ruleClasses[i], rule); // in this page it is also mentioned that IE requires the extra arg to the namespace // http://www.louisremi.com/2009/03/30/changes-in-vml-for-ie8-or-what-feature-can-the-ie-dev-team-break-for-you-today/ // but someone commented saying they didn't need it, and it seems jsPlumb doesnt need it either. // var iev = document.documentMode; //if (!iev || iev < 8) document.namespaces.add("jsplumb", "urn:schemas-microsoft-com:vml"); //else // document.namespaces.add("jsplumb", "urn:schemas-microsoft-com:vml", "#default#VML"); } jsPlumb.vml = {}; var scale = 1000, _groupMap = {}, _getGroup = function(container, connectorClass) { var id = jsPlumb.getId(container), g = _groupMap[id]; if(!g) { g = _node("group", [0,0,scale, scale], {"class":connectorClass}); //g.style.position=absolute; //g["coordsize"] = "1000,1000"; g.style.backgroundColor="red"; _groupMap[id] = g; jsPlumb.appendElement(g, container); // todo if this gets reinstated, remember to use the current jsplumb instance. //document.body.appendChild(g); } return g; }, _atts = function(o, atts) { for (var i in atts) { // IE8 fix: setattribute does not work after an element has been added to the dom! // http://www.louisremi.com/2009/03/30/changes-in-vml-for-ie8-or-what-feature-can-the-ie-dev-team-break-for-you-today/ //o.setAttribute(i, atts[i]); /*There is an additional problem when accessing VML elements by using get/setAttribute. The simple solution is following: if (document.documentMode==8) { ele.opacity=1; } else { ele.setAttribute(‘opacity’,1); } */ o[i] = atts[i]; } }, _node = function(name, d, atts, parent, _jsPlumb, deferToJsPlumbContainer) { atts = atts || {}; var o = document.createElement("jsplumb:" + name); if (deferToJsPlumbContainer) _jsPlumb.appendElement(o, parent); else jsPlumb.CurrentLibrary.appendElement(o, parent); o.className = (atts["class"] ? atts["class"] + " " : "") + "jsplumb_vml"; _pos(o, d); _atts(o, atts); return o; }, _pos = function(o,d, zIndex) { o.style.left = d[0] + "px"; o.style.top = d[1] + "px"; o.style.width= d[2] + "px"; o.style.height= d[3] + "px"; o.style.position = "absolute"; if (zIndex) o.style.zIndex = zIndex; }, _conv = jsPlumb.vml.convertValue = function(v) { return Math.floor(v * scale); }, // tests if the given style is "transparent" and then sets the appropriate opacity node to 0 if so, // or 1 if not. TODO in the future, support variable opacity. _maybeSetOpacity = function(styleToWrite, styleToCheck, type, component) { if ("transparent" === styleToCheck) component.setOpacity(type, "0.0"); else component.setOpacity(type, "1.0"); }, _applyStyles = function(node, style, component, _jsPlumb) { var styleToWrite = {}; if (style.strokeStyle) { styleToWrite["stroked"] = "true"; var strokeColor = jsPlumbUtil.convertStyle(style.strokeStyle, true); styleToWrite["strokecolor"] = strokeColor; _maybeSetOpacity(styleToWrite, strokeColor, "stroke", component); styleToWrite["strokeweight"] = style.lineWidth + "px"; } else styleToWrite["stroked"] = "false"; if (style.fillStyle) { styleToWrite["filled"] = "true"; var fillColor = jsPlumbUtil.convertStyle(style.fillStyle, true); styleToWrite["fillcolor"] = fillColor; _maybeSetOpacity(styleToWrite, fillColor, "fill", component); } else styleToWrite["filled"] = "false"; if(style["dashstyle"]) { if (component.strokeNode == null) { component.strokeNode = _node("stroke", [0,0,0,0], { dashstyle:style["dashstyle"] }, node, _jsPlumb); } else component.strokeNode.dashstyle = style["dashstyle"]; } else if (style["stroke-dasharray"] && style["lineWidth"]) { var sep = style["stroke-dasharray"].indexOf(",") == -1 ? " " : ",", parts = style["stroke-dasharray"].split(sep), styleToUse = ""; for(var i = 0; i < parts.length; i++) { styleToUse += (Math.floor(parts[i] / style.lineWidth) + sep); } if (component.strokeNode == null) { component.strokeNode = _node("stroke", [0,0,0,0], { dashstyle:styleToUse }, node, _jsPlumb); } else component.strokeNode.dashstyle = styleToUse; } _atts(node, styleToWrite); }, /* * Base class for Vml endpoints and connectors. Extends jsPlumbUIComponent. */ VmlComponent = function() { var self = this, renderer = {}; jsPlumb.jsPlumbUIComponent.apply(this, arguments); this.opacityNodes = { "stroke":null, "fill":null }; this.initOpacityNodes = function(vml) { self.opacityNodes["stroke"] = _node("stroke", [0,0,1,1], {opacity:"0.0"}, vml, self._jsPlumb); self.opacityNodes["fill"] = _node("fill", [0,0,1,1], {opacity:"0.0"}, vml, self._jsPlumb); }; this.setOpacity = function(type, value) { var node = self.opacityNodes[type]; if (node) node["opacity"] = "" + value; }; var displayElements = [ ]; this.getDisplayElements = function() { return displayElements; }; this.appendDisplayElement = function(el, doNotAppendToCanvas) { if (!doNotAppendToCanvas) self.canvas.parentNode.appendChild(el); displayElements.push(el); }; }, /* * Base class for Vml connectors. extends VmlComponent. */ VmlConnector = jsPlumb.ConnectorRenderers.vml = function(params) { var self = this; self.strokeNode = null; self.canvas = null; var _super = VmlComponent.apply(this, arguments); var clazz = self._jsPlumb.connectorClass + (params.cssClass ? (" " + params.cssClass) : ""); this.paint = function(style) { if (style !== null) { var segments = self.getSegments(), p = { "path":"" }, d = [self.x,self.y,self.w,self.h]; // create path from segments. for (var i = 0; i < segments.length; i++) { p.path += jsPlumb.Segments.vml.SegmentRenderer.getPath(segments[i]); p.path += " "; } //* if (style.outlineColor) { var outlineWidth = style.outlineWidth || 1, outlineStrokeWidth = style.lineWidth + (2 * outlineWidth), outlineStyle = { strokeStyle : jsPlumbUtil.convertStyle(style.outlineColor), lineWidth : outlineStrokeWidth }; for (var aa in vmlAttributeMap) outlineStyle[aa] = style[aa]; if (self.bgCanvas == null) { p["class"] = clazz; p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale); self.bgCanvas = _node("shape", d, p, params.parent, self._jsPlumb, true); _pos(self.bgCanvas, d); self.appendDisplayElement(self.bgCanvas, true); self.attachListeners(self.bgCanvas, self); self.initOpacityNodes(self.bgCanvas, ["stroke"]); } else { p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale); _pos(self.bgCanvas, d); _atts(self.bgCanvas, p); } _applyStyles(self.bgCanvas, outlineStyle, self); } //*/ if (self.canvas == null) { p["class"] = clazz; p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale); self.canvas = _node("shape", d, p, params.parent, self._jsPlumb, true); //var group = _getGroup(params.parent); // test of append everything to a group //group.appendChild(self.canvas); // sort of works but not exactly; //params["_jsPlumb"].appendElement(self.canvas, params.parent); //before introduction of groups self.appendDisplayElement(self.canvas, true); self.attachListeners(self.canvas, self); self.initOpacityNodes(self.canvas, ["stroke"]); } else { p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale); _pos(self.canvas, d); _atts(self.canvas, p); } _applyStyles(self.canvas, style, self, self._jsPlumb); } }; this.reattachListeners = function() { if (self.canvas) self.reattachListenersForElement(self.canvas, self); }; }, /* * * Base class for Vml Endpoints. extends VmlComponent. * */ VmlEndpoint = window.VmlEndpoint = function(params) { VmlComponent.apply(this, arguments); var vml = null, self = this, opacityStrokeNode = null, opacityFillNode = null; self.canvas = document.createElement("div"); self.canvas.style["position"] = "absolute"; var clazz = self._jsPlumb.endpointClass + (params.cssClass ? (" " + params.cssClass) : ""); //var group = _getGroup(params.parent); //group.appendChild(self.canvas); params["_jsPlumb"].appendElement(self.canvas, params.parent); this.paint = function(style, anchor) { var p = { }; jsPlumb.sizeCanvas(self.canvas, self.x, self.y, self.w, self.h); if (vml == null) { p["class"] = clazz; vml = self.getVml([0,0, self.w, self.h], p, anchor, self.canvas, self._jsPlumb); self.attachListeners(vml, self); self.appendDisplayElement(vml, true); self.appendDisplayElement(self.canvas, true); self.initOpacityNodes(vml, ["fill"]); } else { _pos(vml, [0,0, self.w, self.h]); _atts(vml, p); } _applyStyles(vml, style, self); }; this.reattachListeners = function() { if (vml) self.reattachListenersForElement(vml, self); }; }; // ******************************* vml segments ***************************************************** jsPlumb.Segments.vml = { SegmentRenderer : { getPath : function(segment) { return ({ "Straight":function(segment) { var d = segment.params; return "m" + _conv(d.x1) + "," + _conv(d.y1) + " l" + _conv(d.x2) + "," + _conv(d.y2) + " e"; }, "Bezier":function(segment) { var d = segment.params; return "m" + _conv(d.x1) + "," + _conv(d.y1) + " c" + _conv(d.cp1x) + "," + _conv(d.cp1y) + "," + _conv(d.cp2x) + "," + _conv(d.cp2y) + "," + _conv(d.x2) + "," + _conv(d.y2) + " e"; }, "Arc":function(segment) { var d = segment.params, xmin = Math.min(d.x1, d.x2), xmax = Math.max(d.x1, d.x2), ymin = Math.min(d.y1, d.y2), ymax = Math.max(d.y1, d.y2), sf = segment.anticlockwise ? 1 : 0, pathType = (segment.anticlockwise ? "at " : "wa "), makePosString = function() { var xy = [ null, [ function() { return [xmin, ymin ];}, function() { return [xmin - d.r, ymin - d.r ];}], [ function() { return [xmin - d.r, ymin ];}, function() { return [xmin, ymin - d.r ];}], [ function() { return [xmin - d.r, ymin - d.r ];}, function() { return [xmin, ymin ];}], [ function() { return [xmin, ymin - d.r ];}, function() { return [xmin - d.r, ymin ];}] ][segment.segment][sf](); return _conv(xy[0]) + "," + _conv(xy[1]) + "," + _conv(xy[0] + (2*d.r)) + "," + _conv(xy[1] + (2*d.r)); }; return pathType + makePosString() + "," + _conv(d.x1) + "," + _conv(d.y1) + "," + _conv(d.x2) + "," + _conv(d.y2) + " e"; } })[segment.type](segment); } } }; // ******************************* /vml segments ***************************************************** // ******************************* vml endpoints ***************************************************** jsPlumb.Endpoints.vml.Dot = function() { jsPlumb.Endpoints.Dot.apply(this, arguments); VmlEndpoint.apply(this, arguments); this.getVml = function(d, atts, anchor, parent, _jsPlumb) { return _node("oval", d, atts, parent, _jsPlumb); }; }; jsPlumb.Endpoints.vml.Rectangle = function() { jsPlumb.Endpoints.Rectangle.apply(this, arguments); VmlEndpoint.apply(this, arguments); this.getVml = function(d, atts, anchor, parent, _jsPlumb) { return _node("rect", d, atts, parent, _jsPlumb); }; }; /* * VML Image Endpoint is the same as the default image endpoint. */ jsPlumb.Endpoints.vml.Image = jsPlumb.Endpoints.Image; /** * placeholder for Blank endpoint in vml renderer. */ jsPlumb.Endpoints.vml.Blank = jsPlumb.Endpoints.Blank; // ******************************* /vml endpoints ***************************************************** // ******************************* vml overlays ***************************************************** /** * VML Label renderer. uses the default label renderer (which adds an element to the DOM) */ jsPlumb.Overlays.vml.Label = jsPlumb.Overlays.Label; /** * VML Custom renderer. uses the default Custom renderer (which adds an element to the DOM) */ jsPlumb.Overlays.vml.Custom = jsPlumb.Overlays.Custom; /** * Abstract VML arrow superclass */ var AbstractVmlArrowOverlay = function(superclass, originalArgs) { superclass.apply(this, originalArgs); VmlComponent.apply(this, originalArgs); var self = this, path = null; self.canvas = null; self.isAppendedAtTopLevel = true; var getPath = function(d) { return "m " + _conv(d.hxy.x) + "," + _conv(d.hxy.y) + " l " + _conv(d.tail[0].x) + "," + _conv(d.tail[0].y) + " " + _conv(d.cxy.x) + "," + _conv(d.cxy.y) + " " + _conv(d.tail[1].x) + "," + _conv(d.tail[1].y) + " x e"; }; this.paint = function(params, containerExtents) { var p = {}, d = params.d, connector = params.component; if (params.strokeStyle) { p["stroked"] = "true"; p["strokecolor"] = jsPlumbUtil.convertStyle(params.strokeStyle, true); } if (params.lineWidth) p["strokeweight"] = params.lineWidth + "px"; if (params.fillStyle) { p["filled"] = "true"; p["fillcolor"] = params.fillStyle; } var xmin = Math.min(d.hxy.x, d.tail[0].x, d.tail[1].x, d.cxy.x), ymin = Math.min(d.hxy.y, d.tail[0].y, d.tail[1].y, d.cxy.y), xmax = Math.max(d.hxy.x, d.tail[0].x, d.tail[1].x, d.cxy.x), ymax = Math.max(d.hxy.y, d.tail[0].y, d.tail[1].y, d.cxy.y), w = Math.abs(xmax - xmin), h = Math.abs(ymax - ymin), dim = [xmin, ymin, w, h]; // for VML, we create overlays using shapes that have the same dimensions and // coordsize as their connector - overlays calculate themselves relative to the // connector (it's how it's been done since the original canvas implementation, because // for canvas that makes sense). p["path"] = getPath(d); p["coordsize"] = (connector.w * scale) + "," + (connector.h * scale); dim[0] = connector.x; dim[1] = connector.y; dim[2] = connector.w; dim[3] = connector.h; if (self.canvas == null) { var overlayClass = connector._jsPlumb.overlayClass || ""; var clazz = originalArgs && (originalArgs.length == 1) ? (originalArgs[0].cssClass || "") : ""; p["class"] = clazz + " " + overlayClass; self.canvas = _node("shape", dim, p, connector.canvas.parentNode, connector._jsPlumb, true); connector.appendDisplayElement(self.canvas, true); self.attachListeners(self.canvas, connector); self.attachListeners(self.canvas, self); } else { _pos(self.canvas, dim); _atts(self.canvas, p); } }; this.reattachListeners = function() { if (self.canvas) self.reattachListenersForElement(self.canvas, self); }; this.cleanup = function() { if (self.canvas != null) jsPlumb.CurrentLibrary.removeElement(self.canvas); }; }; jsPlumb.Overlays.vml.Arrow = function() { AbstractVmlArrowOverlay.apply(this, [jsPlumb.Overlays.Arrow, arguments]); }; jsPlumb.Overlays.vml.PlainArrow = function() { AbstractVmlArrowOverlay.apply(this, [jsPlumb.Overlays.PlainArrow, arguments]); }; jsPlumb.Overlays.vml.Diamond = function() { AbstractVmlArrowOverlay.apply(this, [jsPlumb.Overlays.Diamond, arguments]); }; // ******************************* /vml overlays ***************************************************** })();/* * jsPlumb * * Title:jsPlumb 1.4.0 * * Provides a way to visually connect elements on an HTML page, using either SVG, Canvas * elements, or VML. * * This file contains the SVG renderers. * * Copyright (c) 2010 - 2013 Simon Porritt (http://jsplumb.org) * * http://jsplumb.org * http://github.com/sporritt/jsplumb * http://code.google.com/p/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ /** * SVG support for jsPlumb. * * things to investigate: * * gradients: https://developer.mozilla.org/en/svg_in_html_introduction * css:http://tutorials.jenkov.com/svg/svg-and-css.html * text on a path: http://www.w3.org/TR/SVG/text.html#TextOnAPath * pointer events: https://developer.mozilla.org/en/css/pointer-events * * IE9 hover jquery: http://forum.jquery.com/topic/1-6-2-broke-svg-hover-events * */ ;(function() { // ************************** SVG utility methods ******************************************** var svgAttributeMap = { "joinstyle":"stroke-linejoin", "stroke-linejoin":"stroke-linejoin", "stroke-dashoffset":"stroke-dashoffset", "stroke-linecap":"stroke-linecap" }, STROKE_DASHARRAY = "stroke-dasharray", DASHSTYLE = "dashstyle", LINEAR_GRADIENT = "linearGradient", RADIAL_GRADIENT = "radialGradient", FILL = "fill", STOP = "stop", STROKE = "stroke", STROKE_WIDTH = "stroke-width", STYLE = "style", NONE = "none", JSPLUMB_GRADIENT = "jsplumb_gradient_", LINE_WIDTH = "lineWidth", ns = { svg:"http://www.w3.org/2000/svg", xhtml:"http://www.w3.org/1999/xhtml" }, _attr = function(node, attributes) { for (var i in attributes) node.setAttribute(i, "" + attributes[i]); }, _node = function(name, attributes) { var n = document.createElementNS(ns.svg, name); attributes = attributes || {}; attributes["version"] = "1.1"; attributes["xmlns"] = ns.xhtml; _attr(n, attributes); return n; }, _pos = function(d) { return "position:absolute;left:" + d[0] + "px;top:" + d[1] + "px"; }, _clearGradient = function(parent) { for (var i = 0; i < parent.childNodes.length; i++) { if (parent.childNodes[i].tagName == LINEAR_GRADIENT || parent.childNodes[i].tagName == RADIAL_GRADIENT) parent.removeChild(parent.childNodes[i]); } }, _updateGradient = function(parent, node, style, dimensions, uiComponent) { var id = JSPLUMB_GRADIENT + uiComponent._jsPlumb.idstamp(); // first clear out any existing gradient _clearGradient(parent); // this checks for an 'offset' property in the gradient, and in the absence of it, assumes // we want a linear gradient. if it's there, we create a radial gradient. // it is possible that a more explicit means of defining the gradient type would be // better. relying on 'offset' means that we can never have a radial gradient that uses // some default offset, for instance. // issue 244 suggested the 'gradientUnits' attribute; without this, straight/flowchart connectors with gradients would // not show gradients when the line was perfectly horizontal or vertical. var g; if (!style.gradient.offset) { g = _node(LINEAR_GRADIENT, {id:id, gradientUnits:"userSpaceOnUse"}); } else { g = _node(RADIAL_GRADIENT, { id:id }); } parent.appendChild(g); // the svg radial gradient seems to treat stops in the reverse // order to how canvas does it. so we want to keep all the maths the same, but // iterate the actual style declarations in reverse order, if the x indexes are not in order. for (var i = 0; i < style.gradient.stops.length; i++) { var styleToUse = uiComponent.segment == 1 || uiComponent.segment == 2 ? i: style.gradient.stops.length - 1 - i, stopColor = jsPlumbUtil.convertStyle(style.gradient.stops[styleToUse][1], true), s = _node(STOP, {"offset":Math.floor(style.gradient.stops[i][0] * 100) + "%", "stop-color":stopColor}); g.appendChild(s); } var applyGradientTo = style.strokeStyle ? STROKE : FILL; node.setAttribute(STYLE, applyGradientTo + ":url(#" + id + ")"); }, _applyStyles = function(parent, node, style, dimensions, uiComponent) { if (style.gradient) { _updateGradient(parent, node, style, dimensions, uiComponent); } else { // make sure we clear any existing gradient _clearGradient(parent); node.setAttribute(STYLE, ""); } node.setAttribute(FILL, style.fillStyle ? jsPlumbUtil.convertStyle(style.fillStyle, true) : NONE); node.setAttribute(STROKE, style.strokeStyle ? jsPlumbUtil.convertStyle(style.strokeStyle, true) : NONE); if (style.lineWidth) { node.setAttribute(STROKE_WIDTH, style.lineWidth); } // in SVG there is a stroke-dasharray attribute we can set, and its syntax looks like // the syntax in VML but is actually kind of nasty: values are given in the pixel // coordinate space, whereas in VML they are multiples of the width of the stroked // line, which makes a lot more sense. for that reason, jsPlumb is supporting both // the native svg 'stroke-dasharray' attribute, and also the 'dashstyle' concept from // VML, which will be the preferred method. the code below this converts a dashstyle // attribute given in terms of stroke width into a pixel representation, by using the // stroke's lineWidth. if (style[DASHSTYLE] && style[LINE_WIDTH] && !style[STROKE_DASHARRAY]) { var sep = style[DASHSTYLE].indexOf(",") == -1 ? " " : ",", parts = style[DASHSTYLE].split(sep), styleToUse = ""; parts.forEach(function(p) { styleToUse += (Math.floor(p * style.lineWidth) + sep); }); node.setAttribute(STROKE_DASHARRAY, styleToUse); } else if(style[STROKE_DASHARRAY]) { node.setAttribute(STROKE_DASHARRAY, style[STROKE_DASHARRAY]); } // extra attributes such as join type, dash offset. for (var i in svgAttributeMap) { if (style[i]) { node.setAttribute(svgAttributeMap[i], style[i]); } } }, _decodeFont = function(f) { var r = /([0-9].)(p[xt])\s(.*)/, bits = f.match(r); return {size:bits[1] + bits[2], font:bits[3]}; }, _classManip = function(el, add, clazz) { var classesToAddOrRemove = clazz.split(" "), className = el.className, curClasses = className.baseVal.split(" "); for (var i = 0; i < classesToAddOrRemove.length; i++) { if (add) { if (curClasses.indexOf(classesToAddOrRemove[i]) == -1) curClasses.push(classesToAddOrRemove[i]); } else { var idx = curClasses.indexOf(classesToAddOrRemove[i]); if (idx != -1) curClasses.splice(idx, 1); } } el.className.baseVal = curClasses.join(" "); }, _addClass = function(el, clazz) { _classManip(el, true, clazz); }, _removeClass = function(el, clazz) { _classManip(el, false, clazz); }, _appendAtIndex = function(svg, path, idx) { if (svg.childNodes.length > idx) { svg.insertBefore(path, svg.childNodes[idx]); } else svg.appendChild(path); }; /** utility methods for other objects to use. */ jsPlumbUtil.svg = { addClass:_addClass, removeClass:_removeClass, node:_node, attr:_attr, pos:_pos }; // ************************** / SVG utility methods ******************************************** /* * Base class for SVG components. */ var SvgComponent = function(params) { var self = this, pointerEventsSpec = params.pointerEventsSpec || "all", renderer = {}; jsPlumb.jsPlumbUIComponent.apply(this, params.originalArgs); self.canvas = null, self.path = null, self.svg = null; var clazz = params.cssClass + " " + (params.originalArgs[0].cssClass || ""), svgParams = { "style":"", "width":0, "height":0, "pointer-events":pointerEventsSpec, "position":"absolute" }; self.svg = _node("svg", svgParams); if (params.useDivWrapper) { self.canvas = document.createElement("div"); self.canvas.style["position"] = "absolute"; jsPlumb.sizeCanvas(self.canvas,0,0,1,1); self.canvas.className = clazz; } else { _attr(self.svg, { "class":clazz }); self.canvas = self.svg; } params._jsPlumb.appendElement(self.canvas, params.originalArgs[0]["parent"]); if (params.useDivWrapper) self.canvas.appendChild(self.svg); // TODO this displayElement stuff is common between all components, across all // renderers. would be best moved to jsPlumbUIComponent. var displayElements = [ self.canvas ]; this.getDisplayElements = function() { return displayElements; }; this.appendDisplayElement = function(el) { displayElements.push(el); }; this.paint = function(style, anchor, extents) { if (style != null) { var xy = [ self.x, self.y ], wh = [ self.w, self.h ], p; if (extents != null) { if (extents.xmin < 0) xy[0] += extents.xmin; if (extents.ymin < 0) xy[1] += extents.ymin; wh[0] = extents.xmax + ((extents.xmin < 0) ? -extents.xmin : 0); wh[1] = extents.ymax + ((extents.ymin < 0) ? -extents.ymin : 0); } if (params.useDivWrapper) { jsPlumb.sizeCanvas(self.canvas, xy[0], xy[1], wh[0], wh[1]); xy[0] = 0, xy[1] = 0; p = _pos([ 0, 0 ]); } else p = _pos([ xy[0], xy[1] ]); renderer.paint.apply(this, arguments); _attr(self.svg, { "style":p, "width": wh[0], "height": wh[1] }); } }; return { renderer:renderer }; }; /* * Base class for SVG connectors. */ var SvgConnector = jsPlumb.ConnectorRenderers.svg = function(params) { var self = this, _super = SvgComponent.apply(this, [ { cssClass:params["_jsPlumb"].connectorClass, originalArgs:arguments, pointerEventsSpec:"none", _jsPlumb:params["_jsPlumb"] } ]); _super.renderer.paint = function(style, anchor, extents) { var segments = self.getSegments(), p = "", offset = [0,0]; if (extents.xmin < 0) offset[0] = -extents.xmin; if (extents.ymin < 0) offset[1] = -extents.ymin; // create path from segments. for (var i = 0; i < segments.length; i++) { p += jsPlumb.Segments.svg.SegmentRenderer.getPath(segments[i]); p += " "; } var a = { d:p, transform:"translate(" + offset[0] + "," + offset[1] + ")", "pointer-events":params["pointer-events"] || "visibleStroke" }, outlineStyle = null, d = [self.x,self.y,self.w,self.h]; // outline style. actually means drawing an svg object underneath the main one. if (style.outlineColor) { var outlineWidth = style.outlineWidth || 1, outlineStrokeWidth = style.lineWidth + (2 * outlineWidth), outlineStyle = jsPlumb.CurrentLibrary.extend({}, style); outlineStyle.strokeStyle = jsPlumbUtil.convertStyle(style.outlineColor); outlineStyle.lineWidth = outlineStrokeWidth; if (self.bgPath == null) { self.bgPath = _node("path", a); _appendAtIndex(self.svg, self.bgPath, 0); self.attachListeners(self.bgPath, self); } else { _attr(self.bgPath, a); } _applyStyles(self.svg, self.bgPath, outlineStyle, d, self); } if (self.path == null) { self.path = _node("path", a); _appendAtIndex(self.svg, self.path, style.outlineColor ? 1 : 0); self.attachListeners(self.path, self); } else { _attr(self.path, a); } _applyStyles(self.svg, self.path, style, d, self); }; this.reattachListeners = function() { if (self.bgPath) self.reattachListenersForElement(self.bgPath, self); if (self.path) self.reattachListenersForElement(self.path, self); }; }; // ******************************* svg segment renderer ***************************************************** jsPlumb.Segments.svg = { SegmentRenderer : { getPath : function(segment) { return ({ "Straight":function() { var d = segment.getCoordinates(); return "M " + d.x1 + " " + d.y1 + " L " + d.x2 + " " + d.y2; }, "Bezier":function() { var d = segment.params; return "M " + d.x1 + " " + d.y1 + " C " + d.cp1x + " " + d.cp1y + " " + d.cp2x + " " + d.cp2y + " " + d.x2 + " " + d.y2; }, "Arc":function() { var d = segment.params, laf = segment.sweep > Math.PI ? 1 : 0, sf = segment.anticlockwise ? 0 : 1; return "M" + segment.x1 + " " + segment.y1 + " A " + segment.radius + " " + d.r + " 0 " + laf + "," + sf + " " + segment.x2 + " " + segment.y2; } })[segment.type](); } } }; // ******************************* /svg segments ***************************************************** /* * Base class for SVG endpoints. */ var SvgEndpoint = window.SvgEndpoint = function(params) { var self = this, _super = SvgComponent.apply(this, [ { cssClass:params["_jsPlumb"].endpointClass, originalArgs:arguments, pointerEventsSpec:"all", useDivWrapper:true, _jsPlumb:params["_jsPlumb"] } ]); _super.renderer.paint = function(style) { var s = jsPlumb.extend({}, style); if (s.outlineColor) { s.strokeWidth = s.outlineWidth; s.strokeStyle = jsPlumbUtil.convertStyle(s.outlineColor, true); } if (self.node == null) { self.node = self.makeNode(s); self.svg.appendChild(self.node); self.attachListeners(self.node, self); } else if (self.updateNode != null) { self.updateNode(self.node); } _applyStyles(self.svg, self.node, s, [ self.x, self.y, self.w, self.h ], self); _pos(self.node, [ self.x, self.y ]); }; this.reattachListeners = function() { if (self.node) self.reattachListenersForElement(self.node, self); }; }; /* * SVG Dot Endpoint */ jsPlumb.Endpoints.svg.Dot = function() { jsPlumb.Endpoints.Dot.apply(this, arguments); SvgEndpoint.apply(this, arguments); this.makeNode = function(style) { return _node("circle", { "cx" : this.w / 2, "cy" : this.h / 2, "r" : this.radius }); }; this.updateNode = function(node) { _attr(node, { "cx":this.w / 2, "cy":this.h / 2, "r":this.radius }); }; }; /* * SVG Rectangle Endpoint */ jsPlumb.Endpoints.svg.Rectangle = function() { jsPlumb.Endpoints.Rectangle.apply(this, arguments); SvgEndpoint.apply(this, arguments); this.makeNode = function(style) { return _node("rect", { "width" : this.w, "height" : this.h }); }; this.updateNode = function(node) { _attr(node, { "width":this.w, "height":this.h }); }; }; /* * SVG Image Endpoint is the default image endpoint. */ jsPlumb.Endpoints.svg.Image = jsPlumb.Endpoints.Image; /* * Blank endpoint in svg renderer is the default Blank endpoint. */ jsPlumb.Endpoints.svg.Blank = jsPlumb.Endpoints.Blank; /* * Label overlay in svg renderer is the default Label overlay. */ jsPlumb.Overlays.svg.Label = jsPlumb.Overlays.Label; /* * Custom overlay in svg renderer is the default Custom overlay. */ jsPlumb.Overlays.svg.Custom = jsPlumb.Overlays.Custom; var AbstractSvgArrowOverlay = function(superclass, originalArgs) { superclass.apply(this, originalArgs); jsPlumb.jsPlumbUIComponent.apply(this, originalArgs); this.isAppendedAtTopLevel = false; var self = this, path = null; this.paint = function(params, containerExtents) { // only draws on connections, not endpoints. if (params.component.svg && containerExtents) { if (path == null) { path = _node("path", { "pointer-events":"all" }); params.component.svg.appendChild(path); self.attachListeners(path, params.component); self.attachListeners(path, self); } var clazz = originalArgs && (originalArgs.length == 1) ? (originalArgs[0].cssClass || "") : "", offset = [0,0]; if (containerExtents.xmin < 0) offset[0] = -containerExtents.xmin; if (containerExtents.ymin < 0) offset[1] = -containerExtents.ymin; _attr(path, { "d" : makePath(params.d), "class" : clazz, stroke : params.strokeStyle ? params.strokeStyle : null, fill : params.fillStyle ? params.fillStyle : null, transform : "translate(" + offset[0] + "," + offset[1] + ")" }); } }; var makePath = function(d) { return "M" + d.hxy.x + "," + d.hxy.y + " L" + d.tail[0].x + "," + d.tail[0].y + " L" + d.cxy.x + "," + d.cxy.y + " L" + d.tail[1].x + "," + d.tail[1].y + " L" + d.hxy.x + "," + d.hxy.y; }; this.reattachListeners = function() { if (path) self.reattachListenersForElement(path, self); }; this.cleanup = function() { if (path != null) jsPlumb.CurrentLibrary.removeElement(path); }; }; jsPlumb.Overlays.svg.Arrow = function() { AbstractSvgArrowOverlay.apply(this, [jsPlumb.Overlays.Arrow, arguments]); }; jsPlumb.Overlays.svg.PlainArrow = function() { AbstractSvgArrowOverlay.apply(this, [jsPlumb.Overlays.PlainArrow, arguments]); }; jsPlumb.Overlays.svg.Diamond = function() { AbstractSvgArrowOverlay.apply(this, [jsPlumb.Overlays.Diamond, arguments]); }; // a test jsPlumb.Overlays.svg.GuideLines = function() { var path = null, self = this, p1_1, p1_2; jsPlumb.Overlays.GuideLines.apply(this, arguments); this.paint = function(params, containerExtents) { if (path == null) { path = _node("path"); params.connector.svg.appendChild(path); self.attachListeners(path, params.connector); self.attachListeners(path, self); p1_1 = _node("path"); params.connector.svg.appendChild(p1_1); self.attachListeners(p1_1, params.connector); self.attachListeners(p1_1, self); p1_2 = _node("path"); params.connector.svg.appendChild(p1_2); self.attachListeners(p1_2, params.connector); self.attachListeners(p1_2, self); } var offset =[0,0]; if (containerExtents.xmin < 0) offset[0] = -containerExtents.xmin; if (containerExtents.ymin < 0) offset[1] = -containerExtents.ymin; _attr(path, { "d" : makePath(params.head, params.tail), stroke : "red", fill : null, transform:"translate(" + offset[0] + "," + offset[1] + ")" }); _attr(p1_1, { "d" : makePath(params.tailLine[0], params.tailLine[1]), stroke : "blue", fill : null, transform:"translate(" + offset[0] + "," + offset[1] + ")" }); _attr(p1_2, { "d" : makePath(params.headLine[0], params.headLine[1]), stroke : "green", fill : null, transform:"translate(" + offset[0] + "," + offset[1] + ")" }); }; var makePath = function(d1, d2) { return "M " + d1.x + "," + d1.y + " L" + d2.x + "," + d2.y; }; }; })();/* * jsPlumb * * Title:jsPlumb 1.4.0 * * Provides a way to visually connect elements on an HTML page, using either SVG, Canvas * elements, or VML. * * This file contains the jQuery adapter. * * Copyright (c) 2010 - 2013 Simon Porritt (http://jsplumb.org) * * http://jsplumb.org * http://github.com/sporritt/jsplumb * http://code.google.com/p/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ /* * the library specific functions, such as find offset, get id, get attribute, extend etc. * the full list is: * * addClass adds a class to the given element * animate calls the underlying library's animate functionality * appendElement appends a child element to a parent element. * bind binds some event to an element * dragEvents a dictionary of event names * extend extend some js object with another. probably not overly necessary; jsPlumb could just do this internally. * getAttribute gets some attribute from an element * getDragObject gets the object that is being dragged, by extracting it from the arguments passed to a drag callback * getDragScope gets the drag scope for a given element. * getDropScope gets the drop scope for a given element. * getElementObject turns an id or dom element into an element object of the underlying library's type. * getOffset gets an element's offset * getOriginalEvent gets the original browser event from some wrapper event * getPageXY gets the page event's xy location. * getParent gets the parent of some element. * getScrollLeft gets an element's scroll left. TODO: is this actually used? will it be? * getScrollTop gets an element's scroll top. TODO: is this actually used? will it be? * getSize gets an element's size. * getUIPosition gets the position of some element that is currently being dragged, by extracting it from the arguments passed to a drag callback. * hasClass returns whether or not the given element has the given class. * initDraggable initializes an element to be draggable * initDroppable initializes an element to be droppable * isDragSupported returns whether or not drag is supported for some element. * isDropSupported returns whether or not drop is supported for some element. * removeClass removes a class from a given element. * removeElement removes some element completely from the DOM. * setAttribute sets an attribute on some element. * setDragFilter sets a filter for some element that indicates areas of the element that should not respond to dragging. * setDraggable sets whether or not some element should be draggable. * setDragScope sets the drag scope for a given element. * setOffset sets the offset of some element. * trigger triggers some event on an element. * unbind unbinds some listener from some element. */ (function($) { //var getBoundingClientRectSupported = "getBoundingClientRect" in document.documentElement; var _getElementObject = function(el) { return typeof(el) == "string" ? $("#" + el) : $(el); }; jsPlumb.CurrentLibrary = { /** * adds the given class to the element object. */ addClass : function(el, clazz) { el = _getElementObject(el); try { if (el[0].className.constructor == SVGAnimatedString) { jsPlumbUtil.svg.addClass(el[0], clazz); } } catch (e) { // SVGAnimatedString not supported; no problem. } try { el.addClass(clazz); } catch (e) { // you probably have jQuery 1.9 and Firefox. } }, /** * animates the given element. */ animate : function(el, properties, options) { el.animate(properties, options); }, /** * appends the given child to the given parent. */ appendElement : function(child, parent) { _getElementObject(parent).append(child); }, /** * executes an ajax call. */ ajax : function(params) { params = params || {}; params.type = params.type || "get"; $.ajax(params); }, /** * event binding wrapper. it just so happens that jQuery uses 'bind' also. yui3, for example, * uses 'on'. */ bind : function(el, event, callback) { el = _getElementObject(el); el.bind(event, callback); }, /** * mapping of drag events for jQuery */ dragEvents : { 'start':'start', 'stop':'stop', 'drag':'drag', 'step':'step', 'over':'over', 'out':'out', 'drop':'drop', 'complete':'complete' }, /** * wrapper around the library's 'extend' functionality (which it hopefully has. * otherwise you'll have to do it yourself). perhaps jsPlumb could do this for you * instead. it's not like its hard. */ extend : function(o1, o2) { return $.extend(o1, o2); }, /** * gets the named attribute from the given element object. */ getAttribute : function(el, attName) { return el.attr(attName); }, getClientXY : function(eventObject) { return [eventObject.clientX, eventObject.clientY]; }, /** * takes the args passed to an event function and returns you an object representing that which is being dragged. */ getDragObject : function(eventArgs) { return eventArgs[1].draggable || eventArgs[1].helper; }, getDragScope : function(el) { return el.draggable("option", "scope"); }, getDropEvent : function(args) { return args[0]; }, getDropScope : function(el) { return el.droppable("option", "scope"); }, /** * gets a DOM element from the given input, which might be a string (in which case we just do document.getElementById), * a selector (in which case we return el[0]), or a DOM element already (we assume this if it's not either of the other * two cases). this is the opposite of getElementObject below. */ getDOMElement : function(el) { if (typeof(el) == "string") return document.getElementById(el); else if (el.context || el.length != null) return el[0]; else return el; }, /** * gets an "element object" from the given input. this means an object that is used by the * underlying library on which jsPlumb is running. 'el' may already be one of these objects, * in which case it is returned as-is. otherwise, 'el' is a String, the library's lookup * function is used to find the element, using the given String as the element's id. * */ getElementObject : _getElementObject, /** * gets the offset for the element object. this should return a js object like this: * * { left:xxx, top: xxx } */ getOffset : function(el) { return el.offset(); }, getOriginalEvent : function(e) { return e.originalEvent; }, getPageXY : function(eventObject) { return [eventObject.pageX, eventObject.pageY]; }, getParent : function(el) { return _getElementObject(el).parent(); }, getScrollLeft : function(el) { return el.scrollLeft(); }, getScrollTop : function(el) { return el.scrollTop(); }, getSelector : function(context, spec) { if (arguments.length == 2) return _getElementObject(context).find(spec); else return $(context); }, /** * gets the size for the element object, in an array : [ width, height ]. */ getSize : function(el) { return [el.outerWidth(), el.outerHeight()]; }, getTagName : function(el) { var e = _getElementObject(el); return e.length > 0 ? e[0].tagName : null; }, /** * takes the args passed to an event function and returns you an object that gives the * position of the object being moved, as a js object with the same params as the result of * getOffset, ie: { left: xxx, top: xxx }. * * different libraries have different signatures for their event callbacks. * see getDragObject as well */ getUIPosition : function(eventArgs, zoom) { zoom = zoom || 1; // this code is a workaround for the case that the element being dragged has a margin set on it. jquery UI passes // in the wrong offset if the element has a margin (it doesn't take the margin into account). the getBoundingClientRect // method, which is in pretty much all browsers now, reports the right numbers. but it introduces a noticeable lag, which // i don't like. /*if ( getBoundingClientRectSupported ) { var r = eventArgs[1].helper[0].getBoundingClientRect(); return { left : r.left, top: r.top }; } else {*/ if (eventArgs.length == 1) { ret = { left: eventArgs[0].pageX, top:eventArgs[0].pageY }; } else { var ui = eventArgs[1], _offset = ui.offset; ret = _offset || ui.absolutePosition; // adjust ui position to account for zoom, because jquery ui does not do this. ui.position.left /= zoom; ui.position.top /= zoom; } return { left:ret.left / zoom, top: ret.top / zoom }; }, hasClass : function(el, clazz) { return el.hasClass(clazz); }, /** * initialises the given element to be draggable. */ initDraggable : function(el, options, isPlumbedComponent, _jsPlumb) { options = options || {}; /* // css3 transforms // http://gungfoo.wordpress.com/2013/02/15/jquery-ui-resizabledraggable-with-transform-scale-set/ options.start = _jsPlumb.wrap(options["start"], function(e, ui) { // TODO why is this 0? ui.position.left = 0; ui.position.top = 0; }); options.drag = _jsPlumb.wrap(options["drag"], function(e, ui) { console.log("original", ui.originalPosition.left, ui.originalPosition.top); console.log("current", ui.position.left, ui.position.top); //var changeLeft = ui.position.left - ui.originalPosition.left; // find change in left //var newLeft = ui.originalPosition.left + (changeLeft * _jsPlumb.getZoom()); // adjust new left by our zoomScale //var changeTop = ui.position.top - ui.originalPosition.top; // find change in top //var newTop = ui.originalPosition.top + (changeTop * _jsPlumb.getZoom()); // adjust new top by our zoomScale //ui.position.left = newLeft; //ui.position.top = newTop; ui.position.left *= _jsPlumb.getZoom(); ui.position.top *= _jsPlumb.getZoom(); }); */ // remove helper directive if present and no override if (!options.doNotRemoveHelper) options.helper = null; if (isPlumbedComponent) options['scope'] = options['scope'] || jsPlumb.Defaults.Scope; el.draggable(options); }, /** * initialises the given element to be droppable. */ initDroppable : function(el, options) { options['scope'] = options['scope'] || jsPlumb.Defaults.Scope; el.droppable(options); }, isAlreadyDraggable : function(el) { return _getElementObject(el).hasClass("ui-draggable"); }, /** * returns whether or not drag is supported (by the library, not whether or not it is disabled) for the given element. */ isDragSupported : function(el, options) { return el.draggable; }, /** * returns whether or not drop is supported (by the library, not whether or not it is disabled) for the given element. */ isDropSupported : function(el, options) { return el.droppable; }, /** * removes the given class from the element object. */ removeClass : function(el, clazz) { el = _getElementObject(el); try { if (el[0].className.constructor == SVGAnimatedString) { jsPlumbUtil.svg.removeClass(el[0], clazz); return; } } catch (e) { // SVGAnimatedString not supported; no problem. } el.removeClass(clazz); }, removeElement : function(element) { _getElementObject(element).remove(); }, setAttribute : function(el, attName, attValue) { el.attr(attName, attValue); }, setDragFilter : function(el, filter) { if (jsPlumb.CurrentLibrary.isAlreadyDraggable(el)) el.draggable("option", "cancel", filter); }, setDraggable : function(el, draggable) { el.draggable("option", "disabled", !draggable); }, setDragScope : function(el, scope) { el.draggable("option", "scope", scope); }, setOffset : function(el, o) { _getElementObject(el).offset(o); }, /** * note that jquery ignores the name of the event you wanted to trigger, and figures it out for itself. * the other libraries do not. yui, in fact, cannot even pass an original event. we have to pull out stuff * from the originalEvent to put in an options object for YUI. * @param el * @param event * @param originalEvent */ trigger : function(el, event, originalEvent) { var h = jQuery._data(_getElementObject(el)[0], "handle"); h(originalEvent); }, unbind : function(el, event, callback) { el = _getElementObject(el); el.unbind(event, callback); } }; $(document).ready(jsPlumb.init); })(jQuery); (function(){"undefined"==typeof Math.sgn&&(Math.sgn=function(a){return 0==a?0:0<a?1:-1});var q={subtract:function(a,b){return{x:a.x-b.x,y:a.y-b.y}},dotProduct:function(a,b){return a.x*b.x+a.y*b.y},square:function(a){return Math.sqrt(a.x*a.x+a.y*a.y)},scale:function(a,b){return{x:a.x*b,y:a.y*b}}},B=Math.pow(2,-65),x=function(a,b){for(var f=[],d=b.length-1,g=2*d-1,h=[],e=[],m=[],k=[],l=[[1,0.6,0.3,0.1],[0.4,0.6,0.6,0.4],[0.1,0.3,0.6,1]],c=0;c<=d;c++)h[c]=q.subtract(b[c],a);for(c=0;c<=d-1;c++)e[c]=q.subtract(b[c+ 1],b[c]),e[c]=q.scale(e[c],3);for(c=0;c<=d-1;c++)for(var n=0;n<=d;n++)m[c]||(m[c]=[]),m[c][n]=q.dotProduct(e[c],h[n]);for(c=0;c<=g;c++)k[c]||(k[c]=[]),k[c].y=0,k[c].x=parseFloat(c)/g;g=d-1;for(h=0;h<=d+g;h++){c=Math.max(0,h-g);for(e=Math.min(h,d);c<=e;c++)j=h-c,k[c+j].y+=m[j][c]*l[j][c]}d=b.length-1;k=u(k,2*d-1,f,0);g=q.subtract(a,b[0]);m=q.square(g);for(c=l=0;c<k;c++)g=q.subtract(a,v(b,d,f[c],null,null)),g=q.square(g),g<m&&(m=g,l=f[c]);g=q.subtract(a,b[d]);g=q.square(g);g<m&&(m=g,l=1);return{location:l, distance:m}},u=function(a,b,f,d){var g=[],h=[],e=[],m=[],k=0,l,c;c=Math.sgn(a[0].y);for(var n=1;n<=b;n++)l=Math.sgn(a[n].y),l!=c&&k++,c=l;switch(k){case 0:return 0;case 1:if(64<=d)return f[0]=(a[0].x+a[b].x)/2,1;var r,p,k=a[0].y-a[b].y;c=a[b].x-a[0].x;n=a[0].x*a[b].y-a[b].x*a[0].y;l=max_distance_below=0;for(r=1;r<b;r++)p=k*a[r].x+c*a[r].y+n,p>l?l=p:p<max_distance_below&&(max_distance_below=p);p=c;r=0*p-1*k;l=(1*(n-l)-0*p)*(1/r);p=c;c=n-max_distance_below;r=0*p-1*k;k=(1*c-0*p)*(1/r);c=Math.min(l,k); if(Math.max(l,k)-c<B)return e=a[b].x-a[0].x,m=a[b].y-a[0].y,f[0]=0+1*(e*(a[0].y-0)-m*(a[0].x-0))*(1/(0*e-1*m)),1}v(a,b,0.5,g,h);a=u(g,b,e,d+1);b=u(h,b,m,d+1);for(d=0;d<a;d++)f[d]=e[d];for(d=0;d<b;d++)f[d+a]=m[d];return a+b},v=function(a,b,f,d,g){for(var h=[[]],e=0;e<=b;e++)h[0][e]=a[e];for(a=1;a<=b;a++)for(e=0;e<=b-a;e++)h[a]||(h[a]=[]),h[a][e]||(h[a][e]={}),h[a][e].x=(1-f)*h[a-1][e].x+f*h[a-1][e+1].x,h[a][e].y=(1-f)*h[a-1][e].y+f*h[a-1][e+1].y;if(null!=d)for(e=0;e<=b;e++)d[e]=h[e][0];if(null!=g)for(e= 0;e<=b;e++)g[e]=h[b-e][e];return h[b][0]},y={},s=function(a,b){var f,d=a.length-1;f=y[d];if(!f){f=[];var g=function(a){return function(){return a}},h=function(){return function(a){return a}},e=function(){return function(a){return 1-a}},m=function(a){return function(b){for(var c=1,d=0;d<a.length;d++)c*=a[d](b);return c}};f.push(new function(){return function(a){return Math.pow(a,d)}});for(var k=1;k<d;k++){for(var l=[new g(d)],c=0;c<d-k;c++)l.push(new h);for(c=0;c<k;c++)l.push(new e);f.push(new m(l))}f.push(new function(){return function(a){return Math.pow(1- a,d)}});y[d]=f}for(e=h=g=0;e<a.length;e++)g+=a[e].x*f[e](b),h+=a[e].y*f[e](b);return{x:g,y:h}},z=function(a,b){return Math.sqrt(Math.pow(a.x-b.x,2)+Math.pow(a.y-b.y,2))},A=function(a){return a[0].x==a[1].x&&a[0].y==a[1].y},t=function(a,b,f){if(A(a))return{point:a[0],location:b};for(var d=s(a,b),g=0,h=0<f?1:-1,e=null;g<Math.abs(f);)b+=0.005*h,e=s(a,b),g+=z(e,d),d=e;return{point:e,location:b}},w=function(a,b){var f=s(a,b),d=s(a.slice(0,a.length-1),b),g=d.y-f.y,f=d.x-f.x;return 0==g?Infinity:Math.atan(g/ f)};window.jsBezier={distanceFromCurve:x,gradientAtPoint:w,gradientAtPointAlongCurveFrom:function(a,b,f){b=t(a,b,f);1<b.location&&(b.location=1);0>b.location&&(b.location=0);return w(a,b.location)},nearestPointOnCurve:function(a,b){var f=x(a,b);return{point:v(b,b.length-1,f.location,null,null),location:f.location}},pointOnCurve:s,pointAlongCurveFrom:function(a,b,f){return t(a,b,f).point},perpendicularToCurveAt:function(a,b,f,d){b=t(a,b,null==d?0:d);a=w(a,b.location);d=Math.atan(-1/a);a=f/2*Math.sin(d); f=f/2*Math.cos(d);return[{x:b.point.x+f,y:b.point.y+a},{x:b.point.x-f,y:b.point.y-a}]},locationAlongCurveFrom:function(a,b,f){return t(a,b,f).location},getLength:function(a){if(A(a))return 0;for(var b=s(a,0),f=0,d=0,g=null;1>d;)d+=0.005,g=s(a,d),f+=z(g,b),b=g;return f}}})();
/* Copyright (c) 2006-2011 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the Clear BSD license. * See http://svn.openlayers.org/trunk/openlayers/license.txt for the * full text of the license. */ /** * @requires OpenLayers/Layer.js * @requires OpenLayers/Tile/InlineXhtml.js */ /** * Class: OpenLayers.Layer.ScalableInlineXhtml * Instances of OpenLayers.Layer.ScalableInlineXhtml are used to display data from a * scalable xhtml service or file as a map layer. Create a new xhtml layer with the * <OpenLayers.Layer.ScalableInlineXhtml> constructor. Inherits from <OpenLayers.Layer>. */ OpenLayers.Layer.ScalableInlineXhtml = OpenLayers.Class(OpenLayers.Layer, { /** * Property: isHtmlLayer * {boolean} If true, the incomming content will be treated as html * and the browsers html parser will be used. If false (default), * the content will first be treated (parsed) as xhtml. * Applied to Layer tiles. * Defaults to; false. */ isHtmlLayer: false, /** * Property: fallbackToHtmlLayer * {boolean} If true (and isHtmlLayer is false), the * incomming content will be treated as html should the * initial xhtml parsing fail. Only applies when isHtmlLayer is * false. Applied to Layer tiles * Defaults to; false. */ fallbackToHtmlLayer: false, /** * Property: overflow * {DOMElement} Overflow style for layer tiles. * Applied to Layer tiles. *Defauls to: "hidden". */ overflow: 'hidden', /** * Property: pointerEvents * {DOMElement} Pointer-Events style for layer. * Applied to Layer. */ pointerEvents: null, /** * Property: xhtmlContainerId * {string} String used to search xhtml content for a matching * element having the specified id attribute. Only child nodes of that * element will be imported into the tile. * Applied to Layer tiles. */ xhtmlContainerId: null, /** * Property: sendIdParams * {boolean} indicates whether map, layer and tile Id * parameters are to be passed as the url request. * Applied to Layer tiles. */ sendIdParams: false, /** * Property: evaluatedParams * {object} hash table of parameters to be passed as * part of the url request. Parameters are evaluated * prior to appending to request. Applied to Layer tiles. */ evaluatedParams: null, /** * Property: url * {String} URL of the image to use */ url: null, /** * Property: extent * {<OpenLayers.Bounds>} The image bounds in map units. This extent will * also be used as the default maxExtent for the layer. If you wish * to have a maxExtent that is different than the image extent, set the * maxExtent property of the options argument (as with any other layer). */ extent: null, /** * Property: size * {<OpenLayers.Size>} The image size in pixels as original unscaled where * the viewport corresponds to the specified extent. */ size: null, /** * Property: tile * {<OpenLayers.Tile.InlineXhtml>} */ tile: null, /** * Property: aspectRatio * {Float} The ratio of height/width represented by a single pixel in the * graphic */ aspectRatio: null, /** * Constructor: OpenLayers.Layer.ScalableInlineXhtml * Create a new scalable xhtml layer * * Parameters: * name - {String} A name for the layer. * url - {String} Relative or absolute path to the xhtml service or file * extent - {<OpenLayers.Bounds>} The extent represented by the image * size - {<OpenLayers.Size>} The size (in pixels) of the image (optional) * options - {Object} Hashtable of extra options to tag onto the layer */ initialize: function(name, url, extent, size, options) { this.url = url; this.extent = extent; this.maxExtent = extent; this.size = size; OpenLayers.Layer.prototype.initialize.apply(this, [name, options]); if (this.size != null) { this.aspectRatio = (this.extent.getHeight() / this.size.h) / (this.extent.getWidth() / this.size.w); } else { this.aspectRatio = this.extent.getHeight() / this.extent.getWidth(); }; if (options.id == null && this.options.pointerEvents) { this.div.style.pointerEvents = this.options.pointerEvents; } }, /** * Method: destroy * Destroy this layer */ destroy: function() { if (this.tile) { this.removeTileMonitoringHooks(this.tile); this.tile.destroy(); this.tile = null; } OpenLayers.Layer.prototype.destroy.apply(this, arguments); }, /** * Method: clone * Create a clone of this layer * * Paramters: * obj - {Object} An optional layer (is this ever used?) * * Returns: * {<OpenLayers.Layer.ScalableInlineXhtml>} An exact copy of this layer */ clone: function(obj) { if(obj == null) { obj = new OpenLayers.Layer.ScalableInlineXhtml(this.name, this.url, this.extent, this.size, this.getOptions()); } //get all additions from superclasses obj = OpenLayers.Layer.prototype.clone.apply(this, [obj]); // copy/set any non-init, non-simple values here return obj; }, /** * APIMethod: setMap * * Parameters: * map - {<OpenLayers.Map>} */ setMap: function(map) { /** * If nothing to do with resolutions has been set, assume a single * resolution determined by ratio*extent/size - if an image has a * pixel aspect ratio different than one (as calculated above), the * image will be stretched in one dimension only. */ if( this.options.maxResolution == null && this.size != null) { this.options.maxResolution = this.aspectRatio * this.extent.getWidth() / this.size.w; } OpenLayers.Layer.prototype.setMap.apply(this, arguments); }, /** * Method: moveTo * Create the tile for the image or resize it for the new resolution * * Parameters: * bounds - {<OpenLayers.Bounds>} * zoomChanged - {Boolean} * dragging - {Boolean} */ moveTo:function(bounds, zoomChanged, dragging) { OpenLayers.Layer.prototype.moveTo.apply(this, arguments); var firstRendering = (this.tile == null); if(zoomChanged || firstRendering) { //determine new tile size this.setTileSize(); //determine new position (upper left corner of new bounds) var ul = new OpenLayers.LonLat(this.extent.left, this.extent.top); var ulPx = this.map.getLayerPxFromLonLat(ul); if(firstRendering) { //create the new tile this.tile = new OpenLayers.Tile.InlineXhtml(this, ulPx, this.extent, null, this.tileSize); this.addTileMonitoringHooks(this.tile); this.tile.draw(); } else { //just resize the tile and set it's new position this.tile.size = this.tileSize.clone(); this.tile.position = ulPx.clone(); // position the frame (content is scalable) this.tile.positionFrame(); } } }, /** * Set the tile size based on the map size. */ setTileSize: function() { var tileWidth = this.extent.getWidth() / this.map.getResolution(); var tileHeight = this.extent.getHeight() / this.map.getResolution(); this.tileSize = new OpenLayers.Size(tileWidth, tileHeight); }, /** * Method: addTileMonitoringHooks * This function takes a tile as input and adds the appropriate hooks to * the tile so that the layer can keep track of the loading tiles. * * Parameters: * tile - {<OpenLayers.Tile>} */ addTileMonitoringHooks: function(tile) { tile.onLoadStart = function() { this.events.triggerEvent("loadstart"); }; tile.events.register("loadstart", this, tile.onLoadStart); tile.onLoadEnd = function() { this.events.triggerEvent("loadend"); }; tile.events.register("loadend", this, tile.onLoadEnd); tile.events.register("unload", this, tile.onLoadEnd); }, /** * Method: removeTileMonitoringHooks * This function takes a tile as input and removes the tile hooks * that were added in <addTileMonitoringHooks>. * * Parameters: * tile - {<OpenLayers.Tile>} */ removeTileMonitoringHooks: function(tile) { tile.unload(); tile.events.un({ "loadstart": tile.onLoadStart, "loadend": tile.onLoadEnd, "unload": tile.onLoadEnd, scope: this }); }, /** * APIMethod: setUrl * * Parameters: * newUrl - {String} */ setUrl: function(newUrl) { this.url = newUrl; this.tile.draw(); }, /** * APIMethod: getURL * Return the base url for the image or xhtml service. The tile class * may add additional parameters. * * Parameters: * bounds - {<OpenLayers.Bounds>} */ getURL: function(bounds) { return this.url; }, CLASS_NAME: "OpenLayers.Layer.ScalableInlineXhtml" });
/*global describe beforeEach it expect */ define([ 'angular', 'angularMocks', 'app' ], function(angular, mocks, app) { 'use strict'; describe('directives', function() { beforeEach(mocks.module('immersive.directives')); describe('app-version', function() { it('should print current version', function() { mocks.module(function($provide) { $provide.value('version', 'TEST_VER'); }); mocks.inject(function($compile, $rootScope) { var element = $compile('<span app-version></span>')($rootScope); expect(element.text()).toEqual('TEST_VER'); }); }); }); }); });
var mathlib = require('./mathlib')(); console.log(mathlib); mathlib.add(1,2); mathlib.multiply(2,2); mathlib.square(5); mathlib.random(1,35);
"use strict"; exports.__esModule = true; exports.getBatch = exports.setBatch = void 0; // Default to a dummy "batch" implementation that just runs the callback function defaultNoopBatch(callback) { callback(); } var batch = defaultNoopBatch; // Allow injecting another batching function later var setBatch = function setBatch(newBatch) { return batch = newBatch; }; // Supply a getter just to skip dealing with ESM bindings exports.setBatch = setBatch; var getBatch = function getBatch() { return batch; }; exports.getBatch = getBatch;
/*! * froala_editor v4.0.8 (https://www.froala.com/wysiwyg-editor) * License https://froala.com/wysiwyg-editor/terms/ * Copyright 2014-2021 Froala Labs */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('froala-editor')) : typeof define === 'function' && define.amd ? define(['froala-editor'], factory) : (factory(global.FroalaEditor)); }(this, (function (FE) { 'use strict'; FE = FE && FE.hasOwnProperty('default') ? FE['default'] : FE; FE.LANGUAGE['vi'] = { translation: { // Place holder 'Type something': "Vi\u1EBFt \u0111i\u1EC1u g\xEC \u0111\xF3...", // Basic formatting 'Bold': "\u0110\u1EADm", 'Italic': "Nghi\xEAng", 'Underline': "G\u1EA1ch ch\xE2n", 'Strikethrough': "G\u1EA1ch ngang ch\u1EEF", // Main buttons 'Insert': "Ch\xE8n", 'Delete': "X\xF3a", 'Cancel': "H\u1EE7y", 'OK': 'OK', 'Back': "Tr\u1EDF v\u1EC1", 'Remove': "X\xF3a", 'More': "Th\xEAm", 'Update': "C\u1EADp nh\u1EADt", 'Style': "Ki\u1EC3u", // Font 'Font Family': "Ph\xF4ng ch\u1EEF", 'Font Size': "C\u1EE1 ch\u1EEF", // Colors 'Colors': "M\xE0u s\u1EAFc", 'Background': "N\u1EC1n", 'Text': "Ch\u1EEF", 'HEX Color': 'Màu hex', // Paragraphs 'Paragraph Format': "\u0110\u1ECBnh d\u1EA1ng \u0111o\u1EA1n v\u0103n b\u1EA3n", 'Normal': 'Normal', 'Code': 'Code', 'Heading 1': 'Heading 1', 'Heading 2': 'Heading 2', 'Heading 3': 'Heading 3', 'Heading 4': 'Heading 4', // Style 'Paragraph Style': "Ki\u1EC3u \u0111o\u1EA1n v\u0103n b\u1EA3n", 'Inline Style': "Ki\u1EC3u d\xF2ng", // Alignment 'Align': "C\u0103n ch\u1EC9nh", 'Align Left': "C\u0103n tr\xE1i", 'Align Center': "C\u0103n gi\u1EEFa", 'Align Right': "C\u0103n ph\u1EA3i", 'Align Justify': "C\u0103n \u0111\u1EC1u", 'None': "Kh\xF4ng", // Lists 'Ordered List': "Danh s\xE1ch theo th\u1EE9 t\u1EF1", 'Unordered List': "Danh s\xE1ch li\u1EC7t k\xEA", // Indent 'Decrease Indent': "Gi\u1EA3m c\u0103n l\u1EC1", 'Increase Indent': "T\u0103ng c\u0103n l\u1EC1", // Links 'Insert Link': "Ch\xE8n link", 'Open in new tab': "M\u1EDF trong tab m\u1EDBi", 'Open Link': "M\u1EDF link", 'Edit Link': "S\u1EEDa link", 'Unlink': "B\u1ECF link", 'Choose Link': "Ch\u1ECDn link", // Images 'Insert Image': "Ch\xE8n h\xECnh", 'Upload Image': "T\u1EA3i h\xECnh l\xEAn", 'By URL': "B\u1EB1ng URL", 'Browse': "Duy\u1EC7t file", 'Drop image': "K\xE9o th\u1EA3 h\xECnh", 'or click': "ho\u1EB7c ch\u1ECDn", 'Manage Images': "Qu\u1EA3n l\xFD h\xECnh \u1EA3nh", 'Loading': "\u0110ang t\u1EA3i", 'Deleting': "\u0110ang x\xF3a", 'Tags': 'Tags', 'Are you sure? Image will be deleted.': "B\u1EA1n c\xF3 ch\u1EAFc ch\u1EAFn? H\xECnh \u1EA3nh s\u1EBD b\u1ECB x\xF3a.", 'Replace': "Thay th\u1EBF", 'Uploading': "\u0110ang t\u1EA3i l\xEAn", 'Loading image': "\u0110ang t\u1EA3i h\xECnh \u1EA3nh", 'Display': "Hi\u1EC3n th\u1ECB", 'Inline': "C\xF9ng d\xF2ng v\u1EDBi ch\u1EEF", 'Break Text': "Kh\xF4ng c\xF9ng d\xF2ng v\u1EDBi ch\u1EEF", 'Alternative Text': "Thay th\u1EBF ch\u1EEF", 'Change Size': "Thay \u0111\u1ED5i k\xEDch c\u1EE1", 'Width': "Chi\u1EC1u r\u1ED9ng", 'Height': "Chi\u1EC1u cao", 'Something went wrong. Please try again.': "C\xF3 l\u1ED7i x\u1EA3y ra. Vui l\xF2ng th\u1EED l\u1EA1i sau.", 'Image Caption': 'Chú thích hình ảnh', 'Advanced Edit': 'Chỉnh sửa tiên tiến', // Video 'Insert Video': "Ch\xE8n video", 'Embedded Code': "M\xE3 nh\xFAng", 'Paste in a video URL': 'Dán vào một url video', 'Drop video': 'Thả video', 'Your browser does not support HTML5 video.': 'Trình duyệt của bạn không hỗ trợ video html5.', 'Upload Video': 'Tải video lên', // Tables 'Insert Table': "Ch\xE8n b\u1EA3ng", 'Table Header': "D\xF2ng \u0111\u1EA7u b\u1EA3ng", 'Remove Table': "X\xF3a b\u1EA3ng", 'Table Style': "Ki\u1EC3u b\u1EA3ng", 'Horizontal Align': "C\u0103n ch\u1EC9nh chi\u1EC1u ngang", 'Row': "D\xF2ng", 'Insert row above': "Ch\xE8n d\xF2ng ph\xEDa tr\xEAn", 'Insert row below': "Ch\xE8n d\xF2ng ph\xEDa d\u01B0\u1EDBi", 'Delete row': "X\xF3a d\xF2ng", 'Column': "C\u1ED9t", 'Insert column before': "Ch\xE8n c\u1ED9t b\xEAn tr\xE1i", 'Insert column after': "Ch\xE8n c\u1ED9t b\xEAn ph\u1EA3i", 'Delete column': "X\xF3a c\u1ED9t", 'Cell': "\xD4 b\u1EA3ng", 'Merge cells': "G\u1ED9p \xF4", 'Horizontal split': "Chia d\xF2ng", 'Vertical split': "Chia c\u1ED9t", 'Cell Background': "M\xE0u n\u1EC1n", 'Vertical Align': "C\u0103n ch\u1EC9nh chi\u1EC1u d\u1ECDc", 'Top': "Tr\xEAn c\xF9ng", 'Middle': "Gi\u1EEFa", 'Bottom': "D\u01B0\u1EDBi \u0111\xE1y", 'Align Top': "C\u0103n tr\xEAn", 'Align Middle': "C\u0103n gi\u1EEFa", 'Align Bottom': "C\u0103n d\u01B0\u1EDBi", 'Cell Style': "Ki\u1EC3u \xF4", // Files 'Upload File': "T\u1EA3i file l\xEAn", 'Drop file': "K\xE9o th\u1EA3 file", // Emoticons 'Emoticons': "Bi\u1EC3u t\u01B0\u1EE3ng c\u1EA3m x\xFAc", // Line breaker 'Break': "Ng\u1EAFt d\xF2ng", // Math 'Subscript': 'Subscript', 'Superscript': 'Superscript', // Full screen 'Fullscreen': "To\xE0n m\xE0n h\xECnh", // Horizontal line 'Insert Horizontal Line': "Ch\xE8n \u0111\u01B0\u1EDDng k\u1EBB ngang v\u0103n b\u1EA3n", // Clear formatting 'Clear Formatting': "X\xF3a \u0111\u1ECBnh d\u1EA1ng", // Save 'Save': 'Save', // Undo, redo 'Undo': 'Undo', 'Redo': 'Redo', // Select all 'Select All': "Ch\u1ECDn t\u1EA5t c\u1EA3", // Code view 'Code View': "Xem d\u1EA1ng code", // Quote 'Quote': "Tr\xEDch d\u1EABn", 'Increase': "T\u0103ng", 'Decrease': "Gi\u1EA3m", // Quick Insert 'Quick Insert': "Ch\xE8n nhanh", // Spcial Characters 'Special Characters': 'Nhân vật đặc biệt', 'Latin': 'Latin', 'Greek': 'Người Hy Lạp', 'Cyrillic': 'Chữ viết tay', 'Punctuation': 'Chấm câu', 'Currency': 'Tiền tệ', 'Arrows': 'Mũi tên', 'Math': 'Môn Toán', 'Misc': 'Misc', // Print. 'Print': 'In', // Spell Checker. 'Spell Checker': 'Công cụ kiểm tra chính tả', // Help 'Help': 'Cứu giúp', 'Shortcuts': 'Phím tắt', 'Inline Editor': 'Trình biên tập nội tuyến', 'Show the editor': 'Hiển thị trình soạn thảo', 'Common actions': 'Hành động thông thường', 'Copy': 'Sao chép', 'Cut': 'Cắt tỉa', 'Paste': 'Dán', 'Basic Formatting': 'Định dạng cơ bản', 'Increase quote level': 'Tăng mức báo giá', 'Decrease quote level': 'Giảm mức giá', 'Image / Video': 'Hình ảnh / video', 'Resize larger': 'Thay đổi kích thước lớn hơn', 'Resize smaller': 'Thay đổi kích thước nhỏ hơn', 'Table': 'Bàn', 'Select table cell': 'Chọn ô trong bảng', 'Extend selection one cell': 'Mở rộng lựa chọn một ô', 'Extend selection one row': 'Mở rộng lựa chọn một hàng', 'Navigation': 'Dẫn đường', 'Focus popup / toolbar': 'Tập trung popup / thanh công cụ', 'Return focus to previous position': 'Quay trở lại vị trí trước', // Embed.ly 'Embed URL': 'Url nhúng', 'Paste in a URL to embed': 'Dán vào một url để nhúng', // Word Paste. 'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?': 'Nội dung dán là đến từ một tài liệu từ microsoft. bạn có muốn giữ định dạng hoặc làm sạch nó?', 'Keep': 'Giữ', 'Clean': 'Dọn dẹp', 'Word Paste Detected': 'Dán từ được phát hiện', // Character Counter 'Characters': 'Nhân vật', // More Buttons 'More Text': 'Thêm văn bản', 'More Paragraph': 'Đoạn khác', 'More Rich': 'Giàu hơn', 'More Misc': 'Thêm linh tinh' }, direction: 'ltr' }; }))); //# sourceMappingURL=vi.js.map
/* Highcharts JS v4.0.4 (2014-09-02) (c) 2009-2014 Torstein Honsi License: www.highcharts.com/license */ (function(){function r(a,b){var c;a||(a={});for(c in b)a[c]=b[c];return a}function w(){var a,b=arguments,c,d={},e=function(a,b){var c,d;typeof a!=="object"&&(a={});for(d in b)b.hasOwnProperty(d)&&(c=b[d],a[d]=c&&typeof c==="object"&&Object.prototype.toString.call(c)!=="[object Array]"&&d!=="renderTo"&&typeof c.nodeType!=="number"?e(a[d]||{},c):b[d]);return a};b[0]===!0&&(d=b[1],b=Array.prototype.slice.call(b,2));c=b.length;for(a=0;a<c;a++)d=e(d,b[a]);return d}function y(a,b){return parseInt(a,b|| 10)}function Ga(a){return typeof a==="string"}function da(a){return a&&typeof a==="object"}function Ha(a){return Object.prototype.toString.call(a)==="[object Array]"}function ja(a){return typeof a==="number"}function za(a){return V.log(a)/V.LN10}function ka(a){return V.pow(10,a)}function la(a,b){for(var c=a.length;c--;)if(a[c]===b){a.splice(c,1);break}}function s(a){return a!==u&&a!==null}function F(a,b,c){var d,e;if(Ga(b))s(c)?a.setAttribute(b,c):a&&a.getAttribute&&(e=a.getAttribute(b));else if(s(b)&& da(b))for(d in b)a.setAttribute(d,b[d]);return e}function ra(a){return Ha(a)?a:[a]}function p(){var a=arguments,b,c,d=a.length;for(b=0;b<d;b++)if(c=a[b],c!==u&&c!==null)return c}function B(a,b){if(Aa&&!ba&&b&&b.opacity!==u)b.filter="alpha(opacity="+b.opacity*100+")";r(a.style,b)}function $(a,b,c,d,e){a=x.createElement(a);b&&r(a,b);e&&B(a,{padding:0,border:P,margin:0});c&&B(a,c);d&&d.appendChild(a);return a}function ma(a,b){var c=function(){return u};c.prototype=new a;r(c.prototype,b);return c}function Ba(a, b,c,d){var e=K.numberFormat,f=E.lang,g=+a||0,h=b===-1?(g.toString().split(".")[1]||"").length:isNaN(b=Q(b))?2:b,i=c===void 0?f.decimalPoint:c,f=d===void 0?f.thousandsSep:d,j=g<0?"-":"",k=String(y(g=Q(g).toFixed(h))),l=k.length>3?k.length%3:0;return e!==Ba?e(a,b,c,d):j+(l?k.substr(0,l)+f:"")+k.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+f)+(h?i+Q(g-k).toFixed(h).slice(2):"")}function Ia(a,b){return Array((b||2)+1-String(a).length).join(0)+a}function Na(a,b,c){var d=a[b];a[b]=function(){var a=Array.prototype.slice.call(arguments); a.unshift(d);return c.apply(this,a)}}function Ja(a,b){for(var c="{",d=!1,e,f,g,h,i,j=[];(c=a.indexOf(c))!==-1;){e=a.slice(0,c);if(d){f=e.split(":");g=f.shift().split(".");i=g.length;e=b;for(h=0;h<i;h++)e=e[g[h]];if(f.length)f=f.join(":"),g=/\.([0-9])/,h=E.lang,i=void 0,/f$/.test(f)?(i=(i=f.match(g))?i[1]:-1,e!==null&&(e=Ba(e,i,h.decimalPoint,f.indexOf(",")>-1?h.thousandsSep:""))):e=cb(f,e)}j.push(e);a=a.slice(c+1);c=(d=!d)?"}":"{"}j.push(a);return j.join("")}function mb(a){return V.pow(10,U(V.log(a)/ V.LN10))}function nb(a,b,c,d){var e,c=p(c,1);e=a/c;b||(b=[1,2,2.5,5,10],d===!1&&(c===1?b=[1,2,5,10]:c<=0.1&&(b=[1/c])));for(d=0;d<b.length;d++)if(a=b[d],e<=(b[d]+(b[d+1]||b[d]))/2)break;a*=c;return a}function ob(a,b){var c=a.length,d,e;for(e=0;e<c;e++)a[e].ss_i=e;a.sort(function(a,c){d=b(a,c);return d===0?a.ss_i-c.ss_i:d});for(e=0;e<c;e++)delete a[e].ss_i}function Oa(a){for(var b=a.length,c=a[0];b--;)a[b]<c&&(c=a[b]);return c}function Ca(a){for(var b=a.length,c=a[0];b--;)a[b]>c&&(c=a[b]);return c} function Pa(a,b){for(var c in a)a[c]&&a[c]!==b&&a[c].destroy&&a[c].destroy(),delete a[c]}function Qa(a){db||(db=$(Ka));a&&db.appendChild(a);db.innerHTML=""}function ea(a){return parseFloat(a.toPrecision(14))}function Ra(a,b){va=p(a,b.animation)}function Bb(){var a=E.global.useUTC,b=a?"getUTC":"get",c=a?"setUTC":"set";Da=E.global.Date||window.Date;Sa=(a&&E.global.timezoneOffset||0)*6E4;eb=a?Da.UTC:function(a,b,c,g,h,i){return(new Da(a,b,p(c,1),p(g,0),p(h,0),p(i,0))).getTime()};pb=b+"Minutes";qb=b+ "Hours";rb=b+"Day";Xa=b+"Date";fb=b+"Month";gb=b+"FullYear";Cb=c+"Minutes";Db=c+"Hours";sb=c+"Date";Eb=c+"Month";Fb=c+"FullYear"}function S(){}function Ta(a,b,c,d){this.axis=a;this.pos=b;this.type=c||"";this.isNew=!0;!c&&!d&&this.addLabel()}function na(){this.init.apply(this,arguments)}function Ya(){this.init.apply(this,arguments)}function Gb(a,b,c,d,e){var f=a.chart.inverted;this.axis=a;this.isNegative=c;this.options=b;this.x=d;this.total=null;this.points={};this.stack=e;this.alignOptions={align:b.align|| (f?c?"left":"right":"center"),verticalAlign:b.verticalAlign||(f?"middle":c?"bottom":"top"),y:p(b.y,f?4:c?14:-6),x:p(b.x,f?c?-6:6:0)};this.textAlign=b.textAlign||(f?c?"right":"left":"center")}var u,x=document,G=window,V=Math,v=V.round,U=V.floor,La=V.ceil,t=V.max,L=V.min,Q=V.abs,aa=V.cos,fa=V.sin,oa=V.PI,Ea=oa*2/360,wa=navigator.userAgent,Hb=G.opera,Aa=/msie/i.test(wa)&&!Hb,hb=x.documentMode===8,tb=/AppleWebKit/.test(wa),Ua=/Firefox/.test(wa),Ib=/(Mobile|Android|Windows Phone)/.test(wa),xa="http://www.w3.org/2000/svg", ba=!!x.createElementNS&&!!x.createElementNS(xa,"svg").createSVGRect,Ob=Ua&&parseInt(wa.split("Firefox/")[1],10)<4,ga=!ba&&!Aa&&!!x.createElement("canvas").getContext,Za,$a,Jb={},ub=0,db,E,cb,va,vb,A,ha,sa=function(){return u},W=[],ab=0,Ka="div",P="none",Pb=/^[0-9]+$/,Qb="stroke-width",Da,eb,Sa,pb,qb,rb,Xa,fb,gb,Cb,Db,sb,Eb,Fb,H={},K;G.Highcharts?ha(16,!0):K=G.Highcharts={};cb=function(a,b,c){if(!s(b)||isNaN(b))return"Invalid date";var a=p(a,"%Y-%m-%d %H:%M:%S"),d=new Da(b-Sa),e,f=d[qb](),g=d[rb](), h=d[Xa](),i=d[fb](),j=d[gb](),k=E.lang,l=k.weekdays,d=r({a:l[g].substr(0,3),A:l[g],d:Ia(h),e:h,b:k.shortMonths[i],B:k.months[i],m:Ia(i+1),y:j.toString().substr(2,2),Y:j,H:Ia(f),I:Ia(f%12||12),l:f%12||12,M:Ia(d[pb]()),p:f<12?"AM":"PM",P:f<12?"am":"pm",S:Ia(d.getSeconds()),L:Ia(v(b%1E3),3)},K.dateFormats);for(e in d)for(;a.indexOf("%"+e)!==-1;)a=a.replace("%"+e,typeof d[e]==="function"?d[e](b):d[e]);return c?a.substr(0,1).toUpperCase()+a.substr(1):a};ha=function(a,b){var c="Highcharts error #"+a+": www.highcharts.com/errors/"+ a;if(b)throw c;G.console&&console.log(c)};A={millisecond:1,second:1E3,minute:6E4,hour:36E5,day:864E5,week:6048E5,month:26784E5,year:31556952E3};vb={init:function(a,b,c){var b=b||"",d=a.shift,e=b.indexOf("C")>-1,f=e?7:3,g,b=b.split(" "),c=[].concat(c),h,i,j=function(a){for(g=a.length;g--;)a[g]==="M"&&a.splice(g+1,0,a[g+1],a[g+2],a[g+1],a[g+2])};e&&(j(b),j(c));a.isArea&&(h=b.splice(b.length-6,6),i=c.splice(c.length-6,6));if(d<=c.length/f&&b.length===c.length)for(;d--;)c=[].concat(c).splice(0,f).concat(c); a.shift=0;if(b.length)for(a=c.length;b.length<a;)d=[].concat(b).splice(b.length-f,f),e&&(d[f-6]=d[f-2],d[f-5]=d[f-1]),b=b.concat(d);h&&(b=b.concat(h),c=c.concat(i));return[b,c]},step:function(a,b,c,d){var e=[],f=a.length;if(c===1)e=d;else if(f===b.length&&c<1)for(;f--;)d=parseFloat(a[f]),e[f]=isNaN(d)?a[f]:c*parseFloat(b[f]-d)+d;else e=b;return e}};(function(a){G.HighchartsAdapter=G.HighchartsAdapter||a&&{init:function(b){var c=a.fx;a.extend(a.easing,{easeOutQuad:function(a,b,c,g,h){return-g*(b/= h)*(b-2)+c}});a.each(["cur","_default","width","height","opacity"],function(b,e){var f=c.step,g;e==="cur"?f=c.prototype:e==="_default"&&a.Tween&&(f=a.Tween.propHooks[e],e="set");(g=f[e])&&(f[e]=function(a){var c,a=b?a:this;if(a.prop!=="align")return c=a.elem,c.attr?c.attr(a.prop,e==="cur"?u:a.now):g.apply(this,arguments)})});Na(a.cssHooks.opacity,"get",function(a,b,c){return b.attr?b.opacity||0:a.call(this,b,c)});this.addAnimSetter("d",function(a){var c=a.elem,f;if(!a.started)f=b.init(c,c.d,c.toD), a.start=f[0],a.end=f[1],a.started=!0;c.attr("d",b.step(a.start,a.end,a.pos,c.toD))});this.each=Array.prototype.forEach?function(a,b){return Array.prototype.forEach.call(a,b)}:function(a,b){var c,g=a.length;for(c=0;c<g;c++)if(b.call(a[c],a[c],c,a)===!1)return c};a.fn.highcharts=function(){var a="Chart",b=arguments,c,g;if(this[0]){Ga(b[0])&&(a=b[0],b=Array.prototype.slice.call(b,1));c=b[0];if(c!==u)c.chart=c.chart||{},c.chart.renderTo=this[0],new K[a](c,b[1]),g=this;c===u&&(g=W[F(this[0],"data-highcharts-chart")])}return g}}, addAnimSetter:function(b,c){a.Tween?a.Tween.propHooks[b]={set:c}:a.fx.step[b]=c},getScript:a.getScript,inArray:a.inArray,adapterRun:function(b,c){return a(b)[c]()},grep:a.grep,map:function(a,c){for(var d=[],e=0,f=a.length;e<f;e++)d[e]=c.call(a[e],a[e],e,a);return d},offset:function(b){return a(b).offset()},addEvent:function(b,c,d){a(b).bind(c,d)},removeEvent:function(b,c,d){var e=x.removeEventListener?"removeEventListener":"detachEvent";x[e]&&b&&!b[e]&&(b[e]=function(){});a(b).unbind(c,d)},fireEvent:function(b, c,d,e){var f=a.Event(c),g="detached"+c,h;!Aa&&d&&(delete d.layerX,delete d.layerY,delete d.returnValue);r(f,d);b[c]&&(b[g]=b[c],b[c]=null);a.each(["preventDefault","stopPropagation"],function(a,b){var c=f[b];f[b]=function(){try{c.call(f)}catch(a){b==="preventDefault"&&(h=!0)}}});a(b).trigger(f);b[g]&&(b[c]=b[g],b[g]=null);e&&!f.isDefaultPrevented()&&!h&&e(f)},washMouseEvent:function(a){var c=a.originalEvent||a;if(c.pageX===u)c.pageX=a.pageX,c.pageY=a.pageY;return c},animate:function(b,c,d){var e= a(b);if(!b.style)b.style={};if(c.d)b.toD=c.d,c.d=1;e.stop();c.opacity!==u&&b.attr&&(c.opacity+="px");b.hasAnim=1;e.animate(c,d)},stop:function(b){b.hasAnim&&a(b).stop()}}})(G.jQuery);var T=G.HighchartsAdapter,M=T||{};T&&T.init.call(T,vb);var ib=M.adapterRun,Rb=M.getScript,Ma=M.inArray,q=M.each,wb=M.grep,Sb=M.offset,Va=M.map,N=M.addEvent,X=M.removeEvent,I=M.fireEvent,Tb=M.washMouseEvent,jb=M.animate,bb=M.stop,M={enabled:!0,x:0,y:15,style:{color:"#606060",cursor:"default",fontSize:"11px"}};E={colors:"#7cb5ec,#434348,#90ed7d,#f7a35c,#8085e9,#f15c80,#e4d354,#8085e8,#8d4653,#91e8e1".split(","), symbols:["circle","diamond","square","triangle","triangle-down"],lang:{loading:"Loading...",months:"January,February,March,April,May,June,July,August,September,October,November,December".split(","),shortMonths:"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(","),weekdays:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".split(","),decimalPoint:".",numericSymbols:"k,M,G,T,P,E".split(","),resetZoom:"Reset zoom",resetZoomTitle:"Reset zoom level 1:1",thousandsSep:","},global:{useUTC:!0, canvasToolsURL:"http://code.highcharts.com/4.0.4/modules/canvas-tools.js",VMLRadialGradientURL:"http://code.highcharts.com/4.0.4/gfx/vml-radial-gradient.png"},chart:{borderColor:"#4572A7",borderRadius:0,defaultSeriesType:"line",ignoreHiddenSeries:!0,spacing:[10,10,15,10],backgroundColor:"#FFFFFF",plotBorderColor:"#C0C0C0",resetZoomButton:{theme:{zIndex:20},position:{align:"right",x:-10,y:10}}},title:{text:"Chart title",align:"center",margin:15,style:{color:"#333333",fontSize:"18px"}},subtitle:{text:"", align:"center",style:{color:"#555555"}},plotOptions:{line:{allowPointSelect:!1,showCheckbox:!1,animation:{duration:1E3},events:{},lineWidth:2,marker:{lineWidth:0,radius:4,lineColor:"#FFFFFF",states:{hover:{enabled:!0,lineWidthPlus:1,radiusPlus:2},select:{fillColor:"#FFFFFF",lineColor:"#000000",lineWidth:2}}},point:{events:{}},dataLabels:w(M,{align:"center",enabled:!1,formatter:function(){return this.y===null?"":Ba(this.y,-1)},verticalAlign:"bottom",y:0}),cropThreshold:300,pointRange:0,states:{hover:{lineWidthPlus:1, marker:{},halo:{size:10,opacity:0.25}},select:{marker:{}}},stickyTracking:!0,turboThreshold:1E3}},labels:{style:{position:"absolute",color:"#3E576F"}},legend:{enabled:!0,align:"center",layout:"horizontal",labelFormatter:function(){return this.name},borderColor:"#909090",borderRadius:0,navigation:{activeColor:"#274b6d",inactiveColor:"#CCC"},shadow:!1,itemStyle:{color:"#333333",fontSize:"12px",fontWeight:"bold"},itemHoverStyle:{color:"#000"},itemHiddenStyle:{color:"#CCC"},itemCheckboxStyle:{position:"absolute", width:"13px",height:"13px"},symbolPadding:5,verticalAlign:"bottom",x:0,y:0,title:{style:{fontWeight:"bold"}}},loading:{labelStyle:{fontWeight:"bold",position:"relative",top:"45%"},style:{position:"absolute",backgroundColor:"white",opacity:0.5,textAlign:"center"}},tooltip:{enabled:!0,animation:ba,backgroundColor:"rgba(249, 249, 249, .85)",borderWidth:1,borderRadius:3,dateTimeLabelFormats:{millisecond:"%A, %b %e, %H:%M:%S.%L",second:"%A, %b %e, %H:%M:%S",minute:"%A, %b %e, %H:%M",hour:"%A, %b %e, %H:%M", day:"%A, %b %e, %Y",week:"Week from %A, %b %e, %Y",month:"%B %Y",year:"%Y"},headerFormat:'<span style="font-size: 10px">{point.key}</span><br/>',pointFormat:'<span style="color:{series.color}">●</span> {series.name}: <b>{point.y}</b><br/>',shadow:!0,snap:Ib?25:10,style:{color:"#333333",cursor:"default",fontSize:"12px",padding:"8px",whiteSpace:"nowrap"}},credits:{enabled:!0,text:"Highcharts.com",href:"http://www.highcharts.com",position:{align:"right",x:-10,verticalAlign:"bottom",y:-5},style:{cursor:"pointer", color:"#909090",fontSize:"9px"}}};var ca=E.plotOptions,T=ca.line;Bb();var Ub=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/,Vb=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/,Wb=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/,ya=function(a){var b=[],c,d;(function(a){a&&a.stops?d=Va(a.stops,function(a){return ya(a[1])}):(c=Ub.exec(a))?b=[y(c[1]),y(c[2]),y(c[3]),parseFloat(c[4],10)]:(c=Vb.exec(a))?b=[y(c[1],16),y(c[2],16),y(c[3], 16),1]:(c=Wb.exec(a))&&(b=[y(c[1]),y(c[2]),y(c[3]),1])})(a);return{get:function(c){var f;d?(f=w(a),f.stops=[].concat(f.stops),q(d,function(a,b){f.stops[b]=[f.stops[b][0],a.get(c)]})):f=b&&!isNaN(b[0])?c==="rgb"?"rgb("+b[0]+","+b[1]+","+b[2]+")":c==="a"?b[3]:"rgba("+b.join(",")+")":a;return f},brighten:function(a){if(d)q(d,function(b){b.brighten(a)});else if(ja(a)&&a!==0){var c;for(c=0;c<3;c++)b[c]+=y(a*255),b[c]<0&&(b[c]=0),b[c]>255&&(b[c]=255)}return this},rgba:b,setOpacity:function(a){b[3]=a;return this}}}; S.prototype={opacity:1,textProps:"fontSize,fontWeight,fontFamily,color,lineHeight,width,textDecoration,textShadow,HcTextStroke".split(","),init:function(a,b){this.element=b==="span"?$(b):x.createElementNS(xa,b);this.renderer=a},animate:function(a,b,c){b=p(b,va,!0);bb(this);if(b){b=w(b,{});if(c)b.complete=c;jb(this,a,b)}else this.attr(a),c&&c();return this},colorGradient:function(a,b,c){var d=this.renderer,e,f,g,h,i,j,k,l,n,m,o=[];a.linearGradient?f="linearGradient":a.radialGradient&&(f="radialGradient"); if(f){g=a[f];h=d.gradients;j=a.stops;n=c.radialReference;Ha(g)&&(a[f]=g={x1:g[0],y1:g[1],x2:g[2],y2:g[3],gradientUnits:"userSpaceOnUse"});f==="radialGradient"&&n&&!s(g.gradientUnits)&&(g=w(g,{cx:n[0]-n[2]/2+g.cx*n[2],cy:n[1]-n[2]/2+g.cy*n[2],r:g.r*n[2],gradientUnits:"userSpaceOnUse"}));for(m in g)m!=="id"&&o.push(m,g[m]);for(m in j)o.push(j[m]);o=o.join(",");h[o]?a=h[o].attr("id"):(g.id=a="highcharts-"+ub++,h[o]=i=d.createElement(f).attr(g).add(d.defs),i.stops=[],q(j,function(a){a[1].indexOf("rgba")=== 0?(e=ya(a[1]),k=e.get("rgb"),l=e.get("a")):(k=a[1],l=1);a=d.createElement("stop").attr({offset:a[0],"stop-color":k,"stop-opacity":l}).add(i);i.stops.push(a)}));c.setAttribute(b,"url("+d.url+"#"+a+")")}},attr:function(a,b){var c,d,e=this.element,f,g=this,h;typeof a==="string"&&b!==u&&(c=a,a={},a[c]=b);if(typeof a==="string")g=(this[a+"Getter"]||this._defaultGetter).call(this,a,e);else{for(c in a){d=a[c];h=!1;this.symbolName&&/^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(c)&&(f||(this.symbolAttr(a), f=!0),h=!0);if(this.rotation&&(c==="x"||c==="y"))this.doTransform=!0;h||(this[c+"Setter"]||this._defaultSetter).call(this,d,c,e);this.shadows&&/^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(c)&&this.updateShadows(c,d)}if(this.doTransform)this.updateTransform(),this.doTransform=!1}return g},updateShadows:function(a,b){for(var c=this.shadows,d=c.length;d--;)c[d].setAttribute(a,a==="height"?t(b-(c[d].cutHeight||0),0):a==="d"?this.d:b)},addClass:function(a){var b=this.element,c=F(b,"class")|| "";c.indexOf(a)===-1&&F(b,"class",c+" "+a);return this},symbolAttr:function(a){var b=this;q("x,y,r,start,end,width,height,innerR,anchorX,anchorY".split(","),function(c){b[c]=p(a[c],b[c])});b.attr({d:b.renderer.symbols[b.symbolName](b.x,b.y,b.width,b.height,b)})},clip:function(a){return this.attr("clip-path",a?"url("+this.renderer.url+"#"+a.id+")":P)},crisp:function(a){var b,c={},d,e=a.strokeWidth||this.strokeWidth||0;d=v(e)%2/2;a.x=U(a.x||this.x||0)+d;a.y=U(a.y||this.y||0)+d;a.width=U((a.width||this.width|| 0)-2*d);a.height=U((a.height||this.height||0)-2*d);a.strokeWidth=e;for(b in a)this[b]!==a[b]&&(this[b]=c[b]=a[b]);return c},css:function(a){var b=this.styles,c={},d=this.element,e,f,g="";e=!b;if(a&&a.color)a.fill=a.color;if(b)for(f in a)a[f]!==b[f]&&(c[f]=a[f],e=!0);if(e){e=this.textWidth=a&&a.width&&d.nodeName.toLowerCase()==="text"&&y(a.width);b&&(a=r(b,c));this.styles=a;e&&(ga||!ba&&this.renderer.forExport)&&delete a.width;if(Aa&&!ba)B(this.element,a);else{b=function(a,b){return"-"+b.toLowerCase()}; for(f in a)g+=f.replace(/([A-Z])/g,b)+":"+a[f]+";";F(d,"style",g)}e&&this.added&&this.renderer.buildText(this)}return this},on:function(a,b){var c=this,d=c.element;$a&&a==="click"?(d.ontouchstart=function(a){c.touchEventFired=Da.now();a.preventDefault();b.call(d,a)},d.onclick=function(a){(wa.indexOf("Android")===-1||Da.now()-(c.touchEventFired||0)>1100)&&b.call(d,a)}):d["on"+a]=b;return this},setRadialReference:function(a){this.element.radialReference=a;return this},translate:function(a,b){return this.attr({translateX:a, translateY:b})},invert:function(){this.inverted=!0;this.updateTransform();return this},updateTransform:function(){var a=this.translateX||0,b=this.translateY||0,c=this.scaleX,d=this.scaleY,e=this.inverted,f=this.rotation,g=this.element;e&&(a+=this.attr("width"),b+=this.attr("height"));a=["translate("+a+","+b+")"];e?a.push("rotate(90) scale(-1,1)"):f&&a.push("rotate("+f+" "+(g.getAttribute("x")||0)+" "+(g.getAttribute("y")||0)+")");(s(c)||s(d))&&a.push("scale("+p(c,1)+" "+p(d,1)+")");a.length&&g.setAttribute("transform", a.join(" "))},toFront:function(){var a=this.element;a.parentNode.appendChild(a);return this},align:function(a,b,c){var d,e,f,g,h={};e=this.renderer;f=e.alignedObjects;if(a){if(this.alignOptions=a,this.alignByTranslate=b,!c||Ga(c))this.alignTo=d=c||"renderer",la(f,this),f.push(this),c=null}else a=this.alignOptions,b=this.alignByTranslate,d=this.alignTo;c=p(c,e[d],e);d=a.align;e=a.verticalAlign;f=(c.x||0)+(a.x||0);g=(c.y||0)+(a.y||0);if(d==="right"||d==="center")f+=(c.width-(a.width||0))/{right:1,center:2}[d]; h[b?"translateX":"x"]=v(f);if(e==="bottom"||e==="middle")g+=(c.height-(a.height||0))/({bottom:1,middle:2}[e]||1);h[b?"translateY":"y"]=v(g);this[this.placed?"animate":"attr"](h);this.placed=!0;this.alignAttr=h;return this},getBBox:function(){var a=this.bBox,b=this.renderer,c,d,e=this.rotation;c=this.element;var f=this.styles,g=e*Ea;d=this.textStr;var h;if(d===""||Pb.test(d))h="num."+d.toString().length+(f?"|"+f.fontSize+"|"+f.fontFamily:"");h&&(a=b.cache[h]);if(!a){if(c.namespaceURI===xa||b.forExport){try{a= c.getBBox?r({},c.getBBox()):{width:c.offsetWidth,height:c.offsetHeight}}catch(i){}if(!a||a.width<0)a={width:0,height:0}}else a=this.htmlGetBBox();if(b.isSVG){c=a.width;d=a.height;if(Aa&&f&&f.fontSize==="11px"&&d.toPrecision(3)==="16.9")a.height=d=14;if(e)a.width=Q(d*fa(g))+Q(c*aa(g)),a.height=Q(d*aa(g))+Q(c*fa(g))}this.bBox=a;h&&(b.cache[h]=a)}return a},show:function(a){a&&this.element.namespaceURI===xa?this.element.removeAttribute("visibility"):this.attr({visibility:a?"inherit":"visible"});return this}, hide:function(){return this.attr({visibility:"hidden"})},fadeOut:function(a){var b=this;b.animate({opacity:0},{duration:a||150,complete:function(){b.attr({y:-9999})}})},add:function(a){var b=this.renderer,c=a||b,d=c.element||b.box,e=this.element,f=this.zIndex,g,h;if(a)this.parentGroup=a;this.parentInverted=a&&a.inverted;this.textStr!==void 0&&b.buildText(this);if(f)c.handleZ=!0,f=y(f);if(c.handleZ){a=d.childNodes;for(g=0;g<a.length;g++)if(b=a[g],c=F(b,"zIndex"),b!==e&&(y(c)>f||!s(f)&&s(c))){d.insertBefore(e, b);h=!0;break}}h||d.appendChild(e);this.added=!0;if(this.onAdd)this.onAdd();return this},safeRemoveChild:function(a){var b=a.parentNode;b&&b.removeChild(a)},destroy:function(){var a=this,b=a.element||{},c=a.shadows,d=a.renderer.isSVG&&b.nodeName==="SPAN"&&a.parentGroup,e,f;b.onclick=b.onmouseout=b.onmouseover=b.onmousemove=b.point=null;bb(a);if(a.clipPath)a.clipPath=a.clipPath.destroy();if(a.stops){for(f=0;f<a.stops.length;f++)a.stops[f]=a.stops[f].destroy();a.stops=null}a.safeRemoveChild(b);for(c&& q(c,function(b){a.safeRemoveChild(b)});d&&d.div&&d.div.childNodes.length===0;)b=d.parentGroup,a.safeRemoveChild(d.div),delete d.div,d=b;a.alignTo&&la(a.renderer.alignedObjects,a);for(e in a)delete a[e];return null},shadow:function(a,b,c){var d=[],e,f,g=this.element,h,i,j,k;if(a){i=p(a.width,3);j=(a.opacity||0.15)/i;k=this.parentInverted?"(-1,-1)":"("+p(a.offsetX,1)+", "+p(a.offsetY,1)+")";for(e=1;e<=i;e++){f=g.cloneNode(0);h=i*2+1-2*e;F(f,{isShadow:"true",stroke:a.color||"black","stroke-opacity":j* e,"stroke-width":h,transform:"translate"+k,fill:P});if(c)F(f,"height",t(F(f,"height")-h,0)),f.cutHeight=h;b?b.element.appendChild(f):g.parentNode.insertBefore(f,g);d.push(f)}this.shadows=d}return this},xGetter:function(a){this.element.nodeName==="circle"&&(a={x:"cx",y:"cy"}[a]||a);return this._defaultGetter(a)},_defaultGetter:function(a){a=p(this[a],this.element?this.element.getAttribute(a):null,0);/^[\-0-9\.]+$/.test(a)&&(a=parseFloat(a));return a},dSetter:function(a,b,c){a&&a.join&&(a=a.join(" ")); /(NaN| {2}|^$)/.test(a)&&(a="M 0 0");c.setAttribute(b,a);this[b]=a},dashstyleSetter:function(a){var b;if(a=a&&a.toLowerCase()){a=a.replace("shortdashdotdot","3,1,1,1,1,1,").replace("shortdashdot","3,1,1,1").replace("shortdot","1,1,").replace("shortdash","3,1,").replace("longdash","8,3,").replace(/dot/g,"1,3,").replace("dash","4,3,").replace(/,$/,"").split(",");for(b=a.length;b--;)a[b]=y(a[b])*this["stroke-width"];a=a.join(",").replace("NaN","none");this.element.setAttribute("stroke-dasharray",a)}}, alignSetter:function(a){this.element.setAttribute("text-anchor",{left:"start",center:"middle",right:"end"}[a])},opacitySetter:function(a,b,c){this[b]=a;c.setAttribute(b,a)},titleSetter:function(a){var b=this.element.getElementsByTagName("title")[0];b||(b=x.createElementNS(xa,"title"),this.element.appendChild(b));b.textContent=p(a,"").replace(/<[^>]*>/g,"")},textSetter:function(a){if(a!==this.textStr)delete this.bBox,this.textStr=a,this.added&&this.renderer.buildText(this)},fillSetter:function(a,b, c){typeof a==="string"?c.setAttribute(b,a):a&&this.colorGradient(a,b,c)},zIndexSetter:function(a,b,c){c.setAttribute(b,a);this[b]=a},_defaultSetter:function(a,b,c){c.setAttribute(b,a)}};S.prototype.yGetter=S.prototype.xGetter;S.prototype.translateXSetter=S.prototype.translateYSetter=S.prototype.rotationSetter=S.prototype.verticalAlignSetter=S.prototype.scaleXSetter=S.prototype.scaleYSetter=function(a,b){this[b]=a;this.doTransform=!0};S.prototype["stroke-widthSetter"]=S.prototype.strokeSetter=function(a, b,c){this[b]=a;if(this.stroke&&this["stroke-width"])this.strokeWidth=this["stroke-width"],S.prototype.fillSetter.call(this,this.stroke,"stroke",c),c.setAttribute("stroke-width",this["stroke-width"]),this.hasStroke=!0;else if(b==="stroke-width"&&a===0&&this.hasStroke)c.removeAttribute("stroke"),this.hasStroke=!1};var ta=function(){this.init.apply(this,arguments)};ta.prototype={Element:S,init:function(a,b,c,d,e){var f=location,g,d=this.createElement("svg").attr({version:"1.1"}).css(this.getStyle(d)); g=d.element;a.appendChild(g);a.innerHTML.indexOf("xmlns")===-1&&F(g,"xmlns",xa);this.isSVG=!0;this.box=g;this.boxWrapper=d;this.alignedObjects=[];this.url=(Ua||tb)&&x.getElementsByTagName("base").length?f.href.replace(/#.*?$/,"").replace(/([\('\)])/g,"\\$1").replace(/ /g,"%20"):"";this.createElement("desc").add().element.appendChild(x.createTextNode("Created with Highcharts 4.0.4"));this.defs=this.createElement("defs").add();this.forExport=e;this.gradients={};this.cache={};this.setSize(b,c,!1);var h; if(Ua&&a.getBoundingClientRect)this.subPixelFix=b=function(){B(a,{left:0,top:0});h=a.getBoundingClientRect();B(a,{left:La(h.left)-h.left+"px",top:La(h.top)-h.top+"px"})},b(),N(G,"resize",b)},getStyle:function(a){return this.style=r({fontFamily:'"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif',fontSize:"12px"},a)},isHidden:function(){return!this.boxWrapper.getBBox().width},destroy:function(){var a=this.defs;this.box=null;this.boxWrapper=this.boxWrapper.destroy();Pa(this.gradients|| {});this.gradients=null;if(a)this.defs=a.destroy();this.subPixelFix&&X(G,"resize",this.subPixelFix);return this.alignedObjects=null},createElement:function(a){var b=new this.Element;b.init(this,a);return b},draw:function(){},buildText:function(a){for(var b=a.element,c=this,d=c.forExport,e=p(a.textStr,"").toString(),f=e.indexOf("<")!==-1,g=b.childNodes,h,i,j=F(b,"x"),k=a.styles,l=a.textWidth,n=k&&k.lineHeight,m=k&&k.HcTextStroke,o=g.length,Y=function(a){return n?y(n):c.fontMetrics(/(px|em)$/.test(a&& a.style.fontSize)?a.style.fontSize:k&&k.fontSize||c.style.fontSize||12,a).h};o--;)b.removeChild(g[o]);!f&&!m&&e.indexOf(" ")===-1?b.appendChild(x.createTextNode(e)):(h=/<.*style="([^"]+)".*>/,i=/<.*href="(http[^"]+)".*>/,l&&!a.added&&this.box.appendChild(b),e=f?e.replace(/<(b|strong)>/g,'<span style="font-weight:bold">').replace(/<(i|em)>/g,'<span style="font-style:italic">').replace(/<a/g,"<span").replace(/<\/(b|strong|i|em|a)>/g,"</span>").split(/<br.*?>/g):[e],e[e.length-1]===""&&e.pop(),q(e,function(e, f){var g,n=0,e=e.replace(/<span/g,"|||<span").replace(/<\/span>/g,"</span>|||");g=e.split("|||");q(g,function(e){if(e!==""||g.length===1){var m={},o=x.createElementNS(xa,"tspan"),p;h.test(e)&&(p=e.match(h)[1].replace(/(;| |^)color([ :])/,"$1fill$2"),F(o,"style",p));i.test(e)&&!d&&(F(o,"onclick",'location.href="'+e.match(i)[1]+'"'),B(o,{cursor:"pointer"}));e=(e.replace(/<(.|\n)*?>/g,"")||" ").replace(/&lt;/g,"<").replace(/&gt;/g,">");if(e!==" "){o.appendChild(x.createTextNode(e));if(n)m.dx=0;else if(f&& j!==null)m.x=j;F(o,m);b.appendChild(o);!n&&f&&(!ba&&d&&B(o,{display:"block"}),F(o,"dy",Y(o)));if(l)for(var e=e.replace(/([^\^])-/g,"$1- ").split(" "),m=g.length>1||e.length>1&&k.whiteSpace!=="nowrap",q,D,s=k.HcHeight,t=[],u=Y(o),Lb=1;m&&(e.length||t.length);)delete a.bBox,q=a.getBBox(),D=q.width,!ba&&c.forExport&&(D=c.measureSpanWidth(o.firstChild.data,a.styles)),q=D>l,!q||e.length===1?(e=t,t=[],e.length&&(Lb++,s&&Lb*u>s?(e=["..."],a.attr("title",a.textStr)):(o=x.createElementNS(xa,"tspan"),F(o,{dy:u, x:j}),p&&F(o,"style",p),b.appendChild(o))),D>l&&(l=D)):(o.removeChild(o.firstChild),t.unshift(e.pop())),e.length&&o.appendChild(x.createTextNode(e.join(" ").replace(/- /g,"-")));n++}}})}))},button:function(a,b,c,d,e,f,g,h,i){var j=this.label(a,b,c,i,null,null,null,null,"button"),k=0,l,n,m,o,p,q,a={x1:0,y1:0,x2:0,y2:1},e=w({"stroke-width":1,stroke:"#CCCCCC",fill:{linearGradient:a,stops:[[0,"#FEFEFE"],[1,"#F6F6F6"]]},r:2,padding:5,style:{color:"black"}},e);m=e.style;delete e.style;f=w(e,{stroke:"#68A", fill:{linearGradient:a,stops:[[0,"#FFF"],[1,"#ACF"]]}},f);o=f.style;delete f.style;g=w(e,{stroke:"#68A",fill:{linearGradient:a,stops:[[0,"#9BD"],[1,"#CDF"]]}},g);p=g.style;delete g.style;h=w(e,{style:{color:"#CCC"}},h);q=h.style;delete h.style;N(j.element,Aa?"mouseover":"mouseenter",function(){k!==3&&j.attr(f).css(o)});N(j.element,Aa?"mouseout":"mouseleave",function(){k!==3&&(l=[e,f,g][k],n=[m,o,p][k],j.attr(l).css(n))});j.setState=function(a){(j.state=k=a)?a===2?j.attr(g).css(p):a===3&&j.attr(h).css(q): j.attr(e).css(m)};return j.on("click",function(){k!==3&&d.call(j)}).attr(e).css(r({cursor:"default"},m))},crispLine:function(a,b){a[1]===a[4]&&(a[1]=a[4]=v(a[1])-b%2/2);a[2]===a[5]&&(a[2]=a[5]=v(a[2])+b%2/2);return a},path:function(a){var b={fill:P};Ha(a)?b.d=a:da(a)&&r(b,a);return this.createElement("path").attr(b)},circle:function(a,b,c){a=da(a)?a:{x:a,y:b,r:c};b=this.createElement("circle");b.xSetter=function(a){this.element.setAttribute("cx",a)};b.ySetter=function(a){this.element.setAttribute("cy", a)};return b.attr(a)},arc:function(a,b,c,d,e,f){if(da(a))b=a.y,c=a.r,d=a.innerR,e=a.start,f=a.end,a=a.x;a=this.symbol("arc",a||0,b||0,c||0,c||0,{innerR:d||0,start:e||0,end:f||0});a.r=c;return a},rect:function(a,b,c,d,e,f){var e=da(a)?a.r:e,g=this.createElement("rect"),a=da(a)?a:a===u?{}:{x:a,y:b,width:t(c,0),height:t(d,0)};if(f!==u)a.strokeWidth=f,a=g.crisp(a);if(e)a.r=e;g.rSetter=function(a){F(this.element,{rx:a,ry:a})};return g.attr(a)},setSize:function(a,b,c){var d=this.alignedObjects,e=d.length; this.width=a;this.height=b;for(this.boxWrapper[p(c,!0)?"animate":"attr"]({width:a,height:b});e--;)d[e].align()},g:function(a){var b=this.createElement("g");return s(a)?b.attr({"class":"highcharts-"+a}):b},image:function(a,b,c,d,e){var f={preserveAspectRatio:P};arguments.length>1&&r(f,{x:b,y:c,width:d,height:e});f=this.createElement("image").attr(f);f.element.setAttributeNS?f.element.setAttributeNS("http://www.w3.org/1999/xlink","href",a):f.element.setAttribute("hc-svg-href",a);return f},symbol:function(a, b,c,d,e,f){var g,h=this.symbols[a],h=h&&h(v(b),v(c),d,e,f),i=/^url\((.*?)\)$/,j,k;if(h)g=this.path(h),r(g,{symbolName:a,x:b,y:c,width:d,height:e}),f&&r(g,f);else if(i.test(a))k=function(a,b){a.element&&(a.attr({width:b[0],height:b[1]}),a.alignByTranslate||a.translate(v((d-b[0])/2),v((e-b[1])/2)))},j=a.match(i)[1],a=Jb[j]||f&&f.width&&f.height&&[f.width,f.height],g=this.image(j).attr({x:b,y:c}),g.isImg=!0,a?k(g,a):(g.attr({width:0,height:0}),$("img",{onload:function(){k(g,Jb[j]=[this.width,this.height])}, src:j}));return g},symbols:{circle:function(a,b,c,d){var e=0.166*c;return["M",a+c/2,b,"C",a+c+e,b,a+c+e,b+d,a+c/2,b+d,"C",a-e,b+d,a-e,b,a+c/2,b,"Z"]},square:function(a,b,c,d){return["M",a,b,"L",a+c,b,a+c,b+d,a,b+d,"Z"]},triangle:function(a,b,c,d){return["M",a+c/2,b,"L",a+c,b+d,a,b+d,"Z"]},"triangle-down":function(a,b,c,d){return["M",a,b,"L",a+c,b,a+c/2,b+d,"Z"]},diamond:function(a,b,c,d){return["M",a+c/2,b,"L",a+c,b+d/2,a+c/2,b+d,a,b+d/2,"Z"]},arc:function(a,b,c,d,e){var f=e.start,c=e.r||c||d,g=e.end- 0.001,d=e.innerR,h=e.open,i=aa(f),j=fa(f),k=aa(g),g=fa(g),e=e.end-f<oa?0:1;return["M",a+c*i,b+c*j,"A",c,c,0,e,1,a+c*k,b+c*g,h?"M":"L",a+d*k,b+d*g,"A",d,d,0,e,0,a+d*i,b+d*j,h?"":"Z"]},callout:function(a,b,c,d,e){var f=L(e&&e.r||0,c,d),g=f+6,h=e&&e.anchorX,i=e&&e.anchorY,e=v(e.strokeWidth||0)%2/2;a+=e;b+=e;e=["M",a+f,b,"L",a+c-f,b,"C",a+c,b,a+c,b,a+c,b+f,"L",a+c,b+d-f,"C",a+c,b+d,a+c,b+d,a+c-f,b+d,"L",a+f,b+d,"C",a,b+d,a,b+d,a,b+d-f,"L",a,b+f,"C",a,b,a,b,a+f,b];h&&h>c&&i>b+g&&i<b+d-g?e.splice(13,3, "L",a+c,i-6,a+c+6,i,a+c,i+6,a+c,b+d-f):h&&h<0&&i>b+g&&i<b+d-g?e.splice(33,3,"L",a,i+6,a-6,i,a,i-6,a,b+f):i&&i>d&&h>a+g&&h<a+c-g?e.splice(23,3,"L",h+6,b+d,h,b+d+6,h-6,b+d,a+f,b+d):i&&i<0&&h>a+g&&h<a+c-g&&e.splice(3,3,"L",h-6,b,h,b-6,h+6,b,c-f,b);return e}},clipRect:function(a,b,c,d){var e="highcharts-"+ub++,f=this.createElement("clipPath").attr({id:e}).add(this.defs),a=this.rect(a,b,c,d,0).add(f);a.id=e;a.clipPath=f;return a},text:function(a,b,c,d){var e=ga||!ba&&this.forExport,f={};if(d&&!this.forExport)return this.html(a, b,c);f.x=Math.round(b||0);if(c)f.y=Math.round(c);if(a||a===0)f.text=a;a=this.createElement("text").attr(f);e&&a.css({position:"absolute"});if(!d)a.xSetter=function(a,b,c){var d=c.getElementsByTagName("tspan"),e,f=c.getAttribute(b),n;for(n=0;n<d.length;n++)e=d[n],e.getAttribute(b)===f&&e.setAttribute(b,a);c.setAttribute(b,a)};return a},fontMetrics:function(a,b){a=a||this.style.fontSize;if(b&&G.getComputedStyle)b=b.element||b,a=G.getComputedStyle(b,"").fontSize;var a=/px/.test(a)?y(a):/em/.test(a)? parseFloat(a)*12:12,c=a<24?a+4:v(a*1.2),d=v(c*0.8);return{h:c,b:d,f:a}},label:function(a,b,c,d,e,f,g,h,i){function j(){var a,b;a=o.element.style;D=(t===void 0||xb===void 0||m.styles.textAlign)&&o.textStr&&o.getBBox();m.width=(t||D.width||0)+2*C+kb;m.height=(xb||D.height||0)+2*C;R=C+n.fontMetrics(a&&a.fontSize,o).b;if(y){if(!p)a=v(-J*C),b=h?-R:0,m.box=p=d?n.symbol(d,a,b,m.width,m.height,z):n.rect(a,b,m.width,m.height,0,z[Qb]),p.attr("fill",P).add(m);p.isImg||p.attr(r({width:v(m.width),height:v(m.height)}, z));z=null}}function k(){var a=m.styles,a=a&&a.textAlign,b=kb+C*(1-J),c;c=h?0:R;if(s(t)&&D&&(a==="center"||a==="right"))b+={center:0.5,right:1}[a]*(t-D.width);if(b!==o.x||c!==o.y)o.attr("x",b),c!==u&&o.attr("y",c);o.x=b;o.y=c}function l(a,b){p?p.attr(a,b):z[a]=b}var n=this,m=n.g(i),o=n.text("",0,0,g).attr({zIndex:1}),p,D,J=0,C=3,kb=0,t,xb,yb,x,Kb=0,z={},R,y;m.onAdd=function(){o.add(m);m.attr({text:a||a===0?a:"",x:b,y:c});p&&s(e)&&m.attr({anchorX:e,anchorY:f})};m.widthSetter=function(a){t=a};m.heightSetter= function(a){xb=a};m.paddingSetter=function(a){s(a)&&a!==C&&(C=a,k())};m.paddingLeftSetter=function(a){s(a)&&a!==kb&&(kb=a,k())};m.alignSetter=function(a){J={left:0,center:0.5,right:1}[a]};m.textSetter=function(a){a!==u&&o.textSetter(a);j();k()};m["stroke-widthSetter"]=function(a,b){a&&(y=!0);Kb=a%2/2;l(b,a)};m.strokeSetter=m.fillSetter=m.rSetter=function(a,b){b==="fill"&&a&&(y=!0);l(b,a)};m.anchorXSetter=function(a,b){e=a;l(b,a+Kb-yb)};m.anchorYSetter=function(a,b){f=a;l(b,a-x)};m.xSetter=function(a){m.x= a;J&&(a-=J*((t||D.width)+C));yb=v(a);m.attr("translateX",yb)};m.ySetter=function(a){x=m.y=v(a);m.attr("translateY",x)};var A=m.css;return r(m,{css:function(a){if(a){var b={},a=w(a);q(m.textProps,function(c){a[c]!==u&&(b[c]=a[c],delete a[c])});o.css(b)}return A.call(m,a)},getBBox:function(){return{width:D.width+2*C,height:D.height+2*C,x:D.x-C,y:D.y-C}},shadow:function(a){p&&p.shadow(a);return m},destroy:function(){X(m.element,"mouseenter");X(m.element,"mouseleave");o&&(o=o.destroy());p&&(p=p.destroy()); S.prototype.destroy.call(m);m=n=j=k=l=null}})}};Za=ta;r(S.prototype,{htmlCss:function(a){var b=this.element;if(b=a&&b.tagName==="SPAN"&&a.width)delete a.width,this.textWidth=b,this.updateTransform();this.styles=r(this.styles,a);B(this.element,a);return this},htmlGetBBox:function(){var a=this.element,b=this.bBox;if(!b){if(a.nodeName==="text")a.style.position="absolute";b=this.bBox={x:a.offsetLeft,y:a.offsetTop,width:a.offsetWidth,height:a.offsetHeight}}return b},htmlUpdateTransform:function(){if(this.added){var a= this.renderer,b=this.element,c=this.translateX||0,d=this.translateY||0,e=this.x||0,f=this.y||0,g=this.textAlign||"left",h={left:0,center:0.5,right:1}[g],i=this.shadows;B(b,{marginLeft:c,marginTop:d});i&&q(i,function(a){B(a,{marginLeft:c+1,marginTop:d+1})});this.inverted&&q(b.childNodes,function(c){a.invertChild(c,b)});if(b.tagName==="SPAN"){var j=this.rotation,k,l=y(this.textWidth),n=[j,g,b.innerHTML,this.textWidth].join(",");if(n!==this.cTT){k=a.fontMetrics(b.style.fontSize).b;s(j)&&this.setSpanRotation(j, h,k);i=p(this.elemWidth,b.offsetWidth);if(i>l&&/[ \-]/.test(b.textContent||b.innerText))B(b,{width:l+"px",display:"block",whiteSpace:"normal"}),i=l;this.getSpanCorrection(i,k,h,j,g)}B(b,{left:e+(this.xCorr||0)+"px",top:f+(this.yCorr||0)+"px"});if(tb)k=b.offsetHeight;this.cTT=n}}else this.alignOnAdd=!0},setSpanRotation:function(a,b,c){var d={},e=Aa?"-ms-transform":tb?"-webkit-transform":Ua?"MozTransform":Hb?"-o-transform":"";d[e]=d.transform="rotate("+a+"deg)";d[e+(Ua?"Origin":"-origin")]=d.transformOrigin= b*100+"% "+c+"px";B(this.element,d)},getSpanCorrection:function(a,b,c){this.xCorr=-a*c;this.yCorr=-b}});r(ta.prototype,{html:function(a,b,c){var d=this.createElement("span"),e=d.element,f=d.renderer;d.textSetter=function(a){a!==e.innerHTML&&delete this.bBox;e.innerHTML=this.textStr=a};d.xSetter=d.ySetter=d.alignSetter=d.rotationSetter=function(a,b){b==="align"&&(b="textAlign");d[b]=a;d.htmlUpdateTransform()};d.attr({text:a,x:v(b),y:v(c)}).css({position:"absolute",whiteSpace:"nowrap",fontFamily:this.style.fontFamily, fontSize:this.style.fontSize});d.css=d.htmlCss;if(f.isSVG)d.add=function(a){var b,c=f.box.parentNode,j=[];if(this.parentGroup=a){if(b=a.div,!b){for(;a;)j.push(a),a=a.parentGroup;q(j.reverse(),function(a){var d;b=a.div=a.div||$(Ka,{className:F(a.element,"class")},{position:"absolute",left:(a.translateX||0)+"px",top:(a.translateY||0)+"px"},b||c);d=b.style;r(a,{translateXSetter:function(b,c){d.left=b+"px";a[c]=b;a.doTransform=!0},translateYSetter:function(b,c){d.top=b+"px";a[c]=b;a.doTransform=!0},visibilitySetter:function(a, b){d[b]=a}})})}}else b=c;b.appendChild(e);d.added=!0;d.alignOnAdd&&d.htmlUpdateTransform();return d};return d}});var Z;if(!ba&&!ga){Z={init:function(a,b){var c=["<",b,' filled="f" stroked="f"'],d=["position: ","absolute",";"],e=b===Ka;(b==="shape"||e)&&d.push("left:0;top:0;width:1px;height:1px;");d.push("visibility: ",e?"hidden":"visible");c.push(' style="',d.join(""),'"/>');if(b)c=e||b==="span"||b==="img"?c.join(""):a.prepVML(c),this.element=$(c);this.renderer=a},add:function(a){var b=this.renderer, c=this.element,d=b.box,d=a?a.element||a:d;a&&a.inverted&&b.invertChild(c,d);d.appendChild(c);this.added=!0;this.alignOnAdd&&!this.deferUpdateTransform&&this.updateTransform();if(this.onAdd)this.onAdd();return this},updateTransform:S.prototype.htmlUpdateTransform,setSpanRotation:function(){var a=this.rotation,b=aa(a*Ea),c=fa(a*Ea);B(this.element,{filter:a?["progid:DXImageTransform.Microsoft.Matrix(M11=",b,", M12=",-c,", M21=",c,", M22=",b,", sizingMethod='auto expand')"].join(""):P})},getSpanCorrection:function(a, b,c,d,e){var f=d?aa(d*Ea):1,g=d?fa(d*Ea):0,h=p(this.elemHeight,this.element.offsetHeight),i;this.xCorr=f<0&&-a;this.yCorr=g<0&&-h;i=f*g<0;this.xCorr+=g*b*(i?1-c:c);this.yCorr-=f*b*(d?i?c:1-c:1);e&&e!=="left"&&(this.xCorr-=a*c*(f<0?-1:1),d&&(this.yCorr-=h*c*(g<0?-1:1)),B(this.element,{textAlign:e}))},pathToVML:function(a){for(var b=a.length,c=[];b--;)if(ja(a[b]))c[b]=v(a[b]*10)-5;else if(a[b]==="Z")c[b]="x";else if(c[b]=a[b],a.isArc&&(a[b]==="wa"||a[b]==="at"))c[b+5]===c[b+7]&&(c[b+7]+=a[b+7]>a[b+ 5]?1:-1),c[b+6]===c[b+8]&&(c[b+8]+=a[b+8]>a[b+6]?1:-1);return c.join(" ")||"x"},clip:function(a){var b=this,c;a?(c=a.members,la(c,b),c.push(b),b.destroyClip=function(){la(c,b)},a=a.getCSS(b)):(b.destroyClip&&b.destroyClip(),a={clip:hb?"inherit":"rect(auto)"});return b.css(a)},css:S.prototype.htmlCss,safeRemoveChild:function(a){a.parentNode&&Qa(a)},destroy:function(){this.destroyClip&&this.destroyClip();return S.prototype.destroy.apply(this)},on:function(a,b){this.element["on"+a]=function(){var a= G.event;a.target=a.srcElement;b(a)};return this},cutOffPath:function(a,b){var c,a=a.split(/[ ,]/);c=a.length;if(c===9||c===11)a[c-4]=a[c-2]=y(a[c-2])-10*b;return a.join(" ")},shadow:function(a,b,c){var d=[],e,f=this.element,g=this.renderer,h,i=f.style,j,k=f.path,l,n,m,o;k&&typeof k.value!=="string"&&(k="x");n=k;if(a){m=p(a.width,3);o=(a.opacity||0.15)/m;for(e=1;e<=3;e++){l=m*2+1-2*e;c&&(n=this.cutOffPath(k.value,l+0.5));j=['<shape isShadow="true" strokeweight="',l,'" filled="false" path="',n,'" coordsize="10 10" style="', f.style.cssText,'" />'];h=$(g.prepVML(j),null,{left:y(i.left)+p(a.offsetX,1),top:y(i.top)+p(a.offsetY,1)});if(c)h.cutOff=l+1;j=['<stroke color="',a.color||"black",'" opacity="',o*e,'"/>'];$(g.prepVML(j),null,null,h);b?b.element.appendChild(h):f.parentNode.insertBefore(h,f);d.push(h)}this.shadows=d}return this},updateShadows:sa,setAttr:function(a,b){hb?this.element[a]=b:this.element.setAttribute(a,b)},classSetter:function(a){this.element.className=a},dashstyleSetter:function(a,b,c){(c.getElementsByTagName("stroke")[0]|| $(this.renderer.prepVML(["<stroke/>"]),null,null,c))[b]=a||"solid";this[b]=a},dSetter:function(a,b,c){var d=this.shadows,a=a||[];this.d=a.join&&a.join(" ");c.path=a=this.pathToVML(a);if(d)for(c=d.length;c--;)d[c].path=d[c].cutOff?this.cutOffPath(a,d[c].cutOff):a;this.setAttr(b,a)},fillSetter:function(a,b,c){var d=c.nodeName;if(d==="SPAN")c.style.color=a;else if(d!=="IMG")c.filled=a!==P,this.setAttr("fillcolor",this.renderer.color(a,c,b,this))},opacitySetter:sa,rotationSetter:function(a,b,c){c=c.style; this[b]=c[b]=a;c.left=-v(fa(a*Ea)+1)+"px";c.top=v(aa(a*Ea))+"px"},strokeSetter:function(a,b,c){this.setAttr("strokecolor",this.renderer.color(a,c,b))},"stroke-widthSetter":function(a,b,c){c.stroked=!!a;this[b]=a;ja(a)&&(a+="px");this.setAttr("strokeweight",a)},titleSetter:function(a,b){this.setAttr(b,a)},visibilitySetter:function(a,b,c){a==="inherit"&&(a="visible");this.shadows&&q(this.shadows,function(c){c.style[b]=a});c.nodeName==="DIV"&&(a=a==="hidden"?"-999em":0,hb||(c.style[b]=a?"visible":"hidden"), b="top");c.style[b]=a},xSetter:function(a,b,c){this[b]=a;b==="x"?b="left":b==="y"&&(b="top");this.updateClipping?(this[b]=a,this.updateClipping()):c.style[b]=a},zIndexSetter:function(a,b,c){c.style[b]=a}};K.VMLElement=Z=ma(S,Z);Z.prototype.ySetter=Z.prototype.widthSetter=Z.prototype.heightSetter=Z.prototype.xSetter;var ia={Element:Z,isIE8:wa.indexOf("MSIE 8.0")>-1,init:function(a,b,c,d){var e;this.alignedObjects=[];d=this.createElement(Ka).css(r(this.getStyle(d),{position:"relative"}));e=d.element; a.appendChild(d.element);this.isVML=!0;this.box=e;this.boxWrapper=d;this.cache={};this.setSize(b,c,!1);if(!x.namespaces.hcv){x.namespaces.add("hcv","urn:schemas-microsoft-com:vml");try{x.createStyleSheet().cssText="hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke{ behavior:url(#default#VML); display: inline-block; } "}catch(f){x.styleSheets[0].cssText+="hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke{ behavior:url(#default#VML); display: inline-block; } "}}},isHidden:function(){return!this.box.offsetWidth}, clipRect:function(a,b,c,d){var e=this.createElement(),f=da(a);return r(e,{members:[],left:(f?a.x:a)+1,top:(f?a.y:b)+1,width:(f?a.width:c)-1,height:(f?a.height:d)-1,getCSS:function(a){var b=a.element,c=b.nodeName,a=a.inverted,d=this.top-(c==="shape"?b.offsetTop:0),e=this.left,b=e+this.width,f=d+this.height,d={clip:"rect("+v(a?e:d)+"px,"+v(a?f:b)+"px,"+v(a?b:f)+"px,"+v(a?d:e)+"px)"};!a&&hb&&c==="DIV"&&r(d,{width:b+"px",height:f+"px"});return d},updateClipping:function(){q(e.members,function(a){a.element&& a.css(e.getCSS(a))})}})},color:function(a,b,c,d){var e=this,f,g=/^rgba/,h,i,j=P;a&&a.linearGradient?i="gradient":a&&a.radialGradient&&(i="pattern");if(i){var k,l,n=a.linearGradient||a.radialGradient,m,o,p,D,J,C="",a=a.stops,t,s=[],u=function(){h=['<fill colors="'+s.join(",")+'" opacity="',p,'" o:opacity2="',o,'" type="',i,'" ',C,'focus="100%" method="any" />'];$(e.prepVML(h),null,null,b)};m=a[0];t=a[a.length-1];m[0]>0&&a.unshift([0,m[1]]);t[0]<1&&a.push([1,t[1]]);q(a,function(a,b){g.test(a[1])?(f= ya(a[1]),k=f.get("rgb"),l=f.get("a")):(k=a[1],l=1);s.push(a[0]*100+"% "+k);b?(p=l,D=k):(o=l,J=k)});if(c==="fill")if(i==="gradient")c=n.x1||n[0]||0,a=n.y1||n[1]||0,m=n.x2||n[2]||0,n=n.y2||n[3]||0,C='angle="'+(90-V.atan((n-a)/(m-c))*180/oa)+'"',u();else{var j=n.r,r=j*2,v=j*2,x=n.cx,z=n.cy,R=b.radialReference,w,j=function(){R&&(w=d.getBBox(),x+=(R[0]-w.x)/w.width-0.5,z+=(R[1]-w.y)/w.height-0.5,r*=R[2]/w.width,v*=R[2]/w.height);C='src="'+E.global.VMLRadialGradientURL+'" size="'+r+","+v+'" origin="0.5,0.5" position="'+ x+","+z+'" color2="'+J+'" ';u()};d.added?j():d.onAdd=j;j=D}else j=k}else if(g.test(a)&&b.tagName!=="IMG")f=ya(a),h=["<",c,' opacity="',f.get("a"),'"/>'],$(this.prepVML(h),null,null,b),j=f.get("rgb");else{j=b.getElementsByTagName(c);if(j.length)j[0].opacity=1,j[0].type="solid";j=a}return j},prepVML:function(a){var b=this.isIE8,a=a.join("");b?(a=a.replace("/>",' xmlns="urn:schemas-microsoft-com:vml" />'),a=a.indexOf('style="')===-1?a.replace("/>",' style="display:inline-block;behavior:url(#default#VML);" />'): a.replace('style="','style="display:inline-block;behavior:url(#default#VML);')):a=a.replace("<","<hcv:");return a},text:ta.prototype.html,path:function(a){var b={coordsize:"10 10"};Ha(a)?b.d=a:da(a)&&r(b,a);return this.createElement("shape").attr(b)},circle:function(a,b,c){var d=this.symbol("circle");if(da(a))c=a.r,b=a.y,a=a.x;d.isCircle=!0;d.r=c;return d.attr({x:a,y:b})},g:function(a){var b;a&&(b={className:"highcharts-"+a,"class":"highcharts-"+a});return this.createElement(Ka).attr(b)},image:function(a, b,c,d,e){var f=this.createElement("img").attr({src:a});arguments.length>1&&f.attr({x:b,y:c,width:d,height:e});return f},createElement:function(a){return a==="rect"?this.symbol(a):ta.prototype.createElement.call(this,a)},invertChild:function(a,b){var c=this,d=b.style,e=a.tagName==="IMG"&&a.style;B(a,{flip:"x",left:y(d.width)-(e?y(e.top):1),top:y(d.height)-(e?y(e.left):1),rotation:-90});q(a.childNodes,function(b){c.invertChild(b,a)})},symbols:{arc:function(a,b,c,d,e){var f=e.start,g=e.end,h=e.r||c|| d,c=e.innerR,d=aa(f),i=fa(f),j=aa(g),k=fa(g);if(g-f===0)return["x"];f=["wa",a-h,b-h,a+h,b+h,a+h*d,b+h*i,a+h*j,b+h*k];e.open&&!c&&f.push("e","M",a,b);f.push("at",a-c,b-c,a+c,b+c,a+c*j,b+c*k,a+c*d,b+c*i,"x","e");f.isArc=!0;return f},circle:function(a,b,c,d,e){e&&(c=d=2*e.r);e&&e.isCircle&&(a-=c/2,b-=d/2);return["wa",a,b,a+c,b+d,a+c,b+d/2,a+c,b+d/2,"e"]},rect:function(a,b,c,d,e){return ta.prototype.symbols[!s(e)||!e.r?"square":"callout"].call(0,a,b,c,d,e)}}};K.VMLRenderer=Z=function(){this.init.apply(this, arguments)};Z.prototype=w(ta.prototype,ia);Za=Z}ta.prototype.measureSpanWidth=function(a,b){var c=x.createElement("span"),d;d=x.createTextNode(a);c.appendChild(d);B(c,b);this.box.appendChild(c);d=c.offsetWidth;Qa(c);return d};var Mb;if(ga)K.CanVGRenderer=Z=function(){xa="http://www.w3.org/1999/xhtml"},Z.prototype.symbols={},Mb=function(){function a(){var a=b.length,d;for(d=0;d<a;d++)b[d]();b=[]}var b=[];return{push:function(c,d){b.length===0&&Rb(d,a);b.push(c)}}}(),Za=Z;Ta.prototype={addLabel:function(){var a= this.axis,b=a.options,c=a.chart,d=a.horiz,e=a.categories,f=a.names,g=this.pos,h=b.labels,i=h.rotation,j=a.tickPositions,d=d&&e&&!h.step&&!h.staggerLines&&!h.rotation&&c.plotWidth/j.length||!d&&(c.margin[3]||c.chartWidth*0.33),k=g===j[0],l=g===j[j.length-1],n,f=e?p(e[g],f[g],g):g,e=this.label,m=j.info;a.isDatetimeAxis&&m&&(n=b.dateTimeLabelFormats[m.higherRanks[g]||m.unitName]);this.isFirst=k;this.isLast=l;b=a.labelFormatter.call({axis:a,chart:c,isFirst:k,isLast:l,dateTimeLabelFormat:n,value:a.isLog? ea(ka(f)):f});g=d&&{width:t(1,v(d-2*(h.padding||10)))+"px"};if(s(e))e&&e.attr({text:b}).css(g);else{n={align:a.labelAlign};if(ja(i))n.rotation=i;if(d&&h.ellipsis)g.HcHeight=a.len/j.length;this.label=e=s(b)&&h.enabled?c.renderer.text(b,0,0,h.useHTML).attr(n).css(r(g,h.style)).add(a.labelGroup):null;a.tickBaseline=c.renderer.fontMetrics(h.style.fontSize,e).b;i&&a.side===2&&(a.tickBaseline*=aa(i*Ea))}this.yOffset=e?p(h.y,a.tickBaseline+(a.side===2?8:-(e.getBBox().height/2))):0},getLabelSize:function(){var a= this.label,b=this.axis;return a?a.getBBox()[b.horiz?"height":"width"]:0},getLabelSides:function(){var a=this.label.getBBox(),b=this.axis,c=b.horiz,d=b.options.labels,a=c?a.width:a.height,b=c?d.x-a*{left:0,center:0.5,right:1}[b.labelAlign]:0;return[b,c?a+b:a]},handleOverflow:function(a,b){var c=!0,d=this.axis,e=this.isFirst,f=this.isLast,g=d.horiz?b.x:b.y,h=d.reversed,i=d.tickPositions,j=this.getLabelSides(),k=j[0],j=j[1],l,n,m,o=this.label.line;l=o||0;n=d.labelEdge;m=d.justifyLabels&&(e||f);n[l]=== u||g+k>n[l]?n[l]=g+j:m||(c=!1);if(m){l=(n=d.justifyToPlot)?d.pos:0;n=n?l+d.len:d.chart.chartWidth;do a+=e?1:-1,m=d.ticks[i[a]];while(i[a]&&(!m||!m.label||m.label.line!==o));d=m&&m.label.xy&&m.label.xy.x+m.getLabelSides()[e?0:1];e&&!h||f&&h?g+k<l&&(g=l-k,m&&g+j>d&&(c=!1)):g+j>n&&(g=n-j,m&&g+k<d&&(c=!1));b.x=g}return c},getPosition:function(a,b,c,d){var e=this.axis,f=e.chart,g=d&&f.oldChartHeight||f.chartHeight;return{x:a?e.translate(b+c,null,null,d)+e.transB:e.left+e.offset+(e.opposite?(d&&f.oldChartWidth|| f.chartWidth)-e.right-e.left:0),y:a?g-e.bottom+e.offset-(e.opposite?e.height:0):g-e.translate(b+c,null,null,d)-e.transB}},getLabelPosition:function(a,b,c,d,e,f,g,h){var i=this.axis,j=i.transA,k=i.reversed,l=i.staggerLines,a=a+e.x-(f&&d?f*j*(k?-1:1):0),b=b+this.yOffset-(f&&!d?f*j*(k?1:-1):0);if(l)c.line=g/(h||1)%l,b+=c.line*(i.labelOffset/l);return{x:a,y:b}},getMarkPath:function(a,b,c,d,e,f){return f.crispLine(["M",a,b,"L",a+(e?0:-c),b+(e?c:0)],d)},render:function(a,b,c){var d=this.axis,e=d.options, f=d.chart.renderer,g=d.horiz,h=this.type,i=this.label,j=this.pos,k=e.labels,l=this.gridLine,n=h?h+"Grid":"grid",m=h?h+"Tick":"tick",o=e[n+"LineWidth"],q=e[n+"LineColor"],D=e[n+"LineDashStyle"],J=e[m+"Length"],n=e[m+"Width"]||0,C=e[m+"Color"],t=e[m+"Position"],m=this.mark,s=k.step,r=!0,v=d.tickmarkOffset,w=this.getPosition(g,j,v,b),x=w.x,w=w.y,z=g&&x===d.pos+d.len||!g&&w===d.pos?-1:1,c=p(c,1);this.isActive=!0;if(o){j=d.getPlotLinePath(j+v,o*z,b,!0);if(l===u){l={stroke:q,"stroke-width":o};if(D)l.dashstyle= D;if(!h)l.zIndex=1;if(b)l.opacity=0;this.gridLine=l=o?f.path(j).attr(l).add(d.gridGroup):null}if(!b&&l&&j)l[this.isNew?"attr":"animate"]({d:j,opacity:c})}if(n&&J)t==="inside"&&(J=-J),d.opposite&&(J=-J),h=this.getMarkPath(x,w,J,n*z,g,f),m?m.animate({d:h,opacity:c}):this.mark=f.path(h).attr({stroke:C,"stroke-width":n,opacity:c}).add(d.axisGroup);if(i&&!isNaN(x))i.xy=w=this.getLabelPosition(x,w,i,g,k,v,a,s),this.isFirst&&!this.isLast&&!p(e.showFirstLabel,1)||this.isLast&&!this.isFirst&&!p(e.showLastLabel, 1)?r=!1:!d.isRadial&&!k.step&&!k.rotation&&!b&&c!==0&&(r=this.handleOverflow(a,w)),s&&a%s&&(r=!1),r&&!isNaN(w.y)?(w.opacity=c,i[this.isNew?"attr":"animate"](w),this.isNew=!1):i.attr("y",-9999)},destroy:function(){Pa(this,this.axis)}};K.PlotLineOrBand=function(a,b){this.axis=a;if(b)this.options=b,this.id=b.id};K.PlotLineOrBand.prototype={render:function(){var a=this,b=a.axis,c=b.horiz,d=(b.pointRange||0)/2,e=a.options,f=e.label,g=a.label,h=e.width,i=e.to,j=e.from,k=s(j)&&s(i),l=e.value,n=e.dashStyle, m=a.svgElem,o=[],p,q=e.color,J=e.zIndex,C=e.events,r={},u=b.chart.renderer;b.isLog&&(j=za(j),i=za(i),l=za(l));if(h){if(o=b.getPlotLinePath(l,h),r={stroke:q,"stroke-width":h},n)r.dashstyle=n}else if(k){j=t(j,b.min-d);i=L(i,b.max+d);o=b.getPlotBandPath(j,i,e);if(q)r.fill=q;if(e.borderWidth)r.stroke=e.borderColor,r["stroke-width"]=e.borderWidth}else return;if(s(J))r.zIndex=J;if(m)if(o)m.animate({d:o},null,m.onGetPath);else{if(m.hide(),m.onGetPath=function(){m.show()},g)a.label=g=g.destroy()}else if(o&& o.length&&(a.svgElem=m=u.path(o).attr(r).add(),C))for(p in d=function(b){m.on(b,function(c){C[b].apply(a,[c])})},C)d(p);if(f&&s(f.text)&&o&&o.length&&b.width>0&&b.height>0){f=w({align:c&&k&&"center",x:c?!k&&4:10,verticalAlign:!c&&k&&"middle",y:c?k?16:10:k?6:-4,rotation:c&&!k&&90},f);if(!g){r={align:f.textAlign||f.align,rotation:f.rotation};if(s(J))r.zIndex=J;a.label=g=u.text(f.text,0,0,f.useHTML).attr(r).css(f.style).add()}b=[o[1],o[4],k?o[6]:o[1]];k=[o[2],o[5],k?o[7]:o[2]];o=Oa(b);c=Oa(k);g.align(f, !1,{x:o,y:c,width:Ca(b)-o,height:Ca(k)-c});g.show()}else g&&g.hide();return a},destroy:function(){la(this.axis.plotLinesAndBands,this);delete this.axis;Pa(this)}};na.prototype={defaultOptions:{dateTimeLabelFormats:{millisecond:"%H:%M:%S.%L",second:"%H:%M:%S",minute:"%H:%M",hour:"%H:%M",day:"%e. %b",week:"%e. %b",month:"%b '%y",year:"%Y"},endOnTick:!1,gridLineColor:"#C0C0C0",labels:M,lineColor:"#C0D0E0",lineWidth:1,minPadding:0.01,maxPadding:0.01,minorGridLineColor:"#E0E0E0",minorGridLineWidth:1,minorTickColor:"#A0A0A0", minorTickLength:2,minorTickPosition:"outside",startOfWeek:1,startOnTick:!1,tickColor:"#C0D0E0",tickLength:10,tickmarkPlacement:"between",tickPixelInterval:100,tickPosition:"outside",tickWidth:1,title:{align:"middle",style:{color:"#707070"}},type:"linear"},defaultYAxisOptions:{endOnTick:!0,gridLineWidth:1,tickPixelInterval:72,showLastLabel:!0,labels:{x:-8,y:3},lineWidth:0,maxPadding:0.05,minPadding:0.05,startOnTick:!0,tickWidth:0,title:{rotation:270,text:"Values"},stackLabels:{enabled:!1,formatter:function(){return Ba(this.total, -1)},style:M.style}},defaultLeftAxisOptions:{labels:{x:-15,y:null},title:{rotation:270}},defaultRightAxisOptions:{labels:{x:15,y:null},title:{rotation:90}},defaultBottomAxisOptions:{labels:{x:0,y:null},title:{rotation:0}},defaultTopAxisOptions:{labels:{x:0,y:-15},title:{rotation:0}},init:function(a,b){var c=b.isX;this.horiz=a.inverted?!c:c;this.coll=(this.isXAxis=c)?"xAxis":"yAxis";this.opposite=b.opposite;this.side=b.side||(this.horiz?this.opposite?0:2:this.opposite?1:3);this.setOptions(b);var d= this.options,e=d.type;this.labelFormatter=d.labels.formatter||this.defaultLabelFormatter;this.userOptions=b;this.minPixelPadding=0;this.chart=a;this.reversed=d.reversed;this.zoomEnabled=d.zoomEnabled!==!1;this.categories=d.categories||e==="category";this.names=[];this.isLog=e==="logarithmic";this.isDatetimeAxis=e==="datetime";this.isLinked=s(d.linkedTo);this.tickmarkOffset=this.categories&&d.tickmarkPlacement==="between"&&p(d.tickInterval,1)===1?0.5:0;this.ticks={};this.labelEdge=[];this.minorTicks= {};this.plotLinesAndBands=[];this.alternateBands={};this.len=0;this.minRange=this.userMinRange=d.minRange||d.maxZoom;this.range=d.range;this.offset=d.offset||0;this.stacks={};this.oldStacks={};this.min=this.max=null;this.crosshair=p(d.crosshair,ra(a.options.tooltip.crosshairs)[c?0:1],!1);var f,d=this.options.events;Ma(this,a.axes)===-1&&(c&&!this.isColorAxis?a.axes.splice(a.xAxis.length,0,this):a.axes.push(this),a[this.coll].push(this));this.series=this.series||[];if(a.inverted&&c&&this.reversed=== u)this.reversed=!0;this.removePlotLine=this.removePlotBand=this.removePlotBandOrLine;for(f in d)N(this,f,d[f]);if(this.isLog)this.val2lin=za,this.lin2val=ka},setOptions:function(a){this.options=w(this.defaultOptions,this.isXAxis?{}:this.defaultYAxisOptions,[this.defaultTopAxisOptions,this.defaultRightAxisOptions,this.defaultBottomAxisOptions,this.defaultLeftAxisOptions][this.side],w(E[this.coll],a))},defaultLabelFormatter:function(){var a=this.axis,b=this.value,c=a.categories,d=this.dateTimeLabelFormat, e=E.lang.numericSymbols,f=e&&e.length,g,h=a.options.labels.format,a=a.isLog?b:a.tickInterval;if(h)g=Ja(h,this);else if(c)g=b;else if(d)g=cb(d,b);else if(f&&a>=1E3)for(;f--&&g===u;)c=Math.pow(1E3,f+1),a>=c&&e[f]!==null&&(g=Ba(b/c,-1)+e[f]);g===u&&(g=Q(b)>=1E4?Ba(b,0):Ba(b,-1,u,""));return g},getSeriesExtremes:function(){var a=this,b=a.chart;a.hasVisibleSeries=!1;a.dataMin=a.dataMax=a.ignoreMinPadding=a.ignoreMaxPadding=null;a.buildStacks&&a.buildStacks();q(a.series,function(c){if(c.visible||!b.options.chart.ignoreHiddenSeries){var d; d=c.options.threshold;var e;a.hasVisibleSeries=!0;a.isLog&&d<=0&&(d=null);if(a.isXAxis){if(d=c.xData,d.length)a.dataMin=L(p(a.dataMin,d[0]),Oa(d)),a.dataMax=t(p(a.dataMax,d[0]),Ca(d))}else{c.getExtremes();e=c.dataMax;c=c.dataMin;if(s(c)&&s(e))a.dataMin=L(p(a.dataMin,c),c),a.dataMax=t(p(a.dataMax,e),e);if(s(d))if(a.dataMin>=d)a.dataMin=d,a.ignoreMinPadding=!0;else if(a.dataMax<d)a.dataMax=d,a.ignoreMaxPadding=!0}}})},translate:function(a,b,c,d,e,f){var g=1,h=0,i=d?this.oldTransA:this.transA,d=d?this.oldMin: this.min,j=this.minPixelPadding,e=(this.options.ordinal||this.isLog&&e)&&this.lin2val;if(!i)i=this.transA;if(c)g*=-1,h=this.len;this.reversed&&(g*=-1,h-=g*(this.sector||this.len));b?(a=a*g+h,a-=j,a=a/i+d,e&&(a=this.lin2val(a))):(e&&(a=this.val2lin(a)),f==="between"&&(f=0.5),a=g*(a-d)*i+h+g*j+(ja(f)?i*f*this.pointRange:0));return a},toPixels:function(a,b){return this.translate(a,!1,!this.horiz,null,!0)+(b?0:this.pos)},toValue:function(a,b){return this.translate(a-(b?0:this.pos),!0,!this.horiz,null, !0)},getPlotLinePath:function(a,b,c,d,e){var f=this.chart,g=this.left,h=this.top,i,j,k=c&&f.oldChartHeight||f.chartHeight,l=c&&f.oldChartWidth||f.chartWidth,n;i=this.transB;e=p(e,this.translate(a,null,null,c));a=c=v(e+i);i=j=v(k-e-i);if(isNaN(e))n=!0;else if(this.horiz){if(i=h,j=k-this.bottom,a<g||a>g+this.width)n=!0}else if(a=g,c=l-this.right,i<h||i>h+this.height)n=!0;return n&&!d?null:f.renderer.crispLine(["M",a,i,"L",c,j],b||1)},getLinearTickPositions:function(a,b,c){var d,e=ea(U(b/a)*a),f=ea(La(c/ a)*a),g=[];if(b===c&&ja(b))return[b];for(b=e;b<=f;){g.push(b);b=ea(b+a);if(b===d)break;d=b}return g},getMinorTickPositions:function(){var a=this.options,b=this.tickPositions,c=this.minorTickInterval,d=[],e;if(this.isLog){e=b.length;for(a=1;a<e;a++)d=d.concat(this.getLogTickPositions(c,b[a-1],b[a],!0))}else if(this.isDatetimeAxis&&a.minorTickInterval==="auto")d=d.concat(this.getTimeTicks(this.normalizeTimeTickInterval(c),this.min,this.max,a.startOfWeek)),d[0]<this.min&&d.shift();else for(b=this.min+ (b[0]-this.min)%c;b<=this.max;b+=c)d.push(b);return d},adjustForMinRange:function(){var a=this.options,b=this.min,c=this.max,d,e=this.dataMax-this.dataMin>=this.minRange,f,g,h,i,j;if(this.isXAxis&&this.minRange===u&&!this.isLog)s(a.min)||s(a.max)?this.minRange=null:(q(this.series,function(a){i=a.xData;for(g=j=a.xIncrement?1:i.length-1;g>0;g--)if(h=i[g]-i[g-1],f===u||h<f)f=h}),this.minRange=L(f*5,this.dataMax-this.dataMin));if(c-b<this.minRange){var k=this.minRange;d=(k-c+b)/2;d=[b-d,p(a.min,b-d)]; if(e)d[2]=this.dataMin;b=Ca(d);c=[b+k,p(a.max,b+k)];if(e)c[2]=this.dataMax;c=Oa(c);c-b<k&&(d[0]=c-k,d[1]=p(a.min,c-k),b=Ca(d))}this.min=b;this.max=c},setAxisTranslation:function(a){var b=this,c=b.max-b.min,d=b.axisPointRange||0,e,f=0,g=0,h=b.linkedParent,i=!!b.categories,j=b.transA;if(b.isXAxis||i||d)h?(f=h.minPointOffset,g=h.pointRangePadding):q(b.series,function(a){var h=i?1:b.isXAxis?a.pointRange:b.axisPointRange||0,j=a.options.pointPlacement,m=a.closestPointRange;h>c&&(h=0);d=t(d,h);f=t(f,Ga(j)? 0:h/2);g=t(g,j==="on"?0:h);!a.noSharedTooltip&&s(m)&&(e=s(e)?L(e,m):m)}),h=b.ordinalSlope&&e?b.ordinalSlope/e:1,b.minPointOffset=f*=h,b.pointRangePadding=g*=h,b.pointRange=L(d,c),b.closestPointRange=e;if(a)b.oldTransA=j;b.translationSlope=b.transA=j=b.len/(c+g||1);b.transB=b.horiz?b.left:b.bottom;b.minPixelPadding=j*f},setTickPositions:function(a){var b=this,c=b.chart,d=b.options,e=d.startOnTick,f=d.endOnTick,g=b.isLog,h=b.isDatetimeAxis,i=b.isXAxis,j=b.isLinked,k=b.options.tickPositioner,l=d.maxPadding, n=d.minPadding,m=d.tickInterval,o=d.minTickInterval,Y=d.tickPixelInterval,D,J=b.categories;j?(b.linkedParent=c[b.coll][d.linkedTo],c=b.linkedParent.getExtremes(),b.min=p(c.min,c.dataMin),b.max=p(c.max,c.dataMax),d.type!==b.linkedParent.options.type&&ha(11,1)):(b.min=p(b.userMin,d.min,b.dataMin),b.max=p(b.userMax,d.max,b.dataMax));if(g)!a&&L(b.min,p(b.dataMin,b.min))<=0&&ha(10,1),b.min=ea(za(b.min)),b.max=ea(za(b.max));if(b.range&&s(b.max))b.userMin=b.min=t(b.min,b.max-b.range),b.userMax=b.max,b.range= null;b.beforePadding&&b.beforePadding();b.adjustForMinRange();if(!J&&!b.axisPointRange&&!b.usePercentage&&!j&&s(b.min)&&s(b.max)&&(c=b.max-b.min)){if(!s(d.min)&&!s(b.userMin)&&n&&(b.dataMin<0||!b.ignoreMinPadding))b.min-=c*n;if(!s(d.max)&&!s(b.userMax)&&l&&(b.dataMax>0||!b.ignoreMaxPadding))b.max+=c*l}if(ja(d.floor))b.min=t(b.min,d.floor);if(ja(d.ceiling))b.max=L(b.max,d.ceiling);b.min===b.max||b.min===void 0||b.max===void 0?b.tickInterval=1:j&&!m&&Y===b.linkedParent.options.tickPixelInterval?b.tickInterval= b.linkedParent.tickInterval:(b.tickInterval=p(m,J?1:(b.max-b.min)*Y/t(b.len,Y)),!s(m)&&b.len<Y&&!this.isRadial&&!this.isLog&&!J&&e&&f&&(D=!0,b.tickInterval/=4));i&&!a&&q(b.series,function(a){a.processData(b.min!==b.oldMin||b.max!==b.oldMax)});b.setAxisTranslation(!0);b.beforeSetTickPositions&&b.beforeSetTickPositions();if(b.postProcessTickInterval)b.tickInterval=b.postProcessTickInterval(b.tickInterval);if(b.pointRange)b.tickInterval=t(b.pointRange,b.tickInterval);if(!m&&b.tickInterval<o)b.tickInterval= o;if(!h&&!g&&!m)b.tickInterval=nb(b.tickInterval,null,mb(b.tickInterval),p(d.allowDecimals,!(b.tickInterval>1&&b.tickInterval<5&&b.max>1E3&&b.max<9999)));b.minorTickInterval=d.minorTickInterval==="auto"&&b.tickInterval?b.tickInterval/5:d.minorTickInterval;b.tickPositions=a=d.tickPositions?[].concat(d.tickPositions):k&&k.apply(b,[b.min,b.max]);if(!a)!b.ordinalPositions&&(b.max-b.min)/b.tickInterval>t(2*b.len,200)&&ha(19,!0),a=h?b.getTimeTicks(b.normalizeTimeTickInterval(b.tickInterval,d.units),b.min, b.max,d.startOfWeek,b.ordinalPositions,b.closestPointRange,!0):g?b.getLogTickPositions(b.tickInterval,b.min,b.max):b.getLinearTickPositions(b.tickInterval,b.min,b.max),D&&a.splice(1,a.length-2),b.tickPositions=a;if(!j)d=a[0],g=a[a.length-1],h=b.minPointOffset||0,e?b.min=d:b.min-h>d&&a.shift(),f?b.max=g:b.max+h<g&&a.pop(),a.length===0&&s(d)&&a.push((g+d)/2),a.length===1&&(e=Q(b.max)>1E13?1:0.001,b.min-=e,b.max+=e)},setMaxTicks:function(){var a=this.chart,b=a.maxTicks||{},c=this.tickPositions,d=this._maxTicksKey= [this.coll,this.pos,this.len].join("-");if(!this.isLinked&&!this.isDatetimeAxis&&c&&c.length>(b[d]||0)&&this.options.alignTicks!==!1)b[d]=c.length;a.maxTicks=b},adjustTickAmount:function(){var a=this._maxTicksKey,b=this.tickPositions,c=this.chart.maxTicks;if(c&&c[a]&&!this.isDatetimeAxis&&!this.categories&&!this.isLinked&&this.options.alignTicks!==!1&&this.min!==u){var d=this.tickAmount,e=b.length;this.tickAmount=a=c[a];if(e<a){for(;b.length<a;)b.push(ea(b[b.length-1]+this.tickInterval));this.transA*= (e-1)/(a-1);this.max=b[b.length-1]}if(s(d)&&a!==d)this.isDirty=!0}},setScale:function(){var a=this.stacks,b,c,d,e;this.oldMin=this.min;this.oldMax=this.max;this.oldAxisLength=this.len;this.setAxisSize();e=this.len!==this.oldAxisLength;q(this.series,function(a){if(a.isDirtyData||a.isDirty||a.xAxis.isDirty)d=!0});if(e||d||this.isLinked||this.forceRedraw||this.userMin!==this.oldUserMin||this.userMax!==this.oldUserMax){if(!this.isXAxis)for(b in a)for(c in a[b])a[b][c].total=null,a[b][c].cum=0;this.forceRedraw= !1;this.getSeriesExtremes();this.setTickPositions();this.oldUserMin=this.userMin;this.oldUserMax=this.userMax;if(!this.isDirty)this.isDirty=e||this.min!==this.oldMin||this.max!==this.oldMax}else if(!this.isXAxis){if(this.oldStacks)a=this.stacks=this.oldStacks;for(b in a)for(c in a[b])a[b][c].cum=a[b][c].total}this.setMaxTicks()},setExtremes:function(a,b,c,d,e){var f=this,g=f.chart,c=p(c,!0),e=r(e,{min:a,max:b});I(f,"setExtremes",e,function(){f.userMin=a;f.userMax=b;f.eventArgs=e;f.isDirtyExtremes= !0;c&&g.redraw(d)})},zoom:function(a,b){var c=this.dataMin,d=this.dataMax,e=this.options;this.allowZoomOutside||(s(c)&&a<=L(c,p(e.min,c))&&(a=u),s(d)&&b>=t(d,p(e.max,d))&&(b=u));this.displayBtn=a!==u||b!==u;this.setExtremes(a,b,!1,u,{trigger:"zoom"});return!0},setAxisSize:function(){var a=this.chart,b=this.options,c=b.offsetLeft||0,d=this.horiz,e=p(b.width,a.plotWidth-c+(b.offsetRight||0)),f=p(b.height,a.plotHeight),g=p(b.top,a.plotTop),b=p(b.left,a.plotLeft+c),c=/%$/;c.test(f)&&(f=parseInt(f,10)/ 100*a.plotHeight);c.test(g)&&(g=parseInt(g,10)/100*a.plotHeight+a.plotTop);this.left=b;this.top=g;this.width=e;this.height=f;this.bottom=a.chartHeight-f-g;this.right=a.chartWidth-e-b;this.len=t(d?e:f,0);this.pos=d?b:g},getExtremes:function(){var a=this.isLog;return{min:a?ea(ka(this.min)):this.min,max:a?ea(ka(this.max)):this.max,dataMin:this.dataMin,dataMax:this.dataMax,userMin:this.userMin,userMax:this.userMax}},getThreshold:function(a){var b=this.isLog,c=b?ka(this.min):this.min,b=b?ka(this.max): this.max;c>a||a===null?a=c:b<a&&(a=b);return this.translate(a,0,1,0,1)},autoLabelAlign:function(a){a=(p(a,0)-this.side*90+720)%360;return a>15&&a<165?"right":a>195&&a<345?"left":"center"},getOffset:function(){var a=this,b=a.chart,c=b.renderer,d=a.options,e=a.tickPositions,f=a.ticks,g=a.horiz,h=a.side,i=b.inverted?[1,0,3,2][h]:h,j,k,l=0,n,m=0,o=d.title,Y=d.labels,D=0,J=b.axisOffset,b=b.clipOffset,C=[-1,1,1,-1][h],r,v=1,w=p(Y.maxStaggerLines,5),x,y,A,z,R;a.hasData=j=a.hasVisibleSeries||s(a.min)&&s(a.max)&& !!e;a.showAxis=k=j||p(d.showEmpty,!0);a.staggerLines=a.horiz&&Y.staggerLines;if(!a.axisGroup)a.gridGroup=c.g("grid").attr({zIndex:d.gridZIndex||1}).add(),a.axisGroup=c.g("axis").attr({zIndex:d.zIndex||2}).add(),a.labelGroup=c.g("axis-labels").attr({zIndex:Y.zIndex||7}).addClass("highcharts-"+a.coll.toLowerCase()+"-labels").add();if(j||a.isLinked){a.labelAlign=p(Y.align||a.autoLabelAlign(Y.rotation));q(e,function(b){f[b]?f[b].addLabel():f[b]=new Ta(a,b)});if(a.horiz&&!a.staggerLines&&w&&!Y.rotation){for(j= a.reversed?[].concat(e).reverse():e;v<w;){x=[];y=!1;for(r=0;r<j.length;r++)A=j[r],z=(z=f[A].label&&f[A].label.getBBox())?z.width:0,R=r%v,z&&(A=a.translate(A),x[R]!==u&&A<x[R]&&(y=!0),x[R]=A+z);if(y)v++;else break}if(v>1)a.staggerLines=v}q(e,function(b){if(h===0||h===2||{1:"left",3:"right"}[h]===a.labelAlign)D=t(f[b].getLabelSize(),D)});if(a.staggerLines)D*=a.staggerLines,a.labelOffset=D}else for(r in f)f[r].destroy(),delete f[r];if(o&&o.text&&o.enabled!==!1){if(!a.axisTitle)a.axisTitle=c.text(o.text, 0,0,o.useHTML).attr({zIndex:7,rotation:o.rotation||0,align:o.textAlign||{low:"left",middle:"center",high:"right"}[o.align]}).addClass("highcharts-"+this.coll.toLowerCase()+"-title").css(o.style).add(a.axisGroup),a.axisTitle.isNew=!0;if(k)l=a.axisTitle.getBBox()[g?"height":"width"],n=o.offset,m=s(n)?0:p(o.margin,g?5:10);a.axisTitle[k?"show":"hide"]()}a.offset=C*p(d.offset,J[h]);c=h===2?a.tickBaseline:0;g=D+m+(D&&C*(g?p(Y.y,a.tickBaseline+8):Y.x)-c);a.axisTitleMargin=p(n,g);J[h]=t(J[h],a.axisTitleMargin+ l+C*a.offset,g);b[i]=t(b[i],U(d.lineWidth/2)*2)},getLinePath:function(a){var b=this.chart,c=this.opposite,d=this.offset,e=this.horiz,f=this.left+(c?this.width:0)+d,d=b.chartHeight-this.bottom-(c?this.height:0)+d;c&&(a*=-1);return b.renderer.crispLine(["M",e?this.left:f,e?d:this.top,"L",e?b.chartWidth-this.right:f,e?d:b.chartHeight-this.bottom],a)},getTitlePosition:function(){var a=this.horiz,b=this.left,c=this.top,d=this.len,e=this.options.title,f=a?b:c,g=this.opposite,h=this.offset,i=y(e.style.fontSize|| 12),d={low:f+(a?0:d),middle:f+d/2,high:f+(a?d:0)}[e.align],b=(a?c+this.height:b)+(a?1:-1)*(g?-1:1)*this.axisTitleMargin+(this.side===2?i:0);return{x:a?d:b+(g?this.width:0)+h+(e.x||0),y:a?b-(g?this.height:0)+h:d+(e.y||0)}},render:function(){var a=this,b=a.horiz,c=a.reversed,d=a.chart,e=d.renderer,f=a.options,g=a.isLog,h=a.isLinked,i=a.tickPositions,j,k=a.axisTitle,l=a.ticks,n=a.minorTicks,m=a.alternateBands,o=f.stackLabels,p=f.alternateGridColor,D=a.tickmarkOffset,J=f.lineWidth,C=d.hasRendered&&s(a.oldMin)&& !isNaN(a.oldMin),r=a.hasData,t=a.showAxis,v,w=f.labels.overflow,x=a.justifyLabels=b&&w!==!1,A;a.labelEdge.length=0;a.justifyToPlot=w==="justify";q([l,n,m],function(a){for(var b in a)a[b].isActive=!1});if(r||h)if(a.minorTickInterval&&!a.categories&&q(a.getMinorTickPositions(),function(b){n[b]||(n[b]=new Ta(a,b,"minor"));C&&n[b].isNew&&n[b].render(null,!0);n[b].render(null,!1,1)}),i.length&&(j=i.slice(),(b&&c||!b&&!c)&&j.reverse(),x&&(j=j.slice(1).concat([j[0]])),q(j,function(b,c){x&&(c=c===j.length- 1?0:c+1);if(!h||b>=a.min&&b<=a.max)l[b]||(l[b]=new Ta(a,b)),C&&l[b].isNew&&l[b].render(c,!0,0.1),l[b].render(c)}),D&&a.min===0&&(l[-1]||(l[-1]=new Ta(a,-1,null,!0)),l[-1].render(-1))),p&&q(i,function(b,c){if(c%2===0&&b<a.max)m[b]||(m[b]=new K.PlotLineOrBand(a)),v=b+D,A=i[c+1]!==u?i[c+1]+D:a.max,m[b].options={from:g?ka(v):v,to:g?ka(A):A,color:p},m[b].render(),m[b].isActive=!0}),!a._addedPlotLB)q((f.plotLines||[]).concat(f.plotBands||[]),function(b){a.addPlotBandOrLine(b)}),a._addedPlotLB=!0;q([l,n, m],function(a){var b,c,e=[],f=va?va.duration||500:0,g=function(){for(c=e.length;c--;)a[e[c]]&&!a[e[c]].isActive&&(a[e[c]].destroy(),delete a[e[c]])};for(b in a)if(!a[b].isActive)a[b].render(b,!1,0),a[b].isActive=!1,e.push(b);a===m||!d.hasRendered||!f?g():f&&setTimeout(g,f)});if(J)b=a.getLinePath(J),a.axisLine?a.axisLine.animate({d:b}):a.axisLine=e.path(b).attr({stroke:f.lineColor,"stroke-width":J,zIndex:7}).add(a.axisGroup),a.axisLine[t?"show":"hide"]();if(k&&t)k[k.isNew?"attr":"animate"](a.getTitlePosition()), k.isNew=!1;o&&o.enabled&&a.renderStackTotals();a.isDirty=!1},redraw:function(){this.render();q(this.plotLinesAndBands,function(a){a.render()});q(this.series,function(a){a.isDirty=!0})},destroy:function(a){var b=this,c=b.stacks,d,e=b.plotLinesAndBands;a||X(b);for(d in c)Pa(c[d]),c[d]=null;q([b.ticks,b.minorTicks,b.alternateBands],function(a){Pa(a)});for(a=e.length;a--;)e[a].destroy();q("stackTotalGroup,axisLine,axisTitle,axisGroup,cross,gridGroup,labelGroup".split(","),function(a){b[a]&&(b[a]=b[a].destroy())}); this.cross&&this.cross.destroy()},drawCrosshair:function(a,b){if(this.crosshair)if((s(b)||!p(this.crosshair.snap,!0))===!1)this.hideCrosshair();else{var c,d=this.crosshair,e=d.animation;p(d.snap,!0)?s(b)&&(c=this.chart.inverted!=this.horiz?b.plotX:this.len-b.plotY):c=this.horiz?a.chartX-this.pos:this.len-a.chartY+this.pos;c=this.isRadial?this.getPlotLinePath(this.isXAxis?b.x:p(b.stackY,b.y)):this.getPlotLinePath(null,null,null,null,c);if(c===null)this.hideCrosshair();else if(this.cross)this.cross.attr({visibility:"visible"})[e? "animate":"attr"]({d:c},e);else{e={"stroke-width":d.width||1,stroke:d.color||"#C0C0C0",zIndex:d.zIndex||2};if(d.dashStyle)e.dashstyle=d.dashStyle;this.cross=this.chart.renderer.path(c).attr(e).add()}}},hideCrosshair:function(){this.cross&&this.cross.hide()}};r(na.prototype,{getPlotBandPath:function(a,b){var c=this.getPlotLinePath(b),d=this.getPlotLinePath(a);d&&c?d.push(c[4],c[5],c[1],c[2]):d=null;return d},addPlotBand:function(a){return this.addPlotBandOrLine(a,"plotBands")},addPlotLine:function(a){return this.addPlotBandOrLine(a, "plotLines")},addPlotBandOrLine:function(a,b){var c=(new K.PlotLineOrBand(this,a)).render(),d=this.userOptions;c&&(b&&(d[b]=d[b]||[],d[b].push(a)),this.plotLinesAndBands.push(c));return c},removePlotBandOrLine:function(a){for(var b=this.plotLinesAndBands,c=this.options,d=this.userOptions,e=b.length;e--;)b[e].id===a&&b[e].destroy();q([c.plotLines||[],d.plotLines||[],c.plotBands||[],d.plotBands||[]],function(b){for(e=b.length;e--;)b[e].id===a&&la(b,b[e])})}});na.prototype.getTimeTicks=function(a,b, c,d){var e=[],f={},g=E.global.useUTC,h,i=new Da(b-Sa),j=a.unitRange,k=a.count;if(s(b)){j>=A.second&&(i.setMilliseconds(0),i.setSeconds(j>=A.minute?0:k*U(i.getSeconds()/k)));if(j>=A.minute)i[Cb](j>=A.hour?0:k*U(i[pb]()/k));if(j>=A.hour)i[Db](j>=A.day?0:k*U(i[qb]()/k));if(j>=A.day)i[sb](j>=A.month?1:k*U(i[Xa]()/k));j>=A.month&&(i[Eb](j>=A.year?0:k*U(i[fb]()/k)),h=i[gb]());j>=A.year&&(h-=h%k,i[Fb](h));if(j===A.week)i[sb](i[Xa]()-i[rb]()+p(d,1));b=1;Sa&&(i=new Da(i.getTime()+Sa));h=i[gb]();for(var d= i.getTime(),l=i[fb](),n=i[Xa](),m=(A.day+(g?Sa:i.getTimezoneOffset()*6E4))%A.day;d<c;)e.push(d),j===A.year?d=eb(h+b*k,0):j===A.month?d=eb(h,l+b*k):!g&&(j===A.day||j===A.week)?d=eb(h,l,n+b*k*(j===A.day?1:7)):d+=j*k,b++;e.push(d);q(wb(e,function(a){return j<=A.hour&&a%A.day===m}),function(a){f[a]="day"})}e.info=r(a,{higherRanks:f,totalRange:j*k});return e};na.prototype.normalizeTimeTickInterval=function(a,b){var c=b||[["millisecond",[1,2,5,10,20,25,50,100,200,500]],["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]],d=c[c.length-1],e=A[d[0]],f=d[1],g;for(g=0;g<c.length;g++)if(d=c[g],e=A[d[0]],f=d[1],c[g+1]&&a<=(e*f[f.length-1]+A[c[g+1][0]])/2)break;e===A.year&&a<5*e&&(f=[1,2,5]);c=nb(a/e,f,d[0]==="year"?t(mb(a/e),1):1);return{unitRange:e,count:c,unitName:d[0]}};na.prototype.getLogTickPositions=function(a,b,c,d){var e=this.options,f=this.len,g=[];if(!d)this._minorAutoInterval=null;if(a>=0.5)a=v(a),g=this.getLinearTickPositions(a, b,c);else if(a>=0.08)for(var f=U(b),h,i,j,k,l,e=a>0.3?[1,2,4]:a>0.15?[1,2,4,6,8]:[1,2,3,4,5,6,7,8,9];f<c+1&&!l;f++){i=e.length;for(h=0;h<i&&!l;h++)j=za(ka(f)*e[h]),j>b&&(!d||k<=c)&&k!==u&&g.push(k),k>c&&(l=!0),k=j}else if(b=ka(b),c=ka(c),a=e[d?"minorTickInterval":"tickInterval"],a=p(a==="auto"?null:a,this._minorAutoInterval,(c-b)*(e.tickPixelInterval/(d?5:1))/((d?f/this.tickPositions.length:f)||1)),a=nb(a,null,mb(a)),g=Va(this.getLinearTickPositions(a,b,c),za),!d)this._minorAutoInterval=a/5;if(!d)this.tickInterval= a;return g};var Nb=K.Tooltip=function(){this.init.apply(this,arguments)};Nb.prototype={init:function(a,b){var c=b.borderWidth,d=b.style,e=y(d.padding);this.chart=a;this.options=b;this.crosshairs=[];this.now={x:0,y:0};this.isHidden=!0;this.label=a.renderer.label("",0,0,b.shape||"callout",null,null,b.useHTML,null,"tooltip").attr({padding:e,fill:b.backgroundColor,"stroke-width":c,r:b.borderRadius,zIndex:8}).css(d).css({padding:0}).add().attr({y:-9999});ga||this.label.shadow(b.shadow);this.shared=b.shared}, destroy:function(){if(this.label)this.label=this.label.destroy();clearTimeout(this.hideTimer);clearTimeout(this.tooltipTimeout)},move:function(a,b,c,d){var e=this,f=e.now,g=e.options.animation!==!1&&!e.isHidden&&(Q(a-f.x)>1||Q(b-f.y)>1),h=e.followPointer||e.len>1;r(f,{x:g?(2*f.x+a)/3:a,y:g?(f.y+b)/2:b,anchorX:h?u:g?(2*f.anchorX+c)/3:c,anchorY:h?u:g?(f.anchorY+d)/2:d});e.label.attr(f);if(g)clearTimeout(this.tooltipTimeout),this.tooltipTimeout=setTimeout(function(){e&&e.move(a,b,c,d)},32)},hide:function(a){var b= this,c;clearTimeout(this.hideTimer);if(!this.isHidden)c=this.chart.hoverPoints,this.hideTimer=setTimeout(function(){b.label.fadeOut();b.isHidden=!0},p(a,this.options.hideDelay,500)),c&&q(c,function(a){a.setState()}),this.chart.hoverPoints=null},getAnchor:function(a,b){var c,d=this.chart,e=d.inverted,f=d.plotTop,g=0,h=0,i,a=ra(a);c=a[0].tooltipPos;this.followPointer&&b&&(b.chartX===u&&(b=d.pointer.normalize(b)),c=[b.chartX-d.plotLeft,b.chartY-f]);c||(q(a,function(a){i=a.series.yAxis;g+=a.plotX;h+= (a.plotLow?(a.plotLow+a.plotHigh)/2:a.plotY)+(!e&&i?i.top-f:0)}),g/=a.length,h/=a.length,c=[e?d.plotWidth-h:g,this.shared&&!e&&a.length>1&&b?b.chartY-f:e?d.plotHeight-g:h]);return Va(c,v)},getPosition:function(a,b,c){var d=this.chart,e=this.distance,f={},g,h=["y",d.chartHeight,b,c.plotY+d.plotTop],i=["x",d.chartWidth,a,c.plotX+d.plotLeft],j=c.ttBelow||d.inverted&&!c.negative||!d.inverted&&c.negative,k=function(a,b,c,d){var g=c<d-e,b=d+e+c<b,c=d-e-c;d+=e;if(j&&b)f[a]=d;else if(!j&&g)f[a]=c;else if(g)f[a]= c;else if(b)f[a]=d;else return!1},l=function(a,b,c,d){if(d<e||d>b-e)return!1;else f[a]=d<c/2?1:d>b-c/2?b-c-2:d-c/2},n=function(a){var b=h;h=i;i=b;g=a},m=function(){k.apply(0,h)!==!1?l.apply(0,i)===!1&&!g&&(n(!0),m()):g?f.x=f.y=0:(n(!0),m())};(d.inverted||this.len>1)&&n();m();return f},defaultFormatter:function(a){var b=this.points||ra(this),c=b[0].series,d;d=[a.tooltipHeaderFormatter(b[0])];q(b,function(a){c=a.series;d.push(c.tooltipFormatter&&c.tooltipFormatter(a)||a.point.tooltipFormatter(c.tooltipOptions.pointFormat))}); d.push(a.options.footerFormat||"");return d.join("")},refresh:function(a,b){var c=this.chart,d=this.label,e=this.options,f,g,h={},i,j=[];i=e.formatter||this.defaultFormatter;var h=c.hoverPoints,k,l=this.shared;clearTimeout(this.hideTimer);this.followPointer=ra(a)[0].series.tooltipOptions.followPointer;g=this.getAnchor(a,b);f=g[0];g=g[1];l&&(!a.series||!a.series.noSharedTooltip)?(c.hoverPoints=a,h&&q(h,function(a){a.setState()}),q(a,function(a){a.setState("hover");j.push(a.getLabelConfig())}),h={x:a[0].category, y:a[0].y},h.points=j,this.len=j.length,a=a[0]):h=a.getLabelConfig();i=i.call(h,this);h=a.series;this.distance=p(h.tooltipOptions.distance,16);i===!1?this.hide():(this.isHidden&&(bb(d),d.attr("opacity",1).show()),d.attr({text:i}),k=e.borderColor||a.color||h.color||"#606060",d.attr({stroke:k}),this.updatePosition({plotX:f,plotY:g,negative:a.negative,ttBelow:a.ttBelow}),this.isHidden=!1);I(c,"tooltipRefresh",{text:i,x:f+c.plotLeft,y:g+c.plotTop,borderColor:k})},updatePosition:function(a){var b=this.chart, c=this.label,c=(this.options.positioner||this.getPosition).call(this,c.width,c.height,a);this.move(v(c.x),v(c.y),a.plotX+b.plotLeft,a.plotY+b.plotTop)},tooltipHeaderFormatter:function(a){var b=a.series,c=b.tooltipOptions,d=c.dateTimeLabelFormats,e=c.xDateFormat,f=b.xAxis,g=f&&f.options.type==="datetime"&&ja(a.key),c=c.headerFormat,f=f&&f.closestPointRange,h;if(g&&!e){if(f)for(h in A){if(A[h]>=f||A[h]<=A.day&&a.key%A[h]>0){e=d[h];break}}else e=d.day;e=e||d.year}g&&e&&(c=c.replace("{point.key}","{point.key:"+ e+"}"));return Ja(c,{point:a,series:b})}};var pa;$a=x.documentElement.ontouchstart!==u;var Wa=K.Pointer=function(a,b){this.init(a,b)};Wa.prototype={init:function(a,b){var c=b.chart,d=c.events,e=ga?"":c.zoomType,c=a.inverted,f;this.options=b;this.chart=a;this.zoomX=f=/x/.test(e);this.zoomY=e=/y/.test(e);this.zoomHor=f&&!c||e&&c;this.zoomVert=e&&!c||f&&c;this.hasZoom=f||e;this.runChartClick=d&&!!d.click;this.pinchDown=[];this.lastValidTouch={};if(K.Tooltip&&b.tooltip.enabled)a.tooltip=new Nb(a,b.tooltip), this.followTouchMove=b.tooltip.followTouchMove;this.setDOMEvents()},normalize:function(a,b){var c,d,a=a||window.event,a=Tb(a);if(!a.target)a.target=a.srcElement;d=a.touches?a.touches.length?a.touches.item(0):a.changedTouches[0]:a;if(!b)this.chartPosition=b=Sb(this.chart.container);d.pageX===u?(c=t(a.x,a.clientX-b.left),d=a.y):(c=d.pageX-b.left,d=d.pageY-b.top);return r(a,{chartX:v(c),chartY:v(d)})},getCoordinates:function(a){var b={xAxis:[],yAxis:[]};q(this.chart.axes,function(c){b[c.isXAxis?"xAxis": "yAxis"].push({axis:c,value:c.toValue(a[c.horiz?"chartX":"chartY"])})});return b},getIndex:function(a){var b=this.chart;return b.inverted?b.plotHeight+b.plotTop-a.chartY:a.chartX-b.plotLeft},runPointActions:function(a){var b=this.chart,c=b.series,d=b.tooltip,e,f,g=b.hoverPoint,h=b.hoverSeries,i,j,k=b.chartWidth,l=this.getIndex(a);if(d&&this.options.tooltip.shared&&(!h||!h.noSharedTooltip)){f=[];i=c.length;for(j=0;j<i;j++)if(c[j].visible&&c[j].options.enableMouseTracking!==!1&&!c[j].noSharedTooltip&& c[j].singularTooltips!==!0&&c[j].tooltipPoints.length&&(e=c[j].tooltipPoints[l])&&e.series)e._dist=Q(l-e.clientX),k=L(k,e._dist),f.push(e);for(i=f.length;i--;)f[i]._dist>k&&f.splice(i,1);if(f.length&&f[0].clientX!==this.hoverX)d.refresh(f,a),this.hoverX=f[0].clientX}c=h&&h.tooltipOptions.followPointer;if(h&&h.tracker&&!c){if((e=h.tooltipPoints[l])&&e!==g)e.onMouseOver(a)}else d&&c&&!d.isHidden&&(h=d.getAnchor([{}],a),d.updatePosition({plotX:h[0],plotY:h[1]}));if(d&&!this._onDocumentMouseMove)this._onDocumentMouseMove= function(a){if(W[pa])W[pa].pointer.onDocumentMouseMove(a)},N(x,"mousemove",this._onDocumentMouseMove);q(b.axes,function(b){b.drawCrosshair(a,p(e,g))})},reset:function(a,b){var c=this.chart,d=c.hoverSeries,e=c.hoverPoint,f=c.tooltip,g=f&&f.shared?c.hoverPoints:e;(a=a&&f&&g)&&ra(g)[0].plotX===u&&(a=!1);if(a)f.refresh(g),e&&e.setState(e.state,!0);else{if(e)e.onMouseOut();if(d)d.onMouseOut();f&&f.hide(b);if(this._onDocumentMouseMove)X(x,"mousemove",this._onDocumentMouseMove),this._onDocumentMouseMove= null;q(c.axes,function(a){a.hideCrosshair()});this.hoverX=null}},scaleGroups:function(a,b){var c=this.chart,d;q(c.series,function(e){d=a||e.getPlotBox();e.xAxis&&e.xAxis.zoomEnabled&&(e.group.attr(d),e.markerGroup&&(e.markerGroup.attr(d),e.markerGroup.clip(b?c.clipRect:null)),e.dataLabelsGroup&&e.dataLabelsGroup.attr(d))});c.clipRect.attr(b||c.clipBox)},dragStart:function(a){var b=this.chart;b.mouseIsDown=a.type;b.cancelClick=!1;b.mouseDownX=this.mouseDownX=a.chartX;b.mouseDownY=this.mouseDownY=a.chartY}, drag:function(a){var b=this.chart,c=b.options.chart,d=a.chartX,e=a.chartY,f=this.zoomHor,g=this.zoomVert,h=b.plotLeft,i=b.plotTop,j=b.plotWidth,k=b.plotHeight,l,n=this.mouseDownX,m=this.mouseDownY,o=c.panKey&&a[c.panKey+"Key"];d<h?d=h:d>h+j&&(d=h+j);e<i?e=i:e>i+k&&(e=i+k);this.hasDragged=Math.sqrt(Math.pow(n-d,2)+Math.pow(m-e,2));if(this.hasDragged>10){l=b.isInsidePlot(n-h,m-i);if(b.hasCartesianSeries&&(this.zoomX||this.zoomY)&&l&&!o&&!this.selectionMarker)this.selectionMarker=b.renderer.rect(h,i, f?1:j,g?1:k,0).attr({fill:c.selectionMarkerFill||"rgba(69,114,167,0.25)",zIndex:7}).add();this.selectionMarker&&f&&(d-=n,this.selectionMarker.attr({width:Q(d),x:(d>0?0:d)+n}));this.selectionMarker&&g&&(d=e-m,this.selectionMarker.attr({height:Q(d),y:(d>0?0:d)+m}));l&&!this.selectionMarker&&c.panning&&b.pan(a,c.panning)}},drop:function(a){var b=this.chart,c=this.hasPinched;if(this.selectionMarker){var d={xAxis:[],yAxis:[],originalEvent:a.originalEvent||a},e=this.selectionMarker,f=e.attr?e.attr("x"): e.x,g=e.attr?e.attr("y"):e.y,h=e.attr?e.attr("width"):e.width,i=e.attr?e.attr("height"):e.height,j;if(this.hasDragged||c)q(b.axes,function(b){if(b.zoomEnabled){var c=b.horiz,e=a.type==="touchend"?b.minPixelPadding:0,m=b.toValue((c?f:g)+e),c=b.toValue((c?f+h:g+i)-e);!isNaN(m)&&!isNaN(c)&&(d[b.coll].push({axis:b,min:L(m,c),max:t(m,c)}),j=!0)}}),j&&I(b,"selection",d,function(a){b.zoom(r(a,c?{animation:!1}:null))});this.selectionMarker=this.selectionMarker.destroy();c&&this.scaleGroups()}if(b)B(b.container, {cursor:b._cursor}),b.cancelClick=this.hasDragged>10,b.mouseIsDown=this.hasDragged=this.hasPinched=!1,this.pinchDown=[]},onContainerMouseDown:function(a){a=this.normalize(a);a.preventDefault&&a.preventDefault();this.dragStart(a)},onDocumentMouseUp:function(a){W[pa]&&W[pa].pointer.drop(a)},onDocumentMouseMove:function(a){var b=this.chart,c=this.chartPosition,d=b.hoverSeries,a=this.normalize(a,c);c&&d&&!this.inClass(a.target,"highcharts-tracker")&&!b.isInsidePlot(a.chartX-b.plotLeft,a.chartY-b.plotTop)&& this.reset()},onContainerMouseLeave:function(){var a=W[pa];if(a)a.pointer.reset(),a.pointer.chartPosition=null},onContainerMouseMove:function(a){var b=this.chart;pa=b.index;a=this.normalize(a);a.returnValue=!1;b.mouseIsDown==="mousedown"&&this.drag(a);(this.inClass(a.target,"highcharts-tracker")||b.isInsidePlot(a.chartX-b.plotLeft,a.chartY-b.plotTop))&&!b.openMenu&&this.runPointActions(a)},inClass:function(a,b){for(var c;a;){if(c=F(a,"class"))if(c.indexOf(b)!==-1)return!0;else if(c.indexOf("highcharts-container")!== -1)return!1;a=a.parentNode}},onTrackerMouseOut:function(a){var b=this.chart.hoverSeries,c=(a=a.relatedTarget||a.toElement)&&a.point&&a.point.series;if(b&&!b.options.stickyTracking&&!this.inClass(a,"highcharts-tooltip")&&c!==b)b.onMouseOut()},onContainerClick:function(a){var b=this.chart,c=b.hoverPoint,d=b.plotLeft,e=b.plotTop,a=this.normalize(a);a.cancelBubble=!0;b.cancelClick||(c&&this.inClass(a.target,"highcharts-tracker")?(I(c.series,"click",r(a,{point:c})),b.hoverPoint&&c.firePointEvent("click", a)):(r(a,this.getCoordinates(a)),b.isInsidePlot(a.chartX-d,a.chartY-e)&&I(b,"click",a)))},setDOMEvents:function(){var a=this,b=a.chart.container;b.onmousedown=function(b){a.onContainerMouseDown(b)};b.onmousemove=function(b){a.onContainerMouseMove(b)};b.onclick=function(b){a.onContainerClick(b)};N(b,"mouseleave",a.onContainerMouseLeave);ab===1&&N(x,"mouseup",a.onDocumentMouseUp);if($a)b.ontouchstart=function(b){a.onContainerTouchStart(b)},b.ontouchmove=function(b){a.onContainerTouchMove(b)},ab===1&& N(x,"touchend",a.onDocumentTouchEnd)},destroy:function(){var a;X(this.chart.container,"mouseleave",this.onContainerMouseLeave);ab||(X(x,"mouseup",this.onDocumentMouseUp),X(x,"touchend",this.onDocumentTouchEnd));clearInterval(this.tooltipTimeout);for(a in this)this[a]=null}};r(K.Pointer.prototype,{pinchTranslate:function(a,b,c,d,e,f){(this.zoomHor||this.pinchHor)&&this.pinchTranslateDirection(!0,a,b,c,d,e,f);(this.zoomVert||this.pinchVert)&&this.pinchTranslateDirection(!1,a,b,c,d,e,f)},pinchTranslateDirection:function(a, b,c,d,e,f,g,h){var i=this.chart,j=a?"x":"y",k=a?"X":"Y",l="chart"+k,n=a?"width":"height",m=i["plot"+(a?"Left":"Top")],o,p,q=h||1,r=i.inverted,C=i.bounds[a?"h":"v"],t=b.length===1,s=b[0][l],v=c[0][l],u=!t&&b[1][l],w=!t&&c[1][l],x,c=function(){!t&&Q(s-u)>20&&(q=h||Q(v-w)/Q(s-u));p=(m-v)/q+s;o=i["plot"+(a?"Width":"Height")]/q};c();b=p;b<C.min?(b=C.min,x=!0):b+o>C.max&&(b=C.max-o,x=!0);x?(v-=0.8*(v-g[j][0]),t||(w-=0.8*(w-g[j][1])),c()):g[j]=[v,w];r||(f[j]=p-m,f[n]=o);f=r?1/q:q;e[n]=o;e[j]=b;d[r?a?"scaleY": "scaleX":"scale"+k]=q;d["translate"+k]=f*m+(v-f*s)},pinch:function(a){var b=this,c=b.chart,d=b.pinchDown,e=b.followTouchMove,f=a.touches,g=f.length,h=b.lastValidTouch,i=b.hasZoom,j=b.selectionMarker,k={},l=g===1&&(b.inClass(a.target,"highcharts-tracker")&&c.runTrackerClick||b.runChartClick),n={};(i||e)&&!l&&a.preventDefault();Va(f,function(a){return b.normalize(a)});if(a.type==="touchstart")q(f,function(a,b){d[b]={chartX:a.chartX,chartY:a.chartY}}),h.x=[d[0].chartX,d[1]&&d[1].chartX],h.y=[d[0].chartY, d[1]&&d[1].chartY],q(c.axes,function(a){if(a.zoomEnabled){var b=c.bounds[a.horiz?"h":"v"],d=a.minPixelPadding,e=a.toPixels(p(a.options.min,a.dataMin)),f=a.toPixels(p(a.options.max,a.dataMax)),g=L(e,f),e=t(e,f);b.min=L(a.pos,g-d);b.max=t(a.pos+a.len,e+d)}}),b.res=!0;else if(d.length){if(!j)b.selectionMarker=j=r({destroy:sa},c.plotBox);b.pinchTranslate(d,f,k,j,n,h);b.hasPinched=i;b.scaleGroups(k,n);if(!i&&e&&g===1)this.runPointActions(b.normalize(a));else if(b.res)b.res=!1,this.reset(!1,0)}},onContainerTouchStart:function(a){var b= this.chart;pa=b.index;a.touches.length===1?(a=this.normalize(a),b.isInsidePlot(a.chartX-b.plotLeft,a.chartY-b.plotTop)?(this.runPointActions(a),this.pinch(a)):this.reset()):a.touches.length===2&&this.pinch(a)},onContainerTouchMove:function(a){(a.touches.length===1||a.touches.length===2)&&this.pinch(a)},onDocumentTouchEnd:function(a){W[pa]&&W[pa].pointer.drop(a)}});if(G.PointerEvent||G.MSPointerEvent){var ua={},zb=!!G.PointerEvent,Xb=function(){var a,b=[];b.item=function(a){return this[a]};for(a in ua)ua.hasOwnProperty(a)&& b.push({pageX:ua[a].pageX,pageY:ua[a].pageY,target:ua[a].target});return b},Ab=function(a,b,c,d){a=a.originalEvent||a;if((a.pointerType==="touch"||a.pointerType===a.MSPOINTER_TYPE_TOUCH)&&W[pa])d(a),d=W[pa].pointer,d[b]({type:c,target:a.currentTarget,preventDefault:sa,touches:Xb()})};r(Wa.prototype,{onContainerPointerDown:function(a){Ab(a,"onContainerTouchStart","touchstart",function(a){ua[a.pointerId]={pageX:a.pageX,pageY:a.pageY,target:a.currentTarget}})},onContainerPointerMove:function(a){Ab(a, "onContainerTouchMove","touchmove",function(a){ua[a.pointerId]={pageX:a.pageX,pageY:a.pageY};if(!ua[a.pointerId].target)ua[a.pointerId].target=a.currentTarget})},onDocumentPointerUp:function(a){Ab(a,"onContainerTouchEnd","touchend",function(a){delete ua[a.pointerId]})},batchMSEvents:function(a){a(this.chart.container,zb?"pointerdown":"MSPointerDown",this.onContainerPointerDown);a(this.chart.container,zb?"pointermove":"MSPointerMove",this.onContainerPointerMove);a(x,zb?"pointerup":"MSPointerUp",this.onDocumentPointerUp)}}); Na(Wa.prototype,"init",function(a,b,c){a.call(this,b,c);(this.hasZoom||this.followTouchMove)&&B(b.container,{"-ms-touch-action":P,"touch-action":P})});Na(Wa.prototype,"setDOMEvents",function(a){a.apply(this);(this.hasZoom||this.followTouchMove)&&this.batchMSEvents(N)});Na(Wa.prototype,"destroy",function(a){this.batchMSEvents(X);a.call(this)})}var lb=K.Legend=function(a,b){this.init(a,b)};lb.prototype={init:function(a,b){var c=this,d=b.itemStyle,e=p(b.padding,8),f=b.itemMarginTop||0;this.options=b; if(b.enabled)c.itemStyle=d,c.itemHiddenStyle=w(d,b.itemHiddenStyle),c.itemMarginTop=f,c.padding=e,c.initialItemX=e,c.initialItemY=e-5,c.maxItemWidth=0,c.chart=a,c.itemHeight=0,c.lastLineHeight=0,c.symbolWidth=p(b.symbolWidth,16),c.pages=[],c.render(),N(c.chart,"endResize",function(){c.positionCheckboxes()})},colorizeItem:function(a,b){var c=this.options,d=a.legendItem,e=a.legendLine,f=a.legendSymbol,g=this.itemHiddenStyle.color,c=b?c.itemStyle.color:g,h=b?a.legendColor||a.color||"#CCC":g,g=a.options&& a.options.marker,i={fill:h},j;d&&d.css({fill:c,color:c});e&&e.attr({stroke:h});if(f){if(g&&f.isMarker)for(j in i.stroke=h,g=a.convertAttribs(g),g)d=g[j],d!==u&&(i[j]=d);f.attr(i)}},positionItem:function(a){var b=this.options,c=b.symbolPadding,b=!b.rtl,d=a._legendItemPos,e=d[0],d=d[1],f=a.checkbox;a.legendGroup&&a.legendGroup.translate(b?e:this.legendWidth-e-2*c-4,d);if(f)f.x=e,f.y=d},destroyItem:function(a){var b=a.checkbox;q(["legendItem","legendLine","legendSymbol","legendGroup"],function(b){a[b]&& (a[b]=a[b].destroy())});b&&Qa(a.checkbox)},destroy:function(){var a=this.group,b=this.box;if(b)this.box=b.destroy();if(a)this.group=a.destroy()},positionCheckboxes:function(a){var b=this.group.alignAttr,c,d=this.clipHeight||this.legendHeight;if(b)c=b.translateY,q(this.allItems,function(e){var f=e.checkbox,g;f&&(g=c+f.y+(a||0)+3,B(f,{left:b.translateX+e.checkboxOffset+f.x-20+"px",top:g+"px",display:g>c-6&&g<c+d-6?"":P}))})},renderTitle:function(){var a=this.padding,b=this.options.title,c=0;if(b.text){if(!this.title)this.title= this.chart.renderer.label(b.text,a-3,a-4,null,null,null,null,null,"legend-title").attr({zIndex:1}).css(b.style).add(this.group);a=this.title.getBBox();c=a.height;this.offsetWidth=a.width;this.contentGroup.attr({translateY:c})}this.titleHeight=c},renderItem:function(a){var b=this.chart,c=b.renderer,d=this.options,e=d.layout==="horizontal",f=this.symbolWidth,g=d.symbolPadding,h=this.itemStyle,i=this.itemHiddenStyle,j=this.padding,k=e?p(d.itemDistance,20):0,l=!d.rtl,n=d.width,m=d.itemMarginBottom||0, o=this.itemMarginTop,q=this.initialItemX,r=a.legendItem,s=a.series&&a.series.drawLegendSymbol?a.series:a,C=s.options,C=this.createCheckboxForItem&&C&&C.showCheckbox,u=d.useHTML;if(!r){a.legendGroup=c.g("legend-item").attr({zIndex:1}).add(this.scrollGroup);a.legendItem=r=c.text(d.labelFormat?Ja(d.labelFormat,a):d.labelFormatter.call(a),l?f+g:-g,this.baseline||0,u).css(w(a.visible?h:i)).attr({align:l?"left":"right",zIndex:2}).add(a.legendGroup);if(!this.baseline)this.baseline=c.fontMetrics(h.fontSize, r).f+3+o,r.attr("y",this.baseline);s.drawLegendSymbol(this,a);this.setItemEvents&&this.setItemEvents(a,r,u,h,i);this.colorizeItem(a,a.visible);C&&this.createCheckboxForItem(a)}c=r.getBBox();f=a.checkboxOffset=d.itemWidth||a.legendItemWidth||f+g+c.width+k+(C?20:0);this.itemHeight=g=v(a.legendItemHeight||c.height);if(e&&this.itemX-q+f>(n||b.chartWidth-2*j-q-d.x))this.itemX=q,this.itemY+=o+this.lastLineHeight+m,this.lastLineHeight=0;this.maxItemWidth=t(this.maxItemWidth,f);this.lastItemY=o+this.itemY+ m;this.lastLineHeight=t(g,this.lastLineHeight);a._legendItemPos=[this.itemX,this.itemY];e?this.itemX+=f:(this.itemY+=o+g+m,this.lastLineHeight=g);this.offsetWidth=n||t((e?this.itemX-q-k:f)+j,this.offsetWidth)},getAllItems:function(){var a=[];q(this.chart.series,function(b){var c=b.options;if(p(c.showInLegend,!s(c.linkedTo)?u:!1,!0))a=a.concat(b.legendItems||(c.legendType==="point"?b.data:b))});return a},render:function(){var a=this,b=a.chart,c=b.renderer,d=a.group,e,f,g,h,i=a.box,j=a.options,k=a.padding, l=j.borderWidth,n=j.backgroundColor;a.itemX=a.initialItemX;a.itemY=a.initialItemY;a.offsetWidth=0;a.lastItemY=0;if(!d)a.group=d=c.g("legend").attr({zIndex:7}).add(),a.contentGroup=c.g().attr({zIndex:1}).add(d),a.scrollGroup=c.g().add(a.contentGroup);a.renderTitle();e=a.getAllItems();ob(e,function(a,b){return(a.options&&a.options.legendIndex||0)-(b.options&&b.options.legendIndex||0)});j.reversed&&e.reverse();a.allItems=e;a.display=f=!!e.length;q(e,function(b){a.renderItem(b)});g=j.width||a.offsetWidth; h=a.lastItemY+a.lastLineHeight+a.titleHeight;h=a.handleOverflow(h);if(l||n){g+=k;h+=k;if(i){if(g>0&&h>0)i[i.isNew?"attr":"animate"](i.crisp({width:g,height:h})),i.isNew=!1}else a.box=i=c.rect(0,0,g,h,j.borderRadius,l||0).attr({stroke:j.borderColor,"stroke-width":l||0,fill:n||P}).add(d).shadow(j.shadow),i.isNew=!0;i[f?"show":"hide"]()}a.legendWidth=g;a.legendHeight=h;q(e,function(b){a.positionItem(b)});f&&d.align(r({width:g,height:h},j),!0,"spacingBox");b.isResizing||this.positionCheckboxes()},handleOverflow:function(a){var b= this,c=this.chart,d=c.renderer,e=this.options,f=e.y,f=c.spacingBox.height+(e.verticalAlign==="top"?-f:f)-this.padding,g=e.maxHeight,h,i=this.clipRect,j=e.navigation,k=p(j.animation,!0),l=j.arrowSize||12,n=this.nav,m=this.pages,o,r=this.allItems;e.layout==="horizontal"&&(f/=2);g&&(f=L(f,g));m.length=0;if(a>f&&!e.useHTML){this.clipHeight=h=t(f-20-this.titleHeight-this.padding,0);this.currentPage=p(this.currentPage,1);this.fullHeight=a;q(r,function(a,b){var c=a._legendItemPos[1],d=v(a.legendItem.getBBox().height), e=m.length;if(!e||c-m[e-1]>h&&(o||c)!==m[e-1])m.push(o||c),e++;b===r.length-1&&c+d-m[e-1]>h&&m.push(c);c!==o&&(o=c)});if(!i)i=b.clipRect=d.clipRect(0,this.padding,9999,0),b.contentGroup.clip(i);i.attr({height:h});if(!n)this.nav=n=d.g().attr({zIndex:1}).add(this.group),this.up=d.symbol("triangle",0,0,l,l).on("click",function(){b.scroll(-1,k)}).add(n),this.pager=d.text("",15,10).css(j.style).add(n),this.down=d.symbol("triangle-down",0,0,l,l).on("click",function(){b.scroll(1,k)}).add(n);b.scroll(0); a=f}else if(n)i.attr({height:c.chartHeight}),n.hide(),this.scrollGroup.attr({translateY:1}),this.clipHeight=0;return a},scroll:function(a,b){var c=this.pages,d=c.length,e=this.currentPage+a,f=this.clipHeight,g=this.options.navigation,h=g.activeColor,g=g.inactiveColor,i=this.pager,j=this.padding;e>d&&(e=d);if(e>0)b!==u&&Ra(b,this.chart),this.nav.attr({translateX:j,translateY:f+this.padding+7+this.titleHeight,visibility:"visible"}),this.up.attr({fill:e===1?g:h}).css({cursor:e===1?"default":"pointer"}), i.attr({text:e+"/"+d}),this.down.attr({x:18+this.pager.getBBox().width,fill:e===d?g:h}).css({cursor:e===d?"default":"pointer"}),c=-c[e-1]+this.initialItemY,this.scrollGroup.animate({translateY:c}),this.currentPage=e,this.positionCheckboxes(c)}};M=K.LegendSymbolMixin={drawRectangle:function(a,b){var c=a.options.symbolHeight||12;b.legendSymbol=this.chart.renderer.rect(0,a.baseline-5-c/2,a.symbolWidth,c,a.options.symbolRadius||0).attr({zIndex:3}).add(b.legendGroup)},drawLineMarker:function(a){var b= this.options,c=b.marker,d;d=a.symbolWidth;var e=this.chart.renderer,f=this.legendGroup,a=a.baseline-v(e.fontMetrics(a.options.itemStyle.fontSize,this.legendItem).b*0.3),g;if(b.lineWidth){g={"stroke-width":b.lineWidth};if(b.dashStyle)g.dashstyle=b.dashStyle;this.legendLine=e.path(["M",0,a,"L",d,a]).attr(g).add(f)}if(c&&c.enabled!==!1)b=c.radius,this.legendSymbol=d=e.symbol(this.symbol,d/2-b,a-b,2*b,2*b).add(f),d.isMarker=!0}};(/Trident\/7\.0/.test(wa)||Ua)&&Na(lb.prototype,"positionItem",function(a, b){var c=this,d=function(){b._legendItemPos&&a.call(c,b)};d();setTimeout(d)});Ya.prototype={init:function(a,b){var c,d=a.series;a.series=null;c=w(E,a);c.series=a.series=d;this.userOptions=a;d=c.chart;this.margin=this.splashArray("margin",d);this.spacing=this.splashArray("spacing",d);var e=d.events;this.bounds={h:{},v:{}};this.callback=b;this.isResizing=0;this.options=c;this.axes=[];this.series=[];this.hasCartesianSeries=d.showAxes;var f=this,g;f.index=W.length;W.push(f);ab++;d.reflow!==!1&&N(f,"load", function(){f.initReflow()});if(e)for(g in e)N(f,g,e[g]);f.xAxis=[];f.yAxis=[];f.animation=ga?!1:p(d.animation,!0);f.pointCount=f.colorCounter=f.symbolCounter=0;f.firstRender()},initSeries:function(a){var b=this.options.chart;(b=H[a.type||b.type||b.defaultSeriesType])||ha(17,!0);b=new b;b.init(this,a);return b},isInsidePlot:function(a,b,c){var d=c?b:a,a=c?a:b;return d>=0&&d<=this.plotWidth&&a>=0&&a<=this.plotHeight},adjustTickAmounts:function(){this.options.chart.alignTicks!==!1&&q(this.axes,function(a){a.adjustTickAmount()}); this.maxTicks=null},redraw:function(a){var b=this.axes,c=this.series,d=this.pointer,e=this.legend,f=this.isDirtyLegend,g,h,i=this.hasCartesianSeries,j=this.isDirtyBox,k=c.length,l=k,n=this.renderer,m=n.isHidden(),o=[];Ra(a,this);m&&this.cloneRenderTo();for(this.layOutTitles();l--;)if(a=c[l],a.options.stacking&&(g=!0,a.isDirty)){h=!0;break}if(h)for(l=k;l--;)if(a=c[l],a.options.stacking)a.isDirty=!0;q(c,function(a){a.isDirty&&a.options.legendType==="point"&&(f=!0)});if(f&&e.options.enabled)e.render(), this.isDirtyLegend=!1;g&&this.getStacks();if(i){if(!this.isResizing)this.maxTicks=null,q(b,function(a){a.setScale()});this.adjustTickAmounts()}this.getMargins();i&&(q(b,function(a){a.isDirty&&(j=!0)}),q(b,function(a){if(a.isDirtyExtremes)a.isDirtyExtremes=!1,o.push(function(){I(a,"afterSetExtremes",r(a.eventArgs,a.getExtremes()));delete a.eventArgs});(j||g)&&a.redraw()}));j&&this.drawChartBox();q(c,function(a){a.isDirty&&a.visible&&(!a.isCartesian||a.xAxis)&&a.redraw()});d&&d.reset(!0);n.draw();I(this, "redraw");m&&this.cloneRenderTo(!0);q(o,function(a){a.call()})},get:function(a){var b=this.axes,c=this.series,d,e;for(d=0;d<b.length;d++)if(b[d].options.id===a)return b[d];for(d=0;d<c.length;d++)if(c[d].options.id===a)return c[d];for(d=0;d<c.length;d++){e=c[d].points||[];for(b=0;b<e.length;b++)if(e[b].id===a)return e[b]}return null},getAxes:function(){var a=this,b=this.options,c=b.xAxis=ra(b.xAxis||{}),b=b.yAxis=ra(b.yAxis||{});q(c,function(a,b){a.index=b;a.isX=!0});q(b,function(a,b){a.index=b}); c=c.concat(b);q(c,function(b){new na(a,b)});a.adjustTickAmounts()},getSelectedPoints:function(){var a=[];q(this.series,function(b){a=a.concat(wb(b.points||[],function(a){return a.selected}))});return a},getSelectedSeries:function(){return wb(this.series,function(a){return a.selected})},getStacks:function(){var a=this;q(a.yAxis,function(a){if(a.stacks&&a.hasVisibleSeries)a.oldStacks=a.stacks});q(a.series,function(b){if(b.options.stacking&&(b.visible===!0||a.options.chart.ignoreHiddenSeries===!1))b.stackKey= b.type+p(b.options.stack,"")})},setTitle:function(a,b,c){var g;var d=this,e=d.options,f;f=e.title=w(e.title,a);g=e.subtitle=w(e.subtitle,b),e=g;q([["title",a,f],["subtitle",b,e]],function(a){var b=a[0],c=d[b],e=a[1],a=a[2];c&&e&&(d[b]=c=c.destroy());a&&a.text&&!c&&(d[b]=d.renderer.text(a.text,0,0,a.useHTML).attr({align:a.align,"class":"highcharts-"+b,zIndex:a.zIndex||4}).css(a.style).add())});d.layOutTitles(c)},layOutTitles:function(a){var b=0,c=this.title,d=this.subtitle,e=this.options,f=e.title, e=e.subtitle,g=this.renderer,h=this.spacingBox.width-44;if(c&&(c.css({width:(f.width||h)+"px"}).align(r({y:g.fontMetrics(f.style.fontSize,c).b-3},f),!1,"spacingBox"),!f.floating&&!f.verticalAlign))b=c.getBBox().height;d&&(d.css({width:(e.width||h)+"px"}).align(r({y:b+(f.margin-13)+g.fontMetrics(f.style.fontSize,d).b},e),!1,"spacingBox"),!e.floating&&!e.verticalAlign&&(b=La(b+d.getBBox().height)));c=this.titleOffset!==b;this.titleOffset=b;if(!this.isDirtyBox&&c)this.isDirtyBox=c,this.hasRendered&& p(a,!0)&&this.isDirtyBox&&this.redraw()},getChartSize:function(){var a=this.options.chart,b=a.width,a=a.height,c=this.renderToClone||this.renderTo;if(!s(b))this.containerWidth=ib(c,"width");if(!s(a))this.containerHeight=ib(c,"height");this.chartWidth=t(0,b||this.containerWidth||600);this.chartHeight=t(0,p(a,this.containerHeight>19?this.containerHeight:400))},cloneRenderTo:function(a){var b=this.renderToClone,c=this.container;a?b&&(this.renderTo.appendChild(c),Qa(b),delete this.renderToClone):(c&& c.parentNode===this.renderTo&&this.renderTo.removeChild(c),this.renderToClone=b=this.renderTo.cloneNode(0),B(b,{position:"absolute",top:"-9999px",display:"block"}),b.style.setProperty&&b.style.setProperty("display","block","important"),x.body.appendChild(b),c&&b.appendChild(c))},getContainer:function(){var a,b=this.options.chart,c,d,e;this.renderTo=a=b.renderTo;e="highcharts-"+ub++;if(Ga(a))this.renderTo=a=x.getElementById(a);a||ha(13,!0);c=y(F(a,"data-highcharts-chart"));!isNaN(c)&&W[c]&&W[c].hasRendered&& W[c].destroy();F(a,"data-highcharts-chart",this.index);a.innerHTML="";!b.skipClone&&!a.offsetWidth&&this.cloneRenderTo();this.getChartSize();c=this.chartWidth;d=this.chartHeight;this.container=a=$(Ka,{className:"highcharts-container"+(b.className?" "+b.className:""),id:e},r({position:"relative",overflow:"hidden",width:c+"px",height:d+"px",textAlign:"left",lineHeight:"normal",zIndex:0,"-webkit-tap-highlight-color":"rgba(0,0,0,0)"},b.style),this.renderToClone||a);this._cursor=a.style.cursor;this.renderer= b.forExport?new ta(a,c,d,b.style,!0):new Za(a,c,d,b.style);ga&&this.renderer.create(this,a,c,d)},getMargins:function(){var a=this.spacing,b,c=this.legend,d=this.margin,e=this.options.legend,f=p(e.margin,20),g=e.x,h=e.y,i=e.align,j=e.verticalAlign,k=this.titleOffset;this.resetMargins();b=this.axisOffset;if(k&&!s(d[0]))this.plotTop=t(this.plotTop,k+this.options.title.margin+a[0]);if(c.display&&!e.floating)if(i==="right"){if(!s(d[1]))this.marginRight=t(this.marginRight,c.legendWidth-g+f+a[1])}else if(i=== "left"){if(!s(d[3]))this.plotLeft=t(this.plotLeft,c.legendWidth+g+f+a[3])}else if(j==="top"){if(!s(d[0]))this.plotTop=t(this.plotTop,c.legendHeight+h+f+a[0])}else if(j==="bottom"&&!s(d[2]))this.marginBottom=t(this.marginBottom,c.legendHeight-h+f+a[2]);this.extraBottomMargin&&(this.marginBottom+=this.extraBottomMargin);this.extraTopMargin&&(this.plotTop+=this.extraTopMargin);this.hasCartesianSeries&&q(this.axes,function(a){a.getOffset()});s(d[3])||(this.plotLeft+=b[3]);s(d[0])||(this.plotTop+=b[0]); s(d[2])||(this.marginBottom+=b[2]);s(d[1])||(this.marginRight+=b[1]);this.setChartSize()},reflow:function(a){var b=this,c=b.options.chart,d=b.renderTo,e=c.width||ib(d,"width"),f=c.height||ib(d,"height"),c=a?a.target:G,d=function(){if(b.container)b.setSize(e,f,!1),b.hasUserSize=null};if(!b.hasUserSize&&e&&f&&(c===G||c===x)){if(e!==b.containerWidth||f!==b.containerHeight)clearTimeout(b.reflowTimeout),a?b.reflowTimeout=setTimeout(d,100):d();b.containerWidth=e;b.containerHeight=f}},initReflow:function(){var a= this,b=function(b){a.reflow(b)};N(G,"resize",b);N(a,"destroy",function(){X(G,"resize",b)})},setSize:function(a,b,c){var d=this,e,f,g;d.isResizing+=1;g=function(){d&&I(d,"endResize",null,function(){d.isResizing-=1})};Ra(c,d);d.oldChartHeight=d.chartHeight;d.oldChartWidth=d.chartWidth;if(s(a))d.chartWidth=e=t(0,v(a)),d.hasUserSize=!!e;if(s(b))d.chartHeight=f=t(0,v(b));(va?jb:B)(d.container,{width:e+"px",height:f+"px"},va);d.setChartSize(!0);d.renderer.setSize(e,f,c);d.maxTicks=null;q(d.axes,function(a){a.isDirty= !0;a.setScale()});q(d.series,function(a){a.isDirty=!0});d.isDirtyLegend=!0;d.isDirtyBox=!0;d.layOutTitles();d.getMargins();d.redraw(c);d.oldChartHeight=null;I(d,"resize");va===!1?g():setTimeout(g,va&&va.duration||500)},setChartSize:function(a){var b=this.inverted,c=this.renderer,d=this.chartWidth,e=this.chartHeight,f=this.options.chart,g=this.spacing,h=this.clipOffset,i,j,k,l;this.plotLeft=i=v(this.plotLeft);this.plotTop=j=v(this.plotTop);this.plotWidth=k=t(0,v(d-i-this.marginRight));this.plotHeight= l=t(0,v(e-j-this.marginBottom));this.plotSizeX=b?l:k;this.plotSizeY=b?k:l;this.plotBorderWidth=f.plotBorderWidth||0;this.spacingBox=c.spacingBox={x:g[3],y:g[0],width:d-g[3]-g[1],height:e-g[0]-g[2]};this.plotBox=c.plotBox={x:i,y:j,width:k,height:l};d=2*U(this.plotBorderWidth/2);b=La(t(d,h[3])/2);c=La(t(d,h[0])/2);this.clipBox={x:b,y:c,width:U(this.plotSizeX-t(d,h[1])/2-b),height:t(0,U(this.plotSizeY-t(d,h[2])/2-c))};a||q(this.axes,function(a){a.setAxisSize();a.setAxisTranslation()})},resetMargins:function(){var a= this.spacing,b=this.margin;this.plotTop=p(b[0],a[0]);this.marginRight=p(b[1],a[1]);this.marginBottom=p(b[2],a[2]);this.plotLeft=p(b[3],a[3]);this.axisOffset=[0,0,0,0];this.clipOffset=[0,0,0,0]},drawChartBox:function(){var a=this.options.chart,b=this.renderer,c=this.chartWidth,d=this.chartHeight,e=this.chartBackground,f=this.plotBackground,g=this.plotBorder,h=this.plotBGImage,i=a.borderWidth||0,j=a.backgroundColor,k=a.plotBackgroundColor,l=a.plotBackgroundImage,n=a.plotBorderWidth||0,m,o=this.plotLeft, p=this.plotTop,q=this.plotWidth,r=this.plotHeight,t=this.plotBox,s=this.clipRect,v=this.clipBox;m=i+(a.shadow?8:0);if(i||j)if(e)e.animate(e.crisp({width:c-m,height:d-m}));else{e={fill:j||P};if(i)e.stroke=a.borderColor,e["stroke-width"]=i;this.chartBackground=b.rect(m/2,m/2,c-m,d-m,a.borderRadius,i).attr(e).addClass("highcharts-background").add().shadow(a.shadow)}if(k)f?f.animate(t):this.plotBackground=b.rect(o,p,q,r,0).attr({fill:k}).add().shadow(a.plotShadow);if(l)h?h.animate(t):this.plotBGImage= b.image(l,o,p,q,r).add();s?s.animate({width:v.width,height:v.height}):this.clipRect=b.clipRect(v);if(n)g?g.animate(g.crisp({x:o,y:p,width:q,height:r,strokeWidth:-n})):this.plotBorder=b.rect(o,p,q,r,0,-n).attr({stroke:a.plotBorderColor,"stroke-width":n,fill:P,zIndex:1}).add();this.isDirtyBox=!1},propFromSeries:function(){var a=this,b=a.options.chart,c,d=a.options.series,e,f;q(["inverted","angular","polar"],function(g){c=H[b.type||b.defaultSeriesType];f=a[g]||b[g]||c&&c.prototype[g];for(e=d&&d.length;!f&& e--;)(c=H[d[e].type])&&c.prototype[g]&&(f=!0);a[g]=f})},linkSeries:function(){var a=this,b=a.series;q(b,function(a){a.linkedSeries.length=0});q(b,function(b){var d=b.options.linkedTo;if(Ga(d)&&(d=d===":previous"?a.series[b.index-1]:a.get(d)))d.linkedSeries.push(b),b.linkedParent=d})},renderSeries:function(){q(this.series,function(a){a.translate();a.setTooltipPoints&&a.setTooltipPoints();a.render()})},renderLabels:function(){var a=this,b=a.options.labels;b.items&&q(b.items,function(c){var d=r(b.style, c.style),e=y(d.left)+a.plotLeft,f=y(d.top)+a.plotTop+12;delete d.left;delete d.top;a.renderer.text(c.html,e,f).attr({zIndex:2}).css(d).add()})},render:function(){var a=this.axes,b=this.renderer,c=this.options;this.setTitle();this.legend=new lb(this,c.legend);this.getStacks();q(a,function(a){a.setScale()});this.getMargins();this.maxTicks=null;q(a,function(a){a.setTickPositions(!0);a.setMaxTicks()});this.adjustTickAmounts();this.getMargins();this.drawChartBox();this.hasCartesianSeries&&q(a,function(a){a.render()}); if(!this.seriesGroup)this.seriesGroup=b.g("series-group").attr({zIndex:3}).add();this.renderSeries();this.renderLabels();this.showCredits(c.credits);this.hasRendered=!0},showCredits:function(a){if(a.enabled&&!this.credits)this.credits=this.renderer.text(a.text,0,0).on("click",function(){if(a.href)location.href=a.href}).attr({align:a.position.align,zIndex:8}).css(a.style).add().align(a.position)},destroy:function(){var a=this,b=a.axes,c=a.series,d=a.container,e,f=d&&d.parentNode;I(a,"destroy");W[a.index]= u;ab--;a.renderTo.removeAttribute("data-highcharts-chart");X(a);for(e=b.length;e--;)b[e]=b[e].destroy();for(e=c.length;e--;)c[e]=c[e].destroy();q("title,subtitle,chartBackground,plotBackground,plotBGImage,plotBorder,seriesGroup,clipRect,credits,pointer,scroller,rangeSelector,legend,resetZoomButton,tooltip,renderer".split(","),function(b){var c=a[b];c&&c.destroy&&(a[b]=c.destroy())});if(d)d.innerHTML="",X(d),f&&Qa(d);for(e in a)delete a[e]},isReadyToRender:function(){var a=this;return!ba&&G==G.top&& x.readyState!=="complete"||ga&&!G.canvg?(ga?Mb.push(function(){a.firstRender()},a.options.global.canvasToolsURL):x.attachEvent("onreadystatechange",function(){x.detachEvent("onreadystatechange",a.firstRender);x.readyState==="complete"&&a.firstRender()}),!1):!0},firstRender:function(){var a=this,b=a.options,c=a.callback;if(a.isReadyToRender()){a.getContainer();I(a,"init");a.resetMargins();a.setChartSize();a.propFromSeries();a.getAxes();q(b.series||[],function(b){a.initSeries(b)});a.linkSeries();I(a, "beforeRender");if(K.Pointer)a.pointer=new Wa(a,b);a.render();a.renderer.draw();c&&c.apply(a,[a]);q(a.callbacks,function(b){b.apply(a,[a])});a.cloneRenderTo(!0);I(a,"load")}},splashArray:function(a,b){var c=b[a],c=da(c)?c:[c,c,c,c];return[p(b[a+"Top"],c[0]),p(b[a+"Right"],c[1]),p(b[a+"Bottom"],c[2]),p(b[a+"Left"],c[3])]}};Ya.prototype.callbacks=[];Z=K.CenteredSeriesMixin={getCenter:function(){var a=this.options,b=this.chart,c=2*(a.slicedOffset||0),d,e=b.plotWidth-2*c,f=b.plotHeight-2*c,b=a.center, a=[p(b[0],"50%"),p(b[1],"50%"),a.size||"100%",a.innerSize||0],g=L(e,f),h;return Va(a,function(a,b){h=/%$/.test(a);d=b<2||b===2&&h;return(h?[e,f,g,g][b]*y(a)/100:a)+(d?c:0)})}};var Fa=function(){};Fa.prototype={init:function(a,b,c){this.series=a;this.applyOptions(b,c);this.pointAttr={};if(a.options.colorByPoint&&(b=a.options.colors||a.chart.options.colors,this.color=this.color||b[a.colorCounter++],a.colorCounter===b.length))a.colorCounter=0;a.chart.pointCount++;return this},applyOptions:function(a, b){var c=this.series,d=c.options.pointValKey||c.pointValKey,a=Fa.prototype.optionsToObject.call(this,a);r(this,a);this.options=this.options?r(this.options,a):a;if(d)this.y=this[d];if(this.x===u&&c)this.x=b===u?c.autoIncrement():b;return this},optionsToObject:function(a){var b={},c=this.series,d=c.pointArrayMap||["y"],e=d.length,f=0,g=0;if(typeof a==="number"||a===null)b[d[0]]=a;else if(Ha(a)){if(a.length>e){c=typeof a[0];if(c==="string")b.name=a[0];else if(c==="number")b.x=a[0];f++}for(;g<e;)b[d[g++]]= a[f++]}else if(typeof a==="object"){b=a;if(a.dataLabels)c._hasPointLabels=!0;if(a.marker)c._hasPointMarkers=!0}return b},destroy:function(){var a=this.series.chart,b=a.hoverPoints,c;a.pointCount--;if(b&&(this.setState(),la(b,this),!b.length))a.hoverPoints=null;if(this===a.hoverPoint)this.onMouseOut();if(this.graphic||this.dataLabel)X(this),this.destroyElements();this.legendItem&&a.legend.destroyItem(this);for(c in this)this[c]=null},destroyElements:function(){for(var a="graphic,dataLabel,dataLabelUpper,group,connector,shadowGroup".split(","), b,c=6;c--;)b=a[c],this[b]&&(this[b]=this[b].destroy())},getLabelConfig:function(){return{x:this.category,y:this.y,key:this.name||this.category,series:this.series,point:this,percentage:this.percentage,total:this.total||this.stackTotal}},tooltipFormatter:function(a){var b=this.series,c=b.tooltipOptions,d=p(c.valueDecimals,""),e=c.valuePrefix||"",f=c.valueSuffix||"";q(b.pointArrayMap||["y"],function(b){b="{point."+b;if(e||f)a=a.replace(b+"}",e+b+"}"+f);a=a.replace(b+"}",b+":,."+d+"f}")});return Ja(a, {point:this,series:this.series})},firePointEvent:function(a,b,c){var d=this,e=this.series.options;(e.point.events[a]||d.options&&d.options.events&&d.options.events[a])&&this.importEvents();a==="click"&&e.allowPointSelect&&(c=function(a){d.select(null,a.ctrlKey||a.metaKey||a.shiftKey)});I(this,a,b,c)}};var O=function(){};O.prototype={isCartesian:!0,type:"line",pointClass:Fa,sorted:!0,requireSorting:!0,pointAttrToOptions:{stroke:"lineColor","stroke-width":"lineWidth",fill:"fillColor",r:"radius"},axisTypes:["xAxis", "yAxis"],colorCounter:0,parallelArrays:["x","y"],init:function(a,b){var c=this,d,e,f=a.series,g=function(a,b){return p(a.options.index,a._i)-p(b.options.index,b._i)};c.chart=a;c.options=b=c.setOptions(b);c.linkedSeries=[];c.bindAxes();r(c,{name:b.name,state:"",pointAttr:{},visible:b.visible!==!1,selected:b.selected===!0});if(ga)b.animation=!1;e=b.events;for(d in e)N(c,d,e[d]);if(e&&e.click||b.point&&b.point.events&&b.point.events.click||b.allowPointSelect)a.runTrackerClick=!0;c.getColor();c.getSymbol(); q(c.parallelArrays,function(a){c[a+"Data"]=[]});c.setData(b.data,!1);if(c.isCartesian)a.hasCartesianSeries=!0;f.push(c);c._i=f.length-1;ob(f,g);this.yAxis&&ob(this.yAxis.series,g);q(f,function(a,b){a.index=b;a.name=a.name||"Series "+(b+1)})},bindAxes:function(){var a=this,b=a.options,c=a.chart,d;q(a.axisTypes||[],function(e){q(c[e],function(c){d=c.options;if(b[e]===d.index||b[e]!==u&&b[e]===d.id||b[e]===u&&d.index===0)c.series.push(a),a[e]=c,c.isDirty=!0});!a[e]&&a.optionalAxis!==e&&ha(18,!0)})}, updateParallelArrays:function(a,b){var c=a.series,d=arguments;q(c.parallelArrays,typeof b==="number"?function(d){var f=d==="y"&&c.toYData?c.toYData(a):a[d];c[d+"Data"][b]=f}:function(a){Array.prototype[b].apply(c[a+"Data"],Array.prototype.slice.call(d,2))})},autoIncrement:function(){var a=this.options,b=this.xIncrement,b=p(b,a.pointStart,0);this.pointInterval=p(this.pointInterval,a.pointInterval,1);this.xIncrement=b+this.pointInterval;return b},getSegments:function(){var a=-1,b=[],c,d=this.points, e=d.length;if(e)if(this.options.connectNulls){for(c=e;c--;)d[c].y===null&&d.splice(c,1);d.length&&(b=[d])}else q(d,function(c,g){c.y===null?(g>a+1&&b.push(d.slice(a+1,g)),a=g):g===e-1&&b.push(d.slice(a+1,g+1))});this.segments=b},setOptions:function(a){var b=this.chart,c=b.options.plotOptions,b=b.userOptions||{},d=b.plotOptions||{},e=c[this.type];this.userOptions=a;c=w(e,c.series,a);this.tooltipOptions=w(E.tooltip,E.plotOptions[this.type].tooltip,b.tooltip,d.series&&d.series.tooltip,d[this.type]&& d[this.type].tooltip,a.tooltip);e.marker===null&&delete c.marker;return c},getCyclic:function(a,b,c){var d=this.userOptions,e="_"+a+"Index",f=a+"Counter";b||(s(d[e])?b=d[e]:(d[e]=b=this.chart[f]%c.length,this.chart[f]+=1),b=c[b]);this[a]=b},getColor:function(){this.options.colorByPoint||this.getCyclic("color",this.options.color||ca[this.type].color,this.chart.options.colors)},getSymbol:function(){var a=this.options.marker;this.getCyclic("symbol",a.symbol,this.chart.options.symbols);if(/^url/.test(this.symbol))a.radius= 0},drawLegendSymbol:M.drawLineMarker,setData:function(a,b,c,d){var e=this,f=e.points,g=f&&f.length||0,h,i=e.options,j=e.chart,k=null,l=e.xAxis,n=l&&!!l.categories,m=e.tooltipPoints,o=i.turboThreshold,r=this.xData,t=this.yData,s=(h=e.pointArrayMap)&&h.length,a=a||[];h=a.length;b=p(b,!0);if(d!==!1&&h&&g===h&&!e.cropped&&!e.hasGroupedData)q(a,function(a,b){f[b].update(a,!1,null,!1)});else{e.xIncrement=null;e.pointRange=n?1:i.pointRange;e.colorCounter=0;q(this.parallelArrays,function(a){e[a+"Data"].length= 0});if(o&&h>o){for(c=0;k===null&&c<h;)k=a[c],c++;if(ja(k)){n=p(i.pointStart,0);i=p(i.pointInterval,1);for(c=0;c<h;c++)r[c]=n,t[c]=a[c],n+=i;e.xIncrement=n}else if(Ha(k))if(s)for(c=0;c<h;c++)i=a[c],r[c]=i[0],t[c]=i.slice(1,s+1);else for(c=0;c<h;c++)i=a[c],r[c]=i[0],t[c]=i[1];else ha(12)}else for(c=0;c<h;c++)if(a[c]!==u&&(i={series:e},e.pointClass.prototype.applyOptions.apply(i,[a[c]]),e.updateParallelArrays(i,c),n&&i.name))l.names[i.x]=i.name;Ga(t[0])&&ha(14,!0);e.data=[];e.options.data=a;for(c=g;c--;)f[c]&& f[c].destroy&&f[c].destroy();if(m)m.length=0;if(l)l.minRange=l.userMinRange;e.isDirty=e.isDirtyData=j.isDirtyBox=!0;c=!1}b&&j.redraw(c)},processData:function(a){var b=this.xData,c=this.yData,d=b.length,e;e=0;var f,g,h=this.xAxis,i,j=this.options;i=j.cropThreshold;var k=0,l=this.isCartesian,n,m;if(l&&!this.isDirty&&!h.isDirty&&!this.yAxis.isDirty&&!a)return!1;if(h)n=h.getExtremes(),m=n.min,n=n.max;if(l&&this.sorted&&(!i||d>i||this.forceCrop))if(b[d-1]<m||b[0]>n)b=[],c=[];else if(b[0]<m||b[d-1]>n)e= this.cropData(this.xData,this.yData,m,n),b=e.xData,c=e.yData,e=e.start,f=!0,k=b.length;for(i=b.length-1;i>=0;i--)d=b[i]-b[i-1],!f&&b[i]>m&&b[i]<n&&k++,d>0&&(g===u||d<g)?g=d:d<0&&this.requireSorting&&ha(15);this.cropped=f;this.cropStart=e;this.processedXData=b;this.processedYData=c;this.activePointCount=k;if(j.pointRange===null)this.pointRange=g||1;this.closestPointRange=g},cropData:function(a,b,c,d){var e=a.length,f=0,g=e,h=p(this.cropShoulder,1),i;for(i=0;i<e;i++)if(a[i]>=c){f=t(0,i-h);break}for(;i< e;i++)if(a[i]>d){g=i+h;break}return{xData:a.slice(f,g),yData:b.slice(f,g),start:f,end:g}},generatePoints:function(){var a=this.options.data,b=this.data,c,d=this.processedXData,e=this.processedYData,f=this.pointClass,g=d.length,h=this.cropStart||0,i,j=this.hasGroupedData,k,l=[],n;if(!b&&!j)b=[],b.length=a.length,b=this.data=b;for(n=0;n<g;n++)i=h+n,j?l[n]=(new f).init(this,[d[n]].concat(ra(e[n]))):(b[i]?k=b[i]:a[i]!==u&&(b[i]=k=(new f).init(this,a[i],d[n])),l[n]=k),l[n].index=i;if(b&&(g!==(c=b.length)|| j))for(n=0;n<c;n++)if(n===h&&!j&&(n+=g),b[n])b[n].destroyElements(),b[n].plotX=u;this.data=b;this.points=l},getExtremes:function(a){var b=this.yAxis,c=this.processedXData,d,e=[],f=0;d=this.xAxis.getExtremes();var g=d.min,h=d.max,i,j,k,l,a=a||this.stackedYData||this.processedYData;d=a.length;for(l=0;l<d;l++)if(j=c[l],k=a[l],i=k!==null&&k!==u&&(!b.isLog||k.length||k>0),j=this.getExtremesFromAll||this.cropped||(c[l+1]||j)>=g&&(c[l-1]||j)<=h,i&&j)if(i=k.length)for(;i--;)k[i]!==null&&(e[f++]=k[i]);else e[f++]= k;this.dataMin=p(void 0,Oa(e));this.dataMax=p(void 0,Ca(e))},translate:function(){this.processedXData||this.processData();this.generatePoints();for(var a=this.options,b=a.stacking,c=this.xAxis,d=c.categories,e=this.yAxis,f=this.points,g=f.length,h=!!this.modifyValue,i=a.pointPlacement,j=i==="between"||ja(i),k=a.threshold,a=0;a<g;a++){var l=f[a],n=l.x,m=l.y,o=l.low,q=b&&e.stacks[(this.negStacks&&m<k?"-":"")+this.stackKey];if(e.isLog&&m<=0)l.y=m=null,ha(10);l.plotX=c.translate(n,0,0,0,1,i,this.type=== "flags");if(b&&this.visible&&q&&q[n])q=q[n],m=q.points[this.index+","+a],o=m[0],m=m[1],o===0&&(o=p(k,e.min)),e.isLog&&o<=0&&(o=null),l.total=l.stackTotal=q.total,l.percentage=q.total&&l.y/q.total*100,l.stackY=m,q.setOffset(this.pointXOffset||0,this.barW||0);l.yBottom=s(o)?e.translate(o,0,1,0,1):null;h&&(m=this.modifyValue(m,l));l.plotY=typeof m==="number"&&m!==Infinity?e.translate(m,0,1,0,1):u;l.clientX=j?c.translate(n,0,0,0,1):l.plotX;l.negative=l.y<(k||0);l.category=d&&d[l.x]!==u?d[l.x]:l.x}this.getSegments()}, animate:function(a){var b=this.chart,c=b.renderer,d;d=this.options.animation;var e=this.clipBox||b.clipBox,f=b.inverted,g;if(d&&!da(d))d=ca[this.type].animation;g=["_sharedClip",d.duration,d.easing,e.height].join(",");a?(a=b[g],d=b[g+"m"],a||(b[g]=a=c.clipRect(r(e,{width:0})),b[g+"m"]=d=c.clipRect(-99,f?-b.plotLeft:-b.plotTop,99,f?b.chartWidth:b.chartHeight)),this.group.clip(a),this.markerGroup.clip(d),this.sharedClipKey=g):((a=b[g])&&a.animate({width:b.plotSizeX},d),b[g+"m"]&&b[g+"m"].animate({width:b.plotSizeX+ 99},d),this.animate=null)},afterAnimate:function(){var a=this.chart,b=this.sharedClipKey,c=this.group,d=this.clipBox;if(c&&this.options.clip!==!1){if(!b||!d)c.clip(d?a.renderer.clipRect(d):a.clipRect);this.markerGroup.clip()}I(this,"afterAnimate");setTimeout(function(){b&&a[b]&&(d||(a[b]=a[b].destroy()),a[b+"m"]&&(a[b+"m"]=a[b+"m"].destroy()))},100)},drawPoints:function(){var a,b=this.points,c=this.chart,d,e,f,g,h,i,j,k,l=this.options.marker,n=this.pointAttr[""],m,o,q,t=this.markerGroup,s=p(l.enabled, !this.requireSorting||this.activePointCount<0.5*this.xAxis.len/l.radius);if(l.enabled!==!1||this._hasPointMarkers)for(f=b.length;f--;)if(g=b[f],d=U(g.plotX),e=g.plotY,k=g.graphic,m=g.marker||{},o=!!g.marker,a=s&&m.enabled===u||m.enabled,q=c.isInsidePlot(v(d),e,c.inverted),a&&e!==u&&!isNaN(e)&&g.y!==null)if(a=g.pointAttr[g.selected?"select":""]||n,h=a.r,i=p(m.symbol,this.symbol),j=i.indexOf("url")===0,k)k[q?"show":"hide"](!0).animate(r({x:d-h,y:e-h},k.symbolName?{width:2*h,height:2*h}:{}));else{if(q&& (h>0||j))g.graphic=c.renderer.symbol(i,d-h,e-h,2*h,2*h,o?m:l).attr(a).add(t)}else if(k)g.graphic=k.destroy()},convertAttribs:function(a,b,c,d){var e=this.pointAttrToOptions,f,g,h={},a=a||{},b=b||{},c=c||{},d=d||{};for(f in e)g=e[f],h[f]=p(a[g],b[f],c[f],d[f]);return h},getAttribs:function(){var a=this,b=a.options,c=ca[a.type].marker?b.marker:b,d=c.states,e=d.hover,f,g=a.color;f={stroke:g,fill:g};var h=a.points||[],i,j=[],k,l=a.pointAttrToOptions;k=a.hasPointSpecificOptions;var n=b.negativeColor,m= c.lineColor,o=c.fillColor;i=b.turboThreshold;var p;b.marker?(e.radius=e.radius||c.radius+e.radiusPlus,e.lineWidth=e.lineWidth||c.lineWidth+e.lineWidthPlus):e.color=e.color||ya(e.color||g).brighten(e.brightness).get();j[""]=a.convertAttribs(c,f);q(["hover","select"],function(b){j[b]=a.convertAttribs(d[b],j[""])});a.pointAttr=j;g=h.length;if(!i||g<i||k)for(;g--;){i=h[g];if((c=i.options&&i.options.marker||i.options)&&c.enabled===!1)c.radius=0;if(i.negative&&n)i.color=i.fillColor=n;k=b.colorByPoint|| i.color;if(i.options)for(p in l)s(c[l[p]])&&(k=!0);if(k){c=c||{};k=[];d=c.states||{};f=d.hover=d.hover||{};if(!b.marker)f.color=f.color||!i.options.color&&e.color||ya(i.color).brighten(f.brightness||e.brightness).get();f={color:i.color};if(!o)f.fillColor=i.color;if(!m)f.lineColor=i.color;k[""]=a.convertAttribs(r(f,c),j[""]);k.hover=a.convertAttribs(d.hover,j.hover,k[""]);k.select=a.convertAttribs(d.select,j.select,k[""])}else k=j;i.pointAttr=k}},destroy:function(){var a=this,b=a.chart,c=/AppleWebKit\/533/.test(wa), d,e,f=a.data||[],g,h,i;I(a,"destroy");X(a);q(a.axisTypes||[],function(b){if(i=a[b])la(i.series,a),i.isDirty=i.forceRedraw=!0});a.legendItem&&a.chart.legend.destroyItem(a);for(e=f.length;e--;)(g=f[e])&&g.destroy&&g.destroy();a.points=null;clearTimeout(a.animationTimeout);q("area,graph,dataLabelsGroup,group,markerGroup,tracker,graphNeg,areaNeg,posClip,negClip".split(","),function(b){a[b]&&(d=c&&b==="group"?"hide":"destroy",a[b][d]())});if(b.hoverSeries===a)b.hoverSeries=null;la(b.series,a);for(h in a)delete a[h]}, getSegmentPath:function(a){var b=this,c=[],d=b.options.step;q(a,function(e,f){var g=e.plotX,h=e.plotY,i;b.getPointSpline?c.push.apply(c,b.getPointSpline(a,e,f)):(c.push(f?"L":"M"),d&&f&&(i=a[f-1],d==="right"?c.push(i.plotX,h):d==="center"?c.push((i.plotX+g)/2,i.plotY,(i.plotX+g)/2,h):c.push(g,i.plotY)),c.push(e.plotX,e.plotY))});return c},getGraphPath:function(){var a=this,b=[],c,d=[];q(a.segments,function(e){c=a.getSegmentPath(e);e.length>1?b=b.concat(c):d.push(e[0])});a.singlePoints=d;return a.graphPath= b},drawGraph:function(){var a=this,b=this.options,c=[["graph",b.lineColor||this.color]],d=b.lineWidth,e=b.dashStyle,f=b.linecap!=="square",g=this.getGraphPath(),h=b.negativeColor;h&&c.push(["graphNeg",h]);q(c,function(c,h){var k=c[0],l=a[k];if(l)bb(l),l.animate({d:g});else if(d&&g.length)l={stroke:c[1],"stroke-width":d,fill:P,zIndex:1},e?l.dashstyle=e:f&&(l["stroke-linecap"]=l["stroke-linejoin"]="round"),a[k]=a.chart.renderer.path(g).attr(l).add(a.group).shadow(!h&&b.shadow)})},clipNeg:function(){var a= this.options,b=this.chart,c=b.renderer,d=a.negativeColor||a.negativeFillColor,e,f=this.graph,g=this.area,h=this.posClip,i=this.negClip;e=b.chartWidth;var j=b.chartHeight,k=t(e,j),l=this.yAxis;if(d&&(f||g)){d=v(l.toPixels(a.threshold||0,!0));d<0&&(k-=d);a={x:0,y:0,width:k,height:d};k={x:0,y:d,width:k,height:k};if(b.inverted)a.height=k.y=b.plotWidth-d,c.isVML&&(a={x:b.plotWidth-d-b.plotLeft,y:0,width:e,height:j},k={x:d+b.plotLeft-e,y:0,width:b.plotLeft+d,height:e});l.reversed?(b=k,e=a):(b=a,e=k);h? (h.animate(b),i.animate(e)):(this.posClip=h=c.clipRect(b),this.negClip=i=c.clipRect(e),f&&this.graphNeg&&(f.clip(h),this.graphNeg.clip(i)),g&&(g.clip(h),this.areaNeg.clip(i)))}},invertGroups:function(){function a(){var a={width:b.yAxis.len,height:b.xAxis.len};q(["group","markerGroup"],function(c){b[c]&&b[c].attr(a).invert()})}var b=this,c=b.chart;if(b.xAxis)N(c,"resize",a),N(b,"destroy",function(){X(c,"resize",a)}),a(),b.invertGroups=a},plotGroup:function(a,b,c,d,e){var f=this[a],g=!f;g&&(this[a]= f=this.chart.renderer.g(b).attr({visibility:c,zIndex:d||0.1}).add(e));f[g?"attr":"animate"](this.getPlotBox());return f},getPlotBox:function(){var a=this.chart,b=this.xAxis,c=this.yAxis;if(a.inverted)b=c,c=this.xAxis;return{translateX:b?b.left:a.plotLeft,translateY:c?c.top:a.plotTop,scaleX:1,scaleY:1}},render:function(){var a=this,b=a.chart,c,d=a.options,e=(c=d.animation)&&!!a.animate&&b.renderer.isSVG&&p(c.duration,500)||0,f=a.visible?"visible":"hidden",g=d.zIndex,h=a.hasRendered,i=b.seriesGroup; c=a.plotGroup("group","series",f,g,i);a.markerGroup=a.plotGroup("markerGroup","markers",f,g,i);e&&a.animate(!0);a.getAttribs();c.inverted=a.isCartesian?b.inverted:!1;a.drawGraph&&(a.drawGraph(),a.clipNeg());q(a.points,function(a){a.redraw&&a.redraw()});a.drawDataLabels&&a.drawDataLabels();a.visible&&a.drawPoints();a.drawTracker&&a.options.enableMouseTracking!==!1&&a.drawTracker();b.inverted&&a.invertGroups();d.clip!==!1&&!a.sharedClipKey&&!h&&c.clip(b.clipRect);e&&a.animate();if(!h)e?a.animationTimeout= setTimeout(function(){a.afterAnimate()},e):a.afterAnimate();a.isDirty=a.isDirtyData=!1;a.hasRendered=!0},redraw:function(){var a=this.chart,b=this.isDirtyData,c=this.group,d=this.xAxis,e=this.yAxis;c&&(a.inverted&&c.attr({width:a.plotWidth,height:a.plotHeight}),c.animate({translateX:p(d&&d.left,a.plotLeft),translateY:p(e&&e.top,a.plotTop)}));this.translate();this.setTooltipPoints&&this.setTooltipPoints(!0);this.render();b&&I(this,"updatedData")}};Gb.prototype={destroy:function(){Pa(this,this.axis)}, render:function(a){var b=this.options,c=b.format,c=c?Ja(c,this):b.formatter.call(this);this.label?this.label.attr({text:c,visibility:"hidden"}):this.label=this.axis.chart.renderer.text(c,null,null,b.useHTML).css(b.style).attr({align:this.textAlign,rotation:b.rotation,visibility:"hidden"}).add(a)},setOffset:function(a,b){var c=this.axis,d=c.chart,e=d.inverted,f=this.isNegative,g=c.translate(c.usePercentage?100:this.total,0,0,0,1),c=c.translate(0),c=Q(g-c),h=d.xAxis[0].translate(this.x)+a,i=d.plotHeight, f={x:e?f?g:g-c:h,y:e?i-h-b:f?i-g-c:i-g,width:e?c:b,height:e?b:c};if(e=this.label)e.align(this.alignOptions,null,f),f=e.alignAttr,e[this.options.crop===!1||d.isInsidePlot(f.x,f.y)?"show":"hide"](!0)}};na.prototype.buildStacks=function(){var a=this.series,b=p(this.options.reversedStacks,!0),c=a.length;if(!this.isXAxis){for(this.usePercentage=!1;c--;)a[b?c:a.length-c-1].setStackedPoints();if(this.usePercentage)for(c=0;c<a.length;c++)a[c].setPercentStacks()}};na.prototype.renderStackTotals=function(){var a= this.chart,b=a.renderer,c=this.stacks,d,e,f=this.stackTotalGroup;if(!f)this.stackTotalGroup=f=b.g("stack-labels").attr({visibility:"visible",zIndex:6}).add();f.translate(a.plotLeft,a.plotTop);for(d in c)for(e in a=c[d],a)a[e].render(f)};O.prototype.setStackedPoints=function(){if(this.options.stacking&&!(this.visible!==!0&&this.chart.options.chart.ignoreHiddenSeries!==!1)){var a=this.processedXData,b=this.processedYData,c=[],d=b.length,e=this.options,f=e.threshold,g=e.stack,e=e.stacking,h=this.stackKey, i="-"+h,j=this.negStacks,k=this.yAxis,l=k.stacks,n=k.oldStacks,m,o,p,q,r,s;for(q=0;q<d;q++){r=a[q];s=b[q];p=this.index+","+q;o=(m=j&&s<f)?i:h;l[o]||(l[o]={});if(!l[o][r])n[o]&&n[o][r]?(l[o][r]=n[o][r],l[o][r].total=null):l[o][r]=new Gb(k,k.options.stackLabels,m,r,g);o=l[o][r];o.points[p]=[o.cum||0];e==="percent"?(m=m?h:i,j&&l[m]&&l[m][r]?(m=l[m][r],o.total=m.total=t(m.total,o.total)+Q(s)||0):o.total=ea(o.total+(Q(s)||0))):o.total=ea(o.total+(s||0));o.cum=(o.cum||0)+(s||0);o.points[p].push(o.cum); c[q]=o.cum}if(e==="percent")k.usePercentage=!0;this.stackedYData=c;k.oldStacks={}}};O.prototype.setPercentStacks=function(){var a=this,b=a.stackKey,c=a.yAxis.stacks,d=a.processedXData;q([b,"-"+b],function(b){var e;for(var f=d.length,g,h;f--;)if(g=d[f],e=(h=c[b]&&c[b][g])&&h.points[a.index+","+f],g=e)h=h.total?100/h.total:0,g[0]=ea(g[0]*h),g[1]=ea(g[1]*h),a.stackedYData[f]=g[1]})};r(Ya.prototype,{addSeries:function(a,b,c){var d,e=this;a&&(b=p(b,!0),I(e,"addSeries",{options:a},function(){d=e.initSeries(a); e.isDirtyLegend=!0;e.linkSeries();b&&e.redraw(c)}));return d},addAxis:function(a,b,c,d){var e=b?"xAxis":"yAxis",f=this.options;new na(this,w(a,{index:this[e].length,isX:b}));f[e]=ra(f[e]||{});f[e].push(a);p(c,!0)&&this.redraw(d)},showLoading:function(a){var b=this,c=b.options,d=b.loadingDiv,e=c.loading,f=function(){d&&B(d,{left:b.plotLeft+"px",top:b.plotTop+"px",width:b.plotWidth+"px",height:b.plotHeight+"px"})};if(!d)b.loadingDiv=d=$(Ka,{className:"highcharts-loading"},r(e.style,{zIndex:10,display:P}), b.container),b.loadingSpan=$("span",null,e.labelStyle,d),N(b,"redraw",f);b.loadingSpan.innerHTML=a||c.lang.loading;if(!b.loadingShown)B(d,{opacity:0,display:""}),jb(d,{opacity:e.style.opacity},{duration:e.showDuration||0}),b.loadingShown=!0;f()},hideLoading:function(){var a=this.options,b=this.loadingDiv;b&&jb(b,{opacity:0},{duration:a.loading.hideDuration||100,complete:function(){B(b,{display:P})}});this.loadingShown=!1}});r(Fa.prototype,{update:function(a,b,c,d){function e(){f.applyOptions(a);if(da(a)&& !Ha(a))f.redraw=function(){if(h)a&&a.marker&&a.marker.symbol?f.graphic=h.destroy():h.attr(f.pointAttr[f.state||""]);if(a&&a.dataLabels&&f.dataLabel)f.dataLabel=f.dataLabel.destroy();f.redraw=null};i=f.index;g.updateParallelArrays(f,i);k.data[i]=f.options;g.isDirty=g.isDirtyData=!0;if(!g.fixedBox&&g.hasCartesianSeries)j.isDirtyBox=!0;k.legendType==="point"&&j.legend.destroyItem(f);b&&j.redraw(c)}var f=this,g=f.series,h=f.graphic,i,j=g.chart,k=g.options,b=p(b,!0);d===!1?e():f.firePointEvent("update", {options:a},e)},remove:function(a,b){var c=this,d=c.series,e=d.points,f=d.chart,g,h=d.data;Ra(b,f);a=p(a,!0);c.firePointEvent("remove",null,function(){g=Ma(c,h);h.length===e.length&&e.splice(g,1);h.splice(g,1);d.options.data.splice(g,1);d.updateParallelArrays(c,"splice",g,1);c.destroy();d.isDirty=!0;d.isDirtyData=!0;a&&f.redraw()})}});r(O.prototype,{addPoint:function(a,b,c,d){var e=this.options,f=this.data,g=this.graph,h=this.area,i=this.chart,j=this.xAxis&&this.xAxis.names,k=g&&g.shift||0,l=e.data, n,m=this.xData;Ra(d,i);c&&q([g,h,this.graphNeg,this.areaNeg],function(a){if(a)a.shift=k+1});if(h)h.isArea=!0;b=p(b,!0);d={series:this};this.pointClass.prototype.applyOptions.apply(d,[a]);g=d.x;h=m.length;if(this.requireSorting&&g<m[h-1])for(n=!0;h&&m[h-1]>g;)h--;this.updateParallelArrays(d,"splice",h,0,0);this.updateParallelArrays(d,h);if(j&&d.name)j[g]=d.name;l.splice(h,0,a);n&&(this.data.splice(h,0,null),this.processData());e.legendType==="point"&&this.generatePoints();c&&(f[0]&&f[0].remove?f[0].remove(!1): (f.shift(),this.updateParallelArrays(d,"shift"),l.shift()));this.isDirtyData=this.isDirty=!0;b&&(this.getAttribs(),i.redraw())},remove:function(a,b){var c=this,d=c.chart,a=p(a,!0);if(!c.isRemoving)c.isRemoving=!0,I(c,"remove",null,function(){c.destroy();d.isDirtyLegend=d.isDirtyBox=!0;d.linkSeries();a&&d.redraw(b)});c.isRemoving=!1},update:function(a,b){var c=this,d=this.chart,e=this.userOptions,f=this.type,g=H[f].prototype,h=["group","markerGroup","dataLabelsGroup"],i;q(h,function(a){h[a]=c[a];delete c[a]}); a=w(e,{animation:!1,index:this.index,pointStart:this.xData[0]},{data:this.options.data},a);this.remove(!1);for(i in g)g.hasOwnProperty(i)&&(this[i]=u);r(this,H[a.type||f].prototype);q(h,function(a){c[a]=h[a]});this.init(d,a);d.linkSeries();p(b,!0)&&d.redraw(!1)}});r(na.prototype,{update:function(a,b){var c=this.chart,a=c.options[this.coll][this.options.index]=w(this.userOptions,a);this.destroy(!0);this._addedPlotLB=u;this.init(c,r(a,{events:u}));c.isDirtyBox=!0;p(b,!0)&&c.redraw()},remove:function(a){for(var b= this.chart,c=this.coll,d=this.series,e=d.length;e--;)d[e]&&d[e].remove(!1);la(b.axes,this);la(b[c],this);b.options[c].splice(this.options.index,1);q(b[c],function(a,b){a.options.index=b});this.destroy();b.isDirtyBox=!0;p(a,!0)&&b.redraw()},setTitle:function(a,b){this.update({title:a},b)},setCategories:function(a,b){this.update({categories:a},b)}});ia=ma(O);H.line=ia;ca.area=w(T,{threshold:0});var qa=ma(O,{type:"area",getSegments:function(){var a=this,b=[],c=[],d=[],e=this.xAxis,f=this.yAxis,g=f.stacks[this.stackKey], h={},i,j,k=this.points,l=this.options.connectNulls,n,m;if(this.options.stacking&&!this.cropped){for(n=0;n<k.length;n++)h[k[n].x]=k[n];for(m in g)g[m].total!==null&&d.push(+m);d.sort(function(a,b){return a-b});q(d,function(b){var d=0,k;if(!l||h[b]&&h[b].y!==null)if(h[b])c.push(h[b]);else{for(n=a.index;n<=f.series.length;n++)if(k=g[b].points[n+","+b]){d=k[1];break}i=e.translate(b);j=f.toPixels(d,!0);c.push({y:null,plotX:i,clientX:i,plotY:j,yBottom:j,onMouseOver:sa})}});c.length&&b.push(c)}else O.prototype.getSegments.call(this), b=this.segments;this.segments=b},getSegmentPath:function(a){var b=O.prototype.getSegmentPath.call(this,a),c=[].concat(b),d,e=this.options;d=b.length;var f=this.yAxis.getThreshold(e.threshold),g;d===3&&c.push("L",b[1],b[2]);if(e.stacking&&!this.closedStacks)for(d=a.length-1;d>=0;d--)g=p(a[d].yBottom,f),d<a.length-1&&e.step&&c.push(a[d+1].plotX,g),c.push(a[d].plotX,g);else this.closeSegment(c,a,f);this.areaPath=this.areaPath.concat(c);return b},closeSegment:function(a,b,c){a.push("L",b[b.length-1].plotX, c,"L",b[0].plotX,c)},drawGraph:function(){this.areaPath=[];O.prototype.drawGraph.apply(this);var a=this,b=this.areaPath,c=this.options,d=c.negativeColor,e=c.negativeFillColor,f=[["area",this.color,c.fillColor]];(d||e)&&f.push(["areaNeg",d,e]);q(f,function(d){var e=d[0],f=a[e];f?f.animate({d:b}):a[e]=a.chart.renderer.path(b).attr({fill:p(d[2],ya(d[1]).setOpacity(p(c.fillOpacity,0.75)).get()),zIndex:0}).add(a.group)})},drawLegendSymbol:M.drawRectangle});H.area=qa;ca.spline=w(T);ia=ma(O,{type:"spline", getPointSpline:function(a,b,c){var d=b.plotX,e=b.plotY,f=a[c-1],g=a[c+1],h,i,j,k;if(f&&g){a=f.plotY;j=g.plotX;var g=g.plotY,l;h=(1.5*d+f.plotX)/2.5;i=(1.5*e+a)/2.5;j=(1.5*d+j)/2.5;k=(1.5*e+g)/2.5;l=(k-i)*(j-d)/(j-h)+e-k;i+=l;k+=l;i>a&&i>e?(i=t(a,e),k=2*e-i):i<a&&i<e&&(i=L(a,e),k=2*e-i);k>g&&k>e?(k=t(g,e),i=2*e-k):k<g&&k<e&&(k=L(g,e),i=2*e-k);b.rightContX=j;b.rightContY=k}c?(b=["C",f.rightContX||f.plotX,f.rightContY||f.plotY,h||d,i||e,d,e],f.rightContX=f.rightContY=null):b=["M",d,e];return b}});H.spline= ia;ca.areaspline=w(ca.area);qa=qa.prototype;ia=ma(ia,{type:"areaspline",closedStacks:!0,getSegmentPath:qa.getSegmentPath,closeSegment:qa.closeSegment,drawGraph:qa.drawGraph,drawLegendSymbol:M.drawRectangle});H.areaspline=ia;ca.column=w(T,{borderColor:"#FFFFFF",borderRadius:0,groupPadding:0.2,marker:null,pointPadding:0.1,minPointLength:0,cropThreshold:50,pointRange:null,states:{hover:{brightness:0.1,shadow:!1,halo:!1},select:{color:"#C0C0C0",borderColor:"#000000",shadow:!1}},dataLabels:{align:null, verticalAlign:null,y:null},stickyTracking:!1,tooltip:{distance:6},threshold:0});ia=ma(O,{type:"column",pointAttrToOptions:{stroke:"borderColor",fill:"color",r:"borderRadius"},cropShoulder:0,trackerGroups:["group","dataLabelsGroup"],negStacks:!0,init:function(){O.prototype.init.apply(this,arguments);var a=this,b=a.chart;b.hasRendered&&q(b.series,function(b){if(b.type===a.type)b.isDirty=!0})},getColumnMetrics:function(){var a=this,b=a.options,c=a.xAxis,d=a.yAxis,e=c.reversed,f,g={},h,i=0;b.grouping=== !1?i=1:q(a.chart.series,function(b){var c=b.options,e=b.yAxis;if(b.type===a.type&&b.visible&&d.len===e.len&&d.pos===e.pos)c.stacking?(f=b.stackKey,g[f]===u&&(g[f]=i++),h=g[f]):c.grouping!==!1&&(h=i++),b.columnIndex=h});var c=L(Q(c.transA)*(c.ordinalSlope||b.pointRange||c.closestPointRange||c.tickInterval||1),c.len),j=c*b.groupPadding,k=(c-2*j)/i,l=b.pointWidth,b=s(l)?(k-l)/2:k*b.pointPadding,l=p(l,k-2*b);return a.columnMetrics={width:l,offset:b+(j+((e?i-(a.columnIndex||0):a.columnIndex)||0)*k-c/2)* (e?-1:1)}},translate:function(){var a=this,b=a.chart,c=a.options,d=a.borderWidth=p(c.borderWidth,a.activePointCount>0.5*a.xAxis.len?0:1),e=a.yAxis,f=a.translatedThreshold=e.getThreshold(c.threshold),g=p(c.minPointLength,5),h=a.getColumnMetrics(),i=h.width,j=a.barW=t(i,1+2*d),k=a.pointXOffset=h.offset,l=-(d%2?0.5:0),n=d%2?0.5:1;b.renderer.isVML&&b.inverted&&(n+=1);c.pointPadding&&(j=La(j));O.prototype.translate.apply(a);q(a.points,function(c){var d=p(c.yBottom,f),h=L(t(-999-d,c.plotY),e.len+999+d), q=c.plotX+k,r=j,s=L(h,d),u;u=t(h,d)-s;Q(u)<g&&g&&(u=g,s=v(Q(s-f)>g?d-g:f-(e.translate(c.y,0,1,0,1)<=f?g:0)));c.barX=q;c.pointWidth=i;c.tooltipPos=b.inverted?[e.len-h,a.xAxis.len-q-r/2]:[q+r/2,h+e.pos-b.plotTop];r=v(q+r)+l;q=v(q)+l;r-=q;d=Q(s)<0.5;u=v(s+u)+n;s=v(s)+n;u-=s;d&&(s-=1,u+=1);c.shapeType="rect";c.shapeArgs={x:q,y:s,width:r,height:u}})},getSymbol:sa,drawLegendSymbol:M.drawRectangle,drawGraph:sa,drawPoints:function(){var a=this,b=this.chart,c=a.options,d=b.renderer,e=c.animationLimit||250, f,g;q(a.points,function(h){var i=h.plotY,j=h.graphic;if(i!==u&&!isNaN(i)&&h.y!==null)f=h.shapeArgs,i=s(a.borderWidth)?{"stroke-width":a.borderWidth}:{},g=h.pointAttr[h.selected?"select":""]||a.pointAttr[""],j?(bb(j),j.attr(i)[b.pointCount<e?"animate":"attr"](w(f))):h.graphic=d[h.shapeType](f).attr(g).attr(i).add(a.group).shadow(c.shadow,null,c.stacking&&!c.borderRadius);else if(j)h.graphic=j.destroy()})},animate:function(a){var b=this.yAxis,c=this.options,d=this.chart.inverted,e={};if(ba)a?(e.scaleY= 0.001,a=L(b.pos+b.len,t(b.pos,b.toPixels(c.threshold))),d?e.translateX=a-b.len:e.translateY=a,this.group.attr(e)):(e.scaleY=1,e[d?"translateX":"translateY"]=b.pos,this.group.animate(e,this.options.animation),this.animate=null)},remove:function(){var a=this,b=a.chart;b.hasRendered&&q(b.series,function(b){if(b.type===a.type)b.isDirty=!0});O.prototype.remove.apply(a,arguments)}});H.column=ia;ca.bar=w(ca.column);qa=ma(ia,{type:"bar",inverted:!0});H.bar=qa;ca.scatter=w(T,{lineWidth:0,tooltip:{headerFormat:'<span style="color:{series.color}">●</span> <span style="font-size: 10px;"> {series.name}</span><br/>', pointFormat:"x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>"},stickyTracking:!1});qa=ma(O,{type:"scatter",sorted:!1,requireSorting:!1,noSharedTooltip:!0,trackerGroups:["markerGroup","dataLabelsGroup"],takeOrdinalPosition:!1,singularTooltips:!0,drawGraph:function(){this.options.lineWidth&&O.prototype.drawGraph.call(this)}});H.scatter=qa;ca.pie=w(T,{borderColor:"#FFFFFF",borderWidth:1,center:[null,null],clip:!1,colorByPoint:!0,dataLabels:{distance:30,enabled:!0,formatter:function(){return this.point.name}}, ignoreHiddenPoint:!0,legendType:"point",marker:null,size:null,showInLegend:!1,slicedOffset:10,states:{hover:{brightness:0.1,shadow:!1}},stickyTracking:!1,tooltip:{followPointer:!0}});T={type:"pie",isCartesian:!1,pointClass:ma(Fa,{init:function(){Fa.prototype.init.apply(this,arguments);var a=this,b;if(a.y<0)a.y=null;r(a,{visible:a.visible!==!1,name:p(a.name,"Slice")});b=function(b){a.slice(b.type==="select")};N(a,"select",b);N(a,"unselect",b);return a},setVisible:function(a){var b=this,c=b.series, d=c.chart;b.visible=b.options.visible=a=a===u?!b.visible:a;c.options.data[Ma(b,c.data)]=b.options;q(["graphic","dataLabel","connector","shadowGroup"],function(c){if(b[c])b[c][a?"show":"hide"](!0)});b.legendItem&&d.legend.colorizeItem(b,a);if(!c.isDirty&&c.options.ignoreHiddenPoint)c.isDirty=!0,d.redraw()},slice:function(a,b,c){var d=this.series;Ra(c,d.chart);p(b,!0);this.sliced=this.options.sliced=a=s(a)?a:!this.sliced;d.options.data[Ma(this,d.data)]=this.options;a=a?this.slicedTranslation:{translateX:0, translateY:0};this.graphic.animate(a);this.shadowGroup&&this.shadowGroup.animate(a)},haloPath:function(a){var b=this.shapeArgs,c=this.series.chart;return this.sliced||!this.visible?[]:this.series.chart.renderer.symbols.arc(c.plotLeft+b.x,c.plotTop+b.y,b.r+a,b.r+a,{innerR:this.shapeArgs.r,start:b.start,end:b.end})}}),requireSorting:!1,noSharedTooltip:!0,trackerGroups:["group","dataLabelsGroup"],axisTypes:[],pointAttrToOptions:{stroke:"borderColor","stroke-width":"borderWidth",fill:"color"},singularTooltips:!0, getColor:sa,animate:function(a){var b=this,c=b.points,d=b.startAngleRad;if(!a)q(c,function(a){var c=a.graphic,a=a.shapeArgs;c&&(c.attr({r:b.center[3]/2,start:d,end:d}),c.animate({r:a.r,start:a.start,end:a.end},b.options.animation))}),b.animate=null},setData:function(a,b,c,d){O.prototype.setData.call(this,a,!1,c,d);this.processData();this.generatePoints();p(b,!0)&&this.chart.redraw(c)},generatePoints:function(){var a,b=0,c,d,e,f=this.options.ignoreHiddenPoint;O.prototype.generatePoints.call(this); c=this.points;d=c.length;for(a=0;a<d;a++)e=c[a],b+=f&&!e.visible?0:e.y;this.total=b;for(a=0;a<d;a++)e=c[a],e.percentage=b>0?e.y/b*100:0,e.total=b},translate:function(a){this.generatePoints();var b=0,c=this.options,d=c.slicedOffset,e=d+c.borderWidth,f,g,h,i=c.startAngle||0,j=this.startAngleRad=oa/180*(i-90),i=(this.endAngleRad=oa/180*(p(c.endAngle,i+360)-90))-j,k=this.points,l=c.dataLabels.distance,c=c.ignoreHiddenPoint,n,m=k.length,o;if(!a)this.center=a=this.getCenter();this.getX=function(b,c){h= V.asin(L((b-a[1])/(a[2]/2+l),1));return a[0]+(c?-1:1)*aa(h)*(a[2]/2+l)};for(n=0;n<m;n++){o=k[n];f=j+b*i;if(!c||o.visible)b+=o.percentage/100;g=j+b*i;o.shapeType="arc";o.shapeArgs={x:a[0],y:a[1],r:a[2]/2,innerR:a[3]/2,start:v(f*1E3)/1E3,end:v(g*1E3)/1E3};h=(g+f)/2;h>1.5*oa?h-=2*oa:h<-oa/2&&(h+=2*oa);o.slicedTranslation={translateX:v(aa(h)*d),translateY:v(fa(h)*d)};f=aa(h)*a[2]/2;g=fa(h)*a[2]/2;o.tooltipPos=[a[0]+f*0.7,a[1]+g*0.7];o.half=h<-oa/2||h>oa/2?1:0;o.angle=h;e=L(e,l/2);o.labelPos=[a[0]+f+aa(h)* l,a[1]+g+fa(h)*l,a[0]+f+aa(h)*e,a[1]+g+fa(h)*e,a[0]+f,a[1]+g,l<0?"center":o.half?"right":"left",h]}},drawGraph:null,drawPoints:function(){var a=this,b=a.chart.renderer,c,d,e=a.options.shadow,f,g;if(e&&!a.shadowGroup)a.shadowGroup=b.g("shadow").add(a.group);q(a.points,function(h){d=h.graphic;g=h.shapeArgs;f=h.shadowGroup;if(e&&!f)f=h.shadowGroup=b.g("shadow").add(a.shadowGroup);c=h.sliced?h.slicedTranslation:{translateX:0,translateY:0};f&&f.attr(c);d?d.animate(r(g,c)):h.graphic=d=b[h.shapeType](g).setRadialReference(a.center).attr(h.pointAttr[h.selected? "select":""]).attr({"stroke-linejoin":"round"}).attr(c).add(a.group).shadow(e,f);h.visible!==void 0&&h.setVisible(h.visible)})},sortByAngle:function(a,b){a.sort(function(a,d){return a.angle!==void 0&&(d.angle-a.angle)*b})},drawLegendSymbol:M.drawRectangle,getCenter:Z.getCenter,getSymbol:sa};T=ma(O,T);H.pie=T;O.prototype.drawDataLabels=function(){var a=this,b=a.options,c=b.cursor,d=b.dataLabels,e=a.points,f,g,h=a.hasRendered||0,i,j;if(d.enabled||a._hasPointLabels)a.dlProcessOptions&&a.dlProcessOptions(d), j=a.plotGroup("dataLabelsGroup","data-labels",d.defer?"hidden":"visible",d.zIndex||6),p(d.defer,!0)&&(j.attr({opacity:+h}),h||N(a,"afterAnimate",function(){a.visible&&j.show();j[b.animation?"animate":"attr"]({opacity:1},{duration:200})})),g=d,q(e,function(b){var e,h=b.dataLabel,m,o,q=b.connector,t=!0;f=b.options&&b.options.dataLabels;e=p(f&&f.enabled,g.enabled);if(h&&!e)b.dataLabel=h.destroy();else if(e){d=w(g,f);e=d.rotation;m=b.getLabelConfig();i=d.format?Ja(d.format,m):d.formatter.call(m,d);d.style.color= p(d.color,d.style.color,a.color,"black");if(h)if(s(i))h.attr({text:i}),t=!1;else{if(b.dataLabel=h=h.destroy(),q)b.connector=q.destroy()}else if(s(i)){h={fill:d.backgroundColor,stroke:d.borderColor,"stroke-width":d.borderWidth,r:d.borderRadius||0,rotation:e,padding:d.padding,zIndex:1};for(o in h)h[o]===u&&delete h[o];h=b.dataLabel=a.chart.renderer[e?"text":"label"](i,0,-999,null,null,null,d.useHTML).attr(h).css(r(d.style,c&&{cursor:c})).add(j).shadow(d.shadow)}h&&a.alignDataLabel(b,h,d,null,t)}})}; O.prototype.alignDataLabel=function(a,b,c,d,e){var f=this.chart,g=f.inverted,h=p(a.plotX,-999),i=p(a.plotY,-999),j=b.getBBox();if(a=this.visible&&(a.series.forceDL||f.isInsidePlot(h,v(i),g)||d&&f.isInsidePlot(h,g?d.x+1:d.y+d.height-1,g)))d=r({x:g?f.plotWidth-i:h,y:v(g?f.plotHeight-h:i),width:0,height:0},d),r(c,{width:j.width,height:j.height}),c.rotation?b[e?"attr":"animate"]({x:d.x+c.x+d.width/2,y:d.y+c.y+d.height/2}).attr({align:c.align}):(b.align(c,null,d),g=b.alignAttr,p(c.overflow,"justify")=== "justify"?this.justifyDataLabel(b,c,g,j,d,e):p(c.crop,!0)&&(a=f.isInsidePlot(g.x,g.y)&&f.isInsidePlot(g.x+j.width,g.y+j.height)));if(!a)b.attr({y:-999}),b.placed=!1};O.prototype.justifyDataLabel=function(a,b,c,d,e,f){var g=this.chart,h=b.align,i=b.verticalAlign,j,k;j=c.x;if(j<0)h==="right"?b.align="left":b.x=-j,k=!0;j=c.x+d.width;if(j>g.plotWidth)h==="left"?b.align="right":b.x=g.plotWidth-j,k=!0;j=c.y;if(j<0)i==="bottom"?b.verticalAlign="top":b.y=-j,k=!0;j=c.y+d.height;if(j>g.plotHeight)i==="top"? b.verticalAlign="bottom":b.y=g.plotHeight-j,k=!0;if(k)a.placed=!f,a.align(b,null,e)};if(H.pie)H.pie.prototype.drawDataLabels=function(){var a=this,b=a.data,c,d=a.chart,e=a.options.dataLabels,f=p(e.connectorPadding,10),g=p(e.connectorWidth,1),h=d.plotWidth,i=d.plotHeight,j,k,l=p(e.softConnector,!0),n=e.distance,m=a.center,o=m[2]/2,r=m[1],s=n>0,u,w,x,A=[[],[]],y,B,I,H,z,R=[0,0,0,0],N=function(a,b){return b.y-a.y};if(a.visible&&(e.enabled||a._hasPointLabels)){O.prototype.drawDataLabels.apply(a);q(b, function(a){a.dataLabel&&a.visible&&A[a.half].push(a)});for(H=2;H--;){var G=[],M=[],F=A[H],K=F.length,E;if(K){a.sortByAngle(F,H-0.5);for(z=b=0;!b&&F[z];)b=F[z]&&F[z].dataLabel&&(F[z].dataLabel.getBBox().height||21),z++;if(n>0){w=L(r+o+n,d.plotHeight);for(z=t(0,r-o-n);z<=w;z+=b)G.push(z);w=G.length;if(K>w){c=[].concat(F);c.sort(N);for(z=K;z--;)c[z].rank=z;for(z=K;z--;)F[z].rank>=w&&F.splice(z,1);K=F.length}for(z=0;z<K;z++){c=F[z];x=c.labelPos;c=9999;var S,P;for(P=0;P<w;P++)S=Q(G[P]-x[1]),S<c&&(c=S, E=P);if(E<z&&G[z]!==null)E=z;else for(w<K-z+E&&G[z]!==null&&(E=w-K+z);G[E]===null;)E++;M.push({i:E,y:G[E]});G[E]=null}M.sort(N)}for(z=0;z<K;z++){c=F[z];x=c.labelPos;u=c.dataLabel;I=c.visible===!1?"hidden":"visible";c=x[1];if(n>0){if(w=M.pop(),E=w.i,B=w.y,c>B&&G[E+1]!==null||c<B&&G[E-1]!==null)B=L(t(0,c),d.plotHeight)}else B=c;y=e.justify?m[0]+(H?-1:1)*(o+n):a.getX(B===r-o-n||B===r+o+n?c:B,H);u._attr={visibility:I,align:x[6]};u._pos={x:y+e.x+({left:f,right:-f}[x[6]]||0),y:B+e.y-10};u.connX=y;u.connY= B;if(this.options.size===null)w=u.width,y-w<f?R[3]=t(v(w-y+f),R[3]):y+w>h-f&&(R[1]=t(v(y+w-h+f),R[1])),B-b/2<0?R[0]=t(v(-B+b/2),R[0]):B+b/2>i&&(R[2]=t(v(B+b/2-i),R[2]))}}}if(Ca(R)===0||this.verifyDataLabelOverflow(R))this.placeDataLabels(),s&&g&&q(this.points,function(b){j=b.connector;x=b.labelPos;if((u=b.dataLabel)&&u._pos)I=u._attr.visibility,y=u.connX,B=u.connY,k=l?["M",y+(x[6]==="left"?5:-5),B,"C",y,B,2*x[2]-x[4],2*x[3]-x[5],x[2],x[3],"L",x[4],x[5]]:["M",y+(x[6]==="left"?5:-5),B,"L",x[2],x[3], "L",x[4],x[5]],j?(j.animate({d:k}),j.attr("visibility",I)):b.connector=j=a.chart.renderer.path(k).attr({"stroke-width":g,stroke:e.connectorColor||b.color||"#606060",visibility:I}).add(a.dataLabelsGroup);else if(j)b.connector=j.destroy()})}},H.pie.prototype.placeDataLabels=function(){q(this.points,function(a){var a=a.dataLabel,b;if(a)(b=a._pos)?(a.attr(a._attr),a[a.moved?"animate":"attr"](b),a.moved=!0):a&&a.attr({y:-999})})},H.pie.prototype.alignDataLabel=sa,H.pie.prototype.verifyDataLabelOverflow= function(a){var b=this.center,c=this.options,d=c.center,e=c=c.minSize||80,f;d[0]!==null?e=t(b[2]-t(a[1],a[3]),c):(e=t(b[2]-a[1]-a[3],c),b[0]+=(a[3]-a[1])/2);d[1]!==null?e=t(L(e,b[2]-t(a[0],a[2])),c):(e=t(L(e,b[2]-a[0]-a[2]),c),b[1]+=(a[0]-a[2])/2);e<b[2]?(b[2]=e,this.translate(b),q(this.points,function(a){if(a.dataLabel)a.dataLabel._pos=null}),this.drawDataLabels&&this.drawDataLabels()):f=!0;return f};if(H.column)H.column.prototype.alignDataLabel=function(a,b,c,d,e){var f=this.chart,g=f.inverted, h=a.dlBox||a.shapeArgs,i=a.below||a.plotY>p(this.translatedThreshold,f.plotSizeY),j=p(c.inside,!!this.options.stacking);if(h&&(d=w(h),g&&(d={x:f.plotWidth-d.y-d.height,y:f.plotHeight-d.x-d.width,width:d.height,height:d.width}),!j))g?(d.x+=i?0:d.width,d.width=0):(d.y+=i?d.height:0,d.height=0);c.align=p(c.align,!g||j?"center":i?"right":"left");c.verticalAlign=p(c.verticalAlign,g||j?"middle":i?"top":"bottom");O.prototype.alignDataLabel.call(this,a,b,c,d,e)};T=K.TrackerMixin={drawTrackerPoint:function(){var a= this,b=a.chart,c=b.pointer,d=a.options.cursor,e=d&&{cursor:d},f=function(c){var d=c.target,e;if(b.hoverSeries!==a)a.onMouseOver();for(;d&&!e;)e=d.point,d=d.parentNode;if(e!==u&&e!==b.hoverPoint)e.onMouseOver(c)};q(a.points,function(a){if(a.graphic)a.graphic.element.point=a;if(a.dataLabel)a.dataLabel.element.point=a});if(!a._hasTracking)q(a.trackerGroups,function(b){if(a[b]&&(a[b].addClass("highcharts-tracker").on("mouseover",f).on("mouseout",function(a){c.onTrackerMouseOut(a)}).css(e),$a))a[b].on("touchstart", f)}),a._hasTracking=!0},drawTrackerGraph:function(){var a=this,b=a.options,c=b.trackByArea,d=[].concat(c?a.areaPath:a.graphPath),e=d.length,f=a.chart,g=f.pointer,h=f.renderer,i=f.options.tooltip.snap,j=a.tracker,k=b.cursor,l=k&&{cursor:k},k=a.singlePoints,n,m=function(){if(f.hoverSeries!==a)a.onMouseOver()},o="rgba(192,192,192,"+(ba?1.0E-4:0.002)+")";if(e&&!c)for(n=e+1;n--;)d[n]==="M"&&d.splice(n+1,0,d[n+1]-i,d[n+2],"L"),(n&&d[n]==="M"||n===e)&&d.splice(n,0,"L",d[n-2]+i,d[n-1]);for(n=0;n<k.length;n++)e= k[n],d.push("M",e.plotX-i,e.plotY,"L",e.plotX+i,e.plotY);j?j.attr({d:d}):(a.tracker=h.path(d).attr({"stroke-linejoin":"round",visibility:a.visible?"visible":"hidden",stroke:o,fill:c?o:P,"stroke-width":b.lineWidth+(c?0:2*i),zIndex:2}).add(a.group),q([a.tracker,a.markerGroup],function(a){a.addClass("highcharts-tracker").on("mouseover",m).on("mouseout",function(a){g.onTrackerMouseOut(a)}).css(l);if($a)a.on("touchstart",m)}))}};if(H.column)ia.prototype.drawTracker=T.drawTrackerPoint;if(H.pie)H.pie.prototype.drawTracker= T.drawTrackerPoint;if(H.scatter)qa.prototype.drawTracker=T.drawTrackerPoint;r(lb.prototype,{setItemEvents:function(a,b,c,d,e){var f=this;(c?b:a.legendGroup).on("mouseover",function(){a.setState("hover");b.css(f.options.itemHoverStyle)}).on("mouseout",function(){b.css(a.visible?d:e);a.setState()}).on("click",function(b){var c=function(){a.setVisible()},b={browserEvent:b};a.firePointEvent?a.firePointEvent("legendItemClick",b,c):I(a,"legendItemClick",b,c)})},createCheckboxForItem:function(a){a.checkbox= $("input",{type:"checkbox",checked:a.selected,defaultChecked:a.selected},this.options.itemCheckboxStyle,this.chart.container);N(a.checkbox,"click",function(b){I(a,"checkboxClick",{checked:b.target.checked},function(){a.select()})})}});E.legend.itemStyle.cursor="pointer";r(Ya.prototype,{showResetZoom:function(){var a=this,b=E.lang,c=a.options.chart.resetZoomButton,d=c.theme,e=d.states,f=c.relativeTo==="chart"?null:"plotBox";this.resetZoomButton=a.renderer.button(b.resetZoom,null,null,function(){a.zoomOut()}, d,e&&e.hover).attr({align:c.position.align,title:b.resetZoomTitle}).add().align(c.position,!1,f)},zoomOut:function(){var a=this;I(a,"selection",{resetSelection:!0},function(){a.zoom()})},zoom:function(a){var b,c=this.pointer,d=!1,e;!a||a.resetSelection?q(this.axes,function(a){b=a.zoom()}):q(a.xAxis.concat(a.yAxis),function(a){var e=a.axis,h=e.isXAxis;if(c[h?"zoomX":"zoomY"]||c[h?"pinchX":"pinchY"])b=e.zoom(a.min,a.max),e.displayBtn&&(d=!0)});e=this.resetZoomButton;if(d&&!e)this.showResetZoom();else if(!d&& da(e))this.resetZoomButton=e.destroy();b&&this.redraw(p(this.options.chart.animation,a&&a.animation,this.pointCount<100))},pan:function(a,b){var c=this,d=c.hoverPoints,e;d&&q(d,function(a){a.setState()});q(b==="xy"?[1,0]:[1],function(b){var d=a[b?"chartX":"chartY"],h=c[b?"xAxis":"yAxis"][0],i=c[b?"mouseDownX":"mouseDownY"],j=(h.pointRange||0)/2,k=h.getExtremes(),l=h.toValue(i-d,!0)+j,i=h.toValue(i+c[b?"plotWidth":"plotHeight"]-d,!0)-j;h.series.length&&l>L(k.dataMin,k.min)&&i<t(k.dataMax,k.max)&&(h.setExtremes(l, i,!1,!1,{trigger:"pan"}),e=!0);c[b?"mouseDownX":"mouseDownY"]=d});e&&c.redraw(!1);B(c.container,{cursor:"move"})}});r(Fa.prototype,{select:function(a,b){var c=this,d=c.series,e=d.chart,a=p(a,!c.selected);c.firePointEvent(a?"select":"unselect",{accumulate:b},function(){c.selected=c.options.selected=a;d.options.data[Ma(c,d.data)]=c.options;c.setState(a&&"select");b||q(e.getSelectedPoints(),function(a){if(a.selected&&a!==c)a.selected=a.options.selected=!1,d.options.data[Ma(a,d.data)]=a.options,a.setState(""), a.firePointEvent("unselect")})})},onMouseOver:function(a){var b=this.series,c=b.chart,d=c.tooltip,e=c.hoverPoint;if(e&&e!==this)e.onMouseOut();this.firePointEvent("mouseOver");d&&(!d.shared||b.noSharedTooltip)&&d.refresh(this,a);this.setState("hover");c.hoverPoint=this},onMouseOut:function(){var a=this.series.chart,b=a.hoverPoints;this.firePointEvent("mouseOut");if(!b||Ma(this,b)===-1)this.setState(),a.hoverPoint=null},importEvents:function(){if(!this.hasImportedEvents){var a=w(this.series.options.point, this.options).events,b;this.events=a;for(b in a)N(this,b,a[b]);this.hasImportedEvents=!0}},setState:function(a,b){var c=this.plotX,d=this.plotY,e=this.series,f=e.options.states,g=ca[e.type].marker&&e.options.marker,h=g&&!g.enabled,i=g&&g.states[a],j=i&&i.enabled===!1,k=e.stateMarkerGraphic,l=this.marker||{},n=e.chart,m=e.halo,o,a=a||"";o=this.pointAttr[a]||e.pointAttr[a];if(!(a===this.state&&!b||this.selected&&a!=="select"||f[a]&&f[a].enabled===!1||a&&(j||h&&i.enabled===!1)||a&&l.states&&l.states[a]&& l.states[a].enabled===!1)){if(this.graphic)g=g&&this.graphic.symbolName&&o.r,this.graphic.attr(w(o,g?{x:c-g,y:d-g,width:2*g,height:2*g}:{})),k&&k.hide();else{if(a&&i)if(g=i.radius,l=l.symbol||e.symbol,k&&k.currentSymbol!==l&&(k=k.destroy()),k)k[b?"animate":"attr"]({x:c-g,y:d-g});else if(l)e.stateMarkerGraphic=k=n.renderer.symbol(l,c-g,d-g,2*g,2*g).attr(o).add(e.markerGroup),k.currentSymbol=l;if(k)k[a&&n.isInsidePlot(c,d,n.inverted)?"show":"hide"]()}if((c=f[a]&&f[a].halo)&&c.size){if(!m)e.halo=m=n.renderer.path().add(e.seriesGroup); m.attr(r({fill:ya(this.color||e.color).setOpacity(c.opacity).get()},c.attributes))[b?"animate":"attr"]({d:this.haloPath(c.size)})}else m&&m.attr({d:[]});this.state=a}},haloPath:function(a){var b=this.series,c=b.chart,d=b.getPlotBox(),e=c.inverted;return c.renderer.symbols.circle(d.translateX+(e?b.yAxis.len-this.plotY:this.plotX)-a,d.translateY+(e?b.xAxis.len-this.plotX:this.plotY)-a,a*2,a*2)}});r(O.prototype,{onMouseOver:function(){var a=this.chart,b=a.hoverSeries;if(b&&b!==this)b.onMouseOut();this.options.events.mouseOver&& I(this,"mouseOver");this.setState("hover");a.hoverSeries=this},onMouseOut:function(){var a=this.options,b=this.chart,c=b.tooltip,d=b.hoverPoint;if(d)d.onMouseOut();this&&a.events.mouseOut&&I(this,"mouseOut");c&&!a.stickyTracking&&(!c.shared||this.noSharedTooltip)&&c.hide();this.setState();b.hoverSeries=null},setState:function(a){var b=this.options,c=this.graph,d=this.graphNeg,e=b.states,b=b.lineWidth,a=a||"";if(this.state!==a)this.state=a,e[a]&&e[a].enabled===!1||(a&&(b=e[a].lineWidth||b+(e[a].lineWidthPlus|| 0)),c&&!c.dashstyle&&(a={"stroke-width":b},c.attr(a),d&&d.attr(a)))},setVisible:function(a,b){var c=this,d=c.chart,e=c.legendItem,f,g=d.options.chart.ignoreHiddenSeries,h=c.visible;f=(c.visible=a=c.userOptions.visible=a===u?!h:a)?"show":"hide";q(["group","dataLabelsGroup","markerGroup","tracker"],function(a){if(c[a])c[a][f]()});if(d.hoverSeries===c)c.onMouseOut();e&&d.legend.colorizeItem(c,a);c.isDirty=!0;c.options.stacking&&q(d.series,function(a){if(a.options.stacking&&a.visible)a.isDirty=!0});q(c.linkedSeries, function(b){b.setVisible(a,!1)});if(g)d.isDirtyBox=!0;b!==!1&&d.redraw();I(c,f)},setTooltipPoints:function(a){var b=[],c,d,e=this.xAxis,f=e&&e.getExtremes(),g=e?e.tooltipLen||e.len:this.chart.plotSizeX,h,i,j=[];if(!(this.options.enableMouseTracking===!1||this.singularTooltips)){if(a)this.tooltipPoints=null;q(this.segments||this.points,function(a){b=b.concat(a)});e&&e.reversed&&(b=b.reverse());this.orderTooltipPoints&&this.orderTooltipPoints(b);a=b.length;for(i=0;i<a;i++)if(e=b[i],c=e.x,c>=f.min&& c<=f.max){h=b[i+1];c=d===u?0:d+1;for(d=b[i+1]?L(t(0,U((e.clientX+(h?h.wrappedClientX||h.clientX:g))/2)),g):g;c>=0&&c<=d;)j[c++]=e}this.tooltipPoints=j}},show:function(){this.setVisible(!0)},hide:function(){this.setVisible(!1)},select:function(a){this.selected=a=a===u?!this.selected:a;if(this.checkbox)this.checkbox.checked=a;I(this,a?"select":"unselect")},drawTracker:T.drawTrackerGraph});r(K,{Axis:na,Chart:Ya,Color:ya,Point:Fa,Tick:Ta,Renderer:Za,Series:O,SVGElement:S,SVGRenderer:ta,arrayMin:Oa,arrayMax:Ca, charts:W,dateFormat:cb,format:Ja,pathAnim:vb,getOptions:function(){return E},hasBidiBug:Ob,isTouchDevice:Ib,numberFormat:Ba,seriesTypes:H,setOptions:function(a){E=w(!0,E,a);Bb();return E},addEvent:N,removeEvent:X,createElement:$,discardElement:Qa,css:B,each:q,extend:r,map:Va,merge:w,pick:p,splat:ra,extendClass:ma,pInt:y,wrap:Na,svg:ba,canvas:ga,vml:!ba&&!ga,product:"Highcharts",version:"4.0.4"})})();
var GliderTrackModel = Backbone.Model.extend({ urlRoot: '#', defaults: { enabled: false, arrayCodes:{ "CP":"Coastal Pioneer", "CE":"Coastal Endurance", "RS":"Cabled Array", "GP":"Station Papa", "GI":"Irminger Sea", "GA":"Argentine Basin", "GS":"Southern Ocean" } } }); var GliderTrackCollection = Backbone.Collection.extend({ url: '/api/uframe/glider_tracks', model: GliderTrackModel, parse: function(response) { if(response && response.gliders) { return response.gliders; } return []; } });
/* * 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'); /** * Hadoop Distributed File System (HDFS) linked service. * * @extends models['LinkedService'] */ class HdfsLinkedService extends models['LinkedService'] { /** * Create a HdfsLinkedService. * @member {object} url The URL of the HDFS service endpoint, e.g. * http://myhostname:50070/webhdfs/v1 . Type: string (or Expression with * resultType string). * @member {object} [authenticationType] Type of authentication used to * connect to the HDFS. Possible values are: Anonymous and Windows. Type: * string (or Expression with resultType string). * @member {object} [encryptedCredential] The encrypted credential used for * authentication. Credentials are encrypted using the integration runtime * credential manager. Type: string (or Expression with resultType string). * @member {object} [userName] User name for Windows authentication. Type: * string (or Expression with resultType string). * @member {object} [password] Password for Windows authentication. * @member {string} [password.value] Value of secure string. */ constructor() { super(); } /** * Defines the metadata of HdfsLinkedService * * @returns {object} metadata of HdfsLinkedService * */ mapper() { return { required: false, serializedName: 'Hdfs', type: { name: 'Composite', className: 'HdfsLinkedService', modelProperties: { connectVia: { required: false, serializedName: 'connectVia', type: { name: 'Composite', className: 'IntegrationRuntimeReference' } }, description: { required: false, serializedName: 'description', type: { name: 'String' } }, type: { required: true, serializedName: 'type', type: { name: 'String' } }, url: { required: true, serializedName: 'typeProperties.url', type: { name: 'Object' } }, authenticationType: { required: false, serializedName: 'typeProperties.authenticationType', type: { name: 'Object' } }, encryptedCredential: { required: false, serializedName: 'typeProperties.encryptedCredential', type: { name: 'Object' } }, userName: { required: false, serializedName: 'typeProperties.userName', type: { name: 'Object' } }, password: { required: false, serializedName: 'typeProperties.password', type: { name: 'Composite', className: 'SecureString' } } } } }; } } module.exports = HdfsLinkedService;
'use strict'; const Bluebird = require('bluebird'); const EventEmitter = require('events').EventEmitter; class SignalListeners extends EventEmitter { static with() { let signalListeners = new this(); return signalListeners.add().disposer(() => signalListeners.remove()); } } SignalListeners.prototype.add = Bluebird.method(function() { this._boundSigInterrupt = () => { this.emit('signal', new Error('Received SIGINT signal')); }; process.on('SIGINT', this._boundSigInterrupt); this._boundSigTerminate = () => { this.emit('signal', new Error('Received SIGTERM signal')); }; process.on('SIGTERM', this._boundSigTerminate); return this; }); SignalListeners.prototype.remove = Bluebird.method(function() { if (this._boundSigInterrupt) { process.removeListener('SIGINT', this._boundSigInterrupt); } if (this._boundSigTerminate) { process.removeListener('SIGTERM', this._boundSigTerminate); } }); module.exports = SignalListeners;
import{createContext}from"react";var RTLContext=createContext(!1);export default RTLContext;
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); switch (arguments.length) { case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); } }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; import { CONST_EXPR } from 'angular2/src/facade/lang'; import { BaseException } from 'angular2/src/facade/exceptions'; import { ListWrapper } from 'angular2/src/facade/collection'; import { DOM } from 'angular2/src/core/dom/dom_adapter'; import { NgZone } from 'angular2/src/core/zone/ng_zone'; import { Injectable, Inject, OpaqueToken } from 'angular2/src/core/di'; export const EVENT_MANAGER_PLUGINS = CONST_EXPR(new OpaqueToken("EventManagerPlugins")); export let EventManager = class { constructor(plugins, _zone) { this._zone = _zone; plugins.forEach(p => p.manager = this); this._plugins = ListWrapper.reversed(plugins); } addEventListener(element, eventName, handler) { var plugin = this._findPluginFor(eventName); plugin.addEventListener(element, eventName, handler); } addGlobalEventListener(target, eventName, handler) { var plugin = this._findPluginFor(eventName); return plugin.addGlobalEventListener(target, eventName, handler); } getZone() { return this._zone; } /** @internal */ _findPluginFor(eventName) { var plugins = this._plugins; for (var i = 0; i < plugins.length; i++) { var plugin = plugins[i]; if (plugin.supports(eventName)) { return plugin; } } throw new BaseException(`No event manager plugin found for event ${eventName}`); } }; EventManager = __decorate([ Injectable(), __param(0, Inject(EVENT_MANAGER_PLUGINS)), __metadata('design:paramtypes', [Array, NgZone]) ], EventManager); export class EventManagerPlugin { // That is equivalent to having supporting $event.target supports(eventName) { return false; } addEventListener(element, eventName, handler) { throw "not implemented"; } addGlobalEventListener(element, eventName, handler) { throw "not implemented"; } } export let DomEventsPlugin = class extends EventManagerPlugin { // This plugin should come last in the list of plugins, because it accepts all // events. supports(eventName) { return true; } addEventListener(element, eventName, handler) { var zone = this.manager.getZone(); var outsideHandler = (event) => zone.run(() => handler(event)); this.manager.getZone().runOutsideAngular(() => { DOM.on(element, eventName, outsideHandler); }); } addGlobalEventListener(target, eventName, handler) { var element = DOM.getGlobalEventTarget(target); var zone = this.manager.getZone(); var outsideHandler = (event) => zone.run(() => handler(event)); return this.manager.getZone().runOutsideAngular(() => { return DOM.onAndCancel(element, eventName, outsideHandler); }); } }; DomEventsPlugin = __decorate([ Injectable(), __metadata('design:paramtypes', []) ], DomEventsPlugin); //# sourceMappingURL=event_manager.js.map
import {ObserverLocator} from '../src/observer-locator'; import {DirtyChecker} from '../src/dirty-checking'; import {EventManager} from '../src/event-manager'; import {Parser} from '../src/parser'; import {BindingExpression} from '../src/binding-expression'; import {TaskQueue} from 'aurelia-task-queue'; export var checkDelay = 20; export function createElement(html) { var div = document.createElement('div'); div.innerHTML = html; return div.firstChild; } export function createEvent(name) { var event = document.createEvent('Event'); event.initEvent(name, true, true); return event; } export function fireEvent(element, name) { var event = createEvent(name); element.dispatchEvent(event); } export function createObserverLocator(adapters = []) { var locator = new ObserverLocator(new TaskQueue(), new EventManager(), new DirtyChecker(), adapters); locator.dirtyChecker.checkDelay = checkDelay; return locator; } export function getBinding(observerLocator, model, modelProperty, view, viewProperty, mode) { var targetProperty, sourceExpression, bindingExpression, binding, parser; parser = new Parser(); targetProperty = observerLocator.getObserver(view, viewProperty); sourceExpression = parser.parse(modelProperty); bindingExpression = new BindingExpression( observerLocator, viewProperty, sourceExpression, mode, name => null, undefined); binding = bindingExpression.createBinding(view); return { targetProperty: targetProperty, sourceExpression: sourceExpression, bindingExpression: bindingExpression, binding: binding, view: view, model: model }; } export class Person { constructor() { this.firstName = 'John'; this.lastName = 'Doe'; } get fullName() { return `${this.firstName} ${this.lastName}`; } } export class Foo { constructor() { this._bar = null; } get bar() { return this._bar; } set bar(newValue) { this._bar = newValue; } } export class FooNoDep { constructor() { this._bar = null; } get bar() { return this._bar; } set bar(newValue) { this._bar = newValue; } } export function executeSharedPropertyObserverTests(obj, observer, done) { var callback = jasmine.createSpy('callback'), oldValue, newValue, dispose = observer.subscribe(callback), values = ['alkjdfs', 0, false, {}, [], null, undefined, 'foo'], next; next = () => { if (values.length) { oldValue = observer.getValue(); newValue = values.splice(0, 1)[0]; observer.setValue(newValue); setTimeout(() => { expect(callback).toHaveBeenCalledWith(newValue, oldValue); next(); }, checkDelay * 2); } else { dispose(); callback.calls.reset(); observer.setValue('bar'); setTimeout(() => { expect(callback.calls.count()).toEqual(0); done(); }, checkDelay * 2); } }; next(); }
ERNO.Controls = (function(){ //Enum of states var STATE = { NONE: -1, ROTATE: 0, INERTIA: 1 }; // Returns the bounding area of the element function getBoundingClientRect( element ){ var bounds = element !== document ? element.getBoundingClientRect() : { left: 0, top: 0, width: window.innerWidth, height: window.innerHeight }; return bounds; } return function ( object, camera, domElement ) { var state = STATE.NONE, direction = new THREE.Vector2, mouse = new THREE.Vector2(), mouseEnd = new THREE.Vector2(), lastPosition = new THREE.Vector2(), projector = new ERNO.Projector( object, domElement ), api = { enabled: true, domElement: domElement, rotationSpeed: 4.0, damping: 0.25 }; var getMouseProjectionOnBall = function( x, y, vector ){ var view = getBoundingClientRect( api.domElement ), aspect = view.height / view.width var dpr = window.devicePixelRatio || 1 x *= dpr y *= dpr return vector.set( ( x - view.width - view.left ) * 0.001 , // view.width,// * ( devicePixelRatio || 1 ) , ( view.height + view.top - y ) * 0.001 // view.height// * aspect // ( devicePixelRatio || 1 ) ); }; api.update = function(){ var axis = new THREE.Vector3, length = 0.0, modelViewInverse = new THREE.Matrix4(); return function updateClosure () { if( api.enabled === false || state === STATE.NONE ) return; // define an axis to rotate on, this is basically at a tangent to the direction axis.set( direction.y, direction.x * -1, 0 ).normalize(); // The axis of rotation needs to be in mode view space, otherwise the rotation // will happen in a really strange way. We therefore need to get the local rotation // of the cube and the relative position of the camera and update our axis. modelViewInverse.getInverse( object.matrixWorld ); modelViewInverse.multiply( camera.matrixWorld ); axis.transformDirection( modelViewInverse ); // If we're in a INERTIA state, then apply an inertia like effect direction.multiplyScalar( 1.0 - Math.max( 0.0, Math.min( 1.0, api.damping ))); // Determine how far we've moved. This to determine how much to rotate by length = direction.length(); // Then we can rotate the cube based on how far the drag occured object.object3D.rotateOnAxis( axis, -length * api.rotationSpeed ); // Reset our internal state if( state === STATE.ROTATE ) state = STATE.NONE; // If the rotation is below a certain threshold specified as a factor of the damping effect, // then for all purposes, any more rotation is not noticesable, so we can might aswell stop rotating. else if( state === STATE.INERTIA && length >= 0.0001 ){ mouse.add( direction ); } else { state = STATE.NONE } }; }(); /** * Define listeners for user initiated events */ function mousedown( event ) { if ( !api.enabled || event.which !== 1 ) return; if( projector.getIntersection( camera, event.pageX, event.pageY ) === null ){ state = STATE.ROTATE; direction.multiplyScalar( 0 ); getMouseProjectionOnBall( event.pageX, event.pageY, mouse ); lastPosition.copy( mouse ); api.domElement.removeEventListener( 'mousedown', mousedown ); document.addEventListener( 'mousemove', mousemove ); document.addEventListener( 'mouseup', mouseup ); } } function mousemove( event ) { if ( api.enabled ){ event.preventDefault(); state = STATE.ROTATE; getMouseProjectionOnBall( event.pageX, event.pageY, mouse ); // Get the delta between mouse positions direction.subVectors( mouse, lastPosition ); lastPosition.copy( mouse ); } } function mouseup( event ) { document.removeEventListener( 'mousemove', mousemove ); document.removeEventListener( 'mouseup', mouseup ); api.domElement.addEventListener( 'mousedown', mousedown ); if ( api.enabled ){ state = STATE.INERTIA; } } function touchstart( event ) { if ( api.enabled && projector.getIntersection( camera, event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ) === null ){ state = STATE.ROTATE; direction.multiplyScalar( 0 ); getMouseProjectionOnBall( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY, mouse ); lastPosition.copy( mouse ); api.domElement.removeEventListener( 'touchstart', touchstart ); document.addEventListener( 'touchend', touchend ); document.addEventListener( 'touchmove', touchmove ); } } function touchmove( event ) { if ( api.enabled ){ // event.preventDefault(); state = STATE.ROTATE; getMouseProjectionOnBall( event.changedTouches[ 0 ].pageX, event.changedTouches[ 0 ].pageY, mouse ); // Get the delta between mouse positions direction.subVectors( mouse, lastPosition ); lastPosition.copy( mouse ); } } function touchend( event ) { document.removeEventListener( 'touchend', touchend ); document.removeEventListener( 'touchmove', touchmove ); api.domElement.addEventListener( 'touchstart', touchstart ); if ( api.enabled ){ state = STATE.INERTIA; } } api.domElement.addEventListener( 'mousedown', mousedown ); api.domElement.addEventListener( 'touchstart', touchstart ); return api; }; }());
#!/usr/bin/env node 'use strict'; var nopt = require('nopt'); var path = require('path'); var sudoBlock = require('sudo-block'); var updateNotifier = require('update-notifier'); var pkg = require('../package.json'); var project = require('../lib'); var opts = nopt({ help: Boolean, version: Boolean, config: path, exclude: Array, 'base-url': path, baseUrl: path, // alias for --base-url transitive: Boolean, 'exclude-dev': Boolean }, { h: '--help', v: '--version', c: '--config', e: '--exclude', b: '--base-url', t: '--transitive', d: '--exclude-dev' }); if (opts['base-url']) { opts.baseUrl = opts['base-url']; } function init() { project(opts); } function help() { var out = [ 'Usage: bower-requirejs [options]', '', 'General options:', ' -h, --help # Print options and usage', ' -v, --version # Print the version number', ' -c, --config # Path to your RequireJS config file', ' -e, --exclude # Name of a dependency to be excluded from the process', ' -b, --base-url # Path which all dependencies will be relative to', ' -t, --transitive # Process transitive dependencies', ' -d, --exclude-dev # Exclude devDependencies', '' ]; return out.join('\n'); } function pre() { if (opts.version) { return console.log(pkg.version); } if (opts.help) { return console.log(help()); } init(); } if (opts['update-notifier'] !== false) { updateNotifier({pkg: pkg}).notify(); } sudoBlock(); pre();
/* * File generated with Blender 2.56 Exporter * https://github.com/mrdoob/three.js/tree/master/utils/exporters/blender/ * * vertices: 8 * faces: 6 * normals: 0 * uvs: 0 * colors: 0 * materials: 1 * edges: 0 * */ var model = { "version" : 2, "scale" : 1.000000, "materials": [ { "DbgColor" : 15658734, "DbgIndex" : 0, "DbgName" : "default", "vertexColors" : false }], "vertices": [1004.782227,2426.338867,-1758.694946,1004.782227,-2426.338623,-1758.694946,-1004.782349,-2426.338379,-1758.694946,-1004.781860,2426.339111,-1758.694946,1004.782715,2426.338379,5056.585938,1004.781494,-2426.339355,5056.585938,-1004.782593,-2426.338379,5056.585938,-1004.782227,2426.338867,5056.585938], "morphTargets": [], "normals": [], "colors": [], "uvs": [[]], "faces": [3,0,1,2,3,0,3,4,7,6,5,0,3,0,4,5,1,0,3,1,5,6,2,0,3,2,6,7,3,0,3,4,0,3,7,0], "edges" : [] }; postMessage( model ); close();
/**! * * Copyright (c) 2015-2016 Cisco Systems, Inc. See LICENSE file. */ 'use strict'; function inNode() { return typeof window === 'undefined'; } function inBrowser() { return !inNode(); } function noop() { // intentionally empty } module.exports = { /** * Wrap the desired mochaMethod with `flaky` to indicate it's a flaky test and * exclude it from the cloudapps pipeline * example: * `flaky(it)('sometimes passes and sometimes failes')` * @param {Function} mochaMethod `it` or `describe` * @returns {Function} mochaMethod or mochaMethod.skip */ flaky: function flaky(mochaMethod) { // If mochaMethod doesn't have a skip method, assume that mochaMethod is // already either a .skip or a .only if (!mochaMethod.skip) { return mochaMethod; } return process.env.SKIP_FLAKY_TESTS ? mochaMethod.skip : mochaMethod; }, inBrowser: inBrowser, inNode: inNode, /** * Wrap the desired mochaMethod with `skipInBrowser` to prevent the * corresponding test or group of tests from running in a web browser * example: * `skipInBrowser(it)('does a thing that only works in node')` * @param {Function} mochaMethod `it` or `describe` * @returns {Function} mochaMethod or mochaMethod.skip */ skipInBrowser: function skipInBrowser(mochaMethod) { // If mochaMethod doesn't have a skip method, assume that mochaMethod is // already either a .skip or a .only if (!mochaMethod.skip) { return mochaMethod; } return inBrowser() ? mochaMethod.skip : mochaMethod; }, /** * Wrap the desired mochaMethod with `skipInNode` to prevent the * corresponding test or group of tests from running in node. * example: * `skipInNode(it)('does a thing that only works in a web browser')` * @param {Function} mochaMethod `it` or `describe` * @returns {Function} mochaMethod or mochaMethod.skip */ skipInNode: function skipInNode(mochaMethod) { // If mochaMethod doesn't have a skip method, assume that mochaMethod is // already either a .skip or a .only if (!mochaMethod.skip) { return mochaMethod; } return inNode() ? mochaMethod.skip : mochaMethod; }, /** * Similar to skipInNode in that it prevents the test from running, but goes a * step further to hide it from the list of skipped tests. Should be used when * the test will never be valid in NodeJS * @param {Function} mochaMethod * @returns {Function} */ browserOnly: function browserOnly(mochaMethod) { return inBrowser() ? mochaMethod : noop; }, /** * Similar to skipInBrowser in that it prevents the test from running, but * goes a step further to hide it from the list of skipped tests. Should be * used when the test will never be valid in a Browser * @param {Function} mochaMethod * @returns {Function} */ nodeOnly: function nodeOnly(mochaMethod) { return inNode() ? mochaMethod : noop; } };
lychee.define('lychee.net.Server').tags({ platform: 'nodejs' }).requires([ 'lychee.net.Remote' ]).includes([ 'lychee.event.Emitter' ]).supports(function(lychee, global) { if (typeof process !== 'undefined') { return true; } return false; }).exports(function(lychee, global) { var http = require('http'); var crypto = require('crypto'); /* * HELPERS */ var _get_websocket_headers = function(httpheaders) { var wsheaders = { host: httpheaders.host, origin: httpheaders.origin || null, version: +httpheaders.version || 0 }; for (var prop in httpheaders) { if (prop.substr(0, 14) === 'sec-websocket-') { wsheaders[prop.substr(14)] = httpheaders[prop]; } } if (wsheaders.version) { return wsheaders; } return null; }; var _get_websocket_handshake = function(request) { var headers = _get_websocket_headers(request.headers); if (headers !== null && headers.origin !== null) { var sha1 = crypto.createHash('sha1'); sha1.update(headers.key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'); // HEAD var handshake = ''; handshake += 'HTTP/1.1 101 WebSocket Protocol Handshake\r\n'; handshake += 'Upgrade: WebSocket\r\n'; handshake += 'Connection: Upgrade\r\n'; handshake += 'Sec-WebSocket-Version: ' + headers.version + '\r\n'; handshake += 'Sec-WebSocket-Origin: ' + headers.origin + '\r\n'; handshake += 'Sec-WebSocket-Accept: ' + sha1.digest('base64') + '\r\n'; // BODY handshake += '\r\n'; return handshake; } return null; }; var _upgrade_to_websocket = function(request, socket, head) { // 1. Validate Upgrade Request var reqheaders = request.headers; if ( !( request.method === 'GET' && typeof reqheaders.upgrade !== 'undefined' && typeof reqheaders.connection !== 'undefined' && reqheaders.upgrade.toLowerCase() === 'websocket' && reqheaders.connection.toLowerCase().indexOf('upgrade') !== -1 ) ) { return false; } // 2. Handshake var handshake = _get_websocket_handshake(request); if (handshake !== null) { socket.write(handshake, 'ascii'); socket.setTimeout(0); socket.setNoDelay(true); socket.setKeepAlive(true, 0); socket.removeAllListeners('timeout'); this.connect(new lychee.net.Remote( this, socket, this.__maxFrameSize, this.__encoder, this.__decoder )); return true; } return false; }; /* * IMPLEMENTATION */ var Class = function(encoder, decoder) { encoder = encoder instanceof Function ? encoder : function(msg) { return msg; }; decoder = decoder instanceof Function ? decoder : function(msg) { return msg; }; this.__encoder = encoder; this.__decoder = decoder; this.__server = null; this.__maxFrameSize = 32768; this.__remotes = []; lychee.event.Emitter.call(this); }; Class.prototype = { listen: function(port, host) { port = typeof port === 'number' ? port : 1337; host = typeof host === 'string' ? host : null; if (lychee.debug === true) { console.log('lychee.net.Server: Listening on ' + host + ':' + port); } var that = this; try { this.__server = new http.Server(); this.__server.on('upgrade', function(request, socket, headers) { if (_upgrade_to_websocket.call(that, request, socket, headers) === false) { socket.end(); socket.destroy(); } }); this.__server.listen(port, host); } catch(e) { if (lychee.debug === true) { console.error(e); } return false; } return true; }, /* * REMOTE INTEGRATION API */ connect: function(remote) { var found = false; for (var r = 0, rl = this.__remotes.length; r < rl; r++) { if (this.__remotes[r] === remote) { found = true; break; } } if (found === false) { if (lychee.debug === true) { console.log('lychee.net.Server: Connected lychee.Remote (' + remote.id + ')'); } this.__remotes.push(remote); this.trigger('connect', [ remote ]); } }, disconnect: function(remote) { var found = false; for (var r = 0, rl = this.__remotes.length; r < rl; r++) { if (this.__remotes[r] === remote) { found = true; this.__remotes.splice(r, 1); rl--; } } if (found === true) { if (lychee.debug === true) { console.log('lychee.net.Server: Disconnected lychee.Remote (' + remote.id + ')'); } this.trigger('disconnect', [ remote ]); } } }; return Class; });
'use strict' var tape = require('tape') var createOrbit = require('../view') var lookAt = require('gl-mat4/lookAt') var modes = [ 'orbit', 'turntable', 'matrix' ] function arrayApproxEquals(a, b) { for(var i=0; i<a.length; ++i) { if(!(Math.abs(a[i] - b[i]) < 1e-4)) { return false } } return true } function matrixApproxEquals(a, b) { var x = a[15] var y = b[15] for(var i=0; i<15; ++i) { if(!(Math.abs(a[i] * y - b[i] * x) < 1e-4)) { return false } } return true } tape('orbit camera', function(t) { for(var i=0; i<100; ++i) { var center = [Math.random()-0.5, Math.random()-0.5, Math.random()-0.5] var eye = [Math.random()-0.5, Math.random()-0.5, Math.random()-0.5] var up = [Math.random()-0.5, Math.random()-0.5, Math.random()-0.5] var mat = lookAt([], eye, center, up) var smat = mat[15] modes.forEach(function(initMode) { var controller = createOrbit() controller.setMode(initMode) controller.lookAt(1, eye, center, up) modes.forEach(function(curMode) { controller.setMode(curMode) controller.recalcMatrix(10) var orbitMat = controller.computedMatrix t.ok(matrixApproxEquals(mat, orbitMat), 'compare mat: ' + mat + ' : ' + orbitMat + '(initMode=' + initMode + ',curMode=' + curMode + ')') var oeye = controller.computedEye t.ok(arrayApproxEquals(eye, oeye), 'compare eye: ' + eye + ':' + oeye) if(curMode === 'matrix') { return } var ocenter = controller.computedCenter t.ok(arrayApproxEquals(center, ocenter), 'compare center: ' + center + ':' + ocenter) var dist = 0.0 for(var j=0; j<3; ++j) { dist += Math.pow(eye[j] - center[j], 2) } dist = Math.sqrt(dist) t.ok(Math.abs(dist - Math.exp(controller.computedRadius[0])) < 1e-4, 'distance:' + controller.computedRadius + " expect " + dist) }) }) } for(var i=0; i<100; ++i) { var center = [Math.random()-0.5, Math.random()-0.5, Math.random()-0.5] var eye = [Math.random()-0.5, Math.random()-0.5, Math.random()-0.5] var up = [Math.random()-0.5, Math.random()-0.5, Math.random()-0.5] var mat = lookAt([], eye, center, up) modes.forEach(function(initMode) { var controller = createOrbit() controller.setMode(initMode) controller.setMatrix(1, mat) controller.recalcMatrix(10) modes.forEach(function(curMode) { controller.setMode(curMode) controller.recalcMatrix(10) var orbitMat = controller.computedMatrix t.ok(matrixApproxEquals(mat, orbitMat), 'compare mat: ' + mat + ' : ' + orbitMat) var oeye = controller.computedEye t.ok(arrayApproxEquals(eye, oeye), 'compare eye: ' + eye + ':' + oeye) }) }) } t.end() })
import { useDeps } from 'react-simple-di'; import { compose, withHandlers, withTracker, withRedux, composeAll } from 'react-komposer-plus'; import { browserHistory } from 'react-router' import Post from '../components/event'; const initData = ({ context, params }, onData) => { const { Meteor, toastr } = context; const eventId = params.id; Meteor.call('events.get.single', eventId, (err, event) => { if (err) { if (err.error === '404'){ toastr.error("活动没有找到,返回到原来页面"); browserHistory.push('/events'); } } else { document.title = event.title; onData(null, { event }); } }); onData(null, {}); }; const depsToProps = (context, actions) => ({ context }); export default composeAll( compose(initData), useDeps(depsToProps) )(Post);
import React, { PropTypes } from 'react' import { META, getUnhandledProps, } from '../../lib' import Image from '../../elements/Image' /** * An item can contain an image **/ function ItemImage(props) { const { size } = props const rest = getUnhandledProps(ItemImage, props) return <Image {...rest} size={size} ui={!!size} wrapped /> } ItemImage._meta = { name: 'ItemImage', parent: 'Item', type: META.TYPES.VIEW, } ItemImage.propTypes = { /** An image may appear at different sizes */ size: PropTypes.oneOf(Image._meta.props.size), } export default ItemImage
const should = require('chai').should(); const expect = require('chai').expect; const assert = require('chai').assert; const {exit} = require('../helpers/utils'); var db; describe('Update(): values:', () => { before(() => { ({db} = require('../../lib')); }); beforeEach(function* (){ const payload = { account: { friends: ['lrn'], name: 'jay' }, newsletter: true, age: 1 }; yield db.users.insert(payload); }); it('should error when given a field that does not exist in schema', function* () { var payload = { $set: { doesnotexist: true } }; try { yield db.users.update({}, payload); exit(); } catch (e) { e.should.be.ok; } }); it('should error given an update w/o an operator that\'s missing required fields', function*() { var payload = { newsletter: false }; try { yield db.users.update({}, payload); exit(); } catch (e) { e.should.be.ok; } }); it('should preform an update w/o an operator that contains required fields', function*() { var payload = { account: { name: 'jay' }, newsletter: false }; yield db.users.update({}, payload); var result = yield db.users.findOne({}); result.account.should.eql({ name: 'hey jay', friends: [] }); result.newsletter.should.eql(false); }); it('should error when given fields that do not exist in schema during an $addToSet w/ $each update', function*() { var payload = { $addToSet: { 'account.doesnotexist': { $each: ['jay', 'lrn'] }, 'account.friends': { $each: ['jay', 'lou'] } } }; try { yield db.users.update({}, payload); exit(); } catch (e) { e.errors.length.should.eql(1); } }); it('should complete an $addToSet w/ $each update', function*() { var payload = { $addToSet: { 'account.friends': { $each: ['jay', 'lou'] } } }; yield db.users.update({}, payload); var result = yield db.users.findOne({}); result.newsletter.should.eql(true); result.age.should.eql(1); result.account.name.should.eql('hey jay'); result.account.friends.should.eql(['lrn', 'jay', 'lou']); }); describe('$inc', function() { it('should error (mongodb error) given an invalid type', function*() { var payload = { '$inc': { age: '1' } }; try { yield db.users.update({}, payload); exit(); } catch (e) { e.should.be.ok; } }); it('should increment the age field', function*() { var payload = { '$inc': { age: -1 } }; yield db.users.update({}, payload); var result = yield db.users.findOne({}); result.age.should.eql(0); }); }); describe('$mul', function() { it('should double the age field', function*() { var payload = { '$mul': { age: 2 } }; yield db.users.update({}, payload); var result = yield db.users.findOne({}); result.age.should.eql(2); }); }); describe('$min', function() { it('should update the age field given a value less than the original', function*() { var payload = { '$min': { age: -1 } }; yield db.users.update({}, payload); var result = yield db.users.findOne({}); result.age.should.eql(-1); }); }); describe('$max', function() { it('should update the age field given a value greater than the original', function*() { var payload = { '$max': { age: 2 } }; yield db.users.update({}, payload); var result = yield db.users.findOne({}); result.age.should.eql(2); }); }); describe('$set', function() { it ('should update fields when executed from cache', function* (){ yield db.users.update({'account.name': 'hey jay'}, { $inc: { age: 1, }, '$set': { 'account.name': 'sam' } }); yield db.users.update({'account.name': 'hey sam'}, { $inc: { age: 10, }, '$set': { 'account.name': 'gus' } }); var result = yield db.users.findOne({}); delete result._id; result.should.eql({ account: {friends: ['lrn'], name: 'hey gus'}, newsletter: true, age: 12, }); }); it('should error given an invalid type', function*() { try { yield db.users.update({}, { '$set': { 'account.name': 1 } }); exit(); } catch (e) { e.errors.length.should.eql(1); e.errors[0].property.should.eql('type'); } }); it('should error when violating the minLength constraint', function*() { try { yield db.users.update({}, { '$set': { 'account.name': '' } }); exit(); } catch (e) { e.errors[0].property.should.eql('minLength'); } }); it('should error when violating the maxLength constraint', function*() { try { yield db.users.update({}, { '$set': { 'account.name': 'abcdefghijklmnopqrstuvqxyz' } }); exit(); } catch (e) { e.errors[0].property.should.eql('maxLength'); } }); it('should not update a field that is not in the payload w/ the schemas default value', function*() { yield db.users.update({}, { '$set': { 'account.name': 'lou' } }); var result = yield db.users.findOne({}); result.account.name.should.eql('hey lou'); result.account.friends.should.eql(['lrn']); }); it('should update a field w/ null if notNull is false', function*() { yield db.users.update({}, { '$set': { age: null } }) var result = yield db.users.findOne({}); expect(result.age).to.eql(null); }); it('should update a nested field and not add extra fields', function*() { yield db.users.update({}, { '$set': { 'account.name': 'gus' } }).catch(console.log); var result = yield db.users.findOne({}); result.account.name.should.eql('hey gus'); result.account.friends.should.eql(['lrn']); result.newsletter.should.eql(true); result.age.should.eql(1); Object.keys(result).length.should.eql(4); }); }); describe('$addToSet', function() { it('should add an item to the friends array', function*() { yield db.users.update({}, { '$addToSet': { 'account.friends': 'gus' } }); var result = yield db.users.findOne({}); result.account.friends.should.eql(['lrn', 'gus']); }); it('should add multiple items using $each to an array', function*() { var payload = { '$addToSet': { 'account.friends': { '$each': ['lou', 'gus'] } } }; yield db.users.update({}, payload); var result = yield db.users.findOne({}); result.account.friends.should.eql(['lrn', 'lou', 'gus']); }); }); describe('$push', function() { it('should add an item to the friends array', function*() { yield db.users.update({}, { '$push': { 'account.friends': 'gus' } }); var result = yield db.users.findOne({}); result.account.friends.should.eql(['lrn', 'gus']); }); it('should add multiple items using $each to an array and apply the $slice operator', function*() { var payload = { '$push': { 'account.friends': { '$each': ['lou', 'gus', 'sam'], '$slice': 2 } } }; yield db.users.update({}, payload); var result = yield db.users.findOne({}); result.account.friends.should.eql(['lrn', 'lou']); }); }); });
/* YUI 3.8.0pr2 (build 154) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and * the core utilities for the library. * @module yui * @main yui * @submodule yui-base */ if (typeof YUI != 'undefined') { YUI._YUI = YUI; } /** The YUI global namespace object. If YUI is already defined, the existing YUI object will not be overwritten so that defined namespaces are preserved. It is the constructor for the object the end user interacts with. As indicated below, each instance has full custom event support, but only if the event system is available. This is a self-instantiable factory function. You can invoke it directly like this: YUI().use('*', function(Y) { // ready }); But it also works like this: var Y = YUI(); Configuring the YUI object: YUI({ debug: true, combine: false }).use('node', function(Y) { //Node is ready to use }); See the API docs for the <a href="config.html">Config</a> class for the complete list of supported configuration properties accepted by the YUI constuctor. @class YUI @constructor @global @uses EventTarget @param [o]* {Object} 0..n optional configuration objects. these values are store in Y.config. See <a href="config.html">Config</a> for the list of supported properties. */ /*global YUI*/ /*global YUI_config*/ var YUI = function() { var i = 0, Y = this, args = arguments, l = args.length, instanceOf = function(o, type) { return (o && o.hasOwnProperty && (o instanceof type)); }, gconf = (typeof YUI_config !== 'undefined') && YUI_config; if (!(instanceOf(Y, YUI))) { Y = new YUI(); } else { // set up the core environment Y._init(); /** YUI.GlobalConfig is a master configuration that might span multiple contexts in a non-browser environment. It is applied first to all instances in all contexts. @property GlobalConfig @type {Object} @global @static @example YUI.GlobalConfig = { filter: 'debug' }; YUI().use('node', function(Y) { //debug files used here }); YUI({ filter: 'min' }).use('node', function(Y) { //min files used here }); */ if (YUI.GlobalConfig) { Y.applyConfig(YUI.GlobalConfig); } /** YUI_config is a page-level config. It is applied to all instances created on the page. This is applied after YUI.GlobalConfig, and before the instance level configuration objects. @global @property YUI_config @type {Object} @example //Single global var to include before YUI seed file YUI_config = { filter: 'debug' }; YUI().use('node', function(Y) { //debug files used here }); YUI({ filter: 'min' }).use('node', function(Y) { //min files used here }); */ if (gconf) { Y.applyConfig(gconf); } // bind the specified additional modules for this instance if (!l) { Y._setup(); } } if (l) { // Each instance can accept one or more configuration objects. // These are applied after YUI.GlobalConfig and YUI_Config, // overriding values set in those config files if there is a ' // matching property. for (; i < l; i++) { Y.applyConfig(args[i]); } Y._setup(); } Y.instanceOf = instanceOf; return Y; }; (function() { var proto, prop, VERSION = '3.8.0pr2', PERIOD = '.', BASE = 'http://yui.yahooapis.com/', /* These CSS class names can't be generated by getClassName since it is not available at the time they are being used. */ DOC_LABEL = 'yui3-js-enabled', CSS_STAMP_EL = 'yui3-css-stamp', NOOP = function() {}, SLICE = Array.prototype.slice, APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo 'io.xdrResponse': 1, // can call. this should 'SWF.eventHandler': 1 }, // be done at build time hasWin = (typeof window != 'undefined'), win = (hasWin) ? window : null, doc = (hasWin) ? win.document : null, docEl = doc && doc.documentElement, docClass = docEl && docEl.className, instances = {}, time = new Date().getTime(), add = function(el, type, fn, capture) { if (el && el.addEventListener) { el.addEventListener(type, fn, capture); } else if (el && el.attachEvent) { el.attachEvent('on' + type, fn); } }, remove = function(el, type, fn, capture) { if (el && el.removeEventListener) { // this can throw an uncaught exception in FF try { el.removeEventListener(type, fn, capture); } catch (ex) {} } else if (el && el.detachEvent) { el.detachEvent('on' + type, fn); } }, handleLoad = function() { YUI.Env.windowLoaded = true; YUI.Env.DOMReady = true; if (hasWin) { remove(window, 'load', handleLoad); } }, getLoader = function(Y, o) { var loader = Y.Env._loader, lCore = [ 'loader-base' ], G_ENV = YUI.Env, mods = G_ENV.mods; if (loader) { //loader._config(Y.config); loader.ignoreRegistered = false; loader.onEnd = null; loader.data = null; loader.required = []; loader.loadType = null; } else { loader = new Y.Loader(Y.config); Y.Env._loader = loader; } if (mods && mods.loader) { lCore = [].concat(lCore, YUI.Env.loaderExtras); } YUI.Env.core = Y.Array.dedupe([].concat(YUI.Env.core, lCore)); return loader; }, clobber = function(r, s) { for (var i in s) { if (s.hasOwnProperty(i)) { r[i] = s[i]; } } }, ALREADY_DONE = { success: true }; // Stamp the documentElement (HTML) with a class of "yui-loaded" to // enable styles that need to key off of JS being enabled. if (docEl && docClass.indexOf(DOC_LABEL) == -1) { if (docClass) { docClass += ' '; } docClass += DOC_LABEL; docEl.className = docClass; } if (VERSION.indexOf('@') > -1) { VERSION = '3.5.0'; // dev time hack for cdn test } proto = { /** * Applies a new configuration object to the YUI instance config. * This will merge new group/module definitions, and will also * update the loader cache if necessary. Updating Y.config directly * will not update the cache. * @method applyConfig * @param {Object} o the configuration object. * @since 3.2.0 */ applyConfig: function(o) { o = o || NOOP; var attr, name, // detail, config = this.config, mods = config.modules, groups = config.groups, aliases = config.aliases, loader = this.Env._loader; for (name in o) { if (o.hasOwnProperty(name)) { attr = o[name]; if (mods && name == 'modules') { clobber(mods, attr); } else if (aliases && name == 'aliases') { clobber(aliases, attr); } else if (groups && name == 'groups') { clobber(groups, attr); } else if (name == 'win') { config[name] = (attr && attr.contentWindow) || attr; config.doc = config[name] ? config[name].document : null; } else if (name == '_yuid') { // preserve the guid } else { config[name] = attr; } } } if (loader) { loader._config(o); } }, /** * Old way to apply a config to the instance (calls `applyConfig` under the hood) * @private * @method _config * @param {Object} o The config to apply */ _config: function(o) { this.applyConfig(o); }, /** * Initialize this YUI instance * @private * @method _init */ _init: function() { var filter, el, Y = this, G_ENV = YUI.Env, Env = Y.Env, prop; /** * The version number of the YUI instance. * @property version * @type string */ Y.version = VERSION; if (!Env) { Y.Env = { core: ['get', 'features', 'intl-base', 'yui-log', 'yui-later'], loaderExtras: ['loader-rollup', 'loader-yui3'], mods: {}, // flat module map versions: {}, // version module map base: BASE, cdn: BASE + VERSION + '/build/', // bootstrapped: false, _idx: 0, _used: {}, _attached: {}, _missed: [], _yidx: 0, _uidx: 0, _guidp: 'y', _loaded: {}, // serviced: {}, // Regex in English: // I'll start at the \b(simpleyui). // 1. Look in the test string for "simpleyui" or "yui" or // "yui-base" or "yui-davglass" or "yui-foobar" that comes after a word break. That is, it // can't match "foyui" or "i_heart_simpleyui". This can be anywhere in the string. // 2. After #1 must come a forward slash followed by the string matched in #1, so // "yui-base/yui-base" or "simpleyui/simpleyui" or "yui-pants/yui-pants". // 3. The second occurence of the #1 token can optionally be followed by "-debug" or "-min", // so "yui/yui-min", "yui/yui-debug", "yui-base/yui-base-debug". NOT "yui/yui-tshirt". // 4. This is followed by ".js", so "yui/yui.js", "simpleyui/simpleyui-min.js" // 0. Going back to the beginning, now. If all that stuff in 1-4 comes after a "?" in the string, // then capture the junk between the LAST "&" and the string in 1-4. So // "blah?foo/yui/yui.js" will capture "foo/" and "blah?some/thing.js&3.3.0/build/yui-davglass/yui-davglass.js" // will capture "3.3.0/build/" // // Regex Exploded: // (?:\? Find a ? // (?:[^&]*&) followed by 0..n characters followed by an & // * in fact, find as many sets of characters followed by a & as you can // ([^&]*) capture the stuff after the last & in \1 // )? but it's ok if all this ?junk&more_junk stuff isn't even there // \b(simpleyui| after a word break find either the string "simpleyui" or // yui(?:-\w+)? the string "yui" optionally followed by a -, then more characters // ) and store the simpleyui or yui-* string in \2 // \/\2 then comes a / followed by the simpleyui or yui-* string in \2 // (?:-(min|debug))? optionally followed by "-min" or "-debug" // .js and ending in ".js" _BASE_RE: /(?:\?(?:[^&]*&)*([^&]*))?\b(simpleyui|yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/, parseBasePath: function(src, pattern) { var match = src.match(pattern), path, filter; if (match) { path = RegExp.leftContext || src.slice(0, src.indexOf(match[0])); // this is to set up the path to the loader. The file // filter for loader should match the yui include. filter = match[3]; // extract correct path for mixed combo urls // http://yuilibrary.com/projects/yui3/ticket/2528423 if (match[1]) { path += '?' + match[1]; } path = { filter: filter, path: path }; } return path; }, getBase: G_ENV && G_ENV.getBase || function(pattern) { var nodes = (doc && doc.getElementsByTagName('script')) || [], path = Env.cdn, parsed, i, len, src; for (i = 0, len = nodes.length; i < len; ++i) { src = nodes[i].src; if (src) { parsed = Y.Env.parseBasePath(src, pattern); if (parsed) { filter = parsed.filter; path = parsed.path; break; } } } // use CDN default return path; } }; Env = Y.Env; Env._loaded[VERSION] = {}; if (G_ENV && Y !== YUI) { Env._yidx = ++G_ENV._yidx; Env._guidp = ('yui_' + VERSION + '_' + Env._yidx + '_' + time).replace(/[^a-z0-9_]+/g, '_'); } else if (YUI._YUI) { G_ENV = YUI._YUI.Env; Env._yidx += G_ENV._yidx; Env._uidx += G_ENV._uidx; for (prop in G_ENV) { if (!(prop in Env)) { Env[prop] = G_ENV[prop]; } } delete YUI._YUI; } Y.id = Y.stamp(Y); instances[Y.id] = Y; } Y.constructor = YUI; // configuration defaults Y.config = Y.config || { bootstrap: true, cacheUse: true, debug: true, doc: doc, fetchCSS: true, throwFail: true, useBrowserConsole: true, useNativeES5: true, win: win, global: Function('return this')() }; //Register the CSS stamp element if (doc && !doc.getElementById(CSS_STAMP_EL)) { el = doc.createElement('div'); el.innerHTML = '<div id="' + CSS_STAMP_EL + '" style="position: absolute !important; visibility: hidden !important"></div>'; YUI.Env.cssStampEl = el.firstChild; if (doc.body) { doc.body.appendChild(YUI.Env.cssStampEl); } else { docEl.insertBefore(YUI.Env.cssStampEl, docEl.firstChild); } } Y.config.lang = Y.config.lang || 'en-US'; Y.config.base = YUI.config.base || Y.Env.getBase(Y.Env._BASE_RE); if (!filter || (!('mindebug').indexOf(filter))) { filter = 'min'; } filter = (filter) ? '-' + filter : filter; Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + filter + '.js'; }, /** * Finishes the instance setup. Attaches whatever modules were defined * when the yui modules was registered. * @method _setup * @private */ _setup: function(o) { var i, Y = this, core = [], mods = YUI.Env.mods, extras = Y.config.core || [].concat(YUI.Env.core); //Clone it.. for (i = 0; i < extras.length; i++) { if (mods[extras[i]]) { core.push(extras[i]); } } Y._attach(['yui-base']); Y._attach(core); if (Y.Loader) { getLoader(Y); } }, /** * Executes a method on a YUI instance with * the specified id if the specified method is whitelisted. * @method applyTo * @param id {String} the YUI instance id. * @param method {String} the name of the method to exectute. * Ex: 'Object.keys'. * @param args {Array} the arguments to apply to the method. * @return {Object} the return value from the applied method or null. */ applyTo: function(id, method, args) { if (!(method in APPLY_TO_AUTH)) { this.log(method + ': applyTo not allowed', 'warn', 'yui'); return null; } var instance = instances[id], nest, m, i; if (instance) { nest = method.split('.'); m = instance; for (i = 0; i < nest.length; i = i + 1) { m = m[nest[i]]; if (!m) { this.log('applyTo not found: ' + method, 'warn', 'yui'); } } return m && m.apply(instance, args); } return null; }, /** Registers a module with the YUI global. The easiest way to create a first-class YUI module is to use the YUI component build tool <a href="http://yui.github.com/shifter/">Shifter</a>. The build system will produce the `YUI.add` wrapper for your module, along with any configuration info required for the module. @method add @param name {String} module name. @param fn {Function} entry point into the module that is used to bind module to the YUI instance. @param {YUI} fn.Y The YUI instance this module is executed in. @param {String} fn.name The name of the module @param version {String} version string. @param details {Object} optional config data: @param details.requires {Array} features that must be present before this module can be attached. @param details.optional {Array} optional features that should be present if loadOptional is defined. Note: modules are not often loaded this way in YUI 3, but this field is still useful to inform the user that certain features in the component will require additional dependencies. @param details.use {Array} features that are included within this module which need to be attached automatically when this module is attached. This supports the YUI 3 rollup system -- a module with submodules defined will need to have the submodules listed in the 'use' config. The YUI component build tool does this for you. @return {YUI} the YUI instance. @example YUI.add('davglass', function(Y, name) { Y.davglass = function() { alert('Dav was here!'); }; }, '3.4.0', { requires: ['yui-base', 'harley-davidson', 'mt-dew'] }); */ add: function(name, fn, version, details) { details = details || {}; var env = YUI.Env, mod = { name: name, fn: fn, version: version, details: details }, //Instance hash so we don't apply it to the same instance twice applied = {}, loader, inst, i, versions = env.versions; env.mods[name] = mod; versions[version] = versions[version] || {}; versions[version][name] = mod; for (i in instances) { if (instances.hasOwnProperty(i)) { inst = instances[i]; if (!applied[inst.id]) { applied[inst.id] = true; loader = inst.Env._loader; if (loader) { if (!loader.moduleInfo[name] || loader.moduleInfo[name].temp) { loader.addModule(details, name); } } } } } return this; }, /** * Executes the function associated with each required * module, binding the module to the YUI instance. * @param {Array} r The array of modules to attach * @param {Boolean} [moot=false] Don't throw a warning if the module is not attached * @method _attach * @private */ _attach: function(r, moot) { var i, name, mod, details, req, use, after, mods = YUI.Env.mods, aliases = YUI.Env.aliases, Y = this, j, cache = YUI.Env._renderedMods, loader = Y.Env._loader, done = Y.Env._attached, len = r.length, loader, def, go, c = []; //Check for conditional modules (in a second+ instance) and add their requirements //TODO I hate this entire method, it needs to be fixed ASAP (3.5.0) ^davglass for (i = 0; i < len; i++) { name = r[i]; mod = mods[name]; c.push(name); if (loader && loader.conditions[name]) { for (j in loader.conditions[name]) { if (loader.conditions[name].hasOwnProperty(j)) { def = loader.conditions[name][j]; go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y))); if (go) { c.push(def.name); } } } } } r = c; len = r.length; for (i = 0; i < len; i++) { if (!done[r[i]]) { name = r[i]; mod = mods[name]; if (aliases && aliases[name] && !mod) { Y._attach(aliases[name]); continue; } if (!mod) { if (loader && loader.moduleInfo[name]) { mod = loader.moduleInfo[name]; moot = true; } //if (!loader || !loader.moduleInfo[name]) { //if ((!loader || !loader.moduleInfo[name]) && !moot) { if (!moot && name) { if ((name.indexOf('skin-') === -1) && (name.indexOf('css') === -1)) { Y.Env._missed.push(name); Y.Env._missed = Y.Array.dedupe(Y.Env._missed); Y.message('NOT loaded: ' + name, 'warn', 'yui'); } } } else { done[name] = true; //Don't like this, but in case a mod was asked for once, then we fetch it //We need to remove it from the missed list ^davglass for (j = 0; j < Y.Env._missed.length; j++) { if (Y.Env._missed[j] === name) { Y.message('Found: ' + name + ' (was reported as missing earlier)', 'warn', 'yui'); Y.Env._missed.splice(j, 1); } } /* If it's a temp module, we need to redo it's requirements if it's already loaded since it may have been loaded by another instance and it's dependencies might have been redefined inside the fetched file. */ if (loader && cache && cache[name] && cache[name].temp) { loader.getRequires(cache[name]); req = []; for (j in loader.moduleInfo[name].expanded_map) { if (loader.moduleInfo[name].expanded_map.hasOwnProperty(j)) { req.push(j); } } Y._attach(req); } details = mod.details; req = details.requires; use = details.use; after = details.after; //Force Intl load if there is a language (Loader logic) @todo fix this shit if (details.lang) { req = req || []; req.unshift('intl'); } if (req) { for (j = 0; j < req.length; j++) { if (!done[req[j]]) { if (!Y._attach(req)) { return false; } break; } } } if (after) { for (j = 0; j < after.length; j++) { if (!done[after[j]]) { if (!Y._attach(after, true)) { return false; } break; } } } if (mod.fn) { if (Y.config.throwFail) { mod.fn(Y, name); } else { try { mod.fn(Y, name); } catch (e) { Y.error('Attach error: ' + name, e, name); return false; } } } if (use) { for (j = 0; j < use.length; j++) { if (!done[use[j]]) { if (!Y._attach(use)) { return false; } break; } } } } } } return true; }, /** * Delays the `use` callback until another event has taken place. Like: window.onload, domready, contentready, available. * @private * @method _delayCallback * @param {Callback} cb The original `use` callback * @param {String|Object} until Either an event (load, domready) or an Object containing event/args keys for contentready/available */ _delayCallback: function(cb, until) { var Y = this, mod = ['event-base']; until = (Y.Lang.isObject(until) ? until : { event: until }); if (until.event === 'load') { mod.push('event-synthetic'); } return function() { var args = arguments; Y._use(mod, function() { Y.on(until.event, function() { args[1].delayUntil = until.event; cb.apply(Y, args); }, until.args); }); }; }, /** * Attaches one or more modules to the YUI instance. When this * is executed, the requirements are analyzed, and one of * several things can happen: * * * All requirements are available on the page -- The modules * are attached to the instance. If supplied, the use callback * is executed synchronously. * * * Modules are missing, the Get utility is not available OR * the 'bootstrap' config is false -- A warning is issued about * the missing modules and all available modules are attached. * * * Modules are missing, the Loader is not available but the Get * utility is and boostrap is not false -- The loader is bootstrapped * before doing the following.... * * * Modules are missing and the Loader is available -- The loader * expands the dependency tree and fetches missing modules. When * the loader is finshed the callback supplied to use is executed * asynchronously. * * @method use * @param modules* {String|Array} 1-n modules to bind (uses arguments array). * @param [callback] {Function} callback function executed when * the instance has the required functionality. If included, it * must be the last parameter. * @param callback.Y {YUI} The `YUI` instance created for this sandbox * @param callback.status {Object} Object containing `success`, `msg` and `data` properties * * @example * // loads and attaches dd and its dependencies * YUI().use('dd', function(Y) {}); * * // loads and attaches dd and node as well as all of their dependencies (since 3.4.0) * YUI().use(['dd', 'node'], function(Y) {}); * * // attaches all modules that are available on the page * YUI().use('*', function(Y) {}); * * // intrinsic YUI gallery support (since 3.1.0) * YUI().use('gallery-yql', function(Y) {}); * * // intrinsic YUI 2in3 support (since 3.1.0) * YUI().use('yui2-datatable', function(Y) {}); * * @return {YUI} the YUI instance. */ use: function() { var args = SLICE.call(arguments, 0), callback = args[args.length - 1], Y = this, i = 0, a = [], name, Env = Y.Env, provisioned = true; // The last argument supplied to use can be a load complete callback if (Y.Lang.isFunction(callback)) { args.pop(); if (Y.config.delayUntil) { callback = Y._delayCallback(callback, Y.config.delayUntil); } } else { callback = null; } if (Y.Lang.isArray(args[0])) { args = args[0]; } if (Y.config.cacheUse) { while ((name = args[i++])) { if (!Env._attached[name]) { provisioned = false; break; } } if (provisioned) { if (args.length) { } Y._notify(callback, ALREADY_DONE, args); return Y; } } if (Y._loading) { Y._useQueue = Y._useQueue || new Y.Queue(); Y._useQueue.add([args, callback]); } else { Y._use(args, function(Y, response) { Y._notify(callback, response, args); }); } return Y; }, /** * Notify handler from Loader for attachment/load errors * @method _notify * @param callback {Function} The callback to pass to the `Y.config.loadErrorFn` * @param response {Object} The response returned from Loader * @param args {Array} The aruments passed from Loader * @private */ _notify: function(callback, response, args) { if (!response.success && this.config.loadErrorFn) { this.config.loadErrorFn.call(this, this, callback, response, args); } else if (callback) { if (this.Env._missed && this.Env._missed.length) { response.msg = 'Missing modules: ' + this.Env._missed.join(); response.success = false; } if (this.config.throwFail) { callback(this, response); } else { try { callback(this, response); } catch (e) { this.error('use callback error', e, args); } } } }, /** * This private method is called from the `use` method queue. To ensure that only one set of loading * logic is performed at a time. * @method _use * @private * @param args* {String} 1-n modules to bind (uses arguments array). * @param *callback {Function} callback function executed when * the instance has the required functionality. If included, it * must be the last parameter. */ _use: function(args, callback) { if (!this.Array) { this._attach(['yui-base']); } var len, loader, handleBoot, handleRLS, Y = this, G_ENV = YUI.Env, mods = G_ENV.mods, Env = Y.Env, used = Env._used, aliases = G_ENV.aliases, queue = G_ENV._loaderQueue, firstArg = args[0], YArray = Y.Array, config = Y.config, boot = config.bootstrap, missing = [], i, r = [], ret = true, fetchCSS = config.fetchCSS, process = function(names, skip) { var i = 0, a = [], name, len, m, req, use; if (!names.length) { return; } if (aliases) { len = names.length; for (i = 0; i < len; i++) { if (aliases[names[i]] && !mods[names[i]]) { a = [].concat(a, aliases[names[i]]); } else { a.push(names[i]); } } names = a; } len = names.length; for (i = 0; i < len; i++) { name = names[i]; if (!skip) { r.push(name); } // only attach a module once if (used[name]) { continue; } m = mods[name]; req = null; use = null; if (m) { used[name] = true; req = m.details.requires; use = m.details.use; } else { // CSS files don't register themselves, see if it has // been loaded if (!G_ENV._loaded[VERSION][name]) { missing.push(name); } else { used[name] = true; // probably css } } // make sure requirements are attached if (req && req.length) { process(req); } // make sure we grab the submodule dependencies too if (use && use.length) { process(use, 1); } } }, handleLoader = function(fromLoader) { var response = fromLoader || { success: true, msg: 'not dynamic' }, redo, origMissing, ret = true, data = response.data; Y._loading = false; if (data) { origMissing = missing; missing = []; r = []; process(data); redo = missing.length; if (redo) { if ([].concat(missing).sort().join() == origMissing.sort().join()) { redo = false; } } } if (redo && data) { Y._loading = true; Y._use(missing, function() { if (Y._attach(data)) { Y._notify(callback, response, data); } }); } else { if (data) { ret = Y._attach(data); } if (ret) { Y._notify(callback, response, args); } } if (Y._useQueue && Y._useQueue.size() && !Y._loading) { Y._use.apply(Y, Y._useQueue.next()); } }; // YUI().use('*'); // bind everything available if (firstArg === '*') { args = []; for (i in mods) { if (mods.hasOwnProperty(i)) { args.push(i); } } ret = Y._attach(args); if (ret) { handleLoader(); } return Y; } if ((mods.loader || mods['loader-base']) && !Y.Loader) { Y._attach(['loader' + ((!mods.loader) ? '-base' : '')]); } // use loader to expand dependencies and sort the // requirements if it is available. if (boot && Y.Loader && args.length) { loader = getLoader(Y); loader.require(args); loader.ignoreRegistered = true; loader._boot = true; loader.calculate(null, (fetchCSS) ? null : 'js'); args = loader.sorted; loader._boot = false; } process(args); len = missing.length; if (len) { missing = YArray.dedupe(missing); len = missing.length; } // dynamic load if (boot && len && Y.Loader) { Y._loading = true; loader = getLoader(Y); loader.onEnd = handleLoader; loader.context = Y; loader.data = args; loader.ignoreRegistered = false; loader.require(missing); loader.insert(null, (fetchCSS) ? null : 'js'); } else if (boot && len && Y.Get && !Env.bootstrapped) { Y._loading = true; handleBoot = function() { Y._loading = false; queue.running = false; Env.bootstrapped = true; G_ENV._bootstrapping = false; if (Y._attach(['loader'])) { Y._use(args, callback); } }; if (G_ENV._bootstrapping) { queue.add(handleBoot); } else { G_ENV._bootstrapping = true; Y.Get.script(config.base + config.loaderPath, { onEnd: handleBoot }); } } else { ret = Y._attach(args); if (ret) { handleLoader(); } } return Y; }, /** Adds a namespace object onto the YUI global if called statically. // creates YUI.your.namespace.here as nested objects YUI.namespace("your.namespace.here"); If called as a method on a YUI <em>instance</em>, it creates the namespace on the instance. // creates Y.property.package Y.namespace("property.package"); Dots in the input string cause `namespace` to create nested objects for each token. If any part of the requested namespace already exists, the current object will be left in place. This allows multiple calls to `namespace` to preserve existing namespaced properties. If the first token in the namespace string is "YAHOO", the token is discarded. Be careful with namespace tokens. Reserved words may work in some browsers and not others. For instance, the following will fail in some browsers because the supported version of JavaScript reserves the word "long": Y.namespace("really.long.nested.namespace"); <em>Note: If you pass multiple arguments to create multiple namespaces, only the last one created is returned from this function.</em> @method namespace @param {String} namespace* namespaces to create. @return {Object} A reference to the last namespace object created. **/ namespace: function() { var a = arguments, o, i = 0, j, d, arg; for (; i < a.length; i++) { o = this; //Reset base object per argument or it will get reused from the last arg = a[i]; if (arg.indexOf(PERIOD) > -1) { //Skip this if no "." is present d = arg.split(PERIOD); for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } } else { o[arg] = o[arg] || {}; o = o[arg]; //Reset base object to the new object so it's returned } } return o; }, // this is replaced if the log module is included log: NOOP, message: NOOP, // this is replaced if the dump module is included dump: function (o) { return ''+o; }, /** * Report an error. The reporting mechanism is controlled by * the `throwFail` configuration attribute. If throwFail is * not specified, the message is written to the Logger, otherwise * a JS error is thrown. If an `errorFn` is specified in the config * it must return `true` to keep the error from being thrown. * @method error * @param msg {String} the error message. * @param e {Error|String} Optional JS error that was caught, or an error string. * @param src Optional additional info (passed to `Y.config.errorFn` and `Y.message`) * and `throwFail` is specified, this error will be re-thrown. * @return {YUI} this YUI instance. */ error: function(msg, e, src) { //TODO Add check for window.onerror here var Y = this, ret; if (Y.config.errorFn) { ret = Y.config.errorFn.apply(Y, arguments); } if (!ret) { throw (e || new Error(msg)); } else { Y.message(msg, 'error', ''+src); // don't scrub this one } return Y; }, /** * Generate an id that is unique among all YUI instances * @method guid * @param pre {String} optional guid prefix. * @return {String} the guid. */ guid: function(pre) { var id = this.Env._guidp + '_' + (++this.Env._uidx); return (pre) ? (pre + id) : id; }, /** * Returns a `guid` associated with an object. If the object * does not have one, a new one is created unless `readOnly` * is specified. * @method stamp * @param o {Object} The object to stamp. * @param readOnly {Boolean} if `true`, a valid guid will only * be returned if the object has one assigned to it. * @return {String} The object's guid or null. */ stamp: function(o, readOnly) { var uid; if (!o) { return o; } // IE generates its own unique ID for dom nodes // The uniqueID property of a document node returns a new ID if (o.uniqueID && o.nodeType && o.nodeType !== 9) { uid = o.uniqueID; } else { uid = (typeof o === 'string') ? o : o._yuid; } if (!uid) { uid = this.guid(); if (!readOnly) { try { o._yuid = uid; } catch (e) { uid = null; } } } return uid; }, /** * Destroys the YUI instance * @method destroy * @since 3.3.0 */ destroy: function() { var Y = this; if (Y.Event) { Y.Event._unload(); } delete instances[Y.id]; delete Y.Env; delete Y.config; } /** * instanceof check for objects that works around * memory leak in IE when the item tested is * window/document * @method instanceOf * @param o {Object} The object to check. * @param type {Object} The class to check against. * @since 3.3.0 */ }; YUI.prototype = proto; // inheritance utilities are not available yet for (prop in proto) { if (proto.hasOwnProperty(prop)) { YUI[prop] = proto[prop]; } } /** Static method on the Global YUI object to apply a config to all YUI instances. It's main use case is "mashups" where several third party scripts are trying to write to a global YUI config at the same time. This way they can all call `YUI.applyConfig({})` instead of overwriting other scripts configs. @static @since 3.5.0 @method applyConfig @param {Object} o the configuration object. @example YUI.applyConfig({ modules: { davglass: { fullpath: './davglass.js' } } }); YUI.applyConfig({ modules: { foo: { fullpath: './foo.js' } } }); YUI().use('davglass', function(Y) { //Module davglass will be available here.. }); */ YUI.applyConfig = function(o) { if (!o) { return; } //If there is a GlobalConfig, apply it first to set the defaults if (YUI.GlobalConfig) { this.prototype.applyConfig.call(this, YUI.GlobalConfig); } //Apply this config to it this.prototype.applyConfig.call(this, o); //Reset GlobalConfig to the combined config YUI.GlobalConfig = this.config; }; // set up the environment YUI._init(); if (hasWin) { // add a window load event at load time so we can capture // the case where it fires before dynamic loading is // complete. add(window, 'load', handleLoad); } else { handleLoad(); } YUI.Env.add = add; YUI.Env.remove = remove; /*global exports*/ // Support the CommonJS method for exporting our single global if (typeof exports == 'object') { exports.YUI = YUI; } }()); /** * The config object contains all of the configuration options for * the `YUI` instance. This object is supplied by the implementer * when instantiating a `YUI` instance. Some properties have default * values if they are not supplied by the implementer. This should * not be updated directly because some values are cached. Use * `applyConfig()` to update the config object on a YUI instance that * has already been configured. * * @class config * @static */ /** * Allows the YUI seed file to fetch the loader component and library * metadata to dynamically load additional dependencies. * * @property bootstrap * @type boolean * @default true */ /** * Turns on writing Ylog messages to the browser console. * * @property debug * @type boolean * @default true */ /** * Log to the browser console if debug is on and the browser has a * supported console. * * @property useBrowserConsole * @type boolean * @default true */ /** * A hash of log sources that should be logged. If specified, only * log messages from these sources will be logged. * * @property logInclude * @type object */ /** * A hash of log sources that should be not be logged. If specified, * all sources are logged if not on this list. * * @property logExclude * @type object */ /** * Set to true if the yui seed file was dynamically loaded in * order to bootstrap components relying on the window load event * and the `domready` custom event. * * @property injected * @type boolean * @default false */ /** * If `throwFail` is set, `Y.error` will generate or re-throw a JS Error. * Otherwise the failure is logged. * * @property throwFail * @type boolean * @default true */ /** * The global object. In Node.js it's an object called "global". In the * browser is the current window object. * * @property global * @type Object * @default the global object */ /** * The window/frame that this instance should operate in. * * @property win * @type Window * @default the window hosting YUI */ /** * The document associated with the 'win' configuration. * * @property doc * @type Document * @default the document hosting YUI */ /** * A list of modules that defines the YUI core (overrides the default list). * * @property core * @type Array * @default [ get,features,intl-base,yui-log,yui-later,loader-base, loader-rollup, loader-yui3 ] */ /** * A list of languages in order of preference. This list is matched against * the list of available languages in modules that the YUI instance uses to * determine the best possible localization of language sensitive modules. * Languages are represented using BCP 47 language tags, such as "en-GB" for * English as used in the United Kingdom, or "zh-Hans-CN" for simplified * Chinese as used in China. The list can be provided as a comma-separated * list or as an array. * * @property lang * @type string|string[] */ /** * The default date format * @property dateFormat * @type string * @deprecated use configuration in `DataType.Date.format()` instead. */ /** * The default locale * @property locale * @type string * @deprecated use `config.lang` instead. */ /** * The default interval when polling in milliseconds. * @property pollInterval * @type int * @default 20 */ /** * The number of dynamic nodes to insert by default before * automatically removing them. This applies to script nodes * because removing the node will not make the evaluated script * unavailable. Dynamic CSS is not auto purged, because removing * a linked style sheet will also remove the style definitions. * @property purgethreshold * @type int * @default 20 */ /** * The default interval when polling in milliseconds. * @property windowResizeDelay * @type int * @default 40 */ /** * Base directory for dynamic loading * @property base * @type string */ /* * The secure base dir (not implemented) * For dynamic loading. * @property secureBase * @type string */ /** * The YUI combo service base dir. Ex: `http://yui.yahooapis.com/combo?` * For dynamic loading. * @property comboBase * @type string */ /** * The root path to prepend to module path for the combo service. * Ex: 3.0.0b1/build/ * For dynamic loading. * @property root * @type string */ /** * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js).</dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * * myFilter: { * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * } * * For dynamic loading. * * @property filter * @type string|object */ /** * The `skin` config let's you configure application level skin * customizations. It contains the following attributes which * can be specified to override the defaults: * * // The default skin, which is automatically applied if not * // overriden by a component-specific skin definition. * // Change this in to apply a different skin globally * defaultSkin: 'sam', * * // This is combined with the loader base property to get * // the default root directory for a skin. * base: 'assets/skins/', * * // Any component-specific overrides can be specified here, * // making it possible to load different skins for different * // components. It is possible to load more than one skin * // for a given component as well. * overrides: { * slider: ['capsule', 'round'] * } * * For dynamic loading. * * @property skin */ /** * Hash of per-component filter specification. If specified for a given * component, this overrides the filter config. * * For dynamic loading. * * @property filters */ /** * Use the YUI combo service to reduce the number of http connections * required to load your dependencies. Turning this off will * disable combo handling for YUI and all module groups configured * with a combo service. * * For dynamic loading. * * @property combine * @type boolean * @default true if 'base' is not supplied, false if it is. */ /** * A list of modules that should never be dynamically loaded * * @property ignore * @type string[] */ /** * A list of modules that should always be loaded when required, even if already * present on the page. * * @property force * @type string[] */ /** * Node or id for a node that should be used as the insertion point for new * nodes. For dynamic loading. * * @property insertBefore * @type string */ /** * Object literal containing attributes to add to dynamically loaded script * nodes. * @property jsAttributes * @type string */ /** * Object literal containing attributes to add to dynamically loaded link * nodes. * @property cssAttributes * @type string */ /** * Number of milliseconds before a timeout occurs when dynamically * loading nodes. If not set, there is no timeout. * @property timeout * @type int */ /** * Callback for the 'CSSComplete' event. When dynamically loading YUI * components with CSS, this property fires when the CSS is finished * loading but script loading is still ongoing. This provides an * opportunity to enhance the presentation of a loading page a little * bit before the entire loading process is done. * * @property onCSS * @type function */ /** * A hash of module definitions to add to the list of YUI components. * These components can then be dynamically loaded side by side with * YUI via the `use()` method. This is a hash, the key is the module * name, and the value is an object literal specifying the metdata * for the module. See `Loader.addModule` for the supported module * metadata fields. Also see groups, which provides a way to * configure the base and combo spec for a set of modules. * * modules: { * mymod1: { * requires: ['node'], * fullpath: '/mymod1/mymod1.js' * }, * mymod2: { * requires: ['mymod1'], * fullpath: '/mymod2/mymod2.js' * }, * mymod3: '/js/mymod3.js', * mycssmod: '/css/mycssmod.css' * } * * * @property modules * @type object */ /** * Aliases are dynamic groups of modules that can be used as * shortcuts. * * YUI({ * aliases: { * davglass: [ 'node', 'yql', 'dd' ], * mine: [ 'davglass', 'autocomplete'] * } * }).use('mine', function(Y) { * //Node, YQL, DD &amp; AutoComplete available here.. * }); * * @property aliases * @type object */ /** * A hash of module group definitions. It for each group you * can specify a list of modules and the base path and * combo spec to use when dynamically loading the modules. * * groups: { * yui2: { * // specify whether or not this group has a combo service * combine: true, * * // The comboSeperator to use with this group's combo handler * comboSep: ';', * * // The maxURLLength for this server * maxURLLength: 500, * * // the base path for non-combo paths * base: 'http://yui.yahooapis.com/2.8.0r4/build/', * * // the path to the combo service * comboBase: 'http://yui.yahooapis.com/combo?', * * // a fragment to prepend to the path attribute when * // when building combo urls * root: '2.8.0r4/build/', * * // the module definitions * modules: { * yui2_yde: { * path: "yahoo-dom-event/yahoo-dom-event.js" * }, * yui2_anim: { * path: "animation/animation.js", * requires: ['yui2_yde'] * } * } * } * } * * @property groups * @type object */ /** * The loader 'path' attribute to the loader itself. This is combined * with the 'base' attribute to dynamically load the loader component * when boostrapping with the get utility alone. * * @property loaderPath * @type string * @default loader/loader-min.js */ /** * Specifies whether or not YUI().use(...) will attempt to load CSS * resources at all. Any truthy value will cause CSS dependencies * to load when fetching script. The special value 'force' will * cause CSS dependencies to be loaded even if no script is needed. * * @property fetchCSS * @type boolean|string * @default true */ /** * The default gallery version to build gallery module urls * @property gallery * @type string * @since 3.1.0 */ /** * The default YUI 2 version to build yui2 module urls. This is for * intrinsic YUI 2 support via the 2in3 project. Also see the '2in3' * config for pulling different revisions of the wrapped YUI 2 * modules. * @since 3.1.0 * @property yui2 * @type string * @default 2.9.0 */ /** * The 2in3 project is a deployment of the various versions of YUI 2 * deployed as first-class YUI 3 modules. Eventually, the wrapper * for the modules will change (but the underlying YUI 2 code will * be the same), and you can select a particular version of * the wrapper modules via this config. * @since 3.1.0 * @property 2in3 * @type string * @default 4 */ /** * Alternative console log function for use in environments without * a supported native console. The function is executed in the * YUI instance context. * @since 3.1.0 * @property logFn * @type Function */ /** * A callback to execute when Y.error is called. It receives the * error message and an javascript error object if Y.error was * executed because a javascript error was caught. The function * is executed in the YUI instance context. Returning `true` from this * function will stop the Error from being thrown. * * @since 3.2.0 * @property errorFn * @type Function */ /** * A callback to execute when the loader fails to load one or * more resource. This could be because of a script load * failure. It can also fail if a javascript module fails * to register itself, but only when the 'requireRegistration' * is true. If this function is defined, the use() callback will * only be called when the loader succeeds, otherwise it always * executes unless there was a javascript error when attaching * a module. * * @since 3.3.0 * @property loadErrorFn * @type Function */ /** * When set to true, the YUI loader will expect that all modules * it is responsible for loading will be first-class YUI modules * that register themselves with the YUI global. If this is * set to true, loader will fail if the module registration fails * to happen after the script is loaded. * * @since 3.3.0 * @property requireRegistration * @type boolean * @default false */ /** * Cache serviced use() requests. * @since 3.3.0 * @property cacheUse * @type boolean * @default true * @deprecated no longer used */ /** * Whether or not YUI should use native ES5 functionality when available for * features like `Y.Array.each()`, `Y.Object()`, etc. When `false`, YUI will * always use its own fallback implementations instead of relying on ES5 * functionality, even when it's available. * * @property useNativeES5 * @type Boolean * @default true * @since 3.5.0 */ /** Delay the `use` callback until a specific event has passed (`load`, `domready`, `contentready` or `available`) @property delayUntil @type String|Object @since 3.6.0 @example You can use `load` or `domready` strings by default: YUI({ delayUntil: 'domready' }, function(Y) { //This will not fire until 'domeready' }); Or you can delay until a node is available (with `available` or `contentready`): YUI({ delayUntil: { event: 'available', args: '#foo' } }, function(Y) { //This will not fire until '#foo' is // available in the DOM }); */ YUI.add('yui-base', function (Y, NAME) { /* * YUI stub * @module yui * @submodule yui-base */ /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Provides core language utilites and extensions used throughout YUI. * * @class Lang * @static */ var L = Y.Lang || (Y.Lang = {}), STRING_PROTO = String.prototype, TOSTRING = Object.prototype.toString, TYPES = { 'undefined' : 'undefined', 'number' : 'number', 'boolean' : 'boolean', 'string' : 'string', '[object Function]': 'function', '[object RegExp]' : 'regexp', '[object Array]' : 'array', '[object Date]' : 'date', '[object Error]' : 'error' }, SUBREGEX = /\{\s*([^|}]+?)\s*(?:\|([^}]*))?\s*\}/g, TRIMREGEX = /^\s+|\s+$/g, NATIVE_FN_REGEX = /\{\s*\[(?:native code|function)\]\s*\}/i; // -- Protected Methods -------------------------------------------------------- /** Returns `true` if the given function appears to be implemented in native code, `false` otherwise. Will always return `false` -- even in ES5-capable browsers -- if the `useNativeES5` YUI config option is set to `false`. This isn't guaranteed to be 100% accurate and won't work for anything other than functions, but it can be useful for determining whether a function like `Array.prototype.forEach` is native or a JS shim provided by another library. There's a great article by @kangax discussing certain flaws with this technique: <http://perfectionkills.com/detecting-built-in-host-methods/> While his points are valid, it's still possible to benefit from this function as long as it's used carefully and sparingly, and in such a way that false negatives have minimal consequences. It's used internally to avoid using potentially broken non-native ES5 shims that have been added to the page by other libraries. @method _isNative @param {Function} fn Function to test. @return {Boolean} `true` if _fn_ appears to be native, `false` otherwise. @static @protected @since 3.5.0 **/ L._isNative = function (fn) { return !!(Y.config.useNativeES5 && fn && NATIVE_FN_REGEX.test(fn)); }; // -- Public Methods ----------------------------------------------------------- /** * Determines whether or not the provided item is an array. * * Returns `false` for array-like collections such as the function `arguments` * collection or `HTMLElement` collections. Use `Y.Array.test()` if you want to * test for an array-like collection. * * @method isArray * @param o The object to test. * @return {boolean} true if o is an array. * @static */ L.isArray = L._isNative(Array.isArray) ? Array.isArray : function (o) { return L.type(o) === 'array'; }; /** * Determines whether or not the provided item is a boolean. * @method isBoolean * @static * @param o The object to test. * @return {boolean} true if o is a boolean. */ L.isBoolean = function(o) { return typeof o === 'boolean'; }; /** * Determines whether or not the supplied item is a date instance. * @method isDate * @static * @param o The object to test. * @return {boolean} true if o is a date. */ L.isDate = function(o) { return L.type(o) === 'date' && o.toString() !== 'Invalid Date' && !isNaN(o); }; /** * <p> * Determines whether or not the provided item is a function. * Note: Internet Explorer thinks certain functions are objects: * </p> * * <pre> * var obj = document.createElement("object"); * Y.Lang.isFunction(obj.getAttribute) // reports false in IE * &nbsp; * var input = document.createElement("input"); // append to body * Y.Lang.isFunction(input.focus) // reports false in IE * </pre> * * <p> * You will have to implement additional tests if these functions * matter to you. * </p> * * @method isFunction * @static * @param o The object to test. * @return {boolean} true if o is a function. */ L.isFunction = function(o) { return L.type(o) === 'function'; }; /** * Determines whether or not the provided item is null. * @method isNull * @static * @param o The object to test. * @return {boolean} true if o is null. */ L.isNull = function(o) { return o === null; }; /** * Determines whether or not the provided item is a legal number. * @method isNumber * @static * @param o The object to test. * @return {boolean} true if o is a number. */ L.isNumber = function(o) { return typeof o === 'number' && isFinite(o); }; /** * Determines whether or not the provided item is of type object * or function. Note that arrays are also objects, so * <code>Y.Lang.isObject([]) === true</code>. * @method isObject * @static * @param o The object to test. * @param failfn {boolean} fail if the input is a function. * @return {boolean} true if o is an object. * @see isPlainObject */ L.isObject = function(o, failfn) { var t = typeof o; return (o && (t === 'object' || (!failfn && (t === 'function' || L.isFunction(o))))) || false; }; /** * Determines whether or not the provided item is a string. * @method isString * @static * @param o The object to test. * @return {boolean} true if o is a string. */ L.isString = function(o) { return typeof o === 'string'; }; /** * Determines whether or not the provided item is undefined. * @method isUndefined * @static * @param o The object to test. * @return {boolean} true if o is undefined. */ L.isUndefined = function(o) { return typeof o === 'undefined'; }; /** * A convenience method for detecting a legitimate non-null value. * Returns false for null/undefined/NaN, true for other values, * including 0/false/'' * @method isValue * @static * @param o The item to test. * @return {boolean} true if it is not null/undefined/NaN || false. */ L.isValue = function(o) { var t = L.type(o); switch (t) { case 'number': return isFinite(o); case 'null': // fallthru case 'undefined': return false; default: return !!t; } }; /** * Returns the current time in milliseconds. * * @method now * @return {Number} Current time in milliseconds. * @static * @since 3.3.0 */ L.now = Date.now || function () { return new Date().getTime(); }; /** * Lightweight version of <code>Y.substitute</code>. Uses the same template * structure as <code>Y.substitute</code>, but doesn't support recursion, * auto-object coersion, or formats. * @method sub * @param {string} s String to be modified. * @param {object} o Object containing replacement values. * @return {string} the substitute result. * @static * @since 3.2.0 */ L.sub = function(s, o) { return s.replace ? s.replace(SUBREGEX, function (match, key) { return L.isUndefined(o[key]) ? match : o[key]; }) : s; }; /** * Returns a string without any leading or trailing whitespace. If * the input is not a string, the input will be returned untouched. * @method trim * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trim = STRING_PROTO.trim ? function(s) { return s && s.trim ? s.trim() : s; } : function (s) { try { return s.replace(TRIMREGEX, ''); } catch (e) { return s; } }; /** * Returns a string without any leading whitespace. * @method trimLeft * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimLeft = STRING_PROTO.trimLeft ? function (s) { return s.trimLeft(); } : function (s) { return s.replace(/^\s+/, ''); }; /** * Returns a string without any trailing whitespace. * @method trimRight * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimRight = STRING_PROTO.trimRight ? function (s) { return s.trimRight(); } : function (s) { return s.replace(/\s+$/, ''); }; /** Returns one of the following strings, representing the type of the item passed in: * "array" * "boolean" * "date" * "error" * "function" * "null" * "number" * "object" * "regexp" * "string" * "undefined" Known issues: * `typeof HTMLElementCollection` returns function in Safari, but `Y.Lang.type()` reports "object", which could be a good thing -- but it actually caused the logic in <code>Y.Lang.isObject</code> to fail. @method type @param o the item to test. @return {string} the detected type. @static **/ L.type = function(o) { return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null'); }; /** @module yui @submodule yui-base */ var Lang = Y.Lang, Native = Array.prototype, hasOwn = Object.prototype.hasOwnProperty; /** Provides utility methods for working with arrays. Additional array helpers can be found in the `collection` and `array-extras` modules. `Y.Array(thing)` returns a native array created from _thing_. Depending on _thing_'s type, one of the following will happen: * Arrays are returned unmodified unless a non-zero _startIndex_ is specified. * Array-like collections (see `Array.test()`) are converted to arrays. * For everything else, a new array is created with _thing_ as the sole item. Note: elements that are also collections, such as `<form>` and `<select>` elements, are not automatically converted to arrays. To force a conversion, pass `true` as the value of the _force_ parameter. @class Array @constructor @param {Any} thing The thing to arrayify. @param {Number} [startIndex=0] If non-zero and _thing_ is an array or array-like collection, a subset of items starting at the specified index will be returned. @param {Boolean} [force=false] If `true`, _thing_ will be treated as an array-like collection no matter what. @return {Array} A native array created from _thing_, according to the rules described above. **/ function YArray(thing, startIndex, force) { var len, result; startIndex || (startIndex = 0); if (force || YArray.test(thing)) { // IE throws when trying to slice HTMLElement collections. try { return Native.slice.call(thing, startIndex); } catch (ex) { result = []; for (len = thing.length; startIndex < len; ++startIndex) { result.push(thing[startIndex]); } return result; } } return [thing]; } Y.Array = YArray; /** Dedupes an array of strings, returning an array that's guaranteed to contain only one copy of a given string. This method differs from `Array.unique()` in that it's optimized for use only with strings, whereas `unique` may be used with other types (but is slower). Using `dedupe()` with non-string values may result in unexpected behavior. @method dedupe @param {String[]} array Array of strings to dedupe. @return {Array} Deduped copy of _array_. @static @since 3.4.0 **/ YArray.dedupe = function (array) { var hash = {}, results = [], i, item, len; for (i = 0, len = array.length; i < len; ++i) { item = array[i]; if (!hasOwn.call(hash, item)) { hash[item] = 1; results.push(item); } } return results; }; /** Executes the supplied function on each item in the array. This method wraps the native ES5 `Array.forEach()` method if available. @method each @param {Array} array Array to iterate. @param {Function} fn Function to execute on each item in the array. The function will receive the following arguments: @param {Any} fn.item Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {YUI} The YUI instance. @static **/ YArray.each = YArray.forEach = Lang._isNative(Native.forEach) ? function (array, fn, thisObj) { Native.forEach.call(array || [], fn, thisObj || Y); return Y; } : function (array, fn, thisObj) { for (var i = 0, len = (array && array.length) || 0; i < len; ++i) { if (i in array) { fn.call(thisObj || Y, array[i], i, array); } } return Y; }; /** Alias for `each()`. @method forEach @static **/ /** Returns an object using the first array as keys and the second as values. If the second array is not provided, or if it doesn't contain the same number of values as the first array, then `true` will be used in place of the missing values. @example Y.Array.hash(['a', 'b', 'c'], ['foo', 'bar']); // => {a: 'foo', b: 'bar', c: true} @method hash @param {String[]} keys Array of strings to use as keys. @param {Array} [values] Array to use as values. @return {Object} Hash using the first array as keys and the second as values. @static **/ YArray.hash = function (keys, values) { var hash = {}, vlen = (values && values.length) || 0, i, len; for (i = 0, len = keys.length; i < len; ++i) { if (i in keys) { hash[keys[i]] = vlen > i && i in values ? values[i] : true; } } return hash; }; /** Returns the index of the first item in the array that's equal (using a strict equality check) to the specified _value_, or `-1` if the value isn't found. This method wraps the native ES5 `Array.indexOf()` method if available. @method indexOf @param {Array} array Array to search. @param {Any} value Value to search for. @param {Number} [from=0] The index at which to begin the search. @return {Number} Index of the item strictly equal to _value_, or `-1` if not found. @static **/ YArray.indexOf = Lang._isNative(Native.indexOf) ? function (array, value, from) { return Native.indexOf.call(array, value, from); } : function (array, value, from) { // http://es5.github.com/#x15.4.4.14 var len = array.length; from = +from || 0; from = (from > 0 || -1) * Math.floor(Math.abs(from)); if (from < 0) { from += len; if (from < 0) { from = 0; } } for (; from < len; ++from) { if (from in array && array[from] === value) { return from; } } return -1; }; /** Numeric sort convenience function. The native `Array.prototype.sort()` function converts values to strings and sorts them in lexicographic order, which is unsuitable for sorting numeric values. Provide `Array.numericSort` as a custom sort function when you want to sort values in numeric order. @example [42, 23, 8, 16, 4, 15].sort(Y.Array.numericSort); // => [4, 8, 15, 16, 23, 42] @method numericSort @param {Number} a First value to compare. @param {Number} b Second value to compare. @return {Number} Difference between _a_ and _b_. @static **/ YArray.numericSort = function (a, b) { return a - b; }; /** Executes the supplied function on each item in the array. Returning a truthy value from the function will stop the processing of remaining items. @method some @param {Array} array Array to iterate over. @param {Function} fn Function to execute on each item. The function will receive the following arguments: @param {Any} fn.value Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated over. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {Boolean} `true` if the function returns a truthy value on any of the items in the array; `false` otherwise. @static **/ YArray.some = Lang._isNative(Native.some) ? function (array, fn, thisObj) { return Native.some.call(array, fn, thisObj); } : function (array, fn, thisObj) { for (var i = 0, len = array.length; i < len; ++i) { if (i in array && fn.call(thisObj, array[i], i, array)) { return true; } } return false; }; /** Evaluates _obj_ to determine if it's an array, an array-like collection, or something else. This is useful when working with the function `arguments` collection and `HTMLElement` collections. Note: This implementation doesn't consider elements that are also collections, such as `<form>` and `<select>`, to be array-like. @method test @param {Object} obj Object to test. @return {Number} A number indicating the results of the test: * 0: Neither an array nor an array-like collection. * 1: Real array. * 2: Array-like collection. @static **/ YArray.test = function (obj) { var result = 0; if (Lang.isArray(obj)) { result = 1; } else if (Lang.isObject(obj)) { try { // indexed, but no tagName (element) or scrollTo/document (window. From DOM.isWindow test which we can't use here), // or functions without apply/call (Safari // HTMLElementCollection bug). if ('length' in obj && !obj.tagName && !(obj.scrollTo && obj.document) && !obj.apply) { result = 2; } } catch (ex) {} } return result; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * A simple FIFO queue. Items are added to the Queue with add(1..n items) and * removed using next(). * * @class Queue * @constructor * @param {MIXED} item* 0..n items to seed the queue. */ function Queue() { this._init(); this.add.apply(this, arguments); } Queue.prototype = { /** * Initialize the queue * * @method _init * @protected */ _init: function() { /** * The collection of enqueued items * * @property _q * @type Array * @protected */ this._q = []; }, /** * Get the next item in the queue. FIFO support * * @method next * @return {MIXED} the next item in the queue. */ next: function() { return this._q.shift(); }, /** * Get the last in the queue. LIFO support. * * @method last * @return {MIXED} the last item in the queue. */ last: function() { return this._q.pop(); }, /** * Add 0..n items to the end of the queue. * * @method add * @param {MIXED} item* 0..n items. * @return {object} this queue. */ add: function() { this._q.push.apply(this._q, arguments); return this; }, /** * Returns the current number of queued items. * * @method size * @return {Number} The size. */ size: function() { return this._q.length; } }; Y.Queue = Queue; YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Queue(); /** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @submodule yui-base **/ var CACHED_DELIMITER = '__', hasOwn = Object.prototype.hasOwnProperty, isObject = Y.Lang.isObject; /** Returns a wrapper for a function which caches the return value of that function, keyed off of the combined string representation of the argument values provided when the wrapper is called. Calling this function again with the same arguments will return the cached value rather than executing the wrapped function. Note that since the cache is keyed off of the string representation of arguments passed to the wrapper function, arguments that aren't strings and don't provide a meaningful `toString()` method may result in unexpected caching behavior. For example, the objects `{}` and `{foo: 'bar'}` would both be converted to the string `[object Object]` when used as a cache key. @method cached @param {Function} source The function to memoize. @param {Object} [cache={}] Object in which to store cached values. You may seed this object with pre-existing cached values if desired. @param {any} [refetch] If supplied, this value is compared with the cached value using a `==` comparison. If the values are equal, the wrapped function is executed again even though a cached value exists. @return {Function} Wrapped function. @for YUI **/ Y.cached = function (source, cache, refetch) { cache || (cache = {}); return function (arg) { var key = arguments.length > 1 ? Array.prototype.join.call(arguments, CACHED_DELIMITER) : String(arg); if (!(key in cache) || (refetch && cache[key] == refetch)) { cache[key] = source.apply(source, arguments); } return cache[key]; }; }; /** Returns the `location` object from the window/frame in which this YUI instance operates, or `undefined` when executing in a non-browser environment (e.g. Node.js). It is _not_ recommended to hold references to the `window.location` object outside of the scope of a function in which its properties are being accessed or its methods are being called. This is because of a nasty bug/issue that exists in both Safari and MobileSafari browsers: [WebKit Bug 34679](https://bugs.webkit.org/show_bug.cgi?id=34679). @method getLocation @return {location} The `location` object from the window/frame in which this YUI instance operates. @since 3.5.0 **/ Y.getLocation = function () { // It is safer to look this up every time because yui-base is attached to a // YUI instance before a user's config is applied; i.e. `Y.config.win` does // not point the correct window object when this file is loaded. var win = Y.config.win; // It is not safe to hold a reference to the `location` object outside the // scope in which it is being used. The WebKit engine used in Safari and // MobileSafari will "disconnect" the `location` object from the `window` // when a page is restored from back/forward history cache. return win && win.location; }; /** Returns a new object containing all of the properties of all the supplied objects. The properties from later objects will overwrite those in earlier objects. Passing in a single object will create a shallow copy of it. For a deep copy, use `clone()`. @method merge @param {Object} objects* One or more objects to merge. @return {Object} A new merged object. **/ Y.merge = function () { var i = 0, len = arguments.length, result = {}, key, obj; for (; i < len; ++i) { obj = arguments[i]; for (key in obj) { if (hasOwn.call(obj, key)) { result[key] = obj[key]; } } } return result; }; /** Mixes _supplier_'s properties into _receiver_. Properties on _receiver_ or _receiver_'s prototype will not be overwritten or shadowed unless the _overwrite_ parameter is `true`, and will not be merged unless the _merge_ parameter is `true`. In the default mode (0), only properties the supplier owns are copied (prototype properties are not copied). The following copying modes are available: * `0`: _Default_. Object to object. * `1`: Prototype to prototype. * `2`: Prototype to prototype and object to object. * `3`: Prototype to object. * `4`: Object to prototype. @method mix @param {Function|Object} receiver The object or function to receive the mixed properties. @param {Function|Object} supplier The object or function supplying the properties to be mixed. @param {Boolean} [overwrite=false] If `true`, properties that already exist on the receiver will be overwritten with properties from the supplier. @param {String[]} [whitelist] An array of property names to copy. If specified, only the whitelisted properties will be copied, and all others will be ignored. @param {Number} [mode=0] Mix mode to use. See above for available modes. @param {Boolean} [merge=false] If `true`, objects and arrays that already exist on the receiver will have the corresponding object/array from the supplier merged into them, rather than being skipped or overwritten. When both _overwrite_ and _merge_ are `true`, _merge_ takes precedence. @return {Function|Object|YUI} The receiver, or the YUI instance if the specified receiver is falsy. **/ Y.mix = function(receiver, supplier, overwrite, whitelist, mode, merge) { var alwaysOverwrite, exists, from, i, key, len, to; // If no supplier is given, we return the receiver. If no receiver is given, // we return Y. Returning Y doesn't make much sense to me, but it's // grandfathered in for backcompat reasons. if (!receiver || !supplier) { return receiver || Y; } if (mode) { // In mode 2 (prototype to prototype and object to object), we recurse // once to do the proto to proto mix. The object to object mix will be // handled later on. if (mode === 2) { Y.mix(receiver.prototype, supplier.prototype, overwrite, whitelist, 0, merge); } // Depending on which mode is specified, we may be copying from or to // the prototypes of the supplier and receiver. from = mode === 1 || mode === 3 ? supplier.prototype : supplier; to = mode === 1 || mode === 4 ? receiver.prototype : receiver; // If either the supplier or receiver doesn't actually have a // prototype property, then we could end up with an undefined `from` // or `to`. If that happens, we abort and return the receiver. if (!from || !to) { return receiver; } } else { from = supplier; to = receiver; } // If `overwrite` is truthy and `merge` is falsy, then we can skip a // property existence check on each iteration and save some time. alwaysOverwrite = overwrite && !merge; if (whitelist) { for (i = 0, len = whitelist.length; i < len; ++i) { key = whitelist[i]; // We call `Object.prototype.hasOwnProperty` instead of calling // `hasOwnProperty` on the object itself, since the object's // `hasOwnProperty` method may have been overridden or removed. // Also, some native objects don't implement a `hasOwnProperty` // method. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { // If we're in merge mode, and the key is present on both // objects, and the value on both objects is either an object or // an array (but not a function), then we recurse to merge the // `from` value into the `to` value instead of overwriting it. // // Note: It's intentional that the whitelist isn't passed to the // recursive call here. This is legacy behavior that lots of // code still depends on. Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { // We're not in merge mode, so we'll only copy the `from` value // to the `to` value if we're in overwrite mode or if the // current key doesn't exist on the `to` object. to[key] = from[key]; } } } else { for (key in from) { // The code duplication here is for runtime performance reasons. // Combining whitelist and non-whitelist operations into a single // loop or breaking the shared logic out into a function both result // in worse performance, and Y.mix is critical enough that the byte // tradeoff is worth it. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { to[key] = from[key]; } } // If this is an IE browser with the JScript enumeration bug, force // enumeration of the buggy properties by making a recursive call with // the buggy properties as the whitelist. if (Y.Object._hasEnumBug) { Y.mix(to, from, overwrite, Y.Object._forceEnum, mode, merge); } } return receiver; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Adds utilities to the YUI instance for working with objects. * * @class Object */ var Lang = Y.Lang, hasOwn = Object.prototype.hasOwnProperty, UNDEFINED, // <-- Note the comma. We're still declaring vars. /** * Returns a new object that uses _obj_ as its prototype. This method wraps the * native ES5 `Object.create()` method if available, but doesn't currently * pass through `Object.create()`'s second argument (properties) in order to * ensure compatibility with older browsers. * * @method () * @param {Object} obj Prototype object. * @return {Object} New object using _obj_ as its prototype. * @static */ O = Y.Object = Lang._isNative(Object.create) ? function (obj) { // We currently wrap the native Object.create instead of simply aliasing it // to ensure consistency with our fallback shim, which currently doesn't // support Object.create()'s second argument (properties). Once we have a // safe fallback for the properties arg, we can stop wrapping // Object.create(). return Object.create(obj); } : (function () { // Reusable constructor function for the Object.create() shim. function F() {} // The actual shim. return function (obj) { F.prototype = obj; return new F(); }; }()), /** * Property names that IE doesn't enumerate in for..in loops, even when they * should be enumerable. When `_hasEnumBug` is `true`, it's necessary to * manually enumerate these properties. * * @property _forceEnum * @type String[] * @protected * @static */ forceEnum = O._forceEnum = [ 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toString', 'toLocaleString', 'valueOf' ], /** * `true` if this browser has the JScript enumeration bug that prevents * enumeration of the properties named in the `_forceEnum` array, `false` * otherwise. * * See: * - <https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug> * - <http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation> * * @property _hasEnumBug * @type Boolean * @protected * @static */ hasEnumBug = O._hasEnumBug = !{valueOf: 0}.propertyIsEnumerable('valueOf'), /** * `true` if this browser incorrectly considers the `prototype` property of * functions to be enumerable. Currently known to affect Opera 11.50. * * @property _hasProtoEnumBug * @type Boolean * @protected * @static */ hasProtoEnumBug = O._hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'), /** * Returns `true` if _key_ exists on _obj_, `false` if _key_ doesn't exist or * exists only on _obj_'s prototype. This is essentially a safer version of * `obj.hasOwnProperty()`. * * @method owns * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ owns = O.owns = function (obj, key) { return !!obj && hasOwn.call(obj, key); }; // <-- End of var declarations. /** * Alias for `owns()`. * * @method hasKey * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ O.hasKey = owns; /** * Returns an array containing the object's enumerable keys. Does not include * prototype keys or non-enumerable keys. * * Note that keys are returned in enumeration order (that is, in the same order * that they would be enumerated by a `for-in` loop), which may not be the same * as the order in which they were defined. * * This method is an alias for the native ES5 `Object.keys()` method if * available. * * @example * * Y.Object.keys({a: 'foo', b: 'bar', c: 'baz'}); * // => ['a', 'b', 'c'] * * @method keys * @param {Object} obj An object. * @return {String[]} Array of keys. * @static */ O.keys = Lang._isNative(Object.keys) ? Object.keys : function (obj) { if (!Lang.isObject(obj)) { throw new TypeError('Object.keys called on a non-object'); } var keys = [], i, key, len; if (hasProtoEnumBug && typeof obj === 'function') { for (key in obj) { if (owns(obj, key) && key !== 'prototype') { keys.push(key); } } } else { for (key in obj) { if (owns(obj, key)) { keys.push(key); } } } if (hasEnumBug) { for (i = 0, len = forceEnum.length; i < len; ++i) { key = forceEnum[i]; if (owns(obj, key)) { keys.push(key); } } } return keys; }; /** * Returns an array containing the values of the object's enumerable keys. * * Note that values are returned in enumeration order (that is, in the same * order that they would be enumerated by a `for-in` loop), which may not be the * same as the order in which they were defined. * * @example * * Y.Object.values({a: 'foo', b: 'bar', c: 'baz'}); * // => ['foo', 'bar', 'baz'] * * @method values * @param {Object} obj An object. * @return {Array} Array of values. * @static */ O.values = function (obj) { var keys = O.keys(obj), i = 0, len = keys.length, values = []; for (; i < len; ++i) { values.push(obj[keys[i]]); } return values; }; /** * Returns the number of enumerable keys owned by an object. * * @method size * @param {Object} obj An object. * @return {Number} The object's size. * @static */ O.size = function (obj) { try { return O.keys(obj).length; } catch (ex) { return 0; // Legacy behavior for non-objects. } }; /** * Returns `true` if the object owns an enumerable property with the specified * value. * * @method hasValue * @param {Object} obj An object. * @param {any} value The value to search for. * @return {Boolean} `true` if _obj_ contains _value_, `false` otherwise. * @static */ O.hasValue = function (obj, value) { return Y.Array.indexOf(O.values(obj), value) > -1; }; /** * Executes a function on each enumerable property in _obj_. The function * receives the value, the key, and the object itself as parameters (in that * order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method each * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {YUI} the YUI instance. * @chainable * @static */ O.each = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { fn.call(thisObj || Y, obj[key], key, obj); } } return Y; }; /** * Executes a function on each enumerable property in _obj_, but halts if the * function returns a truthy value. The function receives the value, the key, * and the object itself as paramters (in that order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method some * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {Boolean} `true` if any execution of _fn_ returns a truthy value, * `false` otherwise. * @static */ O.some = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { if (fn.call(thisObj || Y, obj[key], key, obj)) { return true; } } } return false; }; /** * Retrieves the sub value at the provided path, * from the value object provided. * * @method getValue * @static * @param o The object from which to extract the property value. * @param path {Array} A path array, specifying the object traversal path * from which to obtain the sub value. * @return {Any} The value stored in the path, undefined if not found, * undefined if the source is not an object. Returns the source object * if an empty path is provided. */ O.getValue = function(o, path) { if (!Lang.isObject(o)) { return UNDEFINED; } var i, p = Y.Array(path), l = p.length; for (i = 0; o !== UNDEFINED && i < l; i++) { o = o[p[i]]; } return o; }; /** * Sets the sub-attribute value at the provided path on the * value object. Returns the modified value object, or * undefined if the path is invalid. * * @method setValue * @static * @param o The object on which to set the sub value. * @param path {Array} A path array, specifying the object traversal path * at which to set the sub value. * @param val {Any} The new value for the sub-attribute. * @return {Object} The modified object, with the new sub value set, or * undefined, if the path was invalid. */ O.setValue = function(o, path, val) { var i, p = Y.Array(path), leafIdx = p.length - 1, ref = o; if (leafIdx >= 0) { for (i = 0; ref !== UNDEFINED && i < leafIdx; i++) { ref = ref[p[i]]; } if (ref !== UNDEFINED) { ref[p[i]] = val; } else { return UNDEFINED; } } return o; }; /** * Returns `true` if the object has no enumerable properties of its own. * * @method isEmpty * @param {Object} obj An object. * @return {Boolean} `true` if the object is empty. * @static * @since 3.2.0 */ O.isEmpty = function (obj) { return !O.keys(Object(obj)).length; }; /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and the * core utilities for the library. * @module yui * @submodule yui-base */ /** * YUI user agent detection. * Do not fork for a browser if it can be avoided. Use feature detection when * you can. Use the user agent as a last resort. For all fields listed * as @type float, UA stores a version number for the browser engine, * 0 otherwise. This value may or may not map to the version number of * the browser using the engine. The value is presented as a float so * that it can easily be used for boolean evaluation as well as for * looking for a particular range of versions. Because of this, * some of the granularity of the version info may be lost. The fields that * are @type string default to null. The API docs list the values that * these fields can have. * @class UA * @static */ /** * Static method on `YUI.Env` for parsing a UA string. Called at instantiation * to populate `Y.UA`. * * @static * @method parseUA * @param {String} [subUA=navigator.userAgent] UA string to parse * @return {Object} The Y.UA object */ YUI.Env.parseUA = function(subUA) { var numberify = function(s) { var c = 0; return parseFloat(s.replace(/\./g, function() { return (c++ === 1) ? '' : '.'; })); }, win = Y.config.win, nav = win && win.navigator, o = { /** * Internet Explorer version number or 0. Example: 6 * @property ie * @type float * @static */ ie: 0, /** * Opera version number or 0. Example: 9.2 * @property opera * @type float * @static */ opera: 0, /** * Gecko engine revision number. Will evaluate to 1 if Gecko * is detected but the revision could not be found. Other browsers * will be 0. Example: 1.8 * <pre> * Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7 * Firefox 1.5.0.9: 1.8.0.9 <-- 1.8 * Firefox 2.0.0.3: 1.8.1.3 <-- 1.81 * Firefox 3.0 <-- 1.9 * Firefox 3.5 <-- 1.91 * </pre> * @property gecko * @type float * @static */ gecko: 0, /** * AppleWebKit version. KHTML browsers that are not WebKit browsers * will evaluate to 1, other browsers 0. Example: 418.9 * <pre> * Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the * latest available for Mac OSX 10.3. * Safari 2.0.2: 416 <-- hasOwnProperty introduced * Safari 2.0.4: 418 <-- preventDefault fixed * Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run * different versions of webkit * Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been * updated, but not updated * to the latest patch. * Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native * SVG and many major issues fixed). * Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic * update from 2.x via the 10.4.11 OS patch. * Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event. * yahoo.com user agent hack removed. * </pre> * http://en.wikipedia.org/wiki/Safari_version_history * @property webkit * @type float * @static */ webkit: 0, /** * Safari will be detected as webkit, but this property will also * be populated with the Safari version number * @property safari * @type float * @static */ safari: 0, /** * Chrome will be detected as webkit, but this property will also * be populated with the Chrome version number * @property chrome * @type float * @static */ chrome: 0, /** * The mobile property will be set to a string containing any relevant * user agent information when a modern mobile browser is detected. * Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series * devices with the WebKit-based browser, and Opera Mini. * @property mobile * @type string * @default null * @static */ mobile: null, /** * Adobe AIR version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property air * @type float */ air: 0, /** * PhantomJS version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property phantomjs * @type float */ phantomjs: 0, /** * Detects Apple iPad's OS version * @property ipad * @type float * @static */ ipad: 0, /** * Detects Apple iPhone's OS version * @property iphone * @type float * @static */ iphone: 0, /** * Detects Apples iPod's OS version * @property ipod * @type float * @static */ ipod: 0, /** * General truthy check for iPad, iPhone or iPod * @property ios * @type Boolean * @default null * @static */ ios: null, /** * Detects Googles Android OS version * @property android * @type float * @static */ android: 0, /** * Detects Kindle Silk * @property silk * @type float * @static */ silk: 0, /** * Detects Kindle Silk Acceleration * @property accel * @type Boolean * @static */ accel: false, /** * Detects Palms WebOS version * @property webos * @type float * @static */ webos: 0, /** * Google Caja version number or 0. * @property caja * @type float */ caja: nav && nav.cajaVersion, /** * Set to true if the page appears to be in SSL * @property secure * @type boolean * @static */ secure: false, /** * The operating system. Currently only detecting windows or macintosh * @property os * @type string * @default null * @static */ os: null, /** * The Nodejs Version * @property nodejs * @type float * @default 0 * @static */ nodejs: 0, /** * Window8/IE10 Application host environment * @property winjs * @type Boolean * @static */ winjs: !!((typeof Windows !== "undefined") && Windows.System), /** * Are touch/msPointer events available on this device * @property touchEnabled * @type Boolean * @static */ touchEnabled: false }, ua = subUA || nav && nav.userAgent, loc = win && win.location, href = loc && loc.href, m; /** * The User Agent string that was parsed * @property userAgent * @type String * @static */ o.userAgent = ua; o.secure = href && (href.toLowerCase().indexOf('https') === 0); if (ua) { if ((/windows|win32/i).test(ua)) { o.os = 'windows'; } else if ((/macintosh|mac_powerpc/i).test(ua)) { o.os = 'macintosh'; } else if ((/android/i).test(ua)) { o.os = 'android'; } else if ((/symbos/i).test(ua)) { o.os = 'symbos'; } else if ((/linux/i).test(ua)) { o.os = 'linux'; } else if ((/rhino/i).test(ua)) { o.os = 'rhino'; } // Modern KHTML browsers should qualify as Safari X-Grade if ((/KHTML/).test(ua)) { o.webkit = 1; } if ((/IEMobile|XBLWP7/).test(ua)) { o.mobile = 'windows'; } if ((/Fennec/).test(ua)) { o.mobile = 'gecko'; } // Modern WebKit browsers are at least X-Grade m = ua.match(/AppleWebKit\/([^\s]*)/); if (m && m[1]) { o.webkit = numberify(m[1]); o.safari = o.webkit; if (/PhantomJS/.test(ua)) { m = ua.match(/PhantomJS\/([^\s]*)/); if (m && m[1]) { o.phantomjs = numberify(m[1]); } } // Mobile browser check if (/ Mobile\//.test(ua) || (/iPad|iPod|iPhone/).test(ua)) { o.mobile = 'Apple'; // iPhone or iPod Touch m = ua.match(/OS ([^\s]*)/); if (m && m[1]) { m = numberify(m[1].replace('_', '.')); } o.ios = m; o.os = 'ios'; o.ipad = o.ipod = o.iphone = 0; m = ua.match(/iPad|iPod|iPhone/); if (m && m[0]) { o[m[0].toLowerCase()] = o.ios; } } else { m = ua.match(/NokiaN[^\/]*|webOS\/\d\.\d/); if (m) { // Nokia N-series, webOS, ex: NokiaN95 o.mobile = m[0]; } if (/webOS/.test(ua)) { o.mobile = 'WebOS'; m = ua.match(/webOS\/([^\s]*);/); if (m && m[1]) { o.webos = numberify(m[1]); } } if (/ Android/.test(ua)) { if (/Mobile/.test(ua)) { o.mobile = 'Android'; } m = ua.match(/Android ([^\s]*);/); if (m && m[1]) { o.android = numberify(m[1]); } } if (/Silk/.test(ua)) { m = ua.match(/Silk\/([^\s]*)\)/); if (m && m[1]) { o.silk = numberify(m[1]); } if (!o.android) { o.android = 2.34; //Hack for desktop mode in Kindle o.os = 'Android'; } if (/Accelerated=true/.test(ua)) { o.accel = true; } } } m = ua.match(/(Chrome|CrMo|CriOS)\/([^\s]*)/); if (m && m[1] && m[2]) { o.chrome = numberify(m[2]); // Chrome o.safari = 0; //Reset safari back to 0 if (m[1] === 'CrMo') { o.mobile = 'chrome'; } } else { m = ua.match(/AdobeAIR\/([^\s]*)/); if (m) { o.air = m[0]; // Adobe AIR 1.0 or better } } } if (!o.webkit) { // not webkit // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr) if (/Opera/.test(ua)) { m = ua.match(/Opera[\s\/]([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } m = ua.match(/Version\/([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); // opera 10+ } if (/Opera Mobi/.test(ua)) { o.mobile = 'opera'; m = ua.replace('Opera Mobi', '').match(/Opera ([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } } m = ua.match(/Opera Mini[^;]*/); if (m) { o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316 } } else { // not opera or webkit m = ua.match(/MSIE\s([^;]*)/); if (m && m[1]) { o.ie = numberify(m[1]); } else { // not opera, webkit, or ie m = ua.match(/Gecko\/([^\s]*)/); if (m) { o.gecko = 1; // Gecko detected, look for revision m = ua.match(/rv:([^\s\)]*)/); if (m && m[1]) { o.gecko = numberify(m[1]); } } } } } } //Check for known properties to tell if touch events are enabled on this device or if //the number of MSPointer touchpoints on this device is greater than 0. if (win && nav && !(o.chrome && o.chrome < 6)) { o.touchEnabled = (("ontouchstart" in win) || (("msMaxTouchPoints" in nav) && (nav.msMaxTouchPoints > 0))); } //It was a parsed UA, do not assign the global value. if (!subUA) { if (typeof process === 'object') { if (process.versions && process.versions.node) { //NodeJS o.os = process.platform; o.nodejs = numberify(process.versions.node); } } YUI.Env.UA = o; } return o; }; Y.UA = YUI.Env.UA || YUI.Env.parseUA(); /** Performs a simple comparison between two version numbers, accounting for standard versioning logic such as the fact that "535.8" is a lower version than "535.24", even though a simple numerical comparison would indicate that it's greater. Also accounts for cases such as "1.1" vs. "1.1.0", which are considered equivalent. Returns -1 if version _a_ is lower than version _b_, 0 if they're equivalent, 1 if _a_ is higher than _b_. Versions may be numbers or strings containing numbers and dots. For example, both `535` and `"535.8.10"` are acceptable. A version string containing non-numeric characters, like `"535.8.beta"`, may produce unexpected results. @method compareVersions @param {Number|String} a First version number to compare. @param {Number|String} b Second version number to compare. @return -1 if _a_ is lower than _b_, 0 if they're equivalent, 1 if _a_ is higher than _b_. **/ Y.UA.compareVersions = function (a, b) { var aPart, aParts, bPart, bParts, i, len; if (a === b) { return 0; } aParts = (a + '').split('.'); bParts = (b + '').split('.'); for (i = 0, len = Math.max(aParts.length, bParts.length); i < len; ++i) { aPart = parseInt(aParts[i], 10); bPart = parseInt(bParts[i], 10); isNaN(aPart) && (aPart = 0); isNaN(bPart) && (bPart = 0); if (aPart < bPart) { return -1; } if (aPart > bPart) { return 1; } } return 0; }; YUI.Env.aliases = { "anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"], "anim-shape-transform": ["anim-shape"], "app": ["app-base","app-content","app-transitions","lazy-model-list","model","model-list","model-sync-rest","router","view","view-node-map"], "attribute": ["attribute-base","attribute-complex"], "attribute-events": ["attribute-observable"], "autocomplete": ["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"], "base": ["base-base","base-pluginhost","base-build"], "cache": ["cache-base","cache-offline","cache-plugin"], "collection": ["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"], "color": ["color-base","color-hsl","color-harmony"], "controller": ["router"], "dataschema": ["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"], "datasource": ["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"], "datatable": ["datatable-core","datatable-table","datatable-head","datatable-body","datatable-base","datatable-column-widths","datatable-message","datatable-mutable","datatable-sort","datatable-datasource"], "datatable-deprecated": ["datatable-base-deprecated","datatable-datasource-deprecated","datatable-sort-deprecated","datatable-scroll-deprecated"], "datatype": ["datatype-date","datatype-number","datatype-xml"], "datatype-date": ["datatype-date-parse","datatype-date-format","datatype-date-math"], "datatype-number": ["datatype-number-parse","datatype-number-format"], "datatype-xml": ["datatype-xml-parse","datatype-xml-format"], "dd": ["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"], "dom": ["dom-base","dom-screen","dom-style","selector-native","selector"], "editor": ["frame","editor-selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"], "event": ["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside","event-touch","event-move","event-flick","event-valuechange","event-tap"], "event-custom": ["event-custom-base","event-custom-complex"], "event-gestures": ["event-flick","event-move"], "handlebars": ["handlebars-compiler"], "highlight": ["highlight-base","highlight-accentfold"], "history": ["history-base","history-hash","history-hash-ie","history-html5"], "io": ["io-base","io-xdr","io-form","io-upload-iframe","io-queue"], "json": ["json-parse","json-stringify"], "loader": ["loader-base","loader-rollup","loader-yui3"], "node": ["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"], "pluginhost": ["pluginhost-base","pluginhost-config"], "querystring": ["querystring-parse","querystring-stringify"], "recordset": ["recordset-base","recordset-sort","recordset-filter","recordset-indexer"], "resize": ["resize-base","resize-proxy","resize-constrain"], "slider": ["slider-base","slider-value-range","clickable-rail","range-slider"], "template": ["template-base","template-micro"], "text": ["text-accentfold","text-wordbreak"], "widget": ["widget-base","widget-htmlparser","widget-skin","widget-uievents"] }; }, '3.8.0pr2', {"use": ["get", "features", "intl-base", "yui-log", "yui-later"]}); YUI.add('get', function (Y, NAME) { /*jslint boss:true, expr:true, laxbreak: true */ /** Provides dynamic loading of remote JavaScript and CSS resources. @module get @class Get @static **/ var Lang = Y.Lang, CUSTOM_ATTRS, // defined lazily in Y.Get.Transaction._createNode() Get, Transaction; Y.Get = Get = { // -- Public Properties ---------------------------------------------------- /** Default options for CSS requests. Options specified here will override global defaults for CSS requests. See the `options` property for all available options. @property cssOptions @type Object @static @since 3.5.0 **/ cssOptions: { attributes: { rel: 'stylesheet' }, doc : Y.config.linkDoc || Y.config.doc, pollInterval: 50 }, /** Default options for JS requests. Options specified here will override global defaults for JS requests. See the `options` property for all available options. @property jsOptions @type Object @static @since 3.5.0 **/ jsOptions: { autopurge: true, doc : Y.config.scriptDoc || Y.config.doc }, /** Default options to use for all requests. Note that while all available options are documented here for ease of discovery, some options (like callback functions) only make sense at the transaction level. Callback functions specified via the options object or the `options` parameter of the `css()`, `js()`, or `load()` methods will receive the transaction object as a parameter. See `Y.Get.Transaction` for details on the properties and methods available on transactions. @static @since 3.5.0 @property {Object} options @property {Boolean} [options.async=false] Whether or not to load scripts asynchronously, meaning they're requested in parallel and execution order is not guaranteed. Has no effect on CSS, since CSS is always loaded asynchronously. @property {Object} [options.attributes] HTML attribute name/value pairs that should be added to inserted nodes. By default, the `charset` attribute will be set to "utf-8" and nodes will be given an auto-generated `id` attribute, but you can override these with your own values if desired. @property {Boolean} [options.autopurge] Whether or not to automatically purge inserted nodes after the purge threshold is reached. This is `true` by default for JavaScript, but `false` for CSS since purging a CSS node will also remove any styling applied by the referenced file. @property {Object} [options.context] `this` object to use when calling callback functions. Defaults to the transaction object. @property {Mixed} [options.data] Arbitrary data object to pass to "on*" callbacks. @property {Document} [options.doc] Document into which nodes should be inserted. By default, the current document is used. @property {HTMLElement|String} [options.insertBefore] HTML element or id string of an element before which all generated nodes should be inserted. If not specified, Get will automatically determine the best place to insert nodes for maximum compatibility. @property {Function} [options.onEnd] Callback to execute after a transaction is complete, regardless of whether it succeeded or failed. @property {Function} [options.onFailure] Callback to execute after a transaction fails, times out, or is aborted. @property {Function} [options.onProgress] Callback to execute after each individual request in a transaction either succeeds or fails. @property {Function} [options.onSuccess] Callback to execute after a transaction completes successfully with no errors. Note that in browsers that don't support the `error` event on CSS `<link>` nodes, a failed CSS request may still be reported as a success because in these browsers it can be difficult or impossible to distinguish between success and failure for CSS resources. @property {Function} [options.onTimeout] Callback to execute after a transaction times out. @property {Number} [options.pollInterval=50] Polling interval (in milliseconds) for detecting CSS load completion in browsers that don't support the `load` event on `<link>` nodes. This isn't used for JavaScript. @property {Number} [options.purgethreshold=20] Number of nodes to insert before triggering an automatic purge when `autopurge` is `true`. @property {Number} [options.timeout] Number of milliseconds to wait before aborting a transaction. When a timeout occurs, the `onTimeout` callback is called, followed by `onFailure` and finally `onEnd`. By default, there is no timeout. @property {String} [options.type] Resource type ("css" or "js"). This option is set automatically by the `css()` and `js()` functions and will be ignored there, but may be useful when using the `load()` function. If not specified, the type will be inferred from the URL, defaulting to "js" if the URL doesn't contain a recognizable file extension. **/ options: { attributes: { charset: 'utf-8' }, purgethreshold: 20 }, // -- Protected Properties ------------------------------------------------- /** Regex that matches a CSS URL. Used to guess the file type when it's not specified. @property REGEX_CSS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_CSS: /\.css(?:[?;].*)?$/i, /** Regex that matches a JS URL. Used to guess the file type when it's not specified. @property REGEX_JS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_JS : /\.js(?:[?;].*)?$/i, /** Contains information about the current environment, such as what script and link injection features it supports. This object is created and populated the first time the `_getEnv()` method is called. @property _env @type Object @protected @static @since 3.5.0 **/ /** Mapping of document _yuid strings to <head> or <base> node references so we don't have to look the node up each time we want to insert a request node. @property _insertCache @type Object @protected @static @since 3.5.0 **/ _insertCache: {}, /** Information about the currently pending transaction, if any. This is actually an object with two properties: `callback`, containing the optional callback passed to `css()`, `load()`, or `js()`; and `transaction`, containing the actual transaction instance. @property _pending @type Object @protected @static @since 3.5.0 **/ _pending: null, /** HTML nodes eligible to be purged next time autopurge is triggered. @property _purgeNodes @type HTMLElement[] @protected @static @since 3.5.0 **/ _purgeNodes: [], /** Queued transactions and associated callbacks. @property _queue @type Object[] @protected @static @since 3.5.0 **/ _queue: [], // -- Public Methods ------------------------------------------------------- /** Aborts the specified transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). *Note:* This method is deprecated as of 3.5.0, and will be removed in a future version of YUI. Use the transaction-level `abort()` method instead. @method abort @param {Get.Transaction} transaction Transaction to abort. @deprecated Use the `abort()` method on the transaction instead. @static **/ abort: function (transaction) { var i, id, item, len, pending; if (!transaction.abort) { id = transaction; pending = this._pending; transaction = null; if (pending && pending.transaction.id === id) { transaction = pending.transaction; this._pending = null; } else { for (i = 0, len = this._queue.length; i < len; ++i) { item = this._queue[i].transaction; if (item.id === id) { transaction = item; this._queue.splice(i, 1); break; } } } } transaction && transaction.abort(); }, /** Loads one or more CSS files. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. @example // Load a single CSS file and log a message on completion. Y.Get.css('foo.css', function (err) { if (err) { } else { } }); // Load multiple CSS files and log a message when all have finished // loading. var urls = ['foo.css', 'http://example.com/bar.css', 'baz/quux.css']; Y.Get.css(urls, function (err) { if (err) { } else { } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.css(urls, { attributes: {'class': 'my-css'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.css([ {url: 'foo.css', attributes: {id: 'foo'}}, {url: 'bar.css', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method css @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @static **/ css: function (urls, options, callback) { return this._load('css', urls, options, callback); }, /** Loads one or more JavaScript resources. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. Scripts will be executed in the order they're specified unless the `async` option is `true`, in which case they'll be loaded in parallel and executed in whatever order they finish loading. @example // Load a single JS file and log a message on completion. Y.Get.js('foo.js', function (err) { if (err) { } else { } }); // Load multiple JS files, execute them in order, and log a message when // all have finished loading. var urls = ['foo.js', 'http://example.com/bar.js', 'baz/quux.js']; Y.Get.js(urls, function (err) { if (err) { } else { } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.js(urls, { attributes: {'class': 'my-js'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.js([ {url: 'foo.js', attributes: {id: 'foo'}}, {url: 'bar.js', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method js @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ js: function (urls, options, callback) { return this._load('js', urls, options, callback); }, /** Loads one or more CSS and/or JavaScript resources in the same transaction. Use this method when you want to load both CSS and JavaScript in a single transaction and be notified when all requested URLs have finished loading, regardless of type. Behavior and options are the same as for the `css()` and `js()` methods. If a resource type isn't specified in per-request options or transaction-level options, Get will guess the file type based on the URL's extension (`.css` or `.js`, with or without a following query string). If the file type can't be guessed from the URL, a warning will be logged and Get will assume the URL is a JavaScript resource. @example // Load both CSS and JS files in a single transaction, and log a message // when all files have finished loading. Y.Get.load(['foo.css', 'bar.js', 'baz.css'], function (err) { if (err) { } else { } }); @method load @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ load: function (urls, options, callback) { return this._load(null, urls, options, callback); }, // -- Protected Methods ---------------------------------------------------- /** Triggers an automatic purge if the purge threshold has been reached. @method _autoPurge @param {Number} threshold Purge threshold to use, in milliseconds. @protected @since 3.5.0 @static **/ _autoPurge: function (threshold) { if (threshold && this._purgeNodes.length >= threshold) { this._purge(this._purgeNodes); } }, /** Populates the `_env` property with information about the current environment. @method _getEnv @return {Object} Environment information. @protected @since 3.5.0 @static **/ _getEnv: function () { var doc = Y.config.doc, ua = Y.UA; // Note: some of these checks require browser sniffs since it's not // feasible to load test files on every pageview just to perform a // feature test. I'm sorry if this makes you sad. return (this._env = { // True if this is a browser that supports disabling async mode on // dynamically created script nodes. See // https://developer.mozilla.org/En/HTML/Element/Script#Attributes // IE10 doesn't return true for the MDN feature test, so setting it explicitly, // because it is async by default, and allows you to disable async by setting it to false async: (doc && doc.createElement('script').async === true) || (ua.ie >= 10), // True if this browser fires an event when a dynamically injected // link node fails to load. This is currently true for Firefox 9+ // and WebKit 535.24+ cssFail: ua.gecko >= 9 || ua.compareVersions(ua.webkit, 535.24) >= 0, // True if this browser fires an event when a dynamically injected // link node finishes loading. This is currently true for IE, Opera, // Firefox 9+, and WebKit 535.24+. Note that IE versions <9 fire the // DOM 0 "onload" event, but not "load". All versions of IE fire // "onload". // davglass: Seems that Chrome on Android needs this to be false. cssLoad: ( (!ua.gecko && !ua.webkit) || ua.gecko >= 9 || ua.compareVersions(ua.webkit, 535.24) >= 0 ) && !(ua.chrome && ua.chrome <= 18), // True if this browser preserves script execution order while // loading scripts in parallel as long as the script node's `async` // attribute is set to false to explicitly disable async execution. preservesScriptOrder: !!(ua.gecko || ua.opera || (ua.ie && ua.ie >= 10)) }); }, _getTransaction: function (urls, options) { var requests = [], i, len, req, url; if (!Lang.isArray(urls)) { urls = [urls]; } options = Y.merge(this.options, options); // Clone the attributes object so we don't end up modifying it by ref. options.attributes = Y.merge(this.options.attributes, options.attributes); for (i = 0, len = urls.length; i < len; ++i) { url = urls[i]; req = {attributes: {}}; // If `url` is a string, we create a URL object for it, then mix in // global options and request-specific options. If it's an object // with a "url" property, we assume it's a request object containing // URL-specific options. if (typeof url === 'string') { req.url = url; } else if (url.url) { // URL-specific options override both global defaults and // request-specific options. Y.mix(req, url, false, null, 0, true); url = url.url; // Make url a string so we can use it later. } else { continue; } Y.mix(req, options, false, null, 0, true); // If we didn't get an explicit type for this URL either in the // request options or the URL-specific options, try to determine // one from the file extension. if (!req.type) { if (this.REGEX_CSS.test(url)) { req.type = 'css'; } else { if (!this.REGEX_JS.test(url)) { } req.type = 'js'; } } // Mix in type-specific default options, but don't overwrite any // options that have already been set. Y.mix(req, req.type === 'js' ? this.jsOptions : this.cssOptions, false, null, 0, true); // Give the node an id attribute if it doesn't already have one. req.attributes.id || (req.attributes.id = Y.guid()); // Backcompat for <3.5.0 behavior. if (req.win) { req.doc = req.win.document; } else { req.win = req.doc.defaultView || req.doc.parentWindow; } if (req.charset) { req.attributes.charset = req.charset; } requests.push(req); } return new Transaction(requests, options); }, _load: function (type, urls, options, callback) { var transaction; // Allow callback as third param. if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); options.type = type; options._onFinish = Get._onTransactionFinish; if (!this._env) { this._getEnv(); } transaction = this._getTransaction(urls, options); this._queue.push({ callback : callback, transaction: transaction }); this._next(); return transaction; }, _onTransactionFinish : function() { Get._pending = null; Get._next(); }, _next: function () { var item; if (this._pending) { return; } item = this._queue.shift(); if (item) { this._pending = item; item.transaction.execute(item.callback); } }, _purge: function (nodes) { var purgeNodes = this._purgeNodes, isTransaction = nodes !== purgeNodes, index, node; while (node = nodes.pop()) { // assignment // Don't purge nodes that haven't finished loading (or errored out), // since this can hang the transaction. if (!node._yuiget_finished) { continue; } node.parentNode && node.parentNode.removeChild(node); // If this is a transaction-level purge and this node also exists in // the Get-level _purgeNodes array, we need to remove it from // _purgeNodes to avoid creating a memory leak. The indexOf lookup // sucks, but until we get WeakMaps, this is the least troublesome // way to do this (we can't just hold onto node ids because they may // not be in the same document). if (isTransaction) { index = Y.Array.indexOf(purgeNodes, node); if (index > -1) { purgeNodes.splice(index, 1); } } } } }; /** Alias for `js()`. @method script @static **/ Get.script = Get.js; /** Represents a Get transaction, which may contain requests for one or more JS or CSS files. This class should not be instantiated manually. Instances will be created and returned as needed by Y.Get's `css()`, `js()`, and `load()` methods. @class Get.Transaction @constructor @since 3.5.0 **/ Get.Transaction = Transaction = function (requests, options) { var self = this; self.id = Transaction._lastId += 1; self.data = options.data; self.errors = []; self.nodes = []; self.options = options; self.requests = requests; self._callbacks = []; // callbacks to call after execution finishes self._queue = []; self._reqsWaiting = 0; // Deprecated pre-3.5.0 properties. self.tId = self.id; // Use `id` instead. self.win = options.win || Y.config.win; }; /** Arbitrary data object associated with this transaction. This object comes from the options passed to `Get.css()`, `Get.js()`, or `Get.load()`, and will be `undefined` if no data object was specified. @property {Object} data **/ /** Array of errors that have occurred during this transaction, if any. @since 3.5.0 @property {Object[]} errors @property {String} errors.error Error message. @property {Object} errors.request Request object related to the error. **/ /** Numeric id for this transaction, unique among all transactions within the same YUI sandbox in the current pageview. @property {Number} id @since 3.5.0 **/ /** HTMLElement nodes (native ones, not YUI Node instances) that have been inserted during the current transaction. @property {HTMLElement[]} nodes **/ /** Options associated with this transaction. See `Get.options` for the full list of available options. @property {Object} options @since 3.5.0 **/ /** Request objects contained in this transaction. Each request object represents one CSS or JS URL that will be (or has been) requested and loaded into the page. @property {Object} requests @since 3.5.0 **/ /** Id of the most recent transaction. @property _lastId @type Number @protected @static **/ Transaction._lastId = 0; Transaction.prototype = { // -- Public Properties ---------------------------------------------------- /** Current state of this transaction. One of "new", "executing", or "done". @property _state @type String @protected **/ _state: 'new', // "new", "executing", or "done" // -- Public Methods ------------------------------------------------------- /** Aborts this transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). @method abort @param {String} [msg="Aborted."] Optional message to use in the `errors` array describing why the transaction was aborted. **/ abort: function (msg) { this._pending = null; this._pendingCSS = null; this._pollTimer = clearTimeout(this._pollTimer); this._queue = []; this._reqsWaiting = 0; this.errors.push({error: msg || 'Aborted'}); this._finish(); }, /** Begins execting the transaction. There's usually no reason to call this manually, since Get will call it automatically when other pending transactions have finished. If you really want to execute your transaction before Get does, you can, but be aware that this transaction's scripts may end up executing before the scripts in other pending transactions. If the transaction is already executing, the specified callback (if any) will be queued and called after execution finishes. If the transaction has already finished, the callback will be called immediately (the transaction will not be executed again). @method execute @param {Function} callback Callback function to execute after all requests in the transaction are complete, or after the transaction is aborted. **/ execute: function (callback) { var self = this, requests = self.requests, state = self._state, i, len, queue, req; if (state === 'done') { callback && callback(self.errors.length ? self.errors : null, self); return; } else { callback && self._callbacks.push(callback); if (state === 'executing') { return; } } self._state = 'executing'; self._queue = queue = []; if (self.options.timeout) { self._timeout = setTimeout(function () { self.abort('Timeout'); }, self.options.timeout); } self._reqsWaiting = requests.length; for (i = 0, len = requests.length; i < len; ++i) { req = requests[i]; if (req.async || req.type === 'css') { // No need to queue CSS or fully async JS. self._insert(req); } else { queue.push(req); } } self._next(); }, /** Manually purges any `<script>` or `<link>` nodes this transaction has created. Be careful when purging a transaction that contains CSS requests, since removing `<link>` nodes will also remove any styles they applied. @method purge **/ purge: function () { Get._purge(this.nodes); }, // -- Protected Methods ---------------------------------------------------- _createNode: function (name, attrs, doc) { var node = doc.createElement(name), attr, testEl; if (!CUSTOM_ATTRS) { // IE6 and IE7 expect property names rather than attribute names for // certain attributes. Rather than sniffing, we do a quick feature // test the first time _createNode() runs to determine whether we // need to provide a workaround. testEl = doc.createElement('div'); testEl.setAttribute('class', 'a'); CUSTOM_ATTRS = testEl.className === 'a' ? {} : { 'for' : 'htmlFor', 'class': 'className' }; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { node.setAttribute(CUSTOM_ATTRS[attr] || attr, attrs[attr]); } } return node; }, _finish: function () { var errors = this.errors.length ? this.errors : null, options = this.options, thisObj = options.context || this, data, i, len; if (this._state === 'done') { return; } this._state = 'done'; for (i = 0, len = this._callbacks.length; i < len; ++i) { this._callbacks[i].call(thisObj, errors, this); } data = this._getEventData(); if (errors) { if (options.onTimeout && errors[errors.length - 1].error === 'Timeout') { options.onTimeout.call(thisObj, data); } if (options.onFailure) { options.onFailure.call(thisObj, data); } } else if (options.onSuccess) { options.onSuccess.call(thisObj, data); } if (options.onEnd) { options.onEnd.call(thisObj, data); } if (options._onFinish) { options._onFinish(); } }, _getEventData: function (req) { if (req) { // This merge is necessary for backcompat. I hate it. return Y.merge(this, { abort : this.abort, // have to copy these because the prototype isn't preserved purge : this.purge, request: req, url : req.url, win : req.win }); } else { return this; } }, _getInsertBefore: function (req) { var doc = req.doc, el = req.insertBefore, cache, cachedNode, docStamp; if (el) { return typeof el === 'string' ? doc.getElementById(el) : el; } cache = Get._insertCache; docStamp = Y.stamp(doc); if ((el = cache[docStamp])) { // assignment return el; } // Inserting before a <base> tag apparently works around an IE bug // (according to a comment from pre-3.5.0 Y.Get), but I'm not sure what // bug that is, exactly. Better safe than sorry? if ((el = doc.getElementsByTagName('base')[0])) { // assignment return (cache[docStamp] = el); } // Look for a <head> element. el = doc.head || doc.getElementsByTagName('head')[0]; if (el) { // Create a marker node at the end of <head> to use as an insertion // point. Inserting before this node will ensure that all our CSS // gets inserted in the correct order, to maintain style precedence. el.appendChild(doc.createTextNode('')); return (cache[docStamp] = el.lastChild); } // If all else fails, just insert before the first script node on the // page, which is virtually guaranteed to exist. return (cache[docStamp] = doc.getElementsByTagName('script')[0]); }, _insert: function (req) { var env = Get._env, insertBefore = this._getInsertBefore(req), isScript = req.type === 'js', node = req.node, self = this, ua = Y.UA, cssTimeout, nodeType; if (!node) { if (isScript) { nodeType = 'script'; } else if (!env.cssLoad && ua.gecko) { nodeType = 'style'; } else { nodeType = 'link'; } node = req.node = this._createNode(nodeType, req.attributes, req.doc); } function onError() { self._progress('Failed to load ' + req.url, req); } function onLoad() { if (cssTimeout) { clearTimeout(cssTimeout); } self._progress(null, req); } // Deal with script asynchronicity. if (isScript) { node.setAttribute('src', req.url); if (req.async) { // Explicitly indicate that we want the browser to execute this // script asynchronously. This is necessary for older browsers // like Firefox <4. node.async = true; } else { if (env.async) { // This browser treats injected scripts as async by default // (standard HTML5 behavior) but asynchronous loading isn't // desired, so tell the browser not to mark this script as // async. node.async = false; } // If this browser doesn't preserve script execution order based // on insertion order, we'll need to avoid inserting other // scripts until this one finishes loading. if (!env.preservesScriptOrder) { this._pending = req; } } } else { if (!env.cssLoad && ua.gecko) { // In Firefox <9, we can import the requested URL into a <style> // node and poll for the existence of node.sheet.cssRules. This // gives us a reliable way to determine CSS load completion that // also works for cross-domain stylesheets. // // Props to Zach Leatherman for calling my attention to this // technique. node.innerHTML = (req.attributes.charset ? '@charset "' + req.attributes.charset + '";' : '') + '@import "' + req.url + '";'; } else { node.setAttribute('href', req.url); } } // Inject the node. if (isScript && ua.ie && (ua.ie < 9 || (document.documentMode && document.documentMode < 9))) { // Script on IE < 9, and IE 9+ when in IE 8 or older modes, including quirks mode. node.onreadystatechange = function () { if (/loaded|complete/.test(node.readyState)) { node.onreadystatechange = null; onLoad(); } }; } else if (!isScript && !env.cssLoad) { // CSS on Firefox <9 or WebKit. this._poll(req); } else { // Script or CSS on everything else. Using DOM 0 events because that // evens the playing field with older IEs. if (ua.ie >= 10) { // We currently need to introduce a timeout for IE10, since it // calls onerror/onload synchronously for 304s - messing up existing // program flow. // Remove this block if the following bug gets fixed by GA // https://connect.microsoft.com/IE/feedback/details/763871/dynamically-loaded-scripts-with-304s-responses-interrupt-the-currently-executing-js-thread-onload node.onerror = function() { setTimeout(onError, 0); }; node.onload = function() { setTimeout(onLoad, 0); }; } else { node.onerror = onError; node.onload = onLoad; } // If this browser doesn't fire an event when CSS fails to load, // fail after a timeout to avoid blocking the transaction queue. if (!env.cssFail && !isScript) { cssTimeout = setTimeout(onError, req.timeout || 3000); } } this.nodes.push(node); insertBefore.parentNode.insertBefore(node, insertBefore); }, _next: function () { if (this._pending) { return; } // If there are requests in the queue, insert the next queued request. // Otherwise, if we're waiting on already-inserted requests to finish, // wait longer. If there are no queued requests and we're not waiting // for anything to load, then we're done! if (this._queue.length) { this._insert(this._queue.shift()); } else if (!this._reqsWaiting) { this._finish(); } }, _poll: function (newReq) { var self = this, pendingCSS = self._pendingCSS, isWebKit = Y.UA.webkit, i, hasRules, j, nodeHref, req, sheets; if (newReq) { pendingCSS || (pendingCSS = self._pendingCSS = []); pendingCSS.push(newReq); if (self._pollTimer) { // A poll timeout is already pending, so no need to create a // new one. return; } } self._pollTimer = null; // Note: in both the WebKit and Gecko hacks below, a CSS URL that 404s // will still be treated as a success. There's no good workaround for // this. for (i = 0; i < pendingCSS.length; ++i) { req = pendingCSS[i]; if (isWebKit) { // Look for a stylesheet matching the pending URL. sheets = req.doc.styleSheets; j = sheets.length; nodeHref = req.node.href; while (--j >= 0) { if (sheets[j].href === nodeHref) { pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); break; } } } else { // Many thanks to Zach Leatherman for calling my attention to // the @import-based cross-domain technique used here, and to // Oleg Slobodskoi for an earlier same-domain implementation. // // See Zach's blog for more details: // http://www.zachleat.com/web/2010/07/29/load-css-dynamically/ try { // We don't really need to store this value since we never // use it again, but if we don't store it, Closure Compiler // assumes the code is useless and removes it. hasRules = !!req.node.sheet.cssRules; // If we get here, the stylesheet has loaded. pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); } catch (ex) { // An exception means the stylesheet is still loading. } } } if (pendingCSS.length) { self._pollTimer = setTimeout(function () { self._poll.call(self); }, self.options.pollInterval); } }, _progress: function (err, req) { var options = this.options; if (err) { req.error = err; this.errors.push({ error : err, request: req }); } req.node._yuiget_finished = req.finished = true; if (options.onProgress) { options.onProgress.call(options.context || this, this._getEventData(req)); } if (req.autopurge) { // Pre-3.5.0 Get always excludes the most recent node from an // autopurge. I find this odd, but I'm keeping that behavior for // the sake of backcompat. Get._autoPurge(this.options.purgethreshold); Get._purgeNodes.push(req.node); } if (this._pending === req) { this._pending = null; } this._reqsWaiting -= 1; this._next(); } }; }, '3.8.0pr2', {"requires": ["yui-base"]}); YUI.add('features', function (Y, NAME) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by src/loader/scripts/meta_join.js */ var add = Y.Features.add; // app-transitions-native add('load', '0', { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return false; }, "trigger": "app-transitions" }); // autocomplete-list-keys add('load', '1', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // dd-gestures add('load', '2', { "name": "dd-gestures", "trigger": "dd-drag", "ua": "touchEnabled" }); // dom-style-ie add('load', '3', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // editor-para-ie add('load', '4', { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }); // event-base-ie add('load', '5', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // graphics-canvas add('load', '6', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-canvas-default add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-svg add('load', '8', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-svg-default add('load', '9', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-vml add('load', '10', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // graphics-vml-default add('load', '11', { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // history-hash-ie add('load', '12', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); // io-nodejs add('load', '13', { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }); // scrollview-base-ie add('load', '14', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // selector-css2 add('load', '15', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // transition-timer add('load', '16', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return ret; }, "trigger": "transition" }); // widget-base-ie add('load', '17', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // yql-nodejs add('load', '18', { "name": "yql-nodejs", "trigger": "yql", "ua": "nodejs", "when": "after" }); // yql-winjs add('load', '19', { "name": "yql-winjs", "trigger": "yql", "ua": "winjs", "when": "after" }); }, '3.8.0pr2', {"requires": ["yui-base"]}); YUI.add('intl-base', function (Y, NAME) { /** * The Intl utility provides a central location for managing sets of * localized resources (strings and formatting patterns). * * @class Intl * @uses EventTarget * @static */ var SPLIT_REGEX = /[, ]/; Y.mix(Y.namespace('Intl'), { /** * Returns the language among those available that * best matches the preferred language list, using the Lookup * algorithm of BCP 47. * If none of the available languages meets the user's preferences, * then "" is returned. * Extended language ranges are not supported. * * @method lookupBestLang * @param {String[] | String} preferredLanguages The list of preferred * languages in descending preference order, represented as BCP 47 * language tags. A string array or a comma-separated list. * @param {String[]} availableLanguages The list of languages * that the application supports, represented as BCP 47 language * tags. * * @return {String} The available language that best matches the * preferred language list, or "". * @since 3.1.0 */ lookupBestLang: function(preferredLanguages, availableLanguages) { var i, language, result, index; // check whether the list of available languages contains language; // if so return it function scan(language) { var i; for (i = 0; i < availableLanguages.length; i += 1) { if (language.toLowerCase() === availableLanguages[i].toLowerCase()) { return availableLanguages[i]; } } } if (Y.Lang.isString(preferredLanguages)) { preferredLanguages = preferredLanguages.split(SPLIT_REGEX); } for (i = 0; i < preferredLanguages.length; i += 1) { language = preferredLanguages[i]; if (!language || language === '*') { continue; } // check the fallback sequence for one language while (language.length > 0) { result = scan(language); if (result) { return result; } else { index = language.lastIndexOf('-'); if (index >= 0) { language = language.substring(0, index); // one-character subtags get cut along with the // following subtag if (index >= 2 && language.charAt(index - 2) === '-') { language = language.substring(0, index - 2); } } else { // nothing available for this language break; } } } } return ''; } }); }, '3.8.0pr2', {"requires": ["yui-base"]}); YUI.add('yui-log', function (Y, NAME) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 1, warn: 1, error: 1 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters src = src || ""; if (typeof src !== "undefined") { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console != UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera != UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher == Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '3.8.0pr2', {"requires": ["yui-base"]}); YUI.add('yui-later', function (Y, NAME) { /** * Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module, <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-later */ var NO_ARGS = []; /** * Executes the supplied function in the context of the supplied * object 'when' milliseconds later. Executes the function a * single time unless periodic is set to true. * @for YUI * @method later * @param when {int} the number of milliseconds to wait until the fn * is executed. * @param o the context object. * @param fn {Function|String} the function to execute or the name of * the method in the 'o' object to execute. * @param data [Array] data that is provided to the function. This * accepts either a single item or an array. If an array is provided, * the function is executed with one parameter for each array item. * If you need to pass a single array parameter, it needs to be wrapped * in an array [myarray]. * * Note: native methods in IE may not have the call and apply methods. * In this case, it will work, but you are limited to four arguments. * * @param periodic {boolean} if true, executes continuously at supplied * interval until canceled. * @return {object} a timer object. Call the cancel() method on this * object to stop the timer. */ Y.later = function(when, o, fn, data, periodic) { when = when || 0; data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : NO_ARGS; o = o || Y.config.win || Y; var cancelled = false, method = (o && Y.Lang.isString(fn)) ? o[fn] : fn, wrapper = function() { // IE 8- may execute a setInterval callback one last time // after clearInterval was called, so in order to preserve // the cancel() === no more runny-run, we have to jump through // an extra hoop. if (!cancelled) { if (!method.apply) { method(data[0], data[1], data[2], data[3]); } else { method.apply(o, data || NO_ARGS); } } }, id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when); return { id: id, interval: periodic, cancel: function() { cancelled = true; if (this.interval) { clearInterval(id); } else { clearTimeout(id); } } }; }; Y.Lang.later = Y.later; }, '3.8.0pr2', {"requires": ["yui-base"]}); YUI.add('yui', function (Y, NAME) {}, '3.8.0pr2', {"use": ["get", "features", "intl-base", "yui-log", "yui-later"]}); YUI.add('oop', function (Y, NAME) { /** Adds object inheritance and manipulation utilities to the YUI instance. This module is required by most YUI components. @module oop **/ var L = Y.Lang, A = Y.Array, OP = Object.prototype, CLONE_MARKER = '_~yuim~_', hasOwn = OP.hasOwnProperty, toString = OP.toString; function dispatch(o, f, c, proto, action) { if (o && o[action] && o !== Y) { return o[action].call(o, f, c); } else { switch (A.test(o)) { case 1: return A[action](o, f, c); case 2: return A[action](Y.Array(o, 0, true), f, c); default: return Y.Object[action](o, f, c, proto); } } } /** Augments the _receiver_ with prototype properties from the _supplier_. The receiver may be a constructor function or an object. The supplier must be a constructor function. If the _receiver_ is an object, then the _supplier_ constructor will be called immediately after _receiver_ is augmented, with _receiver_ as the `this` object. If the _receiver_ is a constructor function, then all prototype methods of _supplier_ that are copied to _receiver_ will be sequestered, and the _supplier_ constructor will not be called immediately. The first time any sequestered method is called on the _receiver_'s prototype, all sequestered methods will be immediately copied to the _receiver_'s prototype, the _supplier_'s constructor will be executed, and finally the newly unsequestered method that was called will be executed. This sequestering logic sounds like a bunch of complicated voodoo, but it makes it cheap to perform frequent augmentation by ensuring that suppliers' constructors are only called if a supplied method is actually used. If none of the supplied methods is ever used, then there's no need to take the performance hit of calling the _supplier_'s constructor. @method augment @param {Function|Object} receiver Object or function to be augmented. @param {Function} supplier Function that supplies the prototype properties with which to augment the _receiver_. @param {Boolean} [overwrite=false] If `true`, properties already on the receiver will be overwritten if found on the supplier's prototype. @param {String[]} [whitelist] An array of property names. If specified, only the whitelisted prototype properties will be applied to the receiver, and all others will be ignored. @param {Array|any} [args] Argument or array of arguments to pass to the supplier's constructor when initializing. @return {Function} Augmented object. @for YUI **/ Y.augment = function (receiver, supplier, overwrite, whitelist, args) { var rProto = receiver.prototype, sequester = rProto && supplier, sProto = supplier.prototype, to = rProto || receiver, copy, newPrototype, replacements, sequestered, unsequester; args = args ? Y.Array(args) : []; if (sequester) { newPrototype = {}; replacements = {}; sequestered = {}; copy = function (value, key) { if (overwrite || !(key in rProto)) { if (toString.call(value) === '[object Function]') { sequestered[key] = value; newPrototype[key] = replacements[key] = function () { return unsequester(this, value, arguments); }; } else { newPrototype[key] = value; } } }; unsequester = function (instance, fn, fnArgs) { // Unsequester all sequestered functions. for (var key in sequestered) { if (hasOwn.call(sequestered, key) && instance[key] === replacements[key]) { instance[key] = sequestered[key]; } } // Execute the supplier constructor. supplier.apply(instance, args); // Finally, execute the original sequestered function. return fn.apply(instance, fnArgs); }; if (whitelist) { Y.Array.each(whitelist, function (name) { if (name in sProto) { copy(sProto[name], name); } }); } else { Y.Object.each(sProto, copy, null, true); } } Y.mix(to, newPrototype || sProto, overwrite, whitelist); if (!sequester) { supplier.apply(to, args); } return receiver; }; /** * Copies object properties from the supplier to the receiver. If the target has * the property, and the property is an object, the target object will be * augmented with the supplier's value. * * @method aggregate * @param {Object} receiver Object to receive the augmentation. * @param {Object} supplier Object that supplies the properties with which to * augment the receiver. * @param {Boolean} [overwrite=false] If `true`, properties already on the receiver * will be overwritten if found on the supplier. * @param {String[]} [whitelist] Whitelist. If supplied, only properties in this * list will be applied to the receiver. * @return {Object} Augmented object. */ Y.aggregate = function(r, s, ov, wl) { return Y.mix(r, s, ov, wl, 0, true); }; /** * Utility to set up the prototype, constructor and superclass properties to * support an inheritance strategy that can chain constructors and methods. * Static members will not be inherited. * * @method extend * @param {function} r the object to modify. * @param {function} s the object to inherit. * @param {object} px prototype properties to add/override. * @param {object} sx static properties to add/override. * @return {object} the extended object. */ Y.extend = function(r, s, px, sx) { if (!s || !r) { Y.error('extend failed, verify dependencies'); } var sp = s.prototype, rp = Y.Object(sp); r.prototype = rp; rp.constructor = r; r.superclass = sp; // assign constructor property if (s != Object && sp.constructor == OP.constructor) { sp.constructor = s; } // add prototype overrides if (px) { Y.mix(rp, px, true); } // add object overrides if (sx) { Y.mix(r, sx, true); } return r; }; /** * Executes the supplied function for each item in * a collection. Supports arrays, objects, and * NodeLists * @method each * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {YUI} the YUI instance. */ Y.each = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'each'); }; /** * Executes the supplied function for each item in * a collection. The operation stops if the function * returns true. Supports arrays, objects, and * NodeLists. * @method some * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {boolean} true if the function ever returns true, * false otherwise. */ Y.some = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'some'); }; /** * Deep object/array copy. Function clones are actually * wrappers around the original function. * Array-like objects are treated as arrays. * Primitives are returned untouched. Optionally, a * function can be provided to handle other data types, * filter keys, validate values, etc. * * NOTE: Cloning a non-trivial object is a reasonably heavy operation, due to * the need to recurrsively iterate down non-primitive properties. Clone * should be used only when a deep clone down to leaf level properties * is explicitly required. * * In many cases (for example, when trying to isolate objects used as * hashes for configuration properties), a shallow copy, using Y.merge is * normally sufficient. If more than one level of isolation is required, * Y.merge can be used selectively at each level which needs to be * isolated from the original without going all the way to leaf properties. * * @method clone * @param {object} o what to clone. * @param {boolean} safe if true, objects will not have prototype * items from the source. If false, they will. In this case, the * original is initially protected, but the clone is not completely * immune from changes to the source object prototype. Also, cloned * prototype items that are deleted from the clone will result * in the value of the source prototype being exposed. If operating * on a non-safe clone, items should be nulled out rather than deleted. * @param {function} f optional function to apply to each item in a * collection; it will be executed prior to applying the value to * the new object. Return false to prevent the copy. * @param {object} c optional execution context for f. * @param {object} owner Owner object passed when clone is iterating * an object. Used to set up context for cloned functions. * @param {object} cloned hash of previously cloned objects to avoid * multiple clones. * @return {Array|Object} the cloned object. */ Y.clone = function(o, safe, f, c, owner, cloned) { if (!L.isObject(o)) { return o; } // @todo cloning YUI instances doesn't currently work if (Y.instanceOf(o, YUI)) { return o; } var o2, marked = cloned || {}, stamp, yeach = Y.each; switch (L.type(o)) { case 'date': return new Date(o); case 'regexp': // if we do this we need to set the flags too // return new RegExp(o.source); return o; case 'function': // o2 = Y.bind(o, owner); // break; return o; case 'array': o2 = []; break; default: // #2528250 only one clone of a given object should be created. if (o[CLONE_MARKER]) { return marked[o[CLONE_MARKER]]; } stamp = Y.guid(); o2 = (safe) ? {} : Y.Object(o); o[CLONE_MARKER] = stamp; marked[stamp] = o; } // #2528250 don't try to clone element properties if (!o.addEventListener && !o.attachEvent) { yeach(o, function(v, k) { if ((k || k === 0) && (!f || (f.call(c || this, v, k, this, o) !== false))) { if (k !== CLONE_MARKER) { if (k == 'prototype') { // skip the prototype // } else if (o[k] === o) { // this[k] = this; } else { this[k] = Y.clone(v, safe, f, c, owner || o, marked); } } } }, o2); } if (!cloned) { Y.Object.each(marked, function(v, k) { if (v[CLONE_MARKER]) { try { delete v[CLONE_MARKER]; } catch (e) { v[CLONE_MARKER] = null; } } }, this); marked = null; } return o2; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the beginning of the arguments collection the * supplied to the function. * * @method bind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to include before the arguments the * function is executed with. * @return {function} the wrapped function. */ Y.bind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? xargs.concat(Y.Array(arguments, 0, true)) : arguments; return fn.apply(c || fn, args); }; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the end of the arguments the function * is executed with. * * @method rbind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to append to the end of * arguments collection supplied to the function. * @return {function} the wrapped function. */ Y.rbind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? Y.Array(arguments, 0, true).concat(xargs) : arguments; return fn.apply(c || fn, args); }; }; }, '3.8.0pr2', {"requires": ["yui-base"]}); YUI.add('features', function (Y, NAME) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by src/loader/scripts/meta_join.js */ var add = Y.Features.add; // app-transitions-native add('load', '0', { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return false; }, "trigger": "app-transitions" }); // autocomplete-list-keys add('load', '1', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // dd-gestures add('load', '2', { "name": "dd-gestures", "trigger": "dd-drag", "ua": "touchEnabled" }); // dom-style-ie add('load', '3', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // editor-para-ie add('load', '4', { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }); // event-base-ie add('load', '5', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // graphics-canvas add('load', '6', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-canvas-default add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-svg add('load', '8', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-svg-default add('load', '9', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-vml add('load', '10', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // graphics-vml-default add('load', '11', { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // history-hash-ie add('load', '12', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); // io-nodejs add('load', '13', { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }); // scrollview-base-ie add('load', '14', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // selector-css2 add('load', '15', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // transition-timer add('load', '16', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return ret; }, "trigger": "transition" }); // widget-base-ie add('load', '17', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // yql-nodejs add('load', '18', { "name": "yql-nodejs", "trigger": "yql", "ua": "nodejs", "when": "after" }); // yql-winjs add('load', '19', { "name": "yql-winjs", "trigger": "yql", "ua": "winjs", "when": "after" }); }, '3.8.0pr2', {"requires": ["yui-base"]}); YUI.add('dom-core', function (Y, NAME) { var NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', PARENT_WINDOW = 'parentWindow', TAG_NAME = 'tagName', PARENT_NODE = 'parentNode', PREVIOUS_SIBLING = 'previousSibling', NEXT_SIBLING = 'nextSibling', CONTAINS = 'contains', COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', EMPTY_ARRAY = [], // IE < 8 throws on node.contains(textNode) supportsContainsTextNode = (function() { var node = Y.config.doc.createElement('div'), textNode = node.appendChild(Y.config.doc.createTextNode('')), result = false; try { result = node.contains(textNode); } catch(e) {} return result; })(), /** * The DOM utility provides a cross-browser abtraction layer * normalizing DOM tasks, and adds extra helper functionality * for other common tasks. * @module dom * @main dom * @submodule dom-base * @for DOM * */ /** * Provides DOM helper methods. * @class DOM * */ Y_DOM = { /** * Returns the HTMLElement with the given ID (Wrapper for document.getElementById). * @method byId * @param {String} id the id attribute * @param {Object} doc optional The document to search. Defaults to current document * @return {HTMLElement | null} The HTMLElement with the id, or null if none found. */ byId: function(id, doc) { // handle dupe IDs and IE name collision return Y_DOM.allById(id, doc)[0] || null; }, getId: function(node) { var id; // HTMLElement returned from FORM when INPUT name === "id" // IE < 8: HTMLCollection returned when INPUT id === "id" // via both getAttribute and form.id if (node.id && !node.id.tagName && !node.id.item) { id = node.id; } else if (node.attributes && node.attributes.id) { id = node.attributes.id.value; } return id; }, setId: function(node, id) { if (node.setAttribute) { node.setAttribute('id', id); } else { node.id = id; } }, /* * Finds the ancestor of the element. * @method ancestor * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, the parentNode is returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {HTMLElement | null} The matching DOM node or null if none found. */ ancestor: function(element, fn, testSelf, stopFn) { var ret = null; if (testSelf) { ret = (!fn || fn(element)) ? element : null; } return ret || Y_DOM.elementByAxis(element, PARENT_NODE, fn, null, stopFn); }, /* * Finds the ancestors of the element. * @method ancestors * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, all ancestors are returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {Array} An array containing all matching DOM nodes. */ ancestors: function(element, fn, testSelf, stopFn) { var ancestor = element, ret = []; while ((ancestor = Y_DOM.ancestor(ancestor, fn, testSelf, stopFn))) { testSelf = false; if (ancestor) { ret.unshift(ancestor); if (stopFn && stopFn(ancestor)) { return ret; } } } return ret; }, /** * Searches the element by the given axis for the first matching element. * @method elementByAxis * @param {HTMLElement} element The html element. * @param {String} axis The axis to search (parentNode, nextSibling, previousSibling). * @param {Function} fn optional An optional boolean test to apply. * @param {Boolean} all optional Whether all node types should be returned, or just element nodes. * The optional function is passed the current HTMLElement being tested as its only argument. * If no function is given, the first element is returned. * @return {HTMLElement | null} The matching element or null if none found. */ elementByAxis: function(element, axis, fn, all, stopAt) { while (element && (element = element[axis])) { // NOTE: assignment if ( (all || element[TAG_NAME]) && (!fn || fn(element)) ) { return element; } if (stopAt && stopAt(element)) { return null; } } return null; }, /** * Determines whether or not one HTMLElement is or contains another HTMLElement. * @method contains * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ contains: function(element, needle) { var ret = false; if ( !needle || !element || !needle[NODE_TYPE] || !element[NODE_TYPE]) { ret = false; } else if (element[CONTAINS] && // IE < 8 throws on node.contains(textNode) so fall back to brute. // Falling back for other nodeTypes as well. (needle[NODE_TYPE] === 1 || supportsContainsTextNode)) { ret = element[CONTAINS](needle); } else if (element[COMPARE_DOCUMENT_POSITION]) { // Match contains behavior (node.contains(node) === true). // Needed for Firefox < 4. if (element === needle || !!(element[COMPARE_DOCUMENT_POSITION](needle) & 16)) { ret = true; } } else { ret = Y_DOM._bruteContains(element, needle); } return ret; }, /** * Determines whether or not the HTMLElement is part of the document. * @method inDoc * @param {HTMLElement} element The containing html element. * @param {HTMLElement} doc optional The document to check. * @return {Boolean} Whether or not the element is attached to the document. */ inDoc: function(element, doc) { var ret = false, rootNode; if (element && element.nodeType) { (doc) || (doc = element[OWNER_DOCUMENT]); rootNode = doc[DOCUMENT_ELEMENT]; // contains only works with HTML_ELEMENT if (rootNode && rootNode.contains && element.tagName) { ret = rootNode.contains(element); } else { ret = Y_DOM.contains(rootNode, element); } } return ret; }, allById: function(id, root) { root = root || Y.config.doc; var nodes = [], ret = [], i, node; if (root.querySelectorAll) { ret = root.querySelectorAll('[id="' + id + '"]'); } else if (root.all) { nodes = root.all(id); if (nodes) { // root.all may return HTMLElement or HTMLCollection. // some elements are also HTMLCollection (FORM, SELECT). if (nodes.nodeName) { if (nodes.id === id) { // avoid false positive on name ret.push(nodes); nodes = EMPTY_ARRAY; // done, no need to filter } else { // prep for filtering nodes = [nodes]; } } if (nodes.length) { // filter out matches on node.name // and element.id as reference to element with id === 'id' for (i = 0; node = nodes[i++];) { if (node.id === id || (node.attributes && node.attributes.id && node.attributes.id.value === id)) { ret.push(node); } } } } } else { ret = [Y_DOM._getDoc(root).getElementById(id)]; } return ret; }, isWindow: function(obj) { return !!(obj && obj.scrollTo && obj.document); }, _removeChildNodes: function(node) { while (node.firstChild) { node.removeChild(node.firstChild); } }, siblings: function(node, fn) { var nodes = [], sibling = node; while ((sibling = sibling[PREVIOUS_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.unshift(sibling); } } sibling = node; while ((sibling = sibling[NEXT_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.push(sibling); } } return nodes; }, /** * Brute force version of contains. * Used for browsers without contains support for non-HTMLElement Nodes (textNodes, etc). * @method _bruteContains * @private * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ _bruteContains: function(element, needle) { while (needle) { if (element === needle) { return true; } needle = needle.parentNode; } return false; }, // TODO: move to Lang? /** * Memoizes dynamic regular expressions to boost runtime performance. * @method _getRegExp * @private * @param {String} str The string to convert to a regular expression. * @param {String} flags optional An optinal string of flags. * @return {RegExp} An instance of RegExp */ _getRegExp: function(str, flags) { flags = flags || ''; Y_DOM._regexCache = Y_DOM._regexCache || {}; if (!Y_DOM._regexCache[str + flags]) { Y_DOM._regexCache[str + flags] = new RegExp(str, flags); } return Y_DOM._regexCache[str + flags]; }, // TODO: make getDoc/Win true privates? /** * returns the appropriate document. * @method _getDoc * @private * @param {HTMLElement} element optional Target element. * @return {Object} The document for the given element or the default document. */ _getDoc: function(element) { var doc = Y.config.doc; if (element) { doc = (element[NODE_TYPE] === 9) ? element : // element === document element[OWNER_DOCUMENT] || // element === DOM node element.document || // element === window Y.config.doc; // default } return doc; }, /** * returns the appropriate window. * @method _getWin * @private * @param {HTMLElement} element optional Target element. * @return {Object} The window for the given element or the default window. */ _getWin: function(element) { var doc = Y_DOM._getDoc(element); return doc[DEFAULT_VIEW] || doc[PARENT_WINDOW] || Y.config.win; }, _batch: function(nodes, fn, arg1, arg2, arg3, etc) { fn = (typeof fn === 'string') ? Y_DOM[fn] : fn; var result, i = 0, node, ret; if (fn && nodes) { while ((node = nodes[i++])) { result = result = fn.call(Y_DOM, node, arg1, arg2, arg3, etc); if (typeof result !== 'undefined') { (ret) || (ret = []); ret.push(result); } } } return (typeof ret !== 'undefined') ? ret : nodes; }, generateID: function(el) { var id = el.id; if (!id) { id = Y.stamp(el); el.id = id; } return id; } }; Y.DOM = Y_DOM; }, '3.8.0pr2', {"requires": ["oop", "features"]}); YUI.add('dom-base', function (Y, NAME) { /** * @for DOM * @module dom */ var documentElement = Y.config.doc.documentElement, Y_DOM = Y.DOM, TAG_NAME = 'tagName', OWNER_DOCUMENT = 'ownerDocument', EMPTY_STRING = '', addFeature = Y.Features.add, testFeature = Y.Features.test; Y.mix(Y_DOM, { /** * Returns the text content of the HTMLElement. * @method getText * @param {HTMLElement} element The html element. * @return {String} The text content of the element (includes text of any descending elements). */ getText: (documentElement.textContent !== undefined) ? function(element) { var ret = ''; if (element) { ret = element.textContent; } return ret || ''; } : function(element) { var ret = ''; if (element) { ret = element.innerText || element.nodeValue; // might be a textNode } return ret || ''; }, /** * Sets the text content of the HTMLElement. * @method setText * @param {HTMLElement} element The html element. * @param {String} content The content to add. */ setText: (documentElement.textContent !== undefined) ? function(element, content) { if (element) { element.textContent = content; } } : function(element, content) { if ('innerText' in element) { element.innerText = content; } else if ('nodeValue' in element) { element.nodeValue = content; } }, CUSTOM_ATTRIBUTES: (!documentElement.hasAttribute) ? { // IE < 8 'for': 'htmlFor', 'class': 'className' } : { // w3c 'htmlFor': 'for', 'className': 'class' }, /** * Provides a normalized attribute interface. * @method setAttribute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to set. * @param {String} val The value of the attribute. */ setAttribute: function(el, attr, val, ieAttr) { if (el && attr && el.setAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; el.setAttribute(attr, val, ieAttr); } }, /** * Provides a normalized attribute interface. * @method getAttribute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to get. * @return {String} The current value of the attribute. */ getAttribute: function(el, attr, ieAttr) { ieAttr = (ieAttr !== undefined) ? ieAttr : 2; var ret = ''; if (el && attr && el.getAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; ret = el.getAttribute(attr, ieAttr); if (ret === null) { ret = ''; // per DOM spec } } return ret; }, VALUE_SETTERS: {}, VALUE_GETTERS: {}, getValue: function(node) { var ret = '', // TODO: return null? getter; if (node && node[TAG_NAME]) { getter = Y_DOM.VALUE_GETTERS[node[TAG_NAME].toLowerCase()]; if (getter) { ret = getter(node); } else { ret = node.value; } } // workaround for IE8 JSON stringify bug // which converts empty string values to null if (ret === EMPTY_STRING) { ret = EMPTY_STRING; // for real } return (typeof ret === 'string') ? ret : ''; }, setValue: function(node, val) { var setter; if (node && node[TAG_NAME]) { setter = Y_DOM.VALUE_SETTERS[node[TAG_NAME].toLowerCase()]; if (setter) { setter(node, val); } else { node.value = val; } } }, creators: {} }); addFeature('value-set', 'select', { test: function() { var node = Y.config.doc.createElement('select'); node.innerHTML = '<option>1</option><option>2</option>'; node.value = '2'; return (node.value && node.value === '2'); } }); if (!testFeature('value-set', 'select')) { Y_DOM.VALUE_SETTERS.select = function(node, val) { for (var i = 0, options = node.getElementsByTagName('option'), option; option = options[i++];) { if (Y_DOM.getValue(option) === val) { option.selected = true; //Y_DOM.setAttribute(option, 'selected', 'selected'); break; } } }; } Y.mix(Y_DOM.VALUE_GETTERS, { button: function(node) { return (node.attributes && node.attributes.value) ? node.attributes.value.value : ''; } }); Y.mix(Y_DOM.VALUE_SETTERS, { // IE: node.value changes the button text, which should be handled via innerHTML button: function(node, val) { var attr = node.attributes.value; if (!attr) { attr = node[OWNER_DOCUMENT].createAttribute('value'); node.setAttributeNode(attr); } attr.value = val; } }); Y.mix(Y_DOM.VALUE_GETTERS, { option: function(node) { var attrs = node.attributes; return (attrs.value && attrs.value.specified) ? node.value : node.text; }, select: function(node) { var val = node.value, options = node.options; if (options && options.length) { // TODO: implement multipe select if (node.multiple) { } else if (node.selectedIndex > -1) { val = Y_DOM.getValue(options[node.selectedIndex]); } } return val; } }); var addClass, hasClass, removeClass; Y.mix(Y.DOM, { /** * Determines whether a DOM element has the given className. * @method hasClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the given class. */ hasClass: function(node, className) { var re = Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'); return re.test(node.className); }, /** * Adds a class name to a given DOM element. * @method addClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to add to the class attribute */ addClass: function(node, className) { if (!Y.DOM.hasClass(node, className)) { // skip if already present node.className = Y.Lang.trim([node.className, className].join(' ')); } }, /** * Removes a class name from a given element. * @method removeClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to remove from the class attribute */ removeClass: function(node, className) { if (className && hasClass(node, className)) { node.className = Y.Lang.trim(node.className.replace(Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'), ' ')); if ( hasClass(node, className) ) { // in case of multiple adjacent removeClass(node, className); } } }, /** * Replace a class with another class for a given element. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name */ replaceClass: function(node, oldC, newC) { removeClass(node, oldC); // remove first in case oldC === newC addClass(node, newC); }, /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} className the class name to be toggled * @param {Boolean} addClass optional boolean to indicate whether class * should be added or removed regardless of current state */ toggleClass: function(node, className, force) { var add = (force !== undefined) ? force : !(hasClass(node, className)); if (add) { addClass(node, className); } else { removeClass(node, className); } } }); hasClass = Y.DOM.hasClass; removeClass = Y.DOM.removeClass; addClass = Y.DOM.addClass; var re_tag = /<([a-z]+)/i, Y_DOM = Y.DOM, addFeature = Y.Features.add, testFeature = Y.Features.test, creators = {}, createFromDIV = function(html, tag) { var div = Y.config.doc.createElement('div'), ret = true; div.innerHTML = html; if (!div.firstChild || div.firstChild.tagName !== tag.toUpperCase()) { ret = false; } return ret; }, re_tbody = /(?:\/(?:thead|tfoot|tbody|caption|col|colgroup)>)+\s*<tbody/, TABLE_OPEN = '<table>', TABLE_CLOSE = '</table>'; Y.mix(Y.DOM, { _fragClones: {}, _create: function(html, doc, tag) { tag = tag || 'div'; var frag = Y_DOM._fragClones[tag]; if (frag) { frag = frag.cloneNode(false); } else { frag = Y_DOM._fragClones[tag] = doc.createElement(tag); } frag.innerHTML = html; return frag; }, _children: function(node, tag) { var i = 0, children = node.children, childNodes, hasComments, child; if (children && children.tags) { // use tags filter when possible if (tag) { children = node.children.tags(tag); } else { // IE leaks comments into children hasComments = children.tags('!').length; } } if (!children || (!children.tags && tag) || hasComments) { childNodes = children || node.childNodes; children = []; while ((child = childNodes[i++])) { if (child.nodeType === 1) { if (!tag || tag === child.tagName) { children.push(child); } } } } return children || []; }, /** * Creates a new dom node using the provided markup string. * @method create * @param {String} html The markup used to create the element * @param {HTMLDocument} doc An optional document context * @return {HTMLElement|DocumentFragment} returns a single HTMLElement * when creating one node, and a documentFragment when creating * multiple nodes. */ create: function(html, doc) { if (typeof html === 'string') { html = Y.Lang.trim(html); // match IE which trims whitespace from innerHTML } doc = doc || Y.config.doc; var m = re_tag.exec(html), create = Y_DOM._create, custom = creators, ret = null, creator, tag, nodes; if (html != undefined) { // not undefined or null if (m && m[1]) { creator = custom[m[1].toLowerCase()]; if (typeof creator === 'function') { create = creator; } else { tag = creator; } } nodes = create(html, doc, tag).childNodes; if (nodes.length === 1) { // return single node, breaking parentNode ref from "fragment" ret = nodes[0].parentNode.removeChild(nodes[0]); } else if (nodes[0] && nodes[0].className === 'yui3-big-dummy') { // using dummy node to preserve some attributes (e.g. OPTION not selected) if (nodes.length === 2) { ret = nodes[0].nextSibling; } else { nodes[0].parentNode.removeChild(nodes[0]); ret = Y_DOM._nl2frag(nodes, doc); } } else { // return multiple nodes as a fragment ret = Y_DOM._nl2frag(nodes, doc); } } return ret; }, _nl2frag: function(nodes, doc) { var ret = null, i, len; if (nodes && (nodes.push || nodes.item) && nodes[0]) { doc = doc || nodes[0].ownerDocument; ret = doc.createDocumentFragment(); if (nodes.item) { // convert live list to static array nodes = Y.Array(nodes, 0, true); } for (i = 0, len = nodes.length; i < len; i++) { ret.appendChild(nodes[i]); } } // else inline with log for minification return ret; }, /** * Inserts content in a node at the given location * @method addHTML * @param {HTMLElement} node The node to insert into * @param {HTMLElement | Array | HTMLCollection} content The content to be inserted * @param {HTMLElement} where Where to insert the content * If no "where" is given, content is appended to the node * Possible values for "where" * <dl> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> */ addHTML: function(node, content, where) { var nodeParent = node.parentNode, i = 0, item, ret = content, newNode; if (content != undefined) { // not null or undefined (maybe 0) if (content.nodeType) { // DOM node, just add it newNode = content; } else if (typeof content == 'string' || typeof content == 'number') { ret = newNode = Y_DOM.create(content); } else if (content[0] && content[0].nodeType) { // array or collection newNode = Y.config.doc.createDocumentFragment(); while ((item = content[i++])) { newNode.appendChild(item); // append to fragment for insertion } } } if (where) { if (newNode && where.parentNode) { // insert regardless of relationship to node where.parentNode.insertBefore(newNode, where); } else { switch (where) { case 'replace': while (node.firstChild) { node.removeChild(node.firstChild); } if (newNode) { // allow empty content to clear node node.appendChild(newNode); } break; case 'before': if (newNode) { nodeParent.insertBefore(newNode, node); } break; case 'after': if (newNode) { if (node.nextSibling) { // IE errors if refNode is null nodeParent.insertBefore(newNode, node.nextSibling); } else { nodeParent.appendChild(newNode); } } break; default: if (newNode) { node.appendChild(newNode); } } } } else if (newNode) { node.appendChild(newNode); } return ret; }, wrap: function(node, html) { var parent = (html && html.nodeType) ? html : Y.DOM.create(html), nodes = parent.getElementsByTagName('*'); if (nodes.length) { parent = nodes[nodes.length - 1]; } if (node.parentNode) { node.parentNode.replaceChild(parent, node); } parent.appendChild(node); }, unwrap: function(node) { var parent = node.parentNode, lastChild = parent.lastChild, next = node, grandparent; if (parent) { grandparent = parent.parentNode; if (grandparent) { node = parent.firstChild; while (node !== lastChild) { next = node.nextSibling; grandparent.insertBefore(node, parent); node = next; } grandparent.replaceChild(lastChild, parent); } else { parent.removeChild(node); } } } }); addFeature('innerhtml', 'table', { test: function() { var node = Y.config.doc.createElement('table'); try { node.innerHTML = '<tbody></tbody>'; } catch(e) { return false; } return (node.firstChild && node.firstChild.nodeName === 'TBODY'); } }); addFeature('innerhtml-div', 'tr', { test: function() { return createFromDIV('<tr></tr>', 'tr'); } }); addFeature('innerhtml-div', 'script', { test: function() { return createFromDIV('<script></script>', 'script'); } }); if (!testFeature('innerhtml', 'table')) { // TODO: thead/tfoot with nested tbody // IE adds TBODY when creating TABLE elements (which may share this impl) creators.tbody = function(html, doc) { var frag = Y_DOM.create(TABLE_OPEN + html + TABLE_CLOSE, doc), tb = Y.DOM._children(frag, 'tbody')[0]; if (frag.children.length > 1 && tb && !re_tbody.test(html)) { tb.parentNode.removeChild(tb); // strip extraneous tbody } return frag; }; } if (!testFeature('innerhtml-div', 'script')) { creators.script = function(html, doc) { var frag = doc.createElement('div'); frag.innerHTML = '-' + html; frag.removeChild(frag.firstChild); return frag; }; creators.link = creators.style = creators.script; } if (!testFeature('innerhtml-div', 'tr')) { Y.mix(creators, { option: function(html, doc) { return Y_DOM.create('<select><option class="yui3-big-dummy" selected></option>' + html + '</select>', doc); }, tr: function(html, doc) { return Y_DOM.create('<tbody>' + html + '</tbody>', doc); }, td: function(html, doc) { return Y_DOM.create('<tr>' + html + '</tr>', doc); }, col: function(html, doc) { return Y_DOM.create('<colgroup>' + html + '</colgroup>', doc); }, tbody: 'table' }); Y.mix(creators, { legend: 'fieldset', th: creators.td, thead: creators.tbody, tfoot: creators.tbody, caption: creators.tbody, colgroup: creators.tbody, optgroup: creators.option }); } Y_DOM.creators = creators; Y.mix(Y.DOM, { /** * Sets the width of the element to the given size, regardless * of box model, border, padding, etc. * @method setWidth * @param {HTMLElement} element The DOM element. * @param {String|Number} size The pixel height to size to */ setWidth: function(node, size) { Y.DOM._setSize(node, 'width', size); }, /** * Sets the height of the element to the given size, regardless * of box model, border, padding, etc. * @method setHeight * @param {HTMLElement} element The DOM element. * @param {String|Number} size The pixel height to size to */ setHeight: function(node, size) { Y.DOM._setSize(node, 'height', size); }, _setSize: function(node, prop, val) { val = (val > 0) ? val : 0; var size = 0; node.style[prop] = val + 'px'; size = (prop === 'height') ? node.offsetHeight : node.offsetWidth; if (size > val) { val = val - (size - val); if (val < 0) { val = 0; } node.style[prop] = val + 'px'; } } }); }, '3.8.0pr2', {"requires": ["dom-core"]}); YUI.add('dom-style', function (Y, NAME) { (function(Y) { /** * Add style management functionality to DOM. * @module dom * @submodule dom-style * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', OWNER_DOCUMENT = 'ownerDocument', STYLE = 'style', FLOAT = 'float', CSS_FLOAT = 'cssFloat', STYLE_FLOAT = 'styleFloat', TRANSPARENT = 'transparent', GET_COMPUTED_STYLE = 'getComputedStyle', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', WINDOW = Y.config.win, DOCUMENT = Y.config.doc, UNDEFINED = undefined, Y_DOM = Y.DOM, TRANSFORM = 'transform', TRANSFORMORIGIN = 'transformOrigin', VENDOR_TRANSFORM = [ 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform' ], re_color = /color$/i, re_unit = /width|height|top|left|right|bottom|margin|padding/i; Y.Array.each(VENDOR_TRANSFORM, function(val) { if (val in DOCUMENT[DOCUMENT_ELEMENT].style) { TRANSFORM = val; TRANSFORMORIGIN = val + "Origin"; } }); Y.mix(Y_DOM, { DEFAULT_UNIT: 'px', CUSTOM_STYLES: { }, /** * Sets a style property for a given element. * @method setStyle * @param {HTMLElement} An HTMLElement to apply the style to. * @param {String} att The style property to set. * @param {String|Number} val The value. */ setStyle: function(node, att, val, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES; if (style) { if (val === null || val === '') { // normalize unsetting val = ''; } else if (!isNaN(new Number(val)) && re_unit.test(att)) { // number values may need a unit val += Y_DOM.DEFAULT_UNIT; } if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].set) { CUSTOM_STYLES[att].set(node, val, style); return; // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } else if (att === '') { // unset inline styles att = 'cssText'; val = ''; } style[att] = val; } }, /** * Returns the current style value for the given property. * @method getStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. */ getStyle: function(node, att, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES, val = ''; if (style) { if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].get) { return CUSTOM_STYLES[att].get(node, att, style); // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } val = style[att]; if (val === '') { // TODO: is empty string sufficient? val = Y_DOM[GET_COMPUTED_STYLE](node, att); } } return val; }, /** * Sets multiple style properties. * @method setStyles * @param {HTMLElement} node An HTMLElement to apply the styles to. * @param {Object} hash An object literal of property:value pairs. */ setStyles: function(node, hash) { var style = node.style; Y.each(hash, function(v, n) { Y_DOM.setStyle(node, n, v, style); }, Y_DOM); }, /** * Returns the computed style for the given node. * @method getComputedStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. * @return {String} The computed value of the style property. */ getComputedStyle: function(node, att) { var val = '', doc = node[OWNER_DOCUMENT], computed; if (node[STYLE] && doc[DEFAULT_VIEW] && doc[DEFAULT_VIEW][GET_COMPUTED_STYLE]) { computed = doc[DEFAULT_VIEW][GET_COMPUTED_STYLE](node, null); if (computed) { // FF may be null in some cases (ticket #2530548) val = computed[att]; } } return val; } }); // normalize reserved word float alternatives ("cssFloat" or "styleFloat") if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][CSS_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = CSS_FLOAT; } else if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][STYLE_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = STYLE_FLOAT; } // fix opera computedStyle default color unit (convert to rgb) if (Y.UA.opera) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (re_color.test(att)) { val = Y.Color.toRGB(val); } return val; }; } // safari converts transparent to rgba(), others use "transparent" if (Y.UA.webkit) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (val === 'rgba(0, 0, 0, 0)') { val = TRANSPARENT; } return val; }; } Y.DOM._getAttrOffset = function(node, attr) { var val = Y.DOM[GET_COMPUTED_STYLE](node, attr), offsetParent = node.offsetParent, position, parentOffset, offset; if (val === 'auto') { position = Y.DOM.getStyle(node, 'position'); if (position === 'static' || position === 'relative') { val = 0; } else if (offsetParent && offsetParent[GET_BOUNDING_CLIENT_RECT]) { parentOffset = offsetParent[GET_BOUNDING_CLIENT_RECT]()[attr]; offset = node[GET_BOUNDING_CLIENT_RECT]()[attr]; if (attr === 'left' || attr === 'top') { val = offset - parentOffset; } else { val = parentOffset - node[GET_BOUNDING_CLIENT_RECT]()[attr]; } } } return val; }; Y.DOM._getOffset = function(node) { var pos, xy = null; if (node) { pos = Y_DOM.getStyle(node, 'position'); xy = [ parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'left'), 10), parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'top'), 10) ]; if ( isNaN(xy[0]) ) { // in case of 'auto' xy[0] = parseInt(Y_DOM.getStyle(node, 'left'), 10); // try inline if ( isNaN(xy[0]) ) { // default to offset value xy[0] = (pos === 'relative') ? 0 : node.offsetLeft || 0; } } if ( isNaN(xy[1]) ) { // in case of 'auto' xy[1] = parseInt(Y_DOM.getStyle(node, 'top'), 10); // try inline if ( isNaN(xy[1]) ) { // default to offset value xy[1] = (pos === 'relative') ? 0 : node.offsetTop || 0; } } } return xy; }; Y_DOM.CUSTOM_STYLES.transform = { set: function(node, val, style) { style[TRANSFORM] = val; }, get: function(node, style) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORM); } }; Y_DOM.CUSTOM_STYLES.transformOrigin = { set: function(node, val, style) { style[TRANSFORMORIGIN] = val; }, get: function(node, style) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORMORIGIN); } }; })(Y); (function(Y) { var PARSE_INT = parseInt, RE = RegExp; Y.Color = { KEYWORDS: { black: '000', silver: 'c0c0c0', gray: '808080', white: 'fff', maroon: '800000', red: 'f00', purple: '800080', fuchsia: 'f0f', green: '008000', lime: '0f0', olive: '808000', yellow: 'ff0', navy: '000080', blue: '00f', teal: '008080', aqua: '0ff' }, re_RGB: /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i, re_hex: /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i, re_hex3: /([0-9A-F])/gi, toRGB: function(val) { if (!Y.Color.re_RGB.test(val)) { val = Y.Color.toHex(val); } if(Y.Color.re_hex.exec(val)) { val = 'rgb(' + [ PARSE_INT(RE.$1, 16), PARSE_INT(RE.$2, 16), PARSE_INT(RE.$3, 16) ].join(', ') + ')'; } return val; }, toHex: function(val) { val = Y.Color.KEYWORDS[val] || val; if (Y.Color.re_RGB.exec(val)) { val = [ Number(RE.$1).toString(16), Number(RE.$2).toString(16), Number(RE.$3).toString(16) ]; for (var i = 0; i < val.length; i++) { if (val[i].length < 2) { val[i] = '0' + val[i]; } } val = val.join(''); } if (val.length < 6) { val = val.replace(Y.Color.re_hex3, '$1$1'); } if (val !== 'transparent' && val.indexOf('#') < 0) { val = '#' + val; } return val.toUpperCase(); } }; })(Y); }, '3.8.0pr2', {"requires": ["dom-base"]}); YUI.add('dom-style-ie', function (Y, NAME) { (function(Y) { var HAS_LAYOUT = 'hasLayout', PX = 'px', FILTER = 'filter', FILTERS = 'filters', OPACITY = 'opacity', AUTO = 'auto', BORDER_WIDTH = 'borderWidth', BORDER_TOP_WIDTH = 'borderTopWidth', BORDER_RIGHT_WIDTH = 'borderRightWidth', BORDER_BOTTOM_WIDTH = 'borderBottomWidth', BORDER_LEFT_WIDTH = 'borderLeftWidth', WIDTH = 'width', HEIGHT = 'height', TRANSPARENT = 'transparent', VISIBLE = 'visible', GET_COMPUTED_STYLE = 'getComputedStyle', UNDEFINED = undefined, documentElement = Y.config.doc.documentElement, testFeature = Y.Features.test, addFeature = Y.Features.add, // TODO: unit-less lineHeight (e.g. 1.22) re_unit = /^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i, isIE8 = (Y.UA.ie >= 8), _getStyleObj = function(node) { return node.currentStyle || node.style; }, ComputedStyle = { CUSTOM_STYLES: {}, get: function(el, property) { var value = '', current; if (el) { current = _getStyleObj(el)[property]; if (property === OPACITY && Y.DOM.CUSTOM_STYLES[OPACITY]) { value = Y.DOM.CUSTOM_STYLES[OPACITY].get(el); } else if (!current || (current.indexOf && current.indexOf(PX) > -1)) { // no need to convert value = current; } else if (Y.DOM.IE.COMPUTED[property]) { // use compute function value = Y.DOM.IE.COMPUTED[property](el, property); } else if (re_unit.test(current)) { // convert to pixel value = ComputedStyle.getPixel(el, property) + PX; } else { value = current; } } return value; }, sizeOffsets: { width: ['Left', 'Right'], height: ['Top', 'Bottom'], top: ['Top'], bottom: ['Bottom'] }, getOffset: function(el, prop) { var current = _getStyleObj(el)[prop], // value of "width", "top", etc. capped = prop.charAt(0).toUpperCase() + prop.substr(1), // "Width", "Top", etc. offset = 'offset' + capped, // "offsetWidth", "offsetTop", etc. pixel = 'pixel' + capped, // "pixelWidth", "pixelTop", etc. sizeOffsets = ComputedStyle.sizeOffsets[prop], mode = el.ownerDocument.compatMode, value = ''; // IE pixelWidth incorrect for percent // manually compute by subtracting padding and border from offset size // NOTE: clientWidth/Height (size minus border) is 0 when current === AUTO so offsetHeight is used // reverting to auto from auto causes position stacking issues (old impl) if (current === AUTO || current.indexOf('%') > -1) { value = el['offset' + capped]; if (mode !== 'BackCompat') { if (sizeOffsets[0]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[0]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[0] + 'Width', 1); } if (sizeOffsets[1]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[1]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[1] + 'Width', 1); } } } else { // use style.pixelWidth, etc. to convert to pixels // need to map style.width to currentStyle (no currentStyle.pixelWidth) if (!el.style[pixel] && !el.style[prop]) { el.style[prop] = current; } value = el.style[pixel]; } return value + PX; }, borderMap: { thin: (isIE8) ? '1px' : '2px', medium: (isIE8) ? '3px': '4px', thick: (isIE8) ? '5px' : '6px' }, getBorderWidth: function(el, property, omitUnit) { var unit = omitUnit ? '' : PX, current = el.currentStyle[property]; if (current.indexOf(PX) < 0) { // look up keywords if a border exists if (ComputedStyle.borderMap[current] && el.currentStyle.borderStyle !== 'none') { current = ComputedStyle.borderMap[current]; } else { // otherwise no border (default is "medium") current = 0; } } return (omitUnit) ? parseFloat(current) : current; }, getPixel: function(node, att) { // use pixelRight to convert to px var val = null, style = _getStyleObj(node), styleRight = style.right, current = style[att]; node.style.right = current; val = node.style.pixelRight; node.style.right = styleRight; // revert return val; }, getMargin: function(node, att) { var val, style = _getStyleObj(node); if (style[att] == AUTO) { val = 0; } else { val = ComputedStyle.getPixel(node, att); } return val + PX; }, getVisibility: function(node, att) { var current; while ( (current = node.currentStyle) && current[att] == 'inherit') { // NOTE: assignment in test node = node.parentNode; } return (current) ? current[att] : VISIBLE; }, getColor: function(node, att) { var current = _getStyleObj(node)[att]; if (!current || current === TRANSPARENT) { Y.DOM.elementByAxis(node, 'parentNode', null, function(parent) { current = _getStyleObj(parent)[att]; if (current && current !== TRANSPARENT) { node = parent; return true; } }); } return Y.Color.toRGB(current); }, getBorderColor: function(node, att) { var current = _getStyleObj(node), val = current[att] || current.color; return Y.Color.toRGB(Y.Color.toHex(val)); } }, //fontSize: getPixelFont, IEComputed = {}; addFeature('style', 'computedStyle', { test: function() { return 'getComputedStyle' in Y.config.win; } }); addFeature('style', 'opacity', { test: function() { return 'opacity' in documentElement.style; } }); addFeature('style', 'filter', { test: function() { return 'filters' in documentElement; } }); // use alpha filter for IE opacity if (!testFeature('style', 'opacity') && testFeature('style', 'filter')) { Y.DOM.CUSTOM_STYLES[OPACITY] = { get: function(node) { var val = 100; try { // will error if no DXImageTransform val = node[FILTERS]['DXImageTransform.Microsoft.Alpha'][OPACITY]; } catch(e) { try { // make sure its in the document val = node[FILTERS]('alpha')[OPACITY]; } catch(err) { } } return val / 100; }, set: function(node, val, style) { var current, styleObj = _getStyleObj(node), currentFilter = styleObj[FILTER]; style = style || node.style; if (val === '') { // normalize inline style behavior current = (OPACITY in styleObj) ? styleObj[OPACITY] : 1; // revert to original opacity val = current; } if (typeof currentFilter == 'string') { // in case not appended style[FILTER] = currentFilter.replace(/alpha([^)]*\))/gi, '') + ((val < 1) ? 'alpha(' + OPACITY + '=' + val * 100 + ')' : ''); if (!style[FILTER]) { style.removeAttribute(FILTER); } if (!styleObj[HAS_LAYOUT]) { style.zoom = 1; // needs layout } } } }; } try { Y.config.doc.createElement('div').style.height = '-1px'; } catch(e) { // IE throws error on invalid style set; trap common cases Y.DOM.CUSTOM_STYLES.height = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.height = val; } else { } } }; Y.DOM.CUSTOM_STYLES.width = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.width = val; } else { } } }; } if (!testFeature('style', 'computedStyle')) { // TODO: top, right, bottom, left IEComputed[WIDTH] = IEComputed[HEIGHT] = ComputedStyle.getOffset; IEComputed.color = IEComputed.backgroundColor = ComputedStyle.getColor; IEComputed[BORDER_WIDTH] = IEComputed[BORDER_TOP_WIDTH] = IEComputed[BORDER_RIGHT_WIDTH] = IEComputed[BORDER_BOTTOM_WIDTH] = IEComputed[BORDER_LEFT_WIDTH] = ComputedStyle.getBorderWidth; IEComputed.marginTop = IEComputed.marginRight = IEComputed.marginBottom = IEComputed.marginLeft = ComputedStyle.getMargin; IEComputed.visibility = ComputedStyle.getVisibility; IEComputed.borderColor = IEComputed.borderTopColor = IEComputed.borderRightColor = IEComputed.borderBottomColor = IEComputed.borderLeftColor = ComputedStyle.getBorderColor; Y.DOM[GET_COMPUTED_STYLE] = ComputedStyle.get; Y.namespace('DOM.IE'); Y.DOM.IE.COMPUTED = IEComputed; Y.DOM.IE.ComputedStyle = ComputedStyle; } })(Y); }, '3.8.0pr2', {"requires": ["dom-style"]}); YUI.add('dom-screen', function (Y, NAME) { (function(Y) { /** * Adds position and region management functionality to DOM. * @module dom * @submodule dom-screen * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', COMPAT_MODE = 'compatMode', POSITION = 'position', FIXED = 'fixed', RELATIVE = 'relative', LEFT = 'left', TOP = 'top', _BACK_COMPAT = 'BackCompat', MEDIUM = 'medium', BORDER_LEFT_WIDTH = 'borderLeftWidth', BORDER_TOP_WIDTH = 'borderTopWidth', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', GET_COMPUTED_STYLE = 'getComputedStyle', Y_DOM = Y.DOM, // TODO: how about thead/tbody/tfoot/tr? // TODO: does caption matter? RE_TABLE = /^t(?:able|d|h)$/i, SCROLL_NODE; if (Y.UA.ie) { if (Y.config.doc[COMPAT_MODE] !== 'BackCompat') { SCROLL_NODE = DOCUMENT_ELEMENT; } else { SCROLL_NODE = 'body'; } } Y.mix(Y_DOM, { /** * Returns the inner height of the viewport (exludes scrollbar). * @method winHeight * @return {Number} The current height of the viewport. */ winHeight: function(node) { var h = Y_DOM._getWinSize(node).height; return h; }, /** * Returns the inner width of the viewport (exludes scrollbar). * @method winWidth * @return {Number} The current width of the viewport. */ winWidth: function(node) { var w = Y_DOM._getWinSize(node).width; return w; }, /** * Document height * @method docHeight * @return {Number} The current height of the document. */ docHeight: function(node) { var h = Y_DOM._getDocSize(node).height; return Math.max(h, Y_DOM._getWinSize(node).height); }, /** * Document width * @method docWidth * @return {Number} The current width of the document. */ docWidth: function(node) { var w = Y_DOM._getDocSize(node).width; return Math.max(w, Y_DOM._getWinSize(node).width); }, /** * Amount page has been scroll horizontally * @method docScrollX * @return {Number} The current amount the screen is scrolled horizontally. */ docScrollX: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageXOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollLeft, doc.body.scrollLeft, pageOffset); }, /** * Amount page has been scroll vertically * @method docScrollY * @return {Number} The current amount the screen is scrolled vertically. */ docScrollY: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageYOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollTop, doc.body.scrollTop, pageOffset); }, /** * Gets the current position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getXY * @param element The target element * @return {Array} The XY position of the element TODO: test inDocument/display? */ getXY: function() { if (Y.config.doc[DOCUMENT_ELEMENT][GET_BOUNDING_CLIENT_RECT]) { return function(node) { var xy = null, scrollLeft, scrollTop, mode, box, offX, offY, doc, win, inDoc, rootNode; if (node && node.tagName) { doc = node.ownerDocument; mode = doc[COMPAT_MODE]; if (mode !== _BACK_COMPAT) { rootNode = doc[DOCUMENT_ELEMENT]; } else { rootNode = doc.body; } // inline inDoc check for perf if (rootNode.contains) { inDoc = rootNode.contains(node); } else { inDoc = Y.DOM.contains(rootNode, node); } if (inDoc) { win = doc.defaultView; // inline scroll calc for perf if (win && 'pageXOffset' in win) { scrollLeft = win.pageXOffset; scrollTop = win.pageYOffset; } else { scrollLeft = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollLeft : Y_DOM.docScrollX(node, doc); scrollTop = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollTop : Y_DOM.docScrollY(node, doc); } if (Y.UA.ie) { // IE < 8, quirks, or compatMode if (!doc.documentMode || doc.documentMode < 8 || mode === _BACK_COMPAT) { offX = rootNode.clientLeft; offY = rootNode.clientTop; } } box = node[GET_BOUNDING_CLIENT_RECT](); xy = [box.left, box.top]; if (offX || offY) { xy[0] -= offX; xy[1] -= offY; } if ((scrollTop || scrollLeft)) { if (!Y.UA.ios || (Y.UA.ios >= 4.2)) { xy[0] += scrollLeft; xy[1] += scrollTop; } } } else { xy = Y_DOM._getOffset(node); } } return xy; }; } else { return function(node) { // manually calculate by crawling up offsetParents //Calculate the Top and Left border sizes (assumes pixels) var xy = null, doc, parentNode, bCheck, scrollTop, scrollLeft; if (node) { if (Y_DOM.inDoc(node)) { xy = [node.offsetLeft, node.offsetTop]; doc = node.ownerDocument; parentNode = node; // TODO: refactor with !! or just falsey bCheck = ((Y.UA.gecko || Y.UA.webkit > 519) ? true : false); // TODO: worth refactoring for TOP/LEFT only? while ((parentNode = parentNode.offsetParent)) { xy[0] += parentNode.offsetLeft; xy[1] += parentNode.offsetTop; if (bCheck) { xy = Y_DOM._calcBorders(parentNode, xy); } } // account for any scrolled ancestors if (Y_DOM.getStyle(node, POSITION) != FIXED) { parentNode = node; while ((parentNode = parentNode.parentNode)) { scrollTop = parentNode.scrollTop; scrollLeft = parentNode.scrollLeft; //Firefox does something funky with borders when overflow is not visible. if (Y.UA.gecko && (Y_DOM.getStyle(parentNode, 'overflow') !== 'visible')) { xy = Y_DOM._calcBorders(parentNode, xy); } if (scrollTop || scrollLeft) { xy[0] -= scrollLeft; xy[1] -= scrollTop; } } xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } else { //Fix FIXED position -- add scrollbars xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } } else { xy = Y_DOM._getOffset(node); } } return xy; }; } }(),// NOTE: Executing for loadtime branching /** Gets the width of vertical scrollbars on overflowed containers in the body content. @method getScrollbarWidth @return {Number} Pixel width of a scrollbar in the current browser **/ getScrollbarWidth: Y.cached(function () { var doc = Y.config.doc, testNode = doc.createElement('div'), body = doc.getElementsByTagName('body')[0], // 0.1 because cached doesn't support falsy refetch values width = 0.1; if (body) { testNode.style.cssText = "position:absolute;visibility:hidden;overflow:scroll;width:20px;"; testNode.appendChild(doc.createElement('p')).style.height = '1px'; body.insertBefore(testNode, body.firstChild); width = testNode.offsetWidth - testNode.clientWidth; body.removeChild(testNode); } return width; }, null, 0.1), /** * Gets the current X position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getX * @param element The target element * @return {Number} The X position of the element */ getX: function(node) { return Y_DOM.getXY(node)[0]; }, /** * Gets the current Y position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getY * @param element The target element * @return {Number} The Y position of the element */ getY: function(node) { return Y_DOM.getXY(node)[1]; }, /** * Set the position of an html element in page coordinates. * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setXY * @param element The target element * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @param {Boolean} noRetry By default we try and set the position a second time if the first fails */ setXY: function(node, xy, noRetry) { var setStyle = Y_DOM.setStyle, pos, delta, newXY, currentXY; if (node && xy) { pos = Y_DOM.getStyle(node, POSITION); delta = Y_DOM._getOffset(node); if (pos == 'static') { // default to relative pos = RELATIVE; setStyle(node, POSITION, pos); } currentXY = Y_DOM.getXY(node); if (xy[0] !== null) { setStyle(node, LEFT, xy[0] - currentXY[0] + delta[0] + 'px'); } if (xy[1] !== null) { setStyle(node, TOP, xy[1] - currentXY[1] + delta[1] + 'px'); } if (!noRetry) { newXY = Y_DOM.getXY(node); if (newXY[0] !== xy[0] || newXY[1] !== xy[1]) { Y_DOM.setXY(node, xy, true); } } } else { } }, /** * Set the X position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setX * @param element The target element * @param {Number} x The X values for new position (coordinates are page-based) */ setX: function(node, x) { return Y_DOM.setXY(node, [x, null]); }, /** * Set the Y position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setY * @param element The target element * @param {Number} y The Y values for new position (coordinates are page-based) */ setY: function(node, y) { return Y_DOM.setXY(node, [null, y]); }, /** * @method swapXY * @description Swap the xy position with another node * @param {Node} node The node to swap with * @param {Node} otherNode The other node to swap with * @return {Node} */ swapXY: function(node, otherNode) { var xy = Y_DOM.getXY(node); Y_DOM.setXY(node, Y_DOM.getXY(otherNode)); Y_DOM.setXY(otherNode, xy); }, _calcBorders: function(node, xy2) { var t = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_TOP_WIDTH), 10) || 0, l = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_LEFT_WIDTH), 10) || 0; if (Y.UA.gecko) { if (RE_TABLE.test(node.tagName)) { t = 0; l = 0; } } xy2[0] += l; xy2[1] += t; return xy2; }, _getWinSize: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; var win = doc.defaultView || doc.parentWindow, mode = doc[COMPAT_MODE], h = win.innerHeight, w = win.innerWidth, root = doc[DOCUMENT_ELEMENT]; if ( mode && !Y.UA.opera ) { // IE, Gecko if (mode != 'CSS1Compat') { // Quirks root = doc.body; } h = root.clientHeight; w = root.clientWidth; } return { height: h, width: w }; }, _getDocSize: function(node) { var doc = (node) ? Y_DOM._getDoc(node) : Y.config.doc, root = doc[DOCUMENT_ELEMENT]; if (doc[COMPAT_MODE] != 'CSS1Compat') { root = doc.body; } return { height: root.scrollHeight, width: root.scrollWidth }; } }); })(Y); (function(Y) { var TOP = 'top', RIGHT = 'right', BOTTOM = 'bottom', LEFT = 'left', getOffsets = function(r1, r2) { var t = Math.max(r1[TOP], r2[TOP]), r = Math.min(r1[RIGHT], r2[RIGHT]), b = Math.min(r1[BOTTOM], r2[BOTTOM]), l = Math.max(r1[LEFT], r2[LEFT]), ret = {}; ret[TOP] = t; ret[RIGHT] = r; ret[BOTTOM] = b; ret[LEFT] = l; return ret; }, DOM = Y.DOM; Y.mix(DOM, { /** * Returns an Object literal containing the following about this element: (top, right, bottom, left) * @for DOM * @method region * @param {HTMLElement} element The DOM element. * @return {Object} Object literal containing the following about this element: (top, right, bottom, left) */ region: function(node) { var xy = DOM.getXY(node), ret = false; if (node && xy) { ret = DOM._getRegion( xy[1], // top xy[0] + node.offsetWidth, // right xy[1] + node.offsetHeight, // bottom xy[0] // left ); } return ret; }, /** * Find the intersect information for the passed nodes. * @method intersect * @for DOM * @param {HTMLElement} element The first element * @param {HTMLElement | Object} element2 The element or region to check the interect with * @param {Object} altRegion An object literal containing the region for the first element if we already have the data (for performance e.g. DragDrop) * @return {Object} Object literal containing the following intersection data: (top, right, bottom, left, area, yoff, xoff, inRegion) */ intersect: function(node, node2, altRegion) { var r = altRegion || DOM.region(node), region = {}, n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } off = getOffsets(region, r); return { top: off[TOP], right: off[RIGHT], bottom: off[BOTTOM], left: off[LEFT], area: ((off[BOTTOM] - off[TOP]) * (off[RIGHT] - off[LEFT])), yoff: ((off[BOTTOM] - off[TOP])), xoff: (off[RIGHT] - off[LEFT]), inRegion: DOM.inRegion(node, node2, false, altRegion) }; }, /** * Check if any part of this node is in the passed region * @method inRegion * @for DOM * @param {Object} node The node to get the region from * @param {Object} node2 The second node to get the region from or an Object literal of the region * @param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop) * @return {Boolean} True if in region, false if not. */ inRegion: function(node, node2, all, altRegion) { var region = {}, r = altRegion || DOM.region(node), n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } if (all) { return ( r[LEFT] >= region[LEFT] && r[RIGHT] <= region[RIGHT] && r[TOP] >= region[TOP] && r[BOTTOM] <= region[BOTTOM] ); } else { off = getOffsets(region, r); if (off[BOTTOM] >= off[TOP] && off[RIGHT] >= off[LEFT]) { return true; } else { return false; } } }, /** * Check if any part of this element is in the viewport * @method inViewportRegion * @for DOM * @param {HTMLElement} element The DOM element. * @param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop) * @return {Boolean} True if in region, false if not. */ inViewportRegion: function(node, all, altRegion) { return DOM.inRegion(node, DOM.viewportRegion(node), all, altRegion); }, _getRegion: function(t, r, b, l) { var region = {}; region[TOP] = region[1] = t; region[LEFT] = region[0] = l; region[BOTTOM] = b; region[RIGHT] = r; region.width = region[RIGHT] - region[LEFT]; region.height = region[BOTTOM] - region[TOP]; return region; }, /** * Returns an Object literal containing the following about the visible region of viewport: (top, right, bottom, left) * @method viewportRegion * @for DOM * @return {Object} Object literal containing the following about the visible region of the viewport: (top, right, bottom, left) */ viewportRegion: function(node) { node = node || Y.config.doc.documentElement; var ret = false, scrollX, scrollY; if (node) { scrollX = DOM.docScrollX(node); scrollY = DOM.docScrollY(node); ret = DOM._getRegion(scrollY, // top DOM.winWidth(node) + scrollX, // right scrollY + DOM.winHeight(node), // bottom scrollX); // left } return ret; } }); })(Y); }, '3.8.0pr2', {"requires": ["dom-base", "dom-style"]}); YUI.add('selector-native', function (Y, NAME) { (function(Y) { /** * The selector-native module provides support for native querySelector * @module dom * @submodule selector-native * @for Selector */ /** * Provides support for using CSS selectors to query the DOM * @class Selector * @static * @for Selector */ Y.namespace('Selector'); // allow native module to standalone var COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', OWNER_DOCUMENT = 'ownerDocument'; var Selector = { _types: { esc: { token: '\uE000', re: /\\[:\[\]\(\)#\.\'\>+~"]/gi }, attr: { token: '\uE001', re: /(\[[^\]]*\])/g }, pseudo: { token: '\uE002', re: /(\([^\)]*\))/g } }, useNative: true, _escapeId: function(id) { if (id) { id = id.replace(/([:\[\]\(\)#\.'<>+~"])/g,'\\$1'); } return id; }, _compare: ('sourceIndex' in Y.config.doc.documentElement) ? function(nodeA, nodeB) { var a = nodeA.sourceIndex, b = nodeB.sourceIndex; if (a === b) { return 0; } else if (a > b) { return 1; } return -1; } : (Y.config.doc.documentElement[COMPARE_DOCUMENT_POSITION] ? function(nodeA, nodeB) { if (nodeA[COMPARE_DOCUMENT_POSITION](nodeB) & 4) { return -1; } else { return 1; } } : function(nodeA, nodeB) { var rangeA, rangeB, compare; if (nodeA && nodeB) { rangeA = nodeA[OWNER_DOCUMENT].createRange(); rangeA.setStart(nodeA, 0); rangeB = nodeB[OWNER_DOCUMENT].createRange(); rangeB.setStart(nodeB, 0); compare = rangeA.compareBoundaryPoints(1, rangeB); // 1 === Range.START_TO_END } return compare; }), _sort: function(nodes) { if (nodes) { nodes = Y.Array(nodes, 0, true); if (nodes.sort) { nodes.sort(Selector._compare); } } return nodes; }, _deDupe: function(nodes) { var ret = [], i, node; for (i = 0; (node = nodes[i++]);) { if (!node._found) { ret[ret.length] = node; node._found = true; } } for (i = 0; (node = ret[i++]);) { node._found = null; node.removeAttribute('_found'); } return ret; }, /** * Retrieves a set of nodes based on a given CSS selector. * @method query * * @param {string} selector The CSS Selector to test the node against. * @param {HTMLElement} root optional An HTMLElement to start the query from. Defaults to Y.config.doc * @param {Boolean} firstOnly optional Whether or not to return only the first match. * @return {Array} An array of nodes that match the given selector. * @static */ query: function(selector, root, firstOnly, skipNative) { root = root || Y.config.doc; var ret = [], useNative = (Y.Selector.useNative && Y.config.doc.querySelector && !skipNative), queries = [[selector, root]], query, result, i, fn = (useNative) ? Y.Selector._nativeQuery : Y.Selector._bruteQuery; if (selector && fn) { // split group into seperate queries if (!skipNative && // already done if skipping (!useNative || root.tagName)) { // split native when element scoping is needed queries = Selector._splitQueries(selector, root); } for (i = 0; (query = queries[i++]);) { result = fn(query[0], query[1], firstOnly); if (!firstOnly) { // coerce DOM Collection to Array result = Y.Array(result, 0, true); } if (result) { ret = ret.concat(result); } } if (queries.length > 1) { // remove dupes and sort by doc order ret = Selector._sort(Selector._deDupe(ret)); } } return (firstOnly) ? (ret[0] || null) : ret; }, _replaceSelector: function(selector) { var esc = Y.Selector._parse('esc', selector), // pull escaped colon, brackets, etc. attrs, pseudos; // first replace escaped chars, which could be present in attrs or pseudos selector = Y.Selector._replace('esc', selector); // then replace pseudos before attrs to avoid replacing :not([foo]) pseudos = Y.Selector._parse('pseudo', selector); selector = Selector._replace('pseudo', selector); attrs = Y.Selector._parse('attr', selector); selector = Y.Selector._replace('attr', selector); return { esc: esc, attrs: attrs, pseudos: pseudos, selector: selector }; }, _restoreSelector: function(replaced) { var selector = replaced.selector; selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _replaceCommas: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; if (selector) { selector = selector.replace(/,/g, '\uE007'); replaced.selector = selector; selector = Y.Selector._restoreSelector(replaced); } return selector; }, // allows element scoped queries to begin with combinator // e.g. query('> p', document.body) === query('body > p') _splitQueries: function(selector, node) { if (selector.indexOf(',') > -1) { selector = Y.Selector._replaceCommas(selector); } var groups = selector.split('\uE007'), // split on replaced comma token queries = [], prefix = '', id, i, len; if (node) { // enforce for element scoping if (node.nodeType === 1) { // Elements only id = Y.Selector._escapeId(Y.DOM.getId(node)); if (!id) { id = Y.guid(); Y.DOM.setId(node, id); } prefix = '[id="' + id + '"] '; } for (i = 0, len = groups.length; i < len; ++i) { selector = prefix + groups[i]; queries.push([selector, node]); } } return queries; }, _nativeQuery: function(selector, root, one) { if (Y.UA.webkit && selector.indexOf(':checked') > -1 && (Y.Selector.pseudos && Y.Selector.pseudos.checked)) { // webkit (chrome, safari) fails to pick up "selected" with "checked" return Y.Selector.query(selector, root, one, true); // redo with skipNative true to try brute query } try { return root['querySelector' + (one ? '' : 'All')](selector); } catch(e) { // fallback to brute if available return Y.Selector.query(selector, root, one, true); // redo with skipNative true } }, filter: function(nodes, selector) { var ret = [], i, node; if (nodes && selector) { for (i = 0; (node = nodes[i++]);) { if (Y.Selector.test(node, selector)) { ret[ret.length] = node; } } } else { } return ret; }, test: function(node, selector, root) { var ret = false, useFrag = false, groups, parent, item, items, frag, id, i, j, group; if (node && node.tagName) { // only test HTMLElements if (typeof selector == 'function') { // test with function ret = selector.call(node, node); } else { // test with query // we need a root if off-doc groups = selector.split(','); if (!root && !Y.DOM.inDoc(node)) { parent = node.parentNode; if (parent) { root = parent; } else { // only use frag when no parent to query frag = node[OWNER_DOCUMENT].createDocumentFragment(); frag.appendChild(node); root = frag; useFrag = true; } } root = root || node[OWNER_DOCUMENT]; id = Y.Selector._escapeId(Y.DOM.getId(node)); if (!id) { id = Y.guid(); Y.DOM.setId(node, id); } for (i = 0; (group = groups[i++]);) { // TODO: off-dom test group += '[id="' + id + '"]'; items = Y.Selector.query(group, root); for (j = 0; item = items[j++];) { if (item === node) { ret = true; break; } } if (ret) { break; } } if (useFrag) { // cleanup frag.removeChild(node); } }; } return ret; }, /** * A convenience function to emulate Y.Node's aNode.ancestor(selector). * @param {HTMLElement} element An HTMLElement to start the query from. * @param {String} selector The CSS selector to test the node against. * @return {HTMLElement} The ancestor node matching the selector, or null. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @static * @method ancestor */ ancestor: function (element, selector, testSelf) { return Y.DOM.ancestor(element, function(n) { return Y.Selector.test(n, selector); }, testSelf); }, _parse: function(name, selector) { return selector.match(Y.Selector._types[name].re); }, _replace: function(name, selector) { var o = Y.Selector._types[name]; return selector.replace(o.re, o.token); }, _restore: function(name, selector, items) { if (items) { var token = Y.Selector._types[name].token, i, len; for (i = 0, len = items.length; i < len; ++i) { selector = selector.replace(token, items[i]); } } return selector; } }; Y.mix(Y.Selector, Selector, true); })(Y); }, '3.8.0pr2', {"requires": ["dom-base"]}); YUI.add('selector', function (Y, NAME) { }, '3.8.0pr2', {"requires": ["selector-native"]}); YUI.add('event-custom-base', function (Y, NAME) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static * @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object * replaces the role of this property, but is considered to be private, and * is only mentioned to provide a migration path. * * If you have a use case which warrants migration to the _yuiaop property, * please file a ticket to let us know what it's used for and we can see if * we need to expose hooks for that functionality more formally. */ objs: null, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (!obj._yuiaop) { // create a map entry for the obj if it doesn't exist, to hold overridden methods obj._yuiaop = {}; } o = obj._yuiaop; if (!o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var YArray = Y.Array, AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], CONFIGS_HASH = YArray.hash(CONFIGS), nativeSlice = Array.prototype.slice, YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log', mixConfigs = function(r, s, ov) { var p; for (p in s) { if (CONFIGS_HASH[p] && (ov || !(p in r))) { r[p] = s[p]; } } return r; }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} o configuration object. * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { this._kds = Y.CustomEvent.keepDeprecatedSubs; o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber {} * @deprecated */ if (this._kds) { this.subscribers = {}; } /** * The subscribers to this event * @property _subscribers * @type Subscriber [] * @private */ this._subscribers = []; /** * 'After' subscribers * @property afters * @type Subscriber {} */ if (this._kds) { this.afters = {}; } /** * 'After' subscribers * @property _afters * @type Subscriber [] * @private */ this._afters = []; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; // this.subCount = 0; // this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; /** * Static flag to enable population of the <a href="#property_subscribers">`subscribers`</a> * and <a href="#property_subscribers">`afters`</a> properties held on a `CustomEvent` instance. * * These properties were changed to private properties (`_subscribers` and `_afters`), and * converted from objects to arrays for performance reasons. * * Setting this property to true will populate the deprecated `subscribers` and `afters` * properties for people who may be using them (which is expected to be rare). There will * be a performance hit, compared to the new array based implementation. * * If you are using these deprecated properties for a use case which the public API * does not support, please file an enhancement request, and we can provide an alternate * public implementation which doesn't have the performance cost required to maintiain the * properties as objects. * * @property keepDeprecatedSubs * @static * @for CustomEvent * @type boolean * @default false * @deprecated */ Y.CustomEvent.keepDeprecatedSubs = false; Y.CustomEvent.mixConfigs = mixConfigs; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = this._subscribers.length, a = this._afters.length, sib = this.sibling; if (sib) { s += sib._subscribers.length; a += sib._afters.length; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = nativeSlice.call(arguments, 0); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var s = this._subscribers, a = this._afters, sib = this.sibling; s = (sib) ? s.concat(sib._subscribers) : s.concat(); a = (sib) ? a.concat(sib._afters) : a.concat(); return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { mixConfigs(this, o, force); }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this._afters.push(s); } else { this._subscribers.push(s); } if (this._kds) { if (when == AFTER) { this.afters[s.id] = s; } else { this.subscribers[s.id] = s; } } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; if (this.monitored && this.host) { this.host._monitor('attach', this, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = this._subscribers, afters = this._afters; for (i = subs.length; i >= 0; i--) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, subs, i); found++; } } for (i = afters.length; i >= 0; i--) { s = afters[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, afters, i); found++; } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = nativeSlice.call(arguments, 0); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; if (this.fireOnce) { this.firedWith = args; } if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { this.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i, l; for (i = 0, l = subs.length; i < l; i++) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = args.concat(); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param s subscriber object. * @param subs (optional) on or after subscriber array * @param index (optional) The index found. * @private */ _delete: function(s, subs, i) { var when = s._when; if (!subs) { subs = (when === AFTER) ? this._afters : this._subscribers; i = YArray.indexOf(subs, s, 0); } if (s && subs[i] === s) { subs.splice(i, 1); } if (this._kds) { if (when === AFTER) { delete this.afters[s.id]; } else { delete this.subscribers[s.id]; } } if (this.monitored && this.host) { this.host._monitor('detach', this, { ce: this, sub: s }); } if (s) { s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args, when) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; this._when = when; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config && Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } }, valueOf : function() { return this.id; } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', WILD_TYPE_RE = /(.*?)(:)(.*?)/, _wildType = Y.cached(function(type) { return type.replace(WILD_TYPE_RE, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || (typeof type !== "string") || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaultTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var handle = this.after.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var yuievt = this._yuievt, parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = nativeSlice.call(arguments, 0); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = nativeSlice.call(arguments, 0); args.splice(2, 0, Node.getDOMNode(this)); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = nativeSlice.call(arguments, 0); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = nativeSlice.call(arguments, 0); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = nativeSlice.call(arguments, 0); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, defaults, edata = this._yuievt, pre = edata.config.prefix; if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } type = (pre) ? _getType(type, pre) : type; events = edata.events; ce = events[type]; this._monitor('publish', type, { args: arguments }); if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { // TODO: Lazy publish goes here. defaults = edata.defaults; // apply defaults ce = new Y.CustomEvent(type, defaults); if (opts) { ce.applyConfig(opts, true); } events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object. * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, eventType, o) { var monitorevt, ce, type; if (eventType) { if (typeof eventType === "string") { type = eventType; ce = this.getEvent(eventType, true); } else { ce = eventType; type = eventType.type; } if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; o.monitored = what; this.fire.call(this, monitorevt, o); } } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), yuievt = this._yuievt, pre = yuievt.config.prefix, ce, ret, ce2, args = (typeIncluded) ? nativeSlice.call(arguments, 1) : arguments; t = (pre) ? _getType(t, pre) : t; ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } this._monitor('fire', (ce || t), { args: args }); // this event has not been published or subscribed to if (!ce) { if (yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = nativeSlice.call(arguments, 0); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '3.8.0pr2', {"requires": ["oop"]}); YUI.add('event-custom-complex', function (Y, NAME) { /** * Adds event facades, preventable default behavior, and bubbling. * events. * @module event-custom * @submodule event-custom-complex */ var FACADE, FACADE_KEYS, key, EMPTY = {}, CEProto = Y.CustomEvent.prototype, ETProto = Y.EventTarget.prototype, mixFacadeProps = function(facade, payload) { var p; for (p in payload) { if (!(FACADE_KEYS.hasOwnProperty(p))) { facade[p] = payload[p]; } } }; /** * Wraps and protects a custom event for use when emitFacade is set to true. * Requires the event-custom-complex module * @class EventFacade * @param e {Event} the custom event * @param currentTarget {HTMLElement} the element the listener was attached to */ Y.EventFacade = function(e, currentTarget) { e = e || EMPTY; this._event = e; /** * The arguments passed to fire * @property details * @type Array */ this.details = e.details; /** * The event type, this can be overridden by the fire() payload * @property type * @type string */ this.type = e.type; /** * The real event type * @property _type * @type string * @private */ this._type = e.type; ////////////////////////////////////////////////////// /** * Node reference for the targeted eventtarget * @property target * @type Node */ this.target = e.target; /** * Node reference for the element that the listener was attached to. * @property currentTarget * @type Node */ this.currentTarget = currentTarget; /** * Node reference to the relatedTarget * @property relatedTarget * @type Node */ this.relatedTarget = e.relatedTarget; }; Y.mix(Y.EventFacade.prototype, { /** * Stops the propagation to the next bubble target * @method stopPropagation */ stopPropagation: function() { this._event.stopPropagation(); this.stopped = 1; }, /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ stopImmediatePropagation: function() { this._event.stopImmediatePropagation(); this.stopped = 2; }, /** * Prevents the event's default behavior * @method preventDefault */ preventDefault: function() { this._event.preventDefault(); this.prevented = 1; }, /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ halt: function(immediate) { this._event.halt(immediate); this.prevented = 1; this.stopped = (immediate) ? 2 : 1; } }); CEProto.fireComplex = function(args) { var es, ef, q, queue, ce, ret, events, subs, postponed, self = this, host = self.host || self, next, oldbubble; if (self.stack) { // queue this event if the current item in the queue bubbles if (self.queuable && self.type != self.stack.next.type) { self.log('queue ' + self.type); self.stack.queue.push([self, args]); return true; } } es = self.stack || { // id of the first event in the stack id: self.id, next: self, silent: self.silent, stopped: 0, prevented: 0, bubbling: null, type: self.type, // defaultFnQueue: new Y.Queue(), afterQueue: new Y.Queue(), defaultTargetOnly: self.defaultTargetOnly, queue: [] }; subs = self.getSubs(); self.stopped = (self.type !== es.type) ? 0 : es.stopped; self.prevented = (self.type !== es.type) ? 0 : es.prevented; self.target = self.target || host; if (self.stoppedFn) { events = new Y.EventTarget({ fireOnce: true, context: host }); self.events = events; events.on('stopped', self.stoppedFn); } self.currentTarget = host; self.details = args.slice(); // original arguments in the details // self.log("Firing " + self + ", " + "args: " + args); self.log("Firing " + self.type); self._facade = null; // kill facade to eliminate stale properties ef = self._getFacade(args); if (Y.Lang.isObject(args[0])) { args[0] = ef; } else { args.unshift(ef); } if (subs[0]) { self._procSubs(subs[0], args, ef); } // bubble if this is hosted in an event target and propagation has not been stopped if (self.bubbles && host.bubble && !self.stopped) { oldbubble = es.bubbling; es.bubbling = self.type; if (es.type != self.type) { es.stopped = 0; es.prevented = 0; } ret = host.bubble(self, args, null, es); self.stopped = Math.max(self.stopped, es.stopped); self.prevented = Math.max(self.prevented, es.prevented); es.bubbling = oldbubble; } if (self.prevented) { if (self.preventedFn) { self.preventedFn.apply(host, args); } } else if (self.defaultFn && ((!self.defaultTargetOnly && !es.defaultTargetOnly) || host === ef.target)) { self.defaultFn.apply(host, args); } // broadcast listeners are fired as discreet events on the // YUI instance and potentially the YUI global. self._broadcast(args); // Queue the after if (subs[1] && !self.prevented && self.stopped < 2) { if (es.id === self.id || self.type != host._yuievt.bubbling) { self._procSubs(subs[1], args, ef); while ((next = es.afterQueue.last())) { next(); } } else { postponed = subs[1]; if (es.execDefaultCnt) { postponed = Y.merge(postponed); Y.each(postponed, function(s) { s.postponed = true; }); } es.afterQueue.add(function() { self._procSubs(postponed, args, ef); }); } } self.target = null; if (es.id === self.id) { queue = es.queue; while (queue.length) { q = queue.pop(); ce = q[0]; // set up stack to allow the next item to be processed es.next = ce; ce.fire.apply(ce, q[1]); } self.stack = null; } ret = !(self.stopped); if (self.type != host._yuievt.bubbling) { es.stopped = 0; es.prevented = 0; self.stopped = 0; self.prevented = 0; } // Kill the cached facade to free up memory. // Otherwise we have the facade from the last fire, sitting around forever. self._facade = null; return ret; }; CEProto._getFacade = function() { var ef = this._facade, o, args = this.details; if (!ef) { ef = new Y.EventFacade(this, this.currentTarget); } // if the first argument is an object literal, apply the // properties to the event facade o = args && args[0]; if (Y.Lang.isObject(o, true)) { // protect the event facade properties mixFacadeProps(ef, o); // Allow the event type to be faked // http://yuilibrary.com/projects/yui3/ticket/2528376 ef.type = o.type || ef.type; } // update the details field with the arguments // ef.type = this.type; ef.details = this.details; // use the original target when the event bubbled to this target ef.target = this.originalTarget || this.target; ef.currentTarget = this.currentTarget; ef.stopped = 0; ef.prevented = 0; this._facade = ef; return this._facade; }; /** * Stop propagation to bubble targets * @for CustomEvent * @method stopPropagation */ CEProto.stopPropagation = function() { this.stopped = 1; if (this.stack) { this.stack.stopped = 1; } if (this.events) { this.events.fire('stopped', this); } }; /** * Stops propagation to bubble targets, and prevents any remaining * subscribers on the current target from executing. * @method stopImmediatePropagation */ CEProto.stopImmediatePropagation = function() { this.stopped = 2; if (this.stack) { this.stack.stopped = 2; } if (this.events) { this.events.fire('stopped', this); } }; /** * Prevents the execution of this event's defaultFn * @method preventDefault */ CEProto.preventDefault = function() { if (this.preventable) { this.prevented = 1; if (this.stack) { this.stack.prevented = 1; } } }; /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ CEProto.halt = function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); }; /** * Registers another EventTarget as a bubble target. Bubble order * is determined by the order registered. Multiple targets can * be specified. * * Events can only bubble if emitFacade is true. * * Included in the event-custom-complex submodule. * * @method addTarget * @param o {EventTarget} the target to add * @for EventTarget */ ETProto.addTarget = function(o) { this._yuievt.targets[Y.stamp(o)] = o; this._yuievt.hasTargets = true; }; /** * Returns an array of bubble targets for this object. * @method getTargets * @return EventTarget[] */ ETProto.getTargets = function() { return Y.Object.values(this._yuievt.targets); }; /** * Removes a bubble target * @method removeTarget * @param o {EventTarget} the target to remove * @for EventTarget */ ETProto.removeTarget = function(o) { delete this._yuievt.targets[Y.stamp(o)]; }; /** * Propagate an event. Requires the event-custom-complex module. * @method bubble * @param evt {CustomEvent} the custom event to propagate * @return {boolean} the aggregated return value from Event.Custom.fire * @for EventTarget */ ETProto.bubble = function(evt, args, target, es) { var targs = this._yuievt.targets, ret = true, t, type = evt && evt.type, ce, i, bc, ce2, originalTarget = target || (evt && evt.target) || this, oldbubble; if (!evt || ((!evt.stopped) && targs)) { for (i in targs) { if (targs.hasOwnProperty(i)) { t = targs[i]; ce = t.getEvent(type, true); ce2 = t.getSibling(type, ce); if (ce2 && !ce) { ce = t.publish(type); } oldbubble = t._yuievt.bubbling; t._yuievt.bubbling = type; // if this event was not published on the bubble target, // continue propagating the event. if (!ce) { if (t._yuievt.hasTargets) { t.bubble(evt, args, originalTarget, es); } } else { ce.sibling = ce2; // set the original target to that the target payload on the // facade is correct. ce.target = originalTarget; ce.originalTarget = originalTarget; ce.currentTarget = t; bc = ce.broadcast; ce.broadcast = false; // default publish may not have emitFacade true -- that // shouldn't be what the implementer meant to do ce.emitFacade = true; ce.stack = es; ret = ret && ce.fire.apply(ce, args || evt.details || []); ce.broadcast = bc; ce.originalTarget = null; // stopPropagation() was called if (ce.stopped) { break; } } t._yuievt.bubbling = oldbubble; } } } return ret; }; FACADE = new Y.EventFacade(); FACADE_KEYS = {}; // Flatten whitelist for (key in FACADE) { FACADE_KEYS[key] = true; } }, '3.8.0pr2', {"requires": ["event-custom-base"]}); YUI.add('node-core', function (Y, NAME) { /** * The Node Utility provides a DOM-like interface for interacting with DOM nodes. * @module node * @main node * @submodule node-core */ /** * The Node class provides a wrapper for manipulating DOM Nodes. * Node properties can be accessed via the set/get methods. * Use `Y.one()` to retrieve Node instances. * * <strong>NOTE:</strong> Node properties are accessed using * the <code>set</code> and <code>get</code> methods. * * @class Node * @constructor * @param {DOMNode} node the DOM node to be mapped to the Node instance. * @uses EventTarget */ // "globals" var DOT = '.', NODE_NAME = 'nodeName', NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', TAG_NAME = 'tagName', UID = '_yuid', EMPTY_OBJ = {}, _slice = Array.prototype.slice, Y_DOM = Y.DOM, Y_Node = function(node) { if (!this.getDOMNode) { // support optional "new" return new Y_Node(node); } if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } var uid = (node.nodeType !== 9) ? node.uniqueID : node[UID]; if (uid && Y_Node._instances[uid] && Y_Node._instances[uid]._node !== node) { node[UID] = null; // unset existing uid to prevent collision (via clone or hack) } uid = uid || Y.stamp(node); if (!uid) { // stamp failed; likely IE non-HTMLElement uid = Y.guid(); } this[UID] = uid; /** * The underlying DOM node bound to the Y.Node instance * @property _node * @type DOMNode * @private */ this._node = node; this._stateProxy = node; // when augmented with Attribute if (this._initPlugins) { // when augmented with Plugin.Host this._initPlugins(); } }, // used with previous/next/ancestor tests _wrapFn = function(fn) { var ret = null; if (fn) { ret = (typeof fn == 'string') ? function(n) { return Y.Selector.test(n, fn); } : function(n) { return fn(Y.one(n)); }; } return ret; }; // end "globals" Y_Node.ATTRS = {}; Y_Node.DOM_EVENTS = {}; Y_Node._fromString = function(node) { if (node) { if (node.indexOf('doc') === 0) { // doc OR document node = Y.config.doc; } else if (node.indexOf('win') === 0) { // win OR window node = Y.config.win; } else { node = Y.Selector.query(node, null, true); } } return node || null; }; /** * The name of the component * @static * @type String * @property NAME */ Y_Node.NAME = 'node'; /* * The pattern used to identify ARIA attributes */ Y_Node.re_aria = /^(?:role$|aria-)/; Y_Node.SHOW_TRANSITION = 'fadeIn'; Y_Node.HIDE_TRANSITION = 'fadeOut'; /** * A list of Node instances that have been created * @private * @type Object * @property _instances * @static * */ Y_Node._instances = {}; /** * Retrieves the DOM node bound to a Node instance * @method getDOMNode * @static * * @param {Node | HTMLNode} node The Node instance or an HTMLNode * @return {HTMLNode} The DOM node bound to the Node instance. If a DOM node is passed * as the node argument, it is simply returned. */ Y_Node.getDOMNode = function(node) { if (node) { return (node.nodeType) ? node : node._node || null; } return null; }; /** * Checks Node return values and wraps DOM Nodes as Y.Node instances * and DOM Collections / Arrays as Y.NodeList instances. * Other return values just pass thru. If undefined is returned (e.g. no return) * then the Node instance is returned for chainability. * @method scrubVal * @static * * @param {any} node The Node instance or an HTMLNode * @return {Node | NodeList | Any} Depends on what is returned from the DOM node. */ Y_Node.scrubVal = function(val, node) { if (val) { // only truthy values are risky if (typeof val == 'object' || typeof val == 'function') { // safari nodeList === function if (NODE_TYPE in val || Y_DOM.isWindow(val)) {// node || window val = Y.one(val); } else if ((val.item && !val._nodes) || // dom collection or Node instance (val[0] && val[0][NODE_TYPE])) { // array of DOM Nodes val = Y.all(val); } } } else if (typeof val === 'undefined') { val = node; // for chaining } else if (val === null) { val = null; // IE: DOM null not the same as null } return val; }; /** * Adds methods to the Y.Node prototype, routing through scrubVal. * @method addMethod * @static * * @param {String} name The name of the method to add * @param {Function} fn The function that becomes the method * @param {Object} context An optional context to call the method with * (defaults to the Node instance) * @return {any} Depends on what is returned from the DOM node. */ Y_Node.addMethod = function(name, fn, context) { if (name && fn && typeof fn == 'function') { Y_Node.prototype[name] = function() { var args = _slice.call(arguments), node = this, ret; if (args[0] && args[0]._node) { args[0] = args[0]._node; } if (args[1] && args[1]._node) { args[1] = args[1]._node; } args.unshift(node._node); ret = fn.apply(node, args); if (ret) { // scrub truthy ret = Y_Node.scrubVal(ret, node); } (typeof ret != 'undefined') || (ret = node); return ret; }; } else { } }; /** * Imports utility methods to be added as Y.Node methods. * @method importMethod * @static * * @param {Object} host The object that contains the method to import. * @param {String} name The name of the method to import * @param {String} altName An optional name to use in place of the host name * @param {Object} context An optional context to call the method with */ Y_Node.importMethod = function(host, name, altName) { if (typeof name == 'string') { altName = altName || name; Y_Node.addMethod(altName, host[name], host); } else { Y.Array.each(name, function(n) { Y_Node.importMethod(host, n); }); } }; /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @param {String | HTMLElement} node a node or Selector * @return {Node | null} a Node instance or null if no match found. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @static * @param {String | HTMLElement} node a node or Selector * @return {Node | null} a Node instance or null if no match found. * @for Node */ Y_Node.one = function(node) { var instance = null, cachedNode, uid; if (node) { if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } else if (node.getDOMNode) { return node; // NOTE: return } if (node.nodeType || Y.DOM.isWindow(node)) { // avoid bad input (numbers, boolean, etc) uid = (node.uniqueID && node.nodeType !== 9) ? node.uniqueID : node._yuid; instance = Y_Node._instances[uid]; // reuse exising instances cachedNode = instance ? instance._node : null; if (!instance || (cachedNode && node !== cachedNode)) { // new Node when nodes don't match instance = new Y_Node(node); if (node.nodeType != 11) { // dont cache document fragment Y_Node._instances[instance[UID]] = instance; // cache node } } } } return instance; }; /** * The default setter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_SETTER * @static * @param {String} name The attribute/property being set * @param {any} val The value to be set * @return {any} The value */ Y_Node.DEFAULT_SETTER = function(name, val) { var node = this._stateProxy, strPath; if (name.indexOf(DOT) > -1) { strPath = name; name = name.split(DOT); // only allow when defined on node Y.Object.setValue(node, name, val); } else if (typeof node[name] != 'undefined') { // pass thru DOM properties node[name] = val; } return val; }; /** * The default getter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_GETTER * @static * @param {String} name The attribute/property to look up * @return {any} The current value */ Y_Node.DEFAULT_GETTER = function(name) { var node = this._stateProxy, val; if (name.indexOf && name.indexOf(DOT) > -1) { val = Y.Object.getValue(node, name.split(DOT)); } else if (typeof node[name] != 'undefined') { // pass thru from DOM val = node[name]; } return val; }; Y.mix(Y_Node.prototype, { DATA_PREFIX: 'data-', /** * The method called when outputting Node instances as strings * @method toString * @return {String} A string representation of the Node instance */ toString: function() { var str = this[UID] + ': not bound to a node', node = this._node, attrs, id, className; if (node) { attrs = node.attributes; id = (attrs && attrs.id) ? node.getAttribute('id') : null; className = (attrs && attrs.className) ? node.getAttribute('className') : null; str = node[NODE_NAME]; if (id) { str += '#' + id; } if (className) { str += '.' + className.replace(' ', '.'); } // TODO: add yuid? str += ' ' + this[UID]; } return str; }, /** * Returns an attribute value on the Node instance. * Unless pre-configured (via `Node.ATTRS`), get hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be queried. * @method get * @param {String} attr The attribute * @return {any} The current value of the attribute */ get: function(attr) { var val; if (this._getAttr) { // use Attribute imple val = this._getAttr(attr); } else { val = this._get(attr); } if (val) { val = Y_Node.scrubVal(val, this); } else if (val === null) { val = null; // IE: DOM null is not true null (even though they ===) } return val; }, /** * Helper method for get. * @method _get * @private * @param {String} attr The attribute * @return {any} The current value of the attribute */ _get: function(attr) { var attrConfig = Y_Node.ATTRS[attr], val; if (attrConfig && attrConfig.getter) { val = attrConfig.getter.call(this); } else if (Y_Node.re_aria.test(attr)) { val = this._node.getAttribute(attr, 2); } else { val = Y_Node.DEFAULT_GETTER.apply(this, arguments); } return val; }, /** * Sets an attribute on the Node instance. * Unless pre-configured (via Node.ATTRS), set hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be set. * To set custom attributes use setAttribute. * @method set * @param {String} attr The attribute to be set. * @param {any} val The value to set the attribute to. * @chainable */ set: function(attr, val) { var attrConfig = Y_Node.ATTRS[attr]; if (this._setAttr) { // use Attribute imple this._setAttr.apply(this, arguments); } else { // use setters inline if (attrConfig && attrConfig.setter) { attrConfig.setter.call(this, val, attr); } else if (Y_Node.re_aria.test(attr)) { // special case Aria this._node.setAttribute(attr, val); } else { Y_Node.DEFAULT_SETTER.apply(this, arguments); } } return this; }, /** * Sets multiple attributes. * @method setAttrs * @param {Object} attrMap an object of name/value pairs to set * @chainable */ setAttrs: function(attrMap) { if (this._setAttrs) { // use Attribute imple this._setAttrs(attrMap); } else { // use setters inline Y.Object.each(attrMap, function(v, n) { this.set(n, v); }, this); } return this; }, /** * Returns an object containing the values for the requested attributes. * @method getAttrs * @param {Array} attrs an array of attributes to get values * @return {Object} An object with attribute name/value pairs. */ getAttrs: function(attrs) { var ret = {}; if (this._getAttrs) { // use Attribute imple this._getAttrs(attrs); } else { // use setters inline Y.Array.each(attrs, function(v, n) { ret[v] = this.get(v); }, this); } return ret; }, /** * Compares nodes to determine if they match. * Node instances can be compared to each other and/or HTMLElements. * @method compareTo * @param {HTMLElement | Node} refNode The reference node to compare to the node. * @return {Boolean} True if the nodes match, false if they do not. */ compareTo: function(refNode) { var node = this._node; if (refNode && refNode._node) { refNode = refNode._node; } return node === refNode; }, /** * Determines whether the node is appended to the document. * @method inDoc * @param {Node|HTMLElement} doc optional An optional document to check against. * Defaults to current document. * @return {Boolean} Whether or not this node is appended to the document. */ inDoc: function(doc) { var node = this._node; doc = (doc) ? doc._node || doc : node[OWNER_DOCUMENT]; if (doc.documentElement) { return Y_DOM.contains(doc.documentElement, node); } }, getById: function(id) { var node = this._node, ret = Y_DOM.byId(id, node[OWNER_DOCUMENT]); if (ret && Y_DOM.contains(node, ret)) { ret = Y.one(ret); } else { ret = null; } return ret; }, /** * Returns the nearest ancestor that passes the test applied by supplied boolean method. * @method ancestor * @param {String | Function} fn A selector string or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * If fn is not passed as an argument, the parent node will be returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @param {String | Function} stopFn optional A selector string or boolean * method to indicate when the search should stop. The search bails when the function * returns true or the selector matches. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} The matching Node instance or null if not found */ ancestor: function(fn, testSelf, stopFn) { // testSelf is optional, check for stopFn as 2nd arg if (arguments.length === 2 && (typeof testSelf == 'string' || typeof testSelf == 'function')) { stopFn = testSelf; } return Y.one(Y_DOM.ancestor(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn))); }, /** * Returns the ancestors that pass the test applied by supplied boolean method. * @method ancestors * @param {String | Function} fn A selector string or boolean method for testing elements. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} A NodeList instance containing the matching elements */ ancestors: function(fn, testSelf, stopFn) { if (arguments.length === 2 && (typeof testSelf == 'string' || typeof testSelf == 'function')) { stopFn = testSelf; } return Y.all(Y_DOM.ancestors(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn))); }, /** * Returns the previous matching sibling. * Returns the nearest element node sibling if no method provided. * @method previous * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ previous: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'previousSibling', _wrapFn(fn), all)); }, /** * Returns the next matching sibling. * Returns the nearest element node sibling if no method provided. * @method next * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ next: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'nextSibling', _wrapFn(fn), all)); }, /** * Returns all matching siblings. * Returns all siblings if no method provided. * @method siblings * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} NodeList instance bound to found siblings */ siblings: function(fn) { return Y.all(Y_DOM.siblings(this._node, _wrapFn(fn))); }, /** * Retrieves a single Node instance, the first element matching the given * CSS selector. * Returns null if no match found. * @method one * * @param {string} selector The CSS selector to test against. * @return {Node | null} A Node instance for the matching HTMLElement or null * if no match found. */ one: function(selector) { return Y.one(Y.Selector.query(selector, this._node, true)); }, /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. */ all: function(selector) { var nodelist = Y.all(Y.Selector.query(selector, this._node)); nodelist._query = selector; nodelist._queryRoot = this._node; return nodelist; }, // TODO: allow fn test /** * Test if the supplied node matches the supplied selector. * @method test * * @param {string} selector The CSS selector to test against. * @return {boolean} Whether or not the node matches the selector. */ test: function(selector) { return Y.Selector.test(this._node, selector); }, /** * Removes the node from its parent. * Shortcut for myNode.get('parentNode').removeChild(myNode); * @method remove * @param {Boolean} destroy whether or not to call destroy() on the node * after removal. * @chainable * */ remove: function(destroy) { var node = this._node; if (node && node.parentNode) { node.parentNode.removeChild(node); } if (destroy) { this.destroy(); } return this; }, /** * Replace the node with the other node. This is a DOM update only * and does not change the node bound to the Node instance. * Shortcut for myNode.get('parentNode').replaceChild(newNode, myNode); * @method replace * @param {Node | HTMLNode} newNode Node to be inserted * @chainable * */ replace: function(newNode) { var node = this._node; if (typeof newNode == 'string') { newNode = Y_Node.create(newNode); } node.parentNode.replaceChild(Y_Node.getDOMNode(newNode), node); return this; }, /** * @method replaceChild * @for Node * @param {String | HTMLElement | Node} node Node to be inserted * @param {HTMLElement | Node} refNode Node to be replaced * @return {Node} The replaced node */ replaceChild: function(node, refNode) { if (typeof node == 'string') { node = Y_DOM.create(node); } return Y.one(this._node.replaceChild(Y_Node.getDOMNode(node), Y_Node.getDOMNode(refNode))); }, /** * Nulls internal node references, removes any plugins and event listeners. * Note that destroy() will not remove the node from its parent or from the DOM. For that * functionality, call remove(true). * @method destroy * @param {Boolean} recursivePurge (optional) Whether or not to remove listeners from the * node's subtree (default is false) * */ destroy: function(recursive) { var UID = Y.config.doc.uniqueID ? 'uniqueID' : '_yuid', instance; this.purge(); // TODO: only remove events add via this Node if (this.unplug) { // may not be a PluginHost this.unplug(); } this.clearData(); if (recursive) { Y.NodeList.each(this.all('*'), function(node) { instance = Y_Node._instances[node[UID]]; if (instance) { instance.destroy(); } else { // purge in case added by other means Y.Event.purgeElement(node); } }); } this._node = null; this._stateProxy = null; delete Y_Node._instances[this._yuid]; }, /** * Invokes a method on the Node instance * @method invoke * @param {String} method The name of the method to invoke * @param {Any} a, b, c, etc. Arguments to invoke the method with. * @return Whatever the underly method returns. * DOM Nodes and Collections return values * are converted to Node/NodeList instances. * */ invoke: function(method, a, b, c, d, e) { var node = this._node, ret; if (a && a._node) { a = a._node; } if (b && b._node) { b = b._node; } ret = node[method](a, b, c, d, e); return Y_Node.scrubVal(ret, this); }, /** * @method swap * @description Swap DOM locations with the given node. * This does not change which DOM node each Node instance refers to. * @param {Node} otherNode The node to swap with * @chainable */ swap: Y.config.doc.documentElement.swapNode ? function(otherNode) { this._node.swapNode(Y_Node.getDOMNode(otherNode)); } : function(otherNode) { otherNode = Y_Node.getDOMNode(otherNode); var node = this._node, parent = otherNode.parentNode, nextSibling = otherNode.nextSibling; if (nextSibling === node) { parent.insertBefore(node, otherNode); } else if (otherNode === node.nextSibling) { parent.insertBefore(otherNode, node); } else { node.parentNode.replaceChild(otherNode, node); Y_DOM.addHTML(parent, node, nextSibling); } return this; }, hasMethod: function(method) { var node = this._node; return !!(node && method in node && typeof node[method] != 'unknown' && (typeof node[method] == 'function' || String(node[method]).indexOf('function') === 1)); // IE reports as object, prepends space }, isFragment: function() { return (this.get('nodeType') === 11); }, /** * Removes and destroys all of the nodes within the node. * @method empty * @chainable */ empty: function() { this.get('childNodes').remove().destroy(true); return this; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNode * @return {DOMNode} */ getDOMNode: function() { return this._node; } }, true); Y.Node = Y_Node; Y.one = Y_Node.one; /** * The NodeList module provides support for managing collections of Nodes. * @module node * @submodule node-core */ /** * The NodeList class provides a wrapper for manipulating DOM NodeLists. * NodeList properties can be accessed via the set/get methods. * Use Y.all() to retrieve NodeList instances. * * @class NodeList * @constructor * @param nodes {String|element|Node|Array} A selector, DOM element, Node, list of DOM elements, or list of Nodes with which to populate this NodeList. */ var NodeList = function(nodes) { var tmp = []; if (nodes) { if (typeof nodes === 'string') { // selector query this._query = nodes; nodes = Y.Selector.query(nodes); } else if (nodes.nodeType || Y_DOM.isWindow(nodes)) { // domNode || window nodes = [nodes]; } else if (nodes._node) { // Y.Node nodes = [nodes._node]; } else if (nodes[0] && nodes[0]._node) { // allow array of Y.Nodes Y.Array.each(nodes, function(node) { if (node._node) { tmp.push(node._node); } }); nodes = tmp; } else { // array of domNodes or domNodeList (no mixed array of Y.Node/domNodes) nodes = Y.Array(nodes, 0, true); } } /** * The underlying array of DOM nodes bound to the Y.NodeList instance * @property _nodes * @private */ this._nodes = nodes || []; }; NodeList.NAME = 'NodeList'; /** * Retrieves the DOM nodes bound to a NodeList instance * @method getDOMNodes * @static * * @param {NodeList} nodelist The NodeList instance * @return {Array} The array of DOM nodes bound to the NodeList */ NodeList.getDOMNodes = function(nodelist) { return (nodelist && nodelist._nodes) ? nodelist._nodes : nodelist; }; NodeList.each = function(instance, fn, context) { var nodes = instance._nodes; if (nodes && nodes.length) { Y.Array.each(nodes, fn, context || instance); } else { } }; NodeList.addMethod = function(name, fn, context) { if (name && fn) { NodeList.prototype[name] = function() { var ret = [], args = arguments; Y.Array.each(this._nodes, function(node) { var UID = (node.uniqueID && node.nodeType !== 9 ) ? 'uniqueID' : '_yuid', instance = Y.Node._instances[node[UID]], ctx, result; if (!instance) { instance = NodeList._getTempNode(node); } ctx = context || instance; result = fn.apply(ctx, args); if (result !== undefined && result !== instance) { ret[ret.length] = result; } }); // TODO: remove tmp pointer return ret.length ? ret : this; }; } else { } }; NodeList.importMethod = function(host, name, altName) { if (typeof name === 'string') { altName = altName || name; NodeList.addMethod(name, host[name]); } else { Y.Array.each(name, function(n) { NodeList.importMethod(host, n); }); } }; NodeList._getTempNode = function(node) { var tmp = NodeList._tempNode; if (!tmp) { tmp = Y.Node.create('<div></div>'); NodeList._tempNode = tmp; } tmp._node = node; tmp._stateProxy = node; return tmp; }; Y.mix(NodeList.prototype, { _invoke: function(method, args, getter) { var ret = (getter) ? [] : this; this.each(function(node) { var val = node[method].apply(node, args); if (getter) { ret.push(val); } }); return ret; }, /** * Retrieves the Node instance at the given index. * @method item * * @param {Number} index The index of the target Node. * @return {Node} The Node instance at the given index. */ item: function(index) { return Y.one((this._nodes || [])[index]); }, /** * Applies the given function to each Node in the NodeList. * @method each * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to apply the function with * Default context is the current Node instance * @chainable */ each: function(fn, context) { var instance = this; Y.Array.each(this._nodes, function(node, index) { node = Y.one(node); return fn.call(context || node, node, index, instance); }); return instance; }, batch: function(fn, context) { var nodelist = this; Y.Array.each(this._nodes, function(node, index) { var instance = Y.Node._instances[node[UID]]; if (!instance) { instance = NodeList._getTempNode(node); } return fn.call(context || instance, instance, index, nodelist); }); return nodelist; }, /** * Executes the function once for each node until a true value is returned. * @method some * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to execute the function from. * Default context is the current Node instance * @return {Boolean} Whether or not the function returned true for any node. */ some: function(fn, context) { var instance = this; return Y.Array.some(this._nodes, function(node, index) { node = Y.one(node); context = context || node; return fn.call(context, node, index, instance); }); }, /** * Creates a documenFragment from the nodes bound to the NodeList instance * @method toFrag * @return {Node} a Node instance bound to the documentFragment */ toFrag: function() { return Y.one(Y.DOM._nl2frag(this._nodes)); }, /** * Returns the index of the node in the NodeList instance * or -1 if the node isn't found. * @method indexOf * @param {Node | DOMNode} node the node to search for * @return {Int} the index of the node value or -1 if not found */ indexOf: function(node) { return Y.Array.indexOf(this._nodes, Y.Node.getDOMNode(node)); }, /** * Filters the NodeList instance down to only nodes matching the given selector. * @method filter * @param {String} selector The selector to filter against * @return {NodeList} NodeList containing the updated collection * @see Selector */ filter: function(selector) { return Y.all(Y.Selector.filter(this._nodes, selector)); }, /** * Creates a new NodeList containing all nodes at every n indices, where * remainder n % index equals r. * (zero-based index). * @method modulus * @param {Int} n The offset to use (return every nth node) * @param {Int} r An optional remainder to use with the modulus operation (defaults to zero) * @return {NodeList} NodeList containing the updated collection */ modulus: function(n, r) { r = r || 0; var nodes = []; NodeList.each(this, function(node, i) { if (i % n === r) { nodes.push(node); } }); return Y.all(nodes); }, /** * Creates a new NodeList containing all nodes at odd indices * (zero-based index). * @method odd * @return {NodeList} NodeList containing the updated collection */ odd: function() { return this.modulus(2, 1); }, /** * Creates a new NodeList containing all nodes at even indices * (zero-based index), including zero. * @method even * @return {NodeList} NodeList containing the updated collection */ even: function() { return this.modulus(2); }, destructor: function() { }, /** * Reruns the initial query, when created using a selector query * @method refresh * @chainable */ refresh: function() { var doc, nodes = this._nodes, query = this._query, root = this._queryRoot; if (query) { if (!root) { if (nodes && nodes[0] && nodes[0].ownerDocument) { root = nodes[0].ownerDocument; } } this._nodes = Y.Selector.query(query, root); } return this; }, /** * Returns the current number of items in the NodeList. * @method size * @return {Int} The number of items in the NodeList. */ size: function() { return this._nodes.length; }, /** * Determines if the instance is bound to any nodes * @method isEmpty * @return {Boolean} Whether or not the NodeList is bound to any nodes */ isEmpty: function() { return this._nodes.length < 1; }, toString: function() { var str = '', errorMsg = this[UID] + ': not bound to any nodes', nodes = this._nodes, node; if (nodes && nodes[0]) { node = nodes[0]; str += node[NODE_NAME]; if (node.id) { str += '#' + node.id; } if (node.className) { str += '.' + node.className.replace(' ', '.'); } if (nodes.length > 1) { str += '...[' + nodes.length + ' items]'; } } return str || errorMsg; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNodes * @return {Array} */ getDOMNodes: function() { return this._nodes; } }, true); NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance. Nulls internal node references, * removes any plugins and event listeners * @method destroy * @param {Boolean} recursivePurge (optional) Whether or not to * remove listeners from the node's subtree (default is false) * @see Node.destroy */ 'destroy', /** * Called on each Node instance. Removes and destroys all of the nodes * within the node * @method empty * @chainable * @see Node.empty */ 'empty', /** * Called on each Node instance. Removes the node from its parent. * Shortcut for myNode.get('parentNode').removeChild(myNode); * @method remove * @param {Boolean} destroy whether or not to call destroy() on the node * after removal. * @chainable * @see Node.remove */ 'remove', /** * Called on each Node instance. Sets an attribute on the Node instance. * Unless pre-configured (via Node.ATTRS), set hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be set. * To set custom attributes use setAttribute. * @method set * @param {String} attr The attribute to be set. * @param {any} val The value to set the attribute to. * @chainable * @see Node.set */ 'set' ]); // one-off implementation to convert array of Nodes to NodeList // e.g. Y.all('input').get('parentNode'); /** Called on each Node instance * @method get * @see Node */ NodeList.prototype.get = function(attr) { var ret = [], nodes = this._nodes, isNodeList = false, getTemp = NodeList._getTempNode, instance, val; if (nodes[0]) { instance = Y.Node._instances[nodes[0]._yuid] || getTemp(nodes[0]); val = instance._get(attr); if (val && val.nodeType) { isNodeList = true; } } Y.Array.each(nodes, function(node) { instance = Y.Node._instances[node._yuid]; if (!instance) { instance = getTemp(node); } val = instance._get(attr); if (!isNodeList) { // convert array of Nodes to NodeList val = Y.Node.scrubVal(val, instance); } ret.push(val); }); return (isNodeList) ? Y.all(ret) : ret; }; Y.NodeList = NodeList; Y.all = function(nodes) { return new NodeList(nodes); }; Y.Node.all = Y.all; /** * @module node * @submodule node-core */ var Y_NodeList = Y.NodeList, ArrayProto = Array.prototype, ArrayMethods = { /** Returns a new NodeList combining the given NodeList(s) * @for NodeList * @method concat * @param {NodeList | Array} valueN Arrays/NodeLists and/or values to * concatenate to the resulting NodeList * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'concat': 1, /** Removes the last from the NodeList and returns it. * @for NodeList * @method pop * @return {Node} The last item in the NodeList. */ 'pop': 0, /** Adds the given Node(s) to the end of the NodeList. * @for NodeList * @method push * @param {Node | DOMNode} nodes One or more nodes to add to the end of the NodeList. */ 'push': 0, /** Removes the first item from the NodeList and returns it. * @for NodeList * @method shift * @return {Node} The first item in the NodeList. */ 'shift': 0, /** Returns a new NodeList comprising the Nodes in the given range. * @for NodeList * @method slice * @param {Number} begin Zero-based index at which to begin extraction. As a negative index, start indicates an offset from the end of the sequence. slice(-2) extracts the second-to-last element and the last element in the sequence. * @param {Number} end Zero-based index at which to end extraction. slice extracts up to but not including end. slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. If end is omitted, slice extracts to the end of the sequence. * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'slice': 1, /** Changes the content of the NodeList, adding new elements while removing old elements. * @for NodeList * @method splice * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end. * @param {Number} howMany An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element. If no howMany parameter is specified (second syntax above, which is a SpiderMonkey extension), all elements after index are removed. * {Node | DOMNode| element1, ..., elementN The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array. * @return {NodeList} The element(s) removed. */ 'splice': 1, /** Adds the given Node(s) to the beginning of the NodeList. * @for NodeList * @method unshift * @param {Node | DOMNode} nodes One or more nodes to add to the NodeList. */ 'unshift': 0 }; Y.Object.each(ArrayMethods, function(returnNodeList, name) { Y_NodeList.prototype[name] = function() { var args = [], i = 0, arg, ret; while (typeof (arg = arguments[i++]) != 'undefined') { // use DOM nodes/nodeLists args.push(arg._node || arg._nodes || arg); } ret = ArrayProto[name].apply(this._nodes, args); if (returnNodeList) { ret = Y.all(ret); } else { ret = Y.Node.scrubVal(ret); } return ret; }; }); /** * @module node * @submodule node-core */ Y.Array.each([ /** * Passes through to DOM method. * @for Node * @method removeChild * @param {HTMLElement | Node} node Node to be removed * @return {Node} The removed node */ 'removeChild', /** * Passes through to DOM method. * @method hasChildNodes * @return {Boolean} Whether or not the node has any childNodes */ 'hasChildNodes', /** * Passes through to DOM method. * @method cloneNode * @param {Boolean} deep Whether or not to perform a deep clone, which includes * subtree and attributes * @return {Node} The clone */ 'cloneNode', /** * Passes through to DOM method. * @method hasAttribute * @param {String} attribute The attribute to test for * @return {Boolean} Whether or not the attribute is present */ 'hasAttribute', /** * Passes through to DOM method. * @method scrollIntoView * @chainable */ 'scrollIntoView', /** * Passes through to DOM method. * @method getElementsByTagName * @param {String} tagName The tagName to collect * @return {NodeList} A NodeList representing the HTMLCollection */ 'getElementsByTagName', /** * Passes through to DOM method. * @method focus * @chainable */ 'focus', /** * Passes through to DOM method. * @method blur * @chainable */ 'blur', /** * Passes through to DOM method. * Only valid on FORM elements * @method submit * @chainable */ 'submit', /** * Passes through to DOM method. * Only valid on FORM elements * @method reset * @chainable */ 'reset', /** * Passes through to DOM method. * @method select * @chainable */ 'select', /** * Passes through to DOM method. * Only valid on TABLE elements * @method createCaption * @chainable */ 'createCaption' ], function(method) { Y.Node.prototype[method] = function(arg1, arg2, arg3) { var ret = this.invoke(method, arg1, arg2, arg3); return ret; }; }); /** * Passes through to DOM method. * @method removeAttribute * @param {String} attribute The attribute to be removed * @chainable */ // one-off implementation due to IE returning boolean, breaking chaining Y.Node.prototype.removeAttribute = function(attr) { var node = this._node; if (node) { node.removeAttribute(attr, 0); // comma zero for IE < 8 to force case-insensitive } return this; }; Y.Node.importMethod(Y.DOM, [ /** * Determines whether the node is an ancestor of another HTML element in the DOM hierarchy. * @method contains * @param {Node | HTMLElement} needle The possible node or descendent * @return {Boolean} Whether or not this node is the needle its ancestor */ 'contains', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Wraps the given HTML around the node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable * @for Node */ 'wrap', /** * Removes the node's parent node. * @method unwrap * @chainable */ 'unwrap', /** * Applies a unique ID to the node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @see Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @see Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows for removing attributes on DOM nodes. * This passes through to the DOM node, allowing for custom attributes. * @method removeAttribute * @see Node * @for NodeList * @param {string} name The attribute to remove */ 'removeAttribute', /** * Removes the parent node from node in the list. * @method unwrap * @chainable */ 'unwrap', /** * Wraps the given HTML around each node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable */ 'wrap', /** * Applies a unique ID to each node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); }, '3.8.0pr2', {"requires": ["dom-core", "selector"]}); YUI.add('node-base', function (Y, NAME) { /** * @module node * @submodule node-base */ var methods = [ /** * Determines whether each node has the given className. * @method hasClass * @for Node * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the specified class */ 'hasClass', /** * Adds a class name to each node. * @method addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ 'addClass', /** * Removes a class name from each node. * @method removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ 'removeClass', /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ 'replaceClass', /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @param {String} className the class name to be toggled * @param {Boolean} force Option to force adding or removing the class. * @chainable */ 'toggleClass' ]; Y.Node.importMethod(Y.DOM, methods); /** * Determines whether each node has the given className. * @method hasClass * @see Node.hasClass * @for NodeList * @param {String} className the class name to search for * @return {Array} An array of booleans for each node bound to the NodeList. */ /** * Adds a class name to each node. * @method addClass * @see Node.addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ /** * Removes a class name from each node. * @method removeClass * @see Node.removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @see Node.replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @see Node.toggleClass * @param {String} className the class name to be toggled * @chainable */ Y.NodeList.importMethod(Y.Node.prototype, methods); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Returns a new dom node using the provided markup string. * @method create * @static * @param {String} html The markup used to create the element * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment * @for Node */ Y_Node.create = function(html, doc) { if (doc && doc._node) { doc = doc._node; } return Y.one(Y_DOM.create(html, doc)); }; Y.mix(Y_Node.prototype, { /** * Creates a new Node using the provided markup string. * @method create * @param {String} html The markup used to create the element. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment */ create: Y_Node.create, /** * Inserts the content before the reference node. * @method insert * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {Int | Node | HTMLElement | String} where The position to insert at. * Possible "where" arguments * <dl> * <dt>Y.Node</dt> * <dd>The Node to insert before</dd> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>Int</dt> * <dd>The index of the child element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> * @chainable */ insert: function(content, where) { this._insert(content, where); return this; }, _insert: function(content, where) { var node = this._node, ret = null; if (typeof where == 'number') { // allow index where = this._node.childNodes[where]; } else if (where && where._node) { // Node where = where._node; } if (content && typeof content != 'string') { // allow Node or NodeList/Array instances content = content._node || content._nodes || content; } ret = Y_DOM.addHTML(node, content, where); return ret; }, /** * Inserts the content as the firstChild of the node. * @method prepend * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ prepend: function(content) { return this.insert(content, 0); }, /** * Inserts the content as the lastChild of the node. * @method append * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ append: function(content) { return this.insert(content, null); }, /** * @method appendChild * @param {String | HTMLElement | Node} node Node to be appended * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The appended node */ appendChild: function(node) { return Y_Node.scrubVal(this._insert(node)); }, /** * @method insertBefore * @param {String | HTMLElement | Node} newNode Node to be appended * @param {HTMLElement | Node} refNode Node to be inserted before * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The inserted node */ insertBefore: function(newNode, refNode) { return Y.Node.scrubVal(this._insert(newNode, refNode)); }, /** * Appends the node to the given node. * @method appendTo * @param {Node | HTMLElement} node The node to append to * @chainable */ appendTo: function(node) { Y.one(node).append(this); return this; }, /** * Replaces the node's current content with the content. * Note that this passes to innerHTML and is not escaped. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content or `set('text')` to add as text. * @method setContent * @deprecated Use setHTML * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ setContent: function(content) { this._insert(content, 'replace'); return this; }, /** * Returns the node's current content (e.g. innerHTML) * @method getContent * @deprecated Use getHTML * @return {String} The current content */ getContent: function(content) { return this.get('innerHTML'); } }); /** * Replaces the node's current html content with the content provided. * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @method setHTML * @param {String | HTML | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ Y.Node.prototype.setHTML = Y.Node.prototype.setContent; /** * Returns the node's current html content (e.g. innerHTML) * @method getHTML * @return {String} The html content */ Y.Node.prototype.getHTML = Y.Node.prototype.getContent; Y.NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @for NodeList * @method append * @see Node.append */ 'append', /** * Called on each Node instance * @for NodeList * @method insert * @see Node.insert */ 'insert', /** * Called on each Node instance * @for NodeList * @method appendChild * @see Node.appendChild */ 'appendChild', /** * Called on each Node instance * @for NodeList * @method insertBefore * @see Node.insertBefore */ 'insertBefore', /** * Called on each Node instance * @for NodeList * @method prepend * @see Node.prepend */ 'prepend', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setContent * @deprecated Use setHTML */ 'setContent', /** * Called on each Node instance * @for NodeList * @method getContent * @deprecated Use getHTML */ 'getContent', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setHTML * @see Node.setHTML */ 'setHTML', /** * Called on each Node instance * @for NodeList * @method getHTML * @see Node.getHTML */ 'getHTML' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Static collection of configuration attributes for special handling * @property ATTRS * @static * @type object */ Y_Node.ATTRS = { /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config text * @type String */ text: { getter: function() { return Y_DOM.getText(this._node); }, setter: function(content) { Y_DOM.setText(this._node, content); return content; } }, /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config for * @type String */ 'for': { getter: function() { return Y_DOM.getAttribute(this._node, 'for'); }, setter: function(val) { Y_DOM.setAttribute(this._node, 'for', val); return val; } }, 'options': { getter: function() { return this._node.getElementsByTagName('option'); } }, /** * Returns a NodeList instance of all HTMLElement children. * @readOnly * @config children * @type NodeList */ 'children': { getter: function() { var node = this._node, children = node.children, childNodes, i, len; if (!children) { childNodes = node.childNodes; children = []; for (i = 0, len = childNodes.length; i < len; ++i) { if (childNodes[i].tagName) { children[children.length] = childNodes[i]; } } } return Y.all(children); } }, value: { getter: function() { return Y_DOM.getValue(this._node); }, setter: function(val) { Y_DOM.setValue(this._node, val); return val; } } }; Y.Node.importMethod(Y.DOM, [ /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; var Y_NodeList = Y.NodeList; /** * List of events that route to DOM events * @static * @property DOM_EVENTS * @for Node */ Y_Node.DOM_EVENTS = { abort: 1, beforeunload: 1, blur: 1, change: 1, click: 1, close: 1, command: 1, contextmenu: 1, dblclick: 1, DOMMouseScroll: 1, drag: 1, dragstart: 1, dragenter: 1, dragover: 1, dragleave: 1, dragend: 1, drop: 1, error: 1, focus: 1, key: 1, keydown: 1, keypress: 1, keyup: 1, load: 1, message: 1, mousedown: 1, mouseenter: 1, mouseleave: 1, mousemove: 1, mousemultiwheel: 1, mouseout: 1, mouseover: 1, mouseup: 1, mousewheel: 1, orientationchange: 1, reset: 1, resize: 1, select: 1, selectstart: 1, submit: 1, scroll: 1, textInput: 1, unload: 1 }; // Add custom event adaptors to this list. This will make it so // that delegate, key, available, contentready, etc all will // be available through Node.on Y.mix(Y_Node.DOM_EVENTS, Y.Env.evt.plugins); Y.augment(Y_Node, Y.EventTarget); Y.mix(Y_Node.prototype, { /** * Removes event listeners from the node and (optionally) its subtree * @method purge * @param {Boolean} recurse (optional) Whether or not to remove listeners from the * node's subtree * @param {String} type (optional) Only remove listeners of the specified type * @chainable * */ purge: function(recurse, type) { Y.Event.purgeElement(this._node, recurse, type); return this; } }); Y.mix(Y.NodeList.prototype, { _prepEvtArgs: function(type, fn, context) { // map to Y.on/after signature (type, fn, nodes, context, arg1, arg2, etc) var args = Y.Array(arguments, 0, true); if (args.length < 2) { // type only (event hash) just add nodes args[2] = this._nodes; } else { args.splice(2, 0, this._nodes); } args[3] = context || this; // default to NodeList instance as context return args; }, /** Subscribe a callback function for each `Node` in the collection to execute in response to a DOM event. NOTE: Generally, the `on()` method should be avoided on `NodeLists`, in favor of using event delegation from a parent Node. See the Event user guide for details. Most DOM events are associated with a preventable default behavior, such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. By default, the `this` object will be the `NodeList` that the subscription came from, <em>not the `Node` that received the event</em>. Use `e.currentTarget` to refer to the `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.all(".sku").on("keydown", function (e) { if (e.keyCode === 13) { e.preventDefault(); // Use e.currentTarget to refer to the individual Node var item = Y.MyApp.searchInventory( e.currentTarget.get('value') ); // etc ... } }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for NodeList **/ on: function(type, fn, context) { return Y.on.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList. * @method once * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ once: function(type, fn, context) { return Y.once.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an event listener to each Node bound to the NodeList. * The handler is called only after all on() handlers are called * and the event is not prevented. * @method after * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ after: function(type, fn, context) { return Y.after.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList * that will be called only after all on() handlers are called and the * event is not prevented. * * @method onceAfter * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ onceAfter: function(type, fn, context) { return Y.onceAfter.apply(Y, this._prepEvtArgs.apply(this, arguments)); } }); Y_NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @method detach * @see Node.detach * @for NodeList */ 'detach', /** Called on each Node instance * @method detachAll * @see Node.detachAll * @for NodeList */ 'detachAll' ]); /** Subscribe a callback function to execute in response to a DOM event or custom event. Most DOM events are associated with a preventable default behavior such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. If the event name passed as the first parameter is not a whitelisted DOM event, it will be treated as a custom event subscriptions, allowing `node.fire('customEventName')` later in the code. Refer to the Event user guide for the full DOM event whitelist. By default, the `this` object in the callback will refer to the subscribed `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.one("#my-form").on("submit", function (e) { e.preventDefault(); // proceed with ajax form submission instead... }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for Node **/ Y.mix(Y.Node.ATTRS, { offsetHeight: { setter: function(h) { Y.DOM.setHeight(this._node, h); return h; }, getter: function() { return this._node.offsetHeight; } }, offsetWidth: { setter: function(w) { Y.DOM.setWidth(this._node, w); return w; }, getter: function() { return this._node.offsetWidth; } } }); Y.mix(Y.Node.prototype, { sizeTo: function(w, h) { var node; if (arguments.length < 2) { node = Y.one(w); w = node.get('offsetWidth'); h = node.get('offsetHeight'); } this.setAttrs({ offsetWidth: w, offsetHeight: h }); } }); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; Y.mix(Y_Node.prototype, { /** * Makes the node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @for Node * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ show: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(true, callback); return this; }, /** * The implementation for showing nodes. * Default is to toggle the style.display property. * @method _show * @protected * @chainable */ _show: function() { this.setStyle('display', ''); }, _isHidden: function() { return Y.DOM.getStyle(this._node, 'display') === 'none'; }, /** * Displays or hides the node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method toggleView * @for Node * @param {Boolean} [on] An optional boolean value to force the node to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ toggleView: function(on, callback) { this._toggleView.apply(this, arguments); return this; }, _toggleView: function(on, callback) { callback = arguments[arguments.length - 1]; // base on current state if not forcing if (typeof on != 'boolean') { on = (this._isHidden()) ? 1 : 0; } if (on) { this._show(); } else { this._hide(); } if (typeof callback == 'function') { callback.call(this); } return this; }, /** * Hides the node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ hide: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(false, callback); return this; }, /** * The implementation for hiding nodes. * Default is to toggle the style.display property. * @method _hide * @protected * @chainable */ _hide: function() { this.setStyle('display', 'none'); } }); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Makes each node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @for NodeList * @chainable */ 'show', /** * Hides each node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ 'hide', /** * Displays or hides each node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the nodes using either the default * transition effect ('fadeIn'), or the given named effect. * @method toggleView * @param {Boolean} [on] An optional boolean value to force the nodes to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ 'toggleView' ]); if (!Y.config.doc.documentElement.hasAttribute) { // IE < 8 Y.Node.prototype.hasAttribute = function(attr) { if (attr === 'value') { if (this.get('value') !== "") { // IE < 8 fails to populate specified when set in HTML return true; } } return !!(this._node.attributes[attr] && this._node.attributes[attr].specified); }; } // IE throws an error when calling focus() on an element that's invisible, not // displayed, or disabled. Y.Node.prototype.focus = function () { try { this._node.focus(); } catch (e) { } return this; }; // IE throws error when setting input.type = 'hidden', // input.setAttribute('type', 'hidden') and input.attributes.type.value = 'hidden' Y.Node.ATTRS.type = { setter: function(val) { if (val === 'hidden') { try { this._node.type = 'hidden'; } catch(e) { this.setStyle('display', 'none'); this._inputType = 'hidden'; } } else { try { // IE errors when changing the type from "hidden' this._node.type = val; } catch (e) { } } return val; }, getter: function() { return this._inputType || this._node.type; }, _bypassProxy: true // don't update DOM when using with Attribute }; if (Y.config.doc.createElement('form').elements.nodeType) { // IE: elements collection is also FORM node which trips up scrubVal. Y.Node.ATTRS.elements = { getter: function() { return this.all('input, textarea, button, select'); } }; } /** * Provides methods for managing custom Node data. * * @module node * @main node * @submodule node-data */ Y.mix(Y.Node.prototype, { _initData: function() { if (! ('_data' in this)) { this._data = {}; } }, /** * @method getData * @for Node * @description Retrieves arbitrary data stored on a Node instance. * If no data is associated with the Node, it will attempt to retrieve * a value from the corresponding HTML data attribute. (e.g. node.getData('foo') * will check node.getAttribute('data-foo')). * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {any | Object} Whatever is stored at the given field, * or an object hash of all fields. */ getData: function(name) { this._initData(); var data = this._data, ret = data; if (arguments.length) { // single field if (name in data) { ret = data[name]; } else { // initialize from HTML attribute ret = this._getDataAttribute(name); } } else if (typeof data == 'object' && data !== null) { // all fields ret = {}; Y.Object.each(data, function(v, n) { ret[n] = v; }); ret = this._getDataAttributes(ret); } return ret; }, _getDataAttributes: function(ret) { ret = ret || {}; var i = 0, attrs = this._node.attributes, len = attrs.length, prefix = this.DATA_PREFIX, prefixLength = prefix.length, name; while (i < len) { name = attrs[i].name; if (name.indexOf(prefix) === 0) { name = name.substr(prefixLength); if (!(name in ret)) { // only merge if not already stored ret[name] = this._getDataAttribute(name); } } i += 1; } return ret; }, _getDataAttribute: function(name) { var name = this.DATA_PREFIX + name, node = this._node, attrs = node.attributes, data = attrs && attrs[name] && attrs[name].value; return data; }, /** * @method setData * @for Node * @description Stores arbitrary data on a Node instance. * This is not stored with the DOM node. * @param {string} name The name of the field to set. If no val * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { this._initData(); if (arguments.length > 1) { this._data[name] = val; } else { this._data = name; } return this; }, /** * @method clearData * @for Node * @description Clears internally stored data. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { if ('_data' in this) { if (typeof name != 'undefined') { delete this._data[name]; } else { delete this._data; } } return this; } }); Y.mix(Y.NodeList.prototype, { /** * @method getData * @for NodeList * @description Retrieves arbitrary data stored on each Node instance * bound to the NodeList. * @see Node * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {Array} An array containing all of the data for each Node instance. * or an object hash of all fields. */ getData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('getData', args, true); }, /** * @method setData * @for NodeList * @description Stores arbitrary data on each Node instance bound to the * NodeList. This is not stored with the DOM node. * @param {string} name The name of the field to set. If no name * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { var args = (arguments.length > 1) ? [name, val] : [name]; return this._invoke('setData', args); }, /** * @method clearData * @for NodeList * @description Clears data on all Node instances bound to the NodeList. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('clearData', [name]); } }); }, '3.8.0pr2', {"requires": ["event-base", "node-core", "dom-base"]}); (function () { var GLOBAL_ENV = YUI.Env; if (!GLOBAL_ENV._ready) { GLOBAL_ENV._ready = function() { GLOBAL_ENV.DOMReady = true; GLOBAL_ENV.remove(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); }; GLOBAL_ENV.add(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); } })(); YUI.add('event-base', function (Y, NAME) { /* * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * The domready event fires at the moment the browser's DOM is * usable. In most cases, this is before images are fully * downloaded, allowing you to provide a more responsive user * interface. * * In YUI 3, domready subscribers will be notified immediately if * that moment has already passed when the subscription is created. * * One exception is if the yui.js file is dynamically injected into * the page. If this is done, you must tell the YUI instance that * you did this in order for DOMReady (and window load events) to * fire normally. That configuration option is 'injected' -- set * it to true if the yui.js script is not included inline. * * This method is part of the 'event-ready' module, which is a * submodule of 'event'. * * @event domready * @for YUI */ Y.publish('domready', { fireOnce: true, async: true }); if (YUI.Env.DOMReady) { Y.fire('domready'); } else { Y.Do.before(function() { Y.fire('domready'); }, YUI.Env, '_ready'); } /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event * @submodule event-base */ /** * Wraps a DOM event, properties requiring browser abstraction are * fixed here. Provids a security layer when required. * @class DOMEventFacade * @param ev {Event} the DOM event * @param currentTarget {HTMLElement} the element the listener was attached to * @param wrapper {Event.Custom} the custom event wrapper for this DOM event */ var ua = Y.UA, EMPTY = {}, /** * webkit key remapping required for Safari < 3.1 * @property webkitKeymap * @private */ webkitKeymap = { 63232: 38, // up 63233: 40, // down 63234: 37, // left 63235: 39, // right 63276: 33, // page up 63277: 34, // page down 25: 9, // SHIFT-TAB (Safari provides a different key code in // this case, even though the shiftKey modifier is set) 63272: 46, // delete 63273: 36, // home 63275: 35 // end }, /** * Returns a wrapped node. Intended to be used on event targets, * so it will return the node's parent if the target is a text * node. * * If accessing a property of the node throws an error, this is * probably the anonymous div wrapper Gecko adds inside text * nodes. This likely will only occur when attempting to access * the relatedTarget. In this case, we now return null because * the anonymous div is completely useless and we do not know * what the related target was because we can't even get to * the element's parent node. * * @method resolve * @private */ resolve = function(n) { if (!n) { return n; } try { if (n && 3 == n.nodeType) { n = n.parentNode; } } catch(e) { return null; } return Y.one(n); }, DOMEventFacade = function(ev, currentTarget, wrapper) { this._event = ev; this._currentTarget = currentTarget; this._wrapper = wrapper || EMPTY; // if not lazy init this.init(); }; Y.extend(DOMEventFacade, Object, { init: function() { var e = this._event, overrides = this._wrapper.overrides, x = e.pageX, y = e.pageY, c, currentTarget = this._currentTarget; this.altKey = e.altKey; this.ctrlKey = e.ctrlKey; this.metaKey = e.metaKey; this.shiftKey = e.shiftKey; this.type = (overrides && overrides.type) || e.type; this.clientX = e.clientX; this.clientY = e.clientY; this.pageX = x; this.pageY = y; // charCode is unknown in keyup, keydown. keyCode is unknown in keypress. // FF 3.6 - 8+? pass 0 for keyCode in keypress events. // Webkit, FF 3.6-8+?, and IE9+? pass 0 for charCode in keydown, keyup. // Webkit and IE9+? duplicate charCode in keyCode. // Opera never sets charCode, always keyCode (though with the charCode). // IE6-8 don't set charCode or which. // All browsers other than IE6-8 set which=keyCode in keydown, keyup, and // which=charCode in keypress. // // Moral of the story: (e.which || e.keyCode) will always return the // known code for that key event phase. e.keyCode is often different in // keypress from keydown and keyup. c = e.keyCode || e.charCode; if (ua.webkit && (c in webkitKeymap)) { c = webkitKeymap[c]; } this.keyCode = c; this.charCode = c; // Fill in e.which for IE - implementers should always use this over // e.keyCode or e.charCode. this.which = e.which || e.charCode || c; // this.button = e.button; this.button = this.which; this.target = resolve(e.target); this.currentTarget = resolve(currentTarget); this.relatedTarget = resolve(e.relatedTarget); if (e.type == "mousewheel" || e.type == "DOMMouseScroll") { this.wheelDelta = (e.detail) ? (e.detail * -1) : Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1); } if (this._touch) { this._touch(e, currentTarget, this._wrapper); } }, stopPropagation: function() { this._event.stopPropagation(); this._wrapper.stopped = 1; this.stopped = 1; }, stopImmediatePropagation: function() { var e = this._event; if (e.stopImmediatePropagation) { e.stopImmediatePropagation(); } else { this.stopPropagation(); } this._wrapper.stopped = 2; this.stopped = 2; }, preventDefault: function(returnValue) { var e = this._event; e.preventDefault(); e.returnValue = returnValue || false; this._wrapper.prevented = 1; this.prevented = 1; }, halt: function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); } }); DOMEventFacade.resolve = resolve; Y.DOM2EventFacade = DOMEventFacade; Y.DOMEventFacade = DOMEventFacade; /** * The native event * @property _event * @type {Native DOM Event} * @private */ /** The name of the event (e.g. "click") @property type @type {String} **/ /** `true` if the "alt" or "option" key is pressed. @property altKey @type {Boolean} **/ /** `true` if the shift key is pressed. @property shiftKey @type {Boolean} **/ /** `true` if the "Windows" key on a Windows keyboard, "command" key on an Apple keyboard, or "meta" key on other keyboards is pressed. @property metaKey @type {Boolean} **/ /** `true` if the "Ctrl" or "control" key is pressed. @property ctrlKey @type {Boolean} **/ /** * The X location of the event on the page (including scroll) * @property pageX * @type {Number} */ /** * The Y location of the event on the page (including scroll) * @property pageY * @type {Number} */ /** * The X location of the event in the viewport * @property clientX * @type {Number} */ /** * The Y location of the event in the viewport * @property clientY * @type {Number} */ /** * The keyCode for key events. Uses charCode if keyCode is not available * @property keyCode * @type {Number} */ /** * The charCode for key events. Same as keyCode * @property charCode * @type {Number} */ /** * The button that was pushed. 1 for left click, 2 for middle click, 3 for * right click. This is only reliably populated on `mouseup` events. * @property button * @type {Number} */ /** * The button that was pushed. Same as button. * @property which * @type {Number} */ /** * Node reference for the targeted element * @property target * @type {Node} */ /** * Node reference for the element that the listener was attached to. * @property currentTarget * @type {Node} */ /** * Node reference to the relatedTarget * @property relatedTarget * @type {Node} */ /** * Number representing the direction and velocity of the movement of the mousewheel. * Negative is down, the higher the number, the faster. Applies to the mousewheel event. * @property wheelDelta * @type {Number} */ /** * Stops the propagation to the next bubble target * @method stopPropagation */ /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ /** * Prevents the event's default behavior * @method preventDefault * @param returnValue {string} sets the returnValue of the event to this value * (rather than the default false value). This can be used to add a customized * confirmation query to the beforeunload event). */ /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ (function() { /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * @module event * @main event * @submodule event-base */ /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * * @class Event * @static */ Y.Env.evt.dom_wrappers = {}; Y.Env.evt.dom_map = {}; var YDOM = Y.DOM, _eventenv = Y.Env.evt, config = Y.config, win = config.win, add = YUI.Env.add, remove = YUI.Env.remove, onLoad = function() { YUI.Env.windowLoaded = true; Y.Event._load(); remove(win, "load", onLoad); }, onUnload = function() { Y.Event._unload(); }, EVENT_READY = 'domready', COMPAT_ARG = '~yui|2|compat~', shouldIterate = function(o) { try { // TODO: See if there's a more performant way to return true early on this, for the common case return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) && !o.tagName && !YDOM.isWindow(o)); } catch(ex) { return false; } }, // aliases to support DOM event subscription clean up when the last // subscriber is detached. deleteAndClean overrides the DOM event's wrapper // CustomEvent _delete method. _ceProtoDelete = Y.CustomEvent.prototype._delete, _deleteAndClean = function(s) { var ret = _ceProtoDelete.apply(this, arguments); if (!this.hasSubs()) { Y.Event._clean(this); } return ret; }, Event = function() { /** * True after the onload event has fired * @property _loadComplete * @type boolean * @static * @private */ var _loadComplete = false, /** * The number of times to poll after window.onload. This number is * increased if additional late-bound handlers are requested after * the page load. * @property _retryCount * @static * @private */ _retryCount = 0, /** * onAvailable listeners * @property _avail * @static * @private */ _avail = [], /** * Custom event wrappers for DOM events. Key is * 'event:' + Element uid stamp + event type * @property _wrappers * @type Y.Event.Custom * @static * @private */ _wrappers = _eventenv.dom_wrappers, _windowLoadKey = null, /** * Custom event wrapper map DOM events. Key is * Element uid stamp. Each item is a hash of custom event * wrappers as provided in the _wrappers collection. This * provides the infrastructure for getListeners. * @property _el_events * @static * @private */ _el_events = _eventenv.dom_map; return { /** * The number of times we should look for elements that are not * in the DOM at the time the event is requested after the document * has been loaded. The default is 1000@amp;40 ms, so it will poll * for 40 seconds or until all outstanding handlers are bound * (whichever comes first). * @property POLL_RETRYS * @type int * @static * @final */ POLL_RETRYS: 1000, /** * The poll interval in milliseconds * @property POLL_INTERVAL * @type int * @static * @final */ POLL_INTERVAL: 40, /** * addListener/removeListener can throw errors in unexpected scenarios. * These errors are suppressed, the method returns false, and this property * is set * @property lastError * @static * @type Error */ lastError: null, /** * poll handle * @property _interval * @static * @private */ _interval: null, /** * document readystate poll handle * @property _dri * @static * @private */ _dri: null, /** * True when the document is initially usable * @property DOMReady * @type boolean * @static */ DOMReady: false, /** * @method startInterval * @static * @private */ startInterval: function() { if (!Event._interval) { Event._interval = setInterval(Event._poll, Event.POLL_INTERVAL); } }, /** * Executes the supplied callback when the item with the supplied * id is found. This is meant to be used to execute behavior as * soon as possible as the page loads. If you use this after the * initial page load it will poll for a fixed time for the element. * The number of times it will poll and the frequency are * configurable. By default it will poll for 10 seconds. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onAvailable * * @param {string||string[]} id the id of the element, or an array * of ids to look for. * @param {function} fn what to execute when the element is found. * @param {object} p_obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} p_override If set to true, fn will execute * in the context of p_obj, if set to an object it * will execute in the context of that object * @param checkContent {boolean} check child node readiness (onContentReady) * @static * @deprecated Use Y.on("available") */ // @TODO fix arguments onAvailable: function(id, fn, p_obj, p_override, checkContent, compat) { var a = Y.Array(id), i, availHandle; for (i=0; i<a.length; i=i+1) { _avail.push({ id: a[i], fn: fn, obj: p_obj, override: p_override, checkReady: checkContent, compat: compat }); } _retryCount = this.POLL_RETRYS; // We want the first test to be immediate, but async setTimeout(Event._poll, 0); availHandle = new Y.EventHandle({ _delete: function() { // set by the event system for lazy DOM listeners if (availHandle.handle) { availHandle.handle.detach(); return; } var i, j; // otherwise try to remove the onAvailable listener(s) for (i = 0; i < a.length; i++) { for (j = 0; j < _avail.length; j++) { if (a[i] === _avail[j].id) { _avail.splice(j, 1); } } } } }); return availHandle; }, /** * Works the same way as onAvailable, but additionally checks the * state of sibling elements to determine if the content of the * available element is safe to modify. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onContentReady * * @param {string} id the id of the element to look for. * @param {function} fn what to execute when the element is ready. * @param {object} obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} override If set to true, fn will execute * in the context of p_obj. If an object, fn will * exectute in the context of that object * * @static * @deprecated Use Y.on("contentready") */ // @TODO fix arguments onContentReady: function(id, fn, obj, override, compat) { return Event.onAvailable(id, fn, obj, override, true, compat); }, /** * Adds an event listener * * @method attach * * @param {String} type The type of event to append * @param {Function} fn The method the event invokes * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to assign the * listener to. * @param {Object} context optional context object * @param {Boolean|object} args 0..n arguments to pass to the callback * @return {EventHandle} an object to that can be used to detach the listener * * @static */ attach: function(type, fn, el, context) { return Event._attach(Y.Array(arguments, 0, true)); }, _createWrapper: function (el, type, capture, compat, facade) { var cewrapper, ek = Y.stamp(el), key = 'event:' + ek + type; if (false === facade) { key += 'native'; } if (capture) { key += 'capture'; } cewrapper = _wrappers[key]; if (!cewrapper) { // create CE wrapper cewrapper = Y.publish(key, { silent: true, bubbles: false, contextFn: function() { if (compat) { return cewrapper.el; } else { cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el); return cewrapper.nodeRef; } } }); cewrapper.overrides = {}; // for later removeListener calls cewrapper.el = el; cewrapper.key = key; cewrapper.domkey = ek; cewrapper.type = type; cewrapper.fn = function(e) { cewrapper.fire(Event.getEvent(e, el, (compat || (false === facade)))); }; cewrapper.capture = capture; if (el == win && type == "load") { // window load happens once cewrapper.fireOnce = true; _windowLoadKey = key; } cewrapper._delete = _deleteAndClean; _wrappers[key] = cewrapper; _el_events[ek] = _el_events[ek] || {}; _el_events[ek][key] = cewrapper; add(el, type, cewrapper.fn, capture); } return cewrapper; }, _attach: function(args, conf) { var compat, handles, oEl, cewrapper, context, fireNow = false, ret, type = args[0], fn = args[1], el = args[2] || win, facade = conf && conf.facade, capture = conf && conf.capture, overrides = conf && conf.overrides; if (args[args.length-1] === COMPAT_ARG) { compat = true; } if (!fn || !fn.call) { // throw new TypeError(type + " attach call failed, callback undefined"); return false; } // The el argument can be an array of elements or element ids. if (shouldIterate(el)) { handles=[]; Y.each(el, function(v, k) { args[2] = v; handles.push(Event._attach(args.slice(), conf)); }); // return (handles.length === 1) ? handles[0] : handles; return new Y.EventHandle(handles); // If the el argument is a string, we assume it is // actually the id of the element. If the page is loaded // we convert el to the actual element, otherwise we // defer attaching the event until the element is // ready } else if (Y.Lang.isString(el)) { // oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el); if (compat) { oEl = YDOM.byId(el); } else { oEl = Y.Selector.query(el); switch (oEl.length) { case 0: oEl = null; break; case 1: oEl = oEl[0]; break; default: args[2] = oEl; return Event._attach(args, conf); } } if (oEl) { el = oEl; // Not found = defer adding the event until the element is available } else { ret = Event.onAvailable(el, function() { ret.handle = Event._attach(args, conf); }, Event, true, false, compat); return ret; } } // Element should be an html element or node if (!el) { return false; } if (Y.Node && Y.instanceOf(el, Y.Node)) { el = Y.Node.getDOMNode(el); } cewrapper = Event._createWrapper(el, type, capture, compat, facade); if (overrides) { Y.mix(cewrapper.overrides, overrides); } if (el == win && type == "load") { // if the load is complete, fire immediately. // all subscribers, including the current one // will be notified. if (YUI.Env.windowLoaded) { fireNow = true; } } if (compat) { args.pop(); } context = args[3]; // set context to the Node if not specified // ret = cewrapper.on.apply(cewrapper, trimmedArgs); ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null); if (fireNow) { cewrapper.fire(); } return ret; }, /** * Removes an event listener. Supports the signature the event was bound * with, but the preferred way to remove listeners is using the handle * that is returned when using Y.on * * @method detach * * @param {String} type the type of event to remove. * @param {Function} fn the method the event invokes. If fn is * undefined, then all event handlers for the type of event are * removed. * @param {String|HTMLElement|Array|NodeList|EventHandle} el An * event handle, an id, an element reference, or a collection * of ids and/or elements to remove the listener from. * @return {boolean} true if the unbind was successful, false otherwise. * @static */ detach: function(type, fn, el, obj) { var args=Y.Array(arguments, 0, true), compat, l, ok, i, id, ce; if (args[args.length-1] === COMPAT_ARG) { compat = true; // args.pop(); } if (type && type.detach) { return type.detach(); } // The el argument can be a string if (typeof el == "string") { // el = (compat) ? Y.DOM.byId(el) : Y.all(el); if (compat) { el = YDOM.byId(el); } else { el = Y.Selector.query(el); l = el.length; if (l < 1) { el = null; } else if (l == 1) { el = el[0]; } } // return Event.detach.apply(Event, args); } if (!el) { return false; } if (el.detach) { args.splice(2, 1); return el.detach.apply(el, args); // The el argument can be an array of elements or element ids. } else if (shouldIterate(el)) { ok = true; for (i=0, l=el.length; i<l; ++i) { args[2] = el[i]; ok = ( Y.Event.detach.apply(Y.Event, args) && ok ); } return ok; } if (!type || !fn || !fn.call) { return Event.purgeElement(el, false, type); } id = 'event:' + Y.stamp(el) + type; ce = _wrappers[id]; if (ce) { return ce.detach(fn); } else { return false; } }, /** * Finds the event in the window object, the caller's arguments, or * in the arguments of another method in the callstack. This is * executed automatically for events registered through the event * manager, so the implementer should not normally need to execute * this function at all. * @method getEvent * @param {Event} e the event parameter from the handler * @param {HTMLElement} el the element the listener was attached to * @return {Event} the event * @static */ getEvent: function(e, el, noFacade) { var ev = e || win.event; return (noFacade) ? ev : new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]); }, /** * Generates an unique ID for the element if it does not already * have one. * @method generateId * @param el the element to create the id for * @return {string} the resulting id of the element * @static */ generateId: function(el) { return YDOM.generateID(el); }, /** * We want to be able to use getElementsByTagName as a collection * to attach a group of events to. Unfortunately, different * browsers return different types of collections. This function * tests to determine if the object is array-like. It will also * fail if the object is an array, but is empty. * @method _isValidCollection * @param o the object to test * @return {boolean} true if the object is array-like and populated * @deprecated was not meant to be used directly * @static * @private */ _isValidCollection: shouldIterate, /** * hook up any deferred listeners * @method _load * @static * @private */ _load: function(e) { if (!_loadComplete) { _loadComplete = true; // Just in case DOMReady did not go off for some reason // E._ready(); if (Y.fire) { Y.fire(EVENT_READY); } // Available elements may not have been detected before the // window load event fires. Try to find them now so that the // the user is more likely to get the onAvailable notifications // before the window load notification Event._poll(); } }, /** * Polling function that runs before the onload event fires, * attempting to attach to DOM Nodes as soon as they are * available * @method _poll * @static * @private */ _poll: function() { if (Event.locked) { return; } if (Y.UA.ie && !YUI.Env.DOMReady) { // Hold off if DOMReady has not fired and check current // readyState to protect against the IE operation aborted // issue. Event.startInterval(); return; } Event.locked = true; // keep trying until after the page is loaded. We need to // check the page load state prior to trying to bind the // elements so that we can be certain all elements have been // tested appropriately var i, len, item, el, notAvail, executeItem, tryAgain = !_loadComplete; if (!tryAgain) { tryAgain = (_retryCount > 0); } // onAvailable notAvail = []; executeItem = function (el, item) { var context, ov = item.override; try { if (item.compat) { if (item.override) { if (ov === true) { context = item.obj; } else { context = ov; } } else { context = el; } item.fn.call(context, item.obj); } else { context = item.obj || Y.one(el); item.fn.apply(context, (Y.Lang.isArray(ov)) ? ov : []); } } catch (e) { } }; // onAvailable for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && !item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? YDOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { executeItem(el, item); _avail[i] = null; } else { notAvail.push(item); } } } // onContentReady for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? YDOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { // The element is available, but not necessarily ready // @todo should we test parentNode.nextSibling? if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) { executeItem(el, item); _avail[i] = null; } } else { notAvail.push(item); } } } _retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1; if (tryAgain) { // we may need to strip the nulled out items here Event.startInterval(); } else { clearInterval(Event._interval); Event._interval = null; } Event.locked = false; return; }, /** * Removes all listeners attached to the given element via addListener. * Optionally, the node's children can also be purged. * Optionally, you can specify a specific type of event to remove. * @method purgeElement * @param {HTMLElement} el the element to purge * @param {boolean} recurse recursively purge this element's children * as well. Use with caution. * @param {string} type optional type of listener to purge. If * left out, all listeners will be removed * @static */ purgeElement: function(el, recurse, type) { // var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el, var oEl = (Y.Lang.isString(el)) ? Y.Selector.query(el, null, true) : el, lis = Event.getListeners(oEl, type), i, len, children, child; if (recurse && oEl) { lis = lis || []; children = Y.Selector.query('*', oEl); len = children.length; for (i = 0; i < len; ++i) { child = Event.getListeners(children[i], type); if (child) { lis = lis.concat(child); } } } if (lis) { for (i = 0, len = lis.length; i < len; ++i) { lis[i].detachAll(); } } }, /** * Removes all object references and the DOM proxy subscription for * a given event for a DOM node. * * @method _clean * @param wrapper {CustomEvent} Custom event proxy for the DOM * subscription * @private * @static * @since 3.4.0 */ _clean: function (wrapper) { var key = wrapper.key, domkey = wrapper.domkey; remove(wrapper.el, wrapper.type, wrapper.fn, wrapper.capture); delete _wrappers[key]; delete Y._yuievt.events[key]; if (_el_events[domkey]) { delete _el_events[domkey][key]; if (!Y.Object.size(_el_events[domkey])) { delete _el_events[domkey]; } } }, /** * Returns all listeners attached to the given element via addListener. * Optionally, you can specify a specific type of event to return. * @method getListeners * @param el {HTMLElement|string} the element or element id to inspect * @param type {string} optional type of listener to return. If * left out, all listeners will be returned * @return {CustomEvent} the custom event wrapper for the DOM event(s) * @static */ getListeners: function(el, type) { var ek = Y.stamp(el, true), evts = _el_events[ek], results=[] , key = (type) ? 'event:' + ek + type : null, adapters = _eventenv.plugins; if (!evts) { return null; } if (key) { // look for synthetic events if (adapters[type] && adapters[type].eventDef) { key += '_synth'; } if (evts[key]) { results.push(evts[key]); } // get native events as well key += 'native'; if (evts[key]) { results.push(evts[key]); } } else { Y.each(evts, function(v, k) { results.push(v); }); } return (results.length) ? results : null; }, /** * Removes all listeners registered by pe.event. Called * automatically during the unload event. * @method _unload * @static * @private */ _unload: function(e) { Y.each(_wrappers, function(v, k) { if (v.type == 'unload') { v.fire(e); } v.detachAll(); }); remove(win, "unload", onUnload); }, /** * Adds a DOM event directly without the caching, cleanup, context adj, etc * * @method nativeAdd * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeAdd: add, /** * Basic remove listener * * @method nativeRemove * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeRemove: remove }; }(); Y.Event = Event; if (config.injected || YUI.Env.windowLoaded) { onLoad(); } else { add(win, "load", onLoad); } // Process onAvailable/onContentReady items when when the DOM is ready in IE if (Y.UA.ie) { Y.on(EVENT_READY, Event._poll); } try { add(win, "unload", onUnload); } catch(e) { } Event.Custom = Y.CustomEvent; Event.Subscriber = Y.Subscriber; Event.Target = Y.EventTarget; Event.Handle = Y.EventHandle; Event.Facade = Y.EventFacade; Event._poll(); }()); /** * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * Executes the callback as soon as the specified element * is detected in the DOM. This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event available * @param type {string} 'available' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.available = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onAvailable.call(Y.Event, id, fn, o, a); } }; /** * Executes the callback as soon as the specified element * is detected in the DOM with a nextSibling property * (indicating that the element's children are available). * This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event contentready * @param type {string} 'contentready' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.contentready = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onContentReady.call(Y.Event, id, fn, o, a); } }; }, '3.8.0pr2', {"requires": ["event-custom-base"]}); YUI.add('pluginhost-base', function (Y, NAME) { /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost */ /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost-base */ /** * <p> * An augmentable class, which provides the augmented class with the ability to host plugins. * It adds <a href="#method_plug">plug</a> and <a href="#method_unplug">unplug</a> methods to the augmented class, which can * be used to add or remove plugins from instances of the class. * </p> * * <p>Plugins can also be added through the constructor configuration object passed to the host class' constructor using * the "plugins" property. Supported values for the "plugins" property are those defined by the <a href="#method_plug">plug</a> method. * * For example the following code would add the AnimPlugin and IOPlugin to Overlay (the plugin host): * <xmp> * var o = new Overlay({plugins: [ AnimPlugin, {fn:IOPlugin, cfg:{section:"header"}}]}); * </xmp> * </p> * <p> * Plug.Host's protected <a href="#method_initPlugins">_initPlugins</a> and <a href="#method_destroyPlugins">_destroyPlugins</a> * methods should be invoked by the host class at the appropriate point in the host's lifecyle. * </p> * * @class Plugin.Host */ var L = Y.Lang; function PluginHost() { this._plugins = {}; } PluginHost.prototype = { /** * Adds a plugin to the host object. This will instantiate the * plugin and attach it to the configured namespace on the host object. * * @method plug * @chainable * @param P {Function | Object |Array} Accepts the plugin class, or an * object with a "fn" property specifying the plugin class and * a "cfg" property specifying the configuration for the Plugin. * <p> * Additionally an Array can also be passed in, with the above function or * object values, allowing the user to add multiple plugins in a single call. * </p> * @param config (Optional) If the first argument is the plugin class, the second argument * can be the configuration for the plugin. * @return {Base} A reference to the host object */ plug: function(Plugin, config) { var i, ln, ns; if (L.isArray(Plugin)) { for (i = 0, ln = Plugin.length; i < ln; i++) { this.plug(Plugin[i]); } } else { if (Plugin && !L.isFunction(Plugin)) { config = Plugin.cfg; Plugin = Plugin.fn; } // Plugin should be fn by now if (Plugin && Plugin.NS) { ns = Plugin.NS; config = config || {}; config.host = this; if (this.hasPlugin(ns)) { // Update config if (this[ns].setAttrs) { this[ns].setAttrs(config); } } else { // Create new instance this[ns] = new Plugin(config); this._plugins[ns] = Plugin; } } } return this; }, /** * Removes a plugin from the host object. This will destroy the * plugin instance and delete the namespace from the host object. * * @method unplug * @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided, * all registered plugins are unplugged. * @return {Base} A reference to the host object * @chainable */ unplug: function(plugin) { var ns = plugin, plugins = this._plugins; if (plugin) { if (L.isFunction(plugin)) { ns = plugin.NS; if (ns && (!plugins[ns] || plugins[ns] !== plugin)) { ns = null; } } if (ns) { if (this[ns]) { if (this[ns].destroy) { this[ns].destroy(); } delete this[ns]; } if (plugins[ns]) { delete plugins[ns]; } } } else { for (ns in this._plugins) { if (this._plugins.hasOwnProperty(ns)) { this.unplug(ns); } } } return this; }, /** * Determines if a plugin has plugged into this host. * * @method hasPlugin * @param {String} ns The plugin's namespace * @return {Plugin} Returns a truthy value (the plugin instance) if present, or undefined if not. */ hasPlugin : function(ns) { return (this._plugins[ns] && this[ns]); }, /** * Initializes static plugins registered on the host (using the * Base.plug static method) and any plugins passed to the * instance through the "plugins" configuration property. * * @method _initPlugins * @param {Config} config The configuration object with property name/value pairs. * @private */ _initPlugins: function(config) { this._plugins = this._plugins || {}; if (this._initConfigPlugins) { this._initConfigPlugins(config); } }, /** * Unplugs and destroys all plugins on the host * @method _destroyPlugins * @private */ _destroyPlugins: function() { this.unplug(); } }; Y.namespace("Plugin").Host = PluginHost; }, '3.8.0pr2', {"requires": ["yui-base"]}); YUI.add('pluginhost-config', function (Y, NAME) { /** * Adds pluginhost constructor configuration and static configuration support * @submodule pluginhost-config */ var PluginHost = Y.Plugin.Host, L = Y.Lang; /** * A protected initialization method, used by the host class to initialize * plugin configurations passed the constructor, through the config object. * * Host objects should invoke this method at the appropriate time in their * construction lifecycle. * * @method _initConfigPlugins * @param {Object} config The configuration object passed to the constructor * @protected * @for Plugin.Host */ PluginHost.prototype._initConfigPlugins = function(config) { // Class Configuration var classes = (this._getClasses) ? this._getClasses() : [this.constructor], plug = [], unplug = {}, constructor, i, classPlug, classUnplug, pluginClassName; // TODO: Room for optimization. Can we apply statically/unplug in same pass? for (i = classes.length - 1; i >= 0; i--) { constructor = classes[i]; classUnplug = constructor._UNPLUG; if (classUnplug) { // subclasses over-write Y.mix(unplug, classUnplug, true); } classPlug = constructor._PLUG; if (classPlug) { // subclasses over-write Y.mix(plug, classPlug, true); } } for (pluginClassName in plug) { if (plug.hasOwnProperty(pluginClassName)) { if (!unplug[pluginClassName]) { this.plug(plug[pluginClassName]); } } } // User Configuration if (config && config.plugins) { this.plug(config.plugins); } }; /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of the class by default). * * @method plug * @static * * @param {Function} hostClass The host class on which to register the plugins * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin * @for Plugin.Host */ PluginHost.plug = function(hostClass, plugin, config) { // Cannot plug into Base, since Plugins derive from Base [ will cause infinite recurrsion ] var p, i, l, name; if (hostClass !== Y.Base) { hostClass._PLUG = hostClass._PLUG || {}; if (!L.isArray(plugin)) { if (config) { plugin = {fn:plugin, cfg:config}; } plugin = [plugin]; } for (i = 0, l = plugin.length; i < l;i++) { p = plugin[i]; name = p.NAME || p.fn.NAME; hostClass._PLUG[name] = p; } } }; /** * Unregisters any class level plugins which have been registered by the host class, or any * other class in the hierarchy. * * @method unplug * @static * * @param {Function} hostClass The host class from which to unregister the plugins * @param {Function | Array} plugin The plugin class, or an array of plugin classes * @for Plugin.Host */ PluginHost.unplug = function(hostClass, plugin) { var p, i, l, name; if (hostClass !== Y.Base) { hostClass._UNPLUG = hostClass._UNPLUG || {}; if (!L.isArray(plugin)) { plugin = [plugin]; } for (i = 0, l = plugin.length; i < l; i++) { p = plugin[i]; name = p.NAME; if (!hostClass._PLUG[name]) { hostClass._UNPLUG[name] = p; } else { delete hostClass._PLUG[name]; } } } }; }, '3.8.0pr2', {"requires": ["pluginhost-base"]}); YUI.add('event-delegate', function (Y, NAME) { /** * Adds event delegation support to the library. * * @module event * @submodule event-delegate */ var toArray = Y.Array, YLang = Y.Lang, isString = YLang.isString, isObject = YLang.isObject, isArray = YLang.isArray, selectorTest = Y.Selector.test, detachCategories = Y.Env.evt.handles; /** * <p>Sets up event delegation on a container element. The delegated event * will use a supplied selector or filtering function to test if the event * references at least one node that should trigger the subscription * callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {String|node} the element that is the delegation container * @param filter {string|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @static * @for Event */ function delegate(type, fn, el, filter) { var args = toArray(arguments, 0, true), query = isString(el) ? el : null, typeBits, synth, container, categories, cat, i, len, handles, handle; // Support Y.delegate({ click: fnA, key: fnB }, el, filter, ...); // and Y.delegate(['click', 'key'], fn, el, filter, ...); if (isObject(type)) { handles = []; if (isArray(type)) { for (i = 0, len = type.length; i < len; ++i) { args[0] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } else { // Y.delegate({'click', fn}, el, filter) => // Y.delegate('click', fn, el, filter) args.unshift(null); // one arg becomes two; need to make space for (i in type) { if (type.hasOwnProperty(i)) { args[0] = i; args[1] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } } return new Y.EventHandle(handles); } typeBits = type.split(/\|/); if (typeBits.length > 1) { cat = typeBits.shift(); args[0] = type = typeBits.shift(); } synth = Y.Node.DOM_EVENTS[type]; if (isObject(synth) && synth.delegate) { handle = synth.delegate.apply(synth, arguments); } if (!handle) { if (!type || !fn || !el || !filter) { return; } container = (query) ? Y.Selector.query(query, null, true) : el; if (!container && isString(el)) { handle = Y.on('available', function () { Y.mix(handle, Y.delegate.apply(Y, args), true); }, el); } if (!handle && container) { args.splice(2, 2, container); // remove the filter handle = Y.Event._attach(args, { facade: false }); handle.sub.filter = filter; handle.sub._notify = delegate.notifySub; } } if (handle && cat) { categories = detachCategories[cat] || (detachCategories[cat] = {}); categories = categories[type] || (categories[type] = []); categories.push(handle); } return handle; } /** Overrides the <code>_notify</code> method on the normal DOM subscription to inject the filtering logic and only proceed in the case of a match. This method is hosted as a private property of the `delegate` method (e.g. `Y.delegate.notifySub`) @method notifySub @param thisObj {Object} default 'this' object for the callback @param args {Array} arguments passed to the event's <code>fire()</code> @param ce {CustomEvent} the custom event managing the DOM subscriptions for the subscribed event on the subscribing node. @return {Boolean} false if the event was stopped @private @static @since 3.2.0 **/ delegate.notifySub = function (thisObj, args, ce) { // Preserve args for other subscribers args = args.slice(); if (this.args) { args.push.apply(args, this.args); } // Only notify subs if the event occurred on a targeted element var currentTarget = delegate._applyFilter(this.filter, args, ce), //container = e.currentTarget, e, i, len, ret; if (currentTarget) { // Support multiple matches up the the container subtree currentTarget = toArray(currentTarget); // The second arg is the currentTarget, but we'll be reusing this // facade, replacing the currentTarget for each use, so it doesn't // matter what element we seed it with. e = args[0] = new Y.DOMEventFacade(args[0], ce.el, ce); e.container = Y.one(ce.el); for (i = 0, len = currentTarget.length; i < len && !e.stopped; ++i) { e.currentTarget = Y.one(currentTarget[i]); ret = this.fn.apply(this.context || e.currentTarget, args); if (ret === false) { // stop further notifications break; } } return ret; } }; /** Compiles a selector string into a filter function to identify whether Nodes along the parent axis of an event's target should trigger event notification. This function is memoized, so previously compiled filter functions are returned if the same selector string is provided. This function may be useful when defining synthetic events for delegate handling. Hosted as a property of the `delegate` method (e.g. `Y.delegate.compileFilter`). @method compileFilter @param selector {String} the selector string to base the filtration on @return {Function} @since 3.2.0 @static **/ delegate.compileFilter = Y.cached(function (selector) { return function (target, e) { return selectorTest(target._node, selector, (e.currentTarget === e.target) ? null : e.currentTarget._node); }; }); /** Walks up the parent axis of an event's target, and tests each element against a supplied filter function. If any Nodes, including the container, satisfy the filter, the delegated callback will be triggered for each. Hosted as a protected property of the `delegate` method (e.g. `Y.delegate._applyFilter`). @method _applyFilter @param filter {Function} boolean function to test for inclusion in event notification @param args {Array} the arguments that would be passed to subscribers @param ce {CustomEvent} the DOM event wrapper @return {Node|Node[]|undefined} The Node or Nodes that satisfy the filter @protected **/ delegate._applyFilter = function (filter, args, ce) { var e = args[0], container = ce.el, // facadeless events in IE, have no e.currentTarget target = e.target || e.srcElement, match = [], isContainer = false; // Resolve text nodes to their containing element if (target.nodeType === 3) { target = target.parentNode; } // passing target as the first arg rather than leaving well enough alone // making 'this' in the filter function refer to the target. This is to // support bound filter functions. args.unshift(target); if (isString(filter)) { while (target) { isContainer = (target === container); if (selectorTest(target, filter, (isContainer ? null: container))) { match.push(target); } if (isContainer) { break; } target = target.parentNode; } } else { // filter functions are implementer code and should receive wrappers args[0] = Y.one(target); args[1] = new Y.DOMEventFacade(e, container, ce); while (target) { // filter(target, e, extra args...) - this === target if (filter.apply(args[0], args)) { match.push(target); } if (target === container) { break; } target = target.parentNode; args[0] = Y.one(target); } args[1] = e; // restore the raw DOM event } if (match.length <= 1) { match = match[0]; // single match or undefined } // remove the target args.shift(); return match; }; /** * Sets up event delegation on a container element. The delegated event * will use a supplied filter to test if the callback should be executed. * This filter can be either a selector string or a function that returns * a Node to use as the currentTarget for the event. * * The event object for the delegated event is supplied to the callback * function. It is modified slightly in order to support all properties * that may be needed for event delegation. 'currentTarget' is set to * the element that matched the selector string filter or the Node returned * from the filter function. 'container' is set to the element that the * listener is delegated from (this normally would be the 'currentTarget'). * * Filter functions will be called with the arguments that would be passed to * the callback function, including the event object as the first parameter. * The function should return false (or a falsey value) if the success criteria * aren't met, and the Node to use as the event's currentTarget and 'this' * object if they are. * * @method delegate * @param type {string} the event type to delegate * @param fn {function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {string|node} the element that is the delegation container * @param filter {string|function} a selector that must match the target of the * event or a function that returns a Node or false. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.delegate = Y.Event.delegate = delegate; }, '3.8.0pr2', {"requires": ["node-base"]}); YUI.add('node-event-delegate', function (Y, NAME) { /** * Functionality to make the node a delegated event container * @module node * @submodule node-event-delegate */ /** * <p>Sets up a delegation listener for an event occurring inside the Node. * The delegated event will be verified against a supplied selector or * filtering function to test if the event references at least one node that * should trigger the subscription callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param spec {String|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context {Object} optional argument that specifies what 'this' refers to. * @param args* {any} 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for Node */ Y.Node.prototype.delegate = function(type) { var args = Y.Array(arguments, 0, true), index = (Y.Lang.isObject(type) && !Y.Lang.isArray(type)) ? 1 : 2; args.splice(index, 0, this._node); return Y.delegate.apply(Y, args); }; }, '3.8.0pr2', {"requires": ["node-base", "event-delegate"]}); YUI.add('node-pluginhost', function (Y, NAME) { /** * @module node * @submodule node-pluginhost */ /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of Node by default). * * @method plug * @static * @for Node * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin */ Y.Node.plug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.plug.apply(Y.Base, args); return Y.Node; }; /** * Unregisters any class level plugins which have been registered by the Node * * @method unplug * @static * * @param {Function | Array} plugin The plugin class, or an array of plugin classes */ Y.Node.unplug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.unplug.apply(Y.Base, args); return Y.Node; }; Y.mix(Y.Node, Y.Plugin.Host, false, null, 1); // allow batching of plug/unplug via NodeList // doesn't use NodeList.importMethod because we need real Nodes (not tmpNode) /** * Adds a plugin to each node in the NodeList. * This will instantiate the plugin and attach it to the configured namespace on each node * @method plug * @for NodeList * @param P {Function | Object |Array} Accepts the plugin class, or an * object with a "fn" property specifying the plugin class and * a "cfg" property specifying the configuration for the Plugin. * <p> * Additionally an Array can also be passed in, with the above function or * object values, allowing the user to add multiple plugins in a single call. * </p> * @param config (Optional) If the first argument is the plugin class, the second argument * can be the configuration for the plugin. * @chainable */ Y.NodeList.prototype.plug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.plug.apply(Y.one(node), args); }); return this; }; /** * Removes a plugin from all nodes in the NodeList. This will destroy the * plugin instance and delete the namespace each node. * @method unplug * @for NodeList * @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided, * all registered plugins are unplugged. * @chainable */ Y.NodeList.prototype.unplug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.unplug.apply(Y.one(node), args); }); return this; }; }, '3.8.0pr2', {"requires": ["node-base", "pluginhost"]}); YUI.add('node-screen', function (Y, NAME) { /** * Extended Node interface for managing regions and screen positioning. * Adds support for positioning elements and normalizes window size and scroll detection. * @module node * @submodule node-screen */ // these are all "safe" returns, no wrapping required Y.each([ /** * Returns the inner width of the viewport (exludes scrollbar). * @config winWidth * @for Node * @type {Int} */ 'winWidth', /** * Returns the inner height of the viewport (exludes scrollbar). * @config winHeight * @type {Int} */ 'winHeight', /** * Document width * @config docWidth * @type {Int} */ 'docWidth', /** * Document height * @config docHeight * @type {Int} */ 'docHeight', /** * Pixel distance the page has been scrolled horizontally * @config docScrollX * @type {Int} */ 'docScrollX', /** * Pixel distance the page has been scrolled vertically * @config docScrollY * @type {Int} */ 'docScrollY' ], function(name) { Y.Node.ATTRS[name] = { getter: function() { var args = Array.prototype.slice.call(arguments); args.unshift(Y.Node.getDOMNode(this)); return Y.DOM[name].apply(this, args); } }; } ); Y.Node.ATTRS.scrollLeft = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollLeft' in node) ? node.scrollLeft : Y.DOM.docScrollX(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollLeft' in node) { node.scrollLeft = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(val, Y.DOM.docScrollY(node)); // scroll window if win or doc } } else { } } }; Y.Node.ATTRS.scrollTop = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollTop' in node) ? node.scrollTop : Y.DOM.docScrollY(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollTop' in node) { node.scrollTop = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(Y.DOM.docScrollX(node), val); // scroll window if win or doc } } else { } } }; Y.Node.importMethod(Y.DOM, [ /** * Gets the current position of the node in page coordinates. * @method getXY * @for Node * @return {Array} The XY position of the node */ 'getXY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setXY * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @chainable */ 'setXY', /** * Gets the current position of the node in page coordinates. * @method getX * @return {Int} The X position of the node */ 'getX', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setX * @param {Int} x X value for new position (coordinates are page-based) * @chainable */ 'setX', /** * Gets the current position of the node in page coordinates. * @method getY * @return {Int} The Y position of the node */ 'getY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setY * @param {Int} y Y value for new position (coordinates are page-based) * @chainable */ 'setY', /** * Swaps the XY position of this node with another node. * @method swapXY * @param {Node | HTMLElement} otherNode The node to swap with. * @chainable */ 'swapXY' ]); /** * @module node * @submodule node-screen */ /** * Returns a region object for the node * @config region * @for Node * @type Node */ Y.Node.ATTRS.region = { getter: function() { var node = this.getDOMNode(), region; if (node && !node.tagName) { if (node.nodeType === 9) { // document node = node.documentElement; } } if (Y.DOM.isWindow(node)) { region = Y.DOM.viewportRegion(node); } else { region = Y.DOM.region(node); } return region; } }; /** * Returns a region object for the node's viewport * @config viewportRegion * @type Node */ Y.Node.ATTRS.viewportRegion = { getter: function() { return Y.DOM.viewportRegion(Y.Node.getDOMNode(this)); } }; Y.Node.importMethod(Y.DOM, 'inViewportRegion'); // these need special treatment to extract 2nd node arg /** * Compares the intersection of the node with another node or region * @method intersect * @for Node * @param {Node|Object} node2 The node or region to compare with. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Object} An object representing the intersection of the regions. */ Y.Node.prototype.intersect = function(node2, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.intersect(node1, node2, altRegion); }; /** * Determines whether or not the node is within the giving region. * @method inRegion * @param {Node|Object} node2 The node or region to compare with. * @param {Boolean} all Whether or not all of the node must be in the region. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Object} An object representing the intersection of the regions. */ Y.Node.prototype.inRegion = function(node2, all, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.inRegion(node1, node2, all, altRegion); }; }, '3.8.0pr2', {"requires": ["dom-screen", "node-base"]}); YUI.add('node-style', function (Y, NAME) { (function(Y) { /** * Extended Node interface for managing node styles. * @module node * @submodule node-style */ Y.mix(Y.Node.prototype, { /** * Sets a style property of the node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ setStyle: function(attr, val) { Y.DOM.setStyle(this._node, attr, val); return this; }, /** * Sets multiple style properties on the node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ setStyles: function(hash) { Y.DOM.setStyles(this._node, hash); return this; }, /** * Returns the style's current value. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getStyle * @for Node * @param {String} attr The style attribute to retrieve. * @return {String} The current value of the style property for the element. */ getStyle: function(attr) { return Y.DOM.getStyle(this._node, attr); }, /** * Returns the computed value for the given style property. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {String} The computed value of the style property for the element. */ getComputedStyle: function(attr) { return Y.DOM.getComputedStyle(this._node, attr); } }); /** * Returns an array of values for each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getStyle * @for NodeList * @see Node.getStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The current values of the style property for the element. */ /** * Returns an array of the computed value for each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getComputedStyle * @see Node.getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The computed values for each node. */ /** * Sets a style property on each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyle * @see Node.setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ /** * Sets multiple style properties on each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyles * @see Node.setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ // These are broken out to handle undefined return (avoid false positive for // chainable) Y.NodeList.importMethod(Y.Node.prototype, ['getStyle', 'getComputedStyle', 'setStyle', 'setStyles']); })(Y); }, '3.8.0pr2', {"requires": ["dom-style", "node-base"]}); YUI.add('querystring-stringify-simple', function (Y, NAME) { /*global Y */ /** * <p>Provides Y.QueryString.stringify method for converting objects to Query Strings. * This is a subset implementation of the full querystring-stringify.</p> * <p>This module provides the bare minimum functionality (encoding a hash of simple values), * without the additional support for nested data structures. Every key-value pair is * encoded by encodeURIComponent.</p> * <p>This module provides a minimalistic way for io to handle single-level objects * as transaction data.</p> * * @module querystring * @submodule querystring-stringify-simple */ var QueryString = Y.namespace("QueryString"), EUC = encodeURIComponent; QueryString.stringify = function (obj, c) { var qs = [], // Default behavior is false; standard key notation. s = c && c.arrayKey ? true : false, key, i, l; for (key in obj) { if (obj.hasOwnProperty(key)) { if (Y.Lang.isArray(obj[key])) { for (i = 0, l = obj[key].length; i < l; i++) { qs.push(EUC(s ? key + '[]' : key) + '=' + EUC(obj[key][i])); } } else { qs.push(EUC(key) + '=' + EUC(obj[key])); } } } return qs.join('&'); }; }, '3.8.0pr2', {"requires": ["yui-base"]}); YUI.add('io-base', function (Y, NAME) { /** Base IO functionality. Provides basic XHR transport support. @module io @submodule io-base @for IO **/ var // List of events that comprise the IO event lifecycle. EVENTS = ['start', 'complete', 'end', 'success', 'failure', 'progress'], // Whitelist of used XHR response object properties. XHR_PROPS = ['status', 'statusText', 'responseText', 'responseXML'], win = Y.config.win, uid = 0; /** The IO class is a utility that brokers HTTP requests through a simplified interface. Specifically, it allows JavaScript to make HTTP requests to a resource without a page reload. The underlying transport for making same-domain requests is the XMLHttpRequest object. IO can also use Flash, if specified as a transport, for cross-domain requests. @class IO @constructor @param {Object} config Object of EventTarget's publish method configurations used to configure IO's events. **/ function IO (config) { var io = this; io._uid = 'io:' + uid++; io._init(config); Y.io._map[io._uid] = io; } IO.prototype = { //-------------------------------------- // Properties //-------------------------------------- /** * A counter that increments for each transaction. * * @property _id * @private * @type {Number} */ _id: 0, /** * Object of IO HTTP headers sent with each transaction. * * @property _headers * @private * @type {Object} */ _headers: { 'X-Requested-With' : 'XMLHttpRequest' }, /** * Object that stores timeout values for any transaction with a defined * "timeout" configuration property. * * @property _timeout * @private * @type {Object} */ _timeout: {}, //-------------------------------------- // Methods //-------------------------------------- _init: function(config) { var io = this, i, len; io.cfg = config || {}; Y.augment(io, Y.EventTarget); for (i = 0, len = EVENTS.length; i < len; ++i) { // Publish IO global events with configurations, if any. // IO global events are set to broadcast by default. // These events use the "io:" namespace. io.publish('io:' + EVENTS[i], Y.merge({ broadcast: 1 }, config)); // Publish IO transaction events with configurations, if // any. These events use the "io-trn:" namespace. io.publish('io-trn:' + EVENTS[i], config); } }, /** * Method that creates a unique transaction object for each request. * * @method _create * @private * @param {Object} cfg Configuration object subset to determine if * the transaction is an XDR or file upload, * requiring an alternate transport. * @param {Number} id Transaction id * @return {Object} The transaction object */ _create: function(config, id) { var io = this, transaction = { id : Y.Lang.isNumber(id) ? id : io._id++, uid: io._uid }, alt = config.xdr ? config.xdr.use : null, form = config.form && config.form.upload ? 'iframe' : null, use; if (alt === 'native') { // Non-IE and IE >= 10 can use XHR level 2 and not rely on an // external transport. alt = Y.UA.ie && !SUPPORTS_CORS ? 'xdr' : null; // Prevent "pre-flight" OPTIONS request by removing the // `X-Requested-With` HTTP header from CORS requests. This header // can be added back on a per-request basis, if desired. io.setHeader('X-Requested-With'); } use = alt || form; transaction = use ? Y.merge(Y.IO.customTransport(use), transaction) : Y.merge(Y.IO.defaultTransport(), transaction); if (transaction.notify) { config.notify = function (e, t, c) { io.notify(e, t, c); }; } if (!use) { if (win && win.FormData && config.data instanceof win.FormData) { transaction.c.upload.onprogress = function (e) { io.progress(transaction, e, config); }; transaction.c.onload = function (e) { io.load(transaction, e, config); }; transaction.c.onerror = function (e) { io.error(transaction, e, config); }; transaction.upload = true; } } return transaction; }, _destroy: function(transaction) { if (win && !transaction.notify && !transaction.xdr) { if (XHR && !transaction.upload) { transaction.c.onreadystatechange = null; } else if (transaction.upload) { transaction.c.upload.onprogress = null; transaction.c.onload = null; transaction.c.onerror = null; } else if (Y.UA.ie && !transaction.e) { // IE, when using XMLHttpRequest as an ActiveX Object, will throw // a "Type Mismatch" error if the event handler is set to "null". transaction.c.abort(); } } transaction = transaction.c = null; }, /** * Method for creating and firing events. * * @method _evt * @private * @param {String} eventName Event to be published. * @param {Object} transaction Transaction object. * @param {Object} config Configuration data subset for event subscription. */ _evt: function(eventName, transaction, config) { var io = this, params, args = config['arguments'], emitFacade = io.cfg.emitFacade, globalEvent = "io:" + eventName, trnEvent = "io-trn:" + eventName; // Workaround for #2532107 this.detach(trnEvent); if (transaction.e) { transaction.c = { status: 0, statusText: transaction.e }; } // Fire event with parameters or an Event Facade. params = [ emitFacade ? { id: transaction.id, data: transaction.c, cfg: config, 'arguments': args } : transaction.id ]; if (!emitFacade) { if (eventName === EVENTS[0] || eventName === EVENTS[2]) { if (args) { params.push(args); } } else { if (transaction.evt) { params.push(transaction.evt); } else { params.push(transaction.c); } if (args) { params.push(args); } } } params.unshift(globalEvent); // Fire global events. io.fire.apply(io, params); // Fire transaction events, if receivers are defined. if (config.on) { params[0] = trnEvent; io.once(trnEvent, config.on[eventName], config.context || Y); io.fire.apply(io, params); } }, /** * Fires event "io:start" and creates, fires a transaction-specific * start event, if `config.on.start` is defined. * * @method start * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ start: function(transaction, config) { /** * Signals the start of an IO request. * @event io:start */ this._evt(EVENTS[0], transaction, config); }, /** * Fires event "io:complete" and creates, fires a * transaction-specific "complete" event, if config.on.complete is * defined. * * @method complete * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ complete: function(transaction, config) { /** * Signals the completion of the request-response phase of a * transaction. Response status and data are accessible, if * available, in this event. * @event io:complete */ this._evt(EVENTS[1], transaction, config); }, /** * Fires event "io:end" and creates, fires a transaction-specific "end" * event, if config.on.end is defined. * * @method end * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ end: function(transaction, config) { /** * Signals the end of the transaction lifecycle. * @event io:end */ this._evt(EVENTS[2], transaction, config); this._destroy(transaction); }, /** * Fires event "io:success" and creates, fires a transaction-specific * "success" event, if config.on.success is defined. * * @method success * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ success: function(transaction, config) { /** * Signals an HTTP response with status in the 2xx range. * Fires after io:complete. * @event io:success */ this._evt(EVENTS[3], transaction, config); this.end(transaction, config); }, /** * Fires event "io:failure" and creates, fires a transaction-specific * "failure" event, if config.on.failure is defined. * * @method failure * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ failure: function(transaction, config) { /** * Signals an HTTP response with status outside of the 2xx range. * Fires after io:complete. * @event io:failure */ this._evt(EVENTS[4], transaction, config); this.end(transaction, config); }, /** * Fires event "io:progress" and creates, fires a transaction-specific * "progress" event -- for XMLHttpRequest file upload -- if * config.on.progress is defined. * * @method progress * @param {Object} transaction Transaction object. * @param {Object} progress event. * @param {Object} config Configuration object for the transaction. */ progress: function(transaction, e, config) { /** * Signals the interactive state during a file upload transaction. * This event fires after io:start and before io:complete. * @event io:progress */ transaction.evt = e; this._evt(EVENTS[5], transaction, config); }, /** * Fires event "io:complete" and creates, fires a transaction-specific * "complete" event -- for XMLHttpRequest file upload -- if * config.on.complete is defined. * * @method load * @param {Object} transaction Transaction object. * @param {Object} load event. * @param {Object} config Configuration object for the transaction. */ load: function (transaction, e, config) { transaction.evt = e.target; this._evt(EVENTS[1], transaction, config); }, /** * Fires event "io:failure" and creates, fires a transaction-specific * "failure" event -- for XMLHttpRequest file upload -- if * config.on.failure is defined. * * @method error * @param {Object} transaction Transaction object. * @param {Object} error event. * @param {Object} config Configuration object for the transaction. */ error: function (transaction, e, config) { transaction.evt = e; this._evt(EVENTS[4], transaction, config); }, /** * Retry an XDR transaction, using the Flash tranport, if the native * transport fails. * * @method _retry * @private * @param {Object} transaction Transaction object. * @param {String} uri Qualified path to transaction resource. * @param {Object} config Configuration object for the transaction. */ _retry: function(transaction, uri, config) { this._destroy(transaction); config.xdr.use = 'flash'; return this.send(uri, config, transaction.id); }, /** * Method that concatenates string data for HTTP GET transactions. * * @method _concat * @private * @param {String} uri URI or root data. * @param {String} data Data to be concatenated onto URI. * @return {String} */ _concat: function(uri, data) { uri += (uri.indexOf('?') === -1 ? '?' : '&') + data; return uri; }, /** * Stores default client headers for all transactions. If a label is * passed with no value argument, the header will be deleted. * * @method setHeader * @param {String} name HTTP header * @param {String} value HTTP header value */ setHeader: function(name, value) { if (value) { this._headers[name] = value; } else { delete this._headers[name]; } }, /** * Method that sets all HTTP headers to be sent in a transaction. * * @method _setHeaders * @private * @param {Object} transaction - XHR instance for the specific transaction. * @param {Object} headers - HTTP headers for the specific transaction, as * defined in the configuration object passed to YUI.io(). */ _setHeaders: function(transaction, headers) { headers = Y.merge(this._headers, headers); Y.Object.each(headers, function(value, name) { if (value !== 'disable') { transaction.setRequestHeader(name, headers[name]); } }); }, /** * Starts timeout count if the configuration object has a defined * timeout property. * * @method _startTimeout * @private * @param {Object} transaction Transaction object generated by _create(). * @param {Object} timeout Timeout in milliseconds. */ _startTimeout: function(transaction, timeout) { var io = this; io._timeout[transaction.id] = setTimeout(function() { io._abort(transaction, 'timeout'); }, timeout); }, /** * Clears the timeout interval started by _startTimeout(). * * @method _clearTimeout * @private * @param {Number} id - Transaction id. */ _clearTimeout: function(id) { clearTimeout(this._timeout[id]); delete this._timeout[id]; }, /** * Method that determines if a transaction response qualifies as success * or failure, based on the response HTTP status code, and fires the * appropriate success or failure events. * * @method _result * @private * @static * @param {Object} transaction Transaction object generated by _create(). * @param {Object} config Configuration object passed to io(). */ _result: function(transaction, config) { var status; // Firefox will throw an exception if attempting to access // an XHR object's status property, after a request is aborted. try { status = transaction.c.status; } catch(e) { status = 0; } // IE reports HTTP 204 as HTTP 1223. if (status >= 200 && status < 300 || status === 304 || status === 1223) { this.success(transaction, config); } else { this.failure(transaction, config); } }, /** * Event handler bound to onreadystatechange. * * @method _rS * @private * @param {Object} transaction Transaction object generated by _create(). * @param {Object} config Configuration object passed to YUI.io(). */ _rS: function(transaction, config) { var io = this; if (transaction.c.readyState === 4) { if (config.timeout) { io._clearTimeout(transaction.id); } // Yield in the event of request timeout or abort. setTimeout(function() { io.complete(transaction, config); io._result(transaction, config); }, 0); } }, /** * Terminates a transaction due to an explicit abort or timeout. * * @method _abort * @private * @param {Object} transaction Transaction object generated by _create(). * @param {String} type Identifies timed out or aborted transaction. */ _abort: function(transaction, type) { if (transaction && transaction.c) { transaction.e = type; transaction.c.abort(); } }, /** * Requests a transaction. `send()` is implemented as `Y.io()`. Each * transaction may include a configuration object. Its properties are: * * <dl> * <dt>method</dt> * <dd>HTTP method verb (e.g., GET or POST). If this property is not * not defined, the default value will be GET.</dd> * * <dt>data</dt> * <dd>This is the name-value string that will be sent as the * transaction data. If the request is HTTP GET, the data become * part of querystring. If HTTP POST, the data are sent in the * message body.</dd> * * <dt>xdr</dt> * <dd>Defines the transport to be used for cross-domain requests. * By setting this property, the transaction will use the specified * transport instead of XMLHttpRequest. The properties of the * transport object are: * <dl> * <dt>use</dt> * <dd>The transport to be used: 'flash' or 'native'</dd> * <dt>dataType</dt> * <dd>Set the value to 'XML' if that is the expected response * content type.</dd> * </dl></dd> * * <dt>form</dt> * <dd>Form serialization configuration object. Its properties are: * <dl> * <dt>id</dt> * <dd>Node object or id of HTML form</dd> * <dt>useDisabled</dt> * <dd>`true` to also serialize disabled form field values * (defaults to `false`)</dd> * </dl></dd> * * <dt>on</dt> * <dd>Assigns transaction event subscriptions. Available events are: * <dl> * <dt>start</dt> * <dd>Fires when a request is sent to a resource.</dd> * <dt>complete</dt> * <dd>Fires when the transaction is complete.</dd> * <dt>success</dt> * <dd>Fires when the HTTP response status is within the 2xx * range.</dd> * <dt>failure</dt> * <dd>Fires when the HTTP response status is outside the 2xx * range, if an exception occurs, if the transation is aborted, * or if the transaction exceeds a configured `timeout`.</dd> * <dt>end</dt> * <dd>Fires at the conclusion of the transaction * lifecycle, after `success` or `failure`.</dd> * </dl> * * <p>Callback functions for `start` and `end` receive the id of the * transaction as a first argument. For `complete`, `success`, and * `failure`, callbacks receive the id and the response object * (usually the XMLHttpRequest instance). If the `arguments` * property was included in the configuration object passed to * `Y.io()`, the configured data will be passed to all callbacks as * the last argument.</p> * </dd> * * <dt>sync</dt> * <dd>Pass `true` to make a same-domain transaction synchronous. * <strong>CAVEAT</strong>: This will negatively impact the user * experience. Have a <em>very</em> good reason if you intend to use * this.</dd> * * <dt>context</dt> * <dd>The "`this'" object for all configured event handlers. If a * specific context is needed for individual callbacks, bind the * callback to a context using `Y.bind()`.</dd> * * <dt>headers</dt> * <dd>Object map of transaction headers to send to the server. The * object keys are the header names and the values are the header * values.</dd> * * <dt>timeout</dt> * <dd>Millisecond threshold for the transaction before being * automatically aborted.</dd> * * <dt>arguments</dt> * <dd>User-defined data passed to all registered event handlers. * This value is available as the second argument in the "start" and * "end" event handlers. It is the third argument in the "complete", * "success", and "failure" event handlers. <strong>Be sure to quote * this property name in the transaction configuration as * "arguments" is a reserved word in JavaScript</strong> (e.g. * `Y.io({ ..., "arguments": stuff })`).</dd> * </dl> * * @method send * @public * @param {String} uri Qualified path to transaction resource. * @param {Object} config Configuration object for the transaction. * @param {Number} id Transaction id, if already set. * @return {Object} */ send: function(uri, config, id) { var transaction, method, i, len, sync, data, io = this, u = uri, response = {}; config = config ? Y.Object(config) : {}; transaction = io._create(config, id); method = config.method ? config.method.toUpperCase() : 'GET'; sync = config.sync; data = config.data; // Serialize an map object into a key-value string using // querystring-stringify-simple. if ((Y.Lang.isObject(data) && !data.nodeType) && !transaction.upload) { data = Y.QueryString.stringify(data); } if (config.form) { if (config.form.upload) { // This is a file upload transaction, calling // upload() in io-upload-iframe. return io.upload(transaction, uri, config); } else { // Serialize HTML form data into a key-value string. data = io._serialize(config.form, data); } } if (data) { switch (method) { case 'GET': case 'HEAD': case 'DELETE': u = io._concat(u, data); data = ''; break; case 'POST': case 'PUT': // If Content-Type is defined in the configuration object, or // or as a default header, it will be used instead of // 'application/x-www-form-urlencoded; charset=UTF-8' config.headers = Y.merge({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, config.headers); break; } } if (transaction.xdr) { // Route data to io-xdr module for flash and XDomainRequest. return io.xdr(u, transaction, config); } else if (transaction.notify) { // Route data to custom transport return transaction.c.send(transaction, uri, config); } if (!sync && !transaction.upload) { transaction.c.onreadystatechange = function() { io._rS(transaction, config); }; } try { // Determine if request is to be set as // synchronous or asynchronous. transaction.c.open(method, u, !sync, config.username || null, config.password || null); io._setHeaders(transaction.c, config.headers || {}); io.start(transaction, config); // Will work only in browsers that implement the // Cross-Origin Resource Sharing draft. if (config.xdr && config.xdr.credentials && SUPPORTS_CORS) { transaction.c.withCredentials = true; } // Using "null" with HTTP POST will result in a request // with no Content-Length header defined. transaction.c.send(data); if (sync) { // Create a response object for synchronous transactions, // mixing id and arguments properties with the xhr // properties whitelist. for (i = 0, len = XHR_PROPS.length; i < len; ++i) { response[XHR_PROPS[i]] = transaction.c[XHR_PROPS[i]]; } response.getAllResponseHeaders = function() { return transaction.c.getAllResponseHeaders(); }; response.getResponseHeader = function(name) { return transaction.c.getResponseHeader(name); }; io.complete(transaction, config); io._result(transaction, config); return response; } } catch(e) { if (transaction.xdr) { // This exception is usually thrown by browsers // that do not support XMLHttpRequest Level 2. // Retry the request with the XDR transport set // to 'flash'. If the Flash transport is not // initialized or available, the transaction // will resolve to a transport error. return io._retry(transaction, uri, config); } else { io.complete(transaction, config); io._result(transaction, config); } } // If config.timeout is defined, and the request is standard XHR, // initialize timeout polling. if (config.timeout) { io._startTimeout(transaction, config.timeout); } return { id: transaction.id, abort: function() { return transaction.c ? io._abort(transaction, 'abort') : false; }, isInProgress: function() { return transaction.c ? (transaction.c.readyState % 4) : false; }, io: io }; } }; /** Method for initiating an ajax call. The first argument is the url end point for the call. The second argument is an object to configure the transaction and attach event subscriptions. The configuration object supports the following properties: <dl> <dt>method</dt> <dd>HTTP method verb (e.g., GET or POST). If this property is not not defined, the default value will be GET.</dd> <dt>data</dt> <dd>This is the name-value string that will be sent as the transaction data. If the request is HTTP GET, the data become part of querystring. If HTTP POST, the data are sent in the message body.</dd> <dt>xdr</dt> <dd>Defines the transport to be used for cross-domain requests. By setting this property, the transaction will use the specified transport instead of XMLHttpRequest. The properties of the transport object are: <dl> <dt>use</dt> <dd>The transport to be used: 'flash' or 'native'</dd> <dt>dataType</dt> <dd>Set the value to 'XML' if that is the expected response content type.</dd> </dl></dd> <dt>form</dt> <dd>Form serialization configuration object. Its properties are: <dl> <dt>id</dt> <dd>Node object or id of HTML form</dd> <dt>useDisabled</dt> <dd>`true` to also serialize disabled form field values (defaults to `false`)</dd> </dl></dd> <dt>on</dt> <dd>Assigns transaction event subscriptions. Available events are: <dl> <dt>start</dt> <dd>Fires when a request is sent to a resource.</dd> <dt>complete</dt> <dd>Fires when the transaction is complete.</dd> <dt>success</dt> <dd>Fires when the HTTP response status is within the 2xx range.</dd> <dt>failure</dt> <dd>Fires when the HTTP response status is outside the 2xx range, if an exception occurs, if the transation is aborted, or if the transaction exceeds a configured `timeout`.</dd> <dt>end</dt> <dd>Fires at the conclusion of the transaction lifecycle, after `success` or `failure`.</dd> </dl> <p>Callback functions for `start` and `end` receive the id of the transaction as a first argument. For `complete`, `success`, and `failure`, callbacks receive the id and the response object (usually the XMLHttpRequest instance). If the `arguments` property was included in the configuration object passed to `Y.io()`, the configured data will be passed to all callbacks as the last argument.</p> </dd> <dt>sync</dt> <dd>Pass `true` to make a same-domain transaction synchronous. <strong>CAVEAT</strong>: This will negatively impact the user experience. Have a <em>very</em> good reason if you intend to use this.</dd> <dt>context</dt> <dd>The "`this'" object for all configured event handlers. If a specific context is needed for individual callbacks, bind the callback to a context using `Y.bind()`.</dd> <dt>headers</dt> <dd>Object map of transaction headers to send to the server. The object keys are the header names and the values are the header values.</dd> <dt>timeout</dt> <dd>Millisecond threshold for the transaction before being automatically aborted.</dd> <dt>arguments</dt> <dd>User-defined data passed to all registered event handlers. This value is available as the second argument in the "start" and "end" event handlers. It is the third argument in the "complete", "success", and "failure" event handlers. <strong>Be sure to quote this property name in the transaction configuration as "arguments" is a reserved word in JavaScript</strong> (e.g. `Y.io({ ..., "arguments": stuff })`).</dd> </dl> @method io @static @param {String} url qualified path to transaction resource. @param {Object} config configuration object for the transaction. @return {Object} @for YUI **/ Y.io = function(url, config) { // Calling IO through the static interface will use and reuse // an instance of IO. var transaction = Y.io._map['io:0'] || new IO(); return transaction.send.apply(transaction, [url, config]); }; /** Method for setting and deleting IO HTTP headers to be sent with every request. Hosted as a property on the `io` function (e.g. `Y.io.header`). @method header @param {String} name HTTP header @param {String} value HTTP header value @static **/ Y.io.header = function(name, value) { // Calling IO through the static interface will use and reuse // an instance of IO. var transaction = Y.io._map['io:0'] || new IO(); transaction.setHeader(name, value); }; Y.IO = IO; // Map of all IO instances created. Y.io._map = {}; var XHR = win && win.XMLHttpRequest, XDR = win && win.XDomainRequest, AX = win && win.ActiveXObject, // Checks for the presence of the `withCredentials` in an XHR instance // object, which will be present if the environment supports CORS. SUPPORTS_CORS = XHR && 'withCredentials' in (new XMLHttpRequest()); Y.mix(Y.IO, { /** * The ID of the default IO transport, defaults to `xhr` * @property _default * @type {String} * @static */ _default: 'xhr', /** * * @method defaultTransport * @static * @param {String} [id] The transport to set as the default, if empty a new transport is created. * @return {Object} The transport object with a `send` method */ defaultTransport: function(id) { if (id) { Y.IO._default = id; } else { var o = { c: Y.IO.transports[Y.IO._default](), notify: Y.IO._default === 'xhr' ? false : true }; return o; } }, /** * An object hash of custom transports available to IO * @property transports * @type {Object} * @static */ transports: { xhr: function () { return XHR ? new XMLHttpRequest() : AX ? new ActiveXObject('Microsoft.XMLHTTP') : null; }, xdr: function () { return XDR ? new XDomainRequest() : null; }, iframe: function () { return {}; }, flash: null, nodejs: null }, /** * Create a custom transport of type and return it's object * @method customTransport * @param {String} id The id of the transport to create. * @static */ customTransport: function(id) { var o = { c: Y.IO.transports[id]() }; o[(id === 'xdr' || id === 'flash') ? 'xdr' : 'notify'] = true; return o; } }); Y.mix(Y.IO.prototype, { /** * Fired from the notify method of the transport which in turn fires * the event on the IO object. * @method notify * @param {String} event The name of the event * @param {Object} transaction The transaction object * @param {Object} config The configuration object for this transaction */ notify: function(event, transaction, config) { var io = this; switch (event) { case 'timeout': case 'abort': case 'transport error': transaction.c = { status: 0, statusText: event }; event = 'failure'; default: io[event].apply(io, [transaction, config]); } } }); }, '3.8.0pr2', {"requires": ["event-custom-base", "querystring-stringify-simple"]}); YUI.add('json-parse', function (Y, NAME) { /** * <p>The JSON module adds support for serializing JavaScript objects into * JSON strings and parsing JavaScript objects from strings in JSON format.</p> * * <p>The JSON namespace is added to your YUI instance including static methods * Y.JSON.parse(..) and Y.JSON.stringify(..).</p> * * <p>The functionality and method signatures follow the ECMAScript 5 * specification. In browsers with native JSON support, the native * implementation is used.</p> * * <p>The <code>json</code> module is a rollup of <code>json-parse</code> and * <code>json-stringify</code>.</p> * * <p>As their names suggest, <code>json-parse</code> adds support for parsing * JSON data (Y.JSON.parse) and <code>json-stringify</code> for serializing * JavaScript data into JSON strings (Y.JSON.stringify). You may choose to * include either of the submodules individually if you don't need the * complementary functionality, or include the rollup for both.</p> * * @module json * @main json * @class JSON * @static */ /** * Provides Y.JSON.parse method to accept JSON strings and return native * JavaScript objects. * * @module json * @submodule json-parse * @for JSON * @static */ // All internals kept private for security reasons function fromGlobal(ref) { var g = ((typeof global === 'object') ? global : undefined); return ((Y.UA.nodejs && g) ? g : (Y.config.win || {}))[ref]; } /** * Alias to native browser implementation of the JSON object if available. * * @property Native * @type {Object} * @private */ var _JSON = fromGlobal('JSON'), Native = (Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON), useNative = !!Native, /** * Replace certain Unicode characters that JavaScript may handle incorrectly * during eval--either by deleting them or treating them as line * endings--with escape sequences. * IMPORTANT NOTE: This regex will be used to modify the input if a match is * found. * * @property _UNICODE_EXCEPTIONS * @type {RegExp} * @private */ _UNICODE_EXCEPTIONS = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, /** * First step in the safety evaluation. Regex used to replace all escape * sequences (i.e. "\\", etc) with '@' characters (a non-JSON character). * * @property _ESCAPES * @type {RegExp} * @private */ _ESCAPES = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, /** * Second step in the safety evaluation. Regex used to replace all simple * values with ']' characters. * * @property _VALUES * @type {RegExp} * @private */ _VALUES = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, /** * Third step in the safety evaluation. Regex used to remove all open * square brackets following a colon, comma, or at the beginning of the * string. * * @property _BRACKETS * @type {RegExp} * @private */ _BRACKETS = /(?:^|:|,)(?:\s*\[)+/g, /** * Final step in the safety evaluation. Regex used to test the string left * after all previous replacements for invalid characters. * * @property _UNSAFE * @type {RegExp} * @private */ _UNSAFE = /[^\],:{}\s]/, /** * Replaces specific unicode characters with their appropriate \unnnn * format. Some browsers ignore certain characters during eval. * * @method escapeException * @param c {String} Unicode character * @return {String} the \unnnn escapement of the character * @private */ _escapeException = function (c) { return '\\u'+('0000'+(+(c.charCodeAt(0))).toString(16)).slice(-4); }, /** * Traverses nested objects, applying a reviver function to each (key,value) * from the scope if the key:value's containing object. The value returned * from the function will replace the original value in the key:value pair. * If the value returned is undefined, the key will be omitted from the * returned object. * * @method _revive * @param data {MIXED} Any JavaScript data * @param reviver {Function} filter or mutation function * @return {MIXED} The results of the filtered data * @private */ _revive = function (data, reviver) { var walk = function (o,key) { var k,v,value = o[key]; if (value && typeof value === 'object') { for (k in value) { if (value.hasOwnProperty(k)) { v = walk(value, k); if (v === undefined) { delete value[k]; } else { value[k] = v; } } } } return reviver.call(o,key,value); }; return typeof reviver === 'function' ? walk({'':data},'') : data; }, /** * Parse a JSON string, returning the native JavaScript representation. * * @param s {string} JSON string data * @param reviver {function} (optional) function(k,v) passed each key value * pair of object literals, allowing pruning or altering values * @return {MIXED} the native JavaScript representation of the JSON string * @throws SyntaxError * @method parse * @static */ // JavaScript implementation in lieu of native browser support. Based on // the json2.js library from http://json.org _parse = function (s,reviver) { // Replace certain Unicode characters that are otherwise handled // incorrectly by some browser implementations. // NOTE: This modifies the input if such characters are found! s = s.replace(_UNICODE_EXCEPTIONS, _escapeException); // Test for any remaining invalid characters if (!_UNSAFE.test(s.replace(_ESCAPES,'@'). replace(_VALUES,']'). replace(_BRACKETS,''))) { // Eval the text into a JavaScript data structure, apply any // reviver function, and return return _revive( eval('(' + s + ')'), reviver ); } throw new SyntaxError('JSON.parse'); }; Y.namespace('JSON').parse = function (s,reviver) { if (typeof s !== 'string') { s += ''; } return Native && Y.JSON.useNativeParse ? Native.parse(s,reviver) : _parse(s,reviver); }; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( Native ) { try { useNative = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { useNative = false; } } /** * Leverage native JSON parse if the browser has a native implementation. * In general, this is a good idea. See the Known Issues section in the * JSON user guide for caveats. The default value is true for browsers with * native JSON support. * * @property useNativeParse * @type Boolean * @default true * @static */ Y.JSON.useNativeParse = useNative; }, '3.8.0pr2', {"requires": ["yui-base"]}); YUI.add('transition', function (Y, NAME) { /** * Provides the transition method for Node. * Transition has no API of its own, but adds the transition method to Node. * * @module transition * @requires node-style */ var CAMEL_VENDOR_PREFIX = '', VENDOR_PREFIX = '', DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', TRANSITION = 'transition', TRANSITION_CAMEL = 'transition', TRANSITION_PROPERTY_CAMEL = 'transitionProperty', TRANSFORM_CAMEL = 'transform', TRANSITION_PROPERTY, TRANSITION_DURATION, TRANSITION_TIMING_FUNCTION, TRANSITION_DELAY, TRANSITION_END, ON_TRANSITION_END, EMPTY_OBJ = {}, VENDORS = [ 'Webkit', 'Moz' ], VENDOR_TRANSITION_END = { Webkit: 'webkitTransitionEnd' }, /** * A class for constructing transition instances. * Adds the "transition" method to Node. * @class Transition * @constructor */ Transition = function() { this.init.apply(this, arguments); }; Transition._toCamel = function(property) { property = property.replace(/-([a-z])/gi, function(m0, m1) { return m1.toUpperCase(); }); return property; }; Transition._toHyphen = function(property) { property = property.replace(/([A-Z]?)([a-z]+)([A-Z]?)/g, function(m0, m1, m2, m3) { var str = ((m1) ? '-' + m1.toLowerCase() : '') + m2; if (m3) { str += '-' + m3.toLowerCase(); } return str; }); return property; }; Transition.SHOW_TRANSITION = 'fadeIn'; Transition.HIDE_TRANSITION = 'fadeOut'; Transition.useNative = false; if ('transition' in DOCUMENT[DOCUMENT_ELEMENT].style) { Transition.useNative = true; Transition.supported = true; // TODO: remove } else { Y.Array.each(VENDORS, function(val) { // then vendor specific var property = val + 'Transition'; if (property in DOCUMENT[DOCUMENT_ELEMENT].style) { CAMEL_VENDOR_PREFIX = val; VENDOR_PREFIX = Transition._toHyphen(val) + '-'; Transition.useNative = true; Transition.supported = true; // TODO: remove Transition._VENDOR_PREFIX = val; } }); } if (CAMEL_VENDOR_PREFIX) { TRANSITION_CAMEL = CAMEL_VENDOR_PREFIX + 'Transition'; TRANSITION_PROPERTY_CAMEL = CAMEL_VENDOR_PREFIX + 'TransitionProperty'; TRANSFORM_CAMEL = CAMEL_VENDOR_PREFIX + 'Transform'; } TRANSITION_PROPERTY = VENDOR_PREFIX + 'transition-property'; TRANSITION_DURATION = VENDOR_PREFIX + 'transition-duration'; TRANSITION_TIMING_FUNCTION = VENDOR_PREFIX + 'transition-timing-function'; TRANSITION_DELAY = VENDOR_PREFIX + 'transition-delay'; TRANSITION_END = 'transitionend'; ON_TRANSITION_END = 'on' + CAMEL_VENDOR_PREFIX.toLowerCase() + 'transitionend'; TRANSITION_END = VENDOR_TRANSITION_END[CAMEL_VENDOR_PREFIX] || TRANSITION_END; Transition.fx = {}; Transition.toggles = {}; Transition._hasEnd = {}; Transition._reKeywords = /^(?:node|duration|iterations|easing|delay|on|onstart|onend)$/i; Y.Node.DOM_EVENTS[TRANSITION_END] = 1; Transition.NAME = 'transition'; Transition.DEFAULT_EASING = 'ease'; Transition.DEFAULT_DURATION = 0.5; Transition.DEFAULT_DELAY = 0; Transition._nodeAttrs = {}; Transition.prototype = { constructor: Transition, init: function(node, config) { var anim = this; anim._node = node; if (!anim._running && config) { anim._config = config; node._transition = anim; // cache for reuse anim._duration = ('duration' in config) ? config.duration: anim.constructor.DEFAULT_DURATION; anim._delay = ('delay' in config) ? config.delay: anim.constructor.DEFAULT_DELAY; anim._easing = config.easing || anim.constructor.DEFAULT_EASING; anim._count = 0; // track number of animated properties anim._running = false; } return anim; }, addProperty: function(prop, config) { var anim = this, node = this._node, uid = Y.stamp(node), nodeInstance = Y.one(node), attrs = Transition._nodeAttrs[uid], computed, compareVal, dur, attr, val; if (!attrs) { attrs = Transition._nodeAttrs[uid] = {}; } attr = attrs[prop]; // might just be a value if (config && config.value !== undefined) { val = config.value; } else if (config !== undefined) { val = config; config = EMPTY_OBJ; } if (typeof val === 'function') { val = val.call(nodeInstance, nodeInstance); } if (attr && attr.transition) { // take control if another transition owns this property if (attr.transition !== anim) { attr.transition._count--; // remapping attr to this transition } } anim._count++; // properties per transition // make 0 async and fire events dur = ((typeof config.duration != 'undefined') ? config.duration : anim._duration) || 0.0001; attrs[prop] = { value: val, duration: dur, delay: (typeof config.delay != 'undefined') ? config.delay : anim._delay, easing: config.easing || anim._easing, transition: anim }; // native end event doesnt fire when setting to same value // supplementing with timer // val may be a string or number (height: 0, etc), but computedStyle is always string computed = Y.DOM.getComputedStyle(node, prop); compareVal = (typeof val === 'string') ? computed : parseFloat(computed); if (Transition.useNative && compareVal === val) { setTimeout(function() { anim._onNativeEnd.call(node, { propertyName: prop, elapsedTime: dur }); }, dur * 1000); } }, removeProperty: function(prop) { var anim = this, attrs = Transition._nodeAttrs[Y.stamp(anim._node)]; if (attrs && attrs[prop]) { delete attrs[prop]; anim._count--; } }, initAttrs: function(config) { var attr, node = this._node; if (config.transform && !config[TRANSFORM_CAMEL]) { config[TRANSFORM_CAMEL] = config.transform; delete config.transform; // TODO: copy } for (attr in config) { if (config.hasOwnProperty(attr) && !Transition._reKeywords.test(attr)) { this.addProperty(attr, config[attr]); // when size is auto or % webkit starts from zero instead of computed // (https://bugs.webkit.org/show_bug.cgi?id=16020) // TODO: selective set if (node.style[attr] === '') { Y.DOM.setStyle(node, attr, Y.DOM.getComputedStyle(node, attr)); } } } }, /** * Starts or an animation. * @method run * @chainable * @private */ run: function(callback) { var anim = this, node = anim._node, config = anim._config, data = { type: 'transition:start', config: config }; if (!anim._running) { anim._running = true; if (config.on && config.on.start) { config.on.start.call(Y.one(node), data); } anim.initAttrs(anim._config); anim._callback = callback; anim._start(); } return anim; }, _start: function() { this._runNative(); }, _prepDur: function(dur) { dur = parseFloat(dur) * 1000; return dur + 'ms'; }, _runNative: function(time) { var anim = this, node = anim._node, uid = Y.stamp(node), style = node.style, computed = node.ownerDocument.defaultView.getComputedStyle(node), attrs = Transition._nodeAttrs[uid], cssText = '', cssTransition = computed[Transition._toCamel(TRANSITION_PROPERTY)], transitionText = TRANSITION_PROPERTY + ': ', duration = TRANSITION_DURATION + ': ', easing = TRANSITION_TIMING_FUNCTION + ': ', delay = TRANSITION_DELAY + ': ', hyphy, attr, name; // preserve existing transitions if (cssTransition !== 'all') { transitionText += cssTransition + ','; duration += computed[Transition._toCamel(TRANSITION_DURATION)] + ','; easing += computed[Transition._toCamel(TRANSITION_TIMING_FUNCTION)] + ','; delay += computed[Transition._toCamel(TRANSITION_DELAY)] + ','; } // run transitions mapped to this instance for (name in attrs) { hyphy = Transition._toHyphen(name); attr = attrs[name]; if ((attr = attrs[name]) && attr.transition === anim) { if (name in node.style) { // only native styles allowed duration += anim._prepDur(attr.duration) + ','; delay += anim._prepDur(attr.delay) + ','; easing += (attr.easing) + ','; transitionText += hyphy + ','; cssText += hyphy + ': ' + attr.value + '; '; } else { this.removeProperty(name); } } } transitionText = transitionText.replace(/,$/, ';'); duration = duration.replace(/,$/, ';'); easing = easing.replace(/,$/, ';'); delay = delay.replace(/,$/, ';'); // only one native end event per node if (!Transition._hasEnd[uid]) { node.addEventListener(TRANSITION_END, anim._onNativeEnd, ''); Transition._hasEnd[uid] = true; } style.cssText += transitionText + duration + easing + delay + cssText; }, _end: function(elapsed) { var anim = this, node = anim._node, callback = anim._callback, config = anim._config, data = { type: 'transition:end', config: config, elapsedTime: elapsed }, nodeInstance = Y.one(node); anim._running = false; anim._callback = null; if (node) { if (config.on && config.on.end) { setTimeout(function() { // IE: allow previous update to finish config.on.end.call(nodeInstance, data); // nested to ensure proper fire order if (callback) { callback.call(nodeInstance, data); } }, 1); } else if (callback) { setTimeout(function() { // IE: allow previous update to finish callback.call(nodeInstance, data); }, 1); } } }, _endNative: function(name) { var node = this._node, value = node.ownerDocument.defaultView.getComputedStyle(node, '')[Transition._toCamel(TRANSITION_PROPERTY)]; name = Transition._toHyphen(name); if (typeof value === 'string') { value = value.replace(new RegExp('(?:^|,\\s)' + name + ',?'), ','); value = value.replace(/^,|,$/, ''); node.style[TRANSITION_CAMEL] = value; } }, _onNativeEnd: function(e) { var node = this, uid = Y.stamp(node), event = e,//e._event, name = Transition._toCamel(event.propertyName), elapsed = event.elapsedTime, attrs = Transition._nodeAttrs[uid], attr = attrs[name], anim = (attr) ? attr.transition : null, data, config; if (anim) { anim.removeProperty(name); anim._endNative(name); config = anim._config[name]; data = { type: 'propertyEnd', propertyName: name, elapsedTime: elapsed, config: config }; if (config && config.on && config.on.end) { config.on.end.call(Y.one(node), data); } if (anim._count <= 0) { // after propertyEnd fires anim._end(elapsed); node.style[TRANSITION_PROPERTY_CAMEL] = ''; // clean up style } } }, destroy: function() { var anim = this, node = anim._node; if (node) { node.removeEventListener(TRANSITION_END, anim._onNativeEnd, false); anim._node = null; } } }; Y.Transition = Transition; Y.TransitionNative = Transition; // TODO: remove /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.one('#demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for Node * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. * @chainable */ Y.Node.prototype.transition = function(name, config, callback) { var transitionAttrs = Transition._nodeAttrs[Y.stamp(this._node)], anim = (transitionAttrs) ? transitionAttrs.transition || null : null, fxConfig, prop; if (typeof name === 'string') { // named effect, pull config from registry if (typeof config === 'function') { callback = config; config = null; } fxConfig = Transition.fx[name]; if (config && typeof config !== 'boolean') { config = Y.clone(config); for (prop in fxConfig) { if (fxConfig.hasOwnProperty(prop)) { if (! (prop in config)) { config[prop] = fxConfig[prop]; } } } } else { config = fxConfig; } } else { // name is a config, config is a callback or undefined callback = config; config = name; } if (anim && !anim._running) { anim.init(this, config); } else { anim = new Transition(this._node, config); } anim.run(callback); return this; }; Y.Node.prototype.show = function(name, config, callback) { this._show(); // show prior to transition if (name && Y.Transition) { if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.SHOW_TRANSITION; } this.transition(name, config, callback); } return this; }; var _wrapCallBack = function(anim, fn, callback) { return function() { if (fn) { fn.call(anim); } if (callback) { callback.apply(anim._node, arguments); } }; }; Y.Node.prototype.hide = function(name, config, callback) { if (name && Y.Transition) { if (typeof config === 'function') { callback = config; config = null; } callback = _wrapCallBack(this, this._hide, callback); // wrap with existing callback if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.HIDE_TRANSITION; } this.transition(name, config, callback); } else { this._hide(); } return this; }; /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.all('.demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for NodeList * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. The callback fires * once per item in the NodeList. * @chainable */ Y.NodeList.prototype.transition = function(config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).transition(config, callback); } return this; }; Y.Node.prototype.toggleView = function(name, on, callback) { this._toggles = this._toggles || []; callback = arguments[arguments.length - 1]; if (typeof name == 'boolean') { // no transition, just toggle on = name; name = null; } name = name || Y.Transition.DEFAULT_TOGGLE; if (typeof on == 'undefined' && name in this._toggles) { // reverse current toggle on = ! this._toggles[name]; } on = (on) ? 1 : 0; if (on) { this._show(); } else { callback = _wrapCallBack(this, this._hide, callback); } this._toggles[name] = on; this.transition(Y.Transition.toggles[name][on], callback); return this; }; Y.NodeList.prototype.toggleView = function(name, on, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).toggleView(name, on, callback); } return this; }; Y.mix(Transition.fx, { fadeOut: { opacity: 0, duration: 0.5, easing: 'ease-out' }, fadeIn: { opacity: 1, duration: 0.5, easing: 'ease-in' }, sizeOut: { height: 0, width: 0, duration: 0.75, easing: 'ease-out' }, sizeIn: { height: function(node) { return node.get('scrollHeight') + 'px'; }, width: function(node) { return node.get('scrollWidth') + 'px'; }, duration: 0.5, easing: 'ease-in', on: { start: function() { var overflow = this.getStyle('overflow'); if (overflow !== 'hidden') { // enable scrollHeight/Width this.setStyle('overflow', 'hidden'); this._transitionOverflow = overflow; } }, end: function() { if (this._transitionOverflow) { // revert overridden value this.setStyle('overflow', this._transitionOverflow); delete this._transitionOverflow; } } } } }); Y.mix(Transition.toggles, { size: ['sizeOut', 'sizeIn'], fade: ['fadeOut', 'fadeIn'] }); Transition.DEFAULT_TOGGLE = 'fade'; }, '3.8.0pr2', {"requires": ["node-style"]}); YUI.add('selector-css2', function (Y, NAME) { /** * The selector module provides helper methods allowing CSS2 Selectors to be used with DOM elements. * @module dom * @submodule selector-css2 * @for Selector */ /* * Provides helper methods for collecting and filtering DOM elements. */ var PARENT_NODE = 'parentNode', TAG_NAME = 'tagName', ATTRIBUTES = 'attributes', COMBINATOR = 'combinator', PSEUDOS = 'pseudos', Selector = Y.Selector, SelectorCSS2 = { _reRegExpTokens: /([\^\$\?\[\]\*\+\-\.\(\)\|\\])/, SORT_RESULTS: true, // TODO: better detection, document specific _isXML: (function() { var isXML = (Y.config.doc.createElement('div').tagName !== 'DIV'); return isXML; }()), /** * Mapping of shorthand tokens to corresponding attribute selector * @property shorthand * @type object */ shorthand: { '\\#(-?[_a-z0-9]+[-\\w\\uE000]*)': '[id=$1]', '\\.(-?[_a-z]+[-\\w\\uE000]*)': '[className~=$1]' }, /** * List of operators and corresponding boolean functions. * These functions are passed the attribute and the current node's value of the attribute. * @property operators * @type object */ operators: { '': function(node, attr) { return Y.DOM.getAttribute(node, attr) !== ''; }, // Just test for existence of attribute '~=': '(?:^|\\s+){val}(?:\\s+|$)', // space-delimited '|=': '^{val}-?' // optional hyphen-delimited }, pseudos: { 'first-child': function(node) { return Y.DOM._children(node[PARENT_NODE])[0] === node; } }, _bruteQuery: function(selector, root, firstOnly) { var ret = [], nodes = [], tokens = Selector._tokenize(selector), token = tokens[tokens.length - 1], rootDoc = Y.DOM._getDoc(root), child, id, className, tagName; if (token) { // prefilter nodes id = token.id; className = token.className; tagName = token.tagName || '*'; if (root.getElementsByTagName) { // non-IE lacks DOM api on doc frags // try ID first, unless no root.all && root not in document // (root.all works off document, but not getElementById) if (id && (root.all || (root.nodeType === 9 || Y.DOM.inDoc(root)))) { nodes = Y.DOM.allById(id, root); // try className } else if (className) { nodes = root.getElementsByClassName(className); } else { // default to tagName nodes = root.getElementsByTagName(tagName); } } else { // brute getElementsByTagName() child = root.firstChild; while (child) { // only collect HTMLElements // match tag to supplement missing getElementsByTagName if (child.tagName && (tagName === '*' || child.tagName === tagName)) { nodes.push(child); } child = child.nextSibling || child.firstChild; } } if (nodes.length) { ret = Selector._filterNodes(nodes, tokens, firstOnly); } } return ret; }, _filterNodes: function(nodes, tokens, firstOnly) { var i = 0, j, len = tokens.length, n = len - 1, result = [], node = nodes[0], tmpNode = node, getters = Y.Selector.getters, operator, combinator, token, path, pass, value, tests, test; for (i = 0; (tmpNode = node = nodes[i++]);) { n = len - 1; path = null; testLoop: while (tmpNode && tmpNode.tagName) { token = tokens[n]; tests = token.tests; j = tests.length; if (j && !pass) { while ((test = tests[--j])) { operator = test[1]; if (getters[test[0]]) { value = getters[test[0]](tmpNode, test[0]); } else { value = tmpNode[test[0]]; if (test[0] === 'tagName' && !Selector._isXML) { value = value.toUpperCase(); } if (typeof value != 'string' && value !== undefined && value.toString) { value = value.toString(); // coerce for comparison } else if (value === undefined && tmpNode.getAttribute) { // use getAttribute for non-standard attributes value = tmpNode.getAttribute(test[0], 2); // 2 === force string for IE } } if ((operator === '=' && value !== test[2]) || // fast path for equality (typeof operator !== 'string' && // protect against String.test monkey-patch (Moo) operator.test && !operator.test(value)) || // regex test (!operator.test && // protect against RegExp as function (webkit) typeof operator === 'function' && !operator(tmpNode, test[0], test[2]))) { // function test // skip non element nodes or non-matching tags if ((tmpNode = tmpNode[path])) { while (tmpNode && (!tmpNode.tagName || (token.tagName && token.tagName !== tmpNode.tagName)) ) { tmpNode = tmpNode[path]; } } continue testLoop; } } } n--; // move to next token // now that we've passed the test, move up the tree by combinator if (!pass && (combinator = token.combinator)) { path = combinator.axis; tmpNode = tmpNode[path]; // skip non element nodes while (tmpNode && !tmpNode.tagName) { tmpNode = tmpNode[path]; } if (combinator.direct) { // one pass only path = null; } } else { // success if we made it this far result.push(node); if (firstOnly) { return result; } break; } } } node = tmpNode = null; return result; }, combinators: { ' ': { axis: 'parentNode' }, '>': { axis: 'parentNode', direct: true }, '+': { axis: 'previousSibling', direct: true } }, _parsers: [ { name: ATTRIBUTES, re: /^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i, fn: function(match, token) { var operator = match[2] || '', operators = Selector.operators, escVal = (match[3]) ? match[3].replace(/\\/g, '') : '', test; // add prefiltering for ID and CLASS if ((match[1] === 'id' && operator === '=') || (match[1] === 'className' && Y.config.doc.documentElement.getElementsByClassName && (operator === '~=' || operator === '='))) { token.prefilter = match[1]; match[3] = escVal; // escape all but ID for prefilter, which may run through QSA (via Dom.allById) token[match[1]] = (match[1] === 'id') ? match[3] : escVal; } // add tests if (operator in operators) { test = operators[operator]; if (typeof test === 'string') { match[3] = escVal.replace(Selector._reRegExpTokens, '\\$1'); test = new RegExp(test.replace('{val}', match[3])); } match[2] = test; } if (!token.last || token.prefilter !== match[1]) { return match.slice(1); } } }, { name: TAG_NAME, re: /^((?:-?[_a-z]+[\w-]*)|\*)/i, fn: function(match, token) { var tag = match[1]; if (!Selector._isXML) { tag = tag.toUpperCase(); } token.tagName = tag; if (tag !== '*' && (!token.last || token.prefilter)) { return [TAG_NAME, '=', tag]; } if (!token.prefilter) { token.prefilter = 'tagName'; } } }, { name: COMBINATOR, re: /^\s*([>+~]|\s)\s*/, fn: function(match, token) { } }, { name: PSEUDOS, re: /^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i, fn: function(match, token) { var test = Selector[PSEUDOS][match[1]]; if (test) { // reorder match array and unescape special chars for tests if (match[2]) { match[2] = match[2].replace(/\\/g, ''); } return [match[2], test]; } else { // selector token not supported (possibly missing CSS3 module) return false; } } } ], _getToken: function(token) { return { tagName: null, id: null, className: null, attributes: {}, combinator: null, tests: [] }; }, /* Break selector into token units per simple selector. Combinator is attached to the previous token. */ _tokenize: function(selector) { selector = selector || ''; selector = Selector._parseSelector(Y.Lang.trim(selector)); var token = Selector._getToken(), // one token per simple selector (left selector holds combinator) query = selector, // original query for debug report tokens = [], // array of tokens found = false, // whether or not any matches were found this pass match, // the regex match test, i, parser; /* Search for selector patterns, store, and strip them from the selector string until no patterns match (invalid selector) or we run out of chars. Multiple attributes and pseudos are allowed, in any order. for example: 'form:first-child[type=button]:not(button)[lang|=en]' */ outer: do { found = false; // reset after full pass for (i = 0; (parser = Selector._parsers[i++]);) { if ( (match = parser.re.exec(selector)) ) { // note assignment if (parser.name !== COMBINATOR ) { token.selector = selector; } selector = selector.replace(match[0], ''); // strip current match from selector if (!selector.length) { token.last = true; } if (Selector._attrFilters[match[1]]) { // convert class to className, etc. match[1] = Selector._attrFilters[match[1]]; } test = parser.fn(match, token); if (test === false) { // selector not supported found = false; break outer; } else if (test) { token.tests.push(test); } if (!selector.length || parser.name === COMBINATOR) { tokens.push(token); token = Selector._getToken(token); if (parser.name === COMBINATOR) { token.combinator = Y.Selector.combinators[match[1]]; } } found = true; } } } while (found && selector.length); if (!found || selector.length) { // not fully parsed tokens = []; } return tokens; }, _replaceMarkers: function(selector) { selector = selector.replace(/\[/g, '\uE003'); selector = selector.replace(/\]/g, '\uE004'); selector = selector.replace(/\(/g, '\uE005'); selector = selector.replace(/\)/g, '\uE006'); return selector; }, _replaceShorthand: function(selector) { var shorthand = Y.Selector.shorthand, re; for (re in shorthand) { if (shorthand.hasOwnProperty(re)) { selector = selector.replace(new RegExp(re, 'gi'), shorthand[re]); } } return selector; }, _parseSelector: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; // replace shorthand (".foo, #bar") after pseudos and attrs // to avoid replacing unescaped chars selector = Y.Selector._replaceShorthand(selector); selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); // replace braces and parens before restoring escaped chars // to avoid replacing ecaped markers selector = Y.Selector._replaceMarkers(selector); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _attrFilters: { 'class': 'className', 'for': 'htmlFor' }, getters: { href: function(node, attr) { return Y.DOM.getAttribute(node, attr); }, id: function(node, attr) { return Y.DOM.getId(node); } } }; Y.mix(Y.Selector, SelectorCSS2, true); Y.Selector.getters.src = Y.Selector.getters.rel = Y.Selector.getters.href; // IE wants class with native queries if (Y.Selector.useNative && Y.config.doc.querySelector) { Y.Selector.shorthand['\\.(-?[_a-z]+[-\\w]*)'] = '[class~=$1]'; } }, '3.8.0pr2', {"requires": ["selector-native"]}); YUI.add('selector-css3', function (Y, NAME) { /** * The selector css3 module provides support for css3 selectors. * @module dom * @submodule selector-css3 * @for Selector */ /* an+b = get every _a_th node starting at the _b_th 0n+b = no repeat ("0" and "n" may both be omitted (together) , e.g. "0n+1" or "1", not "0+1"), return only the _b_th element 1n+b = get every element starting from b ("1" may may be omitted, e.g. "1n+0" or "n+0" or "n") an+0 = get every _a_th element, "0" may be omitted */ Y.Selector._reNth = /^(?:([\-]?\d*)(n){1}|(odd|even)$)*([\-+]?\d*)$/; Y.Selector._getNth = function(node, expr, tag, reverse) { Y.Selector._reNth.test(expr); var a = parseInt(RegExp.$1, 10), // include every _a_ elements (zero means no repeat, just first _a_) n = RegExp.$2, // "n" oddeven = RegExp.$3, // "odd" or "even" b = parseInt(RegExp.$4, 10) || 0, // start scan from element _b_ result = [], siblings = Y.DOM._children(node.parentNode, tag), op; if (oddeven) { a = 2; // always every other op = '+'; n = 'n'; b = (oddeven === 'odd') ? 1 : 0; } else if ( isNaN(a) ) { a = (n) ? 1 : 0; // start from the first or no repeat } if (a === 0) { // just the first if (reverse) { b = siblings.length - b + 1; } if (siblings[b - 1] === node) { return true; } else { return false; } } else if (a < 0) { reverse = !!reverse; a = Math.abs(a); } if (!reverse) { for (var i = b - 1, len = siblings.length; i < len; i += a) { if ( i >= 0 && siblings[i] === node ) { return true; } } } else { for (var i = siblings.length - b, len = siblings.length; i >= 0; i -= a) { if ( i < len && siblings[i] === node ) { return true; } } } return false; }; Y.mix(Y.Selector.pseudos, { 'root': function(node) { return node === node.ownerDocument.documentElement; }, 'nth-child': function(node, expr) { return Y.Selector._getNth(node, expr); }, 'nth-last-child': function(node, expr) { return Y.Selector._getNth(node, expr, null, true); }, 'nth-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName); }, 'nth-last-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName, true); }, 'last-child': function(node) { var children = Y.DOM._children(node.parentNode); return children[children.length - 1] === node; }, 'first-of-type': function(node) { return Y.DOM._children(node.parentNode, node.tagName)[0] === node; }, 'last-of-type': function(node) { var children = Y.DOM._children(node.parentNode, node.tagName); return children[children.length - 1] === node; }, 'only-child': function(node) { var children = Y.DOM._children(node.parentNode); return children.length === 1 && children[0] === node; }, 'only-of-type': function(node) { var children = Y.DOM._children(node.parentNode, node.tagName); return children.length === 1 && children[0] === node; }, 'empty': function(node) { return node.childNodes.length === 0; }, 'not': function(node, expr) { return !Y.Selector.test(node, expr); }, 'contains': function(node, expr) { var text = node.innerText || node.textContent || ''; return text.indexOf(expr) > -1; }, 'checked': function(node) { return (node.checked === true || node.selected === true); }, enabled: function(node) { return (node.disabled !== undefined && !node.disabled); }, disabled: function(node) { return (node.disabled); } }); Y.mix(Y.Selector.operators, { '^=': '^{val}', // Match starts with value '$=': '{val}$', // Match ends with value '*=': '{val}' // Match contains value as substring }); Y.Selector.combinators['~'] = { axis: 'previousSibling' }; }, '3.8.0pr2', {"requires": ["selector-native", "selector-css2"]}); YUI.add('yui-log', function (Y, NAME) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 1, warn: 1, error: 1 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters src = src || ""; if (typeof src !== "undefined") { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console != UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera != UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher == Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '3.8.0pr2', {"requires": ["yui-base"]}); YUI.add('dump', function (Y, NAME) { /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. Use object notation for * associative arrays. * * If included, the dump method is added to the YUI instance. * * @module dump */ var L = Y.Lang, OBJ = '{...}', FUN = 'f(){...}', COMMA = ', ', ARROW = ' => ', /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. * * @method dump * @param {Object} o The object to dump. * @param {Number} d How deep to recurse child objects, default 3. * @return {String} the dump result. * @for YUI */ dump = function(o, d) { var i, len, s = [], type = L.type(o); // Cast non-objects to string // Skip dates because the std toString is what we want // Skip HTMLElement-like objects because trying to dump // an element will cause an unhandled exception in FF 2.x if (!L.isObject(o)) { return o + ''; } else if (type == 'date') { return o; } else if (o.nodeType && o.tagName) { return o.tagName + '#' + o.id; } else if (o.document && o.navigator) { return 'window'; } else if (o.location && o.body) { return 'document'; } else if (type == 'function') { return FUN; } // dig into child objects the depth specifed. Default 3 d = (L.isNumber(d)) ? d : 3; // arrays [1, 2, 3] if (type == 'array') { s.push('['); for (i = 0, len = o.length; i < len; i = i + 1) { if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } if (s.length > 1) { s.pop(); } s.push(']'); // regexp /foo/ } else if (type == 'regexp') { s.push(o.toString()); // objects {k1 => v1, k2 => v2} } else { s.push('{'); for (i in o) { if (o.hasOwnProperty(i)) { try { s.push(i + ARROW); if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } catch (e) { s.push('Error: ' + e.message); } } } if (s.length > 1) { s.pop(); } s.push('}'); } return s.join(''); }; Y.dump = dump; L.dump = dump; }, '3.8.0pr2', {"requires": ["yui-base"]}); YUI.add('transition-timer', function (Y, NAME) { /** * Provides the base Transition class, for animating numeric properties. * * @module transition * @submodule transition-timer */ var Transition = Y.Transition; Y.mix(Transition.prototype, { _start: function() { if (Transition.useNative) { this._runNative(); } else { this._runTimer(); } }, _runTimer: function() { var anim = this; anim._initAttrs(); Transition._running[Y.stamp(anim)] = anim; anim._startTime = new Date(); Transition._startTimer(); }, _endTimer: function() { var anim = this; delete Transition._running[Y.stamp(anim)]; anim._startTime = null; }, _runFrame: function() { var t = new Date() - this._startTime; this._runAttrs(t); }, _runAttrs: function(time) { var anim = this, node = anim._node, config = anim._config, uid = Y.stamp(node), attrs = Transition._nodeAttrs[uid], customAttr = Transition.behaviors, done = false, allDone = false, data, name, attribute, setter, elapsed, delay, d, t, i; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { d = attribute.duration; delay = attribute.delay; elapsed = (time - delay) / 1000; t = time; data = { type: 'propertyEnd', propertyName: name, config: config, elapsedTime: elapsed }; setter = (i in customAttr && 'set' in customAttr[i]) ? customAttr[i].set : Transition.DEFAULT_SETTER; done = (t >= d); if (t > d) { t = d; } if (!delay || time >= delay) { setter(anim, name, attribute.from, attribute.to, t - delay, d - delay, attribute.easing, attribute.unit); if (done) { delete attrs[name]; anim._count--; if (config[name] && config[name].on && config[name].on.end) { config[name].on.end.call(Y.one(node), data); } //node.fire('transition:propertyEnd', data); if (!allDone && anim._count <= 0) { allDone = true; anim._end(elapsed); anim._endTimer(); } } } } } }, _initAttrs: function() { var anim = this, customAttr = Transition.behaviors, uid = Y.stamp(anim._node), attrs = Transition._nodeAttrs[uid], attribute, duration, delay, easing, val, name, mTo, mFrom, unit, begin, end; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { duration = attribute.duration * 1000; delay = attribute.delay * 1000; easing = attribute.easing; val = attribute.value; // only allow supported properties if (name in anim._node.style || name in Y.DOM.CUSTOM_STYLES) { begin = (name in customAttr && 'get' in customAttr[name]) ? customAttr[name].get(anim, name) : Transition.DEFAULT_GETTER(anim, name); mFrom = Transition.RE_UNITS.exec(begin); mTo = Transition.RE_UNITS.exec(val); begin = mFrom ? mFrom[1] : begin; end = mTo ? mTo[1] : val; unit = mTo ? mTo[2] : mFrom ? mFrom[2] : ''; // one might be zero TODO: mixed units if (!unit && Transition.RE_DEFAULT_UNIT.test(name)) { unit = Transition.DEFAULT_UNIT; } if (typeof easing === 'string') { if (easing.indexOf('cubic-bezier') > -1) { easing = easing.substring(13, easing.length - 1).split(','); } else if (Transition.easings[easing]) { easing = Transition.easings[easing]; } } attribute.from = Number(begin); attribute.to = Number(end); attribute.unit = unit; attribute.easing = easing; attribute.duration = duration + delay; attribute.delay = delay; } else { delete attrs[name]; anim._count--; } } } }, destroy: function() { this.detachAll(); this._node = null; } }, true); Y.mix(Y.Transition, { _runtimeAttrs: {}, /* * Regex of properties that should use the default unit. * * @property RE_DEFAULT_UNIT * @static */ RE_DEFAULT_UNIT: /^width|height|top|right|bottom|left|margin.*|padding.*|border.*$/i, /* * The default unit to use with properties that pass the RE_DEFAULT_UNIT test. * * @property DEFAULT_UNIT * @static */ DEFAULT_UNIT: 'px', /* * Time in milliseconds passed to setInterval for frame processing * * @property intervalTime * @default 20 * @static */ intervalTime: 20, /* * Bucket for custom getters and setters * * @property behaviors * @static */ behaviors: { left: { get: function(anim, attr) { return Y.DOM._getAttrOffset(anim._node, attr); } } }, /* * The default setter to use when setting object properties. * * @property DEFAULT_SETTER * @static */ DEFAULT_SETTER: function(anim, att, from, to, elapsed, duration, fn, unit) { from = Number(from); to = Number(to); var node = anim._node, val = Transition.cubicBezier(fn, elapsed / duration); val = from + val[0] * (to - from); if (node) { if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { unit = unit || ''; Y.DOM.setStyle(node, att, val + unit); } } else { anim._end(); } }, /* * The default getter to use when getting object properties. * * @property DEFAULT_GETTER * @static */ DEFAULT_GETTER: function(anim, att) { var node = anim._node, val = ''; if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { val = Y.DOM.getComputedStyle(node, att); } return val; }, _startTimer: function() { if (!Transition._timer) { Transition._timer = setInterval(Transition._runFrame, Transition.intervalTime); } }, _stopTimer: function() { clearInterval(Transition._timer); Transition._timer = null; }, /* * Called per Interval to handle each animation frame. * @method _runFrame * @private * @static */ _runFrame: function() { var done = true, anim; for (anim in Transition._running) { if (Transition._running[anim]._runFrame) { done = false; Transition._running[anim]._runFrame(); } } if (done) { Transition._stopTimer(); } }, cubicBezier: function(p, t) { var x0 = 0, y0 = 0, x1 = p[0], y1 = p[1], x2 = p[2], y2 = p[3], x3 = 1, y3 = 0, A = x3 - 3 * x2 + 3 * x1 - x0, B = 3 * x2 - 6 * x1 + 3 * x0, C = 3 * x1 - 3 * x0, D = x0, E = y3 - 3 * y2 + 3 * y1 - y0, F = 3 * y2 - 6 * y1 + 3 * y0, G = 3 * y1 - 3 * y0, H = y0, x = (((A*t) + B)*t + C)*t + D, y = (((E*t) + F)*t + G)*t + H; return [x, y]; }, easings: { ease: [0.25, 0, 1, 0.25], linear: [0, 0, 1, 1], 'ease-in': [0.42, 0, 1, 1], 'ease-out': [0, 0, 0.58, 1], 'ease-in-out': [0.42, 0, 0.58, 1] }, _running: {}, _timer: null, RE_UNITS: /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/ }, true); Transition.behaviors.top = Transition.behaviors.bottom = Transition.behaviors.right = Transition.behaviors.left; Y.Transition = Transition; }, '3.8.0pr2', {"requires": ["transition"]}); YUI.add('yui', function (Y, NAME) { // empty }, '3.8.0pr2', { "use": [ "yui", "oop", "dom", "event-custom-base", "event-base", "pluginhost", "node", "event-delegate", "io-base", "json-parse", "transition", "selector-css3", "dom-style-ie", "querystring-stringify-simple" ] }); var Y = YUI().use('*');
define(function(require) { $.extend(KhanUtil, { getPermutations: function(arr) { var permArr = []; var usedChars = []; function permute(input) { for (var i = 0; i < input.length; i++) { var term = input.splice(i, 1)[0]; usedChars.push(term); if (input.length === 0) { permArr.push(usedChars.slice()); } permute(input); input.splice(i, 0, term); usedChars.pop(); } return permArr; } return permute(arr); }, writeExpressionFraction: function(numerator, denominator) { if (denominator.toString() === '1') { return numerator.toString(); } if (denominator.toString() === '-1') { return numerator.multiply(-1).toString(); } if (numerator.isNegative()) { return "-\\dfrac{" + numerator.multiply(-1).toString() + "}{" + denominator.toString() + "}"; } if (denominator.isNegative()) { return "-\\dfrac{" + numerator.toString() + "}{" + denominator.multiply(-1).toString() + "}"; } return "\\dfrac{" + numerator.toString() + "}{" + denominator.toString() + "}"; }, /* Term in an expression Takes an array. The first value is the coefficient and subsequent values are variables and their degree e.g. Term(5) = 5 Term(5, 'x') = 5x Term(5, 'xy') = 5xy Term(5, {'x': 1}) = 5x Term(5, {'x': 2}) = 5x^2 Term(5, {'x': 1, 'y': 2}) = 5xy^2 */ Term: function(coefficient, variables, degree) { this.coefficient = coefficient; this.variables = {}; if (degree === undefined) { degree = 1; } if (typeof variables === 'string') { for (var i = 0; i < variables.length; i++) { this.variables[variables.charAt(i)] = degree; } } else if (variables !== undefined){ this.variables = variables; } // Create a string representing the term // e.g. 5yx^2 = 5y1x2 // Used for hashing this.variableString = ''; for (var vari in this.variables) { if (this.variables[vari] !== 0) { this.variableString += vari + this.variables[vari]; } else { delete this.variables[vari]; } } this.isNegative = function() { return this.coefficient < 0; }; // Return a RationalExpression object representing the sum of this term with the passed object this.add = function(expression) { // Copy self so don't mutate original term var copy = [this.coefficient, this.variables]; if (expression instanceof KhanUtil.RationalExpression) { return expression.add(this); } else if (expression instanceof KhanUtil.Term) { return new KhanUtil.RationalExpression([copy, [expression.coefficient, expression.variables]]); } else { return new KhanUtil.RationalExpression([copy, expression]); } }; this.isOne = function() { return this.toString() === '1'; }; // Given a mapping of variable to value, {'x' : 2}, evaulate the term // Or give a number and all variables will be given that value // TODO: Make this work for multi-variable terms // when only the value of one variable is given this.evaluate = function(values) { var value = this.coefficient; if (typeof values === 'number') { _.each(this.variables, function(v) { value *= Math.pow(values, v); }); } else { _.each(this.variables, function(v, i) { value *= Math.pow(values[i], v); }); } return value; }; // Return a new term representing this term multiplied by another term or a number this.multiply = function(term) { if (term instanceof KhanUtil.RationalExpression) { return term.multiply(this); } var coefficient = this.coefficient; var variables = _.clone(this.variables); if (typeof term === 'number') { coefficient *= term; } else { coefficient *= term.coefficient; for (var i in term.variables) { if (variables[i] != null) { variables[i] += term.variables[i]; } else { variables[i] = term.variables[i]; } } } return new KhanUtil.Term(coefficient, variables); }; // Return a new term representing this term divided by another term or a number this.divide = function(term) { var coefficient = this.coefficient; var variables = _.clone(this.variables); if (typeof term === 'number') { coefficient /= term; } else { coefficient /= term.coefficient; for (var i in term.variables) { if (variables[i]) { variables[i] -= term.variables[i]; } else { variables[i] = -term.variables[i]; } } } return new KhanUtil.Term(coefficient, variables); }; // Return a Term object representing the greatest common factor between this term and another this.getGCD = function(expression) { if (expression instanceof KhanUtil.RationalExpression) { return expression.getGCD(this); } if (typeof expression === 'number') { return KhanUtil.getGCD(this.coefficient, expression); } var coefficient = KhanUtil.getGCD(this.coefficient, expression.coefficient); var variables = {}; for (var i in this.variables) { if (expression.variables[i]) { variables[i] = Math.min(this.variables[i], expression.variables[i]); } } return new KhanUtil.Term(coefficient, variables); }; // includeSign if term is not the first in an expression this.toString = function(includeSign) { if (this.coefficient === 0) { return ''; } var s = ''; if (includeSign) { s += this.coefficient >= 0 ? ' + ' : ' - '; } else if (this.coefficient < 0) { s += '-'; } var coefficient = Math.abs(this.coefficient); if (!(coefficient === 1 && this.variableString !== "")) { s += coefficient; } _.each(this.variables, function(degree, i) { if (degree === 0) { return; // continue } s += i; if (degree !== 1) { s += '^' + degree; } }); return s; }; // Just so Terms can be treated like RationalExpressions this.toStringFactored = function() { return this.toString(); }; // Return a string showing how the term should be evaluated with a given value // e.g. 5x^2 evalated with 3 returns 5(3)^2 // If color is defined, the value representing the variable is colored this.getEvaluateString = function(values, includeSign, color) { var s = ''; if (includeSign) { s += this.coefficient >= 0 ? ' + ' : ' - '; } else if (this.coefficient < 0) { s += '-'; } var coefficient = Math.abs(this.coefficient); if (!(coefficient === 1 && this.variableString !== '')) { s += coefficient; if (this.variableString !== '') { s += '\\cdot'; } } _.each(this.variables, function(degree, i) { var value = (typeof values === 'number') ? values : values[i]; if (color !== undefined) { value = '\\' + color + '{' + value + '}'; } s += (value < 0 || degree === 1) ? value : '(' + value + ')^' + degree; }); return s; }; // Return a regex that will capture this term // If includeSign is true, then 4x is captured by +4x this.regex = function() { return '^' + this.regexForExpression() + '$'; }; // Return a regex that will capture this term // If includeSign is true, then 4x is captured by +4x this.regexForExpression = function(includeSign) { if (this.coefficient === 0) { return ''; } var regex; // Include leading space if there are earlier terms if (this.coefficient < 0){ regex = includeSign ? '[-\\u2212]\\s*' : '\\s*[-\\u2212]\\s*'; } else { regex = includeSign ? '\\+\\s*' : '\\s*'; } if (!(Math.abs(this.coefficient) === 1 && this.variableString !== '')) { regex += Math.abs(this.coefficient); } // Add all permutations of variables var variable_array = []; for (var vari in this.variables) { if (degree !== 0) { variable_array.push([vari, this.variables[vari]]); } } if (variable_array.length > 1) { var permutations = KhanUtil.getPermutations(variable_array); regex += "(?:"; for (var p=0; p<permutations.length; p++) { var variables = permutations[p]; regex += "(?:"; for (var i=0; i<variables.length; i++) { var vari = variables[i][0]; var degree = variables[i][1]; regex += degree > 1 ? vari + "\\s*\\^\\s*" + degree : vari; } regex += p < permutations.length - 1 ? ")|" : ")"; } regex += ")"; } else if (variable_array.length === 1) { var vari = variable_array[0][0]; var degree = variable_array[0][1]; regex += degree > 1 ? vari + "\\s*\\^\\s*" + degree : vari; } return regex + '\\s*'; }; }, /* A flat (i.e. no parentheses), multi-variable polynomial expression Represented as an array of terms that are added together Terms can be numbers or an array representing [coefficient, variable] e.g. [5, [1, 'x']] = 5 + x e.g. [5, [2, {'x': 2}] = 5 + 2x^2 e.g. [5, [2, {'x': 2, 'y': 1}]] = 5 + 2x^2y */ RationalExpression: function(terms) { this.terms = []; for (var i = 0; i < terms.length; i++) { var term = terms[i]; var newTerm; if (typeof term === 'number') { newTerm = new KhanUtil.Term(term); } else if (term instanceof KhanUtil.Term) { newTerm = new KhanUtil.Term(term.coefficient, term.variables); } else { newTerm = new KhanUtil.Term(term[0], term[1]); } if (newTerm.coefficient !== 0) { this.terms.push(newTerm); } } // Given a term, e.g. x1, return the coefficient of that term this.getCoefficient = function(variable) { var coefficient = 0; for (var i = 0; i < this.terms.length; i++) { if (this.terms[i].variableString === variable) { coefficient += this.terms[i].coefficient; } } return coefficient; }; // Combine any terms that have the same variable and remove any with a coefficient of 0 this.combineLikeTerms = function() { var variables = {}; for (var i = 0; i < this.terms.length; i++) { var term = this.terms[i]; var s = term.variableString; if (variables[s]) { variables[s].coefficient += term.coefficient; } else { variables[s] = term; } } this.terms = []; for (var v in variables) { if (variables[v].coefficient !== 0) { this.terms.push(variables[v]); } } }; this.combineLikeTerms(); // Test whether this expressions is equal to the one passed in // Assumes the like terms in both expressions have been combined this.isEqualTo = function(that) { var n1 = this.terms.length; var n2 = that.terms.length; if (n1 !== n2) { return false; } for (var i=0; i<n1; i++) { var t1 = this.terms[i]; var found = false; for (var j=0; j<n2; j++) { var t2 = that.terms[j]; if (t1.coefficient === t2.coefficient && t1.variableString === t2.variableString) { found = true; break; } } if (!found) { return false; } } return true; }; this.isNegative = function() { return this.terms[0].coefficient < 0; }; // Return the coefficient of term contain variable to the degree power // e.g. for 5x^2 + x + 2, getCoefficentOfTerm('x', 2) will return 5 // getCoefficentOfTerm('x',) will return 1 // getCoefficentOfTerm() will return 2 this.getCoefficentOfTerm = function(variable, degree) { var variableString = ""; if (variable === '') { variableString = ''; } else if (variable !== undefined && degree !== 0) { degree = degree || 1; variableString = variable + degree; } for (var i = 0; i < this.terms.length; i++) { if (this.terms[i].variableString === variableString) { return this.terms[i].coefficient; } } return 0; }; this.evaluate = function(values) { var value = 0; for (var i = 0; i < this.terms.length; i++) { value += this.terms[i].evaluate(values); } return value; }; // Return a new expression which is the sum of this one and the one passed in this.add = function(expression) { var terms = []; // Copy own terms for (var i = 0; i < this.terms.length; i++) { var term = this.terms[i]; terms.push([term.coefficient, term.variables]); } if (expression instanceof KhanUtil.Term) { // Add single term terms.push(new KhanUtil.Term(expression.coefficient, expression.variables)); } else if (typeof expression === 'number') { // Add single digit terms.push(new KhanUtil.Term(expression)); } else { // Add all terms from another expression for (var i = 0; i < expression.terms.length; i++) { var term = expression.terms[i]; terms.push([term.coefficient, term.variables]); } } var result = new KhanUtil.RationalExpression(terms); result.combineLikeTerms(); return result; }; // Return a new expression representing the product of this one and the one passed in this.multiply = function(expression) { var multiplyTerms; if (expression instanceof KhanUtil.RationalExpression) { multiplyTerms = expression.terms; } else if (typeof expression === 'number' || expression instanceof KhanUtil.Term) { multiplyTerms = [expression]; } else { // Assume it's a variable name multiplyTerms = [new KhanUtil.Term(1, expression)]; } var terms = []; for (var i = 0; i < multiplyTerms.length; i++) { var value = multiplyTerms[i]; for (var j = 0; j < this.terms.length; j++) { terms.push(this.terms[j].multiply(value)); } } return new KhanUtil.RationalExpression(terms); }; // Return a new expression representing this one divided by another expression // Assumes this expression can be factored to remove the one passed in this.divide = function(expression) { if (expression instanceof KhanUtil.RationalExpression) { if (expression.terms.length === 1) { return this.divide(expression.terms[0]); } var factors1 = this.factor(); var factors2 = expression.factor(); if (factors1[1].isEqualTo(factors2[1])) { var value = factors1[0].divide(factors2[0]); return new KhanUtil.RationalExpression([value]); } else if (factors1[1].isEqualTo(factors2[1].multiply(-1))) { var value = factors1[0].divide(factors2[0]).multiply(-1); return new KhanUtil.RationalExpression([value]); } else { // Cannot divide by this expression // Can be used to check whether expression have a common factor return false; } } else { var terms = []; for (var i = 0; i < this.terms.length; i++) { terms.push(this.terms[i].divide(expression)); } return new KhanUtil.RationalExpression(terms); } }; // Return a Term object representing the greatest common factor between this expression and another this.getGCD = function(that) { var t1 = this.getTermsGCD(); var GCD; if (that instanceof KhanUtil.Term) { GCD = t1.getGCD(that); } else if (that instanceof KhanUtil.RationalExpression) { GCD = t1.getGCD(that.getTermsGCD()); } else { return KhanUtil.getGCD(that, t1.coefficient); } if (GCD.coefficient < 0) { GCD.coefficient *= -1; } return GCD; }; // Return a Term object representing the greatest common divisor of all the terms in this expression this.getTermsGCD = function() { var GCD = this.terms[0]; for (var i=0; i<this.terms.length; i++) { GCD = GCD.getGCD(this.terms[i]); } if (this.isNegative()) { GCD = GCD.multiply(-1); } return GCD; }; // Factor out the GCD of all terms and return [GCD, remaining expression] // e.g. 6x + 4x^2 => [2x, 3 + 2x] this.factor = function() { var gcd = this.getTermsGCD(); var factor = this.divide(gcd); return [gcd, factor]; }; this.toString = function() { if (this.terms.length === 0) { return '0'; } var s = this.terms[0].toString(); for (var i = 1; i < this.terms.length; i++) { s += this.terms[i].toString(s !== ''); } return s !== '' ? s : '0'; }; // Return a string of the factored expression this.toStringFactored = function(parenthesise) { var factors = this.factor(); if (this.terms.length === 1 || factors[0].isOne()) { if (parenthesise) { return "(" + this.toString() + ")"; } else { return this.toString(); } } var s = (factors[0].toString() === '-1') ? '-' : factors[0].toString(); s += "(" + factors[1].toString() + ")"; return s; }; // Returns a string showing the expression with variable substituted. this.getEvaluateString = function(values, color) { var s = this.terms[0].getEvaluateString(values, false, color); for (var i = 1; i < this.terms.length; i++) { s += this.terms[i].getEvaluateString(values, true, color); } return s !== "" ? s : '0'; }; // Returns a regex that captures all permutation passed in this.getTermsRegex = function(permutations, start, stop) { var regex = ""; start = start ? "|(?:^" + start : "|(?:^"; stop = stop ? stop + "$)" : "$)"; for (var p = 0; p < permutations.length; p++) { regex += start; var terms = permutations[p]; for (var i = 0; i < terms.length; i++) { regex += terms[i].regexForExpression(i); } regex += stop; } return regex; }; // Returns a single regex to capture this expression. // It will capture every permutations of terms so is // not recommended for expressions with more than 3 terms // If allowFactors is true, 3(x + 4) will match 3x + 12 this.regex = function(allowFactors) { var permutations = KhanUtil.getPermutations(this.terms); var regex = this.getTermsRegex(permutations).slice(1); if (!allowFactors || this.terms.length === 1) { return regex; } // Generate regex factored expression // If GCD is 1, will accept parenthesised expression // e.g. p - 5 will accept (p - 5) var factors = this.factor(); permutations = KhanUtil.getPermutations(factors[1].terms); if (factors[0].isOne()) { regex += this.getTermsRegex(permutations, "\\s*\\(", "\\)\\s*"); } else if (factors[0].toString() === '-1') { regex += this.getTermsRegex(permutations, "\\s*[-\\u2212]\\s*\\(", "\\)\\s*"); } else { regex += this.getTermsRegex(permutations, factors[0].regexForExpression() + "\\*?\\s*\\(", "\\)\\s*"); } // Factor out a negative factors[0] = factors[0].multiply(-1); factors[1] = factors[1].multiply(-1); permutations = KhanUtil.getPermutations(factors[1].terms); if (factors[0].isOne()) { regex += this.getTermsRegex(permutations, "\\s*\\(", "\\)\\s*"); } else if (factors[0].toString === '-1') { regex += this.getTermsRegex(permutations, "\\s*[-\\u2212]\\s*\\(", "\\)\\s*"); } else { regex += this.getTermsRegex(permutations, factors[0].regexForExpression() + "\\*?\\s*\\(", "\\)\\s*"); } return regex; }; } }); });
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is JavaScript Engine testing utilities. * * The Initial Developer of the Original Code is * Mozilla Foundation. * Portions created by the Initial Developer are Copyright (C) 2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): Igor Bukanov * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ var gTestfile = 'regress-311515.js'; //----------------------------------------------------------------------------- var BUGNUMBER = 311515; var summary = 'Array.sort should skip holes and undefined during sort'; var actual = ''; var expect = ''; printBugNumber(BUGNUMBER); printStatus (summary); var a = [, 1, , 2, undefined]; actual = a.sort().toString(); expect = '1,2,,,'; reportCompare(expect, actual, summary);
/*~ -- KNOT EQUIVALENCE VIEWS --------------------------------------------------------------------------------------------- -- -- Equivalence views combine the identity and equivalent parts of a knot into a single view, making -- it look and behave like a regular knot. They also make it possible to retrieve data for only the -- given equivalent. -- -- @equivalent the equivalent that you want to retrieve data for -- ~*/ var knot; while (knot = schema.nextKnot()) { if(schema.EQUIVALENCE && knot.isEquivalent()) { /*~ -- Knot equivalence view ---------------------------------------------------------------------------------------------- -- $knot.name view and parametrized view ----------------------------------------------------------------------------------------------------------------------- IF Object_ID('$knot.capsule$.$knot.name', 'V') IS NULL BEGIN EXEC(' CREATE VIEW [$knot.capsule].[$knot.name] WITH SCHEMABINDING AS SELECT $(schema.METADATA)? v.$knot.metadataColumnName, i.$knot.identityColumnName, v.$knot.equivalentColumnName, $(knot.hasChecksum())? v.$knot.checksumColumnName, v.$knot.valueColumnName FROM [$knot.capsule].[$knot.identityName] i JOIN [$knot.capsule].[$knot.equivalentName] v ON v.$knot.identityColumnName = i.$knot.identityColumnName; '); END GO IF Object_ID('$knot.capsule$.e$knot.name', 'IF') IS NULL BEGIN EXEC(' CREATE FUNCTION [$knot.capsule].[e$knot.name] ( @equivalent $schema.metadata.equivalentRange ) RETURNS TABLE WITH SCHEMABINDING AS RETURN SELECT $(schema.METADATA)? $knot.metadataColumnName, $knot.identityColumnName, $knot.equivalentColumnName, $(knot.hasChecksum())? $knot.checksumColumnName, $knot.valueColumnName FROM [$knot.capsule].[$knot.name] WHERE $knot.equivalentColumnName = @equivalent; '); END GO ~*/ } }
/* keyboard layout template (copy of "international" from the core plugin) */ jQuery.keyboard.layouts['international'] = { 'name' : 'international', 'lang' : ['all'], // this setting must match the "all" language definition below 'normal': [ '` 1 2 3 4 5 6 7 8 9 0 - = {bksp}', '{tab} q w e r t y u i o p [ ] \\', 'a s d f g h j k l ; \' {enter}', '{shift} z x c v b n m , . / {shift}', '{accept} {alt} {space} {alt} {cancel}' ], 'shift': [ '~ ! @ # $ % ^ & * ( ) _ + {bksp}', '{tab} Q W E R T Y U I O P { } |', 'A S D F G H J K L : " {enter}', '{shift} Z X C V B N M < > ? {shift}', '{accept} {alt} {space} {alt} {cancel}' ], 'alt': [ '~ \u00a1 \u00b2 \u00b3 \u00a4 \u20ac \u00bc \u00bd \u00be \u2018 \u2019 \u00a5 \u00d7 {bksp}', '{tab} \u00e4 \u00e5 \u00e9 \u00ae \u00fe \u00fc \u00fa \u00ed \u00f3 \u00f6 \u00ab \u00bb \u00ac', '\u00e1 \u00df \u00f0 f g h j k \u00f8 \u00b6 \u00b4 {enter}', '{shift} \u00e6 x \u00a9 v b \u00f1 \u00b5 \u00e7 > \u00bf {shift}', '{accept} {alt} {space} {alt} {cancel}' ], 'alt-shift': [ '~ \u00b9 \u00b2 \u00b3 \u00a3 \u20ac \u00bc \u00bd \u00be \u2018 \u2019 \u00a5 \u00f7 {bksp}', '{tab} \u00c4 \u00c5 \u00c9 \u00ae \u00de \u00dc \u00da \u00cd \u00d3 \u00d6 \u00ab \u00bb \u00a6', '\u00c4 \u00a7 \u00d0 F G H J K \u00d8 \u00b0 \u00a8 {enter}', '{shift} \u00c6 X \u00a2 V B \u00d1 \u00b5 \u00c7 . \u00bf {shift}', '{accept} {alt} {space} {alt} {cancel}' ] };
var hasMozTransform, getHasMozTransform = function() { if(hasMozTransform === undefined) { hasMozTransform = document.createElement('p').style.MozTransform !== undefined; } return hasMozTransform; }; $.magnificPopup.registerModule('zoom', { options: { enabled: false, easing: 'ease-in-out', duration: 300, opener: function(element) { return element.is('img') ? element : element.find('img'); } }, proto: { initZoom: function() { var zoomSt = mfp.st.zoom, ns = '.zoom', image; if(!zoomSt.enabled || !mfp.supportsTransition) { return; } var duration = zoomSt.duration, getElToAnimate = function(image) { var newImg = image.clone().removeAttr('style').removeAttr('class').addClass('mfp-animated-image'), transition = 'all '+(zoomSt.duration/1000)+'s ' + zoomSt.easing, cssObj = { position: 'fixed', zIndex: 9999, left: 0, top: 0, '-webkit-backface-visibility': 'hidden' }, t = 'transition'; cssObj['-webkit-'+t] = cssObj['-moz-'+t] = cssObj['-o-'+t] = cssObj[t] = transition; newImg.css(cssObj); return newImg; }, showMainContent = function() { mfp.content.css('visibility', 'visible'); }, openTimeout, animatedImg; _mfpOn('BuildControls'+ns, function() { if(mfp._allowZoom()) { clearTimeout(openTimeout); mfp.content.css('visibility', 'hidden'); // Basically, all code below does is clones existing image, puts in on top of the current one and animated it image = mfp._getItemToZoom(); if(!image) { showMainContent(); return; } animatedImg = getElToAnimate(image); animatedImg.css( mfp._getOffset() ); mfp.wrap.append(animatedImg); openTimeout = setTimeout(function() { animatedImg.css( mfp._getOffset( true ) ); openTimeout = setTimeout(function() { showMainContent(); setTimeout(function() { animatedImg.remove(); image = animatedImg = null; _mfpTrigger('ZoomAnimationEnded'); }, 16); // avoid blink when switching images }, duration); // this timeout equals animation duration }, 16); // by adding this timeout we avoid short glitch at the beginning of animation // Lots of timeouts... } }); _mfpOn(BEFORE_CLOSE_EVENT+ns, function() { if(mfp._allowZoom()) { clearTimeout(openTimeout); mfp.st.removalDelay = duration; if(!image) { image = mfp._getItemToZoom(); if(!image) { return; } animatedImg = getElToAnimate(image); } animatedImg.css( mfp._getOffset(true) ); mfp.wrap.append(animatedImg); mfp.content.css('visibility', 'hidden'); setTimeout(function() { animatedImg.css( mfp._getOffset() ); }, 16); } }); _mfpOn(CLOSE_EVENT+ns, function() { if(mfp._allowZoom()) { showMainContent(); if(animatedImg) { animatedImg.remove(); } image = null; } }); }, _allowZoom: function() { return mfp.currItem.type === 'image'; }, _getItemToZoom: function() { if(mfp.currItem.hasSize) { return mfp.currItem.img; } else { return false; } }, // Get element postion relative to viewport _getOffset: function(isLarge) { var el; if(isLarge) { el = mfp.currItem.img; } else { el = mfp.st.zoom.opener(mfp.currItem.el || mfp.currItem); } var offset = el.offset(); var paddingTop = parseInt(el.css('padding-top'),10); var paddingBottom = parseInt(el.css('padding-bottom'),10); offset.top -= ( $(window).scrollTop() - paddingTop ); /* Animating left + top + width/height looks glitchy in Firefox, but perfect in Chrome. And vice-versa. */ var obj = { width: el.width(), // fix Zepto height+padding issue height: (_isJQ ? el.innerHeight() : el[0].offsetHeight) - paddingBottom - paddingTop }; // I hate to do this, but there is no another option if( getHasMozTransform() ) { obj['-moz-transform'] = obj['transform'] = 'translate(' + offset.left + 'px,' + offset.top + 'px)'; } else { obj.left = offset.left; obj.top = offset.top; } return obj; } } });
define([ "../core", "./var/rsingleTag", "../manipulation" // buildFragment ], function( jQuery, rsingleTag ) { // 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 ); }; return jQuery.parseHTML; });
/* */ System.register([], function (_export) { var _prototypeProperties, _classCallCheck, Redirect; /** * Determines if the provided object is a navigation command. * A navigation command is anything with a navigate method. * @param {object} obj The item to check. * @return {boolean} */ _export("isNavigationCommand", isNavigationCommand); function isNavigationCommand(obj) { return obj && typeof obj.navigate === "function"; } return { setters: [], execute: function () { "use strict"; _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); }; _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; /** * Used during the activation lifecycle to cause a redirect. * * @class Redirect * @constructor * @param {String} url The url to redirect to. */ Redirect = _export("Redirect", (function () { function Redirect(url) { _classCallCheck(this, Redirect); this.url = url; this.shouldContinueProcessing = false; } _prototypeProperties(Redirect, null, { navigate: { /** * Called by the navigation pipeline to navigate. * * @method navigate * @param {Router} appRouter - a router which should redirect */ value: function navigate(appRouter) { (this.router || appRouter).navigate(this.url, { trigger: true, replace: true }); }, writable: true, configurable: true } }); return Redirect; })()); } }; });
/*global define*/ define([ 'Core/RuntimeError' ], function( RuntimeError) { "use strict"; var BadGeometry = function() { this._workerName = '../../Specs/TestWorkers/createBadGeometry'; }; BadGeometry.createGeometry = function() { //This function is only called when synchronous, see Specs/TestWorks/createBadGeometry for asynchronous. throw new RuntimeError('BadGeometry.createGeometry'); }; BadGeometry.packedLength = 0; BadGeometry.pack = function() { }; BadGeometry.unpack = function() { return new BadGeometry(); }; return BadGeometry; });
module.exports = require('./api');
// Dependencies var typpy = require("typpy"); /** * Err * Create a custom error object. * * @name Err * @function * @param {String|Error} error The error message or an existing `Error` instance. * @param {String|Object} code The error code or the data object. * @param {Object} data The data object (its fields will be appended to the `Error` object). * @return {Error} The custom `Error` instance. */ function Err(error, code, data) { // Create the error if (!typpy(error, Error)) { error = new Error(error); } // Err(message, code, data); // Err(message, data); if (typpy(data, Object)) { data.code = code; } else if (typpy(code, Object)) { data = code; code = undefined; } else if (!typpy(code, undefined)) { data = { code: code }; } if (data) { Object.keys(data).forEach(function (c) { error[c] = data[c]; }); } return error; } module.exports = Err;
import React from 'react'; import NotAuthorizedPage from '../../../components/NotAuthorizedPage'; import { usePermission } from '../../../contexts/AuthorizationContext'; import EmailInboxPage from './EmailInboxPage'; function EmailInboxRoute() { const canViewEmailInbox = usePermission('manage-email-inbox'); if (!canViewEmailInbox) { return <NotAuthorizedPage />; } return <EmailInboxPage />; } export default EmailInboxRoute;
import { Template } from 'meteor/templating'; import { createCollapseable } from '../../ui-utils'; createCollapseable(Template.oembedBaseWidget, (instance) => instance.data.settings.collapseMediaByDefault || false); Template.oembedBaseWidget.helpers({ template() { const { collapsedMedia } = Template.instance(); this.collapsedMediaVar = () => collapsedMedia; this.collapsed = collapsedMedia.get(); if (this.headers?.contentType?.match(/image\/.*/)) { return 'oembedImageWidget'; } if (this.headers?.contentType?.match(/audio\/.*/)) { return 'oembedAudioWidget'; } if (this.headers?.contentType?.match(/video\/.*/) || this.meta?.twitterPlayerStreamContentType?.match(/video\/.*/)) { return 'oembedVideoWidget'; } if (this.meta?.oembedHtml) { return 'oembedFrameWidget'; } return 'oembedUrlWidget'; }, });
import PageManager from './page-manager'; export default class OrderComplete extends PageManager {}
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.getSha1 = exports.worker = undefined; let worker = (exports.worker = (() => { var _ref = _asyncToGenerator(function*(data) { if ( data.hasteImplModulePath && data.hasteImplModulePath !== hasteImplModulePath ) { if (hasteImpl) { throw new Error('jest-haste-map: hasteImplModulePath changed'); } hasteImplModulePath = data.hasteImplModulePath; // $FlowFixMe: dynamic require hasteImpl = require(hasteImplModulePath); } let content; let dependencies; let id; let module; let sha1; const computeDependencies = data.computeDependencies, computeSha1 = data.computeSha1, filePath = data.filePath; const getContent = function() { if (content === undefined) { content = (_gracefulFs || _load_gracefulFs()).default.readFileSync( filePath, 'utf8' ); } return content; }; if (filePath.endsWith(PACKAGE_JSON)) { // Process a package.json that is returned as a PACKAGE type with its name. try { const fileData = JSON.parse(getContent()); if (fileData.name) { id = fileData.name; module = [ filePath, (_constants || _load_constants()).default.PACKAGE ]; } } catch (err) { throw new Error(`Cannot parse ${filePath} as JSON: ${err.message}`); } } else if ( !(_blacklist || _load_blacklist()).default.has( filePath.substr(filePath.lastIndexOf('.')) ) ) { // Process a random file that is returned as a MODULE. if (hasteImpl) { id = hasteImpl.getHasteName(filePath); } else { const doc = (_jestDocblock || _load_jestDocblock()).parse( (_jestDocblock || _load_jestDocblock()).extract(getContent()) ); id = [].concat(doc.providesModule || doc.provides)[0]; } if (computeDependencies) { dependencies = (0, (_extract_requires || _load_extract_requires()).default)(getContent()); } if (id) { module = [filePath, (_constants || _load_constants()).default.MODULE]; } } // If a SHA-1 is requested on update, compute it. if (computeSha1) { sha1 = sha1hex( getContent() || (_gracefulFs || _load_gracefulFs()).default.readFileSync(filePath) ); } return {dependencies: dependencies, id: id, module: module, sha1: sha1}; }); return function worker(_x) { return _ref.apply(this, arguments); }; })()); let getSha1 = (exports.getSha1 = (() => { var _ref2 = _asyncToGenerator(function*(data) { const sha1 = data.computeSha1 ? sha1hex( (_gracefulFs || _load_gracefulFs()).default.readFileSync( data.filePath ) ) : null; return { dependencies: undefined, id: undefined, module: undefined, sha1: sha1 }; }); return function getSha1(_x2) { return _ref2.apply(this, arguments); }; })()); var _crypto; function _load_crypto() { return (_crypto = _interopRequireDefault(require('crypto'))); } var _path; function _load_path() { return (_path = _interopRequireDefault(require('path'))); } var _jestDocblock; function _load_jestDocblock() { return (_jestDocblock = _interopRequireWildcard(require('jest-docblock'))); } var _gracefulFs; function _load_gracefulFs() { return (_gracefulFs = _interopRequireDefault(require('graceful-fs'))); } var _blacklist; function _load_blacklist() { return (_blacklist = _interopRequireDefault(require('./blacklist'))); } var _constants; function _load_constants() { return (_constants = _interopRequireDefault(require('./constants'))); } var _extract_requires; function _load_extract_requires() { return (_extract_requires = _interopRequireDefault( require('./lib/extract_requires') )); } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : {default: obj}; } function _asyncToGenerator(fn) { return function() { var gen = fn.apply(this, arguments); return new Promise(function(resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then( function(value) { step('next', value); }, function(err) { step('throw', err); } ); } } return step('next'); }); }; } /** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ const PACKAGE_JSON = (_path || _load_path()).default.sep + 'package.json'; let hasteImpl = null; let hasteImplModulePath = null; function sha1hex(content) { return (_crypto || _load_crypto()).default .createHash('sha1') .update(content) .digest('hex'); }
$(function() { // Get the form. var form = $('#contact-form'); // Get the messages div. var formMessages = $('.form-messege'); // Set up an event listener for the contact form. $(form).submit(function(e) { // Stop the browser from submitting the form. e.preventDefault(); // Serialize the form data. var formData = $(form).serialize(); // Submit the form using AJAX. $.ajax({ type: 'POST', url: $(form).attr('action'), data: formData }) .done(function(response) { // Make sure that the formMessages div has the 'success' class. $(formMessages).removeClass('error'); $(formMessages).addClass('success'); // Set the message text. $(formMessages).text(response); // Clear the form. $('#contact-form input,#contact-form textarea').val(''); }) .fail(function(data) { // Make sure that the formMessages div has the 'error' class. $(formMessages).removeClass('success'); $(formMessages).addClass('error'); // Set the message text. if (data.responseText !== '') { $(formMessages).text(data.responseText); } else { $(formMessages).text('Oops! An error occured and your message could not be sent.'); } }); }); });
/** * Copyright (c) Tiny Technologies, Inc. All rights reserved. * Licensed under the LGPL or a commercial license. * For LGPL see License.txt in the project root for license information. * For commercial licenses see https://www.tiny.cloud/ * * Version: 5.0.8 (2019-06-18) */ !function(){"use strict";var n=tinymce.util.Tools.resolve("tinymce.PluginManager"),o=function(n){n.addCommand("InsertHorizontalRule",function(){n.execCommand("mceInsertContent",!1,"<hr />")})},t=function(n){n.ui.registry.addButton("hr",{icon:"horizontal-rule",tooltip:"Horizontal line",onAction:function(){return n.execCommand("InsertHorizontalRule")}}),n.ui.registry.addMenuItem("hr",{icon:"horizontal-rule",text:"Horizontal line",onAction:function(){return n.execCommand("InsertHorizontalRule")}})};!function e(){n.add("hr",function(n){o(n),t(n)})}()}();
'use strict'; var path = require('path'); var fs = require('fs'); var crypto = require('crypto'); var expect = require('chai').expect; var walkSync = require('walk-sync'); var appName = 'some-cool-app'; var EOL = require('os').EOL; var runCommand = require('../helpers/run-command'); var acceptance = require('../helpers/acceptance'); var copyFixtureFiles = require('../helpers/copy-fixture-files'); var killCliProcess = require('../helpers/kill-cli-process'); var assertDirEmpty = require('../helpers/assert-dir-empty'); var ember = require('../helpers/ember'); var createTestTargets = acceptance.createTestTargets; var teardownTestTargets = acceptance.teardownTestTargets; var linkDependencies = acceptance.linkDependencies; var cleanupRun = acceptance.cleanupRun; describe('Acceptance: smoke-test', function() { this.timeout(500000); before(function() { return createTestTargets(appName); }); after(function() { return teardownTestTargets(); }); beforeEach(function() { return linkDependencies(appName); }); afterEach(function() { delete process.env._TESTEM_CONFIG_JS_RAN; return cleanupRun().then(function() { assertDirEmpty('tmp'); }); }); it('ember new foo, clean from scratch', function() { return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'test'); }); it('ember test exits with non-zero when tests fail', function() { return copyFixtureFiles('smoke-tests/failing-test') .then(function() { return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'test') .then(function() { expect(false, 'should have rejected with a failing test'); }) .catch(function(result) { expect(result.code).to.equal(1); }); }); }); it('ember test exits with non-zero when build fails', function() { return copyFixtureFiles('smoke-tests/test-with-syntax-error') .then(function() { return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'test') .then(function() { expect(false, 'should have rejected with a failing test'); }) .catch(function(result) { expect(result.code).to.equal(1); }); }); }); it('ember test exits with non-zero when no tests are run', function() { return copyFixtureFiles('smoke-tests/no-testem-launchers') .then(function() { return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'test') .then(function() { expect(false, 'should have rejected with a failing test'); }) .catch(function(result) { expect(result.code).to.equal(1); }); }); }); // TODO: re-enable, something is funky with test cleanup... // it('ember test exits with zero when tests pass', function() { // return copyFixtureFiles('smoke-tests/passing-test') // .then(function() { // return ember(['test']) // .then(function(result) { // expect(result.code).to.equal(0); // }) // .catch(function() { // expect(false, 'should NOT have rejected with a failing test'); // }); // }); // }); it('ember test still runs when only a JavaScript testem config exists', function() { return copyFixtureFiles('smoke-tests/js-testem-config') .then(function() { // testem.json "wins" over testem.js by default so we need to delete // it from the default blueprint first fs.unlinkSync('testem.json'); return ember(['test']); }) .then(function() { expect(!!process.env._TESTEM_CONFIG_JS_RAN).to.equal(true); }); }); // there is a bug in here when running the entire suite on Travis // when run in isolation, it passes // here is the error: // test-support-80f2fe63fae0c44478fe0f8af73200a7.js contains the fingerprint (2871106928f813936fdd64f4d16005ac): expected 'test-support-80f2fe63fae0c44478fe0f8af73200a7.js' to include '2871106928f813936fdd64f4d16005ac' it.skip('ember new foo, build production and verify fingerprint', function() { return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'build', '--environment=production') .then(function() { var dirPath = path.join('.', 'dist', 'assets'); var dir = fs.readdirSync(dirPath); var files = []; dir.forEach(function (filepath) { if (filepath === '.gitkeep') { return; } files.push(filepath); var file = fs.readFileSync(path.join(dirPath, filepath), { encoding: null }); var md5 = crypto.createHash('md5'); md5.update(file); var hex = md5.digest('hex'); expect(filepath).to.contain(hex, filepath + ' contains the fingerprint (' + hex + ')'); }); var indexHtml = fs.readFileSync(path.join('.', 'dist', 'index.html'), { encoding: 'utf8' }); files.forEach(function (filename) { expect(indexHtml).to.contain(filename); }); }); }); // TODO: restore, test harness npm appears to incorrectly dedupe broccoli-filter, causing this test to fail. // manually testing that case, it seems to work correctly, will restore soon. it.skip('ember test --environment=production', function() { return copyFixtureFiles('smoke-tests/passing-test') .then(function() { return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'test', '--environment=production'); }) .then(function(result) { var exitCode = result.code; var output = result.output.join(EOL); expect(exitCode).to.equal(0, 'exit code should be 0 for passing tests'); expect(output).to.match(/JSHint/, 'JSHint should be run on production assets'); expect(output).to.match(/fail\s+0/, 'no failures'); expect(output).to.match(/pass\s+\d+/, 'man=y passing'); }); }); it('ember test --path with previous build', function() { var originalWrite = process.stdout.write; var output = []; return copyFixtureFiles('smoke-tests/passing-test') .then(function() { // TODO: Change to using ember() helper once it properly saves build artifacts return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'build'); }) .then(function() { // TODO: Figure out how to get this to write into the MockUI process.stdout.write = (function() { return function() { output.push(arguments[0]); }; }(originalWrite)); return ember([ 'test', '--path=dist' ]); }).finally(function() { process.stdout.write = originalWrite; }) .then(function(result) { expect(result.exitCode).to.equal(0, 'exit code should be 0 for passing tests'); output = output.join(EOL); expect(output).to.match(/JSHint/, 'JSHint should be run'); expect(output).to.match(/fail\s+0/, 'no failures'); expect(output).to.match(/pass\s+12/, '1 passing'); }); }); it('ember new foo, build development, and verify generated files', function() { return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'build') .then(function() { var dirPath = path.join('.', 'dist'); var paths = walkSync(dirPath); expect(paths).to.have.length.below(23, 'expected fewer than 23 files in dist, found ' + paths.length); }); }); it('ember build exits with non-zero code when build fails', function () { var appJsPath = path.join('.', 'app', 'app.js'); var ouputContainsBuildFailed = false; return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'build') .then(function (result) { expect(result.code).to.equal(0, 'expected exit code to be zero, but got ' + result.code); // add something broken to the project to make build fail fs.appendFileSync(appJsPath, '{(syntaxError>$@}{'); return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'build', { onOutput: function(string) { // discard output as there will be a lot of errors and a long stacktrace // just mark that the output contains expected text if (!ouputContainsBuildFailed && string.match(/Build failed/)) { ouputContainsBuildFailed = true; } } }); }).then(function () { expect(false, 'should have rejected with a failing build'); }).catch(function (result) { expect(ouputContainsBuildFailed, 'command output must contain "Build failed" text'); expect(result.code).to.not.equal(0, 'expected exit code to be non-zero, but got ' + result.code); }); }); it('ember new foo, build --watch development, and verify rebuilt after change', function() { var touched = false; var appJsPath = path.join('.', 'app', 'app.js'); var builtJsPath = path.join('.', 'dist', 'assets', 'some-cool-app.js'); var text = 'anotuhaonteuhanothunaothanoteh'; var line = 'console.log("' + text + '");'; return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'build', '--watch', { onOutput: function(string, child) { if (touched) { if (string.match(/Build successful/)) { // build after change to app.js var contents = fs.readFileSync(builtJsPath).toString(); expect(contents).to.contain(text, 'must contain changed line after rebuild'); killCliProcess(child); } } else { if (string.match(/Build successful/)) { // first build touched = true; fs.appendFileSync(appJsPath, line); } } } }) .catch(function() { // swallowing because of SIGINT }); }); it('ember new foo, build --watch development, and verify rebuilt after multiple changes', function() { var buildCount = 0; var touched = false; var appJsPath = path.join('.', 'app', 'app.js'); var builtJsPath = path.join('.', 'dist', 'assets', 'some-cool-app.js'); var firstText = 'anotuhaonteuhanothunaothanoteh'; var firstLine = 'console.log("' + firstText + '");'; var secondText = 'aahsldfjlwioruoiiononociwewqwr'; var secondLine = 'console.log("' + secondText + '");'; return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'build', '--watch', { onOutput: function(string, child) { if (buildCount === 0) { if (string.match(/Build successful/)) { // first build touched = true; buildCount = 1; fs.appendFileSync(appJsPath, firstLine); } } else if (buildCount === 1) { if (string.match(/Build successful/)) { // second build touched = true; buildCount = 2; fs.appendFileSync(appJsPath, secondLine); } } else if (touched && buildCount === 2) { if (string.match(/Build successful/)) { // build after change to app.js var contents = fs.readFileSync(builtJsPath).toString(); expect(contents.indexOf(secondText) > 1, 'must contain second changed line after rebuild'); killCliProcess(child); } } } }) .catch(function() { // swallowing because of SIGINT }); }); it('ember new foo, server, SIGINT clears tmp/', function() { return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'server', '--port=54323','--live-reload=false', { onOutput: function(string, child) { if (string.match(/Build successful/)) { killCliProcess(child); } } }) .catch(function() { // just eat the rejection as we are testing what happens }); }); it('ember new foo, build production and verify css files are concatenated', function() { return copyFixtureFiles('with-styles') .then(function() { return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'build', '--environment=production') .then(function() { var dirPath = path.join('.', 'dist', 'assets'); var dir = fs.readdirSync(dirPath); var cssNameRE = new RegExp(appName + '-([a-f0-9]+)\\.css','i'); dir.forEach(function (filepath) { if(cssNameRE.test(filepath)) { var appCss = fs.readFileSync(path.join('.', 'dist', 'assets', filepath), { encoding: 'utf8' }); expect(appCss).to.contain('.some-weird-selector'); expect(appCss).to.contain('.some-even-weirder-selector'); } }); }); }); }); it('ember new foo, build production and verify single "use strict";', function() { return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'build', '--environment=production') .then(function() { var dirPath = path.join('.', 'dist', 'assets'); var dir = fs.readdirSync(dirPath); var appNameRE = new RegExp(appName + '-([a-f0-9]+)\\.js','i'); dir.forEach(function(filepath) { if (appNameRE.test(filepath)) { var contents = fs.readFileSync(path.join('.', 'dist', 'assets', filepath), { encoding: 'utf8' }); var count = (contents.match(/(["'])use strict\1;/g) || []).length; expect(count).to.equal(1); } }); }); }); it('ember can override and reuse the built-in blueprints', function() { return copyFixtureFiles('addon/with-blueprint-override') .then(function() { return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'generate', 'component', 'foo-bar', '-p'); }) .then(function() { // because we're overriding, the fileMapTokens is default, sans 'component' var componentPath = path.join('app','foo-bar','component.js'); var contents = fs.readFileSync(componentPath, { encoding: 'utf8' }); expect(contents).to.contain('generated component successfully'); }); }); });